Posts

Showing posts from February, 2011

linq-to-sql fails if local list variable -

i'm struggling thought simple linq-to-sql query work. can construct query ok , can verify sql generates correct when executing dreaded "system.notsupportedexception: queries local collections not supported" exception. i've simplified query in short query below works: var query = asset in context new[] { 1, 2, 3 }.contains(asset.code) select asset this query works: var query = asset in context new list<int>() { 1, 2, 3 }.contains(asset.code) select asset but query below fail when attempt made result set: list<int> mylist = new list<int>(){1, 2, 3}; var query = asset in context mylist.contains(asset.code) select asset anyone solved sort of issue? what posted should work, leading me believe didn't post broken code. make sure mylist variable list<int> , not ilist<int> ... if variable type ilist<int> , you'd exception.

c++ - Question about how to general a bezier curve by inputing several points -

i want generate bezier curve pass through several points input mouse.these points more four,can me , give me suggestions how implent it? more thanks. luck! you have solve distance between points along curve first u & v. generally, shortest arc lengths between points approx. best curve. p0 , p3 endpoints; f , g 2 points along curve. d1 distance between p0 , f; d2 between f , g; d3 between g , p3. solving control points, p1 , p2: let u=d1/(d1+d2+d3); v=(d1+d2)/(d1+d2+d3) this link to: how find control points beziersegment given start, end, , 2 intersection pts in c# - aka cubic bezier 4-point interpolation

c++ - error C2664 - code compiles fine in VC6; not in VS 2010 -

i have typedef, class member vector using type , method using std::<vector>::erase(). #typedef dword wordno_t; class cwordlist : public cobject { public: wordno_t* begin() { return m_words.begin(); } wordno_t* end() { return m_words.end(); } void truncate (wordno_t *ptr) { if (ptr == end()) return; assert (ptr >= begin() && ptr < end()); // following line generates c2664 m_words.erase (ptr, end()); } private: std:vector<wordno_t> m_words; } the detailed error is: error c2664: 'std::_vector_iterator<_myvec> std::vector<_ty>::erase(std::_vector_const_iterator<_myvec>,std::_vector_const_iterator<_myvec>)' : cannot convert parameter 1 'const wordno_t' 'std::_vector_const_iterator<_myvec>' pretty new stl... appreciated. i'm surprised begin , end compiling, shouldn't. std::vector (and friends) use iterators, not pointers. (though intended act similarly.) in case,...

Algorithm/Data Structure Design Interview Questions -

what simple algorithm or data structure related "white boarding" problems find effective during candidate screening process? i have simple ones use validate problem solving skills , can expressed have opportunity application of heuristics. one of basics use junior developers is: write c# method takes string contains set of words (a sentence) , rotates words x number of places right. when word in last position of sentence rotated should show @ front of resulting string. when candidate answers question see available .net data structures , methods (string.join, string.split, list, etc...) solve problem. them identify special cases optimization. number of times words need rotated isn't x it's x % number of words. what of white board problems use interview candidate , of things in answer (do not need post actual answer). i enjoy classic "what's difference between linkedlist , arraylist (or between linked list , array/vector) , why cho...

asp.net - ActiveTab setting in javascript -

when setting tabcontainer first tab active tab through javascript following code : var tc = document.getelementbyid('<%= tabcontainer.clientid %>'); tc.firstchild.lastchild.style.visibility = "hidden"; tc.set_activetabindex(0); i getting exception like: propert or method not supported object. note second line succefully hides second tab panel third line raises excception any suggestion how set tab active through javascript? error generated line tc.set_activetabindex(0); we don't have built-in set_activetabindex() method. you should apply appropriate css properties enabling/disabling tabs.

c# - Updating a Detached Entity Instance using Entity Framework 4.0 -

i utilizing entity framework 4.0 , wcf. new using entity framework , more familiar nhibernate. however, concerned detached instances of objects when performing update. i have looked on various websites retrieve object, attach instance context, , set properties modified leaves 2 problems: all fields updated in database (not huge problem, adds overhead each update statement). many of examples not handle situations may have ienumerable property objects need updated (this requirement). is there 'best practice' example of how handle updating detached entity instances? guidance appreciated. brandon, able make use of self-tracking entities template? designed make handling updates of detached entities easier. http://msdn.microsoft.com/en-us/library/ee789839.aspx

Most effective form of CAPTCHA? -

of forms of captcha available, 1 "least crackable" while remaining human readable? i agree thomas. captcha on way out. if must use it, recaptcha pretty provider simple api.

gitignore - Can I 'git commit' a file and ignore its content changes? -

every developer on team has own local configuration. configuration information stored in file called devtargets.rb used in our rake build tasks. don't want developers clobber each other's devtargets file, though. my first thought put file in .gitignore list not committed git. then started wondering: possible commit file, ignore changes file? so, commit default version of file , when developer changes on local machine, git ignore changes , wouldn't show in list of changed files when git status or git commit. is possible? nice feature... sure, time time using git update-index --assume-unchanged [<file> ...] to undo , start tracking again (if forgot files untracked, see question ): git update-index --no-assume-unchanged [<file> ...] relevant documentation : --[no-]assume-unchanged when flag specified, object names recorded paths not updated. instead, option sets/unsets "assume unchanged" bit paths. when "assume ...

