Posts

Showing posts from July, 2011

arrays - Strings are not sequence of characters in java? -

in java, why not possible convert string char array , vice versa? why aren't comparable? char matrixc[][] = {{'s', 't','a', 'c','k'}, {'o','v','e','r'}, {'f','l','o','w'}}; string [] matrixs = {"stack", "over","flow"}; // matrixs=matrixc //not allowed... if (matrixs.equals(matrixc) || matrixc.equals(matrixs) ) { system.out.print("true"); } else system.out.print("false"); //output edited: after research , digging, found answer of first question (why not possible convert string char array , vice versa?) in below link, explained roger_that. hint james. immutable string immutable. meaning? so, have separate string pool in java heap, stores , creates new string literals each time , refer them string objects accordingly. still, have doubts comparison (i talking simple

bash - Perl to substitute string with a string containing spaces and double quotes -

my bash script builds string variable $arraylmes , containing string like: var availabletags=[ "01 east bering sea", "02 gulf of alaska"]; i need put string in javascript code, replace placeholder. thinking use like: perl -i -pe 's/placeholder/'"${arraylmes}"'/' filename but command complains, because of double quotes found in string, messing bash command , in consequence perl command. how can fix command keep spaces , double quotes? use -s switch pass variable perl: perl -spe 's/placeholder/$var/' -- -var="$arraylmes" filename the -- signifies end of command line arguments. -var="$arraylmes" sets perl variable value of shell variable $arraylmes . alternatively, use awk: awk -v var="$arraylmes" '{sub(/placeholder/, var)}1' filename a nice side-effect of using awk replacement simple string, metacharacters in original string won't interpreted.

python - Difference between math.exp(2) and math.e**2 -

this question has answer here: why floating point numbers inaccurate? 3 answers while programming noticed difference between result of math.exp(2) , math.e**2. can see below, difference not arise when calculating e^1. not being experienced programmer, wondered why differs? assume has rounding up. python docs math.exp(x) return e**x , appears not precisely correct. how come math.exp(x) operation differs math.e**x ? >>> math.exp(1) 2.718281828459045 >>> math.e**1 2.718281828459045 >>> math.exp(1)==math.e**1 true >>> math.exp(2) 7.38905609893065 >>> math.e**2 7.3890560989306495 >>> math.exp(2)==math.e**2 false >>> math.exp(100) 2.6881171418161356e+43 >>> math.e**100 2.6881171418161212e+43 >>> math.exp(100)==math.e**100 false it's different due differences in implementatio

javascript - How import a React component from github? -

i'm trying understand how react works. i want use react-chartjs library. ( https://github.com/jhudson8/react-chartjs ). how can import in project? i tried in way: in file mycomponent.js: var lc = react.createclass({ render: function(){ var xfield = this.props.xfield; var yfield = this.props.yfield; var data = { labels: xfield, datasets: [ { label: "my first dataset", fillcolor: "rgba(220,220,220,0.2)", strokecolor: "rgba(220,220,220,1)", pointcolor: "rgba(220,220,220,1)", pointstrokecolor: "#fff", pointhighlightfill: "#fff", pointhighlightstroke: "rgba(220,220,220,1)", data: yfield }] } return( <linechart data={data} width="600" height="250" /> ); }}); var mycomp

entity framework - EF Code First - Multiple Application Versions Sharing A Database -

we have application developed using code first in ef6. running quite happily on our live infrastructure. i have made changes required schema alterations , i've generated appropriate migrations. since application deployed our release process live environment has changed , applications deployed prelive area can validate interaction other applications/services , run tests before application files released live location. the problem migrations alter database schema when application run in prelive , live version of application choke on model compatibility check. how have other people approached issue? is there way of safely running multiple versions of code first application against same database? if can disable model checking, migrations still run when application first starts or have go generating sql change scripts , running them manually? i faced same problem. nick disabled migration in dbcontext , created different project database migration. added below c

php - SQL future dates in request -

i'm trying execute sql request future events. so far, looks : $dql = "select aofvhflybundle:flight precisedate >= now()"; $query = $em->createquery($dql); but following error: line 0, col 59: error: expected known function, got 'now' how can future flights ? the dql function looking current_timestamp() . described in doc .

