Posts

Showing posts from July, 2013

logic - Is break; required after die() php -

i've been thinking much... in area of switch case break; required after die() example: switch($i){ case 0: die('case without break;'); case 1: die('case break;'); break; } die() alias exit() , exit() terminate program flow immediately. (shutdown functions , object destructors still executed after exit() ) and no, not syntax error omit break , on contrary there many useful cases omitting break . check manual page of switch statement examples.

c# - Where to find samples for latest ServiceStack release? -

i new servicestack. want know sample codes link (and samples github) still working latest servicestack release? http://www.servicestack.net/docs/ormlite/ormlite-overview i encountered error @ //re-create table schemas: dbcmd.droptable<orderdetail>(); dbcmd.droptable<order>(); dbcmd.droptable<customer>(); dbcmd.droptable<product>(); dbcmd.droptable<employee>(); dbcmd.createtable<employee>(); dbcmd.createtable<product>(); dbcmd.createtable<customer>(); dbcmd.createtable<order>(); dbcmd.createtable<orderdetail>(); when switched older dlls (3.7.9.0) that's fine those docs appear 2011, , servicestack has had new api (or two) since then. you'll better off looking @ github: https://github.com/servicestack/servicestack.ormlite in particular case, methods added idbcommand have been moved idbconnection .

ios6 - sizeWithAttributes causes crash on ios 6. Works in ios 7 -

since sizewithfont method deprecated wanted try sizewithattributes works expected when running ios 7. when run on ios 6 causes crash, , can see looking @ header looks this. - (cgsize)sizewithattributes:(nsdictionary *)attrs ns_available_ios(7_0); since sizewithattributes came category removed can't use in ios 6 , under. what can it? can use sizewithfont: if target < ios 7, there must reason has been deprecated, want avoid it. any ideas? it did not exist on ios 6 guess why crash. in osx 10.8 , 10.9.

Python, How to extend Decimal class to add helpful methods -

i extend decimal class add helpful methods it, specially handling money. the problem when go this: from decimal import decimal class newdecimal(decimal): def new_str(self): return "${}".format(self) d1 = newdecimal(1) print d1.new_str() # prints '$1' d2 = newdecimal(2) d3 = newdecimal(3) d5 = d2 + d3 print d5.new_str() #exception happens here it throws exception: attributeerror: 'decimal' object has no attribute 'new_str' this because of way decimal arithmetic, returns new decimal object, literally calling decimal( new value ) @ end of computation. no workaround other reimplementing arithmetic? you don't want have method printing decimal objects in alternate way. top-level function or monkeypatched method whole lot simpler, , cleaner. or, alternatively, money class has decimal member delegates arithmetic to. but want doable. to make newdecimal(1) + newdecimal(2) return newdecimal(3) , can override __...

reporting services - Report Builder 3.0 underlying SQL -

