Posts

Showing posts from January, 2010

python - My ProjectEuler implementation is much too slow -

this question has answer here: smallest positive number evenly divisible of numbers 1 20? 5 answers these problem: 2520 smallest number can divided each of numbers 1 10 without remainder. smallest positive number evenly divisible of numbers 1 20? these solution, takes lot of time! x = 0 check = [11, 13, 14, 16, 17, 18, 19, 20] while true: x += 1 if all(x % j == 0 j in check): print "the number is", x break print x how improve it? counter main problem? or while? edit: i've seen there lot of differente solutions, should check every single number 1 , without function lcm? this implementation c++ program. instead of number++ , go number += 2 , why? because odd number never divisible 2 therefore reducing search space o(n) o(n/2) . there 1 more way reduce space search, shifting code number += 20 (limit)

javascript - NODE.JS Routing issue while following angular fundamental course -

when trying access url http://localhost:8000/data/event/1 getting error saying cannot /data/event/1 my web server js code below , following have provided directory structure. looks routing problem i'm not able what's wrong. i looking serve json file using node. var express = require('express'); var path = require('path'); var events = require('./eventscontroller'); var app = express(); var rootpath = path.normalize(__dirname + '/../'); console.log(__dirname); var bodyparser = require('body-parser'); app.use(bodyparser.urlencoded({extended: true})); app.use(bodyparser.json()); app.use(express.static( rootpath + '/app')); app.get('data/event/:id',events.get); app.post('data/event/:id',events.save); app.listen(8000); console.log('listening on port ' + 8000 + '...') directory structure demoapp app css data event 1.json 2.json scripts node_modules ev

scala - Akka http client - URI encoding -

i trying invoke rest api using akka http client using below code. val httprequest = httprequest( method = httpmethods.get, uri ="https://example.com/customers/~/profiles/dj2bqryhpcj4ivrc48xtpd%2bhswk%2fqnwx%2bluua0g2t6glnybvd6wc231ijgdbyjnt/preferences", headers = list(accept(mediarange(mediatypes.`application/json`.withparams(map("v" → "3")))), rawheader("content-type", "application/json;v=3"), rawheader("api-key", "xyz") ) ) http().singlerequest(httprequest, gatewayhelper.connectioncontext) before call goes out, when check httprequest.uri (through debugger), there partial uri decoding happening (%2b changed +) dj2bqryhpcj4ivrc48xtpd+hswk%2fqnwx+luua0g2t6glnybvd6wc231ijgdbyjnt because of api returning error. there option can make akka not tamper uri? i have not tried spray , akka-htt

python: compare list containing multiple lists with a single different list -

i solving issue have make program correct evidence. program receives feedback , answers "n" students , compares supplied template. responses of students put single list. problem is, how compare list of responses feedback , print individual score each student. ex: answer_teacher = ['a','b','d','e','f'] answer_student = [['a','b','f','e','f'],['a','a','d','e','f'], ...] without seeing tried im going give answer ... prepared explain solution teacher print([sum(a==b a,b in zip(student,answer_teacher))*1.0/len(answer_teacher) student in answer_student])

java - How to get children of class in jsoup -

i want scrape comment website. having trouble p tag inside class in jsoup. example html code below <html> <head> <title>my webpage</title> </head> <body> <div class="container"> <div class="comment"> <p>this comment</p> </div> </div> </body> </html> here java code public static void main(string args[]){ document doc = null; try { doc = jsoup.connect("https://homeshopping.pk/products/amazon-fire-phone-%284g%2c-32gb%2c-black%29-price-in-pakistan.html").get(); system.out.println("connect successfully"); org.jsoup.select.elements element = doc.select("div.post-message"); system.out.println(element.get(0).text()); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } } } the comments section of page trying fetch not

xpath - Appium : How to select a checkbox from a native Android application -

i want select checkbox list of fruit names . eg . 1.apple [✔] 2.mango [✔] 3.banana [✔] this entire 1 row in 1 relative layout , text view , checkbox . relative layout[parent] //android.widget.textview[@text='mango'] //android.widget.checkbox[@text='liked'] now have written function selecting fruit clicking on checkbox , xpath not returning element. public static void likefruit(string fruitname){ driver.findelement(by.xpath("//android.widget.textview[@text='"+fruitname+"']/following-sibling::android.widget.checkbox[@text='liked']")).click(); } i have tried below xpath , nothing working .am doing wrong? 1.//android.widget.textview[@text='"+fruitname+"']/../android.widget.checkbox[@text='liked'] 2.//android.widget.textview[@text='"+fruitname+"']/following-sibling::*[1]

linux - How to read spaces in FOR loop -

this question has answer here: bash loop spaces 2 answers i'm new here. trying write de-bloat script android. below code :- #/system/bin/sh clear list=$(cat <<'eof' beauty\ plus blackmart cam\ scanner tencent eof ) f in $(echo "$list"); if [ -e /sdcard/$f* ]; rm -rf /sdcard/$f* echo -e "deleted /sdcard/$f*." else echo -e "/sdcard/$f* not found." fi done now here issue, reads both occurrences space different entries. have made sure use echo variables enclosed in quotes. if try echo "$list" then, gives desired output. have tried using the echo "$list" | while read f echo $f done but, gives same output. please me this. output should :- beauty\ circle cam\ scanner so write further code :- for f in $(echo "list"); rm -rf /sdcard/$f echo -e "removed \/sdc

Analyzing algorithms that include while loops -

when analyzing algorithms, don't have issues for loop while have problems analyzing running time of algorithms involves while loop . i'll show example express question. the following 1 part of coin-change algorithm (well-known algorithm of us) studying right now: counter = 0 s = 0 while(s <= n/100) s = s+1 t1 = n- 100*s h = 0 while(h <= t1/50) h = h +1 t2 = t1 - 50*h ... can explain best way of knowing running time of such algorithms have nested while loops? the while loop way of writing loop assessing complexity should not different. here, outer while loop runs n times in complexity world (proportional n in real world) since s increases 1 each iteration , runs until s reaches value proportional n . the inner loop assume little confused about, runs t1 times (again in complexity world) t1 = n - 100s . thinking algorithm o(n^2) t1 decreases in each iteration inner loop runs fewer number of times each subseq

pycharm - Debugging django-channels -

i'm trying incorporate django-channels next project having issues debugging. have tried pycharms debugger , pdb not hit breakpoints. take django channels panel. plugin django debug toolbar . can add django-channels-panel add channel debug functionality project. ensures can channel details when app in development mode. https://github.com/krukov/django-channels-panel installation [ django debug toolbar ] pip install django-debug-toolbar in settings.py installed_apps = [ # ... 'django.contrib.staticfiles', # ... 'debug_toolbar', ] middleware = [ # ... 'debug_toolbar.middleware.debugtoolbarmiddleware', # ... ] in urls.py from django.conf import settings django.conf.urls import include, url if settings.debug: import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ] configuration debug_toolbar_panels = [ 'debug_toolbar.panels.versi

angularjs - Unit testing angular.js service (node.js server) in controller -

i'm new unit testing in client side. application uses express.js, angularjs-ui-router , node.js. start writing unit test cases application. i'm using karma, mocha, chai, sinon unit testing. my router config below: $stateprovider .state('drive', { url: '/drive', templateurl: 'drive.jade', controller: 'drivectrl', }); controller: angular.module('mapp').controller('drivectrl', ['$scope', 'driveservice', function($scope, driveservice) { var driveinfo = driveservice.get({}, function() {}); driveinfo.$promise.then(function(rs) { var drivers = []; //logical operation $scope.drivers = drivers; }); }]); factory resource: mapp.factory('driveservice', ['$resource', function($resource) { return $resource('/drive/id/:id/', {id:'@id'}); }]); the driveservice factory insid

.htaccess - Moving from IIS ISAPI rewrite to Apache mod_rewrite -

i've seen few people have asked on here already, none of solutions provided worked me far. we have been developing iis isapi rewrite (on windows) , 1 of clients decided place project on linux server running apache. result of rules no longer working. example of isapi rewrite rule: rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewriterule ^login/?([^/]*)([^/]*)$ /login.cfm?msg=$1&$2 [l,qsa] rewriterule ^login.cfm$ /login/ [r=301,l,nc] login.cfm actual existing page , not dynamically generated based on template. could me how translate apache mod_rewrite please? rule creates infinitive loop , output is: login/?msg=&&msg=&&msg=&&msg=&&msg=&&msg... (till limit of url length) safe page not found either doesn't check whether file such name exists. the page /login or /login/wrong rule should recognize both cases. you can use these rules in site root .htaccess: rewriteengine on #

devise - Rails NoMethodError: undefined method `[]=' for nil:NilClass in production environment -

i stuck on weird issue. have developed , tested rails application in development environment, in proccess of site , running on production environment needed run rake secret command. unfortunately, faced following error message: rake aborted! nomethoderror: undefined method `[]=' nil:nilclass /var/www/html/comigo/comigo/config/application.rb:31:in `<class:application>' /var/www/html/comigo/comigo/config/application.rb:19:in `<module:comigo>' /var/www/html/comigo/comigo/config/application.rb:18:in `<top (required)>' /var/www/html/comigo/comigo/rakefile:4:in `require' /var/www/html/comigo/comigo/rakefile:4:in `<top (required)>' /home/deplguerrabr/.rvm/gems/ruby-2.3.1/gems/rake-11.2.2/lib/rake/rake_module.rb:28:in `load' /home/deplguerrabr/.rvm/gems/ruby-2.3.1/gems/rake-11.2.2/lib/rake/rake_module.rb:28:in `load_rakefile' /home/deplguerrabr/.rvm/gems/ruby-2.3.1/gems/rake-11.2.2/lib/rake/application.rb:686:in `raw_load_rakefile&

reactjs - Having trouble using Firebase v3 to host my React sample -

i new hosting react apps on firebase, appreciated. i've followed instructions on new v3 documentations @ firebase.com, unsure assets/files place public directory. felt documentation quite vague in regard. here firebase.json: { "database": { "rules": "database.rules.json" }, "hosting": { "public": "public", "rewrites": [ { "source": "**", "destination": "/index.html" } ] } } and directory structure below: name of app -build -css -node_modules -public -scripts .firebaserc database.rules.json firebase.json gulpfile.js index.html package.json readme.md i've tried copying entire contents of parent directory public folder no success. appreciated. so after messing around few hours found out solution. since gulp minifies needed push main.js minified file under build along minified css folder pu

How can I use Postman to replicate SAML post made by Kentor test idP? -

Image
i trying use postman make saml 2 post. imitates post request http://stubidp.kentor.se/ sends our service provider saml authentication. however, postman request returns error. there additional requirements in post?

python - Setting up a result backend (rpc) with Celery in Django -

i attempting result backend working on local machine project i'm working on running issue. currently trying create queue system in order lab create cases. prevent duplicate sequence numbers being used. using celery our printing figured create new celery queue , use handle case. front-end needs results of case creations display case number created. http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html#rabbitmq i following above tutorial on getting celery configured. below source: celeryconfig.py: from kombu import queue celery_default_queue = 'celery' celery_default_exchange = 'celery' celery_default_exchange_type = 'direct' celery_result_backend = 'rpc://' celery_result_persistent = false celery_queues = ( queue('celery', routing_key="celery"), queue('case_creation', routing_key='create.#') ) celery_routes = { 'case.tasks.create_case': {

java - JavaFX Olympic Rings overlap in the correct order -

this first time posting here. i'm doing assignment need create olympic rings in javafx , make them intersect in correct places. this it's supposed like: olympic rings http://ksuweb.kennesaw.edu/~ashaw8/cs1302-07-fall16/assignments/images/olympicrings.png currently, rings intersect dominate in order created objects. blue gets covered yellow when intersect, yellow gets covered black when intersect, etc. can see in picture of olympic rings, first time yellow , blue intersect, yellow covers blue, blue covers yellow second time. each of rings gets covered other ring 1 time intersect, covers other time. if point me in right direction how make them intersect properly, fantastic. here code have far: package com.company; import javafx.application.application; import javafx.scene.scene; import javafx.scene.layout.pane; import javafx.scene.paint.color; import javafx.scene.shape.circle; import javafx.stage.stage; public class olympicrings extends application{ public

reactjs - React Material-UI styling active menu items -

i'm trying figure out how apply css styles :active , :hover states of material-ui menu. the docs say, selectedmenuitemstyle | object | | override inline-styles of selected menu items. but applying, <menu selectedmenuitemstyle={{ color: 'red'}}> <menuitem style={ menuitemstyles } primarytext={ pages.dashboard.title.touppercase() } containerelement={<navlink to={ `${pages.dashboard.slug}` } />} /> </menu> has no effect when click on <menuitem> i've tried react-router's activestyle , activeclassname have no effect because material-ui overrides them. anyone know how apply :active , :hover correctly? have there : material-ui every component provides classname property. properties applied root element. note css properties defined inline given priority on defined in css class. need use !important take precedence on inline style. try add !important on custom style override material-ui l

html - How to keep a link active after refreshing page using angularjs? -

<ul class="nav navbar-nav"> <li ng-class="{ active: isactive('/dashboards/{{dashboard.id}}/dashboard')}" style="border-right: #ececec 1px solid; display: block;" dir-paginate="dashboard in dashboards | itemsperpage:itemsize" data-match-route="/dashboards/{{dashboard.id}}"> <a ng-href="#/dashboards/{{dashboard.id}}/dashboard"> {{ dashboard.name }} </a> </li> </ul> i created nav bar number of links, wanted current link stay active after reloading page, how can that? you can add 1 variable make false default. whenever u click on other links make true. in ng-class put 1 condition if false add active class

exec - How to get execution of python print statements as a string? -

this question has answer here: python: print output in exec statement 5 answers i writing python script contains list containing python print statements string. in function, using loop run exec function run statements. here function: g_list = ["print('wow!')\n", "print('great!')\n", "print('epic!')\n"] def run_statements(): item in g_list: exec(item) when run run_statements() function, following output: wow! great! epic! basically, want save output string later, can save database. does have idea how can it? edit: @ following question: python: print output in exec statement trying output, question different in way trying output string if need print statement in list of strings (as opposed print-like function different name, suggested in answer), can reassign name print own

sql - Can't multiple insert using openrowset -

i searched couple of times. post related still can't me on problem. here sample items of items.txt. checked .txt file , there absolutely no white space, etc. 0000100000 7005432111 4545213695 4545213612 0000100001 0000100002 so here's code far: insert items(id, customerid) select items.id , c.customerid openrowset(bulk n'c:\items.txt', formatfile='c:\items.fmt') items left join customertable c on items.id = c.id and returns values: 0000100000 null 7005432111 null 4545213695 null 4545213612 null 0000100001 null 0000100002 null it return null values in customerid column, wherein there should data there. think problem on items.id = c.id cannot read each values items.txt when use code: insert items(id, customerid) select items.id , c.customerid openrowset(bulk n'c:\items.txt', formatfile='c:\items.fmt') items left join customertable c on c.id = '0000100000' it returns this: 0000100000 2 700543211

python - Can't Query by Key in NDB -

i'm attempting query entity key assuming ordering key ndb. the line is query = user.query().filter(user.key > ndb.key('user', key_id)) and it's throwing server error: file "/applications/googleappenginelauncher.app/contents/resources/googleappengine-default.bundle/contents/resources/google_appengine/google/appengine/api/datastore_types.py", line 1443, in validatepropertykey 'incomplete key found reference property %s.' % name) badvalueerror: incomplete key found reference property __key__. is i'm not allowed query key in way? other stack overflow posts seem indicate i'm doing should ok. can't find online pertaining error text, , i'm not sure else causing error. any or insight appreciated. try this query = user.query().filter(user._key > ndb.key('user', key_id))

Page format using CSS -

i trying align text in page right of picture, , put kind of box around whole thing have content aligned in center of page. <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>test page</title> <style> body { padding-top: 10px; } </style> </head> <body> <div class="container"> <div> <h1>the title</h1> </div> <hr> <div> <div> <img src="http://placehold.it/200x200" alt=""> </div> <div> <h3>brief description</h3> <p>lorem ipsum dolor sit amet, consectetur adipiscing elit. nam viverra euismod odio, gravida pellentesque urna varius vitae. sed dui lorem, adipiscing in adipiscing et, interdum nec metus. mauris ultricies, justo eu convallis placerat, felis enim. </p> <h3>more details</h3> <ul> <li>lorem ips

javascript - How do I efficiently hash an image for indexed search in the browser? -

i'm writing chrome extension saves images websites. in addition saving files themselves, i'd turn images type of hash. the objective index images in database can determine if image duplicate (independent of size, i.e., thumbnail , full-size image considered duplicates). i'm not worried images slight differences (besides size). i've tried work this library , it's large, bit slower i'd like, , (ostensibly) not supported anymore. i've tried number of phash algorithm implementations, near can tell, they're intended server-side use. i'm using webpack , unable bundle of libs tried (very possible user-error, i'm no webpack-pro). lastly, tried converting image base64 , results 10k+ characters, , it's not clear me work images of different sizes. i implement fast string hash in javascript. convert image base64, run string hash on it: https://www.npmjs.com/package/non-crypto-hash (these work in both node , browser, bring in br

Deserializing XML to C# child class -

my xml : <?xml version="1.0" encoding="utf-8"?> <response id="41cc788a-bc22-4ce0-8e1c-83bf49bbffed"> <message>successfully processed request</message> <payload>alive</payload> </response> my classes : [xmlroot("response")] [serializable] public abstract class esbresponsebase<t> { [xmlattribute] public string id { get; set; } public string message { get; set; } public t payload { get; set; } } [xmlroot("response")] [serializable] public class esbresponseisalive : esbresponsebase<string> { } note if don't have these classes on child classes throws exception seems inheritance doesn't work these. my serialization code : xmlserializer serializer = new xmlserializer(typeof (esbresponseisalive)); var esbresponseisalive = (esbresponseisalive) serializer.deserialize(result); however when serialize object properties null. i think more issue inheri

elixir - How do I map any given function over a list of values? -

i splitting string on character , trim items in resulting split. expect following work string.trim/1 exists: iex> "my delimited ! string of doom" |> string.split("!") |> enum.map(string.trim) ** (undefinedfunctionerror) function string.trim/0 undefined or private. did mean 1 of: * trim/1 * trim/2 (elixir) string.trim() i receive undefinedfunctionerror indicating function string.trim/0 not exist. want accomplished anonymous function passed enum.map : iex> "my delimited ! string of doom" |> string.split("!") |> enum.map(fn (word) -> string.trim(word) end) ["my delimited", "string of doom"] does enum.map/2 require anonymous function second parameter? possible give desired function parameter? you need use & operator . capture operator try this: iex()> "my delimited ! string of doom" |> string.split("!") |> enum.map(&string.trim/1) ["m

How to read values from a redirect url in Django Python -

http://127.0.0.1:8084/happy/studen/#access_token=eyjhbgcioijiuzi1 i have recirect url redirects handler in django app , works fine . the issue um facing read values appearing after # in particular url . how may read values in corresponding handler? this pure django python implementation , there wont javascripts identify urls i cannot change behavior of token coming # i have tried both of these ways n = request.get_full_path() k = resolve(request.path_info).url_name but wont give me values after # there specific way in django?

search - Sort hibernate lucene result by publication date -

scenario of searching news, show latest news on top. how should in hibernate lucene search? seems default shows earliest on top. well don't want set sort manually on publication date, makes relevance useless. i found answer here hibernate search sorting the key point add "sortfield.field_score" in sort field.

python - Index of each element within list of lists -

i have following list of lists: >>> mylist=[['a','b','c'],['d','e'],['f','g','h']] i want construct new list of lists each element tuple first value indicates index of item within sublist, , second value original value. i can obtain using following code: >>> final_list=[] >>> sublist in mylist: ... slist=[] ... i,element in enumerate(sublist): ... slist.append((i,element)) ... final_list.append(slist) ... >>> >>> final_list [[(0, 'a'), (1, 'b'), (2, 'c')], [(0, 'd'), (1, 'e')], [(0, 'f'), (1, 'g'), (2, 'h')]] >>> is there better or more concise way using list comprehension? final_list = [list(enumerate(l)) l in mylist]

Highcharts - Legend style from CSS, Firefox issue -

i using multiple of highcharts has different legend y value position each chart reason. as want generalize charts, trying control y values css below... .highcharts-legend-item rect{y:3;} the above css working great expected in chrome alone.. not working in firefox i can going each chart , alter legend: {y:3} , because of less control on server code not able same. is there other way same firefox please? http://jsfiddle.net/1h91po8b/1/

python - Unable to decorate a class method using Pint units -

here's simple example in effort decorate class method using pint, from pint import unitregistry ureg = unitregistry() q_ = ureg.quantity class simple: def __init__(self): pass @ureg.wraps('m/s', (none, 'm/s'), true) def calculate(self, a, b): return a*b if __name__ == "__main__": c = simple().calculate(1, q_(10, 'm/s')) print c this code results in below valueerror. traceback (most recent call last): c = simple().calculate(1, q_(10, 'm/s')) file "build/bdist.macosx-10.11-intel/egg/pint/registry_helpers.py", line 167, in wrapper file "build/bdist.macosx-10.11-intel/egg/pint/registry_helpers.py", line 118, in _converter valueerror: wrapped function using strict=true requires quantity arguments not none units. (error found m / s, 1) it seems me issue here may class instances being passed pint decorator. have solution fixing this? i think error message pretty clear.

android - View doesn't aligned in the center of layout -

Image
i have simple layout, follow: <?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centervertical="true" android:layout_centerhorizontal="true" android:text: "not centralized!" /> <android.support.v7.widget.recyclerview android:id="@+id/recyclerview" android:layout_width="match_parent" android:layout_height="match_parent" android:visibility="gone" /> </relativelayout> the above layout belongs fragment loaded inside viewpager (which belongs activity - called here activitya.java). the activi

how to apply custom editor to hierarchical column in JXTreeTable? -

i have jxtreetable data model extends defaulttreetablemodel, , customnode extends abstractmutabletreetablenode. each column editable expected, hierarchical tree node. how apply custom editor (treetablecelleditor) hierarchical column in jxtreetable? the following several attempts, yet yielded not expected results: treetable.setcelleditor(editor) treetable.getcolumnmodel().getcolumn(0).setcelleditor(editor) treetable.getcolumn(0).setcelleditor(editor) treetable.getcolumnext(0).setcelleditor(editor) i able inherent tree used rendering hierarchical column, unable specify custom editor through it. private jtree gettree(jxtreetable treetable){ try{ field field = jxtreetable.class.getdeclaredfield("renderer"); field.setaccessible(true); return (jtree)field.get(treetable); }catch(nosuchfieldexception | securityexception | illegalargumentexception | illegalaccessexception ex){ throw new runtimeexception(ex); } } it seems

php - WooCommerce - Increase prices of simple and variable products -

i increase product prices percentage in woocommerce. may using hook (example: regular price 100$ + 10%= 110$ ) for simple , variable products . i increase simple , variable products price 10% of regular price. how can increase prices? thanks there 2 cases case 1 - products (bulk increase products prices percentage) this custom function update products prices percentage can set @ end of code snippet . done only 1 time . all product prices, regular prices , sale price updated… if need time later on, see after snippet code (below), procedure. this script work logged admin users. function bulk_update_product_prices($percent=0){ if(get_option( 'wc_bulk_updated_prices' ) != 'yes' && is_admin() ) { // prevent updating prices more once add_option( 'wc_bulk_updated_prices' ); $args = array( // wc product post types 'post_type' => array('product&

c - How can I assign a specific address to a variable? -

how can assign specific address stored variable? #include <stdio.h> void main() { int = 10; printf("%d\n%d\n", a, &a); &a = 2300000; } no, there no way can assign address variable. can assign arbitrary location ie., can point address pointer like int *ptr; ptr = (int*)7000; but changing or assigning specific address not possible.

java - Sending xml data in hidden field.Is it safe? -

i have html form: <form> <input type="hidden" id="hiddenfield"/> ...other form fields </form> in form want set hidden field xml data. can suggest if fine set hidden field directly xml data. i.e. in javascript function safe directly set hidden field xml like: $(#hiddenfiled).val(xml); , xml in java servlet?please suggest. no can't keep xml without encoding can opt either var stringvalue=escape(xml); var xmlvalue= unescape (stringvalue) in javascript though these methods has been depreciated in newer versions find in library http://underscorejs.org/#escape underscorejs also don't keep xml in hidden field if holds andy sensitive information.

java - Re-open Socket Connection when user switch network Android -

i creating socketserver on server machine , letting android client connect , receive message server. problem: when user switch there network (3g<->2g<->wifi) same socket created on client side can't used anymore. how detect situation , re-open socket connection again? method should called on socket object detect this?

python - how to get C type definition string from ctypes object? -

i want generic function can cast ctypes object cffi object. might looks below def ctypestocffi(ctypes_obj): return ffi.cast(get_type_definition(ctypes_obj), ctypes_obj) get_type_definition(ctypes.c_int)=='int' get_type_definition(ctypes.c_int*10)=='int[10]' #or 'int[]' i've thought ctypes should have kind of function, far know doesn't. function needs work structures, pointers , general c type object. does know function i'm looking for? or there reason explains why kind of functions not implemented in ctypes?

mysql - Reuse parameterized (prepared) SQL Query -

i've coded activedirectory logging system couple of years ago... never become status greater beta still in use... i got issue reported , found out happening... serveral filds in such activedirectory event witch userinputs, i've validate them! -- of course didnt... so after first user got brilliant idea use singlequotes in specific foldername crashed scripts - easy injection possible... so id make update using prepared statements im using in php , others. now powershell script.. id this: $mysql-obj.commandtext = "insert `table-name` (i1,i2,i3) values (@k1,@k2,@k3)" $mysql-obj.parameters.addwithvalue("@k1","value 1") $mysql-obj.parameters.addwithvalue("@k2","value 2") $mysql-obj.parameters.addwithvalue("@k3","value 3") $mysql-obj.executenonquery() this work fine - 1 times. script runs endless service , loops within while($true) loop. powershell clams param set... exception calling &qu

git - How to push new branch to remote repository with tracking option -

this question has answer here: how push new local branch remote git repository , track too? 13 answers i working on local branch (feature1) created mainline branch. push local branch remote repository. how achieve in git along tracking option. push -u option: git push -u origin <branch> -u , short --set-upstream , set upstream in origin <branch> name. if omit branch name, local branch name used instead. full story on git's documentation .

google maps - Best way to store small amounts of data in android -

i have basic application uses maps api display map, , after long press put marker down @ location. if select different location, delete current marker , make new one. the app want @ moment, can data persist after app closed. this i'm trying do: @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_maps); // obtain supportmapfragment , notified when map ready used. supportmapfragment mapfragment = (supportmapfragment) getsupportfragmentmanager() .findfragmentbyid(r.id.map); mapfragment.getmapasync(this); bufferedreader reader; try { final inputstream file = getassets().open("userlatlng"); reader = new bufferedreader(new inputstreamreader(file)); string line = reader.readline(); line = reader.readline(); system.out.print("getting data"); } catch (ioexception i

Remove Protractor from from Aurelia TS WebPack? -

is possible remove protractor , related libraries aurelia typescript webpack skeleton project? i tried npm uninstall protractor , successful, when npm start fires off typescript errors aurelia-protractor can't find protractor. tried typings uninstall aurelia-protractor , tells me typings folder doesn't doesn't exist. argh. there easy way rid of protractor , it's supporting modules? thanks.

c++ - How to reduce in CUDA if __syncthreads can't be called inside conditional branches? -

the reduction method suggested nvidia uses __syncthreads() inside conditional branching e.g.: if (blocksize >= 512) { if (tid < 256) { sdata[tid] += sdata[tid + 256]; } __syncthreads(); } or for (unsigned int s=blockdim.x/2; s>32; s>>=1) { if (tid < s) sdata[tid] += sdata[tid + s]; __syncthreads(); } in second example __syncthreads() inside for loop body, conditional branch. however, number of questions on raise problem of __syncthreads() inside conditional branches (e.g. can use __syncthreads() after having dropped threads? , conditional syncthreads & deadlock (or not) ), , answers __syncthreads() in conditional branches may lead deadlock. consequently, reduction method suggested nvidia may deadlock (if believing documentation on answers based). furthermore, if _syncthreads() can't used inside conditional branches, i'm afraid many of basic operations blocked , reduction example. so how reduction in cuda without u

java - Why does 128==128 return false but 127==127 return true when converting to Integer wrappers? -

class d { public static void main(string args[]) { integer b2=128; integer b3=128; system.out.println(b2==b3); } } output: false class d { public static void main(string args[]) { integer b2=127; integer b3=127; system.out.println(b2==b3); } } output: true note: numbers between -128 , 127 true. when compile number literal in java , assign integer (capital i ) compiler emits: integer b2 =integer.valueof(127) this line of code generated when use autoboxing. valueof implemented such numbers "pooled", , returns same instance values smaller 128. from java 1.6 source code, line 621: public static integer valueof(int i) { if(i >= -128 && <= integercache.high) return integercache.cache[i + 128]; else return new integer(i); } the value of high can configured value, system property. -djava.lang.integer.integercache.high=999 if run progra

c# - Add objects to a List nested inside a Dictionary using LINQ extensions -

i have dictionary<t, t> contains key (that represents category) empty list<t> value: dictionary<string, list<imyobject>> myobjects; each pair looks this: { firstcategory, new list<imyobject>> } i have list<t> of imyobject 's: list<imyobject> myobjectsunsorted; i want loop through myobjectsunsorted , add correct list<t> foreach (var myobject in myobjectsunsorted) { myobjects[myobject.category].add(myobject); } how can without loop? example linq extension method? other objects in example created .select() dosen't fit bill in last foreach . i suggest using lookup instead: ilookup<string, imyobject> lookup = myobjectsunsorted.tolookup(t => t.category); ilookup<,> precisely designed "multiple values per key" dictionary. being incredibly simple construct, has benefit if key isn't represented, empty sequence instead of exception. can always write: foreach (var

scrum - Atlassian Jira: best practice for declined stories? -

what's best way keep declined stories? don't want delete them, prevent created again. when search still find story, know it's declined. currently tag declined story , set status "done", it's removed backlog. solution not good, because in search don't see tags , story seems "done". do have better suggestions? thank you you can customise jira change workflow of user story "or other issue type" include "declined" status different "done". go administration -> issues -> workflows , click edit in project related workflow. this open graphical view of issue workflow. you can add new status "declined" publish workflow. this configuration applicable project only. allow filtering user story status "not declined".

ecmascript 6 - Yeoman fail with gulp in babel (es2015) -

i created yeoman generator , when start using babel e.g. change gulpefile.js gulpfile.babel.js (and add .babelrc file) outside gulpfile.js (not project gulpfile.babel.js ) start fail. the project generated gulpfile.babel.js works. , manage pin point failed gulp task gulp pre-test . this yeoman generator tree: . ├── readme.md ├── generators │   └── app │   ├── index.js │   └── templates │   └── my-awesome-site │   ├── gemfile │   ├── readme.md │   ├── _config.yml │   ├── _includes │   │   ├── footer.html │   │   ├── head.html │   │   └── header.html │   ├── _layouts │   │   ├── default.html │   │   ├── page.html │   │   └── post.html │   ├── _posts │   │   └── 2016-09-08-welcome-to-jekyll.markdown │   ├── about.md │   ├── feed.xml │   ├── gulpfile.babel.js │