Posts

Showing posts from August, 2015

android - FileAsyncHttpResponseHandler cancel request -

i want cancel fileasynchttpresponsehandler request in android app, 1 (not of them). there these methods available, none of them cancel request. proceeds until file downloaded. fileasynchttpresponsehandler fileasynchttpresponsehandler; ...get request... fileasynchttpresponsehandler.deletetargetfile(); fileasynchttpresponsehandler.oncancel(); fileasynchttpresponsehandler.sendcancelmessage(); please me!! i'm dev of said library, , have 3 options. first, obtain requesthandle creating request, , cancel through that asynchttpclient ahc = new asynchttpclient(); requesthandle rh = ahc.get(context, url, fileresponsehandler); rh.cancel(); second, cancel request belonging context asynchttpclient ahc = new asynchttpclient(); ahc.get(currentactivity.this, url, fileresponsehandler); ahc.cancelrequests(currentactivity.this, boolean mayinterruptifrunning); third, in 1.4.8 snapshot (will released in on sunday 1.4.8 release), put tag request (or implement gettag() in re

haskell - Why won't GHC reduce my type family? -

here's untyped lambda calculus terms indexed free variables. i'm using singletons library singleton values of type-level strings. {-# language datakinds #-} {-# language gadts #-} {-# language polykinds #-} {-# language typefamilies #-} {-# language typeoperators #-} {-# language undecidableinstances #-} import data.singletons import data.singletons.typelits data expr (free :: [symbol]) var :: sing -> expr '[a] lam :: sing -> expr -> expr (remove as) app :: expr free1 -> expr free2 -> expr (union free1 free2) a var introduces free variable. lambda abstraction binds variable appears free in body (if there's 1 matches). applications join free variables of 2 parts of expression, removing duplicates (so free variables of x y x , y , while free variables of x x x ). wrote out type families: type family remove x xs remove x '[] = '[] remove x (x ': xs) = remove x xs remove x (y ': xs) = y ': remove x

ios - Are dSYM files necessary during development? -

i know dsym files useful have when generate final version of app app store, because have debug symbols used symbolicate crash log. my question if necessary during develop time. ask because disabling them compiling time drops 75%. first off, avoid confusion: default debug info format debug configuration new ios projects "dwarf dsym file", new os x projects "dwarf". part of historical, @ present, ios setting still "dwarf dsym file" because part of xcode symbolicates crash logs copied off ios devices uses dsym purpose. if planning test development build downloading device, , finger-launching , exercising outside debugger, having dsym handy understanding crashes run into. if you're running under debugger, of course, stop @ point of crash, don't need symbolicate crash report. other that, don't think lose switching dwarf ios. , spacedog noted, speed turn around time since debugger knows how lazily link dwarf needs, whereas dsym c

php - Get Value From Textbox to File_get_contents -

<div class="form-group"> <label for="inputsm">put url</label> <input class="form-control input-sm" id="inputsm" type="text"> <br> <input type="submit" class="btn btn-info" value="count contact"> </div> this code text box , button <?php $gettext = file_get_contents("", true); $contact = substr_count($gettext ,"contactid"); print_r($contact); ?> and code php value , count example i need put link https://s3-ap-southeast-1.amazonaws.com/cloudpoc2/us-east-1%3a4502ecdd-1994-40da-8eb2-b6ccc96d6be0/contacts/contact_2014_11_19_09_53_28_278.vcf in text box , click button show number of contact in file $gettext = file_get_contents("https://s3-ap-southeast-1.amazonaws.com/cloudpoc2/us-east-1%3a4502ecdd-1994-40da-8eb2-b6ccc96d6be0/contacts/contact_2014_11_19_09_53_28_278.vcf", true); you have su

Javascript: Async and jQuery's document ready / DOMContentLoaded -

i've 5 scripts need load on specific page. they're big libraries datatables or tinymce . i've been doing reading , found out use async in order not block page loading. some of pages include code like: <script type="text/javascript"> $(document).ready(function() { $("#title").on('input propertychange paste', function() { $("#slug").val(getslug($(this).val())); }); }); </script> this code needs library loaded in order work. otherwise i'll get error saying function not available. — happening right now. my doubts are: doesn't domcontentloaded fires after script loaded, if they're set async ? isn't jquery's $(document).ready() supposed happen after domcontentloaded , why script fails? if i'm wrong, how supposed avoid bottleneck caused not loading scripts asynchronously? thank you.

python - In what form should data be passed onto View? -

let's assume i'm following 'traditional' mvc pattern desktop applications (a simple crud app) using wxpython. the model utilises peewee orm interface postgres db. these objects are, obviously, custom classes , view has no idea them. let's define part class here: class part(basemodel): part_number = pw.charfield() kind = pw.charfield() description = pw.charfield() unit = pw.charfield(db_column = 'unit') the user clicks button , 'edit part' window pops up. window needs show part's details. the question is, model pass above class' instance view , view accesses instance's properties? (mypart.part_number) or convert them more simpler form list or dictionary? are using controller?. controllers integral part of model-view-controller pattern. act glue between model , view. need create view model , pass model through controller. please see example below. assume have viewmodel this public class reportviewmodel { publ

java - Deserialization of map with integer keys using Jackson -

i have serialize simple integer-to-string map json , read back. serialization pretty simple, since json keys must strings resulting json looks like: { "123" : "hello", "456" : "bye", } when read using code like: new objectmapper().readvalue(json, map.class) i map<string, string> instead of map<integer, string> need. i tried add key deserializer following: map<integer, string> map1 = new hashmap<>(); map1.put(1, "foo"); map1.put(2, "bar"); objectmapper mapper = new objectmapper(); simplemodule module = new simplemodule(); module.addkeydeserializer(integer.class, new keydeserializer() { @override public object deserializekey(string key, deserializationcontext ctxt) throws ioexception, jsonprocessingexception { system.out.println("deserialize " + key); return integer.parseint(key); } }); mapp

c++ - Non-const lvalue reference initialized to prvalue -

if class-type, expression a() prvalue, correct? why legal a &aref = a(); also, found this: a reference t can initialized object of type t, function of type t, or object implicitly convertible t. once initialized, reference cannot changed refer object. references initialized in following situations: 1) when named lvalue reference variable declared initializer [...] which justifies action. i new c++, initializer either expression formed call constructor or containing new operator?

Removing \n from list being split into variables - Python -

so here's code i'm working with: # initialization twitter oauth open(curdir + '\oauth.txt', 'r') f: words = f.readlines() data = [w.replace('\n', '') w in words] consumer_key = data[0] consumer_secret = data[1] access_key = data[2] access_secret = data[3] auth = tweepy.oauthhandler(consumer_key, consumer_secret) auth.set_access_token(access_key, access_secret) api = tweepy.api(auth) f.close() so basically, i'm trying read each line , deposit them api variables without stuff '\n'. file oauth.txt looks this: 45623sdajhjgsqqwdewf hrjkewrrew892391hnfbndsjhkfb278f93 hb3278dndlwwoerrewewr r3h278cewwooweoifnccvbdgdhsshdgs how can use keys alone input vars consumer_key, etc. without other chars '\n'? thanks lot. edit: adding reason why yours isn't working. environment.newline resolves \r\n on windows , \n on unix systems. given backslash in path, appears you're using windows, meaning \n

c# - Using SmtpClient to send an email from Gmail -

i'm trying connect gmail account through smtpclient seems not work should. specify port 465, enable ssl , define everything, takes 2 minutes , shows error message wasn't sent. what doing wrong here? try { mailmessage msg = new mailmessage(); msg.from = new mailaddress("myemail@gmail.com); msg.to.add(new mailaddress("theiremil@email.com)); msg.subject = "this subject"; msg.body = "this body"; smtpclient sc = new smtpclient("smtp.gmail.com", 465); sc.enablessl = true; sc.usedefaultcredentials = false; sc.credentials = new networkcredential("myemail@gmail.com", "pass"); sc.deliverymethod = smtpdeliverymethod.network; sc.send(msg); erroremail.text = "email has been sent successfully."; } catch (exception ex) { erroremail.text = "error: " + ex.message; } you need allow "less secure apps": https://support.google.com/accounts