i have report builder 3.0 report has several parameters on it. specifically, account number (defined char(12) in database). database vendor supplied database, have 0 control on database schema. my question when have free form parameter account id, how transformed query sent sql database? the way handle these free form fields have user defined function: public function convertstringtoarray(sourcestring string) string() dim arrayofstrings() string dim emptystring string = " " if string.isnullorempty(sourcestring) arrayofstrings = emptystring.split(",") else arrayofstrings = sourcestring.replace(" ", "").split(",") end if return arrayofstrings end function and parameter defined as: @acctlist = code.convertstringtoarray(parameters!acctlist.value) the sql query has in clause: ac.account_id in (@acctlist) my question how build in clause. literally like: ac.account_id in (n'acct1',n'...

javascript - How do I display user input into my story -

i trying create story interjects users input answers text boxes , radio buttons. yet having trouble display. displays until "+transport+". have far: function story() { //collect users input data var transport = ""; var name = document.getelementsbyname("name")[0].value var title = document.getelementsbyname("title")[0].value var noun = document.getelementsbyname("noun")[0].value var num1 = document.getelementsbyname("num1")[0].value var num2 = document.getelementsbyname("num2")[0].value var travelmeasure = document.getelementsbyname("measuretravel")[0].value //determine mode of transportation chosen if (document.getelementsbyname("transport")[0].checked) { transport = spaceship; } else if (document.getelementsby...

sql - Return everything after specific value -

this question has answer here: convert fraction decimal [closed] 1 answer working on 10g. i tried write regexp removes before first dash(-). however, did not anticipate complexity of syntax. i have this: regexp_substr (myval, '[^"]+') this removes values after first double quotation leaving me data like: 10-3/4, 5-1/2, 7-5/8 i assumed changing double quotes dash , putting carat after dash it, no luck. if that's need do, don't need use regex , since other simpler functions: select substring(myval,instr(myval,'-'),length(myval)) yourtable

automatic code generation for IDL (ITTVIS/exelis) in eclipse IDE? -

i hoping find way automatically generate code based on existing code. actual functionality similar javadoc or in case idldoc or automatic get/set functions. i want create generic code based on listed parameters. how accomplish within eclipse? i think example best, here accomplish: keyword1: stuffidontcareabout, $;comments keyword2: otherstuffidontcareabout, $;more comments keyword3: laststuffidontcareabout $ what need in eclipse can have eclipse parse above block , output following part of code? keyword1=inp_keyword1, keyword2=inp_keyword2, keyword3=inp_keyword3 thanks my usual knee-jerk response suggest use jet it's designed for. for specific case, however, might better off writing simple popup action (use new plugin project popup action template) parses properties file (looks simple enough in java) , writes out target code file, console or, if you're clever, existing file in right place. once have plugin generated template, rest should simple ja...

c++ - How to iterate through std::tuple? -

this question has answer here: iterate on tuple 9 answers any better solution manually writing utility this? template < size_t > struct sizet { }; template < typename tupletype, typename actiontype > inline void tupleforeach( tupletype& tuple, actiontype action ) { tupleforeach( tuple, action, sizet<std::tuple_size<tupletype>::value>() ); } template < typename tupletype, typename actiontype > inline void tupleforeach( tupletype& tuple, actiontype action, sizet<0> ) { } template < typename tupletype, typename actiontype, size_t n > inline void tupleforeach( tupletype& tuple, actiontype action, sizet<n> ) { tupleforeach( tuple, action, sizet<n-1>() ); action( std::get<n-1>( tuple ) ); } to used this: std::tuple<char, int, double> tt; tupleforeach( tt, (boost::lambda::_1 =...

c# - Getting spans for a SpanNear query? -

i trying words surrounding match in spannearquery not able figure out how to. know there function called getspans documented here : 129 public override spans getspans(indexreader reader) 130 { 131 if (clauses.count == 0) 132 // optimize 0-clause case 133 return new spanorquery(getclauses()).getspans(reader); 134 135 if (clauses.count == 1) 136 // optimize 1-clause case 137 return clauses[0].getspans(reader); 138 139 return inorder?(spans) new nearspansordered(this, reader, collectpayloads):(spans) new nearspansunordered(this, reader); 140 } is function supposed use (because return list/array of spans single span) or there other function? for instance, if text is: lucene powerful , search term lucene powerful , want retrieve words in match. in order able access adjacent words, need store termvectors pos...

opengl - Level Of Detail Surfaces from Multilevel B Splines -

Image
i read paper scattered data interpolation multilevel b-splines . consider surface z(x,y), xmin<=x<=xmax, ymin<=y<=ymax. next consider 4x4 grid of "control" points (black): p0 surface covers central cell: the z value of point (red) on surface (yellow) may approximated weighted sum of values in control points. weights distances control points. next divide center cell 2x2 cells , add 1 cell border around surface. result control grid p1 (blue). more accurate approximation of z value in red point may found adding distance weighted sum of 4x4 closest control points in p1 initial approximation above. likewise can repeatedly half size of cells , create new control grids: p2, p3, ...pn. each grid new "level". each new grid add more detail surface. control grids become increasingly sparse; values differ 0 surface changes abruptly relative sourrounding points. the result possible storage scheme should able store surface great amount of detail r...

makefile - How does the make work when the file is not in target? -

i looking code of libavcodec. makefile of https://github.com/libav/libav/tree/master/libavcodec# . instance, if execute make api-example.c, recognize it. while there no target api-example.c. moreover, when remove makefile directory, recognize target. i'm missing something. make has number of built-in rules. if file asked make build exists, , there no target file defined gives prerequisite make can check see if it's date, file up-to-date definition: exists, , has no prerequisites. the way target has no prerequisites can out of date if doesn't exist: has created.

php - Prevent echo JSON from going directly to screen -

i able pass json via ajax call , put contents in , same "echo" statement returning json "echos" json directly page, don't want. how prevent happening? here code: my form: <script type="text/javascript" src="includes_js/registration3.js"></script> ajax: $.ajax({ type: "post", url: "includes_php/registration3.php", data: datastring, datatype: "json", success: function(data) { $('.message').text(data); } }) php in url: $msgarr[] = "please enter fields"; $json_msg=json_encode($msgarr); echo $json_msg; //also sends directly page success: function(data) { $('.message').text(data);//here magic happens, //change line want } you have parse json: link obj=$.parsejson(data) and can have access keys alert(obj.key1); in php: $msgarr = array("key1"=>"please enter fields"); $json_ms...

html - Populate select list using javascript -

i trying populate html select list using javascript. believe doing correctly, not able populate list. list still empty. missing here? html: <%@ page language="c#" inherits="system.web.mvc.viewpage<dynamic>" %> <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <script type="text/javascript" src="../../scripts/app/base.js"></script> <title>index</title> </head> <body> <div> select <select id = "mylist"></select> </div> </body> </html> js: window.onload = function(){ var select = document.getelementbyid("mylist"); var options = ["1", "2", "3", "4", "5"]; (var = 0...

ado.net - .NET application will not connect to to SQL Server 2000 -

i've been pulling hair out on one. have legacy app (asp.net 2.0) have moved different machine , trying connect sql server 2000 database on same machine, failing every time general error: a network-related or instance-specific error occurred while establishing connection sql server. server not found or not accessible. verify instance name correct , sql server configured allow remote connections. what weird .net apps (windows or web). can connect fine - using windows or sql server authentication - enterprise manager, query analyser, server explorer in visual studio. works fine on xp machine, new setup in on win 7 i've checked tcpip enabled sql server , listening on port 1433. the server setup mixed mode authentication. have tried both methods of trying connect. removed mixed mode , tried windows authentication , still did not work. i have double checked using right server name\instance name , correct credentials. port 1433 open on firewall (not matters - same machin...

java - Jersey 2.0 Content-Length not set -

i'm trying post web service requires content-length header set using following code: // edit: added apache connector code clientconfig clientconfig = new clientconfig(); apacheconnector apache = new apacheconnector(clientconfig); // setup client log requests , responses , entities client.register(new loggingfilter(logger.getlogger("com.example.app"), true)); part part = new part("123"); webtarget target = client.target("https://api.thing.com/v1.0/thing/{thingid}"); response jsonresponse = target.resolvetemplate("thingid", "abcdefg") .request(mediatype.application_json) .header(httpheaders.authorization, "anauthcodehere") .post(entity.json(part)); from release notes https://java.net/jira/browse/jersey-1617 , jersey 2.0 documentation https://jersey.java.net/documentation/latest/message-body-workers.html implies content-length automatically set. however, 411 response...

javascript - jQuery or JS turn all words into italic type -

var test = $('.text1').val(); var re = /\w+/g $('.text3').html(test.replace(re, '<i>' + test.match(/\w+/g) + '</i>')); if basic value "link text тест", return " <i>link,text</i> <i>link,text</i> тест ". need " <i>link</i> <i>text</i> текст " what can do? couldn't do, body { font-style: italic; // add italic!important if need to... } your question isn't worded well. otherwise if must jquery or js then... $("*").css("font-style", "italic"); that should work.

html - Responsive solution for long URLs (that exceed the device width) -

as title implies, while building responsive sites, run issue long(ish) urls breaking fluid grid , causing horizontal scrolling on smaller devices. because they're 1 long string, don't wrap , push width of container wider device width... <--device--> ______________ | | | http://longurlthatdoesntfit.com | | | | sometimes make container overflow:hidden chops off end of url , tends lock glitchy. approach might shrink font-size on smaller devices, in situations url lengths vary, mean shrinking way down ensure has enough space. there must better way. if neither hiding or scrolling overflow work you, consider forcefully word wrapping in css : word-wrap: break-word;

apache - Mod-rewrite lock execution of PHP files and access to .git folder -

i want use mod-rewrite block execution of files except bootstrap.php file in document root, , want block access files in .git folder (also in document root). (probably better solution) allow access files inside of directory called public (there multiple directories called public in different parts of application), deny direct access other file while directing other requests through bootstrap.php file. here's have. rewriteengine on rewritecond %{request_filename} !-f rewriterule .* /bootstrap.php rewritecond %{request_filename} -fd rewriterule .*\.php /denied.php rewritecond %{request_filename} -fd rewriterule \.git /denied.php any suggestions appreciated. you not allowed use multiple verification on condition files, give error bad flag delimiters , if use this: rewritecond %{request_filename} !-fd so this: options +followsymlinks -multiviews rewriteengine on # not existent file rewritecond %{request_filename} !-f # , not folder rewritecond %{request_filen...

Can I create a websocket server using JavaScript (client-side)? -

Image
this question has answer here: do websockets allow p2p (browser browser) communication? 5 answers i have seen websockets reference mdn article says websocketserver used opening new websocket server. required information (port, origin, location). then, mean can create websocket server client-side? if that's it, mean can turn this... (each arrow websocket connection) ...into this? but, browsers have power of doing without router/firewall configuration? and how can use it? websocketserver link broken. , have tried searching haven't found anything. it looks websocketserver under development mozilla without support or of like. searched through of repositories , couldn't find references, except in testing code normal websockets. if you're looking form of p2p websockets, don't think that's possible without wor...

Symantec EV SSL with Heroku? -

does know how set symantec ev ssl certificate on heroku? i'm super confused @ moment. offer me download of x.509 cert , pkcs7 cert. in addition, can download apache bundle, plesk bundle, certificate issuer, or intermediate ca 1. i'm lost.

ruby on rails - Why do I get "bad ecpoint" with OpenSSL::SSL::SSLError Stripe transaction? -

i building rails application stripe integrated. have setup except when try carry out transaction on local development environment. get: ssl_connect returned=1 errno=0 state=sslv3 read server key exchange b: bad ecpoint i tried lot of different things valid ssl cert on machine nothing seems working. it isn't setup because working fine on test heroku server. any appreciated. it typically happens when there issues ruby/openssl integration. try updating rvm , reinstalling libs/ruby . if you're still having issues, please list os, ruby, openssl , rvm/rbenv versions you're using.

Apply function to a MultiIndex dataframe with pandas/python -

i have following dataframe wish apply date range calculations to. want select rows in date frame the date difference between samples unique persons (from sample_date) less 8 weeks , keep row oldest date (i.e. first sample). here example dataset. actual dataset can exceed 200,000 records. labno name sex dob id location sample_date 1 john m 12/07/1969 12345 12/05/2112 2 john b m 10/01/1964 54321 b 6/12/2010 3 james m 30/08/1958 87878 30/04/2012 4 james m 30/08/1958 45454 b 29/04/2012 5 peter m 12/05/1935 33322 c 15/07/2011 6 john m 12/07/1969 12345 14/05/2012 7 peter m 12/05/1935 33322 23/03/2011 8 jack m 5/12/1921 65655 b 15/08/2011 9 jill f 6/08/1986 65459 16/02/2012 10 julie f 4/03/1992 41211 c 15/09/2011 11 angela f 1/10/1977 12345 23/10/200...

java - out.write runs several times but resulting file is empty -

i developing in java se on netbeans 7.3.1 on windows 7. i trying write set on numbers, 1 on each line, ascii text file. filewriter fstream = new filewriter(outputfilename, false); //false tells not append data. bufferedwriter out = new bufferedwriter(fstream); (int i=0; i<numbins; ++i){ string str=integer.tostring(hist[i]); str.concat("\n"); out.write(str); } br.close(); numbins 6 , program runs through without errors. check tih debugger and out.write(str); is called 6 times. hist[i] small integral numbers. reason, resulting file empty , of 0 size. close bufferedwriter object filewriter fstream = new filewriter(outputfilename, false); //false tells not append data. bufferedwriter out = new bufferedwriter(fstream); (int i=0; i<numbins; ++i){ string str=integer.tostring(hist[i]); s...

c# - System.FormatException: String was not recognized as a valid DateTime -

i using ajax calender extender textbox, , want disable past dates, user not able select those, less today's date. code follows in .aspx page <asp:textbox id="txtfromdate" runat="server" ontextchanged="txtfromdate_textchanged" autopostback="true"></asp:textbox> <asp:calendarextender id="calendarextender1" runat="server" targetcontrolid="txtfromdate"> </asp:calendarextender> <asp:toolkitscriptmanager id="toolkitscriptmanager1" runat="server"> </asp:toolkitscriptmanager> and on .cs page protected void txtfromdate_textchanged(object sender, eventargs e) { datetime dt1 = datetime.parse(txtfromdate.text); if (dt1 < datetime.now) { //response.write("you can not choose date earlier today's date"); txtfromdate.text = null; } } but gettin...

android - No result with barcode scanner -

i'm new android apps. i'm trying create barcode scanner, result not appear in edittext . also, in onactivityresult following error shown: the method onactivityresult(int, int, intent) type new view.onclicklistener(){} never used locally i have class intentintegrator , intentresult in project. this part of code: btnbar.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { intent intent = new intent("com.google.zxing.client.android.scan"); startactivityforresult(intent, 0); } public void onactivityresult(int requestcode, int resultcode, intent data) {; if (resultcode == activity.result_ok && requestcode == 0) { bundle extras = data.getextras(); string result = extras.getstring("scan_result"); edittext desc = (edittext) findviewbyid(r.produto.desc); des...

c++ - How to create an emacs macro for text templates -

i new lisp , having trouble figuring out how create macro in emacs following functionality: tired of writing out pattern in c++ for loop: for (int = 0; < n; i++) { } call macro "forloop" following: when type "m-x forloop" macro prints out for (int in buffer , waits input. type "i" , hit return after macro continues , prints for (int = 0; < and again waits input. after type "n" , hit return macro finishes printing rest: for (int = 0; < n; i++) { } after extensive reading , testing, able write simple lisp functions, create own macros, save them , call them , on... still can't quite figure out how make macro have described above. thoughts appreciated! in advance! macros nice speeding coding in language. prefer macro dynamic in way described don't have remember how many arguments needs , in order go when calling it. i use yasnippet ( http://www.emacswiki.org/emacs/yasnippet ) this, there lot of o...

wpf - How to change the default program to open any Word documents, using C#? -

in wpf application, want open word documents in word 2007 or above, whether or not default program opening word documents word 2007. if default program open word documents open office, want open them in word 2007+. how can this? this doesn't have wpf. you'll need word installed or add the folder in located path environment variable. assuming file name variable called filename , full path of winword.exe stored in wordpath (or winword.exe in path), need - processstartinfo startinfo = new processstartinfo { createnowindow = false, arguments = filename, filename = wordpath }; process wordprocess = process.start(startinfo); note 1 - filename passed directly word. if path contains white spaces you'll have wrap in "". like filename =...

Can't find how to select path to run a C program -

i using mac os x , have written c program using gcc compiler. while running program on terminal being shown "no such file or directory found" please me how select path? run $./yourprogramfile command ./ in beginning important. means program resides in current directory. example: /path/to/your/cfile $ gcc myfile.c -o myfile /path/to/your/cfile $ ./myfile

r - How to find matches among two list of names -

i have 2 long vectors of names ( list.1 , list.2 ). want run loop check whether name in list.2 matches name in list.1. if want append vector result value position of matching name in vector list.1. (i in list.2){ (j in list.1){ if(length(grep(list.2[i], list.1[j]), ignore.case=true)==0){ append(result, j) break } else append(namecomment.corresponding, 0) } } the above code brute-force , since vectors 5,000 , 60,000 name long, run on 360,000,000 cycles. how improve it? which , %in% task, or match depending on going for. point note match returns index of first match of it's first argument in it's second argument (that if have multiple values in lookup table first match returned): set.seed(123) # assuming these values want check if in lookup 'table' list2 <- sample( letters[1:10] , 10 , repl = t ) [1] "c" "h" "e" "i" "j" "a" "f" "i" "f...

c# - Error while reading ConnectionString from App.config file -

i have app.config file: <?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionstrings> <add name="acwconnectionstring" connectionstring="data source=ashish-pc\\sqlexpress;initial catalog=acw;user id=ash159;password=password"/> </connectionstrings> </configuration> which using here: string connstring = configurationmanager.connectionstrings["acwconnectionstring"].tostring(); here getting error 'nullreferenceexception unhandled'.. why getting error? thankyou!! tried these getting same error: string connstring = configurationmanager.connectionstrings["acwconnectionstring"].connectionstring; string connstring = configurationmanager.connectionstrings["acwconnectionstring"].connectionstring.tostring(); note: have added system.configuration , set reference it. know have 3 projects(admin,employee,database) in single project(abc). have added...

Python pandas change duplicate timestamp to unique -

i have file containing duplicate timestamps, maximum 2 each timestamp, not duplicate, second timestamp needs add millisecond timestamp. example, having these in file, .... 2011/1/4 9:14:00 2011/1/4 9:15:00 2011/1/4 9:15:01 2011/1/4 9:15:01 2011/1/4 9:15:02 2011/1/4 9:15:02 2011/1/4 9:15:03 2011/1/4 9:15:03 2011/1/4 9:15:04 .... i change them into 2011/1/4 9:14:00 2011/1/4 9:15:00 2011/1/4 9:15:01 2011/1/4 9:15:01.500 2011/1/4 9:15:02 2011/1/4 9:15:02.500 2011/1/4 9:15:03 2011/1/4 9:15:03.500 2011/1/4 9:15:04 .... what efficient way perform such task? setup in [69]: df = dataframe(dict(time = x)) in [70]: df out[70]: time 0 2013-01-01 09:01:00 1 2013-01-01 09:01:00 2 2013-01-01 09:01:01 3 2013-01-01 09:01:01 4 2013-01-01 09:01:02 5 2013-01-01 09:01:02 6 2013-01-01 09:01:03 7 2013-01-01 09:01:03 8 2013-01-01 09:01:04 9 2013-01-01 09:01:04 find locations difference in time previous row 0 seco...

asp.net mvc 3 - Changing <a href> dynamically in jquery Teleric grid MVC3 -

hello working on teleric grid in mvc3 i want change href of "a" tag dynamically below code function onrowdatabound(e) { if (e.dataitem.affiliateid == 1) { var id=e.dataitem.id; e.row.cells[0].innerhtml ="<a href=\"@url.content("~/customer/address/list/"+id)\" target=_blank>nxn v</a>"; e.row.cells[0].style["color"] = "red"; } but error id not exist in current context any solutions? the url.content() call executed @ time view parsed , sent browser. javascript executed when grid renders in browser (much later). all this @url.content("~/customer/address/list/"+id) is c#-code. cannot access javascript variables in c# code or vice versa. what need generate url without id , concatenate in javascript: e.row.cells[0].innerhtml ="<a href=\"@url.content("~/customer/address/list/")"+ id +"\" target=_blank>nxn v...

Phonegap camera crash on android 4.1.2, samsung galaxy s3, HTC -

i think lot of developers familier problem of phonegap crashes/restarts after getting picture camera / library on android 4.1.2. after many searches of many solutions want put order problem , wish me understand current solution. note: current stable phonegap version 2.9.0. using fileuri , not dataurl, because encoded base64 big dom handle. editing (not via phonegap build config.xml) android manifest file , add following line every activity: android:alwaysretaintaskstate="true" android:launchmode="singletask". limit resolution using targetwidth/targetheight, because image big causes memory on load. , reducing quality.. switch off "do not keep actitivies" option in android settings.. ofcourse not real solutions becaues can't ask users that.. again, editing android manifest (with discarding phonegap build service) , add: android:configchanges="orientation|keyboardhidden|keyboard|screensize|locale" <uses-fea...

unit testing - How do you write tests for the argparse portion of a python module? -

i have python module uses argparse library. how write tests section of code base? you should refactor code , move parsing function: def parse_args(args): parser = argparse.argumentparser(...) parser.add_argument... # ...create parser like... return parser.parse_args(args) then in main function should call with: parser = parse_args(sys.argv[1:]) (where first element of sys.argv represents script name removed not send additional switch during cli operation.) in tests, can call parser function whatever list of arguments want test with: def test_parser(self): parser = parse_args(['-l', '-m']) self.asserttrue(parser.long) # ...and on. this way you'll never have execute code of application test parser. if need change and/or add options parser later in application, create factory method: def create_parser(): parser = argparse.argumentparser(...) parser.add_argument... # ...create parser like... re...

sql server - update cascade in self referencing table - best practice? -

it seems not possible set update cascade on self-referencing table. as consequence, not possible rename parent node. workaround can see create new entry, , re-link child nodes (and data other tables), , delete old entry. as rather complicated, there better solution, cannot see in moment? the simplest (i guess depends on specific case) solution create identity primary key , reference/self reference on instead of name simple field. that allow rename nodes without affecting dependant nodes, , make less complicated update structure while still maintaining foreign key relationships other tables.

hibernate - Insertion happened when update the record -

in jsf project seam3.2.2 integration, update doesn't work. instead update value, insert new value in table. please need here. flow of project. pages.xml: <page view-id="/updateuser.xhtml" action="#{usereditaction.setcurrentuser()}"> <navigation> <rule if-outcome="success"> <redirect view-id="/secure/admin/user/updateuser.xhtml"/> </rule> </navigation> <begin-conversation join="true"></begin-conversation> </page> usereditaction.java bean: @requestparameter private integer userid; @override public string setcurrentuser(){ system.out.println("selected userid ----- " + userid); currentuser = userservice.getuser(userid); return "success...

Python : Get gtk.treeview selection from another widget -

it looks way selected item of gtk.treeview() click on : tree_selection = self.treeview.get_selection() tree_selection.connect('changed', self.my_callback) self.treeview.connect('row-activated', self.my_other_callback) but if i'm listing files in treeview, , need "file properties" menu item? or play button, needs access selected file pass filename player class / method ? bonus question : how call my_other_callback tree_selection.connect('changed', ...) (that not seem return row data..?) or in other words, how pass treeview , path callback? to selection of tree view, call the get_selected_rows method of gtk.treeselection object. can call @ place can access tree view. it unclear why want pass tree view my_other_callback since it, being method on class, can access self.treeview . if want anyway, can add tree view (or other python object) additional argument connect : tree_selection.connect('changed',...

android - Google+-Package name not getting added to String[]? -

my app keeping "third-party app-exclude-list" package names in string[] (and serializing sharedpreferences using method below). works fine, users, google+ isn't getting added list. only happens google+ app. know, g+ app isn't special, it's package name on google play listed com.google.android.apps.plus , shouldn't confuse saving-algorithm. works fine on own phone, i'm stumped @ causes this, lot of users have reported issue :-/! public void saveexcludedapplicationlist(string[] applicationlist) { mexcludedapplicationlist = applicationlist; string combined = ""; (int i=0; i<mexcludedapplicationlist.length; i++){ combined = combined + mexcludedapplicationlist[i] + ";"; } mpref.edit().putstring(pref_excluded_application_list, combined).commit(); } turns out had nothing way serializing this, "google+ messaging" app beging distributed same package g+.

javascript - Phonegap events online/offline not working -

i writing app phonegap(cordova) 3.0.0 , events "online" , "offline" doesn't work. when tried event "resume", event ok. using xcode 4.5 , ios. this main javascript file of phonegap project: var app = { initialize: function() { this.bindevents(); }, // bind event listeners // // bind events required on startup. common events are: // 'load', 'deviceready', 'offline', , 'online'. bindevents: function() { document.addeventlistener('deviceready', this.ondeviceready, false); document.addeventlistener('online', this.ondeviceonline, false); document.addeventlistener('resume', this.ondeviceresume, false); }, ondeviceready: function() { app.receivedevent('deviceready'); }, ondeviceonline: function() { app.receivedevent('deviceonline'); }, ondeviceresume: function() { app.re...

asp.net mvc - Making my own HtmlHelper extension for input that works with model binding -

i unhappy current dropdownlist implementation, because can't option tags (only selected, text , value supported). want make own can set disabled , other stuff on individual options. currently i'm altering options javascript, think it's bit of hacky way it, , i'd prefer render correct html begin with. i know can make template uses select , option tags , make options want them - normal dropdownlist extension adds stuff val stuff , specific name , id guess proper databinding when submitting form: <select data-val="true" data-val-number="the field selectedvalue must number." id="parentdropdown_selectedvalue" name="parentdropdown.selectedvalue"> how go adding these attributes own templates? you right, attributes (and specially name attribute) critical model binding. say want create custom helper like public static mvchtmlstring customhelperfor<tmodel, tvalue>(this htmlhelper<tmodel> html, expr...

jsp - How to add an extra URL mapping for an servlet that already mapped in Eclipse IDE 4.2? -

i want add url mapping application in eclipse. since eclipse ide not using web.xml deployment descriptor , don't know how this. that , servlet logservlet mapped /logservlet , have need add mapping /tamil/logservlet . since web.xml not used deployment descriptor in eclipse , don't know how . please me in issue. (project created in dynamic web module 3.0 in java ee 6[jdk 7] ) 2) please guide me how create web.xml file contains deployment info on it.( "generate deployment descriptor stub" not generating servlet mappings , welcome pages tags ) read the javadoc : java.lang.string[] urlpatterns url patterns of servlet so need @webservlet(urlpatterns = {"/logservlet", "/tamil/logservlet"}) that said, given patterns want, seems you're confused between relative , absolute paths, , single pattern should sufficient. if want more help, explain why want these 2 patterns.

design - I am not able to find joomla table content -

i new joomla, , not able find content want change in table layout. i fount in template code , in whole admin panel (article, category, module, etc..), not able displaying. please me. thank you. all content stored in mysql database. if have content appearing on page , can't figure out coming recommend go through sample data version of joomla , unpublished modules 1 @ time until find it.

javac - Set Java compiler compliance level -

i need compile java program on command line, , trying set compiler level lower 1 (1.6). tried didn't work: javac -1.6 hello.java use -source , -target options: javac -target 1.6 -source 1.6 hello.java

ios - "Expected status code in (200-299), got 404" -

this code: nsurl *url = [nsurl urlwithstring:@"http://wspublisherv2.skygiraffe.com/wspublisherv2.svc/authenticate"]; afhttpclient *client = [[afhttpclient alloc]initwithbaseurl:url]; nsdictionary *parameters = [nsdictionary dictionarywithobjectsandkeys:@"john@sgdemo.com", @"username", @"123", @"password", nil]; nslog(@"%@", parameters); [client postpath:nil parameters:parameters success:^(afhttprequestoperation *operation, id responseobject) { nslog(@"success: %@", responseobject); } failure:^(afhttprequestoperation *operation, nserror *error) { nslog(@"failure: %@", error); }]; it triggers failure block , "expected status code in (200-299), got 404" message. when try through fiddler works. you need more information. use proxy charles proxy watch traffic between device , server. that'll let see actual request. can compare request w...

jquery - what is the traditional way of sorting search results? -

i stuck in issue since yesterday. i have page writing in django/python. , have search function in project. 1 searches , comes result page. here issue: which possibilities there implement sort tool? know are: with jquery's load() function, load part of page results are i heard of dajaxice similiar job this know. fighting load , having difficulties. there other technologies in django make sort results ? you can sort in django using instructions found here: good ways sort queryset? - django . instead of using jquery, i'd recommend use underscore.js sort array. it depends on you'd sort array , framework you're more comfortable with, although lean towards django solution allows avoid import.

getLastNonConfigurationInstance() substitute android -

when use getlastnonconfigurationinstance() the eclipse ide tells me depreceated.can tell me substitute of method? from documentation: this method deprecated in api level 13. use new fragment api setretaininstance(boolean) instead

regex - What does the following regular expression match for? -

for sample url's following req.url.match(/^\/node\// match? i couldn't find expression in http://www.w3schools.com/jsref/jsref_obj_regexp.asp , other resources following so, had put community. it matches string /node/ , must @ beginning of string. the first , last / regex delimiters. the ^ matches beginning of string. the \/ escapes / match / . the node matches exact string node .

python - Exception TypeError warning sometimes shown, sometimes not when using throw method of generator -

there code: class myexception(exception): pass def gen(): in range(3): try: yield except myexception: print("myexception!") = gen() next(a) a.throw(myexception) running code: $ python3.3 main.py myexception! $ python3.3 main.py myexception! exception typeerror: typeerror('catching classes not inherit baseexception not allowed',) in <generator object gen @ 0xb712efa4> ignored $ python3.3 main.py myexception! $ python3.3 main.py myexception! $ python3.3 main.py myexception! exception typeerror: typeerror('catching classes not inherit baseexception not allowed',) in <generator object gen @ 0xb714afa4> ignored the thing don't understand why there printed exception typeerror warning. there wrong custom exception? you seeing __del__ hook misbehaving somewhere. the typeerror being thrown while shutting down , python interpreter exiting deleted , exceptions thrown in __del__ deconstructor hook bei...

java - Equivalent for Strict mode in API level less than 8 -

i'm developing android application.i connect application mysql database through php file hosted in webserver.the code use is strictmode.threadpolicy policy = new strictmode.threadpolicy.builder().permitall().build(); strictmode.setthreadpolicy(policy); final arraylist<namevaluepair> namevaluepairs = new arraylist<namevaluepair>(); if(fid.gettext().tostring().trim().length() > 0 && it1.gettext().tostring().trim().length() > 0 && it2.gettext().tostring().trim().length() > 0 && it3.gettext().tostring().trim().length() > 0 && it4.gettext().tostring().trim().length() > 0 && it5.gettext().tostring().trim().length() > 0 && it6.gettext().tostring().trim().length() > 0) { namevaluepairs.add(new basicnamevaluepair("item1",item1)); namevaluepairs.add(new basicnamevaluepair("item2",item2)); name...

sql - Return only one row of a select that would return a set of rows -

i have table like: create table mytab( id integer primary key, is_available boolean not null default true ); i need query returns first encountered row has is_available set false. something like select * mytab not is_available order id asc limit 1

Is there a PYVISA version for Android? -

is there pyvisa version run on android systems? i've discovered qpython , want "export" old python code (which needs pyvisa ) android platforms. well, recommendation alternatives of qpython welcomed... thanks, teby as long theres no visa implementation on android, can't use pyvisa . pyvisa thin python wrapper around visa implementation, e.g. ni-visa. , don't see why wan't to. however, possible run python on android, see qpython , kivy or python-for-android .

ruby on rails - rails_admin ArgumentError when trying to edit or create a new entry -

i'm getting error while trying create new or edit limitation (model below) argumenterror in rails_admin/main#new showing /users/deini/.rvm/gems/ruby-2.0.0-p195/gems/rails_admin-0.4.9/app/views/rails_admin/main/_form_filtering_select.html.haml line #11 raised: wrong number of arguments (0 1+) extracted source (around line #11): (selected_id = field.selected_id) selected_id = selected.send(field.associated_primary_key) selected_name = selected.send(field.associated_object_label_method) else selected_id = field.selected_id selected_name = field.formatted_value end system.rb class system < activerecord::base has_many :attachments has_many :limitations has_many :companies, :through => :limitations accepts_nested_attributes_for :attachments accepts_nested_attributes_for :companies attr_accessible :conf_type, :version, :hardware_type, :name, :attachments_attributes, :company_ids, :companies_attributes rails_admin list...

android - setOnKeyListener not responding -

i new android , working through list example book. have 1 activity displaying edittext , listview beneath it. there onkey event should add text edittext listview , clear edittext. however, when hit enter on keyboard happens new line added edittext , nothing added listview. the oncreate code is: @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_to_do_list); // ui references listview mylistview = (listview)findviewbyid(r.id.mylistview); final edittext myedittext = (edittext)findviewbyid(r.id.myedittext); myedittext.settext("test"); // create arraylist store items final arraylist<string> todoitems = new arraylist<string>(); // create arrayadapter bind items list view final arrayadapter<string> aa; aa = new arrayadapter<string>(this, android.r.layout.simple_list_item_1, ...

python - Turning a string into list of positive and negative numbers -

if have string in form 'a,b,c,d,e' letters positive or negative numbers, e.g '1,-2,3,4,-5' , want turn tuple e.g (1,-2,3,4,-5), how this? one method use ast.literal_eval : safely evaluate expression node or string containing python expression. string or node provided may consist of following python literal structures: strings, numbers, tuples, lists, dicts, booleans, , none . this can used safely evaluating strings containing python expressions untrusted sources without need parse values oneself. >>> import ast >>> ast.literal_eval('1,-2,3,4,-5') (1, -2, 3, 4, -5)

python - PyQt: Adding tabs -

i trying add tabs program isn't working far; tabs show on menubar , not sure why. here code: #! /usr/bin/python import sys import os pyqt4 import qtgui class notepad(qtgui.qmainwindow): def __init__(self): super(notepad, self).__init__() self.initui() def initui(self): newaction = qtgui.qaction('new', self) newaction.setshortcut('ctrl+n') newaction.setstatustip('create new file') newaction.triggered.connect(self.newfile) saveaction = qtgui.qaction('save', self) saveaction.setshortcut('ctrl+s') saveaction.setstatustip('save current file') saveaction.triggered.connect(self.savefile) openaction = qtgui.qaction('open', self) openaction.setshortcut('ctrl+o') openaction.setstatustip('open file') openaction.triggered.connect(self.openfile) closeaction = qtgui.qaction('close...

C# JSON & Parsing -

i have managed set-up simple webclient calls wcf service in wp8 application. method fires fine , data returned via openreadcompleted event. what wish convert returned data in json , populate collection of objects. this webclient code: private void button_click(object sender, routedeventargs e) { var webclient = new webclient(); var uri = new uri("urlgoeshere"); webclient.openreadcompleted += webclient_openreadcompleted; webclient.openreadasync(uri); } this openreadcomplete code: void webclient_openreadcompleted(object sender, openreadcompletedeventargs e) { var sr = new streamreader(e.result); var data = sr.readtoend(); //todo - create collection of sightingtypes , populate sr.close(); sr.dispose(); } and poco/object want populating: public class sightingtype { public string name { get; set; } public string brandid { get; set; } } update when hover on data, can see following (shortened): {\"message\...

List and delete Android notifications -

is there way list of notifications of app? i need list them , let user delete them 1 one, can't find way. i don't believe can list notifications have been shown. if user wants clear notification app need pull notification draw down , swipe away. can have app cancel notification using notificationmanager supplying id of notification cancel method. if use clicks notification have 2 options clearing. 1) when creating notification can call notification#setautocancel(true) , notification automatically cleared when user taps on it. 2) pass notification id part of pendingintent notification can use cancel notification when user taps on it.

ruby on rails - Getting only digits out of a string -

i have string - "4,450.50 $". i need numbers string. in example number - 4450.50 back. how it? str = "4,450.50 $" float str.scan(/[\d.]/).join # => 4450.5

freebase - PHP display sentences up to 100 characters -

my php script calls freebase api , outputs paragraph little bit of regex , other parsing magic on , return data variable $paragraph . paragraph made of multiple sentences. want return shorter version of paragraph instead. i want display first sentence. if less 100 characters i'd display next sentence until @ least 100 characters. how can this? you don't need regular expression this. can use strpos() offset of 99 find first period @ or after position 100 - , substr() grab length. $shortpara = substr($paragraph, 0, strpos($paragraph, '.', 99) + 1); you want add bit of checking in case original paragraph less 100 characters, or doesn't end period: // find first period @ character 100 or greater $breakat = strpos($paragraph, '.', 99); if ($breakat === false) { // no period @ or after character 100 - use whole paragraph $shortpara = $paragraph; } else { // take , including period found $shortpara = substr($paragraph, 0, $...