Multiple permission types (roles) stored in database as single decimal -

i going ask question here whether or not design users/roles database tables acceptable, after research came across question: what best way handle multiple permission types? it sounds innovative approach, instead of many-to-many relationship users_to_roles table, have multiple permissions defined single decimal (int data type presume). means permissions single user in 1 row. won't make sense until read other question , answer i can't brain around one. can please explain conversion process? sounds "right", i'm not getting how convert roles decimal before goes in db, , how gets converted when comes out of db. i'm using java, if stubbed out, cool well. here original answer in off chance other question gets deleted: "personally, use flagged enumeration of permissions. way can use and, or, not , xor bitwise operations on enumeration's items. [flags] public enum permission { viewusers = 1, // 2^0 // 0000 0001 editusers = 2, // 2^1 // ...

installation - Wix - Keeping track of installed applications -

this seems straightforward question i've been unable find answer: let's have 2 products: , b created mycompany. both products , b have shortcuts in start menu in fashion: mycompanyfolder->product_a_folder->a.exe , mycompanyfolder->product_b_folder->b.exe if uninstall "product b" don't want delete "mycompanyfolder" unless last product left. check see if "product a" exists or not (through component or registry search) impossible me know @ time how many future applications added folder. the solution came create registry key contains integer denoting number of apps installed - seems bit inelegant (not mention don't know how increment registry values in wix either). any thoughts? thanks. you must doing unusual in install because should work automatically. shouldn't need have components or createfolder elements start menu directory. create reference below , use applicationprogramsfolder id in shortcut ele...

sql - What are the problems of using transactions in a database? -

from this post . 1 obvious problem scalability/performance. other problems transactions use provoke? could there 2 sets of problems, 1 long running transactions , 1 short running ones? if yes, how define them? edit: deadlock problem, data inconsistency might worse, depending on application domain. assuming transaction-worthy domain (banking, use canonical example), deadlock possibility more cost pay ensuring data consistency, rather problem transactions use, or disagree? if so, other solutions use ensure data consistency deadlock free? it depends lot on transactional implementation inside database , may depend on transaction isolation level use. i'm assuming "repeatable read" or higher here. holding transactions open long time (even ones haven't modified anything) forces database hold on deleted or updated rows of frequently-changing tables (just in case decide read them) otherwise thrown away. also, rolling transactions can expensive. know in mysql...

internet explorer 6 - Which jQuery plugin should be used to fix the IE6 PNG transparency issue? -

is there ie6/png fix officially developed jquery team? if not of available plugins should use? i'm using jquery.pngfix.js . don't know if it's officially sanctioned or not, know works. chose because plugin included fancybox, no other reason.

Getting mail from GMail into Java application using IMAP -

i want access messages in gmail java application using javamail , imap. why getting sockettimeoutexception ? here code: properties props = system.getproperties(); props.setproperty("mail.imap.host", "imap.gmail.com"); props.setproperty("mail.imap.port", "993"); props.setproperty("mail.imap.connectiontimeout", "5000"); props.setproperty("mail.imap.timeout", "5000"); try { session session = session.getdefaultinstance(props, new myauthenticator()); urlname urlname = new urlname("imap://myusername@gmail.com:mypassword@imap.gmail.com"); store store = session.getstore(urlname); if (!store.isconnected()) { store.connect(); } } catch (nosuchproviderexception e) { e.printstacktrace(); system.exit(1); } catch (messagingexception e) { e.printstacktrace(); system.exit(2); } i set timeout values wouldn't take "forever" timeout. also, myauthe...

Load report failed when implementing crystal report in asp.net 3.5 -

im implementing crystal report builtin in visual studio 2008. when create crystal report , check preview shows me data when call on abc.aspx page report doesnt load , gives error 'load report failed'. code <cr:crystalreportviewer id="crystalreportviewer1" runat="server" autodatabind="true" reportsourceid="crystalreportsource1" /> <br /> <br /> <br /> <br /> <cr:crystalreportsource id="crystalreportsource1" runat="server"> <report filename="reports/dailypaymentstatus.rpt"> </report> </cr:crystalreportsource> what may im doing wrong. report accept 4 parameters , im not setting them anywhere. 1 thing want mention if make simple project , same thing runs , give me output. yes. found out answer problem path <report filename="reports/dailypaymentstatus.rpt...

How do I best pass arguments to a Perl one-liner? -

i have file, somefile , this: $cat somefile hdisk1 active hdisk2 active i use shell script check: $cat a.sh #!/usr/bin/ksh d in 1 2 grep -q "hdisk$d" somefile && echo "$d : ok" done i trying convert perl: $cat b.sh #!/usr/bin/ksh export d d in 1 2 cat somefile | perl -lane 'begin{$d=$env{'d'};} print "$d: ok" if /hdisk$d\s+/' done i export variable d in shell script , value using %env in perl. there better way of passing value perl one-liner? you can enable rudimentary command line argument "s" switch. variable gets defined each argument starting dash. -- tells command line arguments start. for d in 1 2 ; cat somefile | perl -slane ' print "$someparameter: ok" if /hdisk$someparameter\s+/' -- -someparameter=$d; done see: perlrun

ckEditor - mouseup event not firing after setData -

