Posts

Showing posts from September, 2012

php - Laravel Update if record exists or Create if not -

i want update record if exists create new 1 if not exists. here got far: merchantbranch.php public function token() { return $this->hasone('app\merchantbranchtoken'); } merchantbranchtoken.php public function merchant_branch() { return $this->belongsto('app\merchantbranch'); } $find = merchantbranchtoken::find($id); if (!$find) { $branch = new merchantbranchtoken(['token' => $token]); merchantbranch::find($id)->token()->save($branch); } else { $find->token = $token; $find->save(); } it's working perfectly. but know laravel powerful eloquent model. can make shorter? or doing correctly?. i've tried using "updateorcreate" method foreign key "merchant_branch_id" need fillable. laravel using methodology save function $user->save() laravel code // if model exists in database can update our record // in database using current ids in &

amazon web services - Update SSL on AWS EC2 Ubuntu -

i trying update ssl certificate client on aws using ec2. there 3 instances , after mucking , changing private keys needed access them, able connect through putty. ubuntu instances. i've tried follow these instruction cannot find add info. i've "grep"ed visturalhost , nothing comes except readme file doesn't help there no /etc/apache2 directories on of instances. all 3 instances have /usr/lib/ssl/certs , /etc/ssl/certs my questions: what webserver being used? where can find config file update location of ssl certificates? where store certificate files on server? how know instance running website? the folks in comments nailed it. it depends. looks next step figure out web server installed, since isn't apache.

plot using gnuplot or python -

Image
i have txt file trajectories. how can plot column 3 gnuplot , have vertical line separate trajectories. #indexes: 0 1 -0.375e+04 0.382e+01 2 -0.375e+04 0.332e+01 3 -0.376e+04 0.353e+01 #indexes: 1 1 -0.735e+04 0.093e+01 2 -0.735e+04 0.096e+01 3 -0.735e+04 0.082e+01 4 -0.735e+04 0.094e+01 #indexes: 2 1 -0.835e+04 0.401e+01 2 -0.035e+04 0.438e+01 3 -0.365e+04 0.438e+01 i have many indexes. photo: here's example shell script works example data. assumes data in file data , creates 2nd tmp file /tmp/data2 , , image /tmp/data.png . #!/bin/bash max=$(awk <data ' !/^#indexes/{ if($3+0>max)max = $3 } end {print max}') awk <data >/tmp/data2 -vmax="$max" ' /^#indexes/ {printf "%s %s\n",i,max; next

asp.net web api2 - Entity Framework DbContext Object Disposal -

