Posts

Showing posts from February, 2010

ractivejs - How to loop in ractive.js -

i have got following data (sample): "data": { "eventsheading": "upcoming events", "eventstobedisplayed": 3, "alleventlinktext": "see events", "eventslist": [ { "eventdate": "22/12/2015", "eventtitle": "event info 1" }, { "eventdate": "22/12/2015", "eventtitle": "event info 2" }, { "eventdate": "14/01/2016", "eventtitle": "event info 3" }, { "eventdate": "14/01/2016", "eventtitle": "event info 4" } ] } and have this: {{#eventslist}} <tr> <td class="date-column">{{eventdate}}</td> <td class="text-link truncate-text"><span decorator="tooltip:{{e...

node.js - Mongodb Query error -

i have collection named configuration, configuration has ostype, want calculate ostype , group on company using solution return configuration.distinct("ostype").then(function (name) { var types = name var groupobj = {"$group": {"_id": "$company.name"}}, projectobj = {"$project": {"_id": 0, "company": "$_id.company"}}; var grouppipeline = types.reduce(function (obj, type) { // set group pipeline object obj["$group"][type + "_count"] = { "$sum": { "$cond": [{"$eq": ["$type", type]}, 1, 0] } }; return obj; }, groupobj); return configuration.aggregate([grouppipeline]).then(function (result) { return {status: true, code: 200, message: "configuration count", data: result} }); i getting error "message": "exception: group aggregate field name '8.1_count' canno...

google maps - Current Location button is not showing -

i using google map v2 in android app tab(viewpager) , want show current location in map couldn't find button. addmasjid.java package com.example.saroosh.masjidnow.tabs; import android.support.annotation.nullable; import android.support.v4.app.fragment; import android.os.bundle; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; import com.example.saroosh.masjidnow.r; import com.google.android.gms.maps.cameraupdatefactory; import com.google.android.gms.maps.googlemap; import com.google.android.gms.maps.mapfragment; import com.google.android.gms.maps.mapview; import com.google.android.gms.maps.mapsinitializer; import com.google.android.gms.maps.onmapreadycallback; import com.google.android.gms.maps.model.latlng; import com.google.android.gms.maps.model.markeroptions; public class addmasjid extends fragment implements onmapreadycallback{ mapview gmapview; googlemap gmap = null; @override public view oncreateview(la...

javascript - D3 Bubble Chart 'bubble.nodes not a function' -

i'm following mike bostock's tutorial here create bubble chart... except i'm using own dataset , i'm using d3 v4. i'm quite new d3 , understand lot has changed in v4 v3. i'm having trouble converting sample code v4. for instance, i've converted code in d3 v3: var bubble = d3.layout.pack() .sort(null) .size([diameter, diameter]) .padding(1.5); to: var bubble = d3.pack(dataset) .size([diameter, diameter]) .padding(1.5); is above correct? i'm not sure since i'm not having errors till point. but error in following piece of code: var node = svg.selectall(".node") .data( bubble.nodes(root) .filter(function(d) { return !d.children; }) ) .enter() .append("g") .attr("class", "node") .attr("transform", function(d) { return "translate(" + d.x + ...

php - Copy(): File name is longer than maximum allowed path ... Base64 image -

i have "drag & drop" image uploader. sending image module via ajax "base64 image" , use "copy()" move image. for example: copy($image_in_b64, $destination); it returns copy(): file name longer maximum allowed path length on platform (4096): data:image/jpeg;base64,/9j/4qayrxhpzgaasukqaagaa ... everything works perfect on local server not able upload on deployed server. how can fix this? in server config (what)? thank comments, had encode image , had upload it. solution: $data = //image in base64 list($img_type, $data) = explode(';', $data); list(, $data) = explode(',', $data); $data = base64_decode($data); file_put_contents($path, $data);

c++ - zlib compilation error with VxWorks 6.8 -

i trying use gzip compression feature on vxworks 6.8. vxworks development guide give says, you can add gzip compression feature system independently of wind river web server adding zlib library files project. so, add files installdir/components/webcli-4.x/target/src/wrn/wm/common/zlib project. use -dwith_zlib compiler flag when build system. i tried getting build errors ../zlib/zlib_adler32.cpp:21: error: 'z_ulong zlib_z_adler32' redeclared different kind of symbol ../zlib/zlib.h:822: error: previous declaration of 'z_ulong zlib_z_adler32(z_ulong, const z_bytef*, z_uint)' ../zlib/zlib_adler32.cpp:25: error: expected unqualified-id before '{' token c:\windriver\utilities-1.0\x86-win32\bin\make.exe: *** [.../zlib/zlib_adler32.o] error 1 note : files .c extension, changed .cpp , using c++ compiler. functions declared extern "c" declaration of function can checked here zextern ulong zexport adler32 of((ulong adler, cons...

c# - ASP net 4 search and render the result in modal bootstrap -

how input text field , when click in button show result modal bootstrap using mvc? have follow class: class vatsearch{ [required] public string vatnumber { get; set; } } controller: [httppost] public partialviewresult searchvatpartialview() { return partialview("searchvatpartialview"); } public jsonresult adduserinfo(searchvatpartialview model) { vatresponse result= new vatresponse(model.country,model.vatnumber) return json(result); } } and have view form result <form id="myform"> @html.labelfor(m => m.name) @html.textboxfor(m => m.name) @html.labelfor(m => m.address) @html.textboxfor(m => m.address) </form> function adduserinfo() { $.ajax({ url: '@url.action("adduserinfo", "home")', type: 'post', data: $("#myform").serialize(), success: function(data) { if (data.result) { $(':input...

java - Same values are getting added to db multiple times -

// logindao, logic save ui values db... new values getting added , old values replaced system.out.println("in vendor registration i.e logindao class::::::::::"+vendorregistration.getvid()+""+""+vendorregistration.getfirstname()); session session = getsession(); session.begintransaction(); //begin transaction session. query query = session.createquery("update vendorregistration set firstname =:firstname,lastname =:lastname,email =:email,password =:password,vid =:vid "); query.setparameter("firstname",vendorregistration.getfirstname()); query.setparameter("lastname",vendorregistration.getlastname()); query.setparameter("email",vendorregistration.getemail()); query.setparameter("password",vendorregistration.getpassw...

ruby on rails - Tool for slicing app into microservices -

we've refactored our code bit , feel separate parts of our app microservices. helpful use tool show me graph of references between parts (directories) of our app. our app in ruby on rails. i know won't 100% coverage of coupling between modules since ruby dynamic language... graph useful though. you start using model dependency diagram rubymine: https://www.jetbrains.com/help/ruby/2016.2/viewing-model-dependency-diagram.html another tool includes controller dependencies https://github.com/preston/railroady

javascript - Use same ng-controller with different aliases in different parts of HTML -

i'm having problem ng-controllers when more of 1 in same page. example, have 1 controller on page header, 1 on section of same page, , 1 in page content, all of them should edit part , content part, different aliases this html code: page header ( alias "timelineicons") <div class="settimanebar" ng-controller="timelinectrl timelineicons"> <div class="main zerogrid"> <div id="week-list-resp"> <ul></ul> </div> <div id="week-list"> <div class="week-list-container content-xlg"> <div class="week-single" ng-repeat="ico in timelineicons.wk_list" ng-click="timelineicons.loadweek($index + 1);"> <img ng-show="{{timelineicons.currentweek == ($index + 1)}}" src="<?php echo img_path; ?>puntatore.png"/> <span ng-class="{...

Pocketsphinx writing to console on word detection instead of waiting for silence -

currently following command starts pocketsphinx , waits volume hit specific threshhold microphone, starts recording, , when volume drops below threshhold start processing recorded audio , output hello if word detected. pocketsphinx_continuous -inmic yes -keyphrase "hello" -kws_threshold 1e-30 due environments can tad noisy, waiting volume threshhold drop can take longer expected. there way pocketsphinx output recognizable words they're being spoken without need of waiting silence? overall if have significant noise, it's better cancel hardware somehow. microphone array source separation, directed beam microphone , on should reduce noise significantly. not idea rely on pocketsphinx deal noise, it's not designed that. if want immediate reaction on spotting, you'd better use pocketsphinx through api, not pocketsphinx_continuous, simple example in python want example: import sys, os, pyaudio pocketsphinx.pocketsphinx import * sphinxbase.sphinx...

javascript - Typings project and use of Definitely Typed Repository -

how add typings typed repository in angular 2 project, , how these files (i.e *d.ts ) mapped corresponding javascript library? the easiest use typings . on second question: if setup typings correctly, compiler find proper module automatically, no need triple-dash references anymore 🙂.

c++ - ffmpeg generate libs only -

i'm trying build ffmpeg static libraries used in vc++. fedora machine i'm able build ffmpeg using following configure option. /configure --pkg-config=mingw32-pkg-config --prefix=$install_root --disable-static --enable-memalign-hack --arch=x86 --target-os=mingw32 --cross-prefix=i686-w64-mingw32- --enable-shared after generating dlls, i've tried using lib.exe tool generate libs. lib /machine:i386 /def:avcodec-56.def /out:avcodec.lib i'm getting lib files size of lib file small indicates need dll during runtime. need single lib file can statically linked 1 of vc++ project , project dll required. question how generate lib files only? (not lib , dll) any appreciated. thanks.

MySQL will not run on OSX El capitan for any reason whatsoever -

first of let me start saying have read , tried approaches found on web , stack overflow. what when try run mysql.server start or sudo /usr/local/mysql/support-files/mysql.server start is error! server quit without updating pid file (/usr/local/var/mysql/hostname.local.pid). what when try run: mysql is error 2002 (hy000): can't connect local mysql server through socket '/tmp/mysql.sock' (2) i tried: sudo mysqld_safe & clicking mysql start button on system preferences. restart computer reinstall mysql install older version of mysql killall , try run mysql sudo chmod -r 777 /usr/local/mysql/ `sudo chown -r mysql /var/lib/mysql/ rm /usr/local/var/mysql/localhost.err sudo /usr/local/mysql/bin/mysqld_safe start tried here: how auto-load mysql on startup on os x yosemite / el capitan i out of ideas, don't know do. what did make work: killall -u username brew remove mysql brew cleanup sudo rm /usr/local/mysql sudo rm -rf...

sage - How do I solve a system of linear equations using SageMath? -

i have system of linear equations, not want answer number - want in terms of parameters. ax+by= m cx+dy= n don't have values of constants, above equation, i'd want answer x = (md-nb)/(ad-bc) , y = (mc-na)/(bc-ad). how do in sage? var('a b c d m n x y') solve([a*x+b*y==m,c*x+d*y==n],x,y)

ios - Put UIView fixed on a UITableViewController -

i'm new in ios app development , i'm trying put uiview fixed on top of uitableviewcontroller (like header). i'm facing difficulties swift syntax. searching solution, found usage of function scrollviewdidscroll, that: -(void)scrollviewdidscroll:(uiscrollview *)scrollview { cgrect fixedframe = self.uitopview.frame; fixedframe.origin.y = 0 + scrollview.contentoffset.y; self.menuviewrelative.frame = fixedframe; } this not work due wrong syntax. so, did that: override func scrollviewdidscroll (scrollview: uiscrollview) { cgrect fixedframe = self.uitopview.frame; fixedframe.origin.y = 0 + scrollview.contentoffset.y; self.menuviewrelative.frame = fixedframe; } however i'm getting error on cgrect code line: "consecutive statements on line must separated ;". said, i'm new in ios development, , can't figure out wrong syntax. me? so in swift declare variable keywords var or let. override func scrollviewdidscroll (sc...

jquery - How To Roll A Img From Right To Left On Load Web Page -

how roll img right left dont have idea please me , sorry bad english . img{ position:absolute; top:50px; right:5px; width:100px; height:100px; border-radius:50%; background:#ff00ff; } <img src="http://cdn.wallpapersafari.com/15/28/zmtlik.jpg" style="height:100px; width:100px;"/> check snippet in css3 @keyframes rule img{ position:absolute; top:50px; right:80%; width:100px; height:100px; border-radius:50%; transition-duration:1s; animation:animate 3s; } @keyframes animate{ from{ transform:rotate(0deg); } to{ transform:rotate(-500deg); } from{ right:5px; } to{ right:80%; } } <img src="http://cdn.wallpapersafari.com/15/28/zmtlik.jpg" style="height:100px; width:100px;"/>

python - Tkinter Dynamic Widget editing -

here code: class render_window: def __init__(self, height, width, window_title): self.root_window = tk() w = width h = height ws = self.root_window.winfo_screenwidth() # width of screen hs = self.root_window.winfo_screenheight() # height of screen x = (ws/2) - (w/2) y = (hs/2) - (h/2) self.root_window.title(window_title) self.root_window.minsize(width, height) self.root_window.geometry('%dx%d+%d+%d' % (w, h, x, y)) def new_button(self, button_text, button_command="", grid_row=0, grid_column=0, grid_sticky="nesw", grid_columnspan=1, grid_rowspan=1): self.button = ttk.button(self.root_window, text=button_text, command=button_command) self.button.grid(row=grid_row, column=grid_column, sticky=grid_sticky, columnspan=grid_columnspan, rowspan=grid_rowspan) self.responsive_grid(grid_row, grid_column) def new_label(self, label_text, text_alignm...

c# - WCF calls 3rd party DLL only works in VS2015 but not without -

i using 64bit windows7 home premium sp1 , vs2015. i wrote wcf application calls 3rd party dll (from vendor) written in c#. when "view in browser" right clicking productreadservice.svc in vs2015 solution explorer, can call svc(localhost:17476/productrestservice.svc) , method(this calls 3rd party dll localhost:17476/productrestservice.svc/getproductlist/1) , wcf works without problem on browser (chrome , ie), returning xml result correctly. now want wcf running without vs2015 since need run in production env. problem: 1) however, when publish wcf iis7.5, able call svc (localhost:8123/productrestservice.svc) without problem, when called method (localhost:8123/productrestservice.svc/getproductlist/1) encountered request error "the server encountered error processing request. see server logs more details." when checked logs found this: 2016-09-07 12:46:44 ::1 /favicon.ico - 8123 - ::1 mozilla/5.0+(windows+nt+6.1;+wow64)+applewebkit/537.36+(khtml,+like+gecko)...

One to many mapping in Cassandra -

i new cassandra , 1 many mapping of user , vehicle. 1 user may have multiple vehicles. user table contain user details name, surname, etc. , vehicle table have vehicle details. my select query fetch vehicle details particular user. how should design in cassandra? you can model in single table: create table uservehicles ( userid text, vehicleid text, name text static, surname text static, vehiclemake text, vehiclemodel text, vehicleyear text, primary key (userid,vehicleid) ); this way can query vehicles single user in 1 shot, , user data can static stored @ partition key level. long cardinality of user vehicle isn't big (as-in, user has 1000 vehicles) should work fine. the case have considered above simple. if user has lot of details around 20 30 fields , same vehicle. still suggest have single table , copying user data vehicle? it depends. use case require returning of them? if so, "yes" still recommend approach. way best ...

sql - Incorrect syntax near '.'. While Update a variable table -

i have issue while updating table variable. i've declared it, when run whole query error: incorrect syntax near '.'. and can't seem solve issue... update @list set nrid = case when nrid null t1.nrid else nrid end @list inner join table1 t1 on @list.pnr = t1.pnr inner join table2 t2 on t1.n nrpnr = t2.nrpnr t1.pnr = t2.pnr , t2.isactive = 0 update list set list.nrid = t1.nrid @list list inner join table1 t1 on list.nrid = t1.nrid inner join table2 t2 on t1.nrid = t2.nrid t1.nrid = t2.nrid , t2.isactive = 0 as mentioned in comments inner join remove nulls in case

javascript - How to load data on swipe in iDangerous Swiper? -

i using idangerous swiper mobile slider. fine, don't know how load data in slider when user swipe particular slider div. in short want load data on swipe. please check snippet. another problem want load data on click of link, in case " slide 3 ". want retrieve id of post using data-post , want load ajax data in current slider div. so need on click of link slide particular slider , load data using link attributions. after if user swipe slide want load other data in slide. i know confusing , sorry english. :( thank you var swiper = new swiper('.swiper-container', { pagination: '.swiper-pagination', paginationclickable: true, slidetoclickedslide:true, loop: true, preloadimages: false, lazyloading: true }); $('#btn').click(function(){ var slider = $(this).data("slider"); swiper.slideto(slider, 1000, false); }) html, body { position: re...

sql - ORA-00905: missing keyword when using Case in order by -

i have below query, if edit date not null, recent record needs returned , should randomized else records should randomized. tried below order , getting missing keyword error. select * ( select c.id,c.edit_date, c.name,l.title tablea c, tableb l c.id = l.id , c.published_ind = 'y' , lc.type_id != 4 , trim(c.img_file) not null order dbms_random.value ) rownum = 1 order case when c.edit_date = 'null' dbms_random.value else dbms_random.value, c.edit_date desc end if correct, try record per id either highest date (a random 1 if more records same date exists) or null date (again random 1 when more null records same id e...

c# - Cannot use Unity dependency in constructor -

i'm running issue can't seem find solution to, because don't understand how fix nullreferenceexception. i have constructor; public mainviewmodel() { this.refresh = new delegatecommand(this.dorefresh); //...more this... //...and finally... this.initializeobjects(); } then somewhere between properties there dependency [dependency] public iunitycontainer container { get; set; } and initializeobjects-method generating nullreferenceexception on 'container' private void initializeobjects() { using (var context = this.container.resolve<idbcontextscope>()) { //...remainder of method... } } the exception thrown @ 3rd row of block of code, row starting 'using (var ...' the exception argumentnullexception; message "value cannot nul.parameter name: container" source = microsoft.practices.unity stacktrace = @ microsoft.practices.unity.unitycontainerextensions.resolve....etc.. so concrete questions are; indeed iu...

class - Object-languages misdescribed by UML? -

i've read uml assumes default : a class can inherit several others an object instance of 1 class an object of given class cannot change class this leads me question : there 3 hypothesis, there 2^3 possible combinations. give me languages examples of each of them ? i mean me java "false-true-true" , c++ "true-true-true". 6 others ? or did misinterpret assumptions ? let's @ uml 2.5 standard of omg, have definitive answer: 1.class inheritance the uml 2.5 standard defines class can have none or several superclasses and, conversely, class can superclass of none or several classes (see section 11.4.2 , 11.8.3.6). so uml definitively allows multiple inheritance (as in c++ or python). may restrict , use single inheritance , several interface implementations, in java , c#. you'd use realization relationship show "inheritance" abstract interface (the inheritance arrow dotted). 2. objects , classes 9.8.1: instance...

python - Cannot create new ipython notebook or start jupyter -

Image
whenever try start jupyter ipython notebook. following error sometimes, after restarting system able start ipython notebook, cannot create notebook , gives me error saying forbidden. my command prompt says 0 active kernels else have issue or know answer problem i used have issue too. seems bug because restarted pc , work again. it's been weeks don't have issue anymore , didn't intentionally solve it.

iText Pdf Merging Checkbox Issue -

we using itext pdf api version 5.5.3 , trying merge pdf documents contain checkboxes , write pdf document in servlet output stream , displays in iframe. it works in ie(tried in 11) checkbox doesn't appear in chrome(tried in 52). below sample code use display pdf. inputstream in = docfile.getimage() .getbinarystream(); reader = new pdfreader(in); pdfreaderlist.add(reader); document = new document(pagesize.a4); bytearrayoutputstream = new bytearrayoutputstream(); pdfcopy copy = new pdfcopy(document, bytearrayoutputstream); document.setmargins(35, 35, 48, 75); document.open(); copy.setmargins(35, 35, 48, 75); // add document iterator<pdfreader> pdfreader = pdfreaderlist.iterator(); while (pdfreader.hasn...

How to convert Timestamp to Date Data Type in Google Bigquery -

i trying convert timestamp data type columns date datatype using: bq query -q --destination_table=new_date_table --replace "select date(curr_dt) curr_dt test.date_table" the new table shows column string rather date. there way convert timestamp date datatype. requested screenshot if use standard sql , can following: select * replace(extract(date curr_dt)) curr_dt test.date_table if curr_dt repeated field, solution following: select * replace( array( select extract(date curr_dt) t.curr_dt ) curr_dt) test.date_table t

html - How to create a slanted div with a background image applied? -

i trying make slanted div background image. here screenshot of trying achieve. i have made slanted divs using css triangles. finding technique troublesome in situation because 2 separate parts , pictures wont connect. as of right in code have div background image applied before element looks this: #booking-form:before{ content: ""; position: absolute; top: 0; bottom: 0; left: -320px; border-top: 726px solid transparent; border-right: 320px solid $secondary; } this makes triangle looking if add image triangle fills entire before css , looks this : but need original . any suggestions? thank you! just use full width div suitably angled gradient background instead. no transforms, no borders. body { text-align: center; } .content { height: 150px; padding: 20px 0; background: linear-gradient(-65deg, rgba(0, 0, 255, 0.5) 65%, transparent 65%); display: flex; } div { background-image: url(http://www.f...

javascript - Define variable and return component from an arrow function -

i'd define variable inside .map() iteration, returning component. but having variable inside map doesn't work (gives me error). possible @ all, , if how do this? below simplified example of i'm trying do: render() { return( <div> {array.map( (element, index) => ( let disturbingvariable = 100 + index <mycomponent disturbingvariable={disturbingvariable} /> ))} </div> ) } when arrow function has more 1 statement can no longer use implicit return syntax. add block braces , return statement: array.map((element, index) => { let disturbingvariable = 100 + index return <mycomponent disturbingvariable={disturbingvariable} /> }) alternatively, forgo variable declaration , perform addition in-place, maintaining implicit return: array.map((element, index) => <mycomponent disturbingvariable={100 + index} />)

c# - Task Position does not contain a definition Xamarin forms -

hello working on app in xamrian forms app needs ask gelocation permission , if granted needs geolocation data device , put geolocation coordinates forecast.io url using geolocator plugin james montemagno permissionsplugin james montemagno getting same error 2 times: severity code description project file line suppression state error cs1061 'task' not contain definition 'longitude' , no extension method 'longitude' accepting first argument of type 'task' found (are missing using directive or assembly reference?) readymo c:\users\debroc1\documents\visual studio 2015\projects\app mac\appname\appname\appname\app\radarhome.xaml.cs 74 active i can not run app because of these 2 errors here's forms code: using xamarin.forms; using system; using system.diagnostics; using plugin.geolocator; namespace appname.radar { public interface mylocationtracker { void obtainmylocation(); event eventhandler...

Python, OpenCV, Raspberry Pi-3 - Attribute Error - 'NoneType' object -

i trying track green ball v2 camera module using opencv , python (using virtualenv), keep encountering attributeerror: 'nonetype' object has no attribute 'shape' any appreciated! traceback (most recent call last): file "/home/pi/ball-track/ball_tracking.py", line 52, in <module> frame = imutils.resize(frame, width=600) file "/usr/local/lib/python2.7/dist-packages/imutils/convenience.py", line 45, in resize (h, w) = image.shape[:2] attributeerror: 'nonetype' object has no attribute 'shape' i have tried add bit of code in amend error not work: while true: grabbed, frame = camera.read() if not grabbed: continue # rest of program i have video file trying use within script , contains desired object (to tracked) here code: # python ball_tracking.py --video ball_tracking_example.mp4 # python ball_tracking.py # import necessary packages collections import deque import numpy np import ...

python - DynamoDB Parallel Scan not splitting results -

i'm using segment , totalsegments parameters split dynamodb scan on multiple workers (as shown in parallel scan section of developer guide). however, of results returned 1 worker. issue here? there perhaps issue how i've implemented threading? import threading import boto3 def scan_foo_table(foo, segment, total_segments): print 'looking @ segment ' + str(segment) session = boto3.session.session() dynamodbclient = session.client('dynamodb') response = dynamodbclient.scan( tablename='footable', filterexpression='bar=:bar', expressionattributevalues={ ':bar': {'s': bar} }, segment=segment, totalsegments=total_segments, ) print 'segment ' + str(segment) + ' returned ' + str(len(response['items'])) + ' items' def create_threads(bar): thread_list = [] total_threads = 3 in range(total_threads): ...

c# - How to toggle image based on BooleanToVisibilityConverter? -

in wpf datagrid, have datagridtemplatecolumn: <datagridtemplatecolumn> <datagridtemplatecolumn.celltemplate> <datatemplate> <image visibility="{binding showimage, mode=oneway, convert{staticresource booleantovisibilityconverter}}" source="{staticresource image1}" /> </datatemplate> </datagridtemplatecolumn.celltemplate> </datagridtemplatecolumn> this column starts no image. processing occurs. if showimage assigned true, image displayed. else, nothing displayed. how toggle between 2 images based on assignment showimage? just use converter (maybe can call booltoimagecoverter) assign 1 image if showimage true , different image if showimage false.

javascript - Karma - Spied function error handling -

i have service this: app.service('usersservice.v2', ['$http', '$q', '$exceptionhandler', 'user', 'uservalidator.v2', 'crud', function($http, $q, $exceptionhandler, user, uservalidator, crud){ function dummypromise(){ var dummydeferred = $q.defer(); dummydeferred.resolve('dummy'); return deferred.promise; } this.getuser = function(userid, companyid){ try{ uservalidator.validateid(userid); uservalidator.validateid(companyid); } catch(e){ $exceptionhandler(e); return dummypromise(); } return $http.get(apiurl + 'api/v2/companies/' + companyid + '/users/' + userid) .then(function(response){ var user = new user(response.data); try{ uservalidator.validateuser(crud.read, user); } catch(e){...

python - Using XML ElementTree to create list of objects with atrributes -

i use python requests module xml teamcity rest api looks this: <triggers count="10"> <trigger id="trigger_1240" type="builddependencytrigger"> <properties count="2"> <property name="aftersuccessfulbuildonly" value="true"/> <property name="dependson" value="bt191"/> </properties> </trigger> <trigger id="trigger_1241" type="builddependencytrigger"> <properties count="2"> <property name="aftersuccessfulbuildonly" value="true"/> <property name="dependson" value="bt171"/> </properties> </trigger> <trigger id="trigger_1242" type="builddependencytrigger"> <properties count="2"> <property name="aftersuccessfulbuildonly" value="true"/> ...

python - Is this approach "vectorized" - used against medium dataset it is relatively slow -

i have data frame: df = pd.dataframe({'a' : np.random.randn(9), 'b' : ['foo', 'bar', 'blah'] * 3, 'c' : np.random.randn(9)}) this function: def my_test2(row, x): if x == 'foo': blah = 10 if x == 'bar': blah = 20 if x == 'blah': blah = 30 return (row['a'] % row['c']) + blah i creating 3 new columns this: df['value_foo'] = df.apply(my_test2, axis=1, x='foo') df['value_bar'] = df.apply(my_test2, axis=1, x='bar') df['value_blah'] = df.apply(my_test2, axis=1, x='blah') it runs ok when make my_test2 more complex , expand df several thousand rows slow - above hear described "vectorized"? can speed things up? as andrew, ami tavory , sohier dane have mentioned in comments there 2 "slow" things in solution: .apply() slow loops under hood. .apply(.....

javascript - Why isn't .save for Mongoose working in ReactJS? -

Image
i have reactjs , redux connected mongodb, mongoose. i have mongoose schema (user.js) set so: var userschema = new schema({ email: { type: string, lowercase: true, unique: true, required: true }, }) and api controller receives email string request, , if nothing entered in text field, sends 422 error, , inside user.findone , if email exists in database, throws 422 error , if not, user.save save in database. "use strict"; const user = require('../models/user') exports.register = function(req, res, next) { const email = req.body.email; console.log('error 1') if(!email) { return res.status(422).send({ error: 'you must enter email address.'}) console.log('error 1') } user.findone({ email: email }, function(err, existinguser) { if(err) { return next(err); } console.log('error 2') if(existinguser) { return res.status(422).send({ error: 'that email address in use.'}...

php - How do I put complex order by code into the model? -

i need order database objects relevance. relevance this: rating / distance(lat0, lng0, lat, lng) . way in controller: mymodel::orderby('rating / func(:lat0, :lng0, lat, lng)', [$lat, $lng]) but first, there's rather going argument, since latitude appears twice in formula: mymodel::orderby('rating / func(:lat0, :lng0, lat, lng)', [$lat, $lat, $lng]) second, doesn't sound have in controller @ all. there i'd do: mymodel::orderbyrelevance($lat, $lng) so, idea extract sql formula helper function sql_distance_to($lat_col_name, $lng_col_name) . then, add 1 more helper: sql_distance_to_args($lat, $lng) , returns [$lat, $lat, $lng] . , use these 2 in model make last statement possible. say? how do that? you can approach defining dynamic scope in model (see eloquent query scopes ), keeping logic in model & re-usable throughout application: class mymodel extends model { public function scoperelevance($query, $lat, $lng) { ...

npm - Error on jhipster:upgrade -

when try upgrade version of jhipster in application following error: lothrimond@lothrimond-k53sd:~/workspace/nscanner$ npm list generator-jhipster n-scanner@0.0.0 /home/lothrimond/workspace/nscanner └── generator-jhipster@3.6.1 lothrimond@lothrimond-k53sd:~/workspace/nscanner$ yo jhipster:upgrade welcome jhipster upgrade sub-generator upgrade current application codebase latest jhipster version looking latest generator-jhipster version... /home/lothrimond/workspace/nscanner/node_modules/semver/semver.js:279 throw new typeerror('invalid version: ' + version); ^ typeerror: invalid version: undefined @ new semver (/home/lothrimond/workspace/nscanner/node_modules/semver/semver.js:279:11) @ compare (/home/lothrimond/workspace/nscanner/node_modules/semver/semver.js:566:10) @ function.lt (/home/lothrimond/workspace/nscanner/node_modules/semver/semver.js:600:10) @ null.<anonymous> (/home/lothrimond/workspace/nscanner/node_modules/generator-jhips...