so have ckeditor loaded through javascript, on instanceready event add event mouseup... works , dandy until use settext property (i used both jquery way , javascript way). after set, mouseup event no longer triggers. not after set event handler again. relevant code: var elem = ckeditor.instances[eid]; elem.document.on("mouseup",function(){ quickhandler(elem); }); function quickhandler(who) { $("#"+who.name).val(who.getdata() + quicktextselected.quicktextdata); $("input[type='text'],textarea, .cke_contents").css({border: "solid 1px rgb(155,181,234)"}).unbind("click"); } this jquery plugin version, works same way internal javascript ckeditor object map. (rather doesn't work). does setdata or settext clear event handlers? it seems using setdata ckeditor infact replaces document element rendering events invalid, see #6633

iphone - cocos2d problem - layer not updating quick enough -

i adding overlays cocos2d layer in preparation screenshot... cgsize winsize = [[ccdirector shareddirector] winsize]; ccscene* currentscene = [[ccdirector shareddirector] runningscene]; gamelayer* toplayer = (gamelayer *)[currentscene.children objectatindex:0]; ccsprite *middlebackground = [ccsprite spritewithfile:@"mid_bg.png"]; middlebackground.position = ccp(winsize.width * 0.5,winsize.height * 0.55); [toplayer addchild:middlebackground z:3 tag:111]; ccsprite *bottombackground = [ccsprite spritewithfile:@"bot_bg.png"]; bottombackground.position = ccp(winsize.width * 0.5,winsize.height * 0.1); [toplayer addchild:bottombackground z:3 tag:112]; ccsprite *topbackground = [ccsprite spritewithfile:@"top_bg.png"]; topbackground.position = ccp(winsize.width * 0.5,winsize.height * 0.94); [toplayer addchild:topbackground z:3 tag:113]; [[uiapplication sharedapplication] setstatusbarhidden:yes]; ccsprite *topbackground2 = [ccsprite spritewit...

python - Help on Regular Expression problem -

i wonder if it's possible make regex following data pattern: '152: ashkenazi a, benlifer a, korenblit j, silberstein sd.' string = '152: ashkenazi a, benlifer a, korenblit j, silberstein sd.' i using regular expression (using python's re module) extract these names: re.findall(r'(\d+): (.+), (.+), (.+), (.+).', string, re.m | re.s) result: [('152', 'ashkenazi a', 'benlifer a', 'korenblit j', 'silberstein sd')] now trying different number (less 4 or more 4) of name data pattern doesn't work anymore because regex expects find 4 of them: (.+), (.+), (.+), (.+). i can't find way generalize pattern. this should trick if want stuff after numbers: re.findall(r'\d+: (.+)(?:, .+)*\.', input, re.m | re.s) and if want everything: re.findall(r'(\d+): (.+)(?:, .+)*\.', input, re.m | re.s) and if want them separated out list of matches, nested regex it: re.findall(...

java - Does Tiles for Struts2 support UTF-8 encoded templates? -

if required configuration elements enable utf-8 tiles? i'm finding tile results sent as: content-type text/html; what if put @ top? <%@ page contenttype="text/html;charset=utf-8" pageencoding="utf-8" language="java" %>

svn - Using Subversion for general purpose backup -

is possible use apache subversion (svn) general purpose backup tool? (as kind of rsync alternative.) i found article pretty cool description of using svn backup home directory, , more: i use subversion backup linux boxes. minor creativity, covers: daily snapshots , offsite backup. easy addition , removal of files , folders. detailed tracking of file versions. it allows few bonus features: regular log emails keep track of filesystem activity via subversion's event hooks. users may request checkout of home folders respository revision. new or replacement servers can setup few svn checkout commands. source: http://www.mythago.net/svn_for_backup.html also found this article shows example of versioning home directory. allows bring environment checking out home directory new machine. used similar , found useful.

.net - Get date equivalent of current day from last year? -

i trying find way date of matching day last year, so example today 4th friday in july, date of same last year? i getting sales restaurant , need check them against last years sales on same day. the problem, stated, has no answer, because months begin on different days in different years (not mention leap year complications). would sufficient subtract 364 days, 52 weeks end same day-of-the-week?

c - What is the difference between '__asm' and '__asm__'? -

i learning inline assembly in c. far can tell, difference between __asm { ... }; , __asm__("..."); first uses mov eax, var , second uses movl %0, %%eax :"=r" (var) @ end. also, there lot less websites first. other differences there? which 1 use depends on compiler. isn't standard c language.

How to implement the Edit -> Copy menu in c#/.net -

how implement copy menu item in windows application written in c#/.net 2.0? i want let user mark text in control , select copy menu item edit menu in menubar of application , paste in example excel. what makes head spin how first determine child form active , how find control contains marked text should copied clipboard. help, please. with aid of heavy pair programming colleague of mine , came this, feel free refactor. the code placed in main form. copytoolstripmenuitem_click method handles click event on copy menu item in edit menu. /// <summary> /// recursively traverse tree of controls find control has focus, if /// </summary> /// <param name="c">the control search, might control container</param> /// <returns>the control either has focus or contains control has focus</returns> private control findfocus(control c) { foreach (control k in c.controls) { if (k.f...

asp.net - Why wss 3.0 dosen't display image properly? -

i have own custom webpart. inside webpart display transparent gif. unfortunately dosen't it. tryign use html img tag or asp.net image tag. src property image set because displays image icon insted of "x". x proof of wrong path under src. said alright. can me , tell why can't display image? it sounds might not problem wss directly - have tried using http proxy tool fiddler ensure bits of image coming across wire?

iphone - Determine if a tableview cell is visible -

is there way know if tableview cell visible? have tableview first cell(0) uisearchbar. if search not active, hide cell 0 via offset. when table has few rows, row 0 visible. how determine if row 0 visible or top row? uitableview has instance method called indexpathsforvisiblerows return nsarray of nsindexpath objects each row in table visible. check method whatever frequency need , check proper row. instance, if tableview reference table, following method tell whether or not row 0 on screen: -(bool)isrowzerovisible { nsarray *indexes = [tableview indexpathsforvisiblerows]; (nsindexpath *index in indexes) { if (index.row == 0) { return yes; } } return no; } because uitableview method returns nsindexpath , can extend sections, or row/section combinations. this more useful visiblecells method, returns array of table cell objects. table cell objects recycled, in large tables have no simple correlation data source.

.net - F# vs IronPython: When is one preferred to the other? -

while languages f# , ironpython technically dissimilar, there large overlap between potential uses in opinion. when 1 more applicable other? so far me f# computationally more efficient while ironpython inherits better library python. happy corrected. there relevant question is f# ironpython/ironruby c# vb.net? of answers there language paradigms rather actual applicability. edit : guess should add bit more background. have experience python in general, , have learnt f# after few hesitant functional programming steps before, in erlang. feel able continue using either python or f# in future. decide 1 should use , where. example: python has data structures part of standard library. other day needed equivalent of python's heap module , not available in standard f#/.net library. point ironpython. f# can used build more convenient libraries, easier access other .net languages. .net residing library prefer f#. cross-platform development. ironpython better here. f#/mono us...

C++ static code analysis tool on Windows -

what c++ static code analysis tool know of microsoft windows development, , main features offer? please state whether particular tool relies on cygwin, , whether foss, free or requires purchase. similar question: what open source c++ static analysis tools available? here summary of current state: prefast found in windows driver kit cppcheck coverity pvs-studio oink klocwork insight pc-lint cppdepend goanna sentry visual studio team system understand cccc cqual++ flawfinder dms software reengineering toolkit vera++ source monitor stack (source code @ github ) cppcheck open source , cross-platform.

Hidden features of Python -

what lesser-known useful features of python programming language? try limit answers python core. one feature per answer. give example , short description of feature, not link documentation. label feature using title first line. quick links answers: argument unpacking braces chaining comparison operators decorators default argument gotchas / dangers of mutable default arguments descriptors dictionary default .get value docstring tests ellipsis slicing syntax enumeration for/else function iter() argument generator expressions import this in place value swapping list stepping __missing__ items multi-line regex named string formatting nested list/generator comprehensions new types @ runtime .pth files rot13 encoding regex debugging sending generators tab completion in interactive interpreter ternary expression try/except/else unpacking+ print() function with statement chaining comparison operators: >>> x = 5 >>...

svn - Adding version control to an existing project -

i working on project has grown decent size, , developer. don't use version control, need start. i want use subversion. best way transfer existing project it? i have test server use developing new features, transfer files 2 production servers. there tool automate upload test, deployment live servers? all developed in asp.net using visual studio (if matters) to expand little on previous answer... 1) create new svn repository 2) commit code you've worked on far it 3) check code out again, create working copy on dev machine 4) work! it's not hurdle, really.

