Posts

Showing posts from February, 2010

ruby - Is there a one liner or more efficient way to get this done? -

given hash, example: hash = { "fish" => 2, "cat" => 3, "dog" => 1 } i need get: a comma separated string values, e.g. "2,3,1" an integer hold total sum of values, e.g. 6 my current code: value_string = hash.map { |k,v| "#{v}"}.join(',') sum = 0 hash.map { |k,v| sum += v} you can this: hash.values.join(",") # => "2,3,1" hash.values.inject(:+) # => 6

javascript - Display image then replace uploaded image -

i want upload images, (but first) click on image(input button upload images) display button replace new image on button images. function displayuploadimages dosen't work if change " class " " id " codes work. here codes : <div class="detail_left"> <div class="take"> <div class="image-upload" onclick="displayuploadimages()"> <label for="file-input"> <div class="takes backgrounds"></div> </label> </div> <img class="uploaded" src="#" alt=""> </div> <input id="file-input" class="" type="file" onchange="readurl(this);"/> <script type="text/javascript">function readurl(input) { if (input.files && input.files[0]) { var reader = new filereader(); reader.onloa...

connecting 2 simple point layers in neo4j spatial -

how connect 2 point layers in neo4j? don't want of points located in 1 simple point layer. let's have 2 point layers, layer 1 - road network (upper ny) layer 2 - road network b (lower ny) so in neo4j spatial, these 2 separated layers, each have own r tree index, etc. so, how have relationship between these 2 layers? what mean 'connecting 2 point layers'? kind of connection? if you, example, add same point 2 layers, 2 layers connected (by point). second sentence seems imply opposite points in 1 layer , in another. add 1 , add others other. perhaps if tell more actual case, can advise better.

c# - Get And Set Session In Web Service -

