Posts

Showing posts from May, 2014

formatting - C - Printing formatted output of money -

in program print out table, 1 of columns has money listed. want print out money values neatly , right justified , below: $9.00 $8.00 $19.20 $200.90 i can right justify numbers so while(condition) { printf("$%5.2f\n", number); } but method $ isn't positioned want it, , output more like: $ 9.00 $ 8.00 $ 19.20 $ 200.90 can formatting want printf ? you can auxiliary string: while(condition) { char str[10] = {}; sprintf(str, "$%.2f", number); printf("%8s\n", str); }

'None' in python -

i have simple program above creates bst sorted array. should parse tree without showing leaves none. explain why program still spits out 'none'. i'm python noob , appreciate help.i have tried != 'none' along none same results. class node: def __init__(self,value): self.value=value self.nodeleft=none self.noderight=none def makebst(ia,start,end,tree): if (end < start): return none mid = (start + end) / 2 n = node(ia[mid]) n.nodeleft = makebst(ia, start, mid-1, tree) n.noderight = makebst(ia, mid+1, end, tree) tree.append(n) return n def printbst(root): print 'rr' ,root.value if root.nodeleft == none: print 'eot' else: print printbst(root.nodeleft) if root.noderight == none: print 'eot' else: print printbst(root.noderight) if __name__ == '__main__': array = [1, 2, 3, 4, 5, 6] dic = [] root

function - How to manipulate the Global Variable in C -

i have multiple void functions relies on each individual output of functions since there multiple variables (that same throughout code), each functions' output "stored" them , passed another. so, decided make variables global variables making them static .... right after necessary #include... codes. i able utilize functions (14 functions in total,all void ) calling 4 of them (each functions, after processing own function, passes result function , after series of passing, 4 of them needed called in int main() ) now, created void function requires global variables parameter since void function relies on data other functions "copied , put" global variables declared earlier. (which found not working, since heard storing data global variables not possible.) can teach me if there other way create series of functions requires output of each individual functions? i checked if variables stored properly, tried using printf method right after #3 process

c# - Adding Text Changed Event for Grid View Cell -

one column of gridview contains textbox , want add textchanged event text box in grid view. i think you're looking datagridview.cellbeginedit event

google cast - Is ChromeCast only for Video? -

can chromecast and/or google cast protocol run apps not video? in other words, possible create html5 app runs on chromecast , controlled smartphone/tablet? yes, receiver arbitrary html5 application. of course, should make sure it's suitable displayed on tv no attached keyboard , mouse, etc. see google cast receiver documentation more detail.

Concantenating strings in Javascript -