database - What is a good OO C++ wrapper for sqlite -

i'd find object oriented c++ (as opposed c) wrapper sqlite. people recommend? if have several suggestions please put them in separate replies voting purposes. also, please indicate whether have experience of wrapper suggesting , how found use. this inviting down-votes, here goes... i use sqlite directly c++, , don't see value added c++ abstraction layer. it's quite (and efficient) is.

css - Remove column dividers in a html table -

i have html table css. cells have white border around them, having trouble removing column borders each cell rows divided white line. similar table i'm trying achive can seen @ http://www.smashingmagazine.com/2008/08/13/top-10-css-table-designs/ , @ example 3 (the top table in example). far code looks like: <html> <head> <style type="text/css"> table, td, th { font-family:calibri; border:collapse:collapse; } th { background-color:#b9c9fe; color:#006add; } td { background-color:#e8edff; color:#666699; } </style> <body> <table cellpadding="5" > <tr> <th>firstname</th> <th>lastname</th> <th>savings</th> </tr> <tr> <td>peter</td> <td>griffin</td> <td>$100</td> </tr> <tr> <td>lois</td> <td>griffin</td> <td>$150</td> </tr> <tr> <td>joe</td> <td>swanson</td...

objective c - iPhone SDK: Can I nab in instance variable from one view and access it in another? -

i'm pretty new oop in general , started working obj-c few months back. so, please gentle! appreciate in advance. question! i have 3 text fields user inputs name, phone, , email. i collect , place them in label using nsstring [this 1 name]: - (ibaction)changegreeting:(id)sender { self.name = textinput.text; nsstring *namestring = name; if([namestring length] == 0) { namestring = @"i forgot"; } nsstring *greeting = [[nsstring alloc] initwithformat:@"hello, name %@! really!", namestring]; label.text = greeting; [greeting release]; } with have been able place text text.input label (as stated in label.text = greeting;) i have view i'd have review information (view label too). need have access name or textinput.text in other view. how can accomplish this? if don't need communicate changes between 2 view controllers, may want pass in using custom init method. may best confirmation screen, prompt make no se...

