Posts

Showing posts from July, 2015

java - Recommended way to execute async tasks with RXJava -

i'm new rxjava , i'm trying understand best/recommended way perform long running tasks asynchronously (e.g. network requests). i've read through lot of examples online appreciate feedback. the following code works (it prints 'one', 'two', 'user: x' ... etc) should creating/managing threads manually? thanks in advance! public void start() throws exception { system.out.println("one"); observeusers() .flatmap(users -> observable.from(users)) .subscribe(user -> system.out.println(string.format("user: %s", user.tostring())); system.out.println("two"); } observable<list<user>> observeusers() { return observable.<list<user>>create(s -> { thread thread = new thread(() -> getusers(s)); thread.start(); }); } void getusers(final subscriber s) { s.onnext(userservice.getusers()); s.oncompleted(); } // userservice.getusers() fe

ruby on rails - Generate MiniTest Spec for Existing Model -

migrations complain model exists when try generate existing minitest spec model. rails generate model user --spec how can work around this? rails generate model user --spec --skip

optimization - Conditionally execute a subquery with MySQL -

i have view describes statistics of table, e.g.: create table people ( playerid int not null auto_increment, name varchar(70), primarykey (playerid) ); create view personinfo_oranges (playerid, number_of_oranges) select playerid, count(orangeid) oranges ... ; unfortunately, there's loads of data in tables person_info looks @ (e.g. oranges) , view slow load. apparently known issues views . created table stores data of people (e.g. when become allergic oranges): create table person_summary ( playerid int not null, number_of_oranges int, foreign key (playerid) references players(playerid) ); ideally create view searches person_summary , and, if not found, looks in personinfo_oranges . logic in model layer, how can in mysql?

ios - NSLocalizedString() picking up cached entry from before Localizable.strings is localized -

i building first ios iphone 6 app. i having problem getting xcode pick key/value pairs localized version of localizable.strings. nslocalizedstring() method seems returning cache entries before localized localizable.strings file. you can see in screenshot below when had 1 localizable.strings file, code picks key/value pair looking fine https://www.evernote.com/l/aaii1y9qyi5h9o_siuduteczjzmvyr5fcfw when tried localizing localizable.strings file (i.e. having base, english, chinese version of file), nslocalizedstring() returns key value when had 1 localizable.strings file. https://www.evernote.com/l/aalbxeqwnuvfhahmlduagzw5n1op8o2alc8 know happening because when change values same key across 3 files, it's still returning old value. i've tried resetting simulator settings (this suggests cache in build) restarting simulator/xcode searching old value in project, couldn't find old values nslocalizedstring returning changing key else altogether, nslocalizedstri

c++ - MSXMLDomDocument to consume XML -

i have existing msxml2::domdocument. document want insert further xml text. what have tried creating second domdocument , using loadxml method. append documentelemt main xmldocument. gives me memory leak. guess shifting nodes 1 doc not valid. so question is: intended way insert xmlsource (text) existing domdocument?

xslt 2.0 how replace $ by escaped dollar (for conversion to LaTeX) -

