Posts

Showing posts from January, 2014

java - Synchronise ArrayList over two threads -

i'm having difficult time understanding how synchronise arraylist on 2 threads. basically, want 1 thread appending objects list , other 1 reading list @ same time. here class deploys threads: public class main { public static arraylist<good> goodlist = new arraylist(); public static void main(string[] args) { thread thread1 = new thread(new goodcreator()); thread thread2 = new thread(new weightcounter()); thread1.start(); thread2.start(); } } then 2 runnable classes: this 1 reads lines of 2 values text file , appends new objects. public class goodcreator implements runnable{ private arraylist<good> goodlist = main.goodlist; private static scanner scan; @override public void run() { system.out.println("thread 1 started"); int objcount = 0; try { scan = new scanner(new file(system.getproperty("user.home") + "//goods.txt")); }

coldfusion - Styling a cfcontent which produced an excel sheet with an external stylesheet -

i trying incorporate stylesheet cfcontent tag produce excel spreadsheet shown below. however, stylesheet ignored when linked explicit reference. ensure excel spreadsheet incorporate stylesheet? <cfsetting enablecfoutputonly="yes"> <cfsavecontent variable="stest"> <cfoutput> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="www.somesite.com/bootstrap/another.css" media="all"> <link rel="stylesheet" type="text/css" href="../cssbootstrap/css/another.css" media="all"> </head> <body> <cfinclude template="../reports/reportexportedasexcel.cfm"> </body> </cfoutput> </cfsavecontent> <cfcontent type="application/vnd.

date - D3 time.parse with colon in time-zone format -

i'm trying use d3.time.format on date this: 2016-02-10t12:40:16-05:00 basically, utc date timezone offset. the issue is, %z formatter in d3 looks timezone written follows: -0500 . in other words, colon missing. does know workaround?

wpf - Binding datacontext viewmodel to usercontrol view when using Mvvm -