c++ - How can I avoid the Diamond of Death when using multiple inheritance? -

http://en.wikipedia.org/wiki/diamond_problem i know means, steps can take avoid it? a practical example: class {}; class b : public {}; class c : public {}; class d : public b, public c {}; notice how class d inherits both b & c. both b & c inherit a. result in 2 copies of class being included in vtable. to solve this, need virtual inheritance. it's class needs virtually inherited. so, fix issue: class {}; class b : virtual public {}; class c : virtual public {}; class d : public b, public c {};

sql server - While-clause in T-SQL that loops forever -

i tasked debugging strange problem within e-commerce application. after application upgrade site started hang time time , sent in debug. after checking event log found sql-server wrote ~200 000 events in couple of minutes message saying constraint had failed. after debugging , tracing found culprit. i've removed unnecessary code , cleaned bit it while exists (select * shoppingcartitem shoppingcartitem.purchid = @purchid) begin select top 1 @tmpgfsid = shoppingcartitem.gfsid, @tmpquantity = shoppingcartitem.quantity, @tmpshoppingcartitemid = shoppingcartitem.shoppingcartitemid, shoppingcartitem inner join goodsforsale on shoppingcartitem.gfsid = goodsforsale.gfsid shoppingcartitem.purchid = @purchid exec @errorcode = spgoodsforsale_reversereservations @tmpgfsid, @tmpquantity if @errorcode <> 0 begin goto cleanup end delete shoppingcartitem shoppingcartitem.shoppingcartitemid = @tmpshoppingcar...

cryptography - Encryption vs. digest -

what difference between encryption , digest? encryption takes plain text , converts encrypted text using key , encryption algorithm. resulting encrypted text can later decrypted (by using same key , algorithm). a digest takes plain text , generates hashcode can used verify if plain text unmodified cannot used decrypt original text hash value.

javascript - Disconnect a jquery connection after an inactivity period -

i'm using tcp keepalive on server side keep connection alive, , notify server if client dies. how can configure jquery.get() disconnect connection after period of idle time? edit - consider "idle time" time no tcp packets exchanged. since server has tcp keepalive, send 0-data packets client. @j-p's answer not exact match want. if connection open, has keep-alive traffic no data, keep open indefinitely. use timeout option: jquery.ajax({ url: '...', timeout: 3000, success: function(){ /*...*/ } }); or, if want same timeout requests: $.ajaxsetup({ timeout: 3000 });

osx - Localizing applications on Mac OS -

i have application supposed work on both windows , mac , localized in portuguese, spanish , german. have ini file localized strings read from. ini file doesn't work same encoding files on both platforms. windows have have file in ansi format or else accented letters in localized strings messed , on mac same file should in western( mac os) encoding or else same result. there way can single file work on both platforms? (1) there no such thing the ansi format. that's unfortunate term on windows means "the local codepage". in particular, means in europe interpretation of bytes 128-255 "ansi format" differ between countries. so, inclined argue won't work on first platform, let alone both. the solution migrate unicode. works everywhere, characters, , number of character not depend on country or current date (see introduction of €).

c# - Expression in DataTable -

i have simple code: currentdatatable.columns.add("active", type.gettype("system.boolean")); currentdatatable.columns.add("symbol", type.gettype("system.string")); currentdatatable.primarykey = new datacolumn[] {currentdatatable.columns[1]}; string filterexpression = "symbol = aaa"; datarow[] existingrows = currentdatatable.select(filterexpression); when executing, error: cannot find column [aaa]. what doing wrong?? if want "aaa" interpreted string, use: string filterexpression = "symbol = 'aaa'"; from datacolumn.expression documentation: when create expression filter, enclose strings single quotation marks:

WCF Authentication using basicHttpBinding and custom UserNamePasswordValidator -

my first question is, possible use custom usernamepasswordvalidor basichttpbinding? i have asp.net web site using forms authentication , custom membership provider. realise use built in system.web.applicationservices.authenticationservice authenticate client (a wpf app) don't want 2 service calls (one auth service, 1 logic). so seems custom usernamepasswordvalidator perfect job. in client can have: var service = new myserviceclient(); service.clientcredentials.username.username = "username"; service.clientcredentials.username.password = "password"; messagebox.show(service.sayhello()); i've seen working wshttpbinding ideally test without ssl certificate. alternatively, possible make use of authenticationservice within wcf service? to clarify mean above regarding authentication service, don't want have 2 service calls i.e: if (authservice.login("username", "password")) ...

c++ - How to detect integer overflow? -