new javascript. code below, looking @ 2nd paragraph in particular...if var str = "sting equality test..." + stra, why 2nd, 3rd lines etc not output same output plus own line? edit sorry not explaining - wondering why code (once have cleaned up) doesn't produce first line (of 2nd paragraph) repeated, plus whatever state in 2nd , 3rd lines etc. don;t need to, exercise, don't understand. seems though should function init() { var stra = "javascript" === "javascript" ; var strb = "javascript" === "javascript" ; var flt = 7.5 === 7.5 ; var inta = 8 !== 8 ; var intb = 24 > 12 ; var intc = 24 < 12 ; var intd = 24 <= 24 ; var str = "string equality test: " + stra ; str += "<br>string equality test 2: " + strb ; str += "<br>float equality test: " ; + strc ; str += "<br>integer inequality test: " + inta ; str += "<br>greater test: " + intb ; str +=

c++ - What means the error : ..."bytes to alignment boundary" in Xcode/Clang? -

transformnode 4 bytes alignment boundary and here code cause warning : class transformnode : public node { public: int number; public: void test() { number = 12; } }; //node.h class node { public: typedef std::set<node *> childset; protected: childset mchildren; node * mparent; public: node(node * parent=0) : mparent(parent) {} ~node() {} node * addchild(node * node); inline node * getparent() { return mparent; } const childset &getchildren() const { return mchildren; } }; inline void node_test() { transformnode * node = new transformnode; node->test(); std::cout << node->number << "\n"; } int main() { node_test(); return 0; } the error happens when derive node class class transformnode. using xcode 5.0 warnings turned on , treating warnings errors. want understand going on code, turning off warnings or stop treating them errors not way want handle this. edit: added

how to delete mp3 file using php? -

how delete mp3 file using php? tried unlink() didn't work. unlink deletes file? for example: unlink('../../assets/users/vincent815_folder/music/eenie_meenie_-_sean_kingston.mp3'); i'm pretty sure it's not path because tried , played in site.

android - actionBar change MenuItem title color and default icon group -

i have menu: <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app_name="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/menu_title" android:title="@string/details_title" app_name:showasaction="always" /> <group android:id="@+id/options" app_name:showasaction="ifroom"> <item android:id="@+id/option1" android:title="@string/title1" /> <item android:id="@+id/option2" android:title="@string/title2" /> </group> my default style theme.appcompat.light, want change title color of menu_title. how can fix white? how change default icon of group? thanks!

delphi - TShellExecuteInfo lpParameters and ">" symbol -

this code calls sqlite3.exe database backup, not working because of ">" symbol in parameters. can tell me how fix it? procedure tfadmin.dodbbackup(adbbackupfile: string); var b, p, q: string; ps: tshellexecuteinfo; begin b := extractfilepath(paramstr(0)) + 'ppdb.bak'; p := extractfilepath(paramstr(0)) + 'sqlite3.exe'; q := extractfilepath(paramstr(0)) + 'ppdb.db .dump > ' + b; //here lies problem showmessage(p + ' ' + q); fmain.uniconnection1.close; try // execute process , wait terminate fillchar(ps, sizeof(ps), 0); ps.cbsize := sizeof(ps); ps.wnd := handle; ps.lpverb := nil; ps.fmask := see_mask_flag_no_ui or see_mask_nocloseprocess; ps.lpfile := pchar(p); ps.lpparameters := pchar(q); ps.nshow := sw_shownormal; if not shellexecuteex(@ps) raiselastoserror; if ps.hprocess <> 0 begin while waitforsingleobject(ps.hprocess, 50) = wait_timeout

php - How to fix VIM omnifunc to work with $this->variable->__AUTOCOMPLETE__ -

how vim omnifunc work this: $this->temp = new temp(); $this->temp-> // don't correct completion choices.... but works: $temp = new temp(); $temp-> // right list of completion choices here....

playframework - how to retrive data from db using hibernate , jpa -

i using play-2.1.3 framework. want retrive data db. using eclipse ,hibernate, , postgresql. when want retrive data db entity mgr, gives me error, not find answer... please me. ----------------------error in log file-------------------------- 2013-10-06 19:08:53,729 - [error] - org.hibernate.engine.jdbc.spi.sqlexceptionhelper in play-akka.actor.default-dispatcher-3 error: column client0_._ebean_intercept not exists position: 31 my entity class: package models; import play.db.ebean.*; import play.data.validation.*; import javax.persistence.*; @entity @table(name="clients") public class client extends model { /** * */ private static final long serialversionuid = 1l; @id @constraints.min(10) public long id; @constraints.required public string username; @constraints.required public string email; @constraints.required public string password; @constraints.required public string passwordsignup_confirm; public

javascript match exact string -

how can check javascript if 1 string contains other string? have like: var = "paris, france" var b = "paris.." a.match(b) //returns "paris, " should return null i think problem match uses regexp. there possibility allow sympols .,-/\ etc. ? thanks to see if 1 string contains another, use string.indexof() : var str = 'paris, france'; var strindex = str.indexof('paris..'); if(strindex == -1) { //string not found } else { //string found } but, in case want have contains() function, can add string below: if(!('contains' in string.prototype)) { string.prototype.contains = function(str, startindex) { return -1 !== string.prototype.indexof.call(this, str, startindex); }; } var str = 'paris, france'; var valid = str.contains('paris..'); if(valid) { //string found } else { //string not found }

python - How to add new requests for my Scrapy Spider during crawling -

i use xmlfeedspider in scrapy scrap real estate website. each url request generated spider (via start_urls) return page in xml bunch of ads , link next page (search results limited 50 ads). i therefore wondering how add additional page new request in spider ? i've been searching through stackoverflow while can't find simple answer problem ! below code have in spider. have updated parse_nodes() method mentioned paul next url not picked reasons. could yield additional requests in adapt_response method ? from scrapy.spider import log scrapy.selector import xmlxpathselector scrapy.contrib.spiders import xmlfeedspider crawler.items import refitem, picitem crawler.seloger_helper import urlbuilder scrapy.http import request class seloger_spider_xml(xmlfeedspider): name = 'seloger_spider_xml' allowed_domains = ['seloger.com'] iterator = 'iternodes' # unnecessary, since it's default value itertag = 'annonce' '&#

VB6 Quotes appearing whenever you open the app -

i have vb6 program saves text in text box file, , when open again, same text there, whenever re-open textbox text has quotes around it, how might remove quotes? code is: private sub form_load() on error goto nofile randomize dim sfile string dim blank string dim c1path string dim ifilenum integer sfile = "c:\jpldata" ifilenum = freefile open sfile input ifilenum line input #ifilenum, c1path close #ifilenum text1.text = c1path nofile: if err.number = 5 sfile = "c:\jpldata" c1path = "no custom defined." ifilenum = freefile open sfile output ifilenum write #ifilenum, text1.text close #ifilenum end if end sub private sub form_queryunload(cancel integer, unloadmode integer) dim sfile string dim cname string dim ifilenum integer sfile = "c:\jpldata" cname = vbclrf & text1.text & vbclrf ifilenum = freefile open sfile output ifilenum write #ifilenum, cname close #ifilenum end sub edit: i've answered own problem, spelled vb

html - bootstrap 3 - crop image to fit width & height -

i'm using span, i'm filling background make sure images same size in browsers. while have no complaints this, i'm missing opportunity use alt tag , potential seo advantage might carry. is there way crop image using html+css (no js) using img tag? if seo image important perhaps can include image relevant alt, style="display: none". crawlers may smart enough rule out though..!

php - How can I add checkbox in the drop down? -

i trying add check box in drop down, don't know how achieve this. below code used define check-boxes: <html> <head> <title>scrolling checkboxes</title> <script type="text/javascript"> </script> </head> <body> <div id="scrollcb" style="height:150;width:200px;overflow:auto"> <input type="checkbox" id="scb1" name="scb1" value="1">0-1 hours<br> <input type="checkbox" id="scb2" name="scb2" value="2">1-2 hours<br> <input type="checkbox" id="scb3" name="scb3" value="3">2-3 hours<br> <input type="checkbox" id="scb4" name="scb4" value="4">3-4 hours<br> <input type="checkbox&qu

jquery - Passing parameters to callbacks JavaScript -

i callback function fire after click event. have javascript $('#btnsubmit').click(function () { $('#testdiv').hide('slow', oncomplete('test')); }); var oncomplete = function (t) { $('#hiddendiv').hide(); alert(t); } the callback function supposed fired after hiding of #testdiv . however, oncomplete function fires first. if remove parameters on oncomplete , give reference , not invoke it, function fires @ right time, can't pass parameters it. how can pass parameters oncomplete , not have fire before div finished hiding? fiddle here you have have anonymous function there wrapping oncomplete() : $('#btnsubmit').click(function () { $('#testdiv').hide('slow', function () { oncomplete('test') }); }); demo here in jquery docs: complete type: function() f

java - Android LocationManager, rough data and battery consumption -

i need rough data location on android, when getting main consideration keep battery power. consider code: locationmanager locationmanager = (locationmanager) getsystemservice(context.location_service); locationmanager.requestlocationupdates(locationmanager.network_provider, 10 * 60 * 1000, 1000, this); is right strategy? or better check, every 10 minutes new location , disable listener, seems closer code proposed on google's site, though less logical me? instead of mentioning provider name use criteria get provider. and, use criteria set requirement. criteria criteria = new criteria(); criteria.setaccuracy(criteria.accuracy_fine); criteria.setaltituderequired(false); criteria.setbearingrequired(false); criteria.setcostallowed(true); criteria.setpowerrequirement(criteria.power_low); final string bestprovider = manager.getbestprovider(criteria, true); and finally, locationmanager.requestlocationupdates(bestprovider, 0,1000, this); alternatively can r

Python matching n-grams from a dictionary to a string of text -

i have dictionary of 2 , 3 word phrases want search in rss feeds match. grab rss feeds, process them , end string in list entitled "documents". want check dictionary below , if of phrases in dictionary match part of string of text want return values key. not sure best way approach problem. suggestions appreciated. ngramlist = {"cash outflows":-1, "pull out":-1,"winding down":-1,"most traded":-1,"steep gains":-1,"military strike":-1, "resumed operations":+1,"state aid":+1,"bail out":-1,"cut costs":-1,"alleged violations":-1,"under perform":-1,"more expected":+1, "pay more taxes":-1,"not sale":+1,"struck deal":+1,"cash flow problems":-2} i'm assuming numbers (-2, -1, +1) in dictionary weights need count each phrase in each document make them useful. so pseudocode : spl

java - Check file, always return true -

i tried code below , if rename music-file musik_stk100.mp3 if still returns true? what doing wrong? string filepath = "file:///mnt/sdcard/data/musikapp/"; final file musicfile = new file(filepath + "/" + "musik_stk100.mp3"); final imageview imagetrue = (imageview) findviewbyid(r.id.imagetrue); final imageview imagefalse = (imageview) findviewbyid(r.id.imagefalse); if (musicfile.exists()){ imagetrue .setvisibility(view.visible); imagefalse .setvisibility(view.gone); } else { imagefalse .setvisibility(view.visible); imagetrue .setvisibility(view.gone); } solution string filepath = (environment.getexternalstoragedirectory() + "/data/musikapp/"); final file musicfile = new file(filepath + "musik_stk100.mp3"); final imageview imagetrue = (imageview) findviewbyid(r.id.imagetrue); final imageview imagefalse = (imageview) findviewbyid(r.id.imagefalse); if (musicfile.exists()){

c# - Getting a foreign key in a table -

in website, user can add foreignexpressions account. user model looks this: [table("userprofile")] public class userprofile { [key] [databasegeneratedattribute(databasegeneratedoption.identity)] public int userid { get; set; } public string username { get; set; } public list<foreignexpression> learnedexpressions { get; set; } } then in controller i'd current user's stored expressions this: db.foreignexpressions.select(f => f.userid == membership.getuser().provideruserkey); however, foreignexpression not contain userid field, there's no visible userid f. userprofile has collecion of foreignexpressions, have userid field in foreignexpression table. i'm confused, how supposed foreignexpressions user? edit: public class foreignexpression { public int id { get; set; } public string expression { get; set; } public string context { get; set; } public string meaning { get; set; } public datet

python - SQL query for merging timestamps -

i have data in postgres table in following form: col1 col2 col3 col4 id1 b c id2 id1 timebegin 1###-##-## id2 id1 timeend 22##-##-## id3 id4 id5 id6 id6 id3 timebegin 2##-##-## id7 id3 timeend 200-3-## id13 id8 id14 id15 id8 id9 timebegin -2-1-1 id10 id11 id12 id13 here 1###-##-## imply uncertainty in time (1000-01-01 1999-12-31) and 22##-##-## imply uncertainty in time (2200-01-01 2200-12-31) and 2##-##-## imply uncertainty in time (200-01-01 200-12-31) and 200-3-## imply uncertainity in time (200-3-01 200-3-31) and 20-3-## imply uncertainty in time (20-3-01 20-3-31) and 200-3-## imply uncertainty in time (200-3-01 200-3-31) and -200-3-## imply uncertainty in time (-200-3-31 -200-3-01) now want merge 3 rows col1==col2 1 of following form: col1 col2 col3 col4

html - Double quote escaping with Javascript function -

json.stringify escapes double quotes. there input such following code (without modification) not result in escape of double quotes? <script> function test(s) { document.write(json.stringify(s)); } </script> <form action="" method="post" onsubmit="test(this.cmd.value); return false;"> <input class="command" type="text" id="cmdbox" name="cmd" /> </form> example input/output: "test" expected: "test" actual: \"test\" use unescape escaped string expected result. unescape(json.stringify(data))

html - Regex - match table tag by its ID fragment -

i didn't got wrong. aplication's running .net 3.5. there no parsers working 3.5, swear. i'm trying fetch table tag, has keyword fragment within id. i tried using regex "<table.*ctl01.*>.*</table>" some listing: <table class="default_gridclass" cellspacing="0" rules="all" border="1" id="ctl00_contentplaceholder1_customerbylocation_viewpanelstandalone_viewpanel_grid_ctl01"> this table tag located inside 2 parent's table tags. actually, parent tables contain no "ctl01" fragment in id. but, using regex 3 tables instead of one

javascript - Using CSS Values in a D3 Transition -

i'd make d3 transition style defined in css. can transition style value explicitly apply in code. but, i'd target values of animation defined in style sheet. here's example of red div transitions blue one: <html> <head> <script src="http://d3js.org/d3.v3.js"></script> <style> div { background: red } </style> </head> <body> <div>hello there</div> <script> d3.select('body div') .transition() .duration(5000) .style("background", "cornflowerblue"); </script> </body> </html> and here's (incorrect) attempt @ "storing" these values in css: <html> <head> <script src="http://d3js.org/d3.v3.js"></script> <

objective c - UIImageView won't animate with UIImages of CGImage -

i have uiimageview trying make animation of set of uiimages created flipping other uiimages. here's code: turtle = [[uiimageview alloc] initwithframe:cgrectmake(self.view.frame.size.width-200, self.view.frame.size.height - sand.frame.size.height - turtle.frame.size.height - 10 - heightofkeyboard, 100,100)]; [flippedturtlearray addobject:[uiimage imagewithcgimage:[uiimage imagenamed:@"turtle1.png"].cgimage scale:1 orientation:uiimageorientationdownmirrored]]; [flippedturtlearray addobject:[uiimage imagewithcgimage:[uiimage imagenamed:@"turtle2.png"].cgimage scale:1 orientation:uiimageorientationdownmirrored]]; [flippedturtlearray addobject:[uiimage imagewithcgimage:[uiimage imagenamed:@"turtle3.png"].cgimage scale:1 orientation:uiimageorientationdownmirrored]]; [flippedturtlearray addobject:[uiimage imagewith

ios - When subclassing RKObjectRequestOperation to check for errors, how to retry the failed operation? -

i have subclassed rkmanagedobjectrequestoperation , overriding following method, - (void)setcompletionblockwithsuccess:(void ( ^ ) ( rkobjectrequestoperation *operation , rkmappingresult *mappingresult ))success failure:(void ( ^ ) ( rkobjectrequestoperation *operation , nserror *error ))failure { [super setcompletionblockwithsuccess:^void(rkobjectrequestoperation *operation , rkmappingresult *mappingresult) { if (success) { success(operation, mappingresult); } }failure:^void(rkobjectrequestoperation *operation , nserror *error) { nsinteger statuscode = operation.httprequestoperation.response.statuscode; switch (statuscode) { case 401: // not authenticated { myerror* errorresponse = (myerror*)[[error.userinfo objectforkey:@"rkobjectmappererrorobjectskey"] firstobject]; if(errorresponse && [errorresponse.oauth2errorcode isequaltostring:@"invali

perl - Auto-increment integers for POD items -

would know of way dynamically increment integer item titles? avoid having change every step number in event new step need added/removed somewhere in middle of ton of steps. below small three-step procedure give rough idea of template structure: =step_wash 1. wash <p>add washing steps here</p> =cut # throw perl code here wash stuff =step_dry 2. dry <p>add drying steps here</p> =cut # throw perl code here dry things =step_fold 3. fold <p>add folding steps here</p> =cut # fold of things perl! disregarding item names , structure of this, goal try , eliminate use of statically numbering title of each item. wondering if there possible way generate integer increments; pretty replacing 1, 2, 3, etc { print $i++ } instead.. in pod. pod pretty plain , doesn't sort of thing. an extension of pod called pseudopod in theory (see https://metacpan.org/pod/distribution/pod-pseudopod/lib/pod/pseudopod/tutorial.pod#lists ) when trie

java - Change JTable row foreground -

i trying color red, foreground when time around condition, painting foreground of rows(should seven).what doing wrong?code below: class redrenderer extends defaulttablecellrenderer{ @override public component gettablecellrenderercomponent(jtable table, object value,boolean isselected, boolean hasfocus, int row, int column) { super.gettablecellrenderercomponent(table, value, isselected, hasfocus, row, column); bigdecimal time=new bigdecimal(jtable.getmodel().getvalueat(row, 17).tostring()); if(time.compareto(new bigdecimal(2))<=0){ setforeground(color.red); setbackground(color.white); }else{ setbackground(null); } return this; } } have tried explicitly setting foreground color different if current row doesn't match criteria?

html - how to hover the whole element no matter what -

i have structure html: <span class='something'> <a href="" title="description"> <img src="/assets/no-image.png" alt="description" title="description" /> <div class="info"> <div class="title">title</div> <div class="subtitle">subtitle</div> </div> </a> </span> and css: .something { display: block; div.info { display: none; } a:hover { display: block; width: 150px; height: 150px; background: green; img:hover { filter: alpha(opacity = 30); opacity: .30; } div.title, div.subtitle { display: block; } div.info { display: block; position: relative; margin-top: -145px; } } } when move cursor on <span class="something"> element, whole area overlayed green color. that's good. problem is,

CSS animation with different transition off :hover -

i'm working css animations i'm trying div bounce out when hovered on (change opacity: 0; 1). however, when mouse hovers want fade opacity original value of 0. far have: @-webkit-keyframes bouncey { 0% { opacity:0; -webkit-transform: scale(1); } 50% { opacity: 1; -webkit-transform: scale(1.1); } 100% { -webkit-transform: scale(1); } } .box { width: 200px; height: 200px; background: red; opacity: 0; } .box:hover { opacity: 1; -webkit-animation: bouncey 1s ease-in-out; } http://jsfiddle.net/xhuuq/ this applies bounce out animation when hovered over, i'm unsure how make div fade 0 on mouseleave. add -webkit-transition: opacity 1s; somewhere help? i prefer css / non js/jquery solution if it's possible. http://jsfiddle.net/xhuuq/7/ .box{ -webkit-transition: opacity 0.5s ease-in-out; } .box:hover { -webkit-transition: none; } transition happens on blur

output - Prevent the zero before the decimal from being displayed in C++ -

in c++, i'm using following statements display output: // example float x = 0.66004; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << x; my output looks like 0.66 how can prevent 0 before decimal being displayed? want: .66 std::string foo = std::to_string(0.553); std::size_t = foo.find("."); if (it != std::string::npos) { std::cout<<foo.erase(0, it); }

binary search tree - BST insertion with C++ -

i created function insert data bst , works fine. used "pass reference" , value of "head" supposed change after each insertion. however, found "head" pointing first value inserted. here explain causes "head" point first data inserted? void insert(node *&head, int val){ if(head == null){ head = newnode(val); } else{ if(val <head->data) insert(head->left,val); else insert(head->right,val); } } that how function should work, head should never change or lose track of tree root. as long have head pointing @ root, have access whole tree. the reason why value not changing is, when writing insert(head->left,val); you not assigning new value head , passing reference left child next function call.

ios7 - Slow down UISnapBehavior -

i using uisnapbehavior snapping liking. there way slow down? or in other words: there way adjust elasticity of object point should snap to? i able solve attaching view uidynamicitembehavior , setting resistance property. uidynamicitembehavior *dynamicitembehavior = [[uidynamicitembehavior alloc] initwithitems:@[ view ]]; dynamicitembehavior.resistance = 100; [animator addbehavior:dynamicitembehavior];

Globally change value in MySQL -

i have following "problem". have mysql db, has around 200k records. in 1 of columns have number (decimal). globally add particular value values in column. for example if there 1000, change lets 1005, 1002 change 1007 etc. etc. one way downloading whole db, open in excel, there, save cvs , upload new db, quite time consuming , maybe overcomplicated, thought if there way of doing using sql command directly in phpbb. update mytable set columnname=columnname+5

html - Bootstrap footer rotate issue -

i creating mobile app using html/css/js bootstrap , phonegap build. in app have footer on pages 3 navigation buttons. problem when rotate device portrait landscape, buttons not resize take full width supposed to. however, if click 1 of nav buttons after rotating, new page loads show buttons @ full width. rotating once again portrait, has buttons taking way space. i utilizing <div class="btn-group btn-group-justified"> documentation states. my footer html follows: <nav id="footer" class="navbar-fixed-bottom col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3 col-lg-4 col-lg-offset-4" role="navigation" style="padding: 0 0;"> <div id="footergroup" class="btn-group btn-group-justified"> <a type="button" class="btn btn-default active" href="#"><span class="glyphicon glyphicon-home"></span> home</a> &

python - HTML page vastly different when using a headless webkit implementation using PyQT -

i under impression using headless browser implementation of webkit using pyqt automatically me html code each url heavy js code in it. seeing partially. comparing page when save page firefox window. i using following code - class jabbawebkit(qwebpage): # 'html' class variable def __init__(self, url, wait, app, parent=none): super(jabbawebkit, self).__init__(parent) jabbawebkit.html = '' if wait: qtimer.singleshot(wait * sec, app.quit) else: self.loadfinished.connect(app.quit) self.mainframe().load(qurl(url)) def save(self): jabbawebkit.html = self.mainframe().tohtml() def useragentforurl(self, url): return user_agent def get_page(url, wait=none): # here trick how call several times app = qapplication.instance() # checks if qapplication exists if not app: # create qapplication if doesnt exist app = qapplication(sys.argv)

python - Catching Errors in MySQLdb Library -

to prevent connections being left open on server - here's i'm doing close mysqldb's cursor , connection, re-raise error: import mysqldb conn = mysqldb.connect(user="username", passwd="secret", db="database", charset='utf8') cur = conn.cursor() try: cur.execute("insert testtable (userid) values(%s);" % id) conn.commit() except: cur.close() conn.close() raise finally: print "insert successful" is there better way this? note: know keyword might better, haven't found documentation saying mysqldb supports keyword close connection automatically. check out tutorial cited: #!/usr/bin/python # -*- coding: utf-8 -*- import mysqldb mdb con = mdb.connect('localhost', 'testuser', 'test623', 'testdb'); con: cur = con.cursor() cur.execute("drop table if exists writers") cur.execute("create table writers(id int primar

jquery - Creating items via ajax force rails to create additional items in DB -

i using foundation , rails (i dont know why, think problem in foundation). when create new comment article, on first article have 1 comment per click, have be, if go article - creates 2 similar comments, go article , 4 comments, 7 , on. think problem in foundation, because render errors in browser: uncaught error: jquery-ujs has been loaded! and object [object object] has no method 'foundation' tell me please how can solve problem my model: class comment include mongoid::document include mongoid::timestamps belongs_to :commentable, polymorphic: true has_many :answers, as: :commentable, class_name: "comment" default_scope queryable.order_by(:created_at.asc) field :body, type: string validates_presence_of :body end my controller action: def create @comment = @commentable.comments.new(params_comment) if @comment.save flash.now[:notice] = "..." @response = {comment: @comment, model: @commentable} respond_with(@comment)

android - App with Google Map crashes when I extend FragmentActivity -

i know question has been asked many times here, none of solutions provided stopped app crashing. here code mainactivity: package com.example.gpstracking2; import android.os.bundle; import android.app.activity; import android.view.menu; import android.app.dialog; import android.os.bundle; import android.support.v4.app.fragmentactivity; import com.google.android.gms.common.connectionresult; import com.google.android.gms.common.googleplayservicesutil; import com.google.android.gms.maps.googlemap; import com.google.android.gms.maps.supportmapfragment; import com.google.android.gms.maps.model.marker; public class mainactivity extends fragmentactivity { googlemap googlemap; marker marker = null; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); } @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().i

C++ Checking String -

say taking string in , want check whether or not has capital letter in string. input string file. how go breaking down check see if has uppercase value using ascii values? thanks! you can use c++ algorithm library find if string contains uppercase value in using predicate (using wrapper version of std::isupper): #include <algorithm> #include <iostream> #include <string> #include <cctype> bool isupper (char c) { return std::isupper(c); } bool hasuppercase (std::string str) { std::string::iterator = std::find_if(str.begin(), str.end(), isupper); if (it != str.end()) { return true; } else { return false; } } int main() { std::string s = "this contains uppercase character in it..."; if (hasuppercase(s)) { std::cout << "string s contains least 1 uppercase character." << std::endl; } else { std::cout << "string s not contain uppercase c

c++ - How can I read a file with lines of different number of numbers -

i trying read in file of data, approx 2000 lines, file looks like 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.0 2.1 2.2 2.3 2.4 2.5 there blank (white space) , 1.3/1.7 in same column the way have setup storing vector of structs where struct num { double d1, d2, d3, d4, d5; }; what trying achieve is num a; vector<num> data (int = 0; < 4; i++) { file >> a.d1 >> a.d2 >> a.d3 >> a.d4 >> a.d5; data.push_back(a); } and find logic recognize blank space in second line , store d1=1.6, d2=0, d3=1.7 etc.. , third line d1=2.0 , d2,d3,d4,d5=0 confused on how test/get logic implementing this, if possible in c++ vs2010 after looking @ first answer thought should provide more info, each line in file belongs satellite, , each number represents observation on specific wavelength, if blank means has no observations on wavelength. so elaborate, first line represents satellite 1 has observation on 5 wavelengths, line 2 reprsents satelit

iphone - ios determine how an app is launched -

is there way determine "how" app launched or made active (i.e. homescreen tap, 4 finger swipe, siri, etc...)? there's thread similar ( determining whether ios application launched via siri ), not many answers in this. there's mac osx ( how can mac app determine method used launch it? ) need similar ios. i've skimmed through ( https://developer.apple.com/library/ios/documentation/iphone/conceptual/iphoneosprogrammingguide/managingyourapplicationsflow/managingyourapplicationsflow.html#//apple_ref/doc/uid/tp40007072-ch4-sw3 ) though coudn't find recognizes "how" app launched. thanks in advance. you can figure out app launched url in application using appdelegate method: - (bool)application:(uiapplication *)application openurl:(nsurl *)url sourceapplication:(nsstring *)sourceapplication annotation:(id)annotation { } additionally, application:didfinishlaunchingwithoptions: has options, keys can find here te

perl - formatting output data to an excel file -

this program gets numeric values web each of values in @values array want these values printed out in table looks like il9 il8 il7 2012 v1 b1 2011 v2 b2 2010 v3 b3 . . 2000 v12 b12 where v1 .. v12 values first variable in @values etc. here program please me structure it. there escape character take me first line of program in perl thanks #!/usr/bin/perl -w use strict; use lwp::useragent; use uri; $browser = lwp::useragent->new; $browser->timeout(10); $browser->env_proxy; open(out, ">out"); $i = 2013; while ($i-- > 2000){print out "$i\n"} $a = 2013 ; $base = 'http://webtools.mf.uni-lj.si/public/summarisenumbers.php'; @values = ('il9', 'il8', 'il6' ); foreach $value (@values) { print out "$value \n" while ($a-- > 2000){ $b = $a + 1; $c = $b + 1; $query = '?query=('.$value.')

java - Multiple Threads spawning multiple threads and how to wait for child Threads -

i have 2 arrays abc[100] , def[1000] , have find array xyz[100] , xyz[i] = mindistance(abc[i],def) i.e every element in abc have find corresponding nearest element in def , set in xyz. for using threads @ 2 level . @ first level creating threads every 10 points in abc , @ second level each creating child threads every 100 points in def. below implementation . my questions how can wait child threads of abc (i.e def threads) . have gone through java join method not able figure out on how use . can use cyclic barrier in case. the actual data in magnitude 1000s abc , 10000 def , haven't used threads before ,so there issues can happen implementation . have seen use of threadpoolexecutor instead of fixedthreads in examples couldnt figure out how threadpoolexecutor have. 1. distancecalculation public class mindistancecalculation { public static list<double[]> xyz = new vector<double[]>(); public void method1(){ double[][] ab