Posts

Showing posts from August, 2012

android getDefaultSharedPreferences doesn't get applied -

i'm new android development , i'm working on fixing bugs. app shouldn't load previous preference load instead of loading default values. here have in main activity preferencemanager.setdefaultvalues(this, r.xml.preferences, false); // register listener sharedpreferences changes preferencemanager.getdefaultsharedpreferences(this).registeronsharedpreferencechangelistener(preferencechangelistener); quizfragment quizfragment = (quizfragment) getfragmentmanager().findfragmentbyid(r.id.quizfragment); quizfragment.updateguessrows(preferencemanager.getdefaultsharedpreferences(this)); quizfragment.updateregions(preferencemanager.getdefaultsharedpreferences(this)); quizfragment.updatenumberquestions(preferencemanager.getdefaultsharedpreferences(this)); and here full code https://github.com/jamin567/android try way: final string eulakey = "mykey"; context mcontext = getapplicationcontext(); mprefs = m

C# BeginInvoke to use or not to use -

i want use call function b function a avoid blocking function a . thought begininvoke seems solution. but came point of asking myself, need this? invoking asynchronous thread wouldn't longer executing function calling function b function a? happen if function looping faster execution of function b? edit: the use of trace debug function having least impact on the caller. i kind of lost, appreciate help thank much making asynchronous call makes sense if call takes considerable time execute. if method call simple , returns, quicker call create thread , start it. if calling method in loop, should consider using asparallel method it. throttle number of threads used work, instead of blindly firing off lot of threads.

angularjs - ng-sortable How to get the list id while item is reordered -

i using https://github.com/a5hik/ng-sortable reorder list using drag , drop. i stuck @ getting list id when move item between 2 list. want know list drag started , dropped. <div id="list1" class="sortable-row" as-sortable="sortableoptions" ng-model="itemslist.items1"> <div ng-repeat="item in itemslist.items1" as-sortable-item> <div as-sortable-item-handle>{{item.label}}</div> </div> </div> in following itemmoved() method want list id $scope.sortableoptions = { containment: '#sortable-container', itemmoved: function (event) { console.log("itemmoved()"); console.dir(event); // identify list on order changed // last , new position // update card position } }; how identify list on drag started , on drop made. here plnkr same i debugged little more. found id using following: co

Typed primitives in Scala 2.11 -

as see, primitive types string , long cannot extended defined final . pity type-safe approach. in code does not revolve around e.g. string manipulation, prefer type data rather use string, long, int, etc: long i'm using type safe language, i'd code typed ground up. as per experimentation , as demonstrated on old question type aliases not seem facilitate this. currently, use things like: case class domaintype(value: string) at cost of having use .value value needed. is there other language feature been introduced after scala 2.8 or otherwise, can neatly facilitate type safe sub-typed primitives? there object overrides proxy underlying value, still let type matching occur? i don't agree way of thinking. java primitives can't extended because primitives (btw string not primitive). direct representation of byte code types . extending them make no sense compiler perspective. implicit value classes scala deals using pimp library pattern, examp

Android: NullPointerException on SimpleCursorAdapter.bindView() -

i experiencing crashes when using simplecursoradapter . it's happening users having android 4.0.3 , 4.0.4, it's nasty interests 1% of users, not little. it fixed on 19th june 2012, comment: " fix crash when simplecursoradapter changes cursor null when spinner's drop-down view shown. " ( this diff ) how can avoid crashes users still have android 4.0.3 , 4.0.4 ? java.lang.nullpointerexception @ android.widget.simplecursoradapter.bindview(simplecursoradapter.java:150) @ android.widget.cursoradapter.getview(cursoradapter.java:250) @ android.widget.abslistview.obtainview(abslistview.java:2424) @ android.widget.listpopupwindow$dropdownlistview.obtainview(listpopupwindow.java:1168) @ android.widget.listview.measureheightofchildren(listview.java:1251) @ android.widget.listpopupwindow.builddropdown(listpopupwindow.java:1095) @ android.widget.listpopupwindow.show(listpopupwindow.java:524)

extjs - Display date and time of record with grid cell data -

i using single-cell grid show notifications in application. how show date , time of notification each cell data? data present in model of associated store. want phabricator https://secure.phabricator.com/ any pointers how may so? one way accomplish use templatecolumn . can specify tpl in config of html representing 2 sources of data. here fiddle created demonstrating , simple , more complex tpl resembles data on site referenced. here simple example of template column: { xtype: 'templatecolumn', header:'name', tpl:'{first_name} {last_name}' } and more complex template column similar style 1 referenced: { xtype: 'templatecolumn', header: 'example date', flex: 1, tpl:'<span style="display:inline-table;width:50%;">{fi

rust - Unresolved name `thread::scoped` in an elementary program -