i writing program in c++ find solutions of a b = c , a , b , c use digits 0-9 once. program looped on values of a , b , , ran digit-counting routine each time on a , b , a b check if digits condition satisfied. however, spurious solutions can generated when a b overflows integer limit. ended checking using code like: unsigned long b, c, c_test; ... c_test=c*b; // possible overflow if (c_test/b != c) {/* there has been overflow*/} else c=c_test; // no overflow is there better way of testing overflow? know chips have internal flag set when overflow occurs, i've never seen accessed through c or c++. there is way determine whether operation overflow, using positions of most-significant one-bits in operands , little basic binary-math knowledge. for addition, 2 operands result in (at most) 1 bit more largest operand's highest one-bit. example: bool addition_is_safe(uint32_t a, uint32_t b) { size_t a_bits=highestonebitposition(a), b_bits...

computer science - What are the main/interesting problems in computational geometry? What are the introductory problems? -

i'm interested in learning computational geometry, i'm not sure start. interesting problems worked on currently? "introductory problems"? also, possible advise respect field? thanks! excellent introductory book: computational geometry: algorithms , applications, second edition (the 4 dutchmen book! :d) it ignores low-level problems (accuracy, degenerate cases - , rest assured applied computational geometry fraught these), , focuses on concepts. easy follow book, enjoyable, many diagrams run on sides of book, next text describes them, , contains quite variety of problems along examples of real applications. i believe best introductory book on computational geometry around. strongly recommended!

c# - Allow multi-select in a .NET TreeView -

i'm stuck in .net 2.0 windows forms. it doesn't ability select multiple nodes exists in standard treeview control. i'm trying context menu selection. check boxes aren't acceptable ui paradigm here. what's best way provide necessary functionality? we did in wtl project once, basic work needed same .net. achieve multiple selection tree control, need draw tree items , override keyboard , mouse handling. need maintain own list of items selected. don't forget consider selection rules (are parents , children allowed, example), , don't forget implement keyboard shortcuts including selection using ctrl, shift, , ctrl+shift, spacebar selecting/deselecting.

c++ - How to link using GCC without -l nor hardcoding path for a library that does not follow the libNAME.so naming convention? -

i have shared library wish link executable against using gcc. shared library has nonstandard name not of form libname.so, can not use usual -l option. (it happens python extension, , has no 'lib' prefix.) i able pass path library file directly link command line, causes library path hardcoded executable. for example: g++ -o build/bin/myapp build/bin/_mylib.so is there way link library without causing path hardcoded executable? there ":" prefix allows give different names libraries. if use g++ -o build/bin/myapp -l:_mylib.so other_source_files should search path _mylib.so.

html - Creating a web application, then adding Ajax to it? -

i imagine there many of out there have developed application online automates lot of processes , saves people @ company time , money. the question is, experiences developing application, having set in place, "spicing" ajax, makes better user experience? also, libraries suggest using when adding ajax already-developed web application? lastly, common processes see in web applications ajax with? example, auto-populating search box type. my preferred way of building ajax-enabled applications build old-fashioned way every button, link, etc. posts server, , hijack button, link, etc. clicks ajax functionality. this ensures app down-browser compatible, good.

flash - When it says put crossdomain.xml in the root where would that be on IIS? -

would wwwroot, c, root virtual directory assets hosted, or same folder assets in? meaning if have virtual directory 'virdir' sub directory 'swf', c:\somedir\assets\swf\, crossdomain.xml need go swf app on different server can access swfs? you need able access http://yoursite.com/crossdomain.xml put that? as rule of thumb put next index.html site.

c# - Linq to sql and timestamp field -

i've created table timestamp field. allow nulls property set false . when want update entity repository , null value field, in databse field set value. knows may problem? correct values other fields. thank you. edit : when entity repository , timestamp field set appropriately. problem somewhere in http post : [acceptverbs(httpverbs.post)] public actionresult edit(product product) the value of timestamp field lost here :( by default, edit view vs generates excludes binary fields. include timestamp field in view, you'll have add view hidden field one: <%: html.hidden("timestamp", model.timestamp.tostring()) %> you'll have add line web.config if compilation error did (using vs 2010): <add assembly="system.data.linq, version=4.0.0.0, culture=neutral, publickeytoken=b77a5c561934e089"/> because timestamp.tostring() extension method. keep in mind cannot explicitly change timestamp field in database. sql server ...

c# - How to generate an 401 error programmatically in an ASP.NET page -

as can see question non web developer. have aspx page which, under circumstances, can generate 401 error code. ideally show iis standard page. set response.statuscode , - if need stop execution - call response.end() .

php - How do you validate/save an embedded form based on a value in the parent form in symfony? -