android - questions about switching from C2DM to GCM -

i'm converting app c2dm gcm , have questions. i've modified gcmquickstart example found here: git clone https://github.com/googlesamples/google-services.git in class extends application, i've got: public class myapp extends application { @override public void oncreate() { super.oncreate(); if (this.checkplayservices()) { intent intent = new intent(this, registrationintentservice.class); startservice(intent); } else{ log.e(tag,"failed checkforgcm"); } } } afaik, starts service , it'll run forever or if operating system shuts down whereupon operating system restart it. correct? checkplayservices() makes sure android 2.3 or greater , google play services installed these requirements use gcm. correct? public class registrationintentservice extends intentservice{ private static final string tag = "regintentservice"; public registratio

java - check if there is at least a single true value in SparseBooleanArray -

i'm creating android app listview , i'm using line: sparsebooleanarray checkedpositions = list.getcheckeditempositions(); then want iterate on array if there @ least single value true in checkedpositions array. can done? you cannot that. create method you. public boolean containstruevalue(sparsebooleanarray sparsebooleanarray) { boolean containsboolean = false; (int = 0; < sparsebooleanarray.size(); i++) { if (sparsebooleanarray.valueat(i) == true) { containsboolean = true; break; } } return containsboolean; }

ember.js - EmberJS 1.13.3 / Component / Block template / access component property -

