Posts

Showing posts from January, 2014

java - Passing Custom Binder between packages -

how send custom binder object between android packages? service activity (in separate packages)? i've been playing while cannot seem work. custombinder contained in library both packages have copy of. the error @ casting point in onserviceconnected. see "casting failed". i've noticed bit more interesting things this. when override tostring method in custombinder, , make return string, , print out binder get, "android.os.binderproxy" instead. updated code reflect: package 1 (contains activity) private serviceconnection mconnection = new serviceconnection(){ @override public void onserviceconnected(componentname name, ibinder binder){ log.d("tag",binder.tostring()); try{ custombinder nbinder = (custombinder)binder; log.d("tag","it worked!"); }catch(exception e){ log.d("tag","casting failed again"); }

c - Why does this code yield a segmentation fault? -

i writing program goal generate random 3 digit number, , have user make 10 guesses @ it. if guess correct digit in correct spot, considered "hit". if guess correct digit it's in wrong spot, considered "match". example, if number guessed 123, , enter 329, 2 hit , 3 match. code far shown below: #include <stdio.h> #include <time.h> #define min 100 #define max 999 int main() { //declare variables int userdig1 = 0, userdig2 = 0, userdig3 = 0, randdig1 = 0, randdig2 = 0, randdig3 = 0, guesses = 0; //generate random 3 digit number srand(time(null)); //seed randdig1 = rand() % ((max + 1) - min) + min; //corresponds first digit randdig2 = rand() % ((max + 1) - min) + min; //corresponds second digit randdig3 = rand() % ((max+ 1 ) - min) + min; //corresponds third digit //a loop keeps track of number of guesses (guesses = 1 ; guesses <= 10 ; guesses++) { //store user's guess appropriate variables

java - How to bind SQLite data to textview in Android -

i'm looking simplest way bind value in sqlite column textview. have hundred textviews across number of activities. i have dbhelper class define table , columns , sqlcontroller class define methods insert, , update data. of pretty boilerplate code. for each activity open database, set cursor , data, update database when activity closes. is there library can use bind fields in db textview directly? use butterknife bind data objects views , considering implementing android data binding, wondering if there's way go directly database view without having write boilerplate code?

increment - Incrementing +1 through range -

i trying randomise set of increments on large number of variables. so example, have 5,000 people, each of these people has base value of 1, adding 1 has variable affect each of these people. example adding 1 person a, means there base number increments 1.1. adding 1 person b increments base 1.4 , on. i have figured out how different values assigned each +1 action vlookups, need loop +1 increments through range. i have base values setup in column b:b can't figure out how loop script. have far: function increment(){ var ss = spreadsheetapp.getactivespreadsheet(); var sheet = ss.getsheets()[1]; var range = sheet.getrange("b1"); var value = range.getvalue(); for (var = 1; >= range; i++); range.setvalue(value + 1); } but increments 1 "b1". how loop runs continously, every second through b1, b2, b3, b4 etc adding +1 each time? simply adding range name using "b" + in getrange() function, , move loop. or can use offse

javascript - How to create a dropdown menu without messing up the rest of the code....? -

i know question has been asked before million times, can't seem find answer or solution fits exact situation or code. (if there one, please link me!) i'm trying create simple dropdown menu on horizontal navigation has logo image centered links on either side. have bootstrap installed, can't seem figure out simple way code using framework, said screw , built 1 scratch. it doesn't have straight html/css, i'm not super familiar js (still learning). here's current code: #header { height: 40px; position: relative; margin: 80px auto 0; } #header ul { margin: 0 auto; width: 800px; padding: 0; list-style: none; } #header ul li { float: left; width: 97px; } #header ul li:nth-of-type(4) { margin-left: 217px; } #header ul li { text-transform: lowercase; text-decoration: none; display: block; text-align: center; padding: 12px 0 0 0; height: 28px; color: #000;

What is "Memory Management" in iOS? -

i have been given these 2 questions in interview. 1. **memory management** in ios. 2. reference counting? can 1 explain me? new ios. please me out. in advance! application memory management process of allocating memory during program’s runtime, using it, , freeing when done it. well-written program uses little memory possible. in objective-c, can seen way of distributing ownership of limited memory resources among many pieces of data , code. when have finished working through guide, have knowledge need manage application’s memory explicitly managing life cycle of objects , freeing them when no longer needed. reference counting

algorithm - How to code a dynamic solution for the 0/1 Knapsack with a specific number of each item -

is possible code dynamic solution 1/0 knapsack problem has requirement number of each item? for example knapsack requires: 1 of item_one 2 of item_two 3 of item_three 1 of item_four 1 of item_five 1 of item_six each item has weight , there max weight of 60000 in sense normal knapsack problem. beyond difference im trying minimize value instead of maximize. here brute force code in vba im running on hunderes of items need faster solution. help! function knapsacksolver(item_one, item_two, item_three, item_four, item_five, item_six) dim knapsack variant redim knapsack(1 9, 1 5) variant dim value long dim minvalue long dim cap long dim weight long minvalue = 9999999 weight = 0 cap = 60000 = 1 ubound(item_one) j = 1 ubound(item_two) t = 1 ubound(item_two) if j <> t m = 1 ubound(item_three) n = 1 ubound(item_three)

java - How to verify that error was logged with unit tests -

let's have following class this: public class myclass { public static final logger log = logger.getlogger(myclass.class); public void mymethod(string condition) { if (condition.equals("terrible")) { log.error("this terrible!"); return; } //rest of logic in method } } my unit test myclass looks this: @test public void testterriblecase() throws moduleexception { mymethod("terrible"); //log should contain "this terrible!" or assert error logged } is there way determine log contains specific string "this terrible"? or better, there way determine if logged error @ without looking specific string value? create custom filter message , record if ever seen. @test public void testterriblecase() throws moduleexception { class terriblefilter implements filter { boolean seen; @override public boolean isloggable(logrecord record) { if ("this

Open certain number of files java -

i want open x number of file(s) when user prompts file. if user decides open file1, file1 display. if file3 prompt, file1 file3 display , etc. how can go doing this? system.out.print("pick file open:"); string promptfile = keyboard.nextline(); scanner filenumber = new scanner(new file(promptfile )); you can store filenames in string array: string [] filenames = {"file1", "file2", "file3"} //etc then need run loop loop variable ranging 1 promptfile , inside loop have go thru each member of filenames , open display.

web services - SoapUI basic authentication to c# code -

i have problem web service want connect to. in soapui used basic authentication username , password (domain empty), , changed wss-password type passwordtext , without problem connect web service. when try connect using c# code: webservice service = new webservice(); service.clientcredentials.username.username = "user"; service.clientcredentials.username.password = "pass"; service.somemethod(); it returns "forbidden" error.

javascript - HTML5 Canvas on Desktop and Mobile -

i'm building web app user can create own image html5 canvas. (i'm using jcanvas). on desktop, canvas size 500x500 (so, generate images of 500x500 pixels). on mobile, canvas size 300x300, still want generate images size of 500x500 pixels. right now, i'm out of idea , can't make work! the width , height attributes of canvas define how many logical pixels there in canvas. not same physical pixels, i.e. how many pixels canvas using on screen. can control css. can this: <canvas style="width: 300px; height: 300px" width=500 height=500> </canvas> this gives canvas displays 500x500 image in 300x300 area

c++ - boost optional and user-defined conversion -

i unable write correct user defined conversion type item . i've tried: #include <iostream> #include <boost/optional.hpp> struct { int x; }; struct item { boost::optional<int> x_; item(){} item(const a& s) : x_(s.x) { } operator boost::optional<a>() const { boost::optional<a> s; if (x_) { s->x = *x_; } return s; } }; std::vector<a> geta(const std::vector<item> &items) { std::vector<a> a; (const auto &i : items) { if (i.x_) { a.push_back(*static_cast<boost::optional<a>>(i)); // <- line causes error } } return a; } that how use it: int main() { a; a.x = 3; item i(a); auto v = geta({i}); return 0; } g++ -std=c++11 says: in file included /usr/include/boost/optional.hpp:15:0, test.cpp:2: /usr/include/boost/optional/optional.hpp: in

Which DSpace Docker container is officially endorsed by the DSpace community? -

the docker hub contains number of dspace docker containers: https://hub.docker.com/search/?q=dspace&page=1&isautomated=0&isofficial=0&pullcount=0&starcount=0 i have experience https://hub.docker.com/r/quantumobject/docker-dspace/ likes create administrator according instructions command line action needs happen after deployment it runs dspace 5.3, latest official stable release of dspace runs java 7 instead of java 8 (which not tested dspace yet) dislikes there's issue postgres, reported closed on https://github.com/quantumobject/docker-dspace/issues/2 still encountered it it can't run on 1gb aws instance, because deploys both xmlui jspui it runs tomcat 8 instead of tomcat 7 it seems on ubuntu 15 instead of ubuntu 14 lts (probably more of personal preference) don't me wrong - love work done contributor, wondering if there reference implementation out there, or if 1 serve reference implementation.

c# - Difference between list.Count > 0 and list.Count != 0 -

i have list of things. there difference between list.count > 0 , list.count != 0 ? or performance difference in these codes? if (list.count > 0) // stuff if (list.count != 0) // stuff note: list.count can't less ziro.. is there difference between list.count > 0 , list.count != 0 ? yes. first 1 evaluates whether list.count greater 0 . second 1 evaluates whether not equal 0 . "greater than" , "not equal" different things.

ios - Any way to store struct in NSCache -

is there way store struct values in nscache ? when read apple documentation can store anyobject it. there couple of work around 1 convert sturct class, second convert sturct values dictionary expensive operation if dataset big. suggestion? i'm going chance arm on 'no' (without workarounds). nscache resoundingly on over objective-c side of runtime, written work nsobject s, bridged via anyobject . unlike nsdictionary , nsarray there no equivalent swift collection compiler can bridge between. implementation points aside: nscache doesn't live in world understands value semantics more sophisticated c atoms. that being said, easiest workaround create object container struct, making bridging explicit owned whomever wants use cache: class yourstructholder: nsobject { let thing: yourstruct init(thing: yourstruct) { self.thing = thing } } cache.setobject(yourstructholder(thing: thing), forkey:"whatever") (cache.objectforkey(&q

php - How to get 'vendor/doctrine/tests' in my Symfony2 project? -

i want unit test orm entity repository written in symfony2 cookbook have no doctrine\tests\ormtestcase class in vendor directory. how can vendor\doctrine\tests directory? thank you.

javascript - jQuery. Find the element where attribute isset -

i need find cell in specific row isset attribute colspan , , no matter contains im trying this var y = 2; // example $table.find('tr[data-y="'+y+'"] > td:not([colspan=""])'); but returns cells in row jsfiddle you want attribute selector it: var $colspanned = $table.find('tr[data-y="'+y+'"] > td[colspan]'); -jsfiddle-

javascript - Run through array and check values of <td> cells in jQuery -

scenario: have table 10 rows, each containing of class '.t3_dc'. these cells contain value of between 1.0 , 9.9 for each td, want check if score/value between amount , if so, change colour. example, < 7.0 red, 7-8 stay white, above 8 green. i got far after few attempts biggest obstacle seems storing each array , running through , checking them individually. $(document).ready( function() { function scores () { var score = $('td.t3_dc').text(); var num = parsefloat(score); alert(score)[0]; if(num < 7 ) { $(score).css('color','green'); } else { $(score).css('color','red'); } }; settimeout(scores, 2000); }); note: timeout function exists table takes couple of seconds load on page q. how can loop through array of 's , check each value, adding colour necessary? imho, don't need timeout, function first fire when page loaded. loop classes using each() , check it's value

python - Dealing with variable number of keyword arguments to send requests -

related python 2.7 how 1 go building request through variable number of kwargs when using requests . i using requests module directly interact rest api requires variable number of keyword arguments in order successful. rather re-writing same get/post request code, maintain within single api class. handling variable number of arguments seems boil down series of if-else statements isn't particularly readable. for example: def request(self): try: if self.data: request = requests.post(url=self.url, headers=self.headers, data=self.data, timeout=self.timeout, verify=false) else: request = requests.get(url=self.url, headers=self.headers, timeout=self.timeout, verify=false) ... ... preferably request properties build on time , them passed through single or post request (granted, above code still require minor). if make attributes default same values arguments requests.po

ios - Is it possible to delegate without `presentViewController` -

this question has answer here: passing data between view controllers 35 answers currently having issues passing data since assuming passing data through delegates require presentviewcontroller currently have set up gameviewcontroller *gamevc = [self.storyboard instantiateviewcontrollerwithidentifier:@"gameviewcontroller"]; gamevc.istwoplayer = istwoplayer; gamevc.delegate = self; [self presentviewcontroller:gamevc animated:yes completion:nil]; so it's possible sent data, have navigation controller in between present modally story through board has relationship segue gameviewcontroller , why can't presentviewcontroller i wondering if possible sent data other way i assuming passing data through delegates require presentviewcontroller well, thats not true. can pass data long object valid. reason calling presentviewcontroller

javascript - Why the coordinates of a location in streetview of Google Earth and Google Maps are different? -

i new google maps development , have issue struggling time. the lat/long of location in street view of google earth , google maps ( web browser) not matching. here coordinate values of location. google maps coordinates (in street view) : 51.81883690 -0.811931358 google earth coordinates (in street view): 51.81883889 -0.811955556 the difference begins @ 5 decimal position looking precision till 6 decimal points. below methodology followed derive coordinates. my requirement exact coordinates of object (pole, manhole etc.) through google streetview. did not find option place marker on mouse click in streetview (in webbrowser), had placed marker around street view camera location though javascript code (code:: panorama.getposition()+ incremental values) directly assigning lat/long marker. also, dragged marker location of interest. marker's lat/long noted down. observed these coordinates not matching base data. now tried google earth alternative; had placed 'plac

javascript - Jquery - get selector when using after -

i have code: $('#.element').on('click', function(e) { $(this).after('<div>...</div>'); }); and want other stuff created div in same line of code without using id . how can that? i mean this: $(this).after('<div>...</div>').css('border', '1px').fadeout('5000'); this above code set border , fadeout element $(this) , want done new created div element. this why .insertafter() have been introduced, return objects in reverse manner. $('<div>...</div>').css('border', '1px').insertafter($(this)).fadeout('5000');

php - Encoded json gets corrupted/escaped by PostgresQL? -

i using yii2 model hooked postgresql database. have behavior encodes , decodes attributes of model to/from json. encode/decode, using json helper, json::encode , json::decode methods. the column in table of json type. example of ends in database: "{\"additional_tags\":[\"#здрасте\",\"#кафе\"],\"vk\":\"vk.com\\\/privetik\"}" when try decode php array, here's what's returned instead: '{"additional_tags":["#здрасте","#кафе"],"vk":"vk.com\/privetik"}' edit: come think of it, string seems fine, behavior of ::decode method strange. essentially, remove escape slashes, instead of converting php array or throwing exception. what should fix this? appreciate feedback. looks string in database encoded twice. try passing through json::decode time, bet return array.

jsf - PrimeFaces responsive is not working -

Image
i want use primefaces responsive , when run app in pc working fine, if resize browser app works expected if open app phone, responsive not working. i using primefaces 5.3.rc1, mojarra 2.2.0 , glassfish 4.0 code : <h:form> <p:datatable var="car" > <p:column headertext="id"> <h:outputtext value="colid" /> </p:column> <p:column headertext="year (p3)" priority="3"> <h:outputtext value="year" /> </p:column> <p:column headertext="brand (p2)" priority="2"> <h:outputtext value="brand " /> </p:column> <p:column headertext="color (p4)" priority="4"> <h:outputtext value="color" /> </p:column> </p:datatable> </h:form> left phone, rigth pc you m

linux - How to add new local host? -

how can set new local host new hostname? [main@evghost ~]$ host evghost host evghost not found: 3(nxdomain) [main@evghost ~]$ host localhost localhost has address 127.0.0.1 [main@evghost ~]$ cat /etc/hosts # # /etc/hosts: static lookup table host names # #<ip-address> <hostname.domain.org> <hostname> 127.0.0.1 localhost.localdomain localhost ::1 localhost.localdomain localhost # end of file i want have new localhost name evghost maybe: 127.0.0.1 evghost evghost you should specify question little more precise. then try localhost evghost evghost // localhost evghost.localdomain evghost // localhost evghost // 127.0.0.1 evghost

java - Android - Arduino Bluetooth communication -

hi im new android studio , java , hoping read data arduino android. the plan have button widget on interface send signal arduino , have flex sensor send info android via bluetooth. the bluetooth module have hc-06 , code designed phone sends '*' arduino , sends random value android random value shown on textbox on interface. change meant happen on java ofcourse im not sure how it. please help. this arduino code first #include <softwareserial.h> const int rx_pin = 2; const int tx_pin = 3; softwareserial serial(rx_pin, tx_pin); char commandchar; void setup () { serial.begin (9600); andomseed(analogread(0)) } void loop () { if(serial.available()) { commandchar = serial.read(); switch(commandchar) { case '*': serial.print(random(1000) + "#"); break; } } } and here code done on android studio: package com.example.ft.myapplication; import android.bluetooth.bluetoothadapter; import android.bluetooth.bluetoothdev

jquery - How can I check if a DNN template editor token is empty or not? -

i have form people can enter information, , each field has token. example if enters name in textbox labeled name, if use [name] token, output entered name on page. i building page output information entered in form name: name entered <span>name: </span>[name] and wondering how can check if token [name] if empty or not, , if field empty, remove element. thank you ok - there doesn't seem built-in way conditional formatting on token replacement. there have been thoughts extending token replacement ( http://www.dnnsoftware.com/community-blog/cid/154432/templating-or-the-art-of-making-complicated-things-simple ), have modify events planner module in order this, , lot of work. as sort of hack, might suggest following: <span id="spnnamelabel">name: </span><span id="spnnametext">[name]</span> <script language="javascript"> if (document.getelementbyid("spnnametext").innerhtml

javascript - Boostrap 3 popover dismiss not working as expected in latest version of bootstrap (3.3.5) -

i trying dismiss bootstrap 3 popover when user clicks anywhere on page besides popover. found excellent example on jsfiddle , added plain html file using latest version of bootstrap 3 (3.3.5). in jsfiddle example works expected because using bootstrap version 3.0.2. in application following happens: i click button show popover, click outside of popover dismiss it. when click button show popover second time popover not open. if click button show popover again opens. here in html file. <!doctype html> <html> <head> <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <title></title> </head> <body> <br/> <br/> <br/> <br/> <br/>

How to store library's resources in azure -

i'm creating mobile service use nmecab library, need dictionary files referred code using server.mappath dicdir = httpcontext.current.server.mappath(@"../app_data/ipadic") when ran service locally work fine when published service on azure system.io.directorynotfoundexception: not find part of path thrown i googling , found this topic on so, recommended use localresource refer local storage think should used in case uploading service not in case. so, how can store resources in azure? the localresource area (also known app_data) temporary data. if storing permanent data, should use 1 of azure storage apis handle it. however, temporary data can stored on disk. topic referenced suggested, should use localresource: localresource localresource = roleenvironment.getlocalresource("downloadedtemplates") the reason path not work assumes current directory in specific place , hence app_data relative that. not case on mobile services. use

php - How can I create this mysql "SELECT" query? -

i have 2 mysql tables named 'categories' , 'products'. these data of tables. mysql> select * categories; +-------------+--------+----------------------+-------------+ | category_id | parent | name | description | +-------------+--------+----------------------+-------------+ | 1 | null | products | null | | 2 | 1 | computers | null | | 3 | 2 | laptops | null | | 4 | 2 | desktop computers | null | | 5 | 2 | tab pcs | null | | 6 | 2 | crt monitors | null | | 7 | 2 | lcd monitors | null | | 8 | 2 | led monitors | null | | 9 | 1 | mobile phones | null | | 10 | 9 | lg phone | null | | 11 | 9 | anroid phone | null |

Is there a python module that will give an estimate of remaining time for a long running process? -

i have long running process io bound. loop uploading items somewhere, of these items take more time others, days whole process slower time can't hardcoded. is there module given progress through loop in terms of (current position, final position) evaluate first few iterations give estimate of remaining time, update on every iteration? i'm thinking progress output tools wget , apt-get. i guess write myself wondered if exists already.

javascript - How to get dojo module path from inside of a widget -

i have dojoconfig below: var base = location.href.split("/"); base.pop(); base = base.join("/"); var dojoconfig = { async: true, parseonload: false, isdebug: false, packages: [{ name: "library", location: base + '/js/lib' }, { name: 'widgets', location: base + '/js/widgets' }]; how access location of widgets inside of loaded module or widget? so official site , dojo/require that. here example: require(["dojo/_base/xhr", "dojo/dom"], function(xhr, dom){ // points $dojoroot/dijit/form/tests/testfile.html var url = require.tourl("dijit/form/tests/testfile.html"); xhr.get({ url: url, load: function(html){ dom.byid("foo").innerhtml = html; } }); });

javascript - How to do a queue in order to wait 5 seconds to execute a function -

i need put debounce everytime object updated. here function need solve updateplayeramount (data) { this.state.playerslots[data.position - 1].playeramount = data.playeramount; } the param data returns this { playeramount : 10, position : 2 } the playeramount key change value on every click in element. so: everytime user clicks on element, amount going change in view, need amount updated every 5 seconds, does't matter whether user clicks 7 times within 2 seconds. i did settimeout of 5 seconds, issue had, user clicked on element 7 times within 5 seconds, , couldn't see changes 1 one full change once. , need user visualizing changes in view every 5 seconds. according explanation coworker gave me, need put new changes in array, , listen changes... (?) but, how ? did ? ps: using lodash don't how use in case. update i did this _playeramount = (data) => { this.state.playerslots[data.position - 1].playeramount = data.player

Mapping openNLP or StanfordNLP in elasticsearch -

i trying map opennlp enable parsing of filed in document. using following code: "article": "properties": "content" : { "type" : "opennlp" } prior create mapping, downloaded named entity extraction binary file sourceforge.net , installed/unpacked using curl in elasticsearch plugin folders. i following error message when tried run above mapping code. "error": "mapperparsingexception[no handler type [opennlp] declared on field [content]]" "status": 400 after quick googling i've found this: https://github.com/spinscale/elasticsearch-opennlp-plugin i assume you're trying install it. - it's outdated , not supported recent elasticsearch versions. the purpose of seems extract data files , index them tags. elasticsearch mapper attachments type plugin that. encourage use instead of onennlp. quick extract documentation: the mapper attachments plugin adds attachment

matlab - Filter elements from a 3D matrix without loop -

i have 3d matrix h(i,j,k) dimensions (i=1:m,j=1:n,k=1:o) . use simple case m=n=o = 2 : h(:,:,1) =[1 2; 3 4]; h(:,:,2) =[5 6; 7 8]; i want filter matrix , project (m,n) matrix selecting each j in 1:n different k in 1:0 . for instance, retrieve (j,k) = {(1,2), (2,1)} , resulting in matrix g: g = [5 2; 7 4]; this can achieved for loop: filter = [2 1]; % meaning filter (j,k) = {(1,2), (2,1)} = 1:length(filter) g(:,i) = squeeze(h(:,i,filter(i))); end but i'm wondering if possible avoid for loop via smart indexing. you can create linear indices such output expansion needed first dimension bsxfun . implementation - szh = size(h) offset = (filter-1)*szh(1)*szh(2) + (0:numel(filter)-1)*szh(1) out = h(bsxfun(@plus,[1:szh(1)].',offset)) how work (filter-1)*szh(1)*szh(2) , (0:numel(filter)-1)*szh(1) gets linear indices considering third , second dimension elements respectively. adding these 2 gives offset linear indices. add first dimenion lin

javascript - Browserify with Angular and non-CommonJS libraries -

i trying convert angular project use commonjs , browserify. issue though of angular modules not in commonjs format. best way include them? for example, in app-js, have: angular .module('app', ['ngroute', 'ngresource', 'ngcookies', 'ngsanitize', 'ngmessages', 'flash', 'smart-table', 'ui.bootstrap', 'isteven-multi-select']) so of these, can npm version , add var ngroute = require(ng-route) , etc. of modules, 'isteven-multi-select' not have commonjs version. how can include in code? how make them commonjs: add in file : require('./isteven-multi-select'); and create isteven-multi-select.js file in same directory (you can change directory in require change path). now in isteven-multi-select.js add @ top: module.exports = angular.module('isteven-multi-select',[]) //rest of code, example .service('someservice'

ios - How to pause and restart NSTimer.scheduledTimerWithTimeInterval in spritekit [SWIFT] when home button is pressed? -

i'm new swift & spritekit , wanted know how possible detect if home button pressed ? the main problem have nstimer.scheduledtimerwithtimeinterval running generate multiple characters in didmovetoview , , going well, when pause game home button , restart game few seconds later, characters floods out alot. assume nstimer had not been paused , therefore, flooding alot of characters when relaunching app. want know simple solution , example, how pause when home button pressed, , resuming when app relaunches ? love here you! testenemy = nstimer.scheduledtimerwithtimeinterval(1.2, target: self, selector: "timerupdate", userinfo: nil, repeats: true) ///this part of project code generating characters within didmovetoview nsnotificationcenter.defaultcenter().addobserver(self, selector: selector("appenterintobackground:"), name:uiapplicationdidenterbackgroundnotification, object: nil) nsnotificationcen

How to delete a dict_key in python -

i trying code algorithm dijkstra in python3 , think have confused python 2 , python 3. want remove unseen_node . code shown below d={} p={} node in graph.keys(): d[node] = -1 p[node] = "" d[start] = 0 unseen_nodes = graph.keys() #graph dict while len(unseen_nodes)>0: shortest = none node = '' temp_node in unseen_nodes: if shortest == none: shortest = d[temp_node] elif(d[temp_node]<shortest): shortest = d[temp_node] node=temp_node unseen_nodes.remove(node) #gives attributeerror: 'dict_keys' object has no attribute'remove'

python : understaning partial functions -

i trying head around snippet : def a_func(a, b, c): print "a: %s\nb: %s\nc: %s" %(a, b, c) def partial(fn, *args): print "args in partial : %s" %str(args) def fn_part(*fn_args): print "fn_args in fn_part : %s" %fn_args return fn(*args+fn_args) return fn_part print_fn = partial(a_func, 'a', 'b') print_fn('c') the output : args in partial : ('a', 'b') fn_args in fn_part : c a: b: b c: c how control flow here ? the function object print_fn points fn_part , has variables predefined ( a , b ). how can view variables defined function ? the fn_part() function accesses args closure . read returned function object: >>> print_fn = partial(a_func, 'a', 'b') args in partial : ('a', 'b') >>> print_fn.__closure__ (<cell @ 0x102a90be8: tuple object @ 0x10075bf38>, <cell @ 0x102a901d8: function object @ 0x102

Relayjs Graphql user authentication -

is possible authenticate users different roles solely trough graphql server in combination relay & react? i looked around, , couldn't find info topic. in current setup, login features different roles, still going trough traditional rest api... ('secured' json web tokens). i did in 1 of app, need user interface, 1 return null on first root query if nobody logged in, , can update login mutation passing in credentials. main problem cookies or session inside post relay request since does'nt handle cookie field in request. here client mutation: export default class loginmutation extends relay.mutation { static fragments = { user: () => relay.ql` fragment on user { id, mail } `, }; getmutation() { return relay.ql`mutation{login}`; } getvariables() { return { mail: this.props.credentials.pseudo, password: this.props.credentials.password, }; } getconfigs() { return [{

Vim: How do I map vimgrep command to avoid typing the file pattern? -

i search in projects using vimgrep command in fahsion: :vimgrep /{pattern}/gj app_name/**/*.py all significant source code lives inside app_name directory , search inside python files, create command avoid writing search path on , on (i'm using project specific vimrc custom mappings). this: :proj_search {pattern} you can use command command -nargs=1 projsearch vimgrep /<args>/gj app_name/**/*.py :h 40.2 edit: mcubik pointed out user-defined commands must start capital letter. cannot use ":x" , ":next" , ":print" . underscore cannot used! can use digits, discouraged.

javascript - JQuery Variables for Arithmetic being treated as strings -

this question has answer here: how ensure javascript addition instead of string concatenation (not adding integers) 4 answers i trying month 3 months selected month using html select box , jquery in below code. code not adding 2 variables instead treating them 2 strings. assist me right? <body> <form role="form" class="form-inline"> <div class="form-group"> <label class="control-label" for="q1month"> quarter 1 month </label> <select class="form-control" id="q1month"> <option selected value=''>--select month--</option> <option value='1'>january</option> <option value='2'>february</option>

javascript - jplayer bug for iphone -

i using last version of http://jplayer.org/ on site , have problems loading on iphone thread. page super simple. <html> <head> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.js" ></script> <script type="text/javascript" src="script/jquery.jplayer.js" ></script> <title>test iphone</title> </head> <body> test <script> $(document).ready(function () { $("#jquery_jplayer_1").jplayer(); }); function supersimple() { $("#jquery_jplayer_1").jplayer("clearmedia"); $("#jquery_jplayer_1").jplayer("setmedia", { artist: "queen", mp3: "/test/examples/blue.monday/music/innuendo.mp3", title: "innuendo" }); $("#jquery_jplayer_1").jplayer("play"); } function supersimplewithdelay() { settimeout(function () {

Handling errors when using custom forms with django-allauth -

i'm using django-allauth , custom login , signup forms in application. works until user submits error login or signup form. error shows on different page. e.g intended login form @ uri: /payment/e886371a-fa52-4718-b8bc-e53fe8ac2bea/ however, when there form error in above page, redirects default login uri: /accounts/login/ , displays error there. is there way make sure user returned original page incase of form error , have error(s) displayed there? thanks in advance. if have login form on uri /payment/e886371a-fa52-4718-b8bc-e53fe8ac2bea/ , not want redirect /account/login, not write action of form. , create payment view can handle authorization directly on payment uri. <form class="login" method="post" action="/payment/e886371a-fa52-4718-b8bc-e53fe8ac2bea/"> ... </form> in payment view can extends class allautho/accounts/views/loginview, handles normal email/password auth.

loops - How to set a base case in Erlang -

i trying set base case in erlang recursive step, however, whenever do, end warning variable new_array unused . curious how go setting base case function, seems when set mine defaults running base case instead recursing first. % base case function(list, array, 0) -> print_board(array); function(list, array, size) -> % stuff here new_array = array, function(list, array, size-1). thanks in advance help! erlang checking if declare variable not use it. interesting warning must analyzed, because points issue in program. in case of first clause, detect base case of recursion because size 0, , in case wants return variable array. first parameter of function useless in case. indicate erlang, can name variable _ or _list . % base case function(_list, array, 0) -> print_board(array); function(list, array, size) -> % stuff here new_array = array, %% compiler complain because new_array unused function(list, array, size-1).

model view controller - MVC bundle with Azure CDN - how to enable caching -

Image
i have web site hosted in azure has lot of javascript , css small pages. have javascript , css delivered via cdn. azure provides neat , convenient mechanism allow described here https://azure.microsoft.com/en-us/documentation/articles/cdn-cloud-service-with-cdn/#integrate-aspnet-bundling-and-minification-with-azure-cdn in short, add following code bundleconfig.cs bundles.usecdn = true; var version = system.reflection.assembly.getassembly(typeof(controllers.homecontroller)) .getname().version.tostring(); var cdnurl = "http://axxxxxx6.vo.msecnd.net/{0}?v=" + version; scriptbundle scriptbundle = new scriptbundle("~/bundles/xx", string.format(cdnurl, "bundles/xx")); scriptbundle.include( "~/scripts/modernizr-*", "~/scripts/jquery-{version}.js", "~/scripts/jquery.signalr-{version}.js", "~/scripts/jquery.watermark.js", .... i have followed instructions

python - Accessing RedShift Table inside UDF -

i have 2 tables: main table rules reference table(if, else if, else) i cannot join tables directly because reference tables contains if,else if condition data. same functionality have implemented using distributed cache udf in hive , want same behavior in redshfit also. i want apply reference rules table each , every main table rows. whether can access entire reference table inside udf? currently it's impossible access underlining db udf on redshift, not supported yet.

java - Multi-Dimensional ArrayList initialized with values -

i'm new coding. teacher introduced arrays , arraylists. have multi-dimensional array this: private string[][] pods = {{"pod1", ""}, {"pod2", ""}, {"pod3", ""}, {"pod4", ""}}; i'd switch arraylist, need edit information in there. how this, multi-dimensional arraylist? i'd initialize above information. i've tried this: private arraylist<arraylist<string>> pods = new arraylist(); whenever put stuff between parenthesis, invalid operator error. by way, in case wondering - not class assignment. i'm trying on own. thanks. firstly, approach half-correct. you can have arraylist of arraylist s double-dimensional array. however... you're initializing list raw type. java 7, can change assignment diamond-type inference: list<list<string>> pods = new arraylist<>(); in earlier versions: list<list<string>> pods

json - How to extract property that is an object in keen.io -

using extractions api in keen.io can't specific properties objects. curl "https://api.keen.io/3.0/projects/project_id/queries/extraction?api_key=read_key&event_collection=collection_name&timeframe=this_7_days" gives me properties, let's say {"result": [ { "userid": 1, "keen": {"timestamp": 'val', "created_at": 'val'}, "name":'val' } ]} but if want "userid" , "keen", "keen" gets ignored. curl "https://api.keen.io/3.0/projects/project_id/queries/extraction?api_key=read_key&event_collection=collection_name&timeframe=this_7_days&property_names=["userid","keen"]" {"result": [{"userid": 1}...]} i noticed can specific properties keen object if specify: property_names=["userid", "keen.timestamp"] result {"result": [

python - Accessing attributes on literals work on all types, but not `int`; why? -

i have read in python object, , such started experiment different types , invoking __str__ on them — @ first feeling excited, got confused. >>> "hello world".__str__() 'hello world' >>> [].__str__() '[]' >>> 3.14.__str__() '3.14' >>> 3..__str__() '3.0' >>> 123.__str__() file "<stdin>", line 1 123.__str__() ^ syntaxerror: invalid syntax why something .__str__() work "everything" besides int ? is 123 not object of type int ? you need parens: (4).__str__() the problem lexer thinks "4." going floating-point number. also, works: x = 4 x.__str__()

javascript - How to display custom search results in grid in dynamics crm 2015 online? -

i'm working dynamics crm 2015 online, want provide way custom search on accounts , display results in standard account grid control, operate standard quick search. reason wanting results standard grid control results can natively flow various charts accounts. what have far custom button on account home command ribbon. have custom javascript behind button takes in crmparameter of selectedcontrol, gives me grid itself. have looked on grid control object , dug sdk documentation related grid control, haven't come across way put data grid control. has done before? in advance!

ios - Using enum string type as dictionary key in swift 2.0 -

i have enum enum filtertype:string { case unitsoldfilter = "unitsoldfilter" case amountfilter = "amountfilter" } i want method in want save corresponding value func getfilterfortype(filterfor:filterfortype) -> nsdata? { if let data: nsdata = nsuserdefaults.standarduserdefaults().objectforkey(filterkey) as? nsdata{ return data } return nil } but getting error can't use filterkey directly. how can solved. two things. in swift 2.0 don't need specify string enum corresponds if they're same string. so enum filtertype:string { case unitsoldfilter = "unitsoldfilter" case amountfilter = "amountfilter" } becomes enum filtertype:string { case unitsoldfilter case amountfilter } and inside of method you're going use rawvalue property. func getfilterfortype(filterfor:filterfortype) -> nsdata? { if let data: nsdata = nsuser