matlab - How to define a regex that matches whole words treating "." like a normal letter -

i trying read several numbers string in matlab. aim str2num does, without using eval (and less advanced). i have regex matching valid double number: '([-+]?([0-9]*\.[0-9]+|[0-9]+\.|[0-9]+)([ee][-+]?([0-9]*\.[0-9]+|[0-9]+\.|[0-9]+))?)' which works fine valid substrings such "1.15e2.4". problem want avoid matching invalid substrings such "1.15.e2.4" (which splits "1.15" , "2.4"). when match whole words (using \< , \> ), invalid string split "1.15" , "4"), because decimal point considered word binary. for using look-around expressions: '((?<=^|[ :,])[-+]?([0-9]*\.[0-9]+|[0-9]+\.|[0-9]+)([ee][-+]?([0-9]*\.[0-9]+|[0-9]+\.|[0-9]+))?(?=$|[ :,]))' but wonder if there easier , more general way. is possible redefine characters considered word boundaries? you cannot redefine word boundary means. can achieve same effect using negative lookarounds: (?<!\.)\< first regex he

javascript - jade mixin, conditional leave out -

i'm trying make jade mixin. want omit stuff if did not input variable. maybe it's easier explain if show mean in code mixin movie-left-image(title, posterurl, venue, rating, 3d) article h2 strong= title div div

php - default Filtering Sonata admin list without a Filter filed -

i'm using sonata mongodb admin bundle , need filter default list data without filter field . i have 'tenant_id' attribute in model , want show models if tenant_id equal id of connected user. any 1 can ? you can override createquery function of admin class described here, https://sonata-project.org/bundles/admin/master/doc/reference/action_list.html#customizing-the-query-used-to-generate-the-list public function createquery($context = 'list') { $query = parent::createquery($context); $query->field('tenant_id')->equals("your user id"); return $query; }

android - Translucent theme with material -

i'm trying create transitions in application , looks bad since background color of "android:windowbackground" (white) flashing few ms when change activity. managed remove translucent theme (parent="android:theme.translucent.notitlebar"), translucent not seem option when using material theme. there way combine themes?

docusignapi - Incorrect time in envelope summary -

on development server have account configured use est/edt timezone api calls. seems configuration, api calls return date incorrect time. for example, have created envelope @ 12:46 gmt api envelope summary returning following date: 2015-06-10t15:46:25.8165848z if not wrong, time incorrect because z timezone utc , expecting 12:46:25.8165848z. setting timezone api calls pacific time, date returned correct: 2015-06-10t12:46:25.8165848z am using api correctly? for example api call: get https://demo.docusign.net/restapi/v2/accounts/917973/envelopes/b7c31971-53e1-417e-b132-e27514befdcf/audit_events http/1.1 returns incorrect time audit events when user configured timezone not "pacific time". docusign support confirmed @luis-scott wrote. not known when bug fixed.

WPF: how to implement a button that make 2 other buttons visible with fading -

i want implement special button , don't know how start this. i want button 's content property be: play . when clicking on it, want 2 other buttons pop in left , in right sides: single play , parallel play after lot of discussion, here result solve problem: xaml: <window x:class="wpfapplication3.mainwindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:my="clr-namespace:wpfapplication3" title="mainwindow" height="350" width="525"> <grid> <stackpanel orientation="horizontal"> <button name="btnsingleplay" visibility="collapsed" my:visibilityanimation.isactive="true">singleplay</button> <button name="btnplay" click="btnplay_click">play</button> <button name="bt

android - Ripple effect using itemBackground on NavigationView -

Image
i wonder if having problems when redefining background of items on navigationview app:itembackground" ? behavior shown on screenshot, no matter item press last item shows ripple instead. here drawer_menu.xml : <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <group android:checkablebehavior="single" android:id="@+id/first_group"> <item android:id="@+id/nav_home" android:icon="@drawable/ic_home" android:title="@string/nav_home" /> </group> <group android:id="@+id/second_group"> <item android:id="@+id/nav_settings" android:title="@string/nav_settings" /> <item android:id="@+id/nav_about" android:title="@string/nav_about" />

