Posts

Showing posts from September, 2015

Python Pandas join aggregated tables -

i have data frame 2 columns: product_id , rating. i'm trying join 2 tables. 1 obtained from a = data.groupby('product_id').count() the other one b = data.groupby('product_id').mean() i'd have table has on columns the product_id count mean try: data.groupby('product_id').agg(['mean', 'count'])

c# - Bluetooth LE CanUpdate Characteristic property -

i building xamarin.forms cross platform mobile app, uses monkey.robotics bluetoth low energy functionality. connecting mbed based implimentation of custom gatt service . in xamarin c#, triggers characteristic. canupdate property in monkey.robotics? this standard example c# based on: if (characteristic.canupdate) { characteristic.valueupdated += (s, e) => { debug.writeline("characteristic.valueupdated"); device.begininvokeonmainthread( () => { updatedisplay(characteristic); }); isbusy = false; // spin until first result received }; isbusy = true; characteristic.startupdates(); } this has been working, since changed own custom gatt service connecting to, canupdate property false. property , how triggered? me debugging gatt service code. thanks monkey.robotics open sour

JavaScript - Replace variable from string in all occurrences -

ok, know if have character '-' , want remove in places in string javascript, ... someword = someword.replace(/-/g, ''); but, when applying array of characters, s not working ... const badchars = ('\/:*?"<>|').split(''); let filename = title.replace(/ /g, '-').tolocalelowercase(); (let item = 0; item < badchars.length; item++) { // below not work global '/ /g' filename = filename.replace(/badchars[item]/g, ''); } any ideas? /badchars[item]/g looks badchars , literally, followed i , t , e , or m . if you're trying use character badchars[item] , you'll need use regexp constructor, , you'll need escape regex-specific characters. escaping regular expression has been well-covered . using that: filename = filename.replace(new regexp(regexp.quote(badchars[item]), 'g'), ''); but , don't want that. want character class: let filename = title.replac

java - Static nested class instance -

this question has answer here: java inner class , static nested class 23 answers i came across in java, know static nested class why create instance of 'static'. isn't whole idea of 'static' use without instance? understand concept of inner classes, why (and frankly how possible to) create 'instance' of 'static' member @ ? why this: 1- outerclass.staticnestedclass nestedobject = new outerclass.staticnestedclass(); 2- nestedobject.anestedclassmethod(); and not this: 1- outerclass outerinstance=new outerclass(); 2- outerinstance.staticnestedclass.anestedclassmethod(); use on inner classes, keyword static indicates can access inner class without instance of outer class. for example: public class outer { public static class inner { /* code here. */ } } with construction, can create instance of inn

process - Python What is the difference between a Pool of worker processes and just running multiple Processes? -

i not sure when use pool of workers vs multiple processes. processes = [] m in range(1,5): p = process(target=some_function) p.start() processes.append(p) p in processes: p.join() vs if __name__ == '__main__': # start 4 worker processes pool(processes=4) pool: pool_outputs = pool.map(another_function, inputs) as says on pymotw : the pool class can used manage fixed number of workers simple cases work done can broken , distributed between workers independently. the return values jobs collected , returned list. the pool arguments include number of processes , function run when starting task process (invoked once per child). please have @ examples given there better understand application, functionalities , parameters. basically pool helper, easing management of processes (workers) in cases need consume common input data, process in parallel , produce joint output. the pool quite few thi

javascript - How to use force Jquery mouseenter fadein over again? -

i'm trying set menu, hover on photo show person name , links underneath image-menu. used mouseenter , fadein hover effect, coupled css class has background color set white (so new item cover old one). when try hover menu item has been shown, nothing happens. also, hover not work on items. when hover left, hover not function on 3 items. when hover right side, first 2 items work. please suggest issues be, , how these resolved? please note need have menu shows when mouseover shown, user can click links provided there. script: $(document).ready(function() { $("#pau").mouseenter(function(){ $("#paup").fadein(600); }); $("#red").mouseenter(function(){ $("#redp").fadein(600); }); $("#aesthet").mouseenter(function(){ $("#aesthetp").fadein(600); }); $("#danny").mouseenter(function(){ $("#dannyp").fadein(600); }); $("#kisic").m

java - How to access payload from REST 404 response in Camel cxfrs? -

i have camel route accesses rest service. things work ok if rest response 200 ok. however, if response 404, rest service returns additional info in payload, cannot find way access. this part of debug log running it: [camel (rraacamelcontext) thread #2 - seda://from_rraa] info org.apache.cxf.interceptor.loggingininterceptor - inbound message ---------------------------- id: 2 response-code: 404 encoding: iso-8859-1 content-type: application/json headers: {accept=[application/json], breadcrumbid=[id-steves-macbook-pro-local-53701-1446241733043-1-7], content-type=[application/json], originalheader=[{name=verifyemployeerequest, version=1, scac=rraa, timesent=null, uuid=abcd-1234}], pin=[1234], reason=[init], server=[jetty(9.2.11.v20150529)], transfer-encoding=[chunked], user-agent=[apache cxf 3.1.2]} payload: { "employeeid": "bad-name", "message": "id not found" } my route set as: <route id="rraaiss"> <from uri="

mysql - Find all kids born on Friday -

how can find dates in 1 table - fridays - can show information in table? i taking information ads.date . look @ mysql function dayofweek() select * ads dayofweek(ads.date)=6 dayofweek() returns weekdaynumber 1-7 1 sunday. if want born on friday have filter on dayofweek() = 6

Arduino + RealTime camera for controlling the arduino robot .Possible? -

so problem need work out solution real time camera controlled arduino robot . hardware should use ? if possible have have multiple cameras on board realtime image transmiting on protocol than ideas :) arduino bad idea kind of project. it's memory not enough hold single image of decent resolution. you did not specify how input cameras going control it's movement, keep in mind microcontroller can not real time image processing algorithms.

Is there a way to globally define a type in typescript? Interested in using bluebird instead of ES6 Promise -

i'm ts beginner. see if compile typescript code --target es6 , knows promise type globally. i want use bluebird instead, , have global promise type represented bluebird. how accomplish this? specifically, want avoid importing bluebird everywhere promise<t> mentioned. use typings npm install typings typings install dt~bluebird --global --save make sure tsconfig.json , typings folder in same directory.

javascript - Node sends data back multiple times everytime a user adds new data -

first of all, apologize horribly worded title; have been trying think of 1 past 20 minutes not know succinct way describe problem having. if has better suggestion, please let me know or edit title if able to. background : in order learn nodejs, creating chat server. when user clicks createroombtn , event created containing name of room user created, , sent socket.js module in app.js , app.js appends room array of rooms (these rooms displayed list in browser), , creates broadcast event users including active user. problem : let's there empty list, , user adds new room, titled "nodejs", display room on screen, , fine , dandy. now, if add room, socket.io, example, browser renders following result: socket.io, nodejs, nodejs . if add "javascript", result javascript, socket.io, nodejs, socket.io, node.js . basically, browser renders list on , on again, , each time list shrinks one. not have slightest idea of why happening. weird thing if press refresh,

Why Rest Api in Sharepoint -

what main reason go rest api in sharepoint 2013. have client object model implementing application. can please guide me. the client side object model built upon rest api 1 reason exist. javascript developers may simplicity of rest api. people trying keep page size minimum, may appreciate forgoing size of csom , dependencies. lastly, in mash scenarios other tools, having easy way address content via rest urls makes better interoperability other tools instead of relying on product specific api (i.e. csom).

Get group names in java regex -

i'm trying receive both pattern & string , return map of group name -> matched result. example: (?<user>.*) i return map containing "user" key , whatever matches value. the problem can't seem group name java regex api. can matched values name or index. don't have list of group names , neither pattern nor matcher seem expose information. have checked source , seems if information there - it's not exposed user. i tried both java's java.util.regex , jregex. (and don't care if suggested other library good, supported & high in terms performance supports feature). there no api in java obtain names of named capturing groups. think missing feature. the easy way out pick out candidate named capturing groups pattern, try access named group from match . in other words, don't know exact names of named capturing groups, until plug in string matches whole pattern. the pattern capture names of named capturing group \(\

