Posts

Showing posts from May, 2015

javascript - How can I close a browser window without receiving the "Do you want to close this window" prompt? -

how can close browser window without receiving do want close window prompt? the prompt occurs when use window.close(); function. window.open('', '_self', ''); window.close(); this works me.

java - "Iterating" through methods -

let's i've got java object that's got among others following methods: public string getfield1(); public string getfield2(); public string getfield3(); public string getfield4(); public string getfield5(); is there way iterate through these methods , call 'em following code? string fields = ""; for(int = 1; <= 5; ++){ fields += object.(getfield+i) + " | "; } thank upcoming ideas. there way using reflection: try{ method m= object.getclass().getmethod("getfield"+string.valueof(i), new class[]{}); fields+=(string)m.invoke(object); }catch(...){...} however: business smells of bad coding practice! can't rewrite getfieldn() methods this? string getfield(int fieldnum) you asking trouble creating numbered methods. remember reflection slow , should used when string-based method calls absolutely essential flow of program. use technique user-defined scripting languages have method by name . isn't case @ ...

asp.net - Session and threads -

not been able find definitive answer this, when client session established asp.net mvc2 application assume particular thread thread pool handles request. same thread handle subsequent requests session? in theory if somehow session id messed , wrong thread picked session level data missing? thanks in short, no, not under iis (i can't vouch "cassini" web development server in visual studio, doubt there too) you can demonstrate thread changing adding following view: <%= system.threading.thread.currentthread.managedthreadid %> now repeatedly hit page browser (or maybe hit 2 or 3 browsers) , see change time time. having said - in simple scenario such this, may often see same thread servicing request not worth asp.net creating more threads needs, once start loading server, see multiple threads.

writing a C/C++ daemon (Linux) -

i want write generic (c/c++) library use develop daemons in linux environment. rather reinventing wheel, thought i'd come in here find out if there known libraries in use. the library either c or c++ - although prefer c++ (maybe part of, or based on excellent boost library?). as aside, in terms of library selection criteria, since daemons pretty 'mission critical' components, better if library propose actively maintained group of developers (e.g. boost library [again]), has active community (or @ least mailing list resort when faced tricky situations), rather lone individual somewhere out there ... i saw document , starting point, dated, i'm wondering if there better , more known/used out there ... ? btw, developing on ubuntu (10.0.4) an alternative solution use process monitor such supervisord , manages multiple services, restarts them when crash, provides minimalistic web page view , control status of processes, can manage groups of services, sup...

asp.net - SqlServer Express slow performance -

i stress testing .net web application. did 2 reasons: wanted see performance under real world conditions , make sure hadn't missed problems during testing. had 30 concurrent users in application using during normal course of jobs. users had multiple windows of application open. 10 users: not bad 20 users: slowing down 30 users: very, slow no timeouts it loaded on production server. virtual server 2.66g hz xeon processor , 2 gb of ram. using win2k3 sp2. have .net 1.1 , 2.0 loaded , using sqlexpress sp1. we rechecked indexes on of tables afterword , should be. how can improve our application's performance? this thought of, check see how memory sql server using when have 20+ users - 1 of limitations of express version is limited 1gb of ram . might simple matter of there not being enough memory available to server due limitations of express.

In SQL, what's the difference between count(column) and count(*)? -

i have following query: select column_name, count(column_name) table group column_name having count(column_name) > 1; what difference if replaced calls count(column_name) count(*) ? this question inspired how find duplicate values in table in oracle? . to clarify accepted answer (and maybe question), replacing count(column_name) count(*) return row in result contains null , count of null values in column. count(*) counts nulls , count(column) not [edit] added code people can run it create table #bla(id int,id2 int) insert #bla values(null,null) insert #bla values(1,null) insert #bla values(null,1) insert #bla values(1,null) insert #bla values(null,1) insert #bla values(1,null) insert #bla values(null,null) select count(*),count(id),count(id2) #bla results 7 3 2

iphone - Load a particular NIB based on tableview selection -

i have initial table view created initial menu within app. each option access different including nibs. part of constants menu options nib. when each option pulled plist, include nib called upon. am missing or going wrong way entirely? right selection nothing. - (void)tableview:(uitableview *)tableview didselectrowatindexpath:(nsindexpath *)indexpath { nsmutablestring *targetnib = [[self.menuoptions objectatindex:indexpath.row] objectforkey:nib_key]; if (targetnib == @"hospitaldirectoryviewcontroller") { hospitaldirectoryviewcontroller *hospitaldirectoryviewcontroller = [[hospitaldirectoryviewcontroller alloc] initwithnibname:@"hospitaldirectoryviewcontroller" bundle:nil]; // ... // pass selected object new view controller. [self.navigationcontroller pushviewcontroller:hospitaldirectoryviewcontroller animated:yes]; [hospitaldirectoryviewcontroller release]; } if (targetnib == @"physiciandirectoryviewcontroller") { physiciandi...

Pex users: what are your Impressions of Pex and Automated Exploratory Testing in general? -

those of have used pex , think advantages , disadvantages of pex tool? also, think advantages , disadvantages of "automated exploratory testing" in general, as supplement to tdd/unit testing? pex lets write parameterized unit tests. in sense, totally fits tdd/unit testing flow: write test, have pex 'explore' it, find failing tests, fix code, , forth. the big advantage can express tests classes of inputs, not couple hard-coded values. gives more expressiveness writing tests , forces think invariant/expectation code should fullfill (i.e. it's harder write assertions).

c# - Can one copy the contents of one object to another dynamically if they have the same interface? -

for example, if have 2 objects, 1 of type monkey , other of type dog, , both implement ianimal, this: interface ianimal { int numberofeyes {get; set;} string name {get; set;} } i want this: monkey monkey = new monkey() { numberofeyes = 7, name = "henry" }; dog dog = new dog(); myfancyclass.dynamiccopy(monkey, dog, typeof(ianimal)); debug.assert(dog.numberofeyes == monkey.numberofeyes); i imagine 1 can create class myfancyclass using reflection... clever person have idea? thanks, stephen a reflection based solution follows. note reflection work done once per type , cached, overhead should minimal. work .net 3.5 , not restricted interfaces. note use reflection properties on type t , filter properties have both getters , setters. build expression tree each property retrieves value source , assigns value target. expression trees compiled , cached in static field. when copyproperties method called, invokes copier each property, copying properties defin...

Html5 Websockets - What should I know about sockets before using websockets -

i'm experimenting html5 , websockets. know next nothing "ordinary" sockets. before messing websockets think might wise learn sockets. there online material should read or excersizes should go through myself speed? might worth pointing out i'm c# programmer mainly. thanks in advance! the short answer: nothing. websocket protocol high-level (layer-7) protocol; normal "sockets" think you're referring tcp sockets, more low-level, , programmed using berkeley sockets api. if want use websocket protocol on pragmatic level, need learn simple javascript api dealing same.

javasound - Java sound recording and mixer settings -

i'm using javax.sound.sampled package in radio data mode decoding program. use program user feeds audio radio receiver pc's line input. user required use mixer program select line in recording input. trouble users don't know how , other programs alter recording input setting. question how can program detect if line in set recording input ? possible program change recording input setting if detects incorrect ? thanks time. ian to answer first question, can check if line.info object recording input matches port.info.line_in this: public static boolean islinein(line.info lineinfo) { line.info[] detected = audiosystem.getsourcelineinfo(port.info.line_in); (line.info linein : detected) { if (linein.matches(lineinfo)) { return true; } } return false; } however, doesn't work operating systems or soundcard driver apis don't provide type of each available mixer channel. when test on windows works, not on linu...

c# - How to get String.Format not to parse {0} -

i writing code generation tool have lines like stringbuilder sp = new stringbuilder(); sp.appendformat(" public {0}textcolumn()\n", classname); sp.appendline(" {" sp.appendline(" column = new datagridviewtextboxcolumn();"); sp.appendformat(" column.datapropertyname = \"{0}\";\n", columnname); however issue having when run in line this. sp.appendformat("return string.format(\"{0} = '{0}'\", cmblist.selectedvalue);", columnname); i want first {0} turn in whatever value of columnname want seccond {0} left alone internal string.format process correctly. how do this? use double curly braces: string result = string.format("{{ignored}} {{123}} {0}", 543);

user interface - How to implement draggable tab using Java Swing? -

how implement draggable tab using java swing? instead of static jtabbedpane drag-and-drop tab different position rearrange tabs. edit : the java tutorials - drag , drop , data transfer . curses! beaten punch google search. unfortunately it's true there no easy way create draggable tab panes (or other components) in swing. whilst example above complete 1 i've written bit simpler. demonstrate more advanced techniques involved bit clearer. steps are: detect drag has occurred draw dragged tab offscreen buffer track mouse position whilst dragging occurs draw tab in buffer on top of component. the above example give want if want understand techniques applied here might better exercise round off edges of example , add features demonstrated above it. or maybe i'm disappointed because spent time writing solution when 1 existed :p import java.awt.component; import java.awt.graphics; import java.awt.image; import java.awt.point; import java.awt.rectangle...

wordpress - What is a good algorithm for showing the most popular blog posts? -

i'm planning on developing own plugin showing popular posts, counting how many times post has been read. but need algorithm figuring out popular blog post, , way of counting number of times post has been viewed. a problem see when comes counting number of times post has been read, avoid counting if same person opens same post many times in row, avoiding web crawlers. http://wordpress.org/extend/plugins/wordpress-popular-posts/ comes in form of plugin. no muss, no fuss.

shell - Avoid going into subdirectories when "find" has a hit -

i trying file in multiple folders. when hit file, want stop going subdirectories. example: /foo/.target /bar/buz/.target /foo/bar/.target i want first two: /foo/.target /bar/buz/.target your requirements not clear. understand them as: “wanted” files inside directory tree; if directory directly contains @ least 1 match, print them, otherwise recurse directory. i can't think of pure find solution. write awk or perl script parse output of find. here's shell script think you're looking for. warning: i've minimally tested it. #!/bin/sh ## return 0 if $1 matching file, 1 otherwise. ## note $1 full path file. wanted () { case ${1##*/} in .target) true;; esac } ## recurse directory $1. print wanted files in directory. ## if there no wanted file, recurse each subdirectory in turn. traverse () { found=0 x in "$1"/.* "$1"/*; if [ "$x" = "$1/." ] || [ "$x" = "$1/.." ]; ...

PHP drop down menu -

i doing select on database , time returns me 10 records , 1000, depending on criteria of search. want drop down have break after every 30 records. this <select id="dd" > <option value="0">1-30</option> <option value="30">31-60</option> <option value="60">61-90</option> <option value="91">91-120</option> </select> how do in php dynamically? here's take on it: echo '<select id="dd">'; $j = 0; for($i=0;$i<$numresults;$i++) { if($i%30==0) echo '<option value="'.$j.'">'.($j+1).'-'.($j+=30).'</option>'; } echo '</select>'; for $numresults == 130 output be: <select id="dd"> <option value="0">1-30</option> <option value="30">31-60</option> <option value="60"...

java - How to hide "Preferences" item in Mac application menu -

i have application built atop eclipse rich-client platform. not yet have user preferences. currently on mac, "preferences" menu item in application menu enabled, nothing. is there easy way hide or disable it? in case else runs same problem, chose simple solution root problem -- show preferences dialog. even in absence of application-layer user preferences, there still preferences panels contributed plug-ins. with current implementation of org.eclipse.ui.internal.carbon.carbonuienhancer, application-menu "preferences" item requires , executes preferences menu item elsewhere in menus (e.g., actionfactory.preferences).

java - Are there frameworks for Jython or JRuby, or is it you can run a py or ruby app on the JVM? -

are there specific frameworks jython or jruby, or can run py or ruby app on jvm? i.e. take python django app, , can run in on tomcat using jython? sorry little confused. jruby 1.5.x compatible ruby 1.8.7, , pretty write in ruby work in jruby. includes applications written in frameworks such ruby on rails, can converted war file , deployed tomcat. in fact netbeans ide comes ruby on rails support , default you're using jruby. makes easy if you're getting started language and/or framework.

java - Spring RestTemplate Behavior when handling responses with a status of NO_CONTENT -

okay, have class namedsystems, has field set of namedsystem. i have method find namedsystems criteria. that's not important. when gets results, works fine. however, when can't find anything, , returns null (or empty -- i've tried both ways) set, problems. let me explain. i'm using spring resttemplate class , i'm making call in unit test: responseentity<?> responseentity = template.exchange(base_service_url + "? alias={aliasvalue}&aliasauthority={aliasassigningauthority}", httpmethod.get, makehttpentity("xml"), namedsystems.class, alias1.getalias(), alias1.getauthority()); now, since return 200, want return 204, have interceptor in service determines if modelandview namedsystem , if set null. if so, set status code no_content (204). when run junit test, error: org.springframework.web.client.restclientexception: cannot extract response: no content-type found setting status no_content seems wipe content-type fiel...

error handling - How to capture crash logs in Java -

i'm working on cross platform application in java works nicely on windows, linux , macos x. i'm trying work out nice way detection (and handling) of 'crashes'. there easy, cross-platform way detect 'crashes' in java , in response? i guess 'crashes' mean uncaught exceptions. code use jni it'd nice able catch crashes bad jni code, have feeling that's jvm specific. for simple catch-all handling, can use following static method in thread . javadoc: static void setdefaultuncaughtexceptionhandler ( thread.uncaughtexceptionhandler eh)           set default handler invoked when thread abruptly terminates due uncaught exception, , no other handler has been defined thread. this broad way deal errors or unchecked exceptions may not caught anywhere else. side-note: it's better if code can catch, log and/or recover exceptions closer source of problem. reserve kind of generalized crash handling totally unrecoverable situatio...

unix - How do I use my pager (more/less) on error output only -

i have program spits out both standard error , standard out, , want run pager less on standard error, ignore standard out. how do that? update: that's ... didn't want lose stdout ... keep out of pager program 2>&1 >log | less then later less log you try redirecting standard out /dev/null, redirecting standard error standard out used go. example in ksh/bash: program 2>&1 >/dev/null | less here redirection 2>&1, sets file descriptor 2 (stderr) point same stream file descriptor 1 (stdout), gets evaluated before redirection >/dev/null , sets file descriptor 1 point /dev/null. effect write stderr gets sent stdout, , write stdout gets thrown away.

c# - IEnumerator implementation problem -

i have code: public class check21csvrecord { public string transactiontype; public string transactioncurrency; public string reference; public string paymenttype; // date of transaction public string transactiondate; public string notes; // customer data goes here public string customerfirstname; public string customerinitial; public string customerlastname; public string customerstreetaddress; public string customercity; public string customerstate; public string customerzipcode; [fieldconverter(converterkind.date, "mm/dd/yy")] public datetime customerdatebirth; public string customercountry; public string customeremail; public string customerphone; public string customeripaddress; // micr line goes here public string auxiliaryonus; public string externalprocessingcode; public string payorbankroutingnumber; public string payorbankroutingnumberc...

c++ - Compiling GCC 4.x.x on MinGW / MSYS Fails -

i've been attempting last week or compile of gcc 4 series of compilers run in mingw 5.1.6 / msys 1.0.11 (automated installers both sourceforge.org) ships gcc version 3.4.5. end goal gcc 4.5 install, haven't been able of 4.x.x compilers build. i've narrowed down sequence of build instructions result in unusual behavior. compiler executes: build/genmodes.exe > tmp-modes.c /bin/sh ../../gcc-4.2.4/gcc/../move-if-change tmp-modes.c insn-modes.c echo timestamp > s-modes gcc -c -g -fkeep-inline-functions -din_gcc -w -wall -wwrite-strings -wstrict-prototypes -wmissing-prototypes -wold-style-definition -wmissing-format-attribute -fno-common -dhave_config_h -i. -i. -i../../gcc-4.2.4/gcc -i../../gcc-4.2.4/gcc/. -i../../gcc-4.2.4/gcc/../include -i./../intl -i../../gcc-4.2.4/gcc/../libcpp/include -i../../gcc-4.2.4/gcc/../libdecnumber -i../libdecnumber insn-modes.c -o insn-modes.o cc1.exe: out of memory allocating 2239725803 bytes make[3]: *** [insn-modes.o] err...

testing - What is the best free test tracking software? -

i'm not talking bug tracking software (like bugzilla or jira). i'm looking that: stores test specifications in text format combines test specs test coverage scenarios keeps track of progress through testing scenarios links test specs bug reports stored in bugzilla generates progress reports is centrally managed on own (i.e. not hack/extension on top of else) testlink pretty nice open source test tracking tool features need, , still under active development. take @ http://testlink.org/

php - How do you separate visitors to two intro pages to compare amt of registration per visitor? -

i making site depend on users register able play online game. if don't login see intro page. if user login site save information cookie next time visit sent directly login.php. if user don't have information in cookie sent intro.php. of course want many users possible register (or in case, high percent possible). want separate 50% of users intro1.php , other 50% intro2.php. want compare amount/percent of users clicks on registration.php link , how many click away site. i want have statistic of percent of visitors go intro1.php registration.php , percent go intro2.php registration.php. way can compare success rate of intro1.php , intro2.php , improve intro page. how can accomplish this? google a/b test seams solution ... take @ www.google.com/websiteoptimizer

c++ - Get the defaults programs -

i use c++ , qt project. know how can default program : default navigator, default mail client, default editor ... i found linux - gnome: gconftool! what windows, mac os or linux (kde) ? thanks you. on windows kind of stuff can recovered directly registry (regedit). search web find out specific registry paths, this .

java - Link Console with source code in Eclipse -

i have j2me project, throws exceptions, in other projects (j2se projects) i'm used press on exception link in console in eclipse, , take me straight source line, reason, in j2me project not happen. any idea on how fix this? adam. you can copy stack trace java stack trace console. in console, switch new java stack trace console, paste stack trace , clickable.

xcode3.2 - Build and Debug in Xcode -

the icon in xcode says "build , run". how change "build , debug" i read if use "build , run" work optimize code. "i read if use "build , run" work optimize code." no - wrong - release builds typically have optimisation enabled , debug builds don't. has nothing how run program (i.e. run vs debug), depends on configuration building.

debugging - How do I use PDB files -

i have heard using pdb files can diagnose crash occurred. basic understanding give visual studio source file, pdb file , crash information (from dr watson?) can please explain how works / involved? (thank you!) pdb files generated when build project. contain information relating built binaries visual studio can interpret. when program crashes , generates crash report, visual studio able take report , link source code via pdb file application. pdb files must built same binary generated crash report! there issues have encountered on time. the machine debugging crash report needs have source on same path machine built binary. release builds optimize extent cannot view state of object member variables if knows how defeat former, grateful input.

Why do I need a flickr api key? -

reading through flickr api documentation keeps stating require api key use rest protocols. building photo viewer, gathering information available flickr's public photo feed (for instance, not planning on writing upload script, api key required). is there added functionality can getting key? update answered question below to use flickr api need have application key. we use track api usage. currently, commercial use of api allowed prior permission. requests api keys intended commercial use reviewed staff. if project personal, artistic, free or otherwise non-commercial please don't request commercial key. if project commercial, please provide sufficient detail decide. thanks! http://www.flickr.com/services/api/misc.api_keys.html

Unit testing a Java Servlet -

i know best way unit testing of servlet. testing internal methods not problem long don't refer servlet context, testing doget/dopost methods internal method refer context or make use of session parameters? is there way using classical tools such junit, or preferrably testng? did need embed tomcat server or that? try httpunit , although end writing automated tests more 'integration tests' (of module) 'unit tests' (of single class).

c# - Test if string is a guid without throwing exceptions? -

Image
i want try convert string guid, don't want rely on catching exceptions ( for performance reasons - exceptions expensive for usability reasons - debugger pops for design reasons - expected not exceptional in other words code: public static boolean trystrtoguid(string s, out guid value) { try { value = new guid(s); return true; } catch (formatexception) { value = guid.empty; return false; } } is not suitable. i try using regex, since guid can parenthesis wrapped, brace wrapped, none wrapped, makes hard. additionally, thought guid values invalid(?) update 1 christiank had idea catch formatexception , rather all. changed question's code sample include suggestion. update 2 why worry thrown exceptions? expecting invalid guids often? the answer yes . why using trystrtoguid - am expecting bad data. example 1 namespace extensions can specified appending guid folder name . might parsing folder ...

sql - Access count on another table doesn't work -

i have posts table , postcomments table of blog system. want count , sort posts comment count query won't work.: select posts.postid, posts.datecreated, posts.title, posts.description, posts.hits, (select count(commentid) postcomments postcomments.postid=posts.postid , postcomments.isapproved=true) commentcount posts order posts.postid desc; i tried: select posts.postid, posts.datecreated, posts.title, posts.description, posts.hits, count([commentid]) commentcount posts inner join postcomments on posts.postid = postcomments.postid; but have error "you tried execute query not include specified expression 'postid' part of aggregate function." i'm complete access noob, try second 1 grouping non-aggregated columns. select posts.postid ,posts.datecreated ,posts.title ,posts.description ,posts.hits ,count([commentid]) commentcount posts inner join postcomments on posts.postid = post...

linux - Add or update a configuration record in /etc/environment -

my /etc/environment looks this: cat /etc/environment path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games" i wish use command (sed, awk, python, whatever....) make this: cat /etc/environment path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games" java_home="/usr/lib/jvm/java-6-sun" now catch is, rather 1 liner (in fields of sed -xyz /domagic/ /etc/environment), needs contain merging logic - either appends new configuration record or update existing one. bottom line, should prevent file looking this: (caused in experienced shell scripters calling echo >> on each invocation) cat /etc/environment path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games" java_home="/usr/lib/jvm/java-5-sun" java_home="/usr/lib/jvm/java-6-sun" java_home="/usr/lib/jvm/java-6-sun" java_home="/usr/lib/jvm/java-6-sun" i guess trick questions, ...

.net - Console-like text control? -

i'm looking winforms control can output text in console window (output appended bottom, color formatting, etc.) "output" window in ides. i tried making 1 myself didn't work way wanted, i'm wondering if there existing control out there. this open-source project. i have wrote simple control. not work colors (its derived textwriter, not support colors). internal class textboxwriter : textwriter { textbox _output; public textboxwriter(textbox output) { _output = output; } public override void writeline(string value) { write(value + system.console.out.newline); } public override void write(string value) { if(_output.invokerequired) { _output.begininvoke((action<string>)write, value); } else { _output.appendtext(value); } } public override void write(char value) { write(value.tostring()); } public override encoding encoding { ...

How do dictionary lookups work in IronRuby? -

i have line of ironpython code: traits['strength'].score + traits['dexterity'].score traits defined such: dim m_traits new dictionary(of string, trait) scope.setvariable("traits", m_traits) i translate ironpython code ironruby, i'm having trouble finding correct syntax. in ruby (and ironruby), variables must begin lowercase letter. therefore, change traits variable traits make code works: var engine = ironruby.ruby.createengine(); var scope = engine.createscope(); scope.setvariable("traits", traits); dynamic result = engine.execute("traits['strength'].score + traits['dexterity'].score", scope); (this code works, checked). by way, creating variable starts capital letter makes constant (that's how ruby works) , adding constant scope done in different way.

php - hidden variables for buttons causing problems -

here code in php. have php creditcard confirmation page, 2 button, edit details , submit. have init file perform tasks based on cc_confirm , editval is, confirm , editing details respectively. if($_post['cc_confirm1']=='y' && $_post['$editval']!='y' && !isset($editval)) {echo '<input name="submitbtn" type="submit" value="edit details" /><input name="editval" type="hidden" value="y" /><input name="cc_confirm" type="hidden" value="n" />'; } if($_post['cc_confirm1']=='y' && $_post['$editval']!='y' && !isset($editval)){ echo '<input name="submitbtn1" type="submit" value="submit card" /><input name="card1" type="hidden" value="y" /><input name="cc_confirm" type="hidden" val...

When to build a separate reporting database? -

we're building application has database (yeah, pretty exciting huh :). database transactional (to support app) , bit of "reporting" part of app - nothing strenuous. above , beyond have reporting requirements - they're pretty vague , high-level @ moment. have standard reporting tool we-use in-house we'll use "heavier" reporting requirements solidify. my question is: how know when separate database reporting required? what sort of questions need asked? sort of things make decide separate reporting database necessary? in general, more mission critical transactional app , more sophisticated reporting requirements, more splitting makes sense. when transaction performance critical. when it's hard maintenance window on transactional app. if reporting needs correlate results not app, other application silos. if reports need support trending or other types of reporting best suited star schema/business intelligence environment. if r...

c++ - What does the comma operator do? -

what following code in c/c++? if (blah(), 5) { //do } comma operator applied , value 5 used determine conditional's true/false. it execute blah() , (presumably), comma operator employed , 5 thing used determine true/false value expression. note , operator overloaded return type of blah() function (which wasn't specified), making result non-obvious.

loops - Value comparison of matrix elements in MATLAB -

say have 256 256 matrix. replace values 'greater' or 'equal' 10 1 , make rest 0 i.e. (values < 10). for example, 2 3 6 15 24 32 1 7 39 10 .... 1 5 7 11 19 10 20 28 9 ........ 10 24 6 29 10 25 32 10 .......... ................................. ................................. and want output be: 0 0 0 1 1 1 0 0 1 1 ............ 0 0 0 1 1 1 1 1 0 .............. 1 1 0 1 1 1 1 1 ................ ................................ ................................ how can it? example: a = [3 2 6 6 ; 7 5 3 7 ; 7 10 8 9 ; 2 4 3 10]; b = ( > 5 ) b = 0 0 1 1 1 0 0 1 1 1 1 1 0 0 0 1

ssis - How do I fix the error unable to enlist Sybase database in distributed transaction? -

i know little (arguably nothing) sybase setup, know ssis having trouble enlisting sybase in distributed transaction. has been able make work? the ssis runtime has failed enlist ole db connection in distributed transaction error 0x80004005 "unspecified error". this happens when change package's transactionoption required. when revert default "supported", package runs without errors (albeit not thread safe). i had same problem when tried create transaction around read gupta sqlbase. basically, seems ssis (at least of 2005) isn't able enroll other providers in transaction part of package. i've tried few times without luck, , end reading data oledb temporary table, , creating transaction around import of data resting place in sql server. that's read side, though - if you're trying use transaction write sybase, you'll need on side - ssis won't able use transaction push data provider. i addition that, didn't want trans...

page.aspx/variable in ASP.NET -

is possible pass/get variables page.aspx/value in asp.net? i'd have page website.com/folder/name instead of website.com/folder/?name , name value. i've done similar routing allow dates passed through blog entries , stuff. to setup need have page processing, lets call folder.aspx , add in route information global.ascx.cs file. so lets @ routes ... routes routes need work specific , work there way out general. way request able find specific version applies url specified. following code needs added global.ascs.cs file. void application_start(object sender, eventargs e) { // code runs on application startup setroutes(routetable.routes); } private static void setroutes(routecollection routes) { routes.mappageroute("folder-file", "{folder}/{file}", "~/folder.aspx"); routes.mappageroute("folder", ...

Java Code unable to delete file -

my java code unable delete files on the system hard drive. whenever file.delete() function called, returns false . ideas, why might happening? file.delete() can fail delete file many reasons including: you don't have correct permissions delete file the file represents directory , directory not empty the file locked process, (or same process in unclosed fileoutputstream ) the file doesn't exist

sql - Return NEWSEQUENTIALID() as an output parameter -

imagine table looks this: create table [dbo].[test]( [id] [uniqueidentifier] null, [name] [varchar](50) null ) go alter table [dbo].[test] add constraint [df_test_id] default (newsequentialid()) [id] go with insert stored procedure looks this: create procedure [insert_test] @name varchar(50), @id uniqueidentifier output begin insert test( name ) values( @name ) end what best way guid inserted , return output parameter? use output clause of insert statement. create procedure [insert_test] @name varchar(50), @id uniqueidentifier output begin declare @returnid table (id uniqueidentifier) insert test( name ) output inserted.id @returnid values( @name ) select @id = r.id @returnid r end go /* test procedure */ declare @myid uniqueidentifier exec insert_test 'dummy', @myid output select @myid

Hidden features of Haskell -

what lesser-known useful features of haskell programming language. (i understand language lesser-known, work me. explanations of simple things in haskell, defining fibonacci sequence 1 line of code, upvoted me.) try limit answers haskell core one feature per answer give example , short description of feature, not link documentation label feature using bold title first line my brain exploded if try compile code: {-# language existentialquantification #-} data foo = forall a. foo ignorefoo f = 1 foo = f you error message: $ ghc foo.hs foo.hs:3:22: brain exploded. can't handle pattern bindings existentially-quantified constructors. instead, use case-expression, or do-notation, unpack constructor. in binding group foo in pattern binding: foo = f in definition of `ignorefoo': ignorefoo f = 1 foo = f

python - Is while True: a suitable way to repeat a block until an accepted case is reached? -

is while true accepted method looping on block of code until accepted case reached below? there more elegant way this? while true: value = input() if value == condition: break else: pass # continue code here. thank input. that's way in python. don't need else: pass bit though. note, in python 2.x you're want raw_input rather input .

makefile - Getting Quiet Make to echo command lines on error -

i have makefile building many c files long long command lines , we've cleaned output having rules such as: .c${mt}.doj: @echo "compiling $<";\ $(compiler) $(copts) -c -o $@ $< now great @ suppresses compilation line being emitted. when error, error message, no command line. can think of "neat" way emit command line? can think of doing echoing file , have higher level make catch error , cat file. hacky know. tested , worked (gnu make in linux): .c${mt}.doj: @echo "compiling $<";\ $(compiler) $(copts) -c -o $@ $< \ || echo "error in command: $(compiler) $(copts) -c -o $@ $<" \ && false

c# - UdpClient, Receive() right after Send() does not work? -

consider following code: client.send(data, data.length, endpoint); byte[] response = client.receive(ref endpoint); while, according wireshark (network sniffer), remote host reply data, application here waits data forever... not receive answer remote host reason. any ideas? you want setup 2 udpclients: 1 listening, 1 sending. for receiving udpclient, use constructor takes port.

Colorize numbers in lstlisting (latex) -

i want know if possible colorize numbers in lstlisting package latex. example want numbers in red, 0x0f (hex) , 0b00001111 (bin): void setapwm2(unsigned char porcento) { //100 * 256 = 25.600 unsigned int val = porcento * pr2; val /= 25; //garante que tem apenas 10 bits val &= 0x03ff; //os 8 primeiros bits são colocados no ccpr1l ccpr2l = val >> 2; //os últimos dois são colocados na posição 5 e 4 ccp1con ccp2con |= (val & 0b00001111) << 4; } if there no way, there other package can it? ps: i'm working c language. thanks minted uses python library (pygments) , can kind of highlighting latex able understand code , not keywords listings does. at least hex supported directly, in pygments demo fails binary numbers , fine if add on line highlighter code (probably regexp similar 1 parses hex). edit: in pygments\lexers\compiled.py line 60 has: (r'0x[0-9a-fa-f]+[ll]?', number.hex), which parses hex c. add below (r...

asp.net - Reacting to click on ListItems in CheckboxList -

i apply logic page containing checkboxlist control when user checks or unchecks individual checkbox items. say, instance dynamically show or hide related control. i came way using asp.net 2.0 callback mechanism (ajax) combination of client-side javascript , server-side logic in code-behind. however, solution not bullet-proof (i.e. suffers timing issues). not portable, because code needs know sequential ids of individual items, etc. the code came separated in 2 functions, 1 handling onclick event, , other processing returned callback string : <script type="text/javascript"> function oncheckboxclicked() { // gathers semi-colon separated list of labels, // associated checked items var texts = ''; // iterate on each individual checkbox item // items in checkboxlist sequential, // stop iteration @ first missing sequence number (var index = 0; index < 99; index++) { var checkbox = document.getelementbyid('c...

xml - How to select unique nodes -

i found this page describing muenchian method, think i'm applying wrong. consider return set of ages: /doc/class/person/descriptive[(@name='age')]/value 1..2..2..2..3..3..4..7 but nodeset 1 node each age. 1..2..3..4..7 each of these seem return of values, instead of unique values: /doc/class/person/descriptive[(@name='age')][not(value=preceding-sibling::value)]/value /doc/class/person/descriptive[(@name='age')]/value[not(value=preceding-sibling::value)] what missing? here's example: <root> <item type='test'>a</item> <item type='test'>b</item> <item type='test'>c</item> <item type='test'>a</item> <item type='other'>a</item> <item type='test'>b</item> <item type='other'>d</item> <item type=''>a</item> </root> and x...

java - packaging tagfiles in jar -

how can package tagfiles in jar can reused acrossed multiple projects? i think found own answer http://java.sun.com/j2ee/1.4/docs/tutorial/doc/jsptags6.html#wp90207

ruby - Requiring gem for acts_as_taggable in rails -

i'm trying tags working in rails application , want use acts_as_taggable. firstly followed instructions found in rails recipies (a free sample bit online) used acts_as_taggable plugin. however, found this site seems have gem acts_as_taggable more advanced (has options related tags etc). i've tried follow instructions there install it, keep getting errors. firstly installed gem normal ( gem install acts_as_taggable ) , tried various ways rails recognise , load gem. require_gem listed on site didn't work (i assume old command has been removed) , neither did straight require (although has worked bluecloth gem). i've tried using config.gem 'acts_as_taggable' keeps telling me haven't got acts_as_taggable installed , asks me run rake gems:install . no matter how many times run still gives error! the result of gem query -l -n acts_as_taggable lists acts_as_taggable installed local gem. i've tried running gem check , doesn't show problems...

.net - How to stop visual studio from updating assembly references? -

in our environment have lib folder contains various third party assemblies referenced our projects. example, enterprise libary , elmah. sometimes dev doesn't latest on folder. when dev loads project can't find assembly in expected folder, visual studio automatically locates copy , updates project references. the problem occurs when dev checks in project , screws else up. is there way stop visual studio 2008 doing this? update: wanted add using tfs source control. here's how guard against @ company. (your mileage vary!) any non-system (or otherwise non-gac) references come our dev server, every developer has mapped w: drive. have common dll directory, subdirectories client (or vendor), , further subdirectories appropriate. no dlls ever stored in source control, except license.dll needed infragistics occasionally. for vendor-provided libraries (entlib, infragistics, etc.), policy reference w: drive. period. no 1 authorized reference anywhere else. ...

jquery - cant get color animation to work -

simple trying animate p-tag #disclaimer highlight background color. example in jquery: $('#disclaimer').animate({'backgroundcolor':'#ff9f5f'}, 2000); the html simple <p id="disclaimer"> disclaimer here </p> but when try open page in ie here js error: webpage error details user agent: mozilla/4.0 (compatible; msie 8.0; windows nt 6.1; trident/4.0; slcc2; .net clr 2.0.50727; .net clr 3.5.30729; .net clr 3.0.30729; media center pc 6.0; infopath.3; .net4.0c; .net4.0e; .net clr 1.1.4322) timestamp: mon, 26 jul 2010 17:57:09 utc message: invalid property value. line: 141 char: 6 code: 0 uri: file:///c:/users/xxxxx/desktop/myjquerysite/lib/jquery-1.4.min.js am doing incorrectly ? jquery doesn't natively support animations on colors. in order work you'll need include jquery color plugin. here's blurb in jquery 1.2 release notes .

unit testing - How to mock PreferenceManager in Android? -

i've written class using context , third party library , sharedpreferences preferencemanager . it's possible mock context , third party library can mocked using mocking framework, preferencemanager ? i have 2 methods: public void savestring(thirdpartyobject obj) { sharedpreferences apppreferences = preferencemanager.getdefaultsharedpreferences(mcontext); sharedpreferences.editor editor = apppreferences.edit(); editor.putstring(mcontext.getstring( r.string.preferences_string_name), obj.getstring()); editor.commit(); } and corresponding, loads preferences. it doesn't want mock instance of preferencemanager (which used in preferencefragment or preferenceactivity ). you want either: a mock sharedpreferences , in case can mock context#getsharedpreferences (which called preferencemanager#getdefaultsharedpreferences anyhow). you'll have make mock sharedpreferences.editor if preferences edited, above. know how moc...

cocoa touch - How to stretch the image size in iphone UIImage or UIImageView -

i'd show image in iphone app, image i'm using big. i'd scale fit iphone screen, can't find class handle it. uiimageview* view = [[uiimageview alloc] initwithimage: [uiimage imagenamed: @"your_image.png"]]; view.frame = cgrectmake(0, 0, width, height); to frame of iphone screen can use cgrect frame = [[uiscreen mainscreen] bounds];

ruby - conditional formatting in rails partials -

i rendering rails partial , want alternate background color when renders partial. know not super clear here example of want do: row 1 grey background row 2 yellow background row 3 grey background row 4 yellow background sorry stackoverflow seams prevent background colors being shown think makes idea clear this view code using <table> <%= render :partial => 'row' :collection => @rows %> </table> the _row.html.erb partial looks this <tr bgcolor="#aaaaaa"> <td><%= row.name %></td> </tr> the problem not know how change background color every other row. there way this? you use cycle helper. this: <tr class="<%= cycle("even", "odd") %>"> <td><%= row.name %></td> </tr> or in case use bgcolor instead, although recomend using css classes. you can cycle through more 2 values: cycle(‘first’, ‘second’, ‘third’...

.net - In C#, should I use string.Empty or String.Empty or "" to intitialize a string? -

in c#, want initialize string value empty string. how should this? right way, , why? string willi = string.empty; or string willi = string.empty; or string willi = ""; or what? use whatever , team find readable. other answers have suggested new string created every time use "" . not true - due string interning, created either once per assembly or once per appdomain (or possibly once whole process - not sure on front). difference negligible - massively, massively insignificant. which find more readable different matter, however. it's subjective , vary person person - suggest find out people on team like, , go consistency. find "" easier read. the argument "" , " " mistaken each other doesn't wash me. unless you're using proportional font (and haven't worked any developers do) it's pretty easy tell difference.

What benchmark would test how well my hardware rates, for my ASP.NET, SQL Server, IIS product? -

what benchmark test how hardware rates, asp.net, sql server, iis product? i have 2 servers, 1 runs code faster other , believe configurations close equivalent , therefore want benchmark two. i do not want question become 1 hardware. this question asking how test how hardware rates, software. in other words, 3d benchmark doesn't accurately rate system asp.net/sql server app. i single best solution i've found problem visual studio team test edition . can write stress tests in whatever .net language , learnable , discoverable. metrics informative. there 90-day trial may able away see talking about. had such experience @ previous company using bought outright @ present company , developer had never worked before had stress tests , running within few hours.

c# - How do I automatically set assembly version during nightly build? -

we have nightly build process automatically versions c++ projecs. here's how works. there's common header file versionnumber.h has specific #define version number. nighly build checks file out, increments integer behind #define , checks in. visual c++ projects #include header resource files , use define specifying version (version smth 1.0.3.thatnumber ). so far good. i'd have same c# class libraries built in same daily build. have [assembly: assemblyversion("1.0.*")] in assemblyinfo.cs files , libraries end 1.0.horriblenumber.anotherhorriblenumber version , 2 numbers don't correlate number used c++ projects. how have same determenistic automatic version numbering in c# projects minimal effort? firstly can specify full version follows: [assembly: assemblyversion("1.0.9.10")] secondly, common approach make little more straightforward (and echoes c++ approach) have single version.cs file (name unimportant) sits in common l...

How to check if a date is in a list of dates - TSQL -

i trying create sql query checks if date in list of dates query doesn't work... select * table1 field1 = value1 , convert(nvarchar(15),date_start,101) in (select convert(nvarchar(15),date_end,101) table2 ) this query should return values doesn't... do not convert data think there no need try : select * table1 field1 = value1 , date_start in (select date_end table2)

Strange jQuery AJAX Firefox Issue -- Page Randomly Won't Finish Downloading -

i have strange issue web app. see, i'm using jquery forms api , doing $('#myform').ajaxsubmit(api parms , callback function goes here). randomly when this, however, , on firefox, page load icon starts spinning, page load progress bar runs in status bar, , stop button goes red -- has posted form , brought result. if refresh page , keep trying this, randomly exhibits problem, not consistently. this problem occurred on ff2 on windows 2008 server , ff3 on ubuntu 8.04. problem not seen ie6, ie7, opera (latest stable, nov 2008), or safari (latest stable, nov 2008). is known bug in ff ajax, or there can jquery stop page load issue? edit: might have tinymce. cannot confirm 100%, when use jquery bring form tinymce control on it, problem seems exhibit more often. tried doing form not have tinymce control on it, several times, , couldn't problem occur. again, that's nothing conclusive, might factor. edit: okay, commented out tinymce stuff , can confirm problem g...

.net - Are delegates and callbacks the same or similar? -

are delegates same thing callbacks? or related somehow? a "callback" term refers coding design pattern, available in language has function pointers, or analogue function pointers (which kinda delegate is) in pattern, pass pointer function function, within called function, can "call back" function passed it. in way can control large chunk of internal behavior of method outside method, passing pointers different "callback" function each time call it... example of callback when have sorting algorithm has passed pointer function "compare" arbitrary pair of objects in list sorted, determine goes before other. on 1 call sort method, might pass callback function compares object name, , time pass function compares object weight, or whatever... a delegate, otoh, specific .net type acts signature-specific container function pointer... in .net managed code, delegates way create , use function pointer. in .net callback, in fact passin...