i new xslt. googled extensively couldn't figure out how following: i transforming xml latex. of course, latex needs escape characters such $ , #. tried following in replace function not work. (they work without replace function.) <xsl:template match="xyz:doc"> \subsubsection{<xsl:value-of select="replace( xyz:headline, '(\$)', '\$1' )"/>} ... </xsl:template> <xsl:template match="xyz:doc"> \subsubsection{<xsl:value-of select="replace( xyz:headline, '\$', '\$' )"/>} ... </xsl:template> possible content escaped is: "locally defined field #931" or "locally defined subfield $b" what doing wrong? many answers! if want replace dollar symbol $ in input \$ in output use replace(xyz:headline, '\$', '\\\$') . if there several characters need same escaping replace(xyz:headline, '([$#])', '\\$1') should do.

c++ - Stroustrup's P:PP Chapter 4 Drill: Stuck -

i'm stuck on stroustrup's p:pp chapter 4 drill, part 5. problem asks me write program consists of while-loop reads 2 doubles , terminates program when character | entered. program should output both doubles, tell smaller , larger, , whether or not they're equal or equal. took definition equal when numbers within 0.1 of each other. wrote program terminates when non-double input entered, instead of |. when input 15.0 , 19.0, i'm still told "the values equal," instead of 15.0 smaller , 19.0 larger. curiously, if input 19.0 , 15.0, tell me smaller value 15, , larger 1 19. if input 15.0 , 15.0, tell me values equal. basically, if x < y, , input in order "x y" "almost equal," if input "y x" i'm told x smaller , y larger. otherwise, error-free. any suggestions? #include "../../../std_lib_facilities.h" int main() { double val1 = 0; double val2 = 0; cout << "enter 2 values: \n";

php - Problems with array Statement -

hello friends problem statement 2 string $i=0; $arr['lam'] = preg_replace('/\s+/', 'd', $arr['lam']); print_r($arr); ///array ( [id] => 123 [lam] => d ) echo '_'.$arr['lam'].'_'; ///_d_ if($arr['lam']!='d'){ $i++; } echo $i; //1 why $i==1? this works expected: <?php $i=0; $arr = array('id' => 123, 'lam' => ' '); $arr['lam'] = preg_replace('/\s+/', 'd', $arr['lam']); print_r($arr); // array ( [id] => 123 [lam] => d ) echo '_'.$arr['lam'].'_'; // _d_ if($arr['lam'] != 'd'){ $i++; } echo $i; // 0 ?> keep in mind regex /\s+/ replace white-space characters. may possible 'd', while 'd', contains other content. don't know goal code, looks should improve regular expression based on input.

javascript - using a variable outside a function in ajax -

how can use variable in function outside function. console.log(response) shows content been fetch php. alert(lng) shows undefined. why? issue script.i have been on while. below script. var lat; var lng ; $.ajax({ type: 'get', url: 'getlocation.php', data: 'param=no' , datatype: 'json', success: function (response) { console.log(response); lat = response.latitude; lng = response.latitude; }, error: function (response){ alert (response); } }); alert( lng); because variable lng not set when code runs line alert(lng) . the ajax call async. means, js engine goes flow: issue http request ( $.ajax... ) (at point, since network operation slow, js engine chooses continue executing following lines. comes after response completes.) runs line alert(lng) .

How to get id from html Objects with Jsoup - Java -

i want find id of html objects jsoup. <object id="gamediv" </object> i tried: string startingurl = "http://www.example.com"; try { doc = jsoup.connect(startingurl) .useragent("mozilla/5.0 (windows nt 6.1; win64; x64; rv:25.0) gecko/20100101 firefox/25.0") .referrer("http://www.google.com") .timeout(1000*5) //it's in milliseconds, means 5 seconds. .get(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } elements = doc.select("object"); (element elem : get){ if (get.attr("id") != null){ system.out.println(get.attr("id")); } } but nothing happens. please? first of can reduce code simple. for (element elem : doc.select("object[id]")) { system.out.println(elem.attr("id")); } secondly if doc doesn't contain object looking for, mean

operators - Reference — What does this symbol mean in PHP? -

what this? this collection of questions come every , syntax in php. community wiki, invited participate in maintaining list. why this? it used hard find questions operators , other syntax tokens.¹ main idea have links existing questions on stack overflow, it's easier reference them, not copy on content php manual. ¹ note: since january 2013, stack overflow does support special characters . surround search terms quotes, e.g. [php] "==" vs "===" what should here? if have been pointed here because have asked such question, please find particular syntax below. linked pages php manual along linked questions answer question then. if so, encouraged upvote answer. list not meant substitute others provided. the list if particular token not listed below, might find in list of parser tokens . & bitwise operators or references what mean start php function ampersand? understanding php & (ampersand, bitwise and) operator php "&

xcode - iOS Swift 1.2 - Primitive Type Comparison Failure -

i have function gets , parses data firebase. have validation "parseusermodel) returns "bool" type if model meets requirements pass. set value validuser of bool type. model i'm pulling passes , returns boolean of true. here's issue happens. if(validuser) { ... code ... } fails though validuser "true". i've played around actual return type , i've tried these things: validuser.boolvalue , setting inside if(validuser.boolvalue) this fails setting if(validuser) { ... code ... } this fails setting if(validuser == true) {..code..} this fails setting if(validuser.boolvalue == true) {code} this fails i'm out of ideas why failing. i'm comparing primitive type (i'm assuming) primitive type. my questions is 'true' keyword in swift not bool object type? why failing when i'm explicitly asking boolvalue? is swift bug should know about? is if statement not doing think should doing? retri

swing - JAVA using JFXPanel in JFrame with mouse listener -

currently having issue cannot jframe , associated jfxpanel pop up/display. have looked @ numerous other examples on site , others of using jfxpanels jframes quite different mine. believe issue may lie in fact using 2 consecutive runnables maybe javafx thread hasnt finished time swing thread tries use components it? appreciated- relevant code below: note: not receiving compilation or runtime errors. issue nothing happens when dialog pop @override protected void onmousedown(mousebutton button, keymodifier keymodifier, int mousex, int mousey) { try { if (mousebutton.left.equals(button)) { featurewrapper closeststationorspanfw = selectionutil.getclosestspanorstation(tomappoint(mousex, mousey)); if (closeststationorspanfw != null) { igeometry shape =

git - What difference between Android Mobile OS and Android Wear OS? -

i downloaded android wear os(lollipop) , compared android mobile os(lollipop). (two full source downloaded android git repositories) result of comparisons, did not find difference.(roughly 98%) if so, difference between android mobile os , android wear os?

java - How to connect to the project jar package for its class without any IDE, using only the command line? -

how connect project jar package class without ide, using command line? i'm going connect jna use external methods. javac -cp lib\*; sample.java java -cp lib\*; sample where folder "lib" contains jar library, "sample" main class

java - Using jOOQs MockResult class in an UPDATE statement for jUnit tests -

i working set unit test cases of dao layer make sure responding in way need to, , need unit test jooq code. running jooq 3.6.1 @ time, , trying use jdbc mocking described in link jooq documentation . my unit testing environment leveraging junit 4.12 , mockito. unfortunately, while works select queries, struggling figure out doing wrong update queries. in non-junit unit testing, know function working (it pretty basic not shocking), able have automated unit tests on piece of code, too. my unit test set in following manner: public class userdaotest { private static userdao userdao; private static logger log = logger.getlogger(userdaotest.class.getname()); private class mymockdataprovider implements mockdataprovider { @override public mockresult[] execute ( mockexecutecontext ctx ) throws sqlexception { dslcontext create = dsl.using(sqldialect.mysql); mockresult[] result = new mockresult[1]; string sql = ctx.sql(); if (

Per-thread items in a Karaf/CXF container -

i need set object created once-per-thread in karaf cxf container, since assume container set multiple service threads. can use threadlocal, there support in blueprint.xml scoping thread? no scope that, prototype (default) , singleton. http://www-01.ibm.com/support/knowledgecenter/sseqtp_8.5.5/com.ibm.websphere.osgi.doc/ae/ca_blueprint_scopes.html viktor

r - Pubishing to rpubs existing html file -

i trying publish rpubs html file generated rmd using knithtml. however, knitting takes long run , not want rerun whole knit process again make minor changes appearance of html document. i cannot seem find publish button moment close html file , reopen again. install package markdown can try code: result <- rpubsupload(title='your title',htmlfile='your_html_file_and_path.html',method=getoption('rpubs.upload.method','auto') a successful upload return 2 values in result , website addresses. copy , paste continueurl browser complete upload. or can use function: browseurl(result$continueurl) to go straight webpage using default browser. note sure there automated way of uploading without using browser way know right now.

javascript - Increment number within string. -

i have simple image viewer on page loads thumbnails underneath. when click thumbnail, swaps thumbnail link main image removing thumbnail folder url so: $('#scroller img').on("click",function(){ $('#main-img').attr('src',$(this).attr('src').replace('t/', '')); }); but want people able click on left , right arrows advance or go one. here code right arrow: $('#rar').on("click",function(){ /*$('#main-img').attr('src',$(this).attr('src').replace(/(\d+)/, function(){return arguments[1]*1+1} ));*/ $('#main-img').attr('src',$(this).attr('src').replace(/\d+/, function(val) { return parseint(val)+1})); }); i think syntax may wrong. isn't working anyway. neither did failed attempt can see commented out. but i'd filecount in image directory , increment 1 in blah/1.jpg until reaches filecount or decrement until reaches 0 left arrow. my filenames

asset pipeline - Rails: "rake aborted! Sass::SyntaxError: File to import not found or unreadable" -

i'm using rails 4.2. in rails project directory, have frontend directory: /railsproject/frontend /railsproject/frontend/styles /railsproject/frontend/styles/main.scss i have added config.assets.paths << rails.root.join("frontend","styles") application.rb . in /railsproject/app/assets/stylesheets/application.css.scss : @import "main.scss"; everything works fine in development mode . but when try precompile production, fails: $ rails_env=production bundle exec rake assets:precompile --trace ** invoke assets:precompile (first_time) ** invoke assets:environment (first_time) ** execute assets:environment ** invoke environment (first_time) ** execute environment ** execute assets:precompile rake aborted! sass::syntaxerror: file import not found or unreadable: main.scss. (sass):17 /users/max/.rbenv/versions/2.2.0/lib/ruby/gems/2.2.0/gems/sass-3.4.15/lib/sass/tree/import_node.rb:67:in `rescue in import' /users/max/.rbenv/versions

xml - How to Parse nodes in datasource return using XAML DataGrid? -

Image
i have odd return webservice proving difficult bind datagrid . here being returned webservice: <new0collection> <new0item> <orno>0010121825</orno> <!-- xml data encoded --> <ponr>&lt;obponr&gt;1&lt;/obponr&gt;&lt;obponr&gt;2&lt;/obponr&gt;&lt;obponr&gt;3&lt;/obponr&gt;</ponr> </new0item> there limitation on our system have encode nested nodes. trying list within list, have been able in datalist rowtemplate . user selects line in datagrid , , sub-list of related items shown. <datagrid name="prodlines_list3" verticalalignment="stretch" horizontalalignment="stretch" itemssource="{binding new0collection}" rowdetailsvisibilitymode="{binding elementname=expandrows_txt,path=text,mode=oneway}" style="{dynamicresource styledatagrid}" headersvisibility="all" autogeneratecolumns="false" rowheade

vb.net - Sending Unicode Characters greater than 0x7F through RS232 -

my application in windows ce 6.0 using compact framework , being used issue remote commands device through rs-232. these commands send using bytes specific hex values, e.g. sending 0x22 0x28 0x00 0x01 command sequence. i'm sending bytes 1 @ time. hex values stored internally in string each command sequence, e.g. "22,28,00,01". i'm sending bytes using following code. dim integer dim sendstring() string dim sendbyte, string dutcommand = "22,0a,00,02,e7,83" 'sample command string sendstring = split(dutcommand, ",") 'split string = 0 ubound(sendstring) 'send each byte after encoding sendbyte = chr(cint("&h" & sendstring(i))) commport.write(sendbyte) next sendbyte being encoded values greater 0x7f last 2 bytes being sent (0xe7 , 0x83) being sent 0x3f, ascii code "?" since it's greater 0x7f. am missing setting comm port handle encoding? there simple method sending data values gre

How to connect to redis with dokku and flask? -

i wanted use redis dokku , flask. first issue installing current version of dokku, using latest version repo now. second problem showing in flask debugger: redis.exceptions.connectionerror connectionerror: error 111 connecting none:6379. connection refused. i set redis url , port in flask: app.config['redis_url'] = 'ip:32768' -----> checking status of redis remote: found image redis/landing remote: checking status...stopped. remote: launching redis/landing...command: docker run -v /home/dokku/.redis/volume-landing:/var/lib/redis -p 6379 -d redis/landing /bin/start_redis.sh -----> setting config vars redis_url: redis://ip:6379 redis_ip: ip redis_port: 6379 any idea? redis_url should set in different way? this code works ok in localhost: https://github.com/kwikiel/bounce (with ['redis_ip'] = '172.

sql - How to optimize select sum() on mysql? -

i have sql, it´s taking 2,5 seconds run. select sum(valorlanca0_.valor_previsto) col_0_0_ cf_valor_lancado_detalhado valorlanca0_ inner join cf_valor_lancado valorlanca1_ on valorlanca0_.id_valor_lancado=valorlanca1_.id_valor_lancado inner join cf_lancamento lancamento2_ on valorlanca1_.id_lancamento=lancamento2_.id_lancamento inner join cf_administracao administra12_ on lancamento2_.id_administracao=administra12_.id_administracao inner join cf_empresa empresa13_ on lancamento2_.id_empresa=empresa13_.id_empresa inner join cf_usuario usuario14_ on lancamento2_.id_usuario_criou=usuario14_.id_usuario left outer join cf_forma_pagamento formapagam9_ on valorlanca1_.id_forma_pagamento=formapagam9_.id_forma_pagamento inner join cf_conta conta10_ on valorlanca1_.id_conta=conta10_.id_conta left outer join cf_fatura fatura11_ on valorlanca1_.id_fatura=fatura11_.id_fatura left outer join cf_categoria categoria3_ on valorlanca0_.id_categoria=categoria3_.id_categoria left outer joi

air - Latest Facebook Graph API > only admin user can login-upload photos -

i'm having issue simple photo upload application whereby 1 user can login-upload images. other user (different facebook account) , permissions errors (user_likes,user_photos) without getting code specific, sound application configuration issue? with latest changes in facebookgraph api, necessary submit app fb review, if kiosk based application (ie not app store or on web).? which permissions necessary upload photo? according documentation, more public_profile , email , user_friends requires submitting app review. https://developers.facebook.com/docs/facebook-login/permissions/v2.4#review in fb application's status&review>status page have made application public , see green icon. part of problem although ios based, not using official sdk (adobe air) , using 3d party native extension interacting facebook. you not need go under login review if app used it's admins/testers/developers. if used other users , uses extended permissions, such pub

javascript - AngularJS ng-class not working in ng-repeat with $index -

i have list created ng-repeat works except adding ng-class on condition. <div ng-repeat="glossary in glossarysections" class="alphabet" ng-click="glossarygotosection($index)" ng-class="{'selected',$index == $parent.glossarysection}"> {{glossary.name}} </div> ng-click works, , creates dom way expect to, doesn't add 'selected' class alphabet shown. is there missing in syntax? there syntax error: replace , : . modify ng-class="{'selected': $index == $parent.glossarysection}"> .

triggers - How to check HTTP response code in zabbix? -

i have zabbix server 2.2 , few linux hosts websites. how can notification zabbix, if http(s) response code not 200? i've tried triggers without success: {owncloud:web.test.rspcode[availability of owncloud,owncloud availability].last(,10)}#200 {owncloud:web.test.error[availability of owncloud].count(10,200)}<1 {owncloud:web.test.error[availability of owncloud].last(#1,10)}=200 but nothing works. never got notification, code not 200 anymore 404, because have renamed index.php of owncloud index2.php i found issue. need specify url check file. example in web scenario: https://owncloud.example.com/index.php "note zabbix frontend uses javascript redirect when logging in, first must log in, , in further steps may check logged-in features. additionally, login step must use full url index.php file." - https://www.zabbix.com/documentation/2.4/manual/web_monitoring/example i used following expression trigger: {owncloud:web.test.fai

javascript - Strange spacing in twitter bootstrap top navbar -

Image
i've been using twitter bootstrap create navbar across top of page has several dropdown menus. reason, first list element aligns bottom of bar virtue of empty link fills top space. copied first term other list items, none of other elements align bottom or have empty link. ideas how can fix this? <!doctype html> <html> <head> <title>nav mockup</title> <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="index.css"> </head> <body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script> <div class="navbar navbar-inverse navbar-static-top"> <div class="container">

Downloading zip file using curl (c++) -

i'm trying download zip file using curl localhost server http://localhost:8080/zip/json.zip?assetids=<comma-separated asset ids> when type url on browser file starts downloading no problem. when tried use curl existing zip file : restclient::response restclient::get(const std::string& url) { restclient::response ret = {}; curl *curl = null; curlcode res = curle_ok; file *fp curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, curlopt_url, url.c_str()); char outfilename[filename_max] = "/users/stage/documents/temp/json.zip"; fp = fopen(outfilename,"wb"); curl_easy_setopt(curl, curlopt_cainfo, "./ca-bundle.crt"); curl_easy_setopt(curl, curlopt_ssl_verifypeer, false); curl_easy_setopt(curl, curlopt_ssl_verifyhost, false); curl_easy_setopt(curl, curlopt_writefunction, restclient::write_data); curl_easy_setopt(curl, curlopt_writedata, fp);

batch file - Dealing with the Header Line of the Single/Multiple Coloumn Variable List -

presently have been using below mentioned script activity; if have header of specific variable list, how ignore (first line of variable file)...? setlocal enabledelayedexpansion set /a n=0 set /a m=0 set /a nline=1 set /a mod=0 /f %%i in (c:\variablelist\variable.txt) ( set /a n=m+1 set /a m=n set /a mod=m%%%nline% if !mod! equ 0 ( run -n -d %%i if !errorlevel! neq 0 ( goto end ) ) ) :end endlocal innovative idea, if filter query find c:\windows\system32\find "z", though it's not necessary because it's coming simple query result (for common variable), , use c:\windows\system32\find /v "x/y/z", though it's not require desire result (for not common other variable); magically header part vanished .