React native redux and ListView -

i have seen @ least 1 similar question . however interested in pattern redux usage in react native application having listview . should reducers create new listview.datasource every time? cause performance problems etc., asked question pointed out? or should take deviation , call setstate({datasource : new listview.datasource()}) componentwillreceiveprops() of component has listview ? i went componentwillrecieveprops route. given clonewithrows needs new object each time updated (depending on how use rowhaschanged ), 1 needs pass new set of data it. luckily redux reducers, kind of pattern expected anyways in terms of data return. here's how did in app of mine: componentwillreceiveprops(newprops) { let days = newprops.days; if (newprops.viewingdayuuid !== this.props.viewingdayuuid) { days = days.map((day) => { if (day.uuid === newprops.viewingdayuuid || day.uuid === this.props.viewingdayuuid) { return object.assign({}, day); } else

firefox addon sdk - Mozilla JetPack Invalid Filename -

i'm trying create simple mozilla add-on using external js file; folders & files /var/www/html/add-ons/hello /var/www/html/add-ons/hello/index.js /var/www/html/add-ons/hello/package.json /var/www/html/add-ons/hello/script/data/test.js /var/www/html/add-ons/hello/index.js // import page-mod api var pagemod = require("sdk/page-mod"); // create page-mod pagemod.pagemod({ include : "*", contentscriptfile : "./test.js", contentscript: 'window.alert("loaded");' }); /var/www/html/add-ons/hello/package.json { "title": "my jetpack addon", "name": "test", "version": "0.0.1", "description": "a basic add-on", "main": "index.js", "author": "", "engines": { "firefox": ">=38.0a1", "fennec": ">=38.0a1" }, &