why compilation failure in elementary program? use std::thread; fn main() { in 1..10 { let _ = thread::scoped( move || { println!("hello thread {}", i); }); } } i try build program , get: src/main.rs:5:17: 5:36 error: unresolved name `thread::scoped` src/main.rs:5 let _ = thread::scoped( move || { ^~~~~~~~~~~~~~~ why? the version of rust use: $ rustc --version rustc 1.0.0-nightly (170c4399e 2015-01-14 00:41:55 +0000) the problem indeed version of rustc. after upgrade program compiled: compiling examples v0.0.1 (file:///home/igor/rust/projects/examples) src/main.rs:1:5: 1:16 warning: unused import, #[warn(unused_imports)] on default src/main.rs:1 use std::thread; ^~~~~~~~~~~ the warning disappeared after removed use : fn main() { in 1..10 { let _ = thread::scoped( move || { println!("hello thread {}", i); });

vb.net string contains only 4 digit numbers(or a year) -

how can check if string contains 4 digit numbers ( or year ) tried dim rgx new regex("^/d{4}") dim number string = "0000" console.writeline(rgx.ismatch(number)) // true number = "000a" console.writeline(rgx.ismatch(number)) // false number = "000" console.writeline(rgx.ismatch(number)) //false number = "00000" console.writeline(rgx.ismatch(number)) // true <<< :( this returns false when less 4 or @ characters not @ more 4 thanks! i wouldn't use regex this. expression deceptively simple ( ^\d{4}$ ), until realize need evaluate numeric value determine valid year range... unless want years 0013 or 9015 . you're going want value integer in end, anyway. given that, best validation try convert integer right off bat: dim numbers() string = {"0000", "000a", "000", "00000"} each number string in numbers dim n integer i

google cloud dns - Website Not working with www -

i have server running on google compute engine ip xx.xx.xx.xx , using google cloud dns map domain name test.com ip address. here did 1.) created zone using ui , added record set type 2.) gave domain name provider ns links 3.) website running beautifully when type test.com, not working when type www.test.com i tried creating cname (after watching solution on internet) got cname , record set conflict error. how solve problem? (preferably ui without using gcloud tool) you can duplicate entry zone's root - e.g., copy ip address, make new rr set of type @ 'www', , paste ip address. but cname should work. trying? want create cname @ www points root of domain. can't have else @ name, though (a cname says "use records other name) you'll need delete that's not cname. easiest delete name , recreate cname.

cakephp - Make an entry to debugkit log -

the debugkit plugin working fine me, cannot figure out how make entry show in toolbar`s log tab (not sql log tab). i`ve tried: debugkit::write('log','got here'); ..but errors out 500. ...btw cakelog::write('debug', 'got here'); works fine. i feel kind of dubm asking this, can`t find references. appreciate wisdom here. shaun

git - Redirect github page to different url -

i have changed repo foo bar . automatically github page url changed /foo /bar want /foo redirects /bar. how can achieve ? i using custom domain don't think makes difference. it seems gihhb doesn't redirect pages when renaming repository: github pages sites not automatically redirected when repositories renamed @ time. i think can still make redirect adding page ritz078.github.io project. create embed-js.html with: --- permalink: /embed-js/ --- <!doctype html> <meta charset=utf-8> <title>redirecting...</title> <link rel=canonical href="http://rkritesh.in/embed.js/index.html"> <meta http-equiv=refresh content="0; url=http://rkritesh.in/embed.js/index.html">

sed - Bash merge variable -

i'm trying status information vpn connections. it's done, except part return actual ph2 name: step 1 #!/bin/bash oldifs=$ifs export ifs=`/bin/echo -ne " \t\n"` vpn="vpn-aaa-bbb-1" ph2table=$(snmpwalk 192.168.1.1 -c public -v2c fgvpntunentphase2name -m /usr/share/snmp/mibs/fortinet-fortigate-mib.mib | sed "s/fortinet-fortigate-mib:://" | sed "s/string: //" | grep $vpn) $ph2table contains: fgvpntunentphase2name.71 = vpn-aaa-bbb-1-p2-0.1 fgvpntunentphase2name.72 = vpn-aaa-bbb-1-p2-0.2 fgvpntunentphase2name.73 = vpn-aaa-bbb-1-p2-0.3 fgvpntunentphase2name.74 = vpn-aaa-bbb-1-p2-0.4 fgvpntunentphase2name.75 = vpn-aaa-bbb-1-p2-1.5 fgvpntunentphase2name.76 = vpn-aaa-bbb-1-p2-1.6 fgvpntunentphase2name.77 = vpn-aaa-bbb-1-p2-1.7 fgvpntunentphase2name.78 = vpn-aaa-bbb-1-p2-1.8 fgvpntunentphase2name.79 = vpn-aaa-bbb-1-p2-2.9 fgvpntunentphase2name.80 = vpn-aaa-bbb-1-p2-3.10 step 2 clean=$(echo $ph2table | sed 's/fgvpntunentphase2nam

java - How can I write the contents of AbstrDoubleList into TextArea? -

i have little problem when trying write contents of abstrdoublelist textarea. i have class autopujcovna.class public class autopujcovna implements iautopujcovna { public abstrdoublelist<iauto> listvypujcenychaut = new abstrdoublelist(); public abstrdoublelist<ipobocka> listpobocek = new abstrdoublelist(); @override public string tostring() { return "seznam poboček: \n " + this.listpobocek; } @override public void vlozpobocku(ipobocka paramipobocka, enumpozice paramenumpozice) { switch (paramenumpozice) { case prvni: listpobocek.vlozprvni(paramipobocka); break; case predchudce: listpobocek.vlozpredchudce(paramipobocka); break; case naslednik: listpobocek.vloznaslednika(paramipobocka); break; case posledni: listpobocek.vlozposledni(paramipobocka); break; } } . . . than have gui button , button ca

html - Chrome Console get values from xpath array -

i'm using google chrome console array of elements have class of attrvalue . i'm using: $x('//*[@class="attrvalue"]'); and output: <td class="attrvalue">transway 1a</td>, <td class="attrvalue">northbound/westbound</td>, <td class="attrvalue">facing west</td> it works great array of elements trying array of values within elements. appreciated. get text() : $x('//*[@class="attrvalue"]/text()');

python - Ignore passed arguments -

is possible ignore passed/overgiven arguments in method? here example want do: def event_handler(one, two): print(one) print(two) and @ place: event_handler(one, two, three) i mean third argument optional. i've tried in python fiddle, doesn't work without error. make third default argument def event_handler(one, two, third = none): then error handling, default, easy. def event_handler(one, two, third = none): print(one) print(two) if (three): print(three)

java - How do I give imageNameRegex an actual regular expression -

i'm trying use specific ami on aws using it's name. it works if set imagenameregex = region/image_name fails if try of following: imagenameregex = image_name imagenameregex = .*/image_name imagenameregex = .*image_name imagenameregex = /.*image_name/ the aim here can copy ami across number of regions , have brooklyn pick correct 1 without having specify specific image id region. looking @ brooklyn tests shouldn't need regex - long name substring of full name should work. i'm setting in brooklyn.properties not yaml though can't imagine makes difference. jclouds restricts number of owners being queried more common ones have better response times. however, if want have more open query, can override default 1 setting jclouds.ec2.ami-query property when creating context. default, jclouds uses one: owner-id=137112412989,801119661308,063491364108,099720109477,411009282317;state=available;image-type=machine

objective c - Session disappear if using automatic anonymous users -

i'm using next code maintain automatic users app: [parse setapplicationid:@"xxx" clientkey:@"xxx"]; [pfuser enableautomaticuser]; [[pfuser currentuser] saveinbackground]; after first launch can see new user created , new session , working ok. after couple of additional launches session automatically disappear dashboard , : "...invalid session token (code: 209, version: 1.7.0)..." error. if log-out lost user info, not way me. how use automatic users , new parse sessions? ps. testing on emulator.

apache - .htaccess forward domain except some directories -

i want forward content of mydomain.com mydomain.somewhereelse.com want www.mydomain.com/mail , www.mydomain.com/stats not forwarded new address. how should this? there if else solution? rewriteengine on rewritebase / rewriterule ^mail squirrelmail/src/login.php [r,nc] rewriterule ^(.*) http://new.example.com/$1 above not work. you can use rule first rule below rewritebase line: rewritecond %{http_host} ^(www\.)?mydomain\.com$ [nc] rewriterule !^(mail|stats) http://mydomain.somewhereelse.com%{request_uri} [l,nc,r=302]

sqlite duplicate column header on select -

i noticed when select : select * table1 join table2 if both tables happened have column same name, sqlite shows 2 columns name. example if both tables have id column, in result 2 identical column header. behaviour causing problems when working jdbc, cannot value of column. there generic way overcome this. example make sqlite give prefix these columns, or refuse execute query.

Android refresh Recyclerview delayed -

i have simple layout recyclerview. in oncreateview method set recyclerview: @override public view oncreateview(layoutinflater inflater, @nullable viewgroup container, @nullable bundle savedinstancestate) { view rootview = inflater.inflate(r.layout.fragment_overview, container, false); recyclerview = (recyclerview) rootview.findviewbyid(r.id.rv_overview); list = new arraylist<>(); linearlayoutmanager layoutmanager = new linearlayoutmanager(getactivity()); layoutmanager.setorientation(linearlayoutmanager.vertical); recyclerview.setlayoutmanager(layoutmanager); list = getoverviewlist(getactivity()); adapter = new overviewrecycleradapter(getactivity(), list); recyclerview.setadapter(adapter); final context context = getactivity(); new handler().postdelayed(new runnable() { @override public void run() { list =getoverviewlist(context); adapter.notifydatasetchanged(); } }, 1000);

android - Retrofit chaining observables -

i'm trying use retrofit rxjava. have problem chaining retrofit observables 1 or observables created me. example: observable<list<friend>> friendslistobservable = friendsservice.getfriends(); observable<void> updatereqestobservable = friendslistobservable.switchmap(friends -> { log.d(tag, "hello"); return userapi.updatefriends(session.getuserid(), friends); }).subscribe(); everything gets called until gets switchmap. hello never displayed, if return instance observable.just(null) instead of retrofit observable works fine. if user retrofit observable without chaining, works. edit1: it's android app. seems map operator not called @ all. happens retrofit observables also. still think has threading. understand operator called when item emitted, calling onnext doesn't trigger map operator. below whole code: public observable<list<facebookfriend>> getfriends() { publishsubject<list<fac

c++ - std::queue::empty() not working? -

i'm going crazy piece of code. have thread calls regularly method: void delivermsgq() { if(delmsgq_mutex.try_lock() == false){ return; } while(delmsgq.empty() == false){ std::vector<unsigned char> v = delmsgq.front(); delmsgq.pop(); } delmsgq_mutex.unlock(); } void processinmsgq() { if(inmsgq_mutex.try_lock()){ if(delmsgq_mutex.try_lock() == false){ inmsgq_mutex.unlock(); } }else{ return; } while(!inmsgq.empty()){ std::vector<unsigned char> msg; inmsgq.front()->getdata(msg); std::cout << "adding del-msg-q: " << msg.size() << std::endl; delmsgq.push(msg); delete inmsgq.front(); inmsgq.pop(); } inmsgq_mutex.unlock(); delmsgq_mutex.unlock(); } i have thread pushing vector queue periodically. these 2 thr

javascript - JSON Parse splice issue -

i can't seem work out why splice isn't working correctly in instance. i have read countless stack overflow examples of splice , can't seem see issue. this code should remove index 14, first item(and only) in json array. var product_variations = json.parse('[{"0":"","1":"","2":"","3":"0.0000","4":"","5":"0.00","6":"0.00","7":"1.00","8":"0","9":"false","10":"false","11":[],"12":"","13":"","14":"red","15":"small"}]'); product_variations[0].splice(14, 1); it not work because splice method available on arrays, not on objects. and object: {"0":"","1":"","2":"","3":"0.0

postgresql - Function taking forever to run for large number of records -

i have created following function in postgres 9.3.5: create or replace function get_result(val1 text, val2 text) returns text $body $declare result text; begin select min(id) result table id_used null , id_type = val2; update table set id_used = 'y', col1 = val1, id_used_date = now() id_type = val2 , id = result; return result; end; $body$ language plpgsql volatile cost 100; when run function in loop of on 1000 or more records freezing , says "query running". when check table nothing being updated. when run 1 or 2 records runs fine. example of function when being run: select get_result('123','idtype'); table columns: id character varying(200), col1 character varying(200), id_used character varying(1), id_used_date timestamp without time zone, id_type character(200) id table index. can help? most running race conditions . when run function 1000 times in quick succession in separate transactions , happens: t

math - Converting 2D projection rotation angles to 3D object -

Image
i projecting 3d matrix of density values 3 2d planes (zx,zy,xy). rotate each projection 3 different angles: pzx, pzy, pxy using rotation matrix below: how convert these 3 separate angles can apply them 3d transformation matrix rotate 3d object x,y,z (or z,y,x) such rotation matrix below: to clear, not wish apply angles pzx, pzy, pxy 3d object, instead calculate individual rotations in 2d translate in 3d. this problem yields system of equations. let r_3d rotation in 3d space, r_xy rotation in xy plane, , [*]_xy projection of * onto xy plane. point v : i: [r_3d v]_zx = r_zx [v]_zx ii: [r_3d v]_zy = r_zy [v]_zy iii: [r_3d v]_xy = r_xy [v]_xy we see every coordinate present in 2 equations. let's check relevant equations x-coordinate: a := alpha, b := beta, c := gamma i: cos b cos c x - cos b sin c y + sin b z = sin pzx z + cos pzx x iii: cos b cos c x - cos b sin c y + sin b z = cos pxy x - sin pxy y we see following relation mus hold v (right h

c - What is wrong here? Expected expression before '=' token? -

this question has answer here: expected expression before '=' token in c 2 answers i trying set structure in c program writing. however, compiler returns expecting expression before '=' token on line 31. below snippet of code containing struct , line of code in question: edit: thread_count defined #define thread_count = 120 struct threadinfo { int threadid; }; struct threadinfo customerids[thread_count]; //offending line here i have tried chaning expression = sign, tried changing way struct declared, nothing has worked far. advice? edit 2: error resolved. definition of thread_count incorrect. don't use = in #define statement. should be: #define thread_count 120 preprocessor definitions aren't variables, simple text replacement.

symfony1 - How to install an older 1.3 version of Symfony framework using Composer or PEAR tools? -

how install older 1.3 version of symfony framework using composer or pear tools? the same problem older zend , other frameworks. need old symfony framework running codes books , tutorials. symfony 1 via pear required: php pear installed add symfony's pear archive: pear channel-discover pear.symfony-project.com to find out version number browse http://pear.symfony-project.com/ please note version links allow manual downloads, e.g. http://pear.symfony-project.com//get/symfony-1.3.0.tgz or pear remote-list -c symfony install pear install symfony/symfony or install specific version, requested: pear install symfony/symfony-1.3.0 symfony 1 via composer the composer repo symfony1 https://packagist.org/packages/symfony/symfony1 in order install v1.3.19 add following line composer.json 's require section: "symfony/symfony1": "1.3.19" or latest v1 "symfony/symfony1": "1.*" zend framework 1 via comp

javascript - Compare two arrays and push different values to new array -

this question has answer here: how difference between 2 arrays in javascript? 54 answers i have 2 arrays want compare , push values not same in both new array. i'm trying push values arraytwo not in arrayone new array. var arrayone = [[1,"121"], [2,"111"], [2,"321"], [3,"232"], [3,"213"], [4,"211"]], arraytwo = [[4,"111"], [1,"131"], [3,"321"], [3,"232"], [3,"211"], [3,"213"], [1, "x1x"]]; donotmatch = []; i tried looping through first 2 arrays comparing values below isn't working: ( var = 0; < arrayone.length; i++ ) { ( var e = 0; e < arraytwo.length; e++ ) { if ( arrayone[i] !== arraytwo[e]) { donotmatch.push(arraytwo[e]) } } } var arr

python - Pandas DataFrame including three numpy arrays -

i make pandas dataframe contents of 3 diferents numpy arrays. valor_norte;value of variable numpy.ndarray valor_este;value of variable numpy.ndarray dtime numpy.ndarray valor_norte array([-0.14300001, -0.10600001, -0.075 , -0.054 , -0.041 , -0.035 , -0.03 , -0.017 , 0.007 , 0.038 , 0.07 , 0.09100001, 0.098 , 0.09 , 0.07300001, 0.05 , 0.023 , -0.004 , -0.023 , -0.03 , -0.025 , -0.014 , -0.003 , 0.004 ], dtype=float32) valor_este array([-0.07600001, -0.078 , -0.071 , -0.06500001, -0.062 , -0.063 , -0.07 , -0.089 , -0.108 , -0.12400001, -0.134 , -0.123 , -0.093 , -0.05 , -0.009 , 0.016 , 0.023 , 0.009 , -0.022 , -0.059 , -0.09200001, -0.11300001, -0.12100001, -0.11400001], dtype=float32) dtime array([datetime.datetime(2015, 4, 1, 0, 30),

php - Fetch array with mysql_fetch_assoc -

$query = mysql_query("select name lottery"); // make lotteries array $queryarray = mysql_fetch_array($query); // each lottery, store name of in $lottery foreach ($queryarray $lottery) { // select ids of tickets in current selected lottery ($lottery) $ticketquery = mysql_query("select id tickets lottery='$lottery'"); // create array ids $ticketarray = mysql_fetch_assoc($ticketquery); // select random id, our winner ticket $winner = $ticketarray[array_rand($ticketarray)]; } when run this, however, error: "warning: array_rand() [function.array-rand]: first argument has array in public_html/php/lotterypick.php on line 25" have tried replace mysql_fetch_assoc mysql_fetch_array , hasn't helped either. given me same error. ideas? thanks. line 25: $winner = $ticketarray[array_rand($ticketarray)]; writing code as: while($lottery = mysql_fetch_array($query)){...} would solve problem.

git color.ui does not work on Ubuntu 14.10 -

Image
i have installed git version 2.1.0 on ubuntu 14.10. i have created local git repository , have branches highlighted colors in ubuntu default terminal. i have done : git config --global color.ui true but has no effect on terminal (i have tried restart it). this content of ~/.gitconfig file: $ cat ~/.gitconfig [alias] st = status co = checkout [color] ui = true branch = auto diff = auto interactive = auto status = auto any ideas why branches not coloured/highlighted in ubuntu terminal when inside repository? i have read this: how color git console in ubuntu? but provide help i expecting this: if you're expecting branch name colored git status appears have turn explicitly on. guess it's missing default color color.ui = auto apply. [color "status"] branch = green

java - How to approach Inputprocessing -

i trying build options menu in libgdx using scene2d , im trying find way how approach user input. i want implement going mainmenu when key on android pressed, not sure how it, since rest of input (pressing button ) handled stage. if have idea on how approach issue , how handle user input correctly please respond. did not include code since more how approach it, instead of actual problem in code. thanks, valentin you need create inputprocessor , implement methods, there no way around because key separate stage. need have way access main menu object inputprocessor; assuming using game , screens, 1 way of doing it: public class optionsscreen implements screen, inputprocessor { final mygame game; public optionsscreen(mygame game) { this.game = game; } ... @override public boolean keyup(int keycode) { if(keycode == keys.back) { game.setscreen(game.mainscreen); return true; } return false; } ...

java - H2 Database OutOfMemoryError on android? -

i'm trying using h2 on android app 1 of main table is: create table if not exists " + "tbl_content(" + "date date primary key, " + "content other); when i'm adding data it, after insert data table below error: change code many times(change read file, split file , so...) nothing change , every time error again , again: java.lang.outofmemoryerror: capacity: i add android:largeheap="true" manifest file nothing change!!! 03-28 15:46:44.786 9512-11006/? d/dalvikvm﹕ gc_before_oom freed 81k, 27% free 12064k/16316k, paused 84ms, total 85ms 03-28 15:46:44.786 9512-11006/? e/dalvikvm-heap﹕ out of memory on 2097168-byte allocation. 03-28 15:46:44.796 9512-11006/? i/dalvikvm﹕ "mvstore background writer nio:/data/data/com.example.me/files/dbx.mv.db" daemon prio=5 tid=14 runnable 03-28 15:46:44.796 9512-11006/? i/dalvikvm﹕ | group="main" scount=0 dscoun

scikit learn - sklearn random forest not parallelizing -

Image
i'm using sklearn 0.16 on ubuntu 12.04 , running: from sklearn.ensemble import randomforestclassifier import numpy np x=np.random.rand(5000,500) y=(np.random.rand(5000).round()) randomforestclassifier(n_jobs=10,n_estimators=1000).fit(x,y) however it's not using cores, , takes same time n_jobs=1. ideas on how debug what's going on here? this screenshot shows other things running busy, htop has been showing available cpus: try : import affinity import multiprocessing affinity.set_process_affinity_mask(0, 2**multiprocessing.cpu_count()-1)

android - How do I programmatically show a specific location in google map? -

so have come here ask again. googled lot on issue. there many solutions , confusing. moreover, of them done in eclipse, said change path, intigrate eclipse , bla bla... problem description: in application (in android studio), have item named map view , want user clicks on it, should take map view page , locate address (i have mentioned in code) in map. how that? dummycontent: ................................ ................................ static { // add 4 sample items. additem(new dummyitem("1", "shopping center details")); additem(new dummyitem("2", "homepage")); additem(new dummyitem("3", "contact")); additem(new dummyitem("4", "map view")); } ................................. .............................. itemdetailfragment: ................. .................... }else if(mitem.equals("4")){//4. map view

php - Symfony swiftmailer in production environment -

i have problem sending mails swiftmailer in symfony2. let me explain it: when go website app_dev.php, send messages, there no problem (also, when write $kernel = new appkernel('prod', true); in app.php). so, don't understand why works in dev , not in prod. here configuration files: parameters.yml: mailer_transport: smtp mailer_host: ****.ovh.net mailer_username: postmaster@mywebsite.com mailer_password: **** mailer_port: **** config.yml: swiftmailer: transport: "%mailer_transport%" host: "%mailer_host%" username: "%mailer_username%" password: "%mailer_password%" port: "%mailer_port%" spool: { type: memory } and php code, think there no problem because said there no problem in dev mode. $message = \swift_message::newinstance() -> setsubject('test') -> setfrom('postmaster@mywebsite.com') -> setto($user -> getmail()) -> setbody('t

java - How to add jpanel to a specific cell of GridLayout -

in below code, created gridlayot 3 rows , 3 columns, want is,,to add jpanel_1 specifc cell of gridlayout, lets in grid cell number (2,3). code : private void setupgui2() { // todo auto-generated method stub jframe_2 = new jframe("border demo"); gridlayout gridlayout = new gridlayout(3,3); jframe_2.setlayout(gridlayout); jpanel_1 = new jpanel(new borderlayout()); jpanel_2 = new jpanel(new borderlayout()); jpanel_1.setborder(borderfactory.createtitledborder("title")); //jpanel_1.setbounds(30, 100, 110, 300); jpanel_1.add(jlabel_hello, borderlayout.east); jpanel_2.setborder(borderfactory.createloweredbevelborder()); //jpanel_2.setbounds(20, 50, 120, 80); jpanel_2.add(jlabel_hello, borderlayout.south); //jframe_2.setbounds(0, 0, 600, 600); jframe_2.add(jpanel_1);//how add jpanel_1 specific cell of gridlayout defined above //jpanel_1.add(jpanel_2); jframe_2.add(jpanel_2); jframe_2.pack();

node.js - New websocket on different instance of site -

i have remote control 4 devices running on node server. each device has own page (/1, /2, /3, /4), generated same html/js. the difference ip each device, loaded json on server depending on url path. this works, problem is: have 3 wrong ips entered testing purposes, , 1 correct one. if open correct one, go parent page , open page of device wrong ip, still shown online , can controlled. i understand like: socket stays open across pages , not built new on every site. how can make sure each subpage generates new socket? right now, have socket = new io.connect(); in browser.js, ioserver.on('connection', function (socket) { //etc. } in app.js , works 1 device. am right assume need kind of "destroy socket if page changed"-function? thanks help by looks of it, want instantiate , boot device when device's client connects first time , emits 'startup'. if not case, i'd instantiate , boot each device when server starts. g

ios - Sort an array by ID and separate same ids in arrays -

i trying tackle following sorting , separating, have array ids 1,2,3,4,5,3,2,1. sorting array nspredicate quite straightforward how can separate same ids in separate sub-arrays [[1,1][2,2,],[3,3],[4],[5]]? guess 1 option loop sorted array , compare previous index ids, wondering if helper function exist in ios, reading nsorderedset cant seem find if can help. a combination of ordered , counted sets: nsarray *array = @[@1,@2,@3,@4,@5,@3,@2,@1]; nsorderedset *os = [[nsorderedset alloc] initwitharray:array]; nscountedset *cs = [[nscountedset alloc] initwitharray:array]; nsmutablearray *sortedarray = [@[] mutablecopy]; [os enumerateobjectsusingblock:^(id obj, nsuinteger idx, bool *stop) { nsmutablearray *countarray = [@[] mutablecopy]; (int = 0; < [cs countforobject:obj]; ++i) { [countarray addobject:obj]; } [sortedarray addobject:[countarray copy]]; }];

javafx - Java reflection for library classes -

i have class large number of variables use myclass.class.getdeclaredfields() , loop save simple types such int, double etc. now i'm stuck on 'not simple ones' such javafx.scene.paint.color , javafx.scene.effect.innershadow etc. can save values somehow using myclass.class.getdeclaredfields() or need save them separately (i.e. manually)?

java - Incorrect GPA method computation -

this question has answer here: how compare strings in java? 23 answers my method keeps returning 0 . can me find why gpa not compute? public static double getgpa(string a) { double value = 0; double sum = 0; for(int = 0; i<a.length(); i++) { string grade = a.substring(i,i+1); if(grade == "a") value = 4; if(grade == "b") value = 3; if(grade == "c") value = 2; if(grade == "d") value = 1; if(grade == "f") value = 0; sum += value; } return sum/(a.length()+1); } you should using .equals(), not ==. you've got couple of lesser mistakes: you're dividing string length plus one . you're not handling invalid inputs sensibly. error or ignore. here's corrected copy: public static double getgpa(string a) { lo

python - Turning a list of lists into a dictionary of lists -

hi there having small problem code trying implement. wish convert list of lists dictionary keys refer lists position in original list of lists, , values list of items in said list (from original list of lists). wish remove of nones present in original list of lists. example: [[(1, none), (2, none)], [(0, none), (2, none)], [(1, none), (0, none)]] i want become: {0: [1, 2], 1: [0, 2], 2: [1, 0]} looks basic dict , list comprehension raw = [[(1, none), (2, none)], [(0, none), (2, none)], [(1, none), (0, none)]] print {i: [el[0] el in l] i, l in enumerate(raw)} prints {0: [1, 2], 1: [0, 2], 2: [1, 0]}

ftp - The archive after upload be damaged PHP -

well, start, english isn't good. apologies. my problem have code, when upload, archive goes, stays damaged. source: <?php $servidor = 'mysite'; $usuario = 'user'; $senha = 'pass'; $ftp = ftp_connect($servidor); $login = ftp_login($ftp, $usuario, $senha); $local_arquivo = './arquivos/documento.doc'; $ftp_pasta = '/public_html/arquivos/'; $ftp_arquivo = 'documento.doc'; // envia o arquivo pelo ftp em modo ascii $envio = ftp_put($ftp, $ftp_pasta.$ftp_arquivo, $local_arquivo, ftp_ascii); thanks ;)

asp.net mvc - MVC Identity 2 - HasBeenVerifiedAsync FAIL -

i sure have see code below: public async function verifycode(provider string, returnurl string, rememberme boolean, email string) task(of actionresult) ' require user has logged in via username/password or external login if not await signinmanager.hasbeenverifiedasync() return view("error") end if return view(new verifycodeviewmodel() { .provider = provider, .returnurl = returnurl, .rememberme = rememberme, .email = email }) end function when log site first time hasbeenverifiedasync indicates user not logged in. if log out log in passes true. any idea why happening seems bug.... assume checking token... looks coming down through fiddler...

ruby on rails - Heroku - Uninitialized constant for importing a module -

i have module lib/basicstats.rb (module basicstats ...etc. end) i importing model class vote < activerecord::base include basicstats #additional class code etc. end i grep -d module , 'basicstats' referenced in basicstats.rb , app/model/vote.rb . this works fine local development. during heroku deployment getting error , can't seem recognize module? (i'm curious how working in local development without require anywhere.) 2015-03-28t22:19:52.714077+00:00 app[web.1]: /app/app/models/vote.rb:16:in `<class:vote>': uninitialized constant basicstats (nameerror) it sounds module isn't being explicitly required or auto-loaded rails (this will/won't happen depending version of rails you're using , how config.autoload_paths configured). your best bet add initializer explicitly requires module: # config/initializers/basicstats.rb require rails.root.join('lib/basicstats')

arrays - Why doesn't my javascript work? -

i'm trying create javascript count 1 1000 , push multiples of 3, 5 array called multiples print array out using console.log(). reason code isn't working. know why? var n; var multiples = []; for(n = 1; n <= 1000; n += 1) { console.log("counting"); } if(n % 3 === 0) { n.push(multiples); } else { } if(n % 5 === 0) { n.push(multiples); } else { } if(n >= 1000) { console.log(multiples); } else { } there few issues code. using {} in block designates scope of code executing in each iteration. in order access each value n need placing conditional statements inside of {} , not outside of them. there slight syntax error multiples array. in order push value array use arrayname followed dot operator , push function argument being value pushed. in terms of multiples , n, means multiples.push(n) . when using if() block, else not required. it best practice include variable declaration inside of loops, , use ++ opposed += 1. ov

How to create and format an image dataset from scratch for machine learning? -

i've worked ml .csv formats. i've worked image formats premade imagesets (mnist,etc). if create imageset scratch, how class labels typically formated? have manually title image of jpeg? best, jeremy i've worked image datasets formatted as: class names folders : name suggests, images belonging specific class filled specific folder folder name representing class. for example dataset classify cats vs. dogs -dataset/ --cats/ ---all cat images here --dogs/ ---all dogs images here single folder + text file : images dumped single folder - every image file have unique name. key-value pairs of image_name : class can stored rows in csv file. for example -dataset/ --all images heree --imagename_class.csv single folder class in filename : images can placed in single folder name of image having class label changing index value. for example -dataset/ --cat_1.jpg --cat_2.jpg --dog_1.jpg --cat_3.jpg --... hope helps!

javascript - Fetch Images From SharePoint Into Bootstrap Modal/Carousel -

i'm fetching images sharepoint rest api , writing calls along html html doc. specifically bootstrap modal carousel. i'm getting images , content writing tiles. problem images in modal. the user clicks on icon, modal fires, first image in carousel displays won't navigate next/previous, though html being written each one. here's html: <div class="container"> <!-- global navigation --> <div class="row"> <div class="col-md-12"> <script type="text/javascript" src="/js/nav.js"></script> </div> </div><!-- /end global nav --> <!-- tile wrapper --> <div class="row bgtexture bgtexture2 "> <div class="col-md-12"> <!-- top row of tiles --> <div class="row aotilestopwrapper"> <h2&g

Rails NoMethodError: undefined method `valid?' -

i relatively new rails , can't figure out how fix bug. here models: user class user < activerecord::base before_save { email.downcase! } has_many :tickets has_many :events, through: :tickets validates :first_name, presence: true validates :last_name, presence: true valid_email_regex = /\a[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i validates :email, presence: true, length: { maximum: 255}, format: { with: valid_email_regex }, uniqueness: { case_sensitive: false } end event: class event < activerecord::base has_many :tickets has_many :users, through: :tickets validates :event_title, presence: true validates :event_place, presence: true validates :event_description, presence: true validates :event_date, presence: true validates_numericality_of :event_number_tickets, presence: true, numericality: { only_integer: true }, greater_than: 0 end ticket: class ti

php - Variable empty without reason -

i developing shopping cart system , working perfectly, except 1 thing. well, use php session store data each product, including id, name, price , quantity. variables correctly completed, unless price variable. not know why! use jquery fetch values , send them page process them in session. i put relevant parts of code facilitate. content of products.php : <?php session_start(); ?> <html> <body> <?php $connection = new mysqli(db_host, db_user, db_pass, db_name); $sql = "select id, name, price products order id"; $result = $connection->query($sql); if ($result->num_rows > 0) { echo "<table>"; echo " <tr>"; echo " <th>id</th>"; echo " <th>name</th>"; echo " <th>price</th>"; echo " <th>quantity</th>";

python - How to iterate over particular keys in a dict to get values -

i have large list containing many dictionaries. within each dictionary want iterate on 3 particular keys , dump new list. keys same each dict. for example, i'd grab keys c, d, e dicts in list below, output list2. list = [{'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6...}, {'a':10, 'b':20, 'c':30, 'd':40, 'e':50, 'f':60...}, {'a':100, 'b':200, 'c':300, 'd':400, 'e':500, 'f':600...},] list2 = [{'c':3, 'd':4, 'e':5}, {'c':30, 'd':40, 'e':50}, {'c':300, 'd':400, 'e':500}] you can use nested dict comprehension: keys = ('c', 'd', 'e') [{k: d[k] k in keys} d in list] if keys may missing, can use dictionary view object ( dict.viewkeys() in python 2, dict.keys() in python 3) find intersection include

Passing javascript variable to next php page -

so have php file form located. <head> <script src="js/create_competition.js" type="text/javascript"></script> </head> <body> <form id='create-competition' action='create_competition_action.php' method='post' accept-charset='utf-8'> <div id="main"> <input type="button" id="addbutton" value="add" class="bt" /> </div> <input type='submit' id='submit' name='submit' value='submit' /> </body> and when press add button field created on page. when press again, field created , on. , when field created variable in create_competition.js gets bigger 1. now when lets there 3 field created , after submit button pressed want pass variable (which 3 @ moment) create_competition_action.php use knowledge of how many fields created there. have no idea how can that. i tried using

html - How to get CSS Background Colour with Python? -

basically question says, i'm trying background colour out website. at moment i'm using beautifulsoup html , it's proving difficult way of getting css . great! this not can reliably solve beautifulsoup . need a real browser . the simplest option use selenium browser automation tool: from selenium import webdriver driver = webdriver.firefox() driver.get('url') element = driver.find_element_by_id('myid') print(element.value_of_css_property('background-color')) value_of_css_property() documentation .

ios - Why is the text label empty when debugger says it is not? Swift app? -

Image
i'm new swift , i'm trying text label show on table view isn't showing up. following file , build. tree nest of ui: --main view controller ----ui tabel view ------main view controller cell i'm beginning think i'm reloading table @ wrong place. i appreciate in advance! when remove self.maintableview.reloaddata(), no cells show up. @ moment, i'm still able click on cells , respond following debugger lines: selected number 0 selected number 1 selected number 2 mainviewcontroller.swift import foundation import locksmith import uikit import alamofire import swiftyjson import alamofire import jwtdecode class mainviewcontroller: uiviewcontroller, uitableviewdelegate, uitableviewdatasource { var userfeed = [userfeedrow]() @iboutlet weak var maintableview: uitableview! override func viewdidload() { maintableview.registerclass(mainviewtableviewcell.self, forcellreuseidentifier: "maintableviewcell") maintab