i have symfony 1.4 form 2 embedded forms. the parent form has drop down determines of embedded forms fill in (hidden/shown on frontend using javascript). the problem is, when submit form, validation , save being run on both of embedded forms, don't want. what best way alter parent form validates , saves relevant embedded form based on selection made in parent form? thanks. note: please see jeremy's answer mine based on his. thank answer jeremy. code had few issues, thought i'd post implemented solution explaining did differently. 1. override dobind() the override of dobind() had issue uncaught sfvalidatorerror thrown if parent value didn't return clean validator. wrapped in try/catch suppress this. i altered work multiple embedded forms, not 2 specified. protected $selectedtemplate; public function gettemplatetoembeddedformkeymap() { // array of template values embedded forms return array( 'template1' => 'te...

process - What do you think when a Boolean "if" has three resulting code paths? -

(background: previous job, co-worker , end discussing bug pile during lunch. began develop topic called "bug of week". doubt have material 52 posts year, here's first one...) reported by: qa tester reading html/js code write functional test of web form, , saw: if (form_field == empty) { ...do stuff empty field } else if (form_field != empty) { ...do stuff non-empty field } else { ...do stuff never done } after couple embarassing attempts, tester realized couldn't trigger alert strings hidden in third block. things i'm wondering are: is problem more or less language specific (can non-js people learn lessons here?) are there legitimate reasons code ended way? what approaches should used find/address problem (code coverage, code review, blackbox testing, etc.) a couple other points: i'm hoping can keep positive. imagine person work (in company not encourage flaming). whatever mean things might think of guilty party, thought them too. i...

persistence - Are there databases that bases durability on redundancy and not on persistent storage? -

sorry title isn't obvious, couldn't word better. we right using conventional db (oracle) our job queue, , these "jobs" consumed number of nodes (machines). db server gets hit these nodes, , have pay lot software , hardware database server. now, occurred me other day that, 1) there multiple nodes in system 2) "jobs" may not lost because of node failures, there no reason have sitting in secondary storage (no reason why couldn't reside in memory, long not lost) given this, couldn't 1 retain these jobs in-memory, making sure @ least n number of copies of job present in entire cluster, thereby getting rid of db server? are such technologies available? did take @ gigaspaces ? on internet scale, not need persist @ all. have know sufficient copies around. if have low latency connections places not on same powergrid (or have battery power), pushing out transactions duplicates enough.

java - Does the ModelDriven interface poses a security explot in struts2? -

background: coded struts2 actionsupport class modeldriven. it's hibernate/spring web app, using osiv , attached entities in view (jsp). i received email today architect 'punishing' me putting object had reference attached entity on struts2 valuestack via modeldriven<e> interface. correct or what? obviously, serious thing doing not following saying, , don't feel taking offer , visiting him @ desk after this. oh boy. time change careers. --- architect --- billy, discussed, still making same mistakes in code on , on again. forth time have made error , i'm concerned quality of work. it's 1 thing make once or twice, after forth time, wondering if unable comprehend saying. following spell out you. if don't after reading email, come desk , we'll go on it. has stop immediately, , want code refactored before end of day correcting mistake. if code bleeds production, we'll have serious security problem on our hands. note copying da...

java - Things possible in IntelliJ that aren't possible in Eclipse? -

i have heard people have switched either way , swear 1 or other. being huge eclipse fan having not had time try out intellij, interested in hearing intellij users "ex-eclipsians" specific things can intellij can not eclipse. note : not subjective question nor @ meant turn ide holy war. please downvote flamebait answers . ctrl-click works anywhere ctrl-click brings clicked object defined works everywhere - not in java classes , variables in java code, in spring configuration (you can click on class name, or property, or bean name), in hibernate (you can click on property name or class, or included resource), can navigate within 1 click java class used spring or hibernate bean; clicking on included jsp or jstl tag works, ctrl-click on javascript variable or function brings place defined or shows menu if there more 1 place, including other .js files , js code in html or jsp files. autocomplete many languagues hibernate autocomplete in hsql expressions, i...

windows - C++ Code Profiler -

can recommend code profiler c++? i came across shiny - good? http://sourceforge.net/projects/shinyprofiler/ callgrind unix/linux devpartner windows

linux - passing URL variables to exec() with php -

i have dedicated server use crunch lots of data. way have now, can open script process id example.php?ex_pid=123 , let go. downloads small portion of data, processes it, uploads database starts again. ideally, call example.php?ex_pid=123 directly , not passing variable example.php exec('./example.php'.' '.escapeshellarg($variable)); keep acting globally. i don't care output, if execute in background, brilliant. server ubuntu distribution btw. is possible? if so, , examples more appreciated. you like: exec("./example.php '".addslashes(serialize($_get))."'); and in example.php this: count($_get) == 0 && $_get = unserialize(stripslashes($_server['argv'][1]))

regex - How do I get a particular word from a string in PHP? -

say have string, don't know contains. , want replace occurences of particular word or part of word formatted version of same word. example, have string contains "lorem ipsum" , want replace entire word contains "lo" "lorem can" end result "lorem can ipsum" if put string "loreal ipsum" through same function, result "loreal can ipsum". thanks $str = preg_replace('/lo(\w*)/', 'lo$1 can', $str); this replaces "lo" plus word characters "lo" + other characters + " can" it replace "lo" "lo can" - if don't want this, change \w* \w+

c++ - Is it possible to write a template to check for a function's existence? -

is possible write template changes behavior depending on if member function defined on class? here's simple example of want write: template<class t> std::string optionaltostring(t* obj) { if (function_exists(t->tostring)) return obj->tostring(); else return "tostring not defined"; } so, if class t has tostring() defined, uses it; otherwise, doesn't. magical part don't know how "function_exists" part. yes, sfinae can check if given class provide method. here's working code: #include <iostream> struct hello { int helloworld() { return 0; } }; struct generic {}; // sfinae test template <typename t> class has_helloworld { typedef char one; typedef long two; template <typename c> static 1 test( typeof(&c::helloworld) ) ; template <typename c> static 2 test(...); public: enum { value = sizeof(test<t>(0)) == sizeof(char) }; }; i...

Can I abandon an InProc ASP.NET session from a session different than one making the request? -

we have application single sign-on using centralized authentication server (cas). we'd single sign-out, such if user logs out of 1 application (say front-end portal), user automatically signed out of applications using same single sign-on ticket. the expectation each application register sign-out hook (url) cas @ time of logon application. when cas receives sign out request 1 of applications, invokes sign-out hook application sharing sso ticket. my question this: there way abandon inproc session different session? presume, since http request coming cas server, own session, session of user want terminate. have pretty idea of how using separate session state server, i'd know if possible using inproc session state. haha, well... looks can. wondering myself if there way this, turns out, there is. when use inproc, inprocsessionstatestore (internal class) persist session state in internal (non public) cache. can access cache through reflection , remove session ...

Unobtrusive javascript with jquery - good 10 minute tutorial? -

i'm looking 10 minute introduction unobtrusive javascript using jquery. i'm new concept, , i'd see how event binding , such works. as background, i'm looking "remove tag" system similar have here on so. looking @ source, didn't see js, img tag. makes me think there must external js that's binding click event. want know how that, , want tutorial shows me how! i guess tutorials page on jquery homepage place start :) simple example remove link have clicked on follows: <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script> <script type="text/javascript"> // execute script when dom has finished loading $(document).ready(function() { $('#removeme').click(function() { // remove element has been target of event $(this).remove(); // stop browser fo...