android - Find all child views for given root view recursively -

i want find child views given root view. public list<view> getallchildviews(view rootview) { //return child views given rootview recursively } consumer of method pass rootview follows //client has custom view list<view> childviews = getallchildviews(customview.getrootview()); //get root view of custom view i can type cast rootview particular layout , children ( @ leaf level ) not sure type of root view. can scrollview or different layout private list<view> getallchildren(view v) { if (!(v instanceof viewgroup)) { arraylist<view> viewarraylist = new arraylist<view>(); viewarraylist.add(v); return viewarraylist; } arraylist<view> result = new arraylist<view>(); viewgroup viewgroup = (viewgroup) v; (int = 0; < viewgroup.getchildcount(); i++) { view child = viewgroup.getchildat(i); //do not add parents, add child e

javascript - google autocomplete setComponentRestrictions -

is there restriction on setting setcomponentrestrictions value ? because not working while setting dynamic values. scenario 1 (works fine) in scenario hard coded county value search specific cities in country.so works fine when use hard coded value. var input = document.getelementbyid('searchcity'); var options = { types: ['(cities)'],componentrestrictions: {country: 'us' }}; var autocomplete = new google.maps.places.autocomplete(cityinput,options);` scenario 2 (not working) in this, have text field using find country using autcomplete , storing short_code value in shortnamecountry id.but not working when passing dynamic value. var input = document.getelementbyid('searchcity'); var countryopt = $("#shortnamecountry").val().tolowercase(); var options = {types: ['(cities)'], componentrestrictions: {country: countryopt }}; var autocomplete = new google.maps.places.autocomplete(input,options); (i have added scenarios. don

javascript - image is not show in json page -

the images database not coming out in json page , html page image source name outputted. how make images show on html page? thank precious time. linejson.php page <?php header("access-control-allow-origin: *"); header("content-type: application/json; charset=utf-8"); $conn = new mysqli("localhost", "db_user", "db_pwd", "db_name"); $result = $conn->query("select tbl_users.image, tbl_users.firstname, tbl_users.lastname, tbl_users.username, tbl_posts.post, tbl_posts.post_date tbl_posts inner join tbl_users on tbl_users.id=tbl_posts.user_id tbl_posts.user_id=3"); $outp = "["; while($rs = $result->fetch_array(mysqli_assoc)) { if ($outp != "[") {$outp .= ",";} $outp .= '{"image":"' . $rs["image"] . '",'; $outp .= '"firstname":"' . $rs["firstname"]

java - Apache Flink Streaming window WordCount -

i have following code count words sockettextstream. both cumulate word counts , time windowed word counts needed. program has issue cumulatecounts same windowed counts. why issue occurs? correct way calculate cumulate counts base on windowed counts? streamexecutionenvironment env = streamexecutionenvironment.getexecutionenvironment(); final hashmap<string, integer> cumulatecounts = new hashmap<string, integer>(); final datastream<tuple2<string, integer>> counts = env .sockettextstream("localhost", 9999) .flatmap(new splitter()) .window(time.of(5, timeunit.seconds)) .groupby(0).sum(1) .flatten(); counts.print(); counts.addsink(new sinkfunction<tuple2<string, integer>>() { @override public void invoke(tuple2<string, integer> value) throws exception { string word = value.f0; integer delta_count = value.f1; integer count = cumulatecounts.g

javascript - node.js & mysql - How to get the last inserted ID? -

db.query("insert `chat_entries`(`author`, `authorrank`, `receiver`, `timestamp`, `message`) values (" + db.escape(getusername(connection)) + ", " + getuserdata(getusername(connection), "rank") + ", '-', " + math.round(new date().gettime() / 1000) + ", '" + db.escape(messagedata.message) + "')", function(result, rows){ console.log(result.insertid); }); the console told me: cannot read property 'insertid' of null after had searched solution found page: https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row according documentation, must work. where's mistake? in advance. you need replace console.log(result.insertid); with console.log(rows.insertid); since it's varibale you're passing callback function.

http - Sending Arabic characters to Google Sheet -

i sending http request google sheet trying add row of data has arabic characters. works fine when using english characters gets empty cell when using arabic characters. can use following post request in language. params.body = "pphrase=عربی‌" network.request( "https://script.google.com/macros/s/111222334445555/exec","post",getfeatured,params) my google sheet script code receives request , saves abpve params.body row under pphrase column: // usage // 1. enter sheet name data written below var sheet_name = "sheet1"; // 2. run > setup // // 3. publish > deploy web app // - enter project version name , click 'save new version' // - set security level , enable service (most execute 'me' , access 'anyone, anonymously) // // 4. copy 'current web app url' , post in form/script action // // 5. insert column names on destination sheet matching parameter names of data passing in (exactly m

ember.js - How to transition to route in Ember from global context? -

i integrating chrome extension ember app. have chrome extension code in app.js file: window.sendtoextension = (message, callback) => { chrome.runtime.sendmessage(extensionid, message, (response) => { console.log('got response extension!!', response) if (response.path) { //here need tell ember app transition given path } }) } this refers window can't call this.transitionto . how can transition route name extension has told me to? i figured out!! had add beforemodel hook application route did window.applicationrouteinstance = this , can access globally, such in extension messaging code, applicationrouteinstance.transitionto(response.path) also there's new app.visit api coming in 2.3

fortran90 - Parse random "String + Integers" in Fortran -

say want parse following string: "compute sum of (integer) , (integer)" in fortran 90, of have no way of telling how large integer be. can 3, 300,000. as far can tell format statement not leave room inferring size of integer @ run-time. choose large size, i5, number small 3 , program crashes. how best go this? if location of integers in string known @ compile time (e.g. 5th , 7th words), can integers directly using list-directed read: character(256) :: line, words( 50 ) integer :: i1, i2 line = "compute sum of 3 , 30000, get..." read( line, * ) words( 1 : 7 ) !! first 7 words line read( words( 5 ), * ) i1 !! convert 5th , 7th words integer read( words( 7 ), * ) i2 !! i1 = 3, i2 = 30000 but if location of integers not known (e.g. when obtained user input), things more complicated... have written subroutines this, if may seem useful please try :) module strmod contains subroutine split ( line, words, nw ) implicit none

multithreading - Python app with tkinter and threading error at closing -

i writing software project homework, having trouble mixing threads , tkinter. following piece works expected, when close (after starting in python shell), windows shows error: "python stopped working". import threading import time import tkinter import tkinter.ttk class btclient: def __init__(self, master): self.root = master self.root.bind("<destroy>", self.on_destroy) self.t = threading.thread(target=self.update) self.running = false def on_destroy(self, event): self.running = false def run_thread(self): self.running = true self.t.start() def update(self): while self.running: print("update.") time.sleep(1) def main(args): root = tkinter.tk() client = btclient(root) client.run_thread() root.mainloop() if __name__ == "__main__": import sys main(sys.argv) how can solve problem? caused design using? sh

python - Arithmetic accuracy issues while testing for intersection of two line segments -

i wrote code testing intersection of 2 line segments in plane. won't bother details. the code takes 2 line segments, each described 2 end-points, fits each segment line fitting a , b in y = a*x + b . finds intersection point of 2 lines x = (b2 - b1) / (a2 - a1) . last, tests if intersection point x contained within 2 line segments. the relevant part looks this: # line parameterization = delta y / delta x, b = y - a*x a1 = (line1.edge2.y - line1.edge1.y) / (line1.edge2.x - line1.edge1.x) b1 = line1.edge1.y - a1 * line1.edge1.x a2 = (line2.edge2.y - line2.edge1.y) / (line2.edge2.x - line2.edge1.x) b2 = line2.edge1.y - a2 * line2.edge1.x # intersection's x x = - (b2 - b1) / (a2 - a1) # if intersection x within interval of each segment # there intersection if (isininterval(x, line1.edge1.x, line1.edge2.x) , isininterval(x, line2.edge1.x, line2.edge2.x)): return true else: return false for brevity dropped lot of tests handling specific cases when edges par

Make POST request with large file in body for PHP 5.5+ -

there api need work php application. 1 endpoint receives file upload body of post request. uploaded file can rather huge (up 25gb). endpoint returns simple json content either 200 ok or different other status codes. example request may this: post /api/upload http/1.1 host: <hostname> content-type: application/octet-stream content-length: 26843545600 connection: close <raw file data 25 gb> basically, need write method perform such request without killing server. i tried find reasonable implementation but, can see, both curl , non-curl ( stream_context_create ) methods require string request body, may exhaust server memory. is there simple way achieve without writing a separate socket transport layer ? since no better options found, went default solution fsockopen . here full source code of utility function perform http request low memory consumption. data parameter can accept string , array , splfileinfo object. /** * performs memory-safe ht

sql - MySQL Query for retrieving records with HTML form Checkboxes -

this question has answer here: storing ids comma separated values 6 answers i everyone, i'm little bit stuck following. i have html form checkboxes. <input type="checkbox" name="colors" value="1"/>1 brown<br> <input type="checkbox" name="colors" value="2"/>2 blue<br> <input type="checkbox" name="colors" value="3"/>3 green<br> <input type="checkbox" name="colors" value="4"/>4 red<br> <input type="checkbox" name="colors" value="5"/>5 yellow<br> i have mysql table below : |id|colorids| +--+--------+ |1 |4 | |2 |2 | |3 |3,1 | |4 |1 | |5 |2,3 | |6 |5 | colorids type varchar when select box '1 brown'

ember.js - Why does data from a model not render in an Ember template's {{#each}} loop? -

Image
data seems loaded model not seem used when rendering page template in ember 2.1.0. how can data shown me in ember inspector called page template? i have model: app.part = ds.model.extend({ name: ds.attr('string'), summary: ds.attr('string') }); app.indexroute = ember.route.extend({ model: function() } return this.store.findall('part') } }); and template: {{appname}} v {{appversion}} <ul> {{#each part in model}} <li>{{part.name}}</li> {{else}} none found... {{/each}} </ul> and in ember inspector see data (loaded via restadapter): but template when rendered says, "none found..." , never lists data appears have been loaded. have tried multiple variations of {{#each}} tag. a standard app controller loads data template fine (calling {{appname}} or {{appversion}}): app.applicationcontroller = ember.controller.extend({ appname: "my app", appvers

angularjs - How do perform an "except" filter in Angular? -

suppose have angular view allows user check books out of library. data model consists of 2 arrays of book entities each have unique id field plus title field. first array contains entity every book in library , second array contains entity every book user has checked out. librarybooks = [{ id: 0, title: "the adventure of tom sawyer"}, { id: 1, title: "moby dick" }, { id: 2, title: "to kill mockingbird" }, { id: 3, title: "the 3 little pigs" }]; checkedoutbooks = [{ id: 0, title: "the adventure of tom sawyer"}, { id: 3, title: "the 3 little pigs" }]; in short, library has 4 books , user has checked out two. if want list books both arrays, can write this: <h1>library books</h1> <div ng-repeat="book in librarybooks"> {{ book.title }} </div> <h1>checked out books</h1> <div ng-repeat="book in checkedoutbooks"

android - call back function java -

i have class called buycoins, within class have method addlisteneronspinneritemselection() public void addlisteneronspinneritemselection() { spinner1 = (spinner) findviewbyid(r.id.spinner1); textview t=(textview) findviewbyid(r.id.conversion); customonitemselectedlistener c = new customonitemselectedlistener(t); spinner1.setonitemselectedlistener(c); //string stockcode=c.getstock(); //log.d(tag,"message"); } this creates new object detects item(product) selected on spinner. pass buyclass. have attempted lines commented out, value receive null. public class customonitemselectedlistener implements onitemselectedlistener { ... public string stock; ... public void onitemselected(adapterview<?> parent, view view, int pos, long id) { string selected=parent.getitematposition(pos).tostring(); switch(selected) { case "20 coins": toast.maketext(parent.getcontext(), "onitemselectedlistene

Get Python stack trace while using cx_freeze -

i have data acquisition program written in python distribute collaboration executable (using cx_freeze ), don't want bother them installing python , installing software dependencies. program has been working year now. recently, program started crash (crash, not give scripting error, i.e., python virtual machine crashing). know library causing problem. problem happening randomly, it's difficult systematically pinpoint cause. i learned faulthandler , , use cx_freeze, because can't sure problem happening due cx_freeze or due other library. the question: how can produce cx_freeze executable use faulthandler ? what tried: my current cx_freeze setup script following: import sys cx_freeze import setup, executable gui.meta import * target = executable("main.py", #base = "win32gui", icon = "gui\\icon.ico", compress=true, targetname="prog.exe") setu

ios - How can I control the time after an UIButton has been tapped to prepare for next action in UI Testing with Xcode -

i using ui test xcode 7 have few problems. when record ui test, xcode translates chinese unicode uppercase 'u' , shows errors. , ui test code xcuiapplication *app = [[xcuiapplication alloc] init]; [app.navigationbars[@"\u5934\u6761"].images[@"new_not_login30"] tap]; xcuielementquery *tablesquery = app.tables; [tablesquery.cells.statictexts[@"\u6211\u7684\u864e\u94b1"] tap]; the problem is: after tapping image, there animation showing sidebar uitableview or showing uialertcontroller cannot handle duration time. actually, within animation testing continues find next elements match these elements not exist or generating. test failed. solution answer question? please me. thanks. try expectationforpredicate. don't know syntax in objective-c. here part of code in swift: let app = xcuiapplication() app.navigationbars["\u5934\u6761"].images["new_not_login30"].tap() let label = app.cells.statictexts["\u6211\u7

ios - Does older version such as 3.1.8 Adobe Analysis is ATS(App Transport Security) compliance -

i using adobe analytics tagging purpose inside app, old app library version 3.1.8. but apple forcing app transport security how check weather library such adobe analytics ats compliance , uses ssl in request. any appreciated. as per adobe website. https://marketing.adobe.com/resources/help/en_us/mobile/ios/app_transport_security.html this page refers 4.7 , later. can seamlessly configure support ats compliance.

sql - alternatives to using IN clause -

i running below query: select receiptvoucherid, voucherid, receiptid, rvtransactionamount, amountused, transactiontypeid [scratch].[dbo].[loyaltyvouchertransactiondetails] voucherid in (2000723, 2000738, 2000774, 2000873, 2000888, 2000924, 2001023, 2001038, 2001074, 2001173) the aim being extract receiptvoucherid / voucherid / receiptid / rvtransactionamount / amountused / transactiontypeid data list of voucherid's have. my problem here list of voucherid's 187k long in clause not possible returns error: internal error: expression services limit has been reached can advise on alternative doing way? i using ssms 2014 just create table containing vouchers (hopefully have one) , use in() selecting table : select receiptvoucherid, voucherid, receiptid, rvtransactionamount, amountused, transactiontypeid [scratch].[dbo].[loyaltyvouchertra

sql - How to pass the value of a dropdownmenu with php to database -

i have following form cannot select (dropdown menu multiple choice) value added in database. wrong? using php , can other value addedd correctly except select part. have dropdown menu choices , when press "submit" selected value database. <form action="post.php" method="post"> <div class="form-group"> <label for="name">customer name:</label> <input type="text" name="name" class="form-control" id="name"> </div> <div class="form-group"> <label for="email">email address:</label> <input type="email" name="email" class="form-control" id="email"> </div> <div class="form-gro

python - Browser Navigation with Flask and ngRoute -

i have single page angularjs app uses ngroute python flask backend. problem when navigate url through app, works fine -- if try refresh page, or navigate route directly, 404 error. for example, if navigate page (localhost:5000/help) through app, get: get /partials/help.html http/1.1 200- but if open new tab , enter in url of localhost:5000/help, get: get http/1.1 - 404 i think problem in directory structure (see below) , in how serving initial route through flask. here relevant part of main.py: app = flask(__name__, static_url_path="") api = api(app) @app.route('/') def index(): return app.send_static_file('index.html') here relevant parts of file structure: project_path |-main.py |-static/ |-index.html |-partials/ #contains html templates routed views |-js/ |-app.js #contains ngroute logic app |-controllers/ |-libs/ if helpful see routes in app.js, let me know , include them. any on appre

properties - How to create an object property from a variable value in JavaScript? -

this question has answer here: how add property javascript object using variable name? 8 answers i want add new property 'myobj', name 'string1' , give value of 'string2', when it returns 'undefined: var myobj = new object; var = 'string1'; var b = 'string2'; myobj.a = b; alert(myobj.string1); //returns 'undefined' alert(myobj.a); //returns 'string2' in other words: how create object property , give name stored in variable, not name of variable itself? there's the dot notation , bracket notation myobj[a] = b;

javascript - Fade in elements when they come into viewport -

i'm trying fade in elements class of "fade-me" whenever elements come view. found fiddle: http://jsfiddle.net/tcloninger/e5qad/ , exact thing, adds opacity value repeatedly elements come view. create looping animation if i'm trying use velocity's transition slideupin instead of opacity. have following code: $(document).ready(function() { /* every time window scrolled ... */ $(window).scroll( function(){ /* check location of each desired element */ $('.hideme').each( function(i){ var bottom_of_object = $(this).offset().top + $(this).outerheight(); var bottom_of_window = $(window).scrolltop() + $(window).height(); /* if object visible in window, fade it */ if( bottom_of_window > bottom_of_object ){ $(this).velocity('transition.slideupin', { stagger: 700 }).delay(1000) } }); }); }); it works it loops slideupin animatio

javascript - Simulate slow typing in Protractor -

sendkeys() method send keys @ once (actually, 1 @ time quickly): var elm = element(by.id("myinput")); elm.sendkeys("test"); is there way slow typing down protractor send one character @ time small delay between each of characters? we can slow down protractor entirely , not change way sendkeys() works , slow down while need "send keys" part , in specific cases. the idea use browser.actions() , construct series of "send keys" command - 1 every character in string. after every "send keys" command adding delay introducing custom sleep action . @ end, here reusable function we've come with: function slowtype(elm, keys, delay) { var action = browser.actions().mousemove(elm).click(); (var = 0; < keys.length; i++) { action = action.sendkeys(keys[i]).sleep(delay); } return action.perform(); } usage: slowtype(elm, "some text", 100);

javascript - Google Sheets Delete Row if value in a column on one tab to not match a column on other -

i trying make script in google sheets check values in column on 1 tab against values in column in tab. for example; have list allowed e-mail addresses in 1 tab ("users") , then, form have entering addresses in other tab ("form1"). if addresses form not in allow list, automatically delete row. i think main problem code here. if( entryvalues[i] === emailsallowed[t] ) even tho values in arrays match never become true. function onopen() { var sheet = spreadsheetapp.getactivespreadsheet(); var s = sheet.getsheetbyname('form1'); //get sheet entered records in it. var s2 = sheet.getsheetbyname('users');//get sheet allow list in it. var entryvalues = s.getrange('c2:c9').getvalues(); //(get list of e-mail addresses entered via form (using cell reference)) var emailsallowed = s2.getrange('a2:a6').getvalues(); //(get list of allowed e-mail addresses (using cell reference)) var isallowed = 0; for(var = entryvalu

ruby on rails - How to redirect/ render to another controller's view? -

once pet saved, want redirect treats/show controller. tried doing takes me pets/show. def create @pets = pet.new(pet_params) respond_to |format| if @pet.save format.html { redirect_to @treat} format.json { template: treats/show, status: :created, location: @pet } else format.html { render :new } format.json { render json: @pet.errors, status: :unprocessable_entity } end end end you redirect path: format.html { redirect_to(treat_path(@treat) }

c# - How to filter out catch blocks -

i need return false prevent logging if sp.serverexception has been thrown. in other cases need logging , return false too. try { folder = getfolderbyrelativeurl(folderrelativepath); } catch (sp.serverexception serverex) { //if file not found logging not need if (serverex?.message == "file not found") { return false; } //how can go here } catch (exception ex) { //to there log(ex.message); return false; } i know solution be try { folder = getfolderbyrelativeurl(folderrelativepath); } catch (exception ex) { //if file not found logging not need if (!(ex sp.serverexception && ex?.message == "file not found")) { log(ex.message); } return false; } try when keyword: try { folder = getfolderbyrelativeurl(folderrelativepath); } catch (sp.serverexception serverex) when (serverex.message == "file not found") { return false; } catch (exception ex) {

python - tornado how to use WebSockets with wsgi -

i trying make game server python, using tornado. the problem websockets don't seem work wsgi. wsgi_app = tornado.wsgi.wsgiadapter(app) server = wsgiref.simple_server.make_server('', 5000, wsgi_app) server.serve_forever() after looking trough answer on stackoverflow, running tornado in apache , i've updated code use httpserver , works websockets. server = tornado.httpserver.httpserver(app) server.listen(5000) tornado.ioloop.ioloop.instance().start() however when use httpserver, error comes saying: typeerror: __call__() takes 2 arguments (3 given) looking on internet, found answer question here: tornado.wsgi.wsgiapplication issue: __call__ takes 3 arguments (2 given) but after adding tornado.wsgi.wsgicontainer around app , error persists. how can solve problem? or there way use tornado web sockets wsgi. here code @ moment: import tornado.web import tornado.websocket import tornado.wsgi import tornado.template import tornado.httpserver #import wsgi

javascript - I need to make a PUT request to a JSON file in an external API. I need to update specific fields -

i have json on external api, and, in documentation of api, instructs use put request update records. have read lot on this, haven't found adequate amount of information. i best provide info can can me, specifically. i have url stored in variable: $record . the documentation instructs to: set request body content json formatted array of record data. “payload”. it provides example: { “name”: “craig j. peters”, “job title”: “director of engineering” } i need change specific fields. how can accomplish using curl , php? i should mention: if easier javascript, open well. i recommend check guzzle starting point - http://docs.guzzlephp.org/en/latest/request-options.html#body

SVN checkout/update --revision - Real difference between them when it's needed do rollback -

i have 2 commands (from documentation): $ svn checkout --revision 1729 # checks out new working copy @ r1729 … $ svn update --revision 1729 # updates existing working copy r1729 what practical difference between them related rollback needs? understand " svn checkout create new workcopy, when svn update updates existing one" mean in practice? will need resolve conflicts after of operations or not? first of all, read documentation: version control subversion 1.8 . suggest reading documentation because svnbook has special section should answer question: svnbook | fetching older repository snapshots . svn checkout --revision 1729 create new working copy @ revision 1729. require transfer data server. svn update --revision 1729 update existing working copy revision 1729. changes between working copy's base , rev 1729 downloaded in case. in case of svn update may required solve conflicts if have local & uncommitted modifications in working co

model view controller - MVC vs. Flux ? Bidirectional vs. Unidirectional? -

Image
looking @ following diagram (which explains mvc), see unidirectional data flow. so why consider mvc have bidirectional data flow while justifying flux ? because in javascript frameworks mvc not work way depicted. ui communicates bi-directionally model, in: user types view input mvc framework binds onchange() update model. ajax request brings in new model data. mvc framework updates view input's value match model. in flux architecture, ui fire independent action type , associated data dispatcher update model same way background ajax method update model. reference: http://www.thesoftwaresimpleton.com/blog/2013/03/23/client-side-mvc/ "client side mvc different server side mvc" "we setting 2 way communication between 2 objects..." "in short wiring value of firstname property of person object value property of input." http://guides.emberjs.com/v1.10.0/object-model/bindings/ bindings in ember.js can use

objective c - Call Swift code from an Apple TV TVML TVJS JavaScript App -

i have basic tvml application set up. simple events (such button press) handled via javascript (tvjs). when user presses button (provided via tvml template) i'd code run in swift instead, manipulates ui elements. what's best way this? you can use evaluateappjavascriptin method in tvapplicationcontrollerdelegate below , write corresponding swift method in it; (swift side) // mark: tvapplicationcontrollerdelegate func appcontroller(_ appcontroller: tvapplicationcontroller, evaluateappjavascriptin jscontext: jscontext){ let debug : @convention(block) (string!) -> void = { (string : string!) -> void in #if debug print("[log]: \(string!)\n") #endif } jscontext.setobject(unsafebitcast(debug, to: anyobject.self), forkeyedsubscript: "debug" (nscopying & nsobjectprotocol)!) } after can call method tvjs this; (js side) debug('hello js swift...');