environment : ef 6.0, sql 2012, webapi 2 approach 1:using block using(myentities test= new myentities ()) { var waredata = test.waretypes.tolist(); //here actual dbconnect , data fetching happens, hope m correct return request.createresponse<ienumerable<waretype>>(httpstatuscode.ok, waredata); } these scenario applicable irrespective of status of proxycreation flag it fails if return entire data model such return entire data model , explicitly specifying entities needs included use dto , return without explicit list conversion it work 1 , if use dto .. convert list , return it. approach 2: without using block myentities test= new myentities (); var waredata = test.waretypes; //here actual dbconnect , data fetching happens, hope m correct return request.createresponse<ienumerable<waretype>>(httpstatuscode.ok, waredata); with approach, res

javascript - i want this java script to show the answer below the button not on the button , please have a look -

so code make text go on button want show below button every time click button text update following: https://jsfiddle.net/santon/mc15vy4f/ <----- example var mybtn = document.getelementbyid("mybutton"); var clicktracker = { count:0, getmessage: function() { var message; switch(this.count) { case 1: message = "you pushed button"; break; case 2: message = "you pushed button (again)."; break; case 3: //fall through case 4: //fall through case 5: //fall through message = "you pushed button "+ this.count + " times."; break; default: message = "stop pushing button" } return message; } }; function processclick() { clicktracker.count++; this.innerhtml = clicktracker.getmessage(); } mybtn.addeventlistener("click", processclick); in line: this.innerhtml = clicktracker.getmessage(); you telli

java - How can I declare HashMap<String, ArrayList<ArrayList<String>>>? -

this question has answer here: the type stack not generic; cannot parameterized arguments <character> 1 answer i declare hashmap; string key , arraylist of arraylist of string value. public map<string,arraylist<arraylist<string>>> idpathmap = new hashmap<string,arraylist<arraylist<string>>>(); but show error:the type hashmap not generic; cannot parameterized arguments <string, arraylist<arraylist<string>>> how can declare type of hashmap? but show error:the type hashmap not generic; cannot parameterized arguments >> you have created own class named hashmap . rename class (it masks java.util.hashmap , if have imported it). or , public map<string,arraylist<arraylist<string>>> idpathmap = new java.util.hashmap<string,arraylist<arraylist<string>>

python - How can I delete GET url parameter after creating array in django? -

i working django , want fetch requests url , want delete couple of parameter , save rest of in database list. for example, requested url is localhost/test?a=a&b=b&c=c&d=d&e=e i know how get parameters in json format doing json.dumps(reqest.get) and when print out in template httpresponse, get {"a":"a", "b":"b", "c":"c", "d":"d", "e":"e"} what want want remove couple elements , create json. want remove key "a" , "d". json should like, {"b":"b", "c":"c", "e":"e"} can tell me how can it? tried list , json list etc , remove(), del element etc method. each time getting errors can me? thank time. you can try this, a = json.loads(json.dumps(request.get)) del a['a'] del a['d'] return httpresponse(json.dumps(a), content_type="

python - How to plot several graphs and make use of the navigation button in [matplotlib] -

Image
the latest version of matplotlib automatically creates navigation buttons under graph . however, examples see in internet show how create 1 graph, making button [next] , [previous] useless. how plot several graphs , make use of buttons? for example want make graph sin() , cos() 0 degree 360 degree. right this: import scipy matplotlib import pyplot datarange = range(0, 360) datarange = map(scipy.deg2rad, datarange) data1 = map(scipy.sin, datarange) data2 = map(scipy.cos, datarange) pyplot.plot(data1) pyplot.show() # <--- if exclude pyplot.plot(data2) pyplot.show() the sin() graph shown. when close window cos graph shown. if exclude first pyplot.show() , both shown in same figure. how make second graph shown when press next button? according documentation , forward , back buttons used allow go previous view of single figure. example if used zoom-to-rectangle feature, back button return previous display. depending on backend, possible hook when t

mysql - SQL query to compare row value to group values, with condition -

i wish port r code hadoop used impala or hive sql-like query. code have based on question: r data table: compare row value group values, condition i wish find, each row, number of rows same id in subgroup 1 cheaper price. let's have following data: create table project ( id int, price int, subgroup int ); insert project(id,price,subgroup) values (1, 10, 1), (1, 10, 1), (1, 12, 1), (1, 15, 1), (1, 8, 2), (1, 11, 2), (2, 9, 1), (2, 12, 1), (2, 14, 2), (2, 18, 2); here output have (with new column cheaper ): id price subgroup cheaper 1 10 1 0 ( because no row cheaper in id 1 subgroup 1) 1 10 1 0 ( because no row cheaper in id 1 subgroup 1) 1 12 1 2 ( rows 1 , 2 cheaper) 1 15 1 3 1 8 2 0 (nobody cheaper in id 1 , subgroup 1) 1 11 2 2 2 9 1 0 2 12 1 1 2 14 2 2 2

symfony - Apache in Docker says: Symbolic link not allowed -

i use docker image: https://github.com/docker-library/php/blob/fec7f537f049aafd2102202519c3ca9cb9576707/5.5/apache/dockerfile and use docker-compose: apache: build: ./site/docker/apachephp environment: - virtual_host=www.test.dev volumes: - ./site/code:/var/www/app expose: - "80" the code symfony app , uses symbolic link in web folder, assets in symbolic links in apache logs: ah00037: symbolic link not allowed or link target not accessible: /var/www/app/web/test all other code runs fine. wonder if options +followsymlinks -symlinksifownermatch used correct , if there maybe other config files override someting? or permission issue? files on host belong not apache user www-data user, read rights set however. the apache config is: # see http://sources.debian.net/src/apache2/2.4.10-1/debian/config-dir/apache2.conf mutex file:/var/lock/apache2 default pidfile /var/run/apache2/apache2.pid timeout 300 keepalive on maxkeepaliverequests 100

class - Can static methods in javascript call non static -

i curious "undefined not function" error. consider following class: var flareerror = require('../flare_error.js'); class currency { constructor() { this._currencystore = []; } static store(currency) { (var key in currency) { if (currency.hasownproperty(key) && currency[key] !== "") { if (object.keys(json.parse(currency[key])).length > 0) { var currencyobject = json.parse(currency[key]); this.currencyvalidator(currencyobject); currencyobject["current_amount"] = 0; this._currencystore.push(currencyobject); } } } } currencyvalidator(currencyjson) { if (!currencyjson.hasownproperty('name')) { flareerror.error('currency must have name attribute in json.'); } if (!currencyjson.hasownproperty('description')) { flareerror.error('currency must have description attribute in json.'); }

testing - Writing tests without violating SRP, OCP, DRY -

i trying understand these 3 principles better. my question is... how write tests without violating srp, ocp, , dry? my current design violates dry because of similar code in test files. i can't merge test files because violate open/closed principle. (there high probability of adding more modules later) is there i'm missing here? if helps i'm using ruby , minitest this. module files a.rb: module # algorithm end b.rb: module b #does algorithm end test files a_test.rb: class moduleatest # tests algorithm end b_test.rb: class modulebtest # tests algorithm end here how did it. ocp: classes test module not have modified srp: classes test module dry: creating including module tester can avoid duplication of code in tests. module def algorithm(foo) #some implementation end end module b def algorithm(foo) #some implementation end end module module_tester def test_module_test

WiX: How to detect URL Rewrite is installed on IIS -

i using wix 3.10 create msi installing iis (7.5 or higher) website. website requires url rewrite extension in iis. is there way of detecting whether url rewrite extension installed in iis in launch conditions of wix project? you can perform registry search key: hkey_local_machine\software\microsoft\iis extensions\url rewrite or file shearch file: %systemroot%\system32\inetsrv\rewrite.dll

bash how to input * from a file -

the problem: have simple compiler compiles simple rpn expression. compiler invoked this: ./compiler 1 2 3 + "*" this works fine. now, let's i've put 1 2 3 + "*" into file called input. when invoke compiler this: ./compiler $(cat input) my compiler complain: unknown symbol: "*" if remove double quote around *, * gets expanded file names. i've tried '' , ``, no good. so, how can input normal * file? zoo.sh content #!/bin/bash set -f echo $@ m.txt content: 1 2 3 + * in shell do: set -f ./zoo.sh 1 2 4 + * 1 2 4 + * ./zoo.sh $(cat m.txt) 1 2 3 + * the shell doing expansion you. happens before command runs. if want stop need explicitly tell it. read here: http://www.gnu.org/software/bash/manual/bash.html#the-set-builtin above script sets prevent echo inside script expansion , make work imagine code works. compiler not (need) this. remember set +f restore filename expansion.

iphone - How to record screen when app is in Background ios 8.4(Swift) -

i not able record screen in swift app once home button of iphone clicked(i.e. when app suspended) explanation: in swift app,i have created buttons record/stop, declared object(myscreenview) of bridged objective c class iboutlet , connected view. when click on record button,a bridged objective c method called records screen.(the code follows) override func viewdidload() { super.viewdidload() } @ibaction func recordaction(sender: anyobject?){ myscreenview.startrecording() } @ibaction func stopaction(sender: anyobject?){ myscreenview.stoprecording() } from above, able record screen when app in foreground when home button pressed stops recording. actions taken: checked audio , airplay , background fetch checkbox in app capabilities set "no" "application not run in background” info property. please advice done record screen when app pushed background. this isn't possible. once app closed, cannot execute pretty code (with exceptions

java - LibGDX GDX-Pay crash -

i implement gdxpay if want start game comes crash value 10-15 04:40:42.963 1721-1721/com.packagename.mygame.android e/androidruntime: caused by: java.lang.nullpointerexception: attempt read field 'com.badlogic.gdx.pay.purchasemanagerconfig com.packagename.mygame.mygame.purchasemanagerconfig' on null object reference 10-15 04:40:42.963 1721-1721/com.packagename.mygame.android e/androidruntime: @ com.packagename.mygame.android.googleplayresolver.(googleplayresolver.java:17) 10-15 04:40:42.963 1721-1721/com.packagename.mygame.android e/androidruntime: @ com.packagename.mygame.androidlauncher.oncreate(androidlauncher.java:42) i don't understand it. hope can me. i found other answer. gdx pay dont work tutorial work good. link

android - Image Slider Using View Pager(With Transparent Toolbar) -

Image
i have created image slider using view pager following tutorials. problems wanted slider have transparent toolbar. , when clicked on screen toolbar hide. here's code output(i made), , output want. my activity public class viewinfo extends appcompatactivity{ private viewpager viewpager; private toolbar toolbar; private customswipeadapter adapter; photoviewattacher mattacher; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_view_info); toolbar = (toolbar) findviewbyid(r.id.app_bar); setsupportactionbar(toolbar); viewpager = (viewpager) findviewbyid(r.id.view_pager); adapter = new customswipeadapter(this); viewpager.setadapter(adapter); } public class customswipeadapter extends pageradapter { private int[] image_resources = {r.drawable.bsu, r.drawable.gameover2}; private context context; private layoutinflater layoutinflater; public customswi

Check LAN connection by javascript -

i have deployed web application in machine, connected other client machine in lan. while client using web app through browser need check whether lan connection exist each request javascript. i have googled lot this, content regarding internet connection , not regarding lan connection. in advance. try 1 : works me :) function hostreachable() { // handle ie , more capable browsers var xhr = new ( window.activexobject || xmlhttprequest )( "microsoft.xmlhttp" ); var status; // open new request head root hostname random param bust cache xhr.open( "head", "//" + window.location.hostname + "/?rand=" + math.floor((1 + math.random()) * 0x10000), false ); // issue request , handle response try { xhr.send(); return ( xhr.status >= 200 && xhr.status < 300 || xhr.status === 304 ); } catch (error) { return false; } } reference

c# - Method chains with nameof operator -

if nameof(instance.someproperty) , evaluates "someproperty" . is there way can entire method chain "instance.someproperty" ? i know nameof(instance) + "." + nameof(instance.someproperty) , there better way that's more maintainable? is there way can entire method chain "instance.someproperty"? nope. can, however, similar other solution: $"{nameof(instance)}.{nameof(instance.someproperty)}" you can try here .

css - Image width 100%, no horizontal scroll -

i have image set 100% width, working correctly. however, image produces horizontal scroll bar equal full width of image (1366 in case). i've tried overflow:hidden; it's doing nothing. how kill white space/horizontal scroll bar? thanks. .header-image-inner img { overflow: hidden; width: 100%; } <div class="header-image-inner"> <img width="1366" height="422" alt="banner" src="http://216.227.216.66/~mercantileportag/wp-content/uploads/2015/10/home_bannerimage1.png"> </div> the overflow needs applied container element, not element itself. example: .header-image-inner{ overflow: hidden; } .header-image-inner img { width: 100%; }

asp.net mvc - Parsing text to return date -

i have textbox can add age {a} y {b} m {c} w y=years, m=months, w=weeks , submit button , want return parsed birth date according age expression. for example want 2y 1 m / 2 yr 1 mon return 2013/09/27. (the difference today , parsed date) how can in asp.mvc? every approach ok...using c#, javascript... thank you! so first create view model view model public class viewmodel { public int years { get; set; } public int months { get; set; } public int weeks { get; set; } } then on view pass in using @model viewmodel @ top. then once have submitted sort of form can following: public datetime calcuate() { var result = datetime.utcnow; result = result.addyears(viewmodel.years*-1).addmonths(viewmodel.months*-1).adddays(viewmodel.weeks*-7); return result; }

javascript - angular js $broadcast not working -

can tell me wrong bellow code. taking value input box , trying broadcast controller on button click var myapp = angular.module('myapp',[]); myapp.controller('firstcontroller',function ($scope){ $scope.setvalue = function(){ console.log ($scope.input); $scope.$broadcast ('senddata',{textdata:$scope.input}); } }); myapp.controller('secondcontroller',function ($scope){ $scope.$on ('senddata',function(event,args){ console.log("welcome"); console.log (args.textdata); }); });

ios - iPad (4th generation) Wi-Fi + Cellular (MM) background mode not working -

i have app working in background mode in iphone 4 , iphone 5. tested in xcode simulator (ios 9.1). in background mode, i'm receiving location notifications , push them server. however, i'm testing on ipad (4th generation) wi-fi + cellular (mm) a1460 , when app enters in background mode stops receiving notifications , sending requests server. any idea why app it's not working in background? i solved issue setting locationmanager.allowsbackgroundlocationupdates = yes;

python 2.7 - email address not recognised in XML-RPC interface to Neos Server -

i using xml-rpc submission api neos server (optimization, ampl, milp, cplex) , receiving error message "cplex not run unless provide valid email address." am misinterpreting should provided python template found on neos site[here] , here ? the relevant snippet of neos-provided .py file edited below import sys import xmlrpclib import time neos_host="www.neos-server.org" neos_port=3332 contact_email = 'me@mail.com' interface = 'xml-rpc' neos=xmlrpclib.server("http://%s:%d" % (neos_host, neos_port)) ... (jobnumber, password) = neos.submitjob(xml, contact_email, interface) sys.stdout.write("jobnumber = %d \n" % jobnumber) besides email error, code works. know because other solvers return result (it seems solvers - though not cplex - don't require email address) an unrelated question folks using neos server interface, alternatives using regex parse returned output file? thanks! the neos server team res

Could I configure IntelliJ diff viewer/merge tool as external tools in tortoiseSVN? -

Image
new intellij diff viewer , merge tool awesome. i'm wondering if configure them external tools in tortoisesvn. i tried setting intellij executable external diff viewer in tortoisesvn configuration...but doesn't work. also i've been reading intellij documentation (running intellij idea diff or merge command line tool) i'm not sure how configure it. thanks help. re-read comparing files using intellij idea diff command line tool until there come enlightenment in getting correct command-line <intellij idea launcher> diff <path file1> <path file2> where file1 local copy, file2 repository version. for external diff tortoisesvn, there have use %base (repository-side file) , %mine (modified file in wc) variables placeholders compared files. you addded nothing (nor command, nor parameters) command line, - got nothing answer /path/to/idea diff %mine %base

Segment.io `analytics.page` not sending to Google Analytics in Rails -

i'm following segment's quickstart guide at: https://segment.com/docs/libraries/analytics.js/quickstart/ basically, google analytics not receiving page views segment , can't figure out why... in layouts/application file, have: :javascript !function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["tracksubmit","trackclick","tracklink","trackform","pageview","identify","reset","group","track","ready","alias","page","once","off","on"];analytics.factory=function(t){return function(){var e=array.prototype.slice.call(arguments);e.unshift(t);analytics.push(e);return analytics}};for(var t=0;t<analytics.methods.length;t

multithreading - Olingo JMS integration Synchronous / asynchronous -

i looking solution integrating apache oilngo jms . requirement have client construct http structure , send on socket connection ( synchronous ) - if http response take more specified time period (e.g. 15 minutes), request gets forwarded asynchronous behavior thread waiting on socket response. once response arrives, original sender gets notified (callback structure) tia. olingo v2 not have these capabilities. in olingo v4 there asynchronous support available. unfortunately there no documentation on olingo website this. suggest @ technical service olingo uses test features: https://github.com/apache/olingo-odata4/blob/master/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/processor/technicalentityprocessor.java#l148 the technicalentityprocessor in tecsvc module can respond asynchronously. specification part of can found here: http://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part1-protocol/odata-v4.0-errata02-os-part1-protocol-complete.htm

javascript - DOM location of ItemView when passed in CompositeView - Marionette -

i have itemview this: var userview= marionette.itemview.extend({ template: "#user1", el: "#imp1" }); question : mean template of itemview: #user1 go (say) div id=imp1 in dom, when rendered? (if not, guess can use regions render userview in div in dom, fine!) now, in case of rendering compositeview , use region1.show() compositeview . in case, how can render (childview) itemview of compositeview @ specific location (say div id) in dom. (as calling region1.show() on compositeview , not on itemview , dont know how render itemview @ specific location on dom) if itemview compositeview child, cannot render @ specific location in dom . can render on specific location inside compositeview(childviewcontainer), , compositeview render directly dom via region. so, if want render itemview @ specific location in dom, should use region , itemview, without compositeview. var myview = new myview(); myregion.show(myview);

twitter - Not able to attach File to an email app in android from asset folder -

i tried attaching image asset folder email. haven't got considerable success in while have been able tweet image asset of contentprovider public class assetprovider extends contentprovider { @override public assetfiledescriptor openassetfile( uri uri, string mode ) throws filenotfoundexception { log.v("herreee", "assetsgetter: open asset file"); assetmanager = getcontext( ).getassets( ); string file_name = uri.getlastpathsegment( ); if( file_name == null ) throw new filenotfoundexception( ); assetfiledescriptor afd = null; try { afd = am.openfd( file_name ); } catch(ioexception e) { e.printstacktrace( ); } return afd;//super.openassetfile(uri, mode); } @override public string gettype( uri p1 ) { // todo: implement method return null; } @override public int delete( uri p1, string p2, string[] p3 ) { // todo: implement method return 0; } @override public cursor query

r - Creating ggplots in a loop -

i struggling create loop make load of different plots variables in file imported r. some data in dummydata.csv : time,a1,a2,a3,a4 1,0.1,0.2,0.1,0.1 2,0.2,0.2,0.2,0.3 3,0.4,0.5,0.3,0.4 4,0.6,0.8,0.4,0.6 5,0.8,0.9,0.6,0.7 basically real data in larger file this, , interested in plotting "time" against each other variable in separate plots, , thought trying loop through more sensible individually writing out each plot! what tried do: library("ggplot2") dummydata <- read.csv("dummydata.csv", header = t) columns <- colnames(dummydata[2:5]) for(i in columns){ title <- paste("graph_", i, ".pdf") pdf(title) ggplot(data = dummydata, aes(x=time, y=i)) + geom_point()} dev.off() clearly doesn't work. i've made few different attempts ggplot (or normal plot function in r) take 1 of variables plotted loop, seemingly can't it. any advice on try appreciated! you can (it default plot function) :

php - CakePHP 2.x ACL - Control at owner level -

i able control application using acl , done , application working smooth acl , auth . now problem is: i have 2 tables, users , posts . there no rbac (role based access control). setting deny , allow each user follow. //allow user1 $user->id=1; $this->acl->allow($user,'controllers'); //allow user2 add, edit , view posts $user->id=2; $this->acl->deny($user, 'controllers'); $this->acl->allow($user, 'controllers/posts'); but here getting 1 problem: user2 getting access edit posts of user1 . example: user1 created post1 . now user2 logged in can edit user1 's post (i.e. post1- /localhost/myapp/posts/edit/1 ) question: how can set acl permission problem, owner of post can edit post , others can not. i can achieve in controller level checking if($_session['auth']['user']['id'] == $post['post']['user_id']){ // you're owner, u can edit }else{ //u cant edi

Is there a CSS parent selector? -

how select <li> element direct parent of anchor element? in example css this: li < a.active { property: value; } obviously there ways of doing javascript i'm hoping there sort of workaround exists native css level 2. the menu trying style being spewed out cms can't move active element <li> element... (unless theme menu creation module i'd rather not do). any ideas? there no way select parent of element in css. if there way it, in either of current css selectors specs: selectors level 3 spec css 2.1 selectors spec in meantime, you'll have resort javascript if need select parent element. the selectors level 4 working draft includes :has() pseudo-class works same jquery implementation . of april 2017, this still not supported browser . using :has() original question solved this: li:has(> a.active) { /* styles apply li tag */ }

ios - Suggest Completion Issue in Xcode 7 -

i'm not getting autocompletion or suggestions text while typing in xcode 7. have tried following methods, none of them worked me. uninstall xcode , reinstall again restarting system clean code , derived data (~/library/developer/xcode/deriveddata) deleted cache (~/library/caches/com.apple.dt.xcode) please check apple guide completingcode https://developer.apple.com/library/mac/recipes/xcode_help-source_editor/chapters/completingcode.html also try disabling , enabling suggest completion . to turn off code completion feature, choose xcode > preferences , click text editing. in editing pane, deselect option “suggest completions while typing.” can invoke code completion pressing control–space bar. thanks, anil

javascript - In jsTree plugin how can we search nodes by node id instead of node name? -

the default search plugin in jstree search through node name pattern matching, can able search through nodes id rather nodes name ? sure! , don't need plugin that. search element id , optionally select found node $('#tree').jstree("select_node", $('#'+searchednodeid)); see example: js fiddle

c# - ASP.NET MVC - How can I check if a file exists on an ftp server -

this question has answer here: how check if file exists on ftp before ftpwebrequest 2 answers i'm working on asp.net mvc 5.1 web site, , need show picture if exists in ftp server (cdn). foldername , filename tied rules know them beforehand. need display message if file not exist. how can check if file exists? suggested duplicate (verify if file exists or not in c#) not since need check if file exists on remote server , not local folder. try following code string destination = "ftp://something.com/"; string file = "test.jpg"; string extention = path.getextension(file); string filename = file.remove(file.length - extention.length); string filenamecopy = filename; int attempt = 1; while (!checkfileexists(getrequest(destination + "//" + filenamecopy + extention))) { filenamecopy =

visual studio - How to uninstall VSIX extension using NSIS? -

actually, noted here how uninstall .vsix visual studio extensions? , have call this: vsixinstaller /u:12345678-1234-5678-1234-123456780000 however, not figure out how path vsixinstaller inside of nsis script. according this blog can find path in registry or using %vs###comntools% environment variable. function getvsidepath exch $0 push $1 push $2 expandenvstrings $1 "%vs$0comntools%" iffileexists "$1\?" "" tryreg getfullpathname $1 "$1\..\..\ide\" iffileexists "$1\?" done tryreg: intop $0 $0 / 10 readregstr $1 hklm "software\microsoft\visualstudio\$0.0" "installdir" done: strcpy $0 $1 pop $2 pop $1 exch $0 functionend !include logiclib.nsh section push 100 ; visual studio 2010 call getvsidepath pop $0 ${if} $0 != "" execwait '"$0\vsixinstaller.exe" /u:12345678-1234-5678-1234-123456780000' ${endif} sectionend if support more 1 version of visual

Scrollview can host only one direct child although I wrap all in one LinearLayout -

following link: scrollview can host 1 direct child , "wrap children inside of linearlayout wrap_content both width , height , vertical orientation."; still exception. following layout code: <scrollview xmlns:tools="http://schemas.android.com/tools" xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".mainactivity" tools:ignore="mergerootframe"> <linearlayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" > <textview android:id="@+id/titletext" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/title_text" /> <linearlayout

search - Scheduling Problems (shift planning), need in a fast algorithm -

i have problem i'll explain , don't know if scheduling problem : for 30 or 31 days/month want assign doctors shifts constraints : 1-every doctor must assigned specific number of days (e.g 10 or 12) 2-everyday need specific number of doctors (e.g 3 doctors normal days , 4 tuesdays , 3 3-there's custom constraints : no 1 stay 2 continuous days or 3 in cases 4-special days holidays predefined, example doctors 1-4 must stay 2 holidays , doctors 5-8 must stay 1 holidays. 5-finally points of table predefined, example doctor 1 want stay 3th , want no shift 5th. ... i myself trying treat problem csp : a table[#doctors][#days]. each cell red green or white , doing dfs search : 1-start choosing cell assign 2-assigning red or green if valid (in stochastic order) or backtrack if not valid 3-check if solution reached o( 2^(#days*#doctors) ) without invalidity prediction now algorithm slow , don't know if faster using better function predicting invalid no

python - Beautifulsoup xml -

i trying use code add xml tree simple info, have in table. each file has id need add it. corresp dictionary has file name , id couples. there empty element in xml, called idno[@type='tm'] in need enter corresponding id number. from bs4 import beautifulsoup dir = 'files/' corresp = {"00100004":"362375", "00100005":"362376", "00100006":"362377", "00100007":"362378"} filename, tm in corresp.iteritems(): soup = beautifulsoup(open(dir + filename + ".xml")) tmid = soup.find("idno", type="tm") tmid.append(tm) print soup my first problem some time works, time says tmid.append(tm) attributeerror: 'nonetype' object has no attribute 'append' i have no idea why. yesterday evening run same sample code , complains in way. i have tried etree import xml.etree.elementtree et dir = 'files/' corresp = {"00100004"

Difference of Genetic Algorithm and Constraint Programming? -

i hope shed light on me topic. if chance considered stupid question ask, i'd gladly remove question right away. i designing course timetabling system , researching, stumbled upon ga , constraint programming approaches in solving problem. however, didn't quite understand differences between 2 , advantages of 1 on other. hope explain me in layman's term or direct me site topic. thanks in advance! best regards. here's how see family of optimization algorithms: exact methods: brute force, branch , bound constraint programming (terrible name): tries reducing domain set linear programming et al: simplex, ... metaheuristics: local search: tabu search, simulated annealing, late acceptance, ... population based algorithms: genetic algorithms, swarm optimization, ... for use case course timetabling specifically, itc2007 research competition showed local search king. genetic algorithms consistently inferior , constraint programming useless due sca

javascript - Magnific Popup - lightbox issue, plus mfp-hide seems to do nothing -

this first time using stackoverflow please patient me, heh. i'm relative newbie when comes html, css , js, gotta use them work every , then. today i've applied magnific popup site i'm working on. i'm trying use "open fade-zoom animation" example, , modify fit needs of course. popup working, indeed, div popup box isn't hiding, despite having mfp-hide class. it's weird because dreamweaver preview hide it, chrome not (i'm on latest version of chrome windows, if helps.) also, lightbox magnific popup site displays behind every popup seen. here's jsfiddle code. posting interface says need post code here here goes: here's html: <div> <a class="popup-with-zoom-anim" href="#dialog"> <span>click here display dialog</span> </a> </div> <div id="dialog" class="zoom-anim-dialog mfp-hide"> <h1>dialog title</h1> <br><

Jquery on click input does not work if input is disabled -

is there way tell jquery target elements disabled? https://jsfiddle.net/o80cqp4h/ $(document).on("click", "input", function () { console.log('click'); $(this).prop('disabled', false); }); jquery ignores clicks on disabled elements (sort of), trick detect click higher chain, , find out if on input element: $(document).on("click", function (e) { $clicked = $(e.toelement); if ($clicked.is("input:disabled")) { $clicked.prop('disabled', false); } }); if have support firefox, have hackier. https://jsfiddle.net/o80cqp4h/3/ <-- firefox support https://jsfiddle.net/o80cqp4h/1/

loopbackjs - Loopback + MongoDB, AutoMigrate giving error -

i'm trying follow getting started loopback instead of connecting mysql instance i'm trying connect mongodb instance running on localhost (default port 27017). while following steps i'm executing node . given @ connect api data source giving me following error , node stopping. d:\testloopback\node_modules\loopback-connector-mongodb\node_modules\mongodb\lib\utils.js:98 process.nexttick(function() { throw err; }); ^ validationerror: `coffeeshop` instance not valid. details: name can't blank (value: undefined).,validationerror: coffeeshop instance not valid. details: name can't blank (value: undefined).,validationerror: coffeeshop instance not valid. details: name can't blank (value: undefined). can me understand error , how can resolve it? my datasources.json file has: { "db": { "name": "db", "connector": "memory" }, &

objective c - How can I get indexPath of a uiview on a cell - iOS -

i have view controller table view. each cell has custom view 5 star rating system. handle touchesbegan of view @ class of view - (void)touchesbegan:(nsset *)touches withevent:(uievent *)event { uitouch *touch = [touches anyobject]; cgpoint touchlocation = [touch locationinview:self]; [self handletouchatlocation:touchlocation]; } how can indexpath in order know on cell user voted? don't have button have uiview cannot use following: cgpoint buttonposition = [sender convertpoint:cgpointzero toview:self.tableview]; nsindexpath *indexpath = [self.tableview indexpathforrowatpoint:buttonposition]; you can store index path in custom view when create view in cellforrowatindexpath: making property in class of view. property can set in init custom view. index path available in touchesbegan:withevent: method reading property.

mongodb - How can I stream GridFS files to web clients in Clojure/Monger? -

i have web app using clojure, clojurescript, , monger. documents uploaded , stored in mongo via gridfs. same files can requested download; @ moment accomplished writing file (the server's) disk , serving static file, awkward; how can serve file represented gridfs object directly in clojure/java? routing handled ring/compojure. it turns out ring/compojure infrastructure used in luminus able return output-streams, allowing easy transmission of files without touching drive. (ns my-app.routes.updown "file uploading , insertion database" (:use compojure.core) (:require [my-app.db.core :as db] ;; db functions see here wrappers monger functions you'd expect [ring.util.response :as r] [ring.util.io :as io])) (defn make-file-stream "takes input stream--such mongodbobject stream--and streams it" [file] (io/piped-input-stream (fn [output-stream] (.writeto file output-stream)))) (defn download-file-by-id &

c# - How to set up an application level variable in Windows Universal App? -

i have list : list<string> stationnames = new list<string>() { "first station", "second station" }; and accesible pages of app if possible. how ? set on every 1 of pages, don't think efficient way. what need public static property. in 1 of classes, define such: public class myclass { public static readonly list<string> stationnames = new list<string> { "first station", "second station" }; } since static properties not associated instance, can access anywhere using: myclass.stationnames edit: added readonly modifier list because, panagiotis pointed out below, not allow list modified @ other time. however, if intended behaviour, don't include readonly modifier.

Qt 5 Logging - definig category with QLoggingCategory -

i have problem qloggingcategory(const char * category). when use like: qstring rt = "3"; qstring sv = "p"; qloggingcategory dailylogger(qstring(rt+sv+"logger").tostdstring().c_str()); it doesn't work (my custom message handler doesn't recognize category). but when use: qloggingcategory dailylogger("3plogger"); message handler sees category. here's handler function: void mymessageoutput(qtmsgtype type, const qmessagelogcontext &context, const qstring &msg) { if (qstring(context.category).contains("3")) { //some code } } why computed category name not work? qloggingcategory retains copy of char* pointer it's constructed. pointed-to characters must remain valid , constant life of qloggingcategory instance. in failing example, c_str() returns temporary no longer valid after std::string goes out of scope. qloggingcategory pointing @ invalid memory (giving un

syntax - What does it mean equal and greater-than sign (=>) in Javascript? -

this question has answer here: what's meaning of “=>” (an arrow formed equals & greater than) in javascript? 9 answers in meteor whatsapp example project file "=>" used, webstorm ide detect error. can't find docs syntax. chats.foreach( chat => { let message = messages.findone({ chatid: { $exists: false } }); chat.lastmessage = message; let chatid = chats.insert(chat); messages.update(message._id, { $set: { chatid: chatid } }) }); github repository bootstrap.js file here what "=>" ? i downvote question, googling answer proved surprisingly difficult if don't know called. can see in links in comments, that's fat arrow function (sometimes referred arrow function). there confusing aspects of arrow functions, i'll hit highlights: normal functions have this pointer set depending on context:

c# - A potentially dangerous Request.Form value was detected from the client (editor="<div id="header" sty...") -

Image
first of should have followed questions , forum post below stackoverflow question 1 stackoverflow question 2 stackoverflow question 3 stackoverflow question 4 aspsnippets.com server error in application ... potentially dangerous request.form value detected avoiding ‘a potentially dangerous request.form value detected’ c-sharpcorner.com a potentially dangerous request.form value detected client in asp.net all thread mentioned add <httpruntime requestvalidationmode = "2.0" /> or <pages validaterequest ="false" /> inside web.config file , isn't working me . once did , start debugging , getting kind of error actually i'm trying loading html file rich text editor content once click save pdf button saving rich text editor content pdf file these relevant controller class methods [validateinput(false)] public actionresult output_xhtml() { prepaireditor(delegate(editor editor)