vba - How to edit text in columns? -

the data in column listed have stated below. a b 1 n 2 n 3 n 4 y 5 y 6 n 7 n 8 y 9 y 10 y 11 y 12 y 13 n 14 n i want automate , list first n , no other n till y appears , list first y till next n appears. : a b 1 n 2 3 4 y 5 6 n 7 8 y 9 10 11 12 13 n 14 any apreciated. unless there's tricky way not aware of, you'll need write macro loops through rows in column, checking value change. pseudocode: set compare variable null loop through cells in column read cell if cell value != compare variable compare = new value - leave cell value there else if cell = compare cell value = null end loop let know come with.

How to make a static map in c++? -

i working on 2 files, lets take file1.cpp , file2.cpp. file1.cpp contains: //file 1 #include <iostream> #include <map> struct category { int id; }; void fun(); std::map<char, category> mymap1; static std::map<char, category> mymap; std::map<char, category>::iterator map_iter; std::map<char, category>::iterator map_iter1; int main () { mymap1['a'] = {20}; mymap1['b'] = {30}; mymap1['c'] = {40}; for(int = 0;i < 4; i++) fun(); return 0; } //file 2 #include<file2.h> void fun() { mymap = mymap1; map_iter = mymap.begin(); (map_iter1 = mymap1.begin(); map_iter1 != mymap1.end();++map_iter1) { map_iter->second.id = map_iter1->second.id - map_iter->second.id; std::cout<<map_iter1->second.id<<" " <<map_iter->second.id; map_iter->second.id=map_iter1->second.id; ++map_iter; } }

asp.net - After changing the table Entity Name in EF edmx designer then Not able to Create controller with Scaffolding options? -

i have tbldepartment , tblemployee in database. added entity data model data , changing entities "tbldepartment" "department" , "tblemployee" "employee" . while creating employeecontroller read/write/edit template using entityframework , scaffolding template model entity "employee" not found in dropdown instead shows "tblemployee" in dropdown. please help. thanks, dnyaneshwar build / rebuild solution or project. updates not automatically reflect esp on controllers.

Is it possible to merge 2 web.xml with Maven overlay -

i have web application 'a' defined in war project. created other web application 'b' import whole content of 'a' overlay. the file web.xml of application 'b' same of application 'a', except additionnal listeners. therefore web.xml of b contains lot of duplicated content a. the question : is possible tell maven-war-plugin merge web.xml of , b, instead of replacing web.xml of web.xml of b ?

java - Servlet 3.0 File Upload Handling Exceptions -