i need binding viewmodel 2 usercontrol views have created. have created reservation window should contain these 2 usercontrols. what got: reservationview (window) reservationlistview (usercontrol) reservationdetailview (usercontrol) reservationview (window) class public partial class reservationview : window { public reservationview() { initializecomponent(); //datacontext = null; } } reservationlistview (usercontrol) class: public partial class reservationlistview : usercontrol, iviewreservationlistviewmodel { public reservationlistview(iviewreservationlistviewmodel viewmodel) { initializecomponent(); datacontext = viewmodel; } } the iviewreservationlistviewmodel empty interface makes contact between usercontrol view , viewmodel. reservationlistviewmodel public class reservationlistviewmodel : inotifypropertychanged, iviewreservationlistviewmodel { public reservationlistviewmodel()

Combine multiple tables to act as a single table on BigQuery? -

i have several tables same schema on bigquery: dataset.table00 dataset.table01 dataset.table02 ... dataset.table99 i want make table dataset.table combines tables together. you can use comma union all feature of bigquery select * dataset.table00, dataset.table01, dataset.table02, ... dataset.table98, dataset.table99 you can save above view , use select * myview you can use table wildcard functions select * table_query([project:dataset], 'regexp_match(table_id, r"^table[\d]{2}")')

php - How to run Multiple querys at the same time? -

i stuck @ point want run multiple queries cannot it. i have code https://gyazo.com/d98f6e68c9c6d4e09620e96a29f3f910 have there 4 queries want run @ same time don't know how it, read lot of other questions on forum already. can separate them of ; signs or use mysqli_multi_query .. don't know anymore. here printscreen of mysql db: https://gyazo.com/15ae4be5831665064b2cf8b4f703f3f3 and connection code: define('db_host', 'localhost'); define('db_user', 'root'); define('db_pass', ''); define('db_name', 'mysql_enquete'); $db_link = mysqli_connect(db_host, db_user, db_pass, db_name) or die ("verbindingsfout"); $mysqli = new mysqli(db_host, db_user, db_pass, db_name); if (mysqli_connect_errno()) { printf("connect failed: %s\n", mysqli_connect_error()); exit(); } if ($result = $mysqli->query("select database()")) { $row = $result->fetch_row(); printf(

c# - Error on CSV to Dictionary -

not sure why isn't working, it's adapted code work. looks need explicit cast i'm not sure why or put it. error is: "cannot implicitly convert type 'system.collections.generic.ienumerable{system.collections.generic.dictionary{string,string}}' 'system.collections.generic.dictionary{string,string}'" public static dictionary<string, string> data_entry(string dataentity, string datacategory, string datastream = "") { var lines = file.readalllines(@"c:\myfile.csv"); var header = lines.first().split(','); return (from line in lines.skip(1) let cols = line.split(',') cols[0].toupper() == dataentity & cols[1].toupper() == datacategory & cols[4].toupper() == datastream select header.select((h, i) => new { header = h, index = }) .todictionary(o => o.header, o => cols[o.index]) ); } your lin

javascript - check checkbox based on dropdown -

i wondering if there way auto check boxes based on value dropdown selection. have been searching forever , can seem find ways show or hide checkboxes based on dropdown not looking for. you can pretty jquery. code listens change event dropdown id="dropdown" , checks checkbox id="checkbox" if dropdown text equal 'foo'. $("#dropdown").change(function() { if($('#dropdown :selected').text() === 'foo') $('#checkbox').prop('checked', true); }); if want uncheck box when selection changed again might better: $("#dropdown").change(function() { var text = $('#dropdown :selected').text(); $('#checkbox').prop('checked', text === 'foo'); }); fiddle

javascript - Using Parameters on a Google Drive API request? -

i trying make request on google drive api, , had questions. want search specific folder files, use q parameter in request follows, string (in case called example ): var request = gapi.client.drive.files.list({ 'q': "'example' in parents" }); now, if want same thing, instead pass parameter in call, follows, not work. var test = 'example' var request = gapi.client.drive.files.list({ 'q': "'test' in parents" }); is there way can pass variable api call? its returning 400 because you're not following right syntax using q . search files section of documentation discusses this. basically, q needs have name, operator , value passed have valid query. hopefully helps issue. happy coding!

c - Can't exitThread with waitForMultipleObjects -

i have 2 threads, first doing:` while(1){ if(recv(conn_s, (char*) &i, sizeof(i),0)>0){ if(i==28){ setevent(event); //printf("nell if di 28\n"); handle t; sleep(1); //terminatethread(scegli, 0); //if (closehandle(scegli)==0) printf("error close\n"); t=createthread(null, 0, (lpthread_start_routine) avvia_conversazionecl, conn, synchronize, 0); waitforsingleobject(t, infinite); the second one: const handle handles[2]={event, stdinhandle}; while(1){ switch(waitformultipleobjects(num, handles, false, 0)){ case 0: exitthread(-1); break; case 1: r=readconsole(stdinhandle, &interlocutore, nlength, &charsread, null); if (r==0){

What is the Sandbox Endpoints to test paypal TLS 1.2 and HTTP/1.1 Upgrade -

we using payflowpro make credit card payments. the current production url payflowpro.paypal.com current test url pilot-payflowpro.paypal.com paypal doing tls 1.2 , http/1.1 upgrade , provides few endpoint sandboxs: api.sandbox.paypal.com api-3t.sandbox.paypal.com api-aa.sandbox.paypal.com api-aa-3t.sandbox.paypal.com svcs.sandbox.paypal.com pointofsale.sandbox.paypal.com ipnpb.sandbox.paypal.com www.sandbox.paypal.com which 1 applicable payflowpro? thanks! ct

vb.net - How does "Overloads" work in a child class? -

i have base class , child class , both have same property , don't understand why vb wants me use "overloads" property in child class. difference child class version of property shared while parent class there structure. properties this: public mustinherit class parent public readonly property species string return "should species child." end end property end class public class child inherits parent public shared readonly property species string return "species1" end end property end class species flagged in line public shared readonly property species string in child class warning message property 'species' shadows overloadable member declared in base class 'parent'. if want overload base method, method must declared 'overloads'. what want know why want overloaded? overloading typically used when different parameters being

javascript - How do I populate textbox from a combobox selected -

i want combobox populates database column, when user selects option combobox populate textboxes, on same page, information related selection in combobox. below code used populate textbox when selected select nama dropdown combobox. doesnt work, textbox still blank. have drop down working , fills javascript array using names cannot work out how use array show in fields. i understand have use javascript , onchange function, can point me in right direction? cheers , thank in advance :) <script src="js/jquery.js"></script> <script type="text/javascript"> var selected = new array(); <?php $query1 = "select * inventori"; $result1 = mysql_query($query1) or die(mysql_error()); // build javascript array while($row1=mysql_fetch_array($result1)){ echo 'selected['.$row1['selectnama'].'] = new array();&#

r - smooth.spline(): fitted model does not match user-specified degree of freedom -

Image
here code ran fun <- function(x) {1 + 3*sin(4*pi*x-pi)} set.seed(1) num.samples <- 1000 x <- runif(num.samples) y <- fun(x) + rnorm(num.samples) * 1.5 fit <- smooth.spline(x, y, all.knots=true, df=3) despite df=3 , when checked fitted model, output was call: smooth.spline(x = x, y = y, df = 3, all.knots = true) smoothing parameter spar= 1.499954 lambda= 0.002508571 (26 iterations) equivalent degrees of freedom (df): 9.86422 could please help? thanks! note r-3.4.0 (2017-04-21), smooth.spline can accept direct specification of λ newly added argument lambda . still converted internal 1 spar during estimation. following answer not affected. smoothing parameter λ / spar lies in centre of smoothness control smoothness controlled smoothing parameter λ . smooth.spline() uses internal smoothing parameter spar rather λ : spar = s0 + 0.0601 * log(λ) such logarithm transform necessary in order unconstrained minimization, gcv/cv. user can speci

android.support.v4.app.Fragment.mFragmentManager' on a null object reference -

i have follow lines of code using create navigationview load fragments , android application. getting error: android.support.v4.app.fragment.mfragmentmanager' on null object reference . created fragments , navigationview works. public void selectdraweritem(menuitem menuitem){ fragment fragment = null; class fragmentclass = null; switch(menuitem.getitemid()){ case r.id.nav_show_all_events_activity: fragmentclass = alleventsfragment.class; break; case r.id.nav_whats_hot_today_activity: fragmentclass = whatshotfragment.class; break; } try { fragment = (fragment) fragmentclass.newinstance(); } catch (exception e) { e.printstacktrace(); } fragmentmanager fragmentmanager = getsupportfragmentmanager(); fragmentmanager.begintransaction().replace(r.id.flcontent, fragment).commit(); menuitem.setchecked(true); settitle(menuitem.gettitle()); mdrawer.closedr

java - How can I get an OptimsticLockException instead of a StaleObjectStateException in Hibernate 4? -

the desire catch ole instead of sose less tightly coupled hibernate in case ever needed change jpa providers. the case producing exception straightforward; i've breakpointed before versioned entity update committed, committed change directly in db, , allowed execution continue. it looks staleobjectstateexception vs optimisticlockexception answer should "use jpa annotations", doing that. specifically, entity in question imports annotations javax.persistence.* it turns out because using hibernate session objects rather entitymanagers - hibernate doesn't check jpa annotations (and wrap soses in oles if present) unless entitymanager being used. we can't fix because dropwizard uses sessions, understand why happening , happen consistently, can catch sose , issue resolved.

string - how to take char input before int input in java? -

public class pack1 { public static void main(string ar[]) throws ioexception { bufferedreader br = new bufferedreader(new inputstreamreader(system.in)); system.out.println("enter character"); char c=(char)br.read(); system.out.println(c); system.out.println("enter integer"); long l=integer.parseint(br.readline()); system.out.println("long l="+l); system.out.println(c); } } let's user types x , presses enter on first question, types 123 , presses enter on second question, mean input stream contains following characters: x <cr> 1 2 3 <cr> when call read() , read x . when call readline() , read <cr> , blank string back. the 1 2 3 <cr> still sitting unread in input stream. solution: call readline() after reading x skip past rest of line, or use readline() read x string , instead of char . fyi: exact same problem people keep having when

javascript - Getting the host URL + the destination URL when -

i using ajax post call data file located on other server, getting host url + destination url url ajax url! my host url: 192.168.1.2 my destination url: 192.168.1.7/var/www/html/pfe/ajax.php how destination url only? var url = "192.168.1.7/var/www/html/pfe/ajax.php"; $("#c1.on").click(function () { $.ajax({ url: url, type: 'post', data: { on : true, pin : 16 }, success: function(data){ $("#c1.on").addclass("hide"); $("#c1.off").removeclass("hide"); } }); }); the url get: 192.168.1.2/192.168.1.7/var/www/html/pfe/ajax.php the url syntax incorrect. if url doesn't have // in it, it's treated filename on same server current page. should be: var url = "//192.168.1.7/var/www/html/pfe/ajax.php"; the // indicates next component name or address of server. not still may not work because of restriction again

excel - Delete row if 2 conditions are met - change in time and same value in another column -

i trying code loop in excel vba following: i have column long date + time. have column has text string. i want delete entire row if change in time (row - row above) less 0:00:05 , value of string same (row vs row above) i'm running problems if condition, 5 second portion, doesn't it... for lrow = lastrow firstrow step -1 'we check values in d column .cells(lrow, "d") if not iserror(.value) if (cells(i,"d") - cells(i-1,"d")) > (0:00:05) , (cells.value(i,"f") = cells.value(i-1,"f") .entirerow.delete end if end next lrow ok, code above sucks. going explore different tack. want compare column f - current cell 1 below it. if same, trigger next clause - seeing if current cell in d < 0:00:05 seconds different 1 below it, if so, delete (or store information delete outside loop). if 2 cells in f not same, skip next cell. that make more sense? let me work

ssl - PHP - Getting more info on failed stream_socket_accept() requests -

i’ve got php communications server running using stream_socket_server() , stream_socket_accept(), complicated thing uses ssl connections , certificates remote side authorized connect server. 1 of things coming in logs failed connections. i’m trying provide more details on these connections security purposes. i’m getting of error detail on failed connections setting error handler stream_socket_accept() call: public function on_ssa_error($errno, $errstr) { $this->ssa_error .= " error [$errno]: $errstr\n"; } public function on_select_read() { $this->ssa_error = ""; set_error_handler(array($this, "on_ssa_error")); $rsocket = stream_socket_accept($this->ss, 0); restore_error_handler(); if ($rsocket !== false) // finish setting socket connection , start using else // report error in $this->ssa_error } …when have failed connection, tend errors this: error [2]: stream_socke

Tcl parsing for a command output exits without giving any output -

i trying write script parse following output - dev1# show stats 20:01:02-180 (stats) id=1a2b3c work stats -- -- -------- overall -------- t1 t2 total t5 t6 total container 3 3 0 3 3 3 operatioms 3 3 0 3 3 3 docker 3 3 0 3 3 3 tcl 3 3 0 3 3 3 app 3 3 0 3 3 3 external 1 4 0 intra 2 6 0 incoming locks 8 6 0 outgoing locks 4 3 0 race-condition times 10 20 23 threads/usage 45 56 70 power 2.3 10 consumption 20.3% 29% ----------------------------------------------------------------------- separate command ----------------------------------------------------------------------- dev1# show usage 20:01:08-100 os: 48270 % core: 4524 %

python 3.x - Django Admin, how to replace the user status sign -

Image
in django admin, super user column, showing these 2 signs how can replace them text? you can define model admin method returns text require, include in list_display . class myuseradmin(useradmin): def is_superuser_text(self, obj): return 'true' if obj.is_superuser else 'false' is_superuser_text.short_description = 'is superuser' is_superuser_text.admin_order_field = 'is_superuser' list_display = ('username', 'first_name', 'email', 'date_joined', 'is_superuser_text',)

osx - Trouble Installing Homebrew on Mac -

i having trouble installing homebrew on mac. running mac os x 10.8.4. when try install through ruby -e "$(curl -fssl https://raw.github.com/mxcl/homebrew/go)" or: ruby <(curl -fsskl raw.github.com/mxcl/homebrew/go) i get: \-bash: curl: command not found -bash: ruby: command not found i have tried: cd /usr/local/bin mkdir homebrew && curl -l https://github.com/mxcl/homebrew/tarball/master | tar xz --strip 1 -c homebrew and got: -bash: mkdir: command not found what think may wrong>

.net - Emulating keyboard enter key in C# -

i trying emulate various tasks in win7 , have problems function : leftmouseclick(cursor.position.x - 720, cursor.position.y - 45); system.threading.thread.sleep(1000); // simulate each key stroke inputsimulator.simulatekeydown(virtualkeycode.return); inputsimulator.simulatekeyup(virtualkeycode.return); inputsimulator.simulatetextentry("cmd"); system.threading.thread.sleep(1000); inputsimulator.simulatekeydown(virtualkeycode.return); inputsimulator.simulatekeyup(virtualkeycode.return); all want press start, write cmd, hit enter. works smooth except hitting enter key. all of happening on rdp activex, here code : var client = (imsrdpclient7)rdp.getocx(); // client.remoteprogram2.remoteprogrammode = true; ((mstsclib.imsrdpclientadvancedsettings5)rdp.advancedsettings).displayconnectionbar = true; ((mstsclib.imsrdpclientadvancedsettings5)rdp.advancedsettings).connectionbarshowpinbutton = true; ((mstsclib.imsrdpclientadvancedsettings5)rdp.advancedsettings).bitmap

parallel processing - what are the models to distribute tasks in processes using openMPI? -

the thing want ask : have several steps of big source code (each step has virtual computation time , virtual communication data,i taking virtual wants model latency , somehow managed measure them throughout source code) . need test make code sleep computation time , transferring data equivalent communication data . can suggest configuration models same ? aim minimizing overall execution time of program , want diminish overhead process can have. the simplest strikes mind : do computation on processes , send virtual data making asynchronous call root processes do same synchronous call . assume communication time linear communication data . use algorithm divide tasks formerly each process (inspired load balancing) start first task root process , sends data next process , sleep on process , show on. can please give me idea or verify ,if strategy makes lot of difference ?

javascript - Uncaught TypeError: DB.find is not a function in React with Meteor 1.3 -

i'm using meteor 1.3 react , got error. if use console in browser works perfectly. import react, {component} 'react'; import trackerreact 'meteor/ultimatejs:tracker-react'; import toolsform './toolsform.jsx'; import toolscards './toolscards.jsx'; export default class tools extends trackerreact(component) { constructor(){ super(); this.state = { subscriptions: { tools: meteor.subscribe('alltools') } } } componentwillunmount() { this.state.subscriptions.tools.stop(); } tools() { return tools.find().fetch(); } render() { return ( <div> <toolsform /> <br/><br/> <ul classname="resolutions"> {this.tools().map( (tool)=> { return <toolscards key={tool._id} tool={tool} />

How do I use a SelectListItem in ASP.NET MVC to display choices via a List Box or Check List box -

i've been reading several articles how present choices users. use listboxfor, use checkboxfor, , there thing called multiselectlist. what (was) confused each example seemed have done totally different way, , none of them used built in "selectlistitem" class instead created own. so going post question asking general clarification, thought representative of other various post , repetitive. so let me re-phrase: how use "list" or "multiselectlist" present user list of choices, including option them displayed list of check boxes? in other words, if have following 2 items in model, how display each of them typical choice list box, or typical check list box? public list<selectlistitem> widgets1 { get; set; } public multiselectlist widgets2 { get; set; } warning... wanted point out "checkbox" option hangs once many choices. (e.g. changed loop 500) , won't submit. the problem traced validation of checkboxfor line. ca

vi - vim using line back in register -

i register this: a b so typed : let @c='a^mb' , tried \r , \n instead of ^m when type "cp vim not consider return line chars. update : i running vim 7.4.52 on 3.16.0-38-generic #52~14.04.1-ubuntu :let @c="a\n\nb" seems working fine me on vim7.4 on freebsd. (double quotes instead of single quotes) if it's not working, might want specify platform , version of vim?

Using 'require' package code to obtain datapackages on the fly in R -

i writing r package uses variety of bioconductor annotation data packages. specific data packages vary use-case. such, have function this: if (!require(biocpack_name, character.only=t)) { source("https://bioconductor.org/bioclite.r") biocinstaller::bioclite(biocpack_name) require(biocpack_name , character.only=t) } biocpack_name can several of ~30+ annotation data packages looked based on particular data being analysed. such, don't want have add each 'suggests' (im not sure work because error not package rather string specifying package). r cmd chk gives me error: 'library' or 'require' call not declared from: ‘biocpack_name’ 'library' or 'require' call ‘biocpack_name’ in package code. how around this? it's not error, warning. goes away if use character.only = true rather t (i guess because value of true known , cannot re-assigned, t unknown , can anything, including false). in addition follow

css - Checking if mouse is over something in jQuery? -

i have found other people have asked in past told use :hover , doesn't exist anymore. there way boolean out of .hover() ? i'm using .hover() in order make div appear when mouseover button, , disappears when mouseout . however, add check, div won't disappear unless mouse not on button , mouse out of div . something should work... var $in_div = 0; $("div").mouseenter( function(){ $in_div = 1; }).mouseleave( function(){ $in_div = 0; }); $("button").mouseenter( function(){ $("div").show(); }).mouseleave( function(){ if ( $in_div == 1 ) { $("div").hide() } }); this method use, delaying hide 500ms, can interrupt if want (in case, if user leaves button enters div). var $delay = 0; $("button").mouseenter( function(){ cleartimeout( $delay ); // don't hide $("div").show(); }).mouseleave( function(){ $delay = settimeout( function(){ $("div").hide() }, 500 );

jquery - export SVG to PNG with image inside SVG -

i trying make website can draw image on top of image using raphael.js. drawing parts finished, , able export lines png. insert images svg raphael generates function paper.image() ; unfortunately export function doesn't include imported image. these scripts i'm using, don't think use them all. <script src="../jquery-2.0.1.min.js"></script> <script src="raphael-min.js"></script> <script src="rgbcolor.js"></script> <script src="canvg.js"></script> <script src="stackblur.js"></script> <script src="svg.min.js"></script> here's export-function $('#save').onmousedown... var canvas = document.getelementbyid('canvas2'); var svg = document.getelementbyid('canvas'); svg = svg.innerhtml; canvg(canvas, svg); var img_url = canvas.todataurl('image/png'); $('#converted_image').attr('src', img_url

javascript - Electron and Babel 6 async / await throw unexpected token -

i want use async / await feature es7 in electron app, seems not working. gives me syntax error: unexpected token function after command npm start .. electron: v0.37.6 node: v5.11.0 stable windows 10 x64 main.js 'use strict'; require("babel-core/register"); require("babel-polyfill"); (async function() { await console.log("test"); })() package.json (snipped) "devdependencies": { "babel": "^6.5.2", "babel-cli": "^6.7.7", "babel-core": "^6.7.7", "babel-eslint": "^6.0.3", "babel-plugin-syntax-async-functions": "^6.5.0", "babel-plugin-transform-async-to-generator": "^6.7.4", "babel-plugin-transform-regenerator": "^6.6.5", "babel-polyfill": "^6.7.4", "babel-preset-es2015": "^6.6.0", "babel-preset-stage-3": "

javascript - Uncaught Error: [$injector:modulerr] when using ng-repeat -

angular.module('app',[]) .controller('myctrl',function() { this.items = m; }); var m = { "india": "4", "england": "2", "brazil": "3", "uk": "1", "usa": "3", "syria": "2" }; <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script> <body> <h3>fifa mactch summary:</h3> <div ng-app='app' ng-controller="myctrl"> <ul> <li ng-repeat="(country,goals) in items">{{country}}: {{goals}}</li> </ul> </div> </body> above code. when run it, got uncaught error [$injector:modulerr] error. can not figure out why error. me? appreciate that. in order access angular properties in dom, need establish scope , inject $scope

typescript - Undefined with class implementing abstract class -

i'm not expert in javascript, , i'm conscious issue follow typescript code starts there. i'm stuck here in last 36 hours, in typescript i'm having undefined issues , let code explain rest: window.onload = () => { var = new ipropindex(new ipropservice()); }; interface iidocservice<t> { getsingle(): ipropdoc; } class ipropservice implements iidocservice<t> { getsingle(): ipropdoc { return new ipropdoc(); } } abstract class idocindex<t> { constructor(public _idoctype: string, public _iidocservice: iidocservice<t>) { console.log(this._idoctype); //not undefined this.methodb(); } public abstract methoda(); public methodb() { this.methoda(this.methodc); //**undefined** } public methodc() { console.log(this._idoctype); } } class ipropindex extends idocindex<ipropdoc> { constructor(public _ipropservice: ipropservice) { super('iprop', _ipropservic

c# - How to optimize and speed up this operation -

list<customer> customers = getcustomers("act"); foreach(var customer in customers) { savecustomerdata (customer); } now in operation - list of customers object, in thousands save each customer object in database, 1 one. there way speed or make parallel in someway achieve performance , right result. list<customer> customers = getcustomers("act"); task[] tasks = new task[maxnumofconcurrentsaves]; while(customers.length > 0) { for(int = 0; < maxnumofconcurrenttasks; i++){ tasks[i] = savecustomerdata(customers[i]); customers[i] = null; } customers = list.findall<customer>(customers, acust => !(acust == null)); task.awaitall(tasks) } ok here's whats happening (and you'll have perfect uses): while have customers in list, every 1 of them starting @ begining through max number of concurrent tasks, start task save , set customer null. then, after loop over, find customer entries

c++ - Program to create a number of threads based on user input not working (cin)? -

my apologies if question looks simple. i'm still learning threads. tried searching solution on here didn't find any. i'm trying program create number of threads based on user input (ex: "cin >> 5" create 5 threads) says "i" in "threads mythreads[ ]" needs constant value. code below: void exec(int n) { cout << "thread " << n << endl; } int main() { int numthreads = 0; // create threads cin >> numthreads; thread mythreads[numthreads]; // part says mythreads "must constant value" (int = 0; < numthreads; i++) { mythreads[i] = thread(exec, i); } (int = 0; < numthreads; i++) { mythreads[i].join(); } cout << "done!" << endl; } any ideas how section can fixed? i've tried few different ways haven't worked far. thank much. there's no problem multithreading. problem stat

javascript - Why is my browser forcing the script tag inside the body tag? -

i'm trying learn javascript beginning understand it. what i'm trying here output nodetypes of each element found in <body> tag. understand there invisible texts between <body> 's child elements unknown reason, makes output 3 1 3 1 i put <script> tag outside <body> tag, it's still being counted in for loop, resulted last digit of 1 in 3 1 3 1 loop sequence. why? why <script> tag being forced inside <body> tag browser? <html> <body id = "bodytest"> <p>some text</p> </body> <script type="text/javascript"> var c = document.body.childnodes; var txt = ""; for(var k = 0; k < c.length; k++) { txt += c[k].nodetype + " "; console.log(txt); console.log(c[k].nodename); } alert(txt); </script> </html> here code using. <html>

ios - NSBundle.mainBundle().pathForResource() why not enter in section of if? -

Image
nsbundle.mainbundle().pathforresource() why not enter in section of if? the argument oftype parameter of pathforresource function needs filename extension, not mime-type. want "xml" , not "text/xml" .

python - pdfminer - import error -

i’m new python , programming in general. i trying install pdfminer. have windows 7 python 2.7 installed. followed instructions when installing (downloaded pdfminer source, unpacked it, , ran setup.py install , installed in c:\pdfminer ) – no errors. it created: build , build\lib,build\lib\pdfminer , copied files build\lib\pdfminer . created build\scripts-2.7 , copied tools\pdf2txt.py , dymppdf.py scripts , wrote install-egg-info , had no errors install. when try running test document command line: c:\pdfminer\pdfminer-20140328> pdf2txt.py samples/simple1.pdf i get: file “c:\python27\scripts\pdf2txt.py”, line3, in <module> pdfminer.pdfdocument import pdfdocument importerror: no module named pdfminer.pdfdocument i saw post: pdfminer - importerror: no module named pdfminer.pdfdocument and tried following (#1..put sys.path.append… pdf2txt.py ) , same error. the system variables include path ( pdfminer\pdfminer-20140328 ). i’ve looked other soluti

java - Does curl remove new line characters? -

i'm posting text file contains list on multiple lines service via curl. when read body of request in spring mvc controller there no new line characters , text on 1 line. does curl remove new line characters? there way maintain new line characters need them parse text. here snippet code using read post body: stringbuilder builder = new stringbuilder(); string line = null; try { bufferedreader reader = request.getreader(); while ((line = reader.readline()) != null) {// 1 line of text! builder.append(line); } } catch (exception e) { //handle exception } yes, curl removes linebreaks data posted -d option. use --data-binary instead. see question how send line break curl? more info.

Adding images to array java -

this question has answer here: variable length (dynamic) arrays in java 9 answers i have array of images created in java, code creates more, id add them created array. methods available add these new images array? java arrays fixed size; once have array cannot resize it. system.arraycopy() allows copy contents of array new (potentially larger) array, manual. the collections api provides number of higher-level data structures more user-friendly arrays, including list interface defines api similar arrays has many additional features including ability resized, , arraylist , list implementation backed arrays under covers. in short, if need resizable array, want arraylist .

Java runtime pg_dump with log -

i'm running pg_dump in java runtime using command: final static string cmd = "/usr/lib/postgresql/9.3/bin/pg_dump -u jboss -v wsemp0316 -f /home/test/test.pg_dump -f /home/test/test.log"; problem not create file test.pg_dump throws actual data test.log. i'm guessing -f used twice using 1> , 2> throws error. encountered this? maybe should take @ pg_dump documentation . -f file --file=file send output specified file. parameter can omitted file based output formats, in case standard output used. must given directory output format however, specifies target directory instead of file. in case directory created pg_dump , must not exist before. my understanding parameter -f should used once.

amazon web services - Shortest path - Giraph example - Not working on AWS -

i'm having problems running shortest path example on aws. downloaded giraph jar through s3 (compiled inside same ami i'm using , uploaded there ) , configured correctly zookeper in both master , slave, , did following steps: nano /tmp/tiny_graph.txt [0,0,[1,1,3,3]] [1,0,[0,1,2,2,3,1]] [2,0,[1,2,4,4]] [3,0,[0,3,1,1,4,4]] [4,0,[3,4,2,4]] hdfs dfs -mkdir /user/hduser /home/hadoop/bin/hdfs dfs -copyfromlocal /tmp/tiny_graph.txt /user/tiny_graph.txt hdfs dfs -mkdir /user/hduser/output /home/hadoop/bin/yarn jar /home/hadoop/share/hadoop/yarn/lib/giraph.jar org.apache.giraph.giraphrunner org.apache.giraph.examples.simpleshortestpathscomputation -vif org.apache.giraph.io.formats.jsonlongdoublefloatdoublevertexinputformat -vip /user/hduser/input/tiny_graph.txt -vof org.apache.giraph.io.formats.idwithvaluetextoutputformat -op /user/hduser/output/shortestpaths -w 2 the console show me , don't have clue of what's happening: slf4j: class path contains multiple slf4

python - Replacing an even element with another element -

i having trouble part class assignment. ask replace element 0. have tried kept getting error trying divide in anyway. there way replace numbers 0, might end adding user input later on, have code finds number , replace it. def main(): list = [7, 2, 2, 4, 5, 6, 9] print(sectionc(list)) def sectionc(list): n, in list: if list == i//2: list[n]=0 main() the errors you're facing your function returns nothing. if want result of function visible , accessible once finished, have return it, otherwise function return none default. while true mutable objects lists passed reference, modifying them inside function modifies them everywhere, idea explicitly return value. you should never name variable list . list() inbuilt function in python, , declaring variable same name, lose ability call it. change variable more appropriate - collection works, instance. n, in list doesn't work - lists let iterate through 1 element. for in

tensorflow - Scaling performance across multi GPUs -

i've been running cifar 10 model in tensorflow tutorials train across multiple gpus. source: https://github.com/tensorflow/tensorflow/blob/r0.8/tensorflow/models/image/cifar10/cifar10_multi_gpu_train.py gpus: nvidia 8 * m40 configuration: tensorflow 0.8.0 , cuda 7.5, cudnn 4 the result of training performance not scalable expected. pattern of graph looks amdahl's law. the chart of scaling performance across multi gpus is normal? if is, see main cause of that? try gpu utilization high can (>80%). data disk not delivered fast enough, gpus idle of time.

node.js - Ember.js data records shows content: null in relationships inspector -

i have following code in 'user.js' model in ember-data: export default ds.model.extend({ organization: ds.belongsto('organization'), //other stuff }); the crud website working expected, , in mongodb can see following organization field of user: "organization" : objectid("571974742ce868d575b79d6a"), but, , i'm not sure if error in code or me not understanding how ember-data works, cannot access id model hook so: model(){ return this.store.findrecord("user", this.get("session.currentuser.id")) .then(user => this.store.findrecord("location", {organization: user.organization})); } and if go ember inspector observe belongsto attribute of user object, see: organization: <(subclass of ember.objectproxy):ember956> but clicking through see content: null what doing wrong? server-side error? edit including json response server above findrecord("user") call:

javascript - is this an efficient way to parseInt? -

is best way convert string int in while loop?i think code in parseint inefficient way because makes computer parseint everytime until dowhile loop true function randomupper(upper) { return math.floor(math.random() * upper) + 1 } var limit = 10; var guess; var randomnumber = randomupper(limit); var guessmade = 0; do{ guess = prompt("guess number"); guess = parseint(guess); guessmade++; } while (guess !== randomnumber); document.write(guessmade) javascript such high level language things string integer type coercions don't put stress on language. you can't avoid type coercion either. compare string integer properly, @ point have same type (loose comparison aside), meaning have convert manually strict comparison won't compare otherwise. this shouldn't concern, when you're using prompt , user input function awaits feedback browser window. that's whole lot more expensive string integer conversion.

c# - Weird division by zero error -

Image
well, im trying calculate slope of line, , naturally, when point becomes undefined when try divide zero. handle in try catch , still getting division 0 error, in rather... unexpected spot... here code: private void tmrenemymovement_tick(object sender, eventargs e) { (int = 0; < enemies.count; i++) { int enex = enemies[i].getenemyworldposx(); int eney = enemies[i].getenemyworldposy(); int playerx = player.getplayerworldposx(); int playery = player.getplayerworldposy(); double slope = -100000000; try { slope = (getdistancebetween(eney, playery)) / (getdistancebetween(enex, playerx)); } catch (dividebyzeroexception) {//division 0 exception handled here. slope = getdistancebetween(eney, playery) / 1; } int multiplicative = 1; int rise = 1;//convert.toint32(slope * multiplicative); int run = multiplicative;

angularjs - How to do intheContextof in javascript so that scope could be changed -

b/c i'm using angular js, have parsing headaches looking @ $rootscope.something is possible function inthecontextof(obj, func){ func.call(obj); } where inthecontextof($rootscope, function(){ flamingo = 5 //$rootscope.flamingo im refering $apply() } you'd have write this: inthecontextof($rootscope, function(){ this.flamingo = 5 //$rootscope.flamingo im refering $apply() } now i'm not sure expect "$apply" here; if it's going implicitly reference "$rootscope" should ok.

html - Inline form with flex, bug in safari -

Image
i create simple inline form flex. in safari found bug - button lose width, here screenshot: in browsers good. how fix bug in safari ? ps: can`t set fixed width on button. here code: <div class="container"> <div class="row"> <div class="col-md-3"> <form action="" class="form-inline-flex"> <div> <input type="text" /> </div> <button type="submit" />subscribe</button> </form> </div> </div> </div> .form-inline-flex{ display: -ms-flexbox; display: -webkit-flex ; display: flex; } button{ display:inline-block; padding: 13px 28px; font-weight: 700; text-align: center; cursor: pointer; border: 1px solid transparent; padding: 13px 20px; font-size: 16px; line-height: 1.375; } input{ display: block; width: 100%; font-size: 14px; padding: 7p