Image
i have web service handle login , logout , in web service set session value , session.in log in [webmethod(enablesession = true)] public object loginbyemail(string email, string password, int regionid) { try { guid? userid = null; int? res = tbll.loginbyemail(ref userid, email, password, regionid); if (res == 1) return new { result = resultenum.notcorrectemailorpassword }; else if (res == 2) { session["user"] = userid; return new { result = resultenum.ok, userid = userid }; } else if (res == 3) return new { result = resultenum.accountnotactive }; else return new { result = resultenum.error }; } catch { return new { result = resultenum.error }; } } when go definition in session ( session["user"] = user...

How to sum hours based on criteria in to tables (Excel) -

having "tables" excel b c d e f 1 category project hours 2 project c1 c2 p1 10 3 p1 x p2 20 4 p2 x p3 30 5 p3 x x 6 p4 x a2:c6 shows list of project. each project belongs 1 og more categories e2:f4 shows time spent on each project i'm looking way sum time spent in each category. answer obvious (40h , 50h), can't figure out how construct working formula, provide answer h 1 category sum hours 2 c1 40 3 c2 50 any ideas ? this simple application of sumif . can enter =sumif(b3:b6;"x";$f2:$f5) in i2 , modify accordingly other category. if apply formulae next 1 instead of below 1 another, can copy formula across. i recommend change sheet in following way: b c d e f 1 ...

css - can we set different border-image for every side of div? -

i trying make div picture frame design using border-image property. frame.jpg left side frame image. can 1 suggest me how can apply right side? i not interested using javascript handle it.. css3 solution please... while might think browser assume "take image , tile way around" you'd wrong. border-image way more versatile , provides kinds of ways slice , dice same image different results. assumptions css3 border-image property makes image provide not intuitive! start reading article excellent explanation of each individual property of border-image: css-tricks: border-image . .mydiv { padding: 20px 38px; border-image-source: url(http://i.stack.imgur.com/lr2x0.jpg); border-image-width: auto; border-image-repeat: repeat; } <div class="mydiv"> <h1> headline: breaking news! </h1> </div> until have feel property, i'd suggest setting each part individually (instead of using omnibus sh...

python - Coverting list of Coordinates to list of tuples -

i'm trying covert list of coordinates list of tuples: from: a_list = ['56,78','72,67','55,66'] to: list_of_tuples = [(56,78),(72,67),(55,66)] i've tried doing for, in loop convert each element in a_list tuple output in form: list_of_tuples = [('5', '6', '7', '8'), ('7', '2', '6', '7'), ('5', '5', '6', '6')] any on doing wrong here appreciated. edit: fixed expected output, no spaces between coordinates , tuples. you can use list comprehension: result = [tuple(map(int,element.split(','))) element in a_list] edit: shorter version @lol4t0 as mentioned spaces between elements come printing list. there no actual "spaces" in data structure. however, if wish print list without spaces can do: print str(result).replace(" ","")

linuxmint - Julia - workspace() -

i've been using win7 develop in julia, , i've got method called loadall() runs include(x) on relevant files (i'm simultaneously working on bunch of scripts , cant bothered write full path every specific file update when try running method using linux mint computer returns error "error: invalid redefinition of constant model", model type i've re-written on win7 machine i attempted work around adding workspace() (crude, know) returned "error: workspace not defined" additionally, if exclude script loads model type (and other types) error "error: @doc not defined" i have posted in julia forum seems possibly might have os rather julia language itself, i'm sure if stuff workspace() , @doc malfunctioning been solved has had experience might understand problem is? appreciated, prefer able use linux instead of windows edit: further removing stuff, removed @doc occurrences, , error came along "error: abstractstring not def...

Why the mongodb database take more space after removing documents -

before remove data, database takes 25.5g space, has 413562171 documents. then execute following operating: db.collectionname.remove( { xxx: "xxx" } ) this operating deletes 165540416 documents , database takes 25.8g. i confused why takes more space after removing data. when remove documents, mongodb doesn't free space automatically (it supposes space can reused new documents) you can free space using repairdatabase command: db.repairdatabase() mongo shell; or mongod --repair (mongod should not running when use way) https://docs.mongodb.com/v3.2/reference/command/repairdatabase/ please, take account repairdatabase requires free disk space equal size of current data set plus 2 gigabytes, , obtains global write lock, block other operations until has completed little addition: if use wiredtiger storage engine can use compact command instead repairdatabase https://docs.mongodb.com/manual/reference/command/compact/ the wiredtiger storage eng...

ORACLE APEX 5.0 Region Source query with html -

the query works in apex 4.2 in 5.0 receive error message in line 1 query cannot parsed within builder. if believe query syntactically correct, check ''generic columns'' checkbox below region source proceed without parsing. ora-00919: invalid function select '<a href="f? p='||&app_id.||':203:'||&session.||'::::p203_ano,p203_id_prj:'||ano||',3">'|| ano||'</a>' ano, 1 id_prj, to_char(muni) "muni", to_char("inscritos",'999g999g999g999g999g999g990') "inscritos", to_char("instituições",'999g999g999g999g999g999g990') "instituições", to_char("turmas",'999g999g999g999g999g999g990') "turmas", to_char("beneficiários",'999g999g999g999g999g999g990') "beneficiários" , to_char("participantes",'999g999g999g999g999g999g990') "participantes" v_most...

c++ - What does "(GameState *) new PlayingState()" do? -

the line (gamestate *) new playingstate() does not make sense me. since gamestate* pointer class , new operator employed shows playingstate() object "newed" class. questions come @ end of post first definition of respective classes: class gamestate { public: virtual void onstart(statebasedgame &game) = 0; }; class playingstate : public gamestate, public eventsubscriber<sf::event> { public: playingstate(); void onstart(statebasedgame &game); }; my questions: 1.is casting between classes? can cast classes in c++ casting data types in c? thought c++ more "formal" , "redundant"? 2.why want that? what's point of such conversion, can author achieve? i'm guessing has constructor. 3.to new something, shouldn't go format?: <class_type> <new_class_name> = new <class_type_name> as in gamestate gamestate = new playerstate; apparently that's not way? without further con...

vb.net - Issue toggling caps lock with check box in vb .net -

i've developed application (with vb .net) can toggle caps lock state clicking on check box. i've coded program in such way when click on checkbox, if gets checked caps lock must turned on , when unchecked must turn off. below codes. public class form1 private declare sub keybd_event lib "user32" (byval bvk byte, byval bscan byte, byval dwflags integer, byval dwextrainfo integer) private const vk_capital integer = &h14 private const vk_scroll integer = &h91 private const vk_numlock integer = &h90 private const keyeventf_extendedkey integer = &h1 private const keyeventf_keyup integer = &h2 private sub checkbutton_caps_checkedchanged(sender object, e eventargs) handles checkbutton_caps.checkstatechanged if checkbutton_caps.checked = true call keybd_event(vk_capital, &h45, keyeventf_extendedkey or 0, 0) checkbutton_caps.image = image.fromfile("resources\btn_ico_caps_on.png") elseif checkbutton_caps.chec...

c++ - OS X /usr/bin/sample load address -

i interested in call graph in os x sample(/usr/bin/sample in activity monitor) one day saw phrase " 89147 ??? (in module_name) load address 0x10ce70000 + 0x3cec " "2 ??? (in module_name) load address 0x115b78000 + 0x5ff899 [0x116177899]" (that example) i focus function name, "???", , "???"s use "load address" "load address"? mean assembly? so find "vm_read", doesn't matter, function or instruction get, "???", "load address" please give me key word. i find many call graph can see "??? function , load address" call graph: 89147 thread_568659 dispatchqueue_1: com.apple.main-thread (serial) + 89147 start (in vboxnetnat) + 52 [0x10ce72134] + 89147 ??? (in vboxnetnat) load address 0x10ce70000 + 0x3cec [0x10ce73cec] + 89147 trustedmain (in vboxnetnat.dylib) + 482 [0x10d5af222] + 89147 ??? (in vboxnetnat.dylib) load address ...

Learn python the hardway ex17, outside the box -

belive me, i've try best print "to_file" after rewriting in vain ! appears "typeerror: coercing unicode: need string or buffer, file found" from sys import argv os.path import exists script, from_file, to_file = argv print "copying %s %s" % (from_file, to_file) # these 2 on 1 line, how? in_file = open(from_file) indata = in_file.read() print "the input file %d bytes long" % len(indata) print "does output file exist? %r" % exists(to_file) print "ready, hit return continue, ctrl-c abort." raw_input() out_file = open(to_file, 'w') out_file.write(indata) print "alright, done." out_file.close() in_file.close() print open(out_file).read()

c# - Adding more directory to user selected directory -

so, of right have start process working private void button3_click(object sender, eventargs e) { processstartinfo startinfo = new processstartinfo(); startinfo.filename = textbox1.text; startinfo.arguments = @"-window -usebe -mod=e:\aaron\addons\"; process.start(startinfo); } but want other users have work them too. in startinfo.arguments have directory e:\aaron... have textbox display directory of user. directory have replace after -mod= tricky part after directory need folder user has in directory. have add \extrafolder directory. in end become startinfo.arguments = @"-window -usebe -mod= //user input directory\@cba_a3"; you want inject user's directory path? this: startinfo.arguments = string.format(@"-window -usebe -mod={0}\@cba_a3", userpathsegment);

ios - Divided operation in Swift -

why error on that? var rotation:float= double(arc4random_uniform(50))/ double(100-0.2) actually try 1 too: var rotation:double= double(arc4random_uniform(50))/ double(100-0.2) thank you swift has strict rules whitespace around operators . divide '/' binary operator . the important rules are: if operator has whitespace around both sides or around neither side, treated binary operator. example, + operator in a+b , + b treated binary operator. if operator has whitespace on left side only, treated prefix unary operator. example, ++ operator in ++b treated prefix unary operator. if operator has whitespace on right side only, treated postfix unary operator. example, ++ operator in a++ b treated postfix unary operator. that means need add space before / or remove space after indicate binary operator: var rotation = double(arc4random_uniform(50)) / (100.0 - 0.2) if want rotation float, should use instead of double: var...

javascript - How to delete elements with react? (Basic React query) -

i'm total newbie react , trying build app react, after many hours of trying, couldn't figure out why elements want delete onclick aren't getting deleted. there 2 similar posts on this, need use independent keys every element. tried that, created different variable , increment after every use. it deletes top element of list. how works - 1) have array stored names channels , , data names , save data array renderall . 2) after filter on how want render them, , render them function rendercards() . renders button if clicked, should delete channel channel array , respective data renderall array 3) have input field can add more channels. what doesn't work - delete button deletes top element instead of element clicked. i have app running without delete functionality var app = react.createclass({ getinitialstate() { return { status: 2 } }, changestatus(i) { this.setstate({ status: }); ...

android - How to start a Google Fit Activity via intent -

i have developed custom android wear watch face soccer referee timer. i'd integrate with google fit. first baby step, want start google fit activity @ same time start timer kickoff of game. in other words, don't want create fit sessions or collect sensor data myself (yet); want save users step of swiping fit activity , starting themselves. it seems should able broadcast intent this, can find no documentation on appropriate format. can point me in right direction?

php - How to add Function on Onclick of a button in an echo? -

here function function addorder($name,$price){ echo $name." price: ".$price; echo "<br>"; alert("function worked"); } and here echo echo "<input type='button'value='add'class='btnadd'onclick=\'addorder("'.$row["name".'","'.$row["price"].'");\'>"; i have tried many solution in stackoverflow, function won't work when click add button ok. clarify things 1 must know when newbie php , javascript. so when hit php, generates output(for consider text). once php execution completes, output text sent browser. @ browser text interpreted html, javascript, , css. functioning trying achieve calling function on click of button, invoke function defined in javascript. so php required generate javascript text include function (javascript method addorder) . the exmple code below make 1 understand how work...

sql - connection string -

i have problem connection string. when using web service server see error: format of initialization string not conform specification starting @ index 114 but in local host don't have problem. , connection string is: name="db_nodeentities1" connectionstring="metadata=res://*/models.node.csdl|res://*/models.node.ssdl|res://*/models.node.msl; provider=system.data.sqlclient; provider connection string=&quot; data source=xx.xxx.xxx.xx,1433; initial catalog=my db name; integrated security=true; multipleactiveresultsets=true; app=entityframework&quot; user id=my id; password=my pass" providername="system.data.entityclient" i think it's related server security policy. example sql server doesn't allows remote access , should connect locally. maybe happened this. in such case hosting service , database engine should on same server contact server administrator. let me know when exception occurred, happens when run...

admob - Clicking on ads on your own app -

it says in admob policies , guidelines: it against admob policy click on own live ads. during development , testing, use test ads. if need render live ads before launch, avoid clicking on them. if click on live ads, admob account may suspended. does mean under no circumstance not allowed click on ads on app? i´m not allowed click on them when testing app. if download app app store, , see ad looks interesting, not allowed click on it? absolutely. avoid clicking on admob ads otherwise end suspended account , loose hard earned money in admob account. not friends or families click on admob ads. google track ip address, cookies, area clicks comings, frequencies of click per thousand impression , on. have rocket science not try this. by mistake if click ads 4-5 times in month totally fine. take serious action when ads click/views ratio high.

jquery - Post data from form without knowing how long the form will be -

i need post form data using jquery , field input values needs posted in json format. problem form fields comprise of fields there like: first name, last name , email, fields after of number because form constructed request. this: var firstname = $('input[name="firstname"]').val(); var lastname = $('input[name="lastname"]').val(); var email = $('input[name="email"]').val(); data: json.stringify({ "firstname": firstname, "lastname": lastname, "email": email }) however wont work remaining fields. ideally need each function or loop through these other questions , put loop json.stringify have no idea how that. might why don't use: $('form').serialize(); to form data problem json needs in following format { "firstname": "string", "lastname": "string", "email": "string", "responses": [ { ...

javascript - Django: django-autocomplete-light does not work properly -

i'm using django-autocomplete-light in django 1.8. don't know how use in forms.py . instead of autocomplete field see select field. followed instructions here . in models.py have: class icd_10(models.model): id = models.integerfield(unique=true,primary_key=true,null=false,blank=false) icd_10_desc = models.charfield('icd-10 description',max_length=80,null=true,blank=true) icd_10_code = models.charfield('icd-10 code',max_length=10,null=true,blank=true) def __str__(self): return str(self.icd_10_desc) class diagnosis(models.model): diagnosis_option = models.manytomanyfield(diagnosisoption) record_of_genotype = models.charfield(max_length=45,null=true,blank=true) icd_10_desc = models.manytomanyfield(icd_10) patient = models.foreignkey(demographic) def __str__(self): return str(self.patient) in settings.py have: installed_apps = ( 'dal', 'dal_select2', 'django.contr...

powershell - Right Click context - Search folder .txt & .log files -

still new powershell , have been creating automation scripts, checks , balances , can think of make our jobs easier day day. contract working on extremely tight when comes applications , forbids opensource\freeware applications. have been working on using powershell job. here have far: 1. created hkcr\directory\shell\powershell (default) reg_sz search folder text & log files 2. created hkcr\directory\shell\powershell\command (default) reg_sz c:\\windows\\system32\\windowspowershell\\v1.0\\powershell.exe -file c:\temp\rightclicksearch.ps1 -noexit -command set-location -literalpath '%l' i able right click launch , script opens , prompts me keyword search. problem is, can't seem figure out how pass location script properly. rightclicksearch.ps1 (i know $path isn't set, before hardcoded , know have pass variable menu) $promt = (read-host -prompt "enter search keyword") get-childitem -path $path -include *.txt, *.log -recurse | select-string -pa...

javascript - Firebase: During testing I get "undefined is not a function" -

this used code: var cred = firebase.auth().emailauthprovider($scope.data.mail, $scope.data.pwd); firebase.auth().signinwithcredential(cred) .then(function() during testing, following error: typeerror: undefined not function (evaluating 'firebase.auth().emailauthprovider($scope.data.mail, $scope.data.pwd)') so what's wrong code? how can fix problem? to log user in via email/pass call signinwithemailandpassword method. firebase.auth().signinwithemailandpassword(email, password).catch(function(error) { // handle errors here. var errorcode = error.code; var errormessage = error.message; // ... }); then can listen realtime auth event: firebase.auth().onauthstatechanged(function(user) { if (user !== null) { console.log('logged in!'); } }); check docs here more on email login. check api reference onauthstatechanged more info.

Find string using regex javascript -

Image
i want find string ,whose last character may or may not present "abc,efg,asd" "abc,asd,efg" so, have find asd or without " , " description [,"](asd)[,"] this regular expression following: match asd between commas or comma , quote, place value capture group 1 example live demo https://regex101.com/r/mv9va9/1 explanation node explanation ---------------------------------------------------------------------- [,"] character of: ',', '"' ---------------------------------------------------------------------- ( group , capture \1: ---------------------------------------------------------------------- asd 'asd' ---------------------------------------------------------------------- ) end of \1 ---------------------------------------------------------------------- [,...

Jquery Ajax call not loading always -

i have link when clicked pops div , collects data page through ajax call , loads data in div after success. problem this, when pop div , data loads, close div. when click link pop div again , reload data data doesn't load, doesn't sends ajax call shows me previous data loaded in div before close it. want achieve when ever div closed , link clicked again, ajax call sent php page , reloads new data link pops div <a href="javascript:;" onclick="showlikes('<?php echo $id; ?>')">likes</a> . , here ajax call: function showlikes(x){ document.getelementbyid('#likediv').style.display='block'; $.ajax({ type: "get", url: "/get_likes.php?id="+x, beforesend: function(){ document.getelementbyid('#beforesendimg').style.display='block'; }, success: function(data){ document.getelementbyid('#beforesendimg').style.d...

arduino uno - ESP8266 WiFi signal strength -

how use at+cwlap in esp8266 wifi signal strength? want signal strength displayed on serial monitor , use in code in arduino ide! after sending at+cwlap command, esp8266 answer list of available ap's detected. the format of response like: +cwlap:<ecn>,<ssid>,<rssi>,<mac>,<freq offset,<freq calibration> where: <ecn>: indicates security level, 0 (open) 4 (maximum security level) <ssid>: it's ssid of ap <rssi>: it's signal strength, indicated in decibel format (e.g. -70) <mac>: it's mac address <ch>: channel <freq offset>: ut's frequency offset of ap,unit:khz. <freq calibration>: it's calibration frequency offset so, <rssi> parameter interested in. maybe, depending on firmware version of esp8266, it's possible at+cwlap command returns different number of parameters, omitting, example, last four.

matlab - fsolve doesn't work with parametrized function handles -

for example, have defined following function handles: f = @(x, y, z)[x+y+z; x*y*z]; funcc = @(x, y)f(x, y, 0); the call res = fsolve(funcc, [10; 10]); leads error: error using @(x,y)f(x,y,0) not enough input arguments. error in fsolve (line 219) fuser = feval(funfcn{3},x,varargin{:}); caused by: failure in initial user-supplied objective function evaluation. fsolve cannot continue. how can fix it? please re-read requirements objective function in documentation . function must take a single vector input , return vector. you're trying pass 2 scalars. instead: f = @(x, y, z)[x+y+z; x*y*z]; funcc = @(x)f(x(1), x(2), 0); the input objective function should match initial guess, x0 ( [10; 10] ).

html - How to pull out a src value and parse out a ID number with php -

im using wordpress , pass custom field through. data ends looking this, different urls sometimes: $embed = '<iframe width="560" height="315" src="//www.youtube.com/embed/abcde12345" frameborder="0" allowfullscreen></iframe>' i wondering how can pull src value out , how store text bolded below within url. src="//www.youtube.com/embed/ abcde12345 " i did search , saw people recommended using eval() tried reading , couldn't understand documentation. $src = array(); preg_match('(src="//www.youtube.com/embed/(.*?)")e', $embed, $src); echo $src[1];

xslt - XPATH error comparing dates -

i'm trying transformation compare dates using xpath here sample of xml: <?xml version="1.0" encoding="utf-8"?><shop xmlns="http://www.dei.isep.ipp.pt/lprog" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:lprog="http://www.dei.isep.ipp.pt/lprog" xsi:schemalocation="http://www.dei.isep.ipp.pt/lprog traxsd.xsd"> <category nome="fish"> <article id="1" nome="fish1"> <proddate>2018-10-02</proddate> </article> </category > </shop> and here sample of xslt a <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/xsl/transform" version="1.0" xmlns:lprog="http://www.dei.ise...

c# - Finding the tweetID of a tweet in tweetinvi -

i relatively new programming in c# (learning on own school project) , decided try using tweetinvi implement twitter functionality. far it's going good, got authentication , publishing , running, i'm struggling find out how use destroytweet() method. it, , many other methods takes tweetid parameter, can't figure out of how find specific tweet. using following code publish tweet, how can find tweetid of tweet? public itweet publishtweet(string text) { return tweet.publishtweet(text); } // snippet test method in main class. twitter.twitteruser.publishtweet(system.console.readline()); // still working on gui using readline now. it's easy solution, can't figure out! in advance. simple solution. explained before need take tweet publishtweet . string text = "text"; itweet tweet = tweet.publishtweet(text); bool destroysuccess = tweet.destroy();

javascript - How can I let a user choose EITHER one option or many of the other ones? -

i have bunch of options in form user select. way options should work follows: either user selects 'all categories' option. or user can select 1 or more of other options. so want clicking of 'all categories' option remove selection on other options, , want selection of options other 'all categories' unselect 'all categories' option. currently, of these options checkboxes, i'm open changing them. i'm guessing i'll need use sort of jquery/javascript behavior. ideas? just create simple event handler .change() event of checkboxes , set 'checked' property: <html> <form> <p><input type="checkbox" name="option[]" class="selectall"> select all</p> <p><input type="checkbox" name="option[]" class="option"> option 1</p> <p><input type="checkbox" name="option[]" class="o...

javascript - How do I pass parameters into a jQuery.click() function on a <span> tag? -

i have used jquery.click() function in past buttons , have had nothing success, tried use click on <span> , doesn't work. also noticed automatically executed function without listening click. judging how used on buttons, syntax: <p><span id="example">click here</span></p> $("#example").click(examplefunction(p1, p2)); but not seem work. again executes without click taking place. tried: $(document).on("click", "#example", examplefunction(p1, p2)); still no luck, same results. i making weather app , goal toggle temperature between fahrenheit , celsius clicking on unit. made copy of code app on codepen.io here: codepen weather app i appreciate help! looks should try this: $(document).on("click", "#example", function() { console.log('hello world'); }); using function() definition alone give me uncaught syntaxerror: unexpected token ( . what you...

Can't open a Python interpreter in Spyder 2.2.5 (Ubuntu 14.04) -

Image
a few weeks ago, opened spyder , found not interact default python interpreter console, appeared greyed-out (screenshot below). consequently, not able run python scripts within ide. have tried rebooting machine, opening new interpreters , ipython interpreters, result same. tried running spyder --reset in terminal erase settings, did not help. the recent changes python installation made in virtualenv installed python3, not convinced related. i had same issue, after updating packages. solved problem updating spyder: sudo pip install --upgrade spyder

java - Multiple JLables into a single addMouseListener -

i got 3 jlable s, , added functionality l3 of when clicked, set jlabel text value store array (ans.get(0,0)) jlabel l1 = new jlabel("obtener x1"); jlabel l2 = new jlabel("obtener x2"); jlabel l3 = new jlabel("obtener x3"); l3.setbounds(30, 180, 100, 25); l3.addmouselistener(new mouselistener() { @override public void mouseclicked(mouseevent e) { l3.settext("x1 = "+ ans.get(0, 0)); } @override public void mouseentered(mouseevent e) { //mouseentered, mousepressed, mouserelease overriden methods.... the question here is, posible implementent rest of jlabel s ( l1 , l2 ) single addmouselistener (same mouselistener belonging jlabel l3 ) ? create local variable mouselistener , assign instance it. add mouselistener each jlable s. jlabel l1 = new jlabel("obtener x1"); jlabel l2 = new jlabel("obtener x2"); jlabel l3 = new jlabel("obtener x3"); mouselistener ml = new mouselistener(...

python - Scope of warnings.simplefilter('error', Image.DecompressionBombWarning) -

i have following skeleton tornado program: class is(basehandler): @tornado.gen.coroutine def get(self): #render stuff def post(self): try: # load image except runtimewarning: # handle exception class application(tornado.web.application): def __init__(self): # current handlers handlers = [ (r'/',is), ] # settings dict application settings = { "template_path": "templates", "static_path": "static" } tornado.web.application.__init__(self,handlers,debug=true,**settings) if __name__ =='__main__': # right place set warnings? warnings.simplefilter('error', image.decompressionbombwarning) app=application() server=tornado.httpserver.httpserver(app) server.listen(7000) tornado.ioloop.ioloop.current().start() i'm wondering scope of settings warnings is? have set within class? or have set ok?...

c# - Sorting array by item type -

i have array of objects sort type. within array set of objects of 1 type in preferred relative order. after sort, these objects grouped together, no longer in same order. using sort follows array.sort(shapes, getvisualcomparer()); i have looked sort method promises preserve original order, have found nothing. i note have workaround, adds unnecessary confusion code, , not address general problem if comes in future. make copy of original array. then, make comparer compare original indexes of elements if type equal. i don't know on base type sorting, sorting name, this: public class typecomparer : icomparer<type> { public int compare(type x, type y) { int result = stringcomparer.invariantculture.compare(x.name, y.name); if (result == 0) { result = array.indexof(originalarray, x).compareto(array.indexof(originalarray, y)); } return result; } }

regex - find matches for positive and negative number in arithmetic expression -

given following arithmetic expression: -1-5+(-3+2) there need find matches positive , negative numbers. expression expected result is: -1 5 -3 2 i tried use regex -?\d+(.\d+)? returns: -1 -5 -3 2 -5 not correct. is possible build regex pattern positive , negative numbers case , other similar cases ? you can use (?<!\d)[-]?\d*\.?\d+ see regex demo pattern details : (?<!\d) - negative lookbehind fails match if digit appears before tested position [-]? - optional (1 or 0) minus sign \d* - 0+ digits \.? - 1 or 0 dots (a literal dot escaped) \d+ - 1+ digits note \d*\.?\d+ allows .456 values, if not need that, use \d+(?:\.\d+)? . if lookbehind not supported, use capturing group alternation check if - not @ start of string or before digit: (?:^|\d)([-]?\d*\.?\d+) see another demo (the necessary value in group 1).

Java Send custom object via socket Client, Server, LAN -

i want send object (custom class) via socket client server. code: server: private class socketserverthread extends thread { @override public void run() { try { serversocket = new serversocket(socketserverport); while (true) { clientsocket = serversocket.accept(); objectinputstream inobject = new objectinputstream( clientsocket.getinputstream()); try { te xxx = (te) inobject.readobject(); } catch (classnotfoundexception e) { e.printstacktrace(); } //datainputstream datainputstream = new datainputstream( //clientsocket.getinputstream()); //messagefromclient=datainputstream.readutf(); activity.runonuithread(new runnable() { @override public void run() { //activity.msgfromc.settext(messagefrom...

python - jupyter: how to stop execution on errors? -

the common way defensively abort execution in python like: if something_went_wrong: print("error message: goodbye cruel world") exit(1) however, not practice when using jupyter notebook , seems abort kernel entirely, not wanted. there proper/better way in jupyter, besides hack-y inifinte loops? no, exit() not way abort python execution usually. exit() meant stop interpreter status code. usually write script that: if __name__ == '__main__': sys.exit(main()) try not put sys.exit() in middle of code bad practice, , might end non closed filehandle or locked resources. to want, raise exception of right type, , if propagate eval loop, ipython stop notebook execution. plus give useful error messages , stack trace. if type(age) not int: raise typeerror("age must integer") elif age < 0: raise valueerror("sorry can't born in future") else : ... you can inspect stack post-mortem %debug , se...

VMWare SDK C# VirtualMachine Interface Type -

i have code gets virtualmachine network connections , retrieves connected switch information. the code have seems work "virtualethernetcardnetworkbackinginfo" type interfaces, fails when server connected vd switch 1 needs use "virtualethernetcarddistributedvirtualportbackinginfo" type in scenario. question is, how detect interface type before try cast object? or should 1 try cast , see 1 works? this code have i'm looking cleaner... bool vswitch = false, vds = false; virtualethernetcard _workloadnic = (virtualethernetcard)_virtualdevice; //first check if vm connected vswitch try { virtualethernetcardnetworkbackinginfo _nic_backing = (virtualethernetcardnetworkbackinginfo)_workloadnic.backing; network_moid = _nic_backing.network.value; vswitch = true; } catch (exception ex) { } //if not vswitch should vds if (!vswitch) { try { virtualethernetcarddistributedvirtualportbackinginfo _nic_backing = (virtualethernetcarddistribut...

Simple filtering in R, but with more than one value -

i aware of how extract data based on condition, whenever try multiple conditions, struggle ensues. have data , want extract years df. here example df: year value 2006 3 2007 4 2007 3 2008 5 2008 4 2008 4 2009 5 2009 9 2010 2 2010 8 2011 3 2011 8 2011 7 2012 3 2013 4 2012 6 now let's want 2008, 2009, 2010, , 2011. try df<-df[df$year == c("2008", "2009", "2010", "2011"),] doesn't work, then: df<-df[df$year == "2008" & df$year == "2009" & df$year == "2010" & df$year == "2011",] no error messages, empty df. missing? you need use %in% , not == df[df$year %in% c(2008, 2009, 2010, 2011),] year value 4 2008 5 5 2008 4 6 2008 4 7 2009 5 8 2009 9 9 2010 2 10 2010 8 11 2011 3 12 2011 8 13 2011 7

jquery - Responsive div columns where column items get shifted on screen resize -

i have 3 columns called <div class="pagecolumnonethird"> . inside each column fetch images , posts using php newest item gets placed in top left column , next 1 in top middle column , third 1 in top right column before goes left column again. now trying make responsive, when 2 columns displayed, placement of each image/post changed. example: when there 2 columns side-by-side need first row of items element 1 , 2. second row has element 3 , 4. is there way using css? if not, there fast jquery code can me? code <!-- first column --> <div class="pagecolumnonethird"> <div class="itemwrap">element 1</div> <div class="itemwrap">element 4</div> <div class="itemwrap">element 7</div> </div> <!-- second column --> <div class="pagecolumnonethird"> <div class="itemwrap">element 2</div> <div class=...

scala - Configuring Play Framework with Spark -

how configure play such can run spark cluster? have web framework using play connects spark cluster. when run spark-shell following, good: sparkdeployschedulerbackend: connected spark cluster app id app-20130813222026-0026 client$clientactor: executor added: app-20130813222026-0026/0 on worker-20130808012122-42908 16 cores sparkdeployschedulerbackend: granted executor id app-20130813222026-0026/8 on host 16 cores, 8.0 gb ram client$clientactor: executor updated: app-20130813222026-0026/0 running ... etc. but when try run play start don't above message (indicating running spark locally , not on cluster). ideas on correct configurations make work?

ios - telling multiple events apart with NSURLConnection and asynchronous connections -

i'm writing ipad app populates ui based on json data grabbed server. i'm using nsurlconnection make initial connection thusly: // create request. nsmutableurlrequest* request = [nsmutableurlrequest requestwithurl:[nsurl urlwithstring:@"http://foo.com/login"]]; [request sethttpmethod:@"post"]; nsstring* credentials = @"username=testfoo&password=passfoo"; self.ffooconnectiondata = [credentials datausingencoding:nsutf8stringencoding]; [request sethttpbody:self.ffooconnectiondata]; self.ffoodataconnection = [[nsurlconnection alloc] initwithrequest:request delegate:self]; [self.ffoodataconnection start]; now, issue can catch response in 'connectiondidx' delegate functions, subsequent steps, how should proceed? if synchronous connection, matter easier, i'd wait return value, asynchronous connection, how handle subsequent requests? how tell 1 event (like logging in) (like requesting specific data ui)? each asynchronous ...

scala - Custom Response from Controller in Finatra -

in app have custom case class below bunch of additional fields. case class user(id: uuid, username: string, password: string) now finatra controller picks response returned service , sends json response contains password hash well. controller basic gets get("/users") {request: getusersrequest => userservice.users() } so question how customize response such can drop password field , add additional data well. assuming userservice.users() returns list of users. i.e. list[user] transform response map . for example, can map new case class. case class userdto(id: uuid, username: string, comment: string) you can map tuple if don't want use class yet. get("/users") {request: getusersrequest => userservice.users().map(u => userdto(u.id, u.username, "comment!")) }

java - How to write out results of a program to Excel? -

i'm trying capture of links website, print them out, , store them in excel file. program correctly displaying results isn't storing them in excel file. package frameworks; public class arrayconversion { public static void main(string[] args) throws exception { webdriver driver = new firefoxdriver(); driver.get("http://only-testing-blog.blogspot.in/2013/09/test.html"); list<webelement> li = driver.findelements(by.tagname("a")); iterator<webelement> itr = li.iterator(); while (itr.hasnext()) { string link = itr.next().gettext(); arraylist<string> stringlist = new arraylist<string>(); stringlist.add(link); string array[] = stringlist.toarray(new string[stringlist.size()]); (string str : array) { system.out.println(str); xlwrite(array); } } } public static void xlwrite(...

ipython - Problems writing to Excel in pandas -

have following annoying problem ipython script using to_excel function in pandas: @ end of script want write results excel file. if include path e.g "~/", script breaks down enclosed error messages. if input file name script runs , produce new file in current folder. bug or doing wrong? code follows: path=dir+file_name print "writing %s " % path opt_design.to_excel(path, sheet_name='sheet1',index=false) print "finished!"`` the runtime error is: --------------------------------------------------------------------------- ioerror traceback (most recent call last) <ipython-input-1-b9e6707b5b6c> in <module>() 43 path=dir+file_name 44 print "writing %s " % path ---> 45 opt_design.to_excel(path, sheet_name='sheet1',index=false) 46 print "finished!" 47 /library/python/2.7/site-packages/pandas-0.11.1.dev_fcced51_20130617-py2.7-macosx-10.8- intel.egg/pandas/core...

javascript - Current day number - different computers, different days -

i´m using this function in about.com today number in year (ex: 226). i´m getting different results (correct , +1 day) in different computers, using this calculator i´m getting wrong +1 day value. using this one correct day number. computers tested have correct date, hour, timezone. ex. 8 minutes past midnight, i´m getting correct day (226), before midnight day when supposed 225, getting 226. i suppose function ok, problem should be? thanks you getting confused between client time , server time.. website.. http://mistupid.com/calendar/dayofyear.htm using javascript calculate day of year using following formula var dayofyear = math.ceil((entereddate.gettime() - startofyear.gettime()) / one_day) + 1 however, second website ( http://www.epochconverter.com/epoch/daynumbers.php ) using server time calculate day of year. updates number of days according utc time. date.prototype.getdoy = function() { var onejan = new date(this.getfullyear(),0,1); return m...

osx yosemite - Deleting folder on my OS X 10.10.5 by executing a file -

i have list of files want delete on mac, how automate without entering each terminal "sudo rm -r foldername" here list of folders: /library/application support/vmware /library/application support/vmware fusion /library/preferences/vmware fusion ~/library/application support/vmware fusion ~/library/caches/com.vmware.fusion ~/library/preferences/vmware fusion ~/library/preferences/com.vmware.fusion.lssharedfilelist.plist ~/library/preferences/com.vmware.fusion.lssharedfilelist.plist.lockfile ~/library/preferences/com.vmware.fusion.plist ~/library/preferences/com.vmware.fusion.plist.lockfile ~/library/preferences/com.vmware.fusiondaemon.plist ~/library/preferences/com.vmware.fusiondaemon.plist.lockfile ~/library/preferences/com.vmware.fusionstartmenu.plist ~/library/preferences/com.vmware.fusionstartmenu.plist.lockfile you use in terminal remove files list , recursively clear out directories in list. while read p; rm -r $p; done <list.txt list.txt list ...

c# - Why does strftime() not work in Sqlite when dates are stored as ticks? -

i have following code: [test] public void sqlitetest() { var insertquery = @"insert metricdata (date) values (@date)"; var selectquery = @"select strftime('%y',date) 'year', date metricdata"; var connectionstring = "data source=:memory:;version=3;datetimeformat=ticks;"; using (var db = new sqliteconnection(connectionstring)) { db.open(); databaseschemabuilder.initializeschema(db); var testdate = datetime.now; using (var cmd = new sqlitecommand(insertquery, db)) { cmd.parameters.addwithvalue("@date", testdate); cmd.executenonquery(); } using (var cmd = new sqlitecommand(selectquery, db)) { using (var reader = cmd.executereader()) { reader.read(); var querieddate = reader.getd...

sinatra - Ruby: creating a class object using the name of the class? -

please don't judge me harshly because new topic don't know how ask question (or search answers): i learning nested forms in sinatra, encountered don't understand relates ruby. see code snippet below--while trying test code in rake console , typed in team , , surprised see object created name "team". if type in my_team = team.new(params) , error message undefined local variable or method 'params' for main:object if typed in else, 'man', nameerror: undefined local variable or method 'man' for main:object why name of class result in instance of class? shouldn't require class_name.new create object? class team attr_accessor :name team = [] def initialize(params) @name = params[:team][:name] team << self end def self.all team end end in ruby, object, classes objects (and instances of class class . team instance of class class (shortened "a class") whereas ...