i trying use java servlet 3.0 upload files. @webservlet("/uploadfile") @multipartconfig(filesizethreshold=1024*1024*1, // 1 mb maxfilesize=1024*1024*10, // 10 mb maxrequestsize=1024*1024*100) // 100 mb public class fileuploadservlet extends httpservlet { @override protected void dopost(httpservletrequest req, httpservletresponse res) throws servletexception, ioexception { string serveruploaddir = getserveruploaddir(req); part file; try { file = req.getpart("filename"); file.write(serveruploaddir + file.separator + file.getsubmittedfilename()); res.sendredirect("viewdirectory?msg=file uploaded."); } catch (illegalstateexception ex) { system.out.println(ex.getmessage()); } } public string getserveruploaddir(httpservletrequest req) { return req.getparameter("serveruploaddir"); } } it works correctly, when files under maxfilesi

apache spark - Serialization error when using a non-serializable object in driver code -

i'm using spark streaming process stream processing each partition (saving events hbase), ack last event in each rdd driver receiver, receiver can ack source in turn. public class streamprocessor { final ackclient ackclient; public streamprocessor(ackclient ackclient) { this.ackclient = ackclient; } public void process(final javareceiverinputdstream<event> inputdstream) inputdstream.foreachrdd(rdd -> { javardd<event> lastevents = rdd.mappartition(events -> { // ------ code executes on worker ------- // process events 1 one; don't use ackclient here // return event max delivery tag here }); // ------ code executes on driver ------- event lastevent = .. // find event max delivery tag across partitions ackclient.ack(lastevent); // use ackclient ack last event }); } } the problem here following error (even though seems work fine): org.apache.spark.sparkexception: task not seri

colors - Matlab - Using symbols in gscatter -

ok, i'm trying use gscatter plot 8 different points in figure. these 8 points different , want give them different symbols. know gscatter automatically assign them different colors, want able use figure in black , white. have written following code: lincol = {'k';'k';'k';'k';'k';'k';'k';'k'}; linsym = {'+';'o';'*';'.';'x';'s';'d';'^'}; limits = [-1 1 -1 1]; close = 1:3; figure(i); hold on gscatter(rfootxdistpertrel(:,i),rfootydistpertrel(:,i),lincol,linsym); legend('pert1', 'pert2', 'pert3', 'pert4', 'pert5', 'pert6', 'pert7', 'pert8') hline(0); vline(0); axis(limits); end according matlab syntax, should able specify color , marker symbol in way (gscatter(x,y,col,sym)). variables used 8 1 vectors, lincol , linsym. however, gives me error: error using plot color value must 3 or 4 e

atlassian - Hide the "Smart querying activated" message in Jira -

Image
every time search in jira, message pops up: now want smart querying enabled, don't need message every time search, because it's placed on top of buttons... is there way disable this? seems there no way disable this, doesn't happen every search. happens keywords trigger smart querying capabilities. example, word matches status in jira (e.g. open, resolved). a workaround described in jira issue: https://jira.atlassian.com/browse/jra-44561 <script type="text/javascript"> jquery(window).load(function(){ /* hides blank announcement banner div. if using announcement banner already, comment or remove line below */ ajs.$("#announcement-banner").hide(); /* if page issue navigator , running jql query (not filter) checks if there "aui flag container". if there 1 , text "smart querying activated", hides banner. */ if (window.location.pathname.includes("/issues/"

c# - Masstransit temporary queue -

i'm developing client application use masstransit , rabbitmq. on application start i'm creating new queue unique name communication server applications via masstransit(request/response model). on application closing should delete queue, if client application crushes queue present on rabbitmq. is possible create temporary queue via masstransit rabbitmq automatically delete when client disconnects queue? you can create temporary queue using ?temporary=true query string parameter. with rabbitmq, can dynamically create queue name using * queue name. such as: x.receivefrom("rabbitmq://localhost/vhost/*?temporary=true"); this create temporary queue randomly generated name deleted when connection closed.

list - Search file by placement of element in a line -

i trying figure out how pull element file. has 4 elements before have anywhere between none , infinity elements behind it. element pull file named in same spot per line. lines of file formatted so... $(eval $(call createtest, file, keyelement_0 ... $(eval $(call createtest, file, keyelement_1 ... $(eval $(call createtest, file, keyelement_2 ... ... $(eval $(call createtest, file, keyelement_n ... i want able pull keyelement , read list doing this... proc filtertests path { set f [listfromfile $path0/listfile] set f [lsearch -all -inline $f "keyelement_*"] return $f } this works right elements might not follow keyelement_* format need able account this. edit the code using read file like; proc listfromfile {$path1} { set find {$(eval $(call createtest, file, *} upvar path1 path1 set f [open $path1 r] while {[gets $f line] != -1} { if {[string match ${find} $line]} { set write [open listfile a] foreach writetofile $

file upload - Is this a legit way to convert images to jpg while uploading them via php? -

i'm working on project right now, users can upload profile pictures server via php. the file automatically renamed according session-id. want convert uploaded pictures automatically jpgs. thought i'd try manipulate file-extension "jpg" while uploads, never thought work. seems does, file uploaded server jpg (tried chrome). is legit way convert images or there problems in other browsers? [...] if ($uploadok != 0) { $filetypetest = "jpg"; $newfilename = $sessionid . '.' .$filetypetest; move_uploaded_file($_files["bild"]["tmp_name"], "uploads/" . $newfilename); } changing file extension doesn't convert it, it'll still whatever file type uploaded as. browser able display information file's mime type, not extension.

python - Customized Trait built from multiple inheritance -

i trying create custom trait represents unipath.path object. seems advantageous re-use machinery provided file trait, thought use multiple inheritance. from unipath import path traits import file class pathtrait(path,file): pass class a(hastraits): p = pathtrait() however, when used via a(p='/tmp/') , a.p not have methods associated path object, expect. should implementing get , set methods? what expect a(p='/tmp') should do? i can tell trying statement should fail typeerror if code correct. instead of type error, replacing variable p on a object, instance of pathtrait , string. what you're trying conceptually mixed up. file class represents trait object. technically python allows extend object, because python has little type safety, doesn't mean python class act trait. to define custom traits need use tools designed operate traits such trait constructor.

Python json encoding with classes that need custom encoders but which may themselves have nested data structures -

this simplified version of trying ... let's have class x(object): pass x = x() y = x() x.val = {1:2,3:4} y.val = {1:2,3:x} how write custom json encoder recurses through encoding loop naturally ? not need json demonstrate class of type x, (a dot dict fine). actual example of may have data structures nested 10 deep. obviously override default() method, not seem allow recursive calls - ie best have mess (and need json.loads otherwise thing gets double quoted / escaped): class xencoder(json.jsonencoder): def default(self, obj): if isinstance(obj, x): return json.loads(self.encode({x:getattr(obj,x) x in dir(obj) if "__" not in x})) return json.jsonencoder.default(self, obj) maybe on kill used used mixin class follow: def _default_json_encoder(obj): """ default encoder, encountered must have to_dict method serialized. """ if hasattr(obj, "to_dict"): return obj.

sql - PostgreSQL: conditional statements in functions -

i've been trying create basic user authentication system within postgresql 9.4, have been coming unstuck. users table looks this: -- users table create table users ( user_id serial not null primary key, first_name text not null, last_name text not null, email text not null, password text not null, failed_login_attempts int not null default 0 constraint positive_login_attempts check (failed_login_attempts >= 0), last_failed_login_attempt timestamp null, unique(email), created_at timestamp not null default current_timestamp, updated_at timestamp not null, deleted_at timestamp null ); these functions work fine: -- check see if user exists create or replace function user_exists (auth_email varchar(254)) returns setof users $$ select * users email = auth_email $$ language sql; -- authenticates user against system create or replace function authenticate_user (auth_email varchar(254), auth_password varchar(72)) returns setof users $$ se

bundle - Parceling objects in android to transfer from one activity to another -

recently interviewer asked me tricky question. there several parts of question. why (question why , not how) need parcel objects while sending 1 activity , not send directly answer gave - parcelable gives capability developers restrict object creation in way makes faster use. i confused on part, decided site difference between using serializable , parcelable :p (clever huuuhhh !), http://www.developerphil.com/parcelable-vs-serializable/ used reference. while using bundle, when use string, int not need parcel data, think string/int default internally parcelled ? answer gave - because string/int primitive data-type, if had used wrapper class directly, might possible had use parcelable(i not sure on part) i did not useful link after googling, or interviewer not quite satisfied answer. if guys can help, wonderful ! why (question why , not how) need parcel objects while sending 1 activity , not send directly parcelling/serializing obj

fast conversion of a text file to arrays C++ -

i've been working on project involves large heightmaps (3000x3000 ~60mb). . need split data several 200x200 arrays (15x15 of them), save them separately (but time in format fast possible load again). i've tried using streams (i'm not @ c++ don't exclude ideas streams) it's agonizingly slow. stuff might (based on i've seen while searching answer): heightmaps supplied text files (.asc) numbers written "125.123" without "". each entry has 3 decimals no matter number ("0.123" , "100.123").as far know there no negative numbers , size of heightmap known beforehand (usually 3000x3000). so questions essentially: whats best way this? (preferably without boost or such if helps lot why not) what format (for 200x200 arrays) allow fastest loading time? any help, ideas, code or links/litterature? part 2 if reading file onto same type of system (endianness) use binary blittable format. ie store straight binary d

javascript - RegExp. Search MAC-adress -

'01:32:54:67:89:ab'.match(/(([a-f0-9]{2}):){5}\2/); //null why not link group? if write well, works: (([a-f0-9]{2}):){5}([a-f0-9]{2}) \2 not reference pattern. reference 2nd captured group. in pattern 89 captured in 2nd group.. search 89 .. hence not getting match. for example: (["'])\w+\1 match "hello" since both ends on same first match " not match "hello'

Excel Formula cell -

Image
corp_hq-[hq corporate] fdll_731-[fdll(fdll)(731)] fil_111-[fil(111)] slr_mex_hold_ii-[ slr mex hold ii (s863)] smart_bv_hold_eur-[smart bv holding (260) euro] i need excel formula values in ( ) in new cell. please me it. thanks in advance. your question not clear if mean result in picture below, see codes: cell b1: =iferror(mid(a1,find("(",a1,1)+1,find(")",a1,1)-find("(",a1,1)-1),"") cell c1: =iferror(mid(a1,find("(",a1,find("(",a1,1)+1)+1,find(")",a1,find(")",a1,1)+1)-find("(",a1,find("(",a1,1)+1)-1),"") then copy both formulas remaining cells in column

javascript - gulp-ftp errors when uploading to remote path -

i'm trying simple gulp-ftp commands work, keep getting error when run task in instances can't quite seem figure out. i've created task uploadcss using gulp-ftp - upload site's .css files css folder. the task uploadcss runs absolutely fine when folder doesn't exist, without errors. folder created on sever , files in there. when folder exists (i.e. want update files), receive error: [11:33:33] using gulpfile ~/desktop/jm_site/gulpfile.js [11:33:33] starting 'uploadcss'... events.js:85 throw er; // unhandled 'error' event ^ error: read econnreset @ exports._errnoexception (util.js:746:11) @ tcp.onread (net.js:559:26) i've included task in watch task, need able update site's css changes made. gulp compiling sass css, concatenating remaining css in local css folder , minifying 1 main file. need gulp watch css sass, , upload new minified css file css folder once changes. uploadcss task gulpfile.js : gulp.ta

How to load balancing multiple Netty TCP socket server with nginx stream module? -

i need load balancing tcp socket connections multiple netty.io server. @ nginx 1.9, has stream-module, support load balancing tcp socket. test success 1 traccar server. nginx listener port 5095 , forward package port 5005 of traccar server. multiple server, problem happen. devicex open socket servera, send package serverb. please give me advice! thank much. i test module stream.i have 3 server x,y,z, , 3 client a,b,c. , don't see problem loss connected think. clienta open socket serverx,and communication send serverx. if clienta close connection socket , reopen it, clienta communicate servery, , communication send servery.

wordpress - WooCommerce Subscription extension - Expiration date shows 1970 -

i use woocommerce subscription extension add subscription products online shop. i set product valid 6 months. if orders product ordering date set correct, expiration date says 1st january 1970. did miss setting somewhere? would great if knows answer!

ruby on rails - Get has_many from ActiveRecord::Relaiton -

is possible has_many records activerecord::relation? i.e. book.where(fiction: true).pages opposed book.where(fiction: true).collect { |book| book.pages } ideally i'd able records using 1 activerecord query, don't have build array in memory, , make code little cleaner, when relationship has multiple levels (i.e. book.where(fiction: true).pages.words well below, book.where(fiction: true).collect { |book| book.pages } can written : page.joins(:book).where("books.fiction = ?", true) similar way : word.joins(page: :book).where("books.fiction = ?", true)

jquery - Change class of Panel right before the click -

how can change class before animation starts/open/close panel? class changes after animation/panel opened or closed. example: http://jsfiddle.net/0b9jppve/ actual code: $('#accordion').find('.panel-default:has(".in")').addclass('panel-danger'); $('#accordion').on('shown.bs.collapse', function (e) { $(e.target).closest('.panel-default').addclass(' panel-danger'); }).on('hidden.bs.collapse', function (e) { $(e.target).closest('.panel-default').removeclass(' panel-danger'); }) all need change events you're listening for. events hide.bs.collapse , show.bs.collapse fire when animation starts, hidden.bs.collapse , shown.bs.collapse fire on completion. $('#accordion').on('show.bs.collapse', function (e) { $(e.target).closest('.panel-default').addclass(' panel-danger'); }).on('hide.bs.collapse', function (e) { $(e.target).cl

node.js - Trying to install yo with npm on Windows -

i on windows , trying follow instructions @ http://yeoman.io/learning/index.html . far have installed grunt-cli , bower when try install yo using following command... npm install -g yo ...the command prompt returns this: > spawn-sync@1.0.11 postinstall c:\users\aaron\appdata\roaming\npm\node_modules\yo\node_modules\cross-spawn\node_modules\spawn-sync > node postinstall npm err! windows_nt 6.3.9600 npm err! argv "c:\\program files\\nodejs\\\\node.exe" "c:\\program files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "yo" npm err! node v0.12.4 npm err! npm v2.10.1 npm err! file ;c:\windows\system32\cmd.exe npm err! path ;c:\windows\system32\cmd.exe npm err! code elifecycle npm err! errno enoent npm err! syscall spawn ;c:\windows\system32\cmd.exe npm err! spawn-sync@1.0.11 postinstall: `node postinstall` npm err! spawn ;c:\windows\system32\cmd.exe enoent npm err! npm err! failed @ spawn-sync@1.0.11 postinsta

arrays - MongoDB commands in linux console with --eval (print -

i try run command mongo in linux console without entering mongo shell. it: [root@router-mongos ~]# mongo --eval " printjson(show databases)" but not run, output: mongodb shell version: 2.6.10 connecting to: test 2015-06-10t18:33:39.834+0200 syntaxerror: unexpected identifier though if uses: [root@router-mongos ~]# mongo maria --eval " printjson (db.stats())" o mongo --eval " printjson(db.admincommand('listdatabases'))" yes, output same if run in shell. has ever used this? can me? thanks. from mongo shell documentation : you cannot use shell helper (e.g. use , show dbs, etc.) inside javascript file because not valid javascript. following that, there table showing javascript equivalents of various shell helpers . that, show dbs , show databases should replaced db.admincommand('listdatabases') in mongo shell scripts.

php - PDO FETCH_CLASS multiple rows into array of objects -

i'm trying fetch multiple rows of bookings database , want each 1 instance of specific class - attempted store them within multidimensional array. so far works in terms of creating array of objects, need index array booking id can access each one. example: $bookings[id] => booking object ( [name:protected] => name, [time:protected] => time ) is possible , best way go want achieve? hugely appreciated, here's code: class create_bookings { private $db; protected $error; function __construct($db, $current, $end) { $this->db = $db; $query = "select id, name, time bookings"; $stmt = $this->db->prepare($query); $stmt->execute(); $result = $stmt->fetchall(pdo::fetch_class, 'booking'); print_r($result); } } ...and 'booking' class set of properties: class booking { private $db; protected $name; protected $time; } instea

java - Sum of ArrayList for different types -

is possible write single method total sum of elements of arraylist , of type <integer> or <long> ? i cannot write public long total(arraylist<integer> list) and public long total(arraylist<long> list) together there error of erasure, , integer not automatically extends long , vice versa... code inside identical! yes, can implement such method, since both integer , long extend number . example can use wildcard type list element type: public static long total(list<? extends number> list) { long sum = 0; (number n : list) { sum += n.longvalue(); } return sum; } this works integral types however, since sum variable , return value of type long . ideally able use method float s , double s , return object of same type list element type, not easy 2 reasons: the thing can number value 1 of primitive number types. can not sum 2 of them in number dependent way. it not possible create 0-object of righ

c# - The foreign key component 'X' is not a declared property on type 'Y'. Verify that it has not been explicitly excluded -

it seems pretty common issue, i've tried , can't see issues. it seems if issue started today. full error message: "the foreign key component 'allocationid' not declared property on type 'portfoliosection'. verify has not been explicitly excluded model , valid primitive property." model: public class portfoliosection { .... stuff public int allocationid { set; get; } [foreignkey("allocationid")] public virtual allocation allocation { get; set; } .... more stuff } public class allocation { ... stuff [foreignkey("portfoliosections")] public int allocationid { set; get; } public string name { set; get;} public string color { set; get; } public int sortorder { set; get; } public virtual list<portfoliosection> portfoliosections { get; set; } } i'm not doing weird w/ configuration can see cause issue. key allocation allocationid , not id? so far

How to Extract only numeric value only from the URL javascript or jquery -

have url's has numeric value in it. need extract numeric value. numeric value position not constant in url. need generic way how extract. can't use split method because position of value not constant. for example: 1. https:// www.example.com/a/1234567/b/d?index.html 2. http://www.example.com/a?index.html/pd=1234567 3. http://www.example.com/a/b/c/1234567?index.html so above 3 url's has numeric value position not constant. can please provide generic method can expected output "1234567". use basic regular expression: "http://www.example.com/a?index.html/pd=1234567".match( /\d+/ ); this returns first series of numbers in string. in above case, following: [ "1234567" ]

java - Choosing between Stream and Collections API -

consider following example prints maximum element in list : list<integer> list = arrays.aslist(1,4,3,9,7,4,8); list.stream().max(comparator.naturalorder()).ifpresent(system.out::println); the same objective can achieved using collections.max method : system.out.println(collections.max(list)); the above code not shorter cleaner read (in opinion). there similar examples come mind such use of binarysearch vs filter used in conjunction findany . i understand stream can infinite pipeline opposed collection limited memory available jvm. criteria deciding whether use stream or collections api. there other reasons choosing stream on collections api (such performance). more generally, reason chose stream on older api can job in cleaner , shorter way? stream api swiss army knife: allows quite complex operations combining tools effectively. on other hand if need screwdriver, standalone screwdriver more convenient. stream api includes many things

c# - ZXing.Net ITF Barcode issues Windows Phone 8.1 -

i can decode barcodes itf using zxing.net, in cases result.text have missing numbers, in this: original barcode: 836900000008262500403007233338786038100661049195 result.text       : 83690000000  26250040300  23333878603  10066104919 in case there missing 8,7,8 , 5 in other case, numbers reordered random order , have missing numbers: original barcode: 23793381285017475716618000050809162310000010000 result.text         23791623100000100003381250174757161800005080 ideas why happening? thanks edit: 06/12/2015 if don't specify possibleformats decoder decodes codes (the images here:1drv.ms/1b6wd5c) itf , result same described above. code i'm using here: public barcodereaderservice(idialogservice _dialogservice) { dialogservice = _dialogservice; barcodereader = new barcodereader { options = new decodingoptions { purebarcode = true, tryharder = true, possi

asp.net mvc - How to keep the application alive without a client -

my goal send email out every 5 min application if there isn't browser open application. i'm using fluentscheduler manage tasks; works until server decides kill application inactivity. my big constraints are: i can't touch server. how , have work around it. i can't rely on client refreshing browser or else along lines of using client side scripts. i can't use scheduler uses database. what have been focusing on trying create artificial postback. note: server load balanced, solution use that is there way can keep application getting killed server? you use monitoring service https://www.pingdom.com/ ping server @ regular intervals. make sure hits endpoint invokes .net code , not static resource.

serialization - django - "Incorrect type. Expected pk value, received str" error -

i django-rest-framework have following models: basically every ride has 1 final destination , can have multiple middle destinations. models.py: class destination(models.model): name=models.charfield(max_length=30) class ride(models.model): driver = models.foreignkey('auth.user', related_name='rides_as_driver') destination=models.foreignkey(destination, related_name='rides_as_final_destination') leaving_time=models.timefield() num_of_spots=models.integerfield() passengers=models.manytomanyfield('auth.user', related_name="rides_as_passenger") mid_destinations=models.manytomanyfield(destination, related_name='rides_as_middle_destination') serializers.py - rideserializer class rideserializer(serializers.modelserializer): driver = serializers.readonlyfield(source='driver.user.username') class meta: model = ride fields = ('driver', 'destination', '

java - How to use MediaScannerConnection scanFile? -

i'm downloading image folder on sdcard. since images , folder not visible in gallery i'm trying mediascannerconnection update , show folder/images in gallery. shows how in view code ? private void downloadimage() { if (future != null) { //set callback , start downloading future.withresponse().setcallback(new futurecallback<response<inputstream>>() { @override public void oncompleted(exception e, response<inputstream> result) { boolean success = false; if (e == null && result != null && result.getresult() != null) { try { //prepare file name string url = mselectedimage.geturl(); string filename = url.substring(url.lastindexof('/') + 1, url.length()); //create temporary directory within cache folder file dir = utils.geta