Structuring several mostly-static pages in ASP.NET MVC -

might not consequential question, but... i have bunch of mostly-static pages: contact, about, terms of use, , 7-8 more. should each of these have own controllers, or should have 1 action each? thanks in advance. just consider each item individually. if think there slightest chance action/view required more static data break or else have worry breaking links in future customers/visitors/search engines have saved/indexed , need possibly maintain redirects etc. if sure never change (ha says never) use 1 controller many actions/views. eg: http://yoursite.com/home/contact http://yoursite.com/home/terms http://yoursite.com/home/about etc... this save project lot of clutter basic data assuming have lot of other code. if majority of code these pages though should break because there nothing clutter anyways.

javascript - How to get the caret position in a textarea, in characters, from the start? -

how caret position in <textarea> using javascript? for example: this is| text this should return 7 . how return strings surrounding cursor / selection? e.g.: 'this is', '', ' text' . if word “is” highlighted, return 'this ', 'is', ' text' . with firefox, safari (and other gecko based browsers) can use textarea.selectionstart, ie doesn't work, have this: function getcaret(node) { if (node.selectionstart) { return node.selectionstart; } else if (!document.selection) { return 0; } var c = "\001", sel = document.selection.createrange(), dul = sel.duplicate(), len = 0; dul.movetoelementtext(node); sel.text = c; len = dul.text.indexof(c); sel.movestart('character',-1); sel.text = ""; return len; } ( complete code here ) i recommend check jquery fieldselection plugin, allows , more... edit: re-implemented above code: function...

tsql - How do I retrieve hierarchic XML in t-sql? -

my table has following schema: id, parent_id, text given following data return xml hierarchy: data: (1,null,'x'), (2,1,'y'), (3,1,'z'), (4,2,'a') xml: [row text="x"] [row text="y"] [row text="a"/] [/row] [row text="z"/] [/row] added: hierachy has no maximum depth if have finite depth there's quickie looks this: select t.*, t2.*, t3.* /*, ...*/ mytable t inner join mytable t2 on t2.parent_id=t.id inner join mytable t3 on t3.parent_id=t2.id /* ... */ t.parent_id null xml auto i'm not sure might possible devise similar result using recursive queries . of course, it's easier (and makes more sense) in application level.

c - C1x: When will it land, what to expect? -

c99 still isn't supported many compilers, , of focus on c++, , upcoming standard c++1x. i'm curious c "get" in next standard, when it, , how keep c competitive. c , c++ known feed on 1 another's improvements, c feeding on c++1x standard? what can forward in c's future? the iso/iec 9899:2011 standard , aka c11, published in december 2011 . the latest draft n1570 ; i'm not aware of differences between , final standard. there's technical corrigendum fixing oversight in specification of __stdc_version__ (now 201112l ) , optional __stdc_lib_ext1__ (now 201112l ).

python - Interactive console using Pydev in Eclipse? -

i'm debugging python code in eclipse using pydev plugin. i'm able open pydev console , gives me 2 options: "console active editor" , "python console". none of them useful inspect current variable status after breakpoint. for example, code stopped @ breakpoint , want inspect "action" variable using console. variables not available. how can things "dir(action)", etc? (even if not using console). this feature documented here: http://pydev.org/manual_adv_debug_console.html

java - Why do we need the decorator in the decorator design pattern? -

presuming have class named a , , want use decorator design pattern. correct me if i'm wrong, work , we'll need create decorator class, adecorator , hold reference a instance, , other decorators extend add functionality. i don't understand why have create decorator class, instead of using a instance? the decorator pattern used add capabilities objects dynamically (that is, @ run time). object have capabilities fixed when write class. important point functionality of object extended in way transparent client of object because implements same interface original object delegates responsibility decorated object. the decorator pattern works in scenarios there many optional functionality object may have. without decorator pattern have create different class each object-option configuration. 1 example pretty useful comes head first design patterns book o'reilly. uses coffee shop example sounds starbucks. so have basic coffee method cost. public double co...