i'm using ember 1.13.3 (latest 1 of 2015-07-16). i have component defined way: import ember 'ember'; export default ember.component.extend({ tagname: 'li', yow: 'argh', }); it's corresponding hbs simple (the default): {{yield}} i use component way (in application.hbs): {{#side-menuitem name='medium' current=selectedmenuitem clicked='menuitemselected'}} {{#link-to name}}hey ... {{yow}}{{/link-to}} {{/side-menuitem}} i'm expectint see link label: hey ... argh. get: hey ... (without argh). there's similar thread here: accessing component scope within template block i tried also: {{view.yow}} , {{component.yow}}, no luck. looks ember 1.13 (still) has behavior: block format drops out of component scope , parent scope, there isn't available link parent scope component due isolation level. this undesirable..., , somehow thought behavior has been changed in 1.13 (toward compatibility 2.0), i'm not se

PHP session value defined in one file, is undefined in another file -

i have 2 php files, in first file: <?php session_start(); . . . $_session['favcolor'] = "green"; echo "ses: ".$_session['favcolor']; ?> and in second file: <?php session_start(); echo "ses: ".$_session['favcolor']; ?> when executing first page, see correct favcolor when executing second page in same browser, {"error":"undefined index: favcolor"}. know need check existence of key before using wondering why it's not there in first place because want achieve, store/restore session value between php calls. missing?

python - PyCharm Type error Message -

i'm newbie trying out ml/dbn in python (3.4) under pycharm (comm.ed 4.5). following definition def make_thetas(xmin,xmax,n): xs = np.linespace(xmin,xmax,n) widths = (xs[1:] - xs[:-1])/2.0 thetas = xs[:-1] + widths return thetas throws error "class 'tuple' not define ' sub ', '-' operator cannot used on instance" on - operator on third line (widths = ....) ideas on how code running under pycharm - works alright in interactive python window. thx. to all, after g'g lot have found workaround seems work within pycharm. workaround because (even python newbie) expected python not need explicit typecasting, not when using datatypes imported lib such numpy. def make_thetas(xmin,xmax,n): xs = np.array(np.linspace(xmin,xmax,n)) widths = (xs[1:] - xs[:-1])/2.0 thetas = xs[:-1]+ widths return thetas using docstrings type-hinting such below did not work def make_thetas(xmin,xmax,n): "&q

java - Groovy could not find matching constructor -

could explain me why simple piece of code not compile? node.groovy class node{ integer key string value node leftnode node rightnode node(){} node(integer k, string v){ this.key = k this.value = v } } binarytree.groovy class binarytree{ node root; def addnode(k, v){ def newnode = new node(k,v) if(!root){ root = newnode }else{ node currentnode = root node parent while(true){ parent = currentnode if(k < currentnode.key) { currentnode = currentnode.leftnode if(!currentnode){ parent.leftnode = newnode return } } else { currentnode = currentnode.rightnode if(!currentnode){ parent.rightnode = newnode retur

angularjs ng-bind-html html input part missing -

i have included ngsanitize display html in bind-html have bind following in code: $scope.discslist = '<div class="items text-center"><img src="assets/uploads/discs/'+obj.image+'" class="img-circle"><br><input type="radio" id="chkdisc'+obj.id+'" name="chkdisc" value="'+obj.id+'" required data-ng-model="formdata.disc"></div>'; and in controller have included $sanitize it binds html ng-bind-html="disclist" div images , div added, input element missing that: <div class="items text-center"><img src="assets/uploads/discs/disc9.png" class="img-circle"><br></div> i wants bind html div. i using angularjs 1.4 here have tried. js angular.module("test",['ngsanitize']) .controller("testctrl",['$scope','$sce',function($scope,

Python: How to atomically hardlink files for deduplication? -

i have application deduplicates contents of 2 directories using hardlinks. i'd protect code crashes, such traceback never result in loss of data. currently, code looks this: import os import tempfile path_a, path_b in paths_to_dedupe: handle, tmp = tempfile.mkstemp(dir=os.path.dirname(path_a)) handle.close() os.remove(tmp) os.link(path_a, tmp) os.rename(tmp, path_b) the problem code call os.remove() -- makes call mkstemp no longer entirely safe (because tempfile of same name created, unlikely). is there safer way this? i considered copying , modifying tempfile._mkstemp_inner() runs _os.link rather _os.open . the simplest method loop until os.link succeeds: while true: handle, tmp = tempfile.mkstemp(…) os.close(handle) os.remove(tmp) try: os.link(path_a, tmp) except oserror e: if e.errno == 17: # file exists continue raise break and in case, there's no real benefit using te

add dynamically foreign object in svg using javascript -

when run code shows me blank screen when update code using developer tool in chrome shows data. please explanation why shows when update code using developer tool of chrome, due dom @ browser runs again, if yes why not @ 1 first time shows. happen due foreignobject. <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title></title> </head> <body> <svg id="t"> <g> <text x="10" y="10">hello</text> </g> </svg> <script> var s = document.getelementbyid('t'); var g = s.childnodes[1]; console.log(g.childnodes[1].remove()); var foreign = document.createelementns('http://www.w3.org/2000/svg',"foreignobject"); foreign.setattribute('width', 500); foreign.setattribute('he

java - Transferring focus between focus traversal policy providers -

i have several custom panels arranged in basic boxlayout, on have set sortingfocustraversalpolicy (and set setfocustraversalpolicyprovider(true) , in order policy take effect). the custom focus traversal works within each custom panel, when tab out of last component in custom panel, focus goes first component in same panel, rather first component in next custom panel. how go "chaining" focus 1 custom panel another?

Android access django rest framework makes HTTP 500 -

i'm experienced developer android , developing android application has django server side on heroku cloud. i'm pretty new django , django rest framework dont how use except guide on website. what trying using volley/asynchttpclient/apache http contact django server. with each of these libraries got http 500 error on django in console output. what tried on each of them adding data body or parameters. on volley - overrided getparams , added them hash on asynchttpclient - made requestparams on httpclient(apache) - used list of namevaluepair , added them entity of urlencodedform http post request. i tried on volley , asynchttpclient add data body of request , didn't worked also. i thought of changing server side because of trouble django causing me , please if have answer please give :) this server side(django): class user(apiview): queryset = appuser.objects.all() def get(self,request,format=none): users = appuser.objects.all() seri

elasticsearch - Cannot select time field for default index -

i'm using kibana-4. following documentation here should able create index putting in elasticsearch.yaml file: put .kibana { "index.mapper.dynamic": true } i'm not sure understand how this, because yaml file should not take values formatted above block, right? i noticed .kibana default index, after inputting kibana console, asked input time field default index. however, input html element dropdown contained no options. without selecting time-field option not allowed create default index. supposed do? has else run similar problem? i understand problem faced you. faced same while using kibana 4 first time. here 2 possible solutions problem:- 1. input data elasticsearch contains timestamped field. upon inputting data field directly recognized kibana & showed in dropdown menu (where seeing empty). it empty because kibana couldn't recognize timestamped field data inserted in elasticsearch. 2. untick option of index contains t

mongodb - Randomizing unique data with mongo? -

i'm trying scramble email properties in db. email defined in mongoose model unique. here's script i'm attempting run in shell db.getcollection('users').update( {}, {$set{ email:'sanitized'+math.random()*100000000000000000+'@'+math.random()*100000000000000000+'.com' }}, {multi:true} ) i'm trying this: but comes error: duplicate key error index: test.users.$email_1 dup key i realize math.random() isn't perfect, command has never updated more first document in collection. how can want do? the math.random functions executing once each client-side , 1 constant email value being passed update function. if there not unique index on email, every user in database set same email. you individual updates this: db.getcollection('users').find().foreach(function(u){ db.users.update({_id : u._id}, {$set:{ email:'sanitized'+math.random()*100000000000000000+'@'+math.random()*10

loops - Simple PHP Templating With Looping -

hey wrote simple template system our designers use. uses str_replace under hood thing. its works great! issue i'd looping ( foreach ) on data passed. here's , example of template code $var_c = [ [ "head" => "a", "body" => "b", "foot" => "c" ], [ "head" => "x", "body" => "y", "foot" => "z" ] ]; $tpl_vars = [ "__{var_a}__", "__{var_b}__", "__{var_c}__" ]; $real_vars = [ $var_a, $var_b, $var_c ]; str_replace($tpl_vars, $real_vars, $content_body); note $var_c contains array , i'd loop through array. how achieve that. structure thinking __startloop__ loop var_c c c[head] c[body] c[foot] __endloop__ i cant seem head around how code this. :) update: twig, smarty , likes big , cumbersome work. intro

winforms - Add values to a combobox in c#.net from SQL Server -

tried few set of codes populating combobox table in sql server, no avail! combobox in windowsapplicationform.this code using public void binddata1() { myconnection prms = new myconnection(); using (sqlconnection con = prms.getconnection()) { string query = "select countryname countries"; sqlcommand cmd = new sqlcommand(query, con); sqldataadapter d = new sqldataadapter(query, con); dataset dt = new dataset(); d.fill(dt); combobox1.datasource = dt.tables[0]; combobox1.displaymember = "countryname"; } } the method called @ form load event, there no values in combobox @ runtime. try using datatable instead of dataset . datatable dt = new datatable(); d.fill(dt); combobox1.datasource = dt; combobox1.displaymember = "countryname";

java - ActiveMQ FailoverTransport reconnecting too fast on Linux compared to Windows -

i have 1 activemq broker on linux machine , standalone java application acts producer running on windows machine. both windows , linux machines using same version of java 7. i specify broker url be: failover://(tcp://10.0.112.49:61616)?timeout=1000&warnafterreconnectattempts=1&maxreconnectattempts=0` windows scenario: start application , automatically connects activemq broker. when stop broker, failovertransport tries reconnect every second. 2015-07-16 15:14:52,737 error [activemq task-1] (failovertransport.java:1099) csn: failed connect [tcp://10.0.112.49:61616] after: 1 attempt(s) this expected behavior. however, when run application on linux, instead of trying reconnect every second, reconnects every 5-10 milliseconds! wondering why behavior different. your problem don't understand timeout option. here documentation says timeout enables timeout on send operations (in miliseconds) without interruption of reconnection process

ios - target specifies product type 'com.apple.product-type.bundle.ui-testing', but there's no such product type for the 'iphonesimulator' platform -

when running swift project, got error. target specifies product type ' com.apple.product-type.bundle.ui-testing ', there's no such product type 'iphonesimulator' platform i found similar questions on this answer didn't solve problem. googled too, there no project product type inside. i'm using xcode 6.4 , swift 1.2 i had issue after adding product ui testing using xcode 7 beta , switching between xcode 6.4 , 7 beta. simple clean made go away.

Jenkins user-based job security -

i have single instance of jenkins on local machine using build our code. have different project teams working on different projects, , different jobs each project. eliminate possibility of 1 team accidentally messing team's job, have created multiple jenkins users. however, of users can log on still see of jobs. there way users see jobs pertain them? i have searched extensively no luck. haven't found plugins this. using matrix based security currently, , although can change permissions of users through this, can not apply specific permissions specific jobs. @ least knowledge. ideas? just clarify, want 1 of many teams log in user account in jenkins, , see jobs. jobs of other teams should not visible, ones assigned should visible when log on the closest thing have found in role strategy plugin, there user-based job filter turns out there feature in jenkins this, no plugins necessary! in configure global security section in manage jenkins, click "project

sql server - SQL Database Select, Sort, and Eliminate Duplicates without DISTINCT -

in sample sql database, i've got invoice totals , vendor names on 2 separate tables. as general orientation, here current code i've created: select top 5 invoicetotal, vendorname invoices join vendors on invoices.vendorid = vendors.vendorid order invoicetotal desc; i'm looking top 5 invoice totals displayed without repeating of vendor names. example, current output is: 137966.19 malloy lithographing inc 26881.40 malloy lithographing inc 23517.58 malloy lithographing inc 21842.00 data reproductions corp 20551.18 malloy lithographing inc however, target output like: 137966.19 malloy lithographing inc 21842.00 data reproductions corp 20076.01 smith & co 14590.00 tim's management ltd 13878.50 helloworld corp is can make happen in management studio? i've tried implementing distinct, doesn't seem work. any extremely appreciated. would following work? select top 5 max(invoicetotal) total, vendorname invoice

javascript - How to use this js script in Angular: have I got to create a service? -

i'm trying create small iot project external bluetooth sensor. i'm using sensortag ti , have couple of js library manage it. at moment i'm using simple html page js code, want move project ionic framework using angular. <script> // globals. var sensortag var values; var compensationx = 0; var compensationy = 0; function initialise() { initialisesensortag() } function initialisesensortag() { // create sensortag cc2650 instance. sensortag = evothings.tisensortag.createinstance( evothings.tisensortag.cc2650_bluetooth_smart) // set callbacks , sensors. sensortag .statuscallback(statushandler) .errorcallback(errorhandler) .keypresscallback(keypresshandler) .accelerometercallback(accelerometerhandler, 100) } function connect() { sensortag.connecttonearestdevice() } function disconnect() { sensortag.disconnectdevice() displaystatus('disconnected') } functio

git - list branches forked from current branch -

i'm organising code having branches new features , creating child branches feature related bugs. when come feature branch need command tell me branches (bugs) forked it. if there no related branches can assume it's safe merge feature master. just because can use git create infinite number of branches doesn't mean should. become unmanageable quite , potential benefits think you'll doing washed away irrelevance finding out how manage many branches. to extent, doesn't matter; git commits form directed acyclic graph anyway; they'll have property whether name them individual branches or not. increasing branch count increase confusion. anyway, answer question; given commit hash, can find out branches on doing: git branch --contains hash

python - vmin vmax algorithm matplotlib -

i write script calibration of image (dark frame , flat field)...here part of code for n in range(len(img)): pyfits.open(img[n],mode='update',memmap=true) im: imgg=im[0].data header=im[0].header imgg.astype(float) imgg=(imgg-dd)/df imgg[np.isnan(imgg)]=1 imgg.astype(int) plt.imshow(imgg,cmap=plt.cm.greys_r,vmin=0.5,vmax=1.5) plt.show() this part of code make calibration of image dark frame , flat field...when use @ plotting vmin vmax right picture dont know how vmin , vmax work.i need apply on image data (imgg) because when save data images without vmin vmax... any suggestion? and second question ...how can save data changes in fits files? when used im.close() work on 1 file dont work in loop. thanks edit ok here full script import numpy np import pyfits matplotlib import pyplot plt import glob dark=glob.glob('.../ha/dark/*.fits') flat=glob.glob('.../ha/flat/*.fits') img=glob.glob('.../ha/*.fits') sum

file - Using BufferedReader to read a single line in Java -

i have code reading csv. when try use filereader read solo line, makes code stop working. here code: try { string line = ""; filereader = new bufferedreader(new filereader(filename)); while ((line = filereader.readline()) != null) { string[] tokens = line.split(delimiter); (string token : tokens) { totaldata.add(token); if (!artists.contains(token)) { artists.add(token); } } (int l = 0; l <= 999; l++) { linedata = filereader.readline(); linearray[l] = linedata; } } } { filereader.close(); } when try read arraylist sizes , print data arraylist s above code below makes stop working: for (int l = 0; l <= 80; l++) { linedata = filereader.readline(); linearray[l] = linedata; } if comment loop, fine. need loop, how can edit code resolve issue? also, happening? for (int l = 0; l <= 80; l++) { linedata

java - GLFW with LWJGL - glfwGetKey once -

i'm developing game java , lwjgl3. don't understand how fix problem, i've tried search on internet information lwjgl minimal , couldn't find glfw. let's example have menu 4 buttons (new game, options, credits, exit) , count variable know 1 selected. every time arrow key pressed want subtract 1 select, select previous one, , same down arrow key, want add one. the problem following: if in frame 0 press arrow key count variable added in next frame key still pressed, added again. don't know how fix this, tried changing glfw_press glfw_release, want action happen when key pressed. if ((glfwgetkey(window, glfw_key_up) == glfw_repeat) && select > 0) { button[select].toggleselect(); select--; button[select].toggleselect(); } if ((glfwgetkey(window, glfw_key_down) == glfw_repeat) && select < button.length) { button[select].toggleselect(); select++; button[select].toggleselect(); } i know code can throw array inde

asp.net - IExceptionHandler does not handle UnsupportedMediaTypeException -

i have implemented exception handler ( iexceptionhandler ). handleasync method called when exceptions thrown inside controllers. however, when wrong content-type passed request , unsupportedmediatypeexception thrown in formatter, handler not called. instead default error message returned { "message": "the request entity's media type... "exceptionmessage": "no mediatypeformatter ... ... } i handle exceptions. missing here? you need catch global exceptionfilterattribute , , filter httpresponseexception , not unsupportedmediatypeexception . e.g. httpconfiguration.filters.add(new myhttpresponseexceptionfilterattribute()); it turns out unsupportedmediatypeexception wrapped in httpresponseexception time hits webapi pipeline. httpresponseexception not intercepted iexceptionhandler , because designed transport httpresponsmessage out client. unsupportedmediatypeexception automatically wrapped httpresponsmessage framew

java - Getting current stage GraphicsDevice in JavaFX -

is possible graphicsdevice of current javafx stage? i know able current screen via screen.getscreensforrectangle method, need graphicsdevice instead. use screen method, e.g. 1 of getscreensforrectangle() , find screen of interest. in graphicsenvironment obtained getlocalgraphicsenvironment() , iterate though each graphicsconfiguration of each graphicsdevice find devices bounds intersect bounds obtained screen.getbounds() . there may more one. typical iteration scheme shown here .

javascript - Angular Ajax temporaly variables -

i'm trying of number of records return ajax json file when i'm trying of print number records outside ".success block" don't value exits inside ".success block" example: var total = 0; $http.get("json/noticias.json") .success(function(response) { $scope.lista = response; total = response.noticias.length; alert(total);//print 3 }); alert(total);//print 0 i need print 3 in second 1 also. angularjs uses promise module called $q. have use then() or catch() json data after success var total = 0; $http.get("json/noticias.json") .success(function(response) { $scope.lista = response; response.total = response.noticias.length; ; alert(total);//print 3 }).then( function( response ) { alert(response.total); //print 3 }); i hope help

ruby - Rails 4.2.1: `rspec` results in a blinking cursor as if app is initializing, nothing ever happens (spring??) -

i've been working on new app few days, writing tests go. until last night there hadn't been problems. of sudden when run rspec cursor moves next line while waiting app initialize, except specs never run. seems permanently frozen/hanging , have use ctrl + c stop process. normally attribute spring gem freaking out. have in gemfile: group :development gem "spring" gem "spring-commands-rspec" gem "web-console" end however, used spring stop , problem continues. used ps aux | grep spring make sure spring processes stopped , still can't run tests. in desperation went far take spring , spring-commands-rspec our of gemfile , run bundle , , try again, process still hangs. not sure if related, when run ps aux | grep spring still output: me 72973 0.0 0.0 2432772 672 s000 s+ 1:40pm 0:00.00 grep --color=auto --exclude-dir=.bzr --exclude-dir=.cvs --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn spring i

jquery - Change textbox value using dropdown selected in php and mysql -

i have texbox , dropdown list populated mysql database.i want change textbox value using dropdown list, without refreshing page. here code , in advance. <select name="select" id="dropdownlist1"> <option id="0">-- select company --</option> <?php require("dbcon.php"); $getallcompanies = mysql_query("select * ifcandetails6"); while($viewallcompanies = mysql_fetch_array($getallcompanies)){ ?> <option id="<?php echo $viewallcompanies['tcuid']; ?>"><?php echo $viewallcompanies['tcname'] ?></option> <?php } ?> </select> here input field code: <input type="text" id="field1" value="<?php echo $viewallcompanies['tcname']?>" disabled/> use following $(documen

php - Issues outputting database information if a column has a selected word -

i attempting output information database, if record has 'pending' in column 'status' filled in. of right breaking , have multiple records 'pending' filled in, in column. what doing wrong? <?php $con = mysqli_connect("localhost", "root", "", "db"); $run = mysqli_query($con,"select * user_requests order id desc"); $numrows = mysqli_num_rows($run); if( $numrows > 0) { while($row = mysqli_fetch_assoc($run)){ $pending_id = $row['status']; if($pending_id == ["pending"]){ $pending_id = $row['user_id']; $pending_firstname = $row['firstname']; $pending_lastname = $row['lastname']; $pending_username = $row['username']; } } } echo $pending_firstname; ?> update: i first result this... if( $n

java - Regarding `Variable (var-name) might not have been initialized` -

import java.io.*; interface myioaction { void ioaction(reader rdr) throws ioexception; } class myclass { public static void main(string args[]) throws ioexception { reader rdr1; int read = rdr1.read(); //statement 1 myioaction myio = (rdr2) -> { int ch = rdr2.read(); //statement 2 }; } } in above code, statement 1 produces following error variable rdr1 might not have been initialized whereas statement 2 compiles successfully. so, why same error in statement 1 not produced in statement 2 ? in statement 2, rdr2 in essence formal argument method. initialized when method invoked. see lambda quick start or lambda expressions tutorials more information what's going on statement 2.

sorting - Selection Sort Algorithm in R -

i need understand type of code , action happens here. instance, take vector x defined integer (8,6,5,4,2,1,9). the first step of function check if condition given, length of vector higher 1. x, condition given. next step highlight position of smallest value in vector, 6. dont understand happens in next steps , why has combine vector? selsort <- function(x) { if(length(x) > 1) { mini <- which.min(x) c(x[mini], selsort(x[-mini])) #selsort() somewhere in here -> recursion } else x } in recursion, there 2 key cases: base case - input produces result directly recursive case - input causes program call again in function, base case when length of x not greater 1. when happens, return x. when reach base case, not running function more times, track through of previous recursive cases finish executing selsort() calls. the recursive case when length greater 1. this, combine smallest value in our vector result of selsort() without smallest valu

javascript - Difficulty in displaying text in Force layout ? (D3js) -

Image
i using force layout , have problem in displaying text in layout. here screenshot : and code : svg.selectall("circle") .data(data) .enter().append("circle") .attr("class", "node") .attr("fill", "blue") .attr("r", 4.5) .attr("dx", ".10em") .attr("dy", ".10em") .text(function(d){ return d.name}); the text there in code, not showing in browser. changed color nothing helps. as @lars kotthoff mentioned circle s don't support text() . should change code sample this: svg.selectall("circle") .data(data) .enter().append("circle") .attr("class", "node") .attr("fill", "blue") .attr("r", 4.5) .attr("cx", ".10em") .attr("cy", ".10em"); svg.selectall("text")

Django: Using named urls in @login_required decorator -

most of views in django app use @login_required decorator. also, have 3 different login urls. views have corresponding login urls hardcoded @login_required decorators. @login_required('myapp/logintype1'): def usertype1_home(request): # further dode # ... @login_required('myapp/logintype2'): def usertype2_home(request): # further code # ... since number of such views quite large, whenever change login url in urls.py have change login-url in decorators. want use {% urls 'urlpatter1' %} , {% urls 'urlpatter2' %} . can use reverse ? how can use named url patterns instead of hard coding url patterns in @login_required decorator? somewhere in top of views.py after import ... statements add this login_type1 = reverse_lazy('urlpatter1') # or login_type1 login_type2 = reverse_lazy('urlpatter2') # or login_type2 and use these variables later @login_required(login_url=login_type1) ... update: rev

linux - Jedi Vim Python subclasses are not detected on TAB-completion -

Image
the issue on arch (1) & debian jessie (2) where: 1. > uname -r 4.0.5-1-arch > echo $pythonpath /usr/lib/python2.7/ debian jessie without pythonpath set. my vim compiled python. :python import sys; print(sys.version) 2.7.10 (default, may 26 2015, 04:16:29) [gcc 5.1.0] i tried following arch linux packages: > pacman -s python2-jedi vim-jedi completion works on classes not on subclasses. import os # os built-in library. os. # ycm not complete members of class. i removed them , downloaded git package. > cd ~/.vim/bundle/jedi-vim/jedi/test/ && ./run.py summary: (0 fails of 962 tests) in 18.819s > cd ../ && ./setup build && ./setup install and again, completion works on classes not on subclasses. my previous question sent me jedi-vim vim youcompleteme python subclasses not detected on tab-completion in arch linux i realized did error due incomprehension. trying import following way:

JavaScript Working When Access From Internet But Not Responding When Access Page From Folder Assets On WebView Android -

i try access page url : demo face tracker using android webview. , using code: protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); wv = (webview) findviewbyid(r.id.webview); wv.setwebchromeclient(new webchromeclient()); wv.setwebviewclient(new webviewclient(){ @override public void onpagefinished(webview view, string url) { super.onpagefinished(view, url); } }); wv.getsettings().setjavascriptenabled(true); wv.addjavascriptinterface(new webappinterface(this), "android"); wv.loadurl("http://auduno.github.io/clmtrackr/clm_image.html"); } and works! but when copy of page (include javascript) local, , access form assets folder app return not responding. this code use access local assets: protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.a

Last Segment before the question mark ( ? ) in Javascript -

here url http://localhost:8080/bim/teacher/reports/section-exercise/assignment?assessmentid=206a9246-ce83-412b-b8ad-6b3e28be44e3&classroomid=722bfadb-9774-4d59-9a47-89ac9a7a8f9a i want grab last segment of url before ? , ignore after ? can please teach me how ? i've tried var href = location.href; var lastsegment = href.substr(href.lastindexof('/') + 1); console.log(lastsegment); i got assignment?assessmentid=206a9246-ce83-412b-b8ad-6b3e28be44e3&classroomid=722bfadb-9774-4d59-9a47-89ac9a7a8f9a i want assignment try this var pathparts = location.pathname.split('/'), basename = pathparts[pathparts.length - 1]; or super handy one-liner (sometimes have remind myself arrays have methods) var basename = location.pathname.split('/').pop(); see urlutils.pathname

node.js - npm install installing extra packages not specified in package.json -

i have typical package.json on aws ec2 instance. i'm running npm install , instead of installing { "name": "angular-app-server", "description": "back end server support our angular app", "version": "0.0.1", "private": true, "dependencies": { "assert": "^1.3.0", "async": "^0.9.0", "bcrypt-nodejs": "0.0.3", "body-parser": "^1.13.1", "connect-multiparty": "^1.2.5", "express": "~3.0", "express-namespace": "~0.1.1", "express-session": "^1.11.1", "forever": "^0.14.2", "mongodb": "^2.0.36", "multiparty": "^4.1.2", "nodemailer": "^1.3.4", "open": "0.0.3", "passport": "

osx - NSWindow returns nil (NSApplication) -

i've come across issue cannot access app's main window, returns nil . let window = nsapplication.sharedapplication().mainwindow i've found similar questions: how main window (app delegate) other class (subclass of nsviewcontroller)? but doing: let window = (nsapplication.sharedapplication() as! nsarray).objectatindex(0) doesn't seem work either. do have mess around in storyboard? thanks in advance. update: i'm trying port objective-c. nswindow *mainwindow = [[[nsapplication sharedapplication] windows] objectatindex:0]; nslog(@"%@", mainwindow.contentviewcontroller); this returns proper value, when put in viewdidload() block in nsviewcontroller , i'm guessing there wrong nsapplication.sharedapplication() . it can return nil if main app window not active on macos. instance ran when making drag , drop file uploader. if window not in front (on operating system) return nil. following line of code activate app (b

sql - CASE Statement inside a subquery -

i able create following query after post below select * duppri t exists ( select 1 duppri symbolup = t.symbolup , date = t.date , price <> t.price) order date sql check when pairs don't match i have realized need add case statement indicate when above criteria fits, type value equal between duppri , t.duppri. occurs because of case sensitivity. query attempt clean portfolio accounting system unfortunately allowed numerous duplicates because didn't have strong referential integrity or constraints. i case statement produce column 'ismatch' date |type|symbol |symbolup |concatt |price |ismatch 6/30/1995 |gaus|313586u72|313586u72|gaus313586u72|109.25|different 6/30/1995 |gbus|313586u72|313586u72|gbus313586u72|108.94|different 6/30/1995 |agus|srr |srr |agussrr |10.25 |different 6/30/1995 |lcus|srr |srr |lcussrr |0.45 |different 11/27/1996|lcus|lly |lly |lcuslly |76.37 |matched 11/27/1996