Posts

Showing posts from August, 2015

java - Strange issue with an array -

so i'm in middle of working on class called planner [no main in it's separate class], i'm having issue declaring array eclipse. need enter in eclipse see because have no idea means 'syntax error on token ";", , expected'. here code: import java.util.scanner; public class planner { private int maxevents = 1000; private int numevents = 0; private int choice; int[] anarray; anarray = new int [1000]; public void planner() { scanner scan = new scanner (system.in); system.out.print("press 1 add event. 2 display events day. 3 display events week. 4 quit: "); choice = scan.nextint(); if (choice == 1){addevent();} if (choice == 2){displayonedate();} if (choice == 3){displayoneweek();} if (choice == 4){system.out.println("have day.");} else {planner();} } public void addevent() { event newevent = new event(); if (numevents == maxevents){system.out.println("error: no more room.");}

C Pointers Past Paper -

i'm looking @ past paper course i'm doing @ university, , there question c pointers. i reckon have reasonable grasp of how work, question confusing me: consider running c program fragment: int x[4] = {0,2,4,6}; int *y; y = &x[2]; *(x + 2) = y[1] + 1; value of expression *y afterwards? (a) 2 (b) 4 (c) 5 (d) 7 (e) 8 now, in answers said question, says answer d . i'm super confused, seeing as: the value of x not declared, i'd have thought impossible evaluate x+2 y isn't array, how can y[1] evaluated? why 7 correct answer here? lets break down: int x[4] = {0,2,4,6}; x [0] = 0 x [1] = 2 x [2] = 4 x [3] = 6 int *y; pointer integer y point location in x x [0] = 0 // <-- y ? x [1] = 2 // <-- y ? x [2] = 4 // <-- y ? x [3] = 6 // <-- y ? y = &x[2]; have specified y points x[2] x [0] = 0 x [1] = 2 x [2] = 4 // <-- y (or y[0]) x [3] = 6 *(x + 2) same x[2] so: x[2] = y[1] + 1

asp.net mvc - Razor - How do I output the current cshtml filename -

for debugging purposes, output html comment indicating filename of current cshtml file @ beginning , end of every cshtml file. for example, i'd when view source of generated webpage, see this: <!-- begin _layout.cshtml --> ... headings , such ... <!-- begin about.cshtml --> ... generated content about.cshtml ... <!-- end about.cshtml --> ... footers , such ... <!-- end _layout.cshtml --> i'm new platform, i'm not sure right terminology this, let alone in api look. i'm hoping @ least can edit of cshtml files , reference object @ runtime contains filename property, in syntax similar to: <!-- begin @object.optionalproperty.optionalsubproperty.filename --> or, alternatively, way modify rendering engine automatically @ beginning , end of every rendered file. thank time , responses.

c unix execl not working with string built with strcat -

i trying run execl pathname built command line arguments. not working hardcoded strings being concatenated still did not work. if supply char *path = "some path name" , pass execl, works correctly. #include <stdio.h> int main(int argc,char *argv[]){ //set char path name char pathname[256]; strcat(pathname,"/bin/"); strcat(pathname,"ls"); //"ls" replaced arg[1] int pid=fork(); if (pid==0){ execl(pathname,"ls",(char *)0); } else{ wait((int*)0); } return 0; } i've printed out pathname make sure "/bin/ls" is. the problem here: char pathname[256]; strcat(pathname,"/bin/"); you did not initialize pathname . therefore, contents "indeterminate" , call strcat has officially known undefined behavior -- allowed literally anything . concrete thing happened was, there binary garbage in memory space allocated pathname , , strcat cheerfully treated string, contents of

cocoa - Coreplot Legend drawing outside of plot frame -

Image
i have chart os x app can resized window. expected when width reduced enough legend truncated or clipped. however, spilling outside of plot area shown below. ideally, legend truncate or @ least clip contents. how can done? my legend setup follows - (void)configurelegend { // 1 - graph instance cptgraph *graph = self.graphhostingview.hostedgraph; // 2 - create legend cptlegend *thelegend; if (!thelegend) { thelegend = [cptlegend legendwithgraph:graph]; } //configure text cptmutabletextstyle *textstyle = [cptmutabletextstyle textstyle]; textstyle.color = [cptcolor colorwithcomponentred:0.612f green:0.612f blue:0.612f alpha:1.00f]; textstyle.fontname = @"helveticaneue"; textstyle.fontsize = 12.0f; thelegend.textstyle = textstyle; // 3 - configure legend thelegend.numberofcolumns = 1; thelegend.fill = nil; thelegend.borderlinestyle = nil; thelegend.swatchsize = cgsizemake(10.0, 10.0); thel

java - Using Default Locale Separator with NumberFormat, and then rounding number -

i have java code: numberformat nf = numberformat.getnumberinstance(locale.getdefault()); decimalformat df = (decimalformat)nf; newcurr = df.format(dcurr); basically, pass in number, 12.344. i want rounded 2 places , use locale's default separator (either "." or ","). so, example in countries in europe, want 12,34 so far code above, halfway there. 12,344. can't find place decimalformat of ("#.##") can rounded. in other words, can incorporate decimalformat df=new decimalformat("#.##"); in above? or have find way? edit: thinking have old way of (100.00 * var)/ 100.00 , pass in? the method setmaximumfractiondigit work. see rest of available methods: http://docs.oracle.com/javase/7/docs/api/java/text/decimalformat.html#setmaximumfractiondigits%28int%29

asp.net mvc - Custom validation of HttpPostedFileBase -

i use mvc5. i've got issue file uploading using httppostedfilebase. i've got form can can choose file disk , type information it(in textbox). when submit form controller action called. in action open file , check if has specific data(related data textbox). validation here. can't using jquery - it's complex. server side validation option. if validation fails return model(with file) view after i've got validation error next file field file field empty. i've read that's hard return file view. don't want use ajax upload file. want simple. if got article can help, please share me. how can solve problem? i know mentioned not using ajax file upload, think solution simple one. using following jquery plugin ( https://blueimp.github.io/jquery-file-upload/ ), can automate process , if there validation issues in file, can return following model error. string errors = "errors returned complex logic"; if (!string.isnullorempty(errors)) {

mysql - SQL split values to multiple rows -

i have table : id | name 1 | a,b,c 2 | b i want output : id | name 1 | 1 | b 1 | c 2 | b if can create numbers table, contains numbers 1 maximum fields split, use solution this: select tablename.id, substring_index(substring_index(tablename.name, ',', numbers.n), ',', -1) name numbers inner join tablename on char_length(tablename.name) -char_length(replace(tablename.name, ',', ''))>=numbers.n-1 order id, n please see fiddle here . if cannot create table, solution can this: select tablename.id, substring_index(substring_index(tablename.name, ',', numbers.n), ',', -1) name (select 1 n union select 2 union select 3 union select 4 union select 5) numbers inner join tablename on char_length(tablename.name) -char_length(replace(tablename.name, ',', ''))>=numbers.n-1 order id, n an example fiddle here .

java - how to get index or position of listview control -

hello guys new android programming. want create puzzle game in user sort html unsorted tags dragging them on screen. using listview control store unsorted html tags. have implemented following library: https://github.com/terlici/dragndroplist now trying position or index of list item after user drop list item can compare user sorted list items actual sorted items. here code main.java puzzlemanager pm = new puzzlemanager(this); pm.insertpuzzle("<html>,</h1>,<h1>,</html>,<body>,</body>", "<html>,<body>,<h1>,</h1>,</body>,</html>"); cursor cursor = pm.getpuzzle(1); pm.close(); string s = cursor.getstring(1); list<string> puzzlelist = arrays.aslist(s.split(",")); arraylist<map<string, object>> items = new arraylist<map<string, object>>(); for(int = 0; < puzzlelist.size(); ++i) { hashmap<string, object> item = new hashmap<string, obj

c# - Is there a situation in which using `i <= 2` in place of `i < 3` in loops would cause a change in behavior of the loop? -

this silly question. lot of data extrapolation for loops in applications. in cases tend find i <= 2 easier read/interpret i < 3 . based on know should mean same thing, i'm wondering if there special cases evaluated differently when used in for loop. example, if used ++i instead of i++ . provided i integer, expressions i<=2 , i<3 should identical in function. (they may different in terms of speed performance) if i has type float , double , decimal , or related, value of 2.3 fail first test, pass second test. if overload operator< or operator<= , make possible.

c# - WCF showing 403 Forbidden using SSL and client certificates -

we having problem wcf - getting error below when trying connect. there tons of suggestions various configurations, having tried them use help. we using https transport security, using real ssl certificate got godaddy. seems installed , working when browse web pages on site. no authentication, can connect our wcf service. for authentication, using client certificates created ourselves. these client certificates working fine before switched https, when using message security self-signed server certificate (which pain because had clients install server certificate). error http request forbidden client authentication scheme 'anonymous'. inner exception: remote server returned error: (403) forbidden server configuration file <system.servicemodel> <bindings> <wshttpbinding> <binding name="newbinding0"> <security mode="transport"> <transport clientcredentialtype="certificate"

regex - Removing Code by using rereplace -

hi have following code, using following code remove contents page not know: i using regex, , cannot use jsoup, please not provide jsoup link or code because useless use here me.. <cfset removetitle = rereplacenocase(cfhttp.filecontent, '<title[^>]*>(.+)</title>', "\1")> now above same way, want use follwoing things: 1. <base href="http://search.google.com"> 2. <link rel="stylesheet" href="mystyle.css"> 3. , there 5 tables inside body, want remove 2nd table., can guide on scott right, , leigh right before, when asked similar question, jsoup best option. as regex solution. possible regex there problems regex cannot solve. instance, if first or second table contains nested table, regex trip. (note text not required between tables, i'm demonstrating things can between tables) (if there nested table, regex can handle it, if there nested table, in other words: unknown), gets lot m

reactjs - transition.retry() seems to be removing the ‘?’ from the query-string -

i using willtransitionto static method auth. here’s example i’m following. my transition.retry() going original route along it’s original query-string. query-string missing question mark @ beginning, instead of going route intended in transition, it’s going /authtoken=xyz123 so, the user goes http://wickedsweet-react-site.com/?authtoken=xyz123 react routes (via transition.redirect ) http://wickedsweet-react-site.com/waitforserverauth server authing , returns react routes (via transition.retry() ) http://wickedsweet-react-site.com/authtoken=xyz123 oops how can avoid stripping of ? ? incidentally, don’t want authtoken query string @ point because we've authed, now, that’s secondary concern. here willtransitionto method. mixins: [reflux.connect(stores.authdatastore, 'auth_data')], statics: { willtransitionto: function (transition, params, query) { var auth_data = stores.authdatastore.getdata(); if (!auth_data.authenticated) {

php - Allow login to website only if request comes from another specific website -

i have php/mysql website (website 1) has login system asks pin code (just long numeric string). user has 2 ways of login in code: going website 1 login page , enter code in typical login form clicking in website 2 on link carries pin code value. link has format http://myurl.com/login.php?pin=123456789 . calls function receives pin parameter , processes login. website 2 located in different domain/server website 1 . until here works fine. now come's question. know if when using second method described above, if it's possible allow login (assuming pin correct) only if link has been clicked in specific website . the way works now, link use login website 1. want prevent that, want allow happen if link has been clicked win website 2. the idea "detect" referring website in login function, , allow if matches url (or other unique identifier) of website 2. if using "plain" link not allow wouldn't problem, i'm flexible way use this, in end n

bash - append given variable in stream of cpp files using awk/sed by ignoring backslash -

i have variable in shell script follows: var=file1.cpp file2.cpp file3.cpp file4.cpp i want append " folder/subfolder/ " every .cpp file. use following sed command helps partially: echo $var | sed 's/^/'"$i"'\//g;s/\s/ '"$i"'\//g' $i --> "folder" , sed adds "/" this sed able append " folder/ " files.... unable append " folder/subfolder " every file. how can modify sed add "folder/subfolder/" path files. can modify somehow ignore backslash "/ " in $i variable ( i.e. ignore "/" in folder/subfolder you can use different delimiter sed # also can combine s command single sed example $ echo $var | sed -r 's#(^| )#\1folder/subfolder/#g' folder/subfolder/file1.cpp folder/subfolder/file2.cpp folder/subfolder/file3.cpp folder/subfolder/file4.cpp or if want use variables inside sed $ re="folder/subfolder/"

php - Mention API - Mark a mention as READ -

using api here: https://dev.mention.com/resources/alert_mentions/#put-accounts-id-alerts-alert-id-mentions-mention-id from understand, if want mark specific "mention" read, this: $browser = new \buzz\browser(new \buzz\client\curl); $params = ['read' => true]; //tried $url = "https://api.mention.net/api/accounts/" . $this->getaccountid() . "/alerts/{$alert_id}/mentions/{$mention_id}"; if(!empty($params)) { $url .= '?' . http_build_query($params); //i think isnt needed because pass $params below $browser->put worth try. } $response = $browser->put($url, array( "authorization: bearer {$this->getaccesstoken()}", "accept: application/json", ), $params); if (200 != $response->getstatuscode()) { return false; } however, when run code, doesn't produce errors , infact returns valid response, "read" flag still set false. also tried: $params

android - Deleting items from list view bug -

so have problem listview when delete data database. problem other items in list view mest have noted when delete second bottom problem occurs database //getrowrevers public cursor getallrowre(){ string where=null; string orderby = id_key + " desc"; cursor cursor=db.query(true, database_table, all_key, where, null, null, null,id_key + " desc", null); if(cursor!=null){ cursor.movetofirst(); } return cursor; } //delete public boolean deleatrow(string idrow){ string where=id_key+"="+idrow; return db.delete(database_table, where, null) != 0; } public void deleatall(){ cursor cursor=getallrowre(); long idrow=cursor.getcolumnindexorthrow(id_key); if(cursor.movetofirst()){ do{ deleatrow(cursor.getstring((int) idrow)); }while(cursor.movetonext()); } } so here how managed list view working think method not be

database - How to Get time from CSV data? -

i have downloaded csv file database. in date field found 1416551169 1417798664 1415727808 etc times please can please tell how extract time , date 01:04:2014 10:30 pm thank that unix timestamp. can convert unix time stamp excel following excel formula (assuming unix time stamp in a1 ) =a1/(60*60*24)+"1/1/1970"

javascript - How do I make D3js script responsive to window size? -

i trying make example in d3js, http://bl.ocks.org/nsonnad/4481531 but make graph responsive window size. how that? tried searching online , looks making svg responsive seem solution, can't seem implement make work. please help?

c# - Remove unnecessary xsi and xsd namespaces from wcf -

i have built web services working except trying remove xsi , xsd namespaces. i have seen lot link showing have use custom serializer : xmlserializernamespaces namespaces = new xmlserializernamespaces(); namespaces.add(string.empty, string.empty); but did not find way implement in code. here code : [servicecontract, xmlserializerformat] [aspnetcompatibilityrequirements(requirementsmode = aspnetcompatibilityrequirementsmode.allowed)] public class myuser { [operationcontract] [webget(responseformat = webmessageformat.xml, uritemplate = "getuserinfo?token={userid}", bodystyle = webmessagebodystyle.bare)] public personnresponse validatetoken(string userid) { var response = new personnresponse(); response.userid = userid; response.firstname = myotherservicegetfirstname(userid); response.lastname = myotherservicegetlastname(userid); return response; } [datacontract(name = "person", namespace = "&

excel - How do I add an array INDEX function nested inside of a GETPIVOTDATA function? -

i have workbook 2 spreadsheets. sheet 1 has pivot table, sheet 2 has comparable data , getpivotdata formula. having trouble getting formula work. think because have nested index/match array formula (which works find on own), i'm not sure how fix it. here have far: =getpivotdata("[m].[u a]",'sheet 1'!$a$10,"[a].[p]","[a].[p].[r t 1].&["&'sheet 2'!f$1&"]","[s].[s n]","[s].[s n].&["&index('sheet 1'!a:a,match('sheet 2'!a12,left('sheet 1'!a:a,find("_", 'sheet 1'!a:a&"_")-1),0))&"]") i getting #ref error. have suggestions? you missing argument in index bit. assume 1 column number.

python - Metaclass error when extending scipy.stats.rv_continuous mocked for Read the Docs -

in python project, i’m extending scipy.stats.rv_continuous this: class genlogisticgen(lmomdistrmixin, scipy.stats.rv_continuous): ... i’m trying build documentation on read docs , getting build errors: class genlogisticgen(lmomdistrmixin, scipy.stats.rv_continuous): typeerror: metaclass conflict: metaclass of derived class must (non-strict) subclass of metaclasses of bases note i’m mocking out scipy.stats module per read docs faq . i guess mocking out base class goes wrong. what?

Is adding 1 to a number repeatedly slower than adding everything at the same time in C++? -

if have number a, slower add 1 b times rather adding + b? a += b; or for (int = 0; < b; i++) { += 1; } i realize second example seems kind of silly, have situation coding easier way, , wondering if impact performance. edit: thank answers. looks posters know situation have. trying write function shift inputted character number of characters on (ie. cipher) if letter. so, want 1 char += number of shifts, need account jumps between lowercase characters , uppercase characters on ascii table, , wrapping z a. so, while doable in way, thought easiest keep adding 1 until end of block of letter characters, jump next 1 , keep going. the language c++ not describe how long either of operations take. compilers free turn first statement second, , legal way compile it. in practice, many compilers treat 2 subexpressions same expression, assuming of type int . second, however, fragile in seemingly innocuous changes cause massive performance degradation. small changes in

angularjs - Why functions are returned from angular services -

while defining angular services, 1 expected pass constructor function. constructor function initialized using "new" keyword , object returned "new" set service. far good. however come across instances programmers creating services below: app.service('aobj', function aclass(){ return function(a,b){ alert(a + b); }; }); this called aobj(1,2) although undertsand aobj end being function, cannot understand why programmers initialize services way. constructor functions have definition like: app.service('aobj', function aclass(){ this.var1 = undefined; this.calculate = function(b){ alert(this.var1 + b); }; }); then 1 call aobj.var1 = 1; aobj.calculate(2); can elaborate on purpose of defining services using former method ? plnkr: http://plnkr.co/edit/tpl:frtqqtnoy8befhs9bb0f this depends on kind of api want expose service. return object , call them myservice.methoda() , myservice.methodb() i

javascript - Detecting mousewheel with onscroll -

i tried several ways detect accurately mousewheel / dommousescroll event, seems result vary browser browser, , above hardware hardware. (ex: macbook magic trackpad fires many mousewheel events, etc.) there has been many attempts of js library "normalize" wheeldelta of mousewheel event. many of them failed (i don't find relevant question anymore there point failure). that's why try solution without mousewheel event, rather onscroll event. here example of scrolling / mousewheel detection hidden container scrolls ( #scroller ), , normal container ( #fixed_container ) normal content. as #scroller has finite height (here 4000px), cannot detect scrolling / mousewheel infinitely... how allow endless scroll events (by setting infinite height #scroller ? how?) ? code / live demo : <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <style> body {

ios - Wait for subview to be displayed, then process, then remove subview -

i have spent week trying figure out how this. what want display subview, http calls backend, , after remove subview. ... //display view [superview addsubview:blurredoverlay]; [superview bringsubviewtofront:blurredoverlay]; //after blurredoverlay displayed, try login user dispatch_group_t d_group = dispatch_group_create(); dispatch_queue_t bg_queue = dispatch_get_global_queue(dispatch_queue_priority_default, 0); dispatch_group_async(d_group, bg_queue, ^{ //try login user success = [self loginuser]; nslog(@"success=%i", success); [nsthread sleepfortimeinterval:10.0]; //here force thread not return immediatly }); dispatch_group_wait(d_group, dispatch_time_forever); //remove view after thread done processing [blurredoverlay removefromsuperview]; this not working. if have [blurredoverlay removefromsuperview]; uncommented, blurredoverlay never display. if comment out, blurredovleray displayed can't remove it. what need display blurredoverlay fi

html - Hide vimeo play bar in bootstrap -

i'm trying find out how hide play bar in bootstrap vimeo embed. here's bootply i tried doing based off this guy's code but had no luck getting work within bootstrap. you can use css this. to hide controls added display none controls div div.controls { display: none; } you can specific controls just progress bar or play button. it's you.

Rust: Executing dereferenced closure inside a task -

i have code takes vector of functions , iterates on them , executes each 1 @ each step. trying incorporate tasks loop these function calls can executed asynchronously instead of having first 1 block second 1 , on... let mut arr: vec<|i32| -> i32> = vec::new(); arr.push(function1); arr.push(function2); let ref num_in = os::args()[1]; let num_str = num_in.to_string(); let num = match from_str::<i32>(num_str.as_slice()) { some(x) => x, none => panic!("not number"), }; f in arr.iter_mut() { spawn(proc(){ println!("{}", (*f)(num.clone())); }); }; without task, , doing println! inside loop code runs fine, in blocking way trying avoid using tasks. task these errors , notes... error: trait 'core::kinds::send' not implemented type '&mut |i32| -> i32' note: closure captures 'f' requires captured variables implement trait 'core::kinds::send' there couple of issues in co

Phalcon PHP NativeArray accessing multidimensional array using Volt Template -

i able add multi language support in phalcon using volt template. but can't access phalcon multi dimensional nativearray in volt. here gettranslation function: private function _gettranslation() { global $config; if ( isset($config[$_server['http_host']]['language']) ) { $language = $config[$_server['http_host']]['language']; } else if ( $this->session->get('auth') ) { $language = "pt"; } else { //ask browser best language $language = $this->request->getbestlanguage(); } //check if have translation file lang if (file_exists(__dir__ . "/../translations/".$language.".php")) { require __dir__ . "/../translations/".$language.".php"; } else { // fallback default require __dir__ . "/../translations/en-us.php"; } //return translation object return new \phalcon\translate\

combinatorics - Number of combinations (N choose R) in C++ -

here try write program in c++ find ncr. i've got problem in result. not correct. can me find mistake in program? #include <iostream> using namespace std; int fact(int n){ if(n==0) return 1; if (n>0) return n*fact(n-1); }; int ncr(int n,int r){ if(n==r) return 1; if (r==0&&n!=0) return 1; else return (n*fact(n-1))/fact(n-1)*fact(n-r); }; int main(){ int n; //cout<<"enter digit n"; cin>>n; int r; //cout<<"enter digit r"; cin>>r; int result=ncr(n,r); cout<<result; return 0; } your formula totally wrong, it's supposed fact(n)/fact(r)/fact(n-r) , in turn inefficient way compute it. see fast computation of multi-category number of combinations , comments on question. (oh, , please reopen question can answer properly) the single-split case easy handle: unsigned nchoosek( unsigned n, unsigned k ) { if (k > n) return 0; if (k *

javascript - How to create circle around maker when using Google maps MarkerCluster for api v3 -

i using google maps markercluster api v3 create cluster marker. works well. want use circle around marker , can drag radius of circle. var markerclusterer = null; var map = null; var imageurl = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&' + 'chco=ffffff,008cff,000000&ext=.png'; function initialize() { map = new google.maps.map(document.getelementbyid('map_canvas'), { zoom: 6, center: new google.maps.latlng(46.578498, 2.457275), maptypeid: google.maps.maptypeid.roadmap }); var markers = []; var markerimage = new google.maps.markerimage(imageurl, new google.maps.size(24, 32)); (var = 0; < macdolist.length; i++) { var latlng = new google.maps.latlng(macdolist[i].lat, macdolist[i].lng); var marker = new google.maps.marker({ position: latlng, icon: markerimage }); markers.push(marker); } markerclusterer = new

rest - Creating a WADL and WSDL in Java? -

i have been tasked @ work create wadl , wsdl in java. have few questions though. first wsdl xml document describes how client requests information soap system. wadl xml document describes how client request info rest system. both of correct? if do? understand how soap , rest work http, i'm having trouble wrapping head around point of wadl , wsdl , for, , how should go creating 1 in java. when have method in code , need call it, how call it? @ method signature , javadoc. see parameter names are, mean, type have, javadoc tells if there restrictions on values, exception if don't respect that, etc. now consider web service. let's start soap first. it's operations exposed on network. how call beast? can @ endpoint must send formatted soap payload. tell operation names? parameter names , types? restrictions on values? no! tells absolutely nothing. need way tell clients how call service. you can have documentation, javadoc. use learn how make call. xml. p

python 2.7 - Dictionary Key Error -

i trying construct dictionary values csv file.say 10 columns there , want set first column key , remaining values. if setting loop dictionary has have 1 value. kindly suggest me way. import csv import numpy aname = {} #loading file in numpy result=numpy.array(list(csv.reader(open('somefile',"rb"),delimiter=','))).astype('string') #devolop dict\ r = {aname[rows[0]]: rows[1:] rows in result} print r[0] error follows. r = {aname[rows[0]]: rows[1:] rows in result} keyerror: '2a9ac84c-3315-5576-4dfd-8bc34072360d|11937055' i'm not entirely sure mean here, help: >>> result = [[1, 'a', 'b'], [2, 'c', 'd']] >>> dict([(row[0], row[1:]) row in result]) {1: ['a', 'b'], 2: ['c', 'd']}

javascript - Possible to get line numbers or stack traces in Screeps? -

in screeps, possible not see error in console output, module, line, , perhaps stack trace? update: errors like. don't see line number or stack trace, or perhaps button enable these? https://www.dropbox.com/s/9znxz5xe0j42616/screen%20shot%202014-12-06%20at%2012.21.18%20pm.png?dl=0 at time there no full error support in console stacktraces in firefox. artch have implement feature. other browsers chrome , opera seem work. can better transfer localstorage browsers , work there. can follow info in answer , work local filesystem , open in browser if have nodejs installed.

symfony - Symfony2 Custom Voter Role Hierarchy -

i'm trying create custom voter check access on entities specific actions. logic working fine. have actions allowed if user either "owner" of entity, or admin. however, can't check role of user because i'm looking @ role hierarchy. example in docs uses in_array , won't work ( http://symfony.com/doc/current/best_practices/security.html ) my voter (shortened clarity). i've tried injecting security context (or authorizationcheckerinterface in 2.6), has circular dependency since voter. <?php // ... class applicationvoter extends abstractvoter { const view = 'view'; /** * @var authorizationcheckerinterface */ private $security; /*public function __construct(authorizationcheckerinterface $security) { $this->security = $security; }*/ /** * {@inheritdoc} */ protected function getsupportedattributes() { return array( self::view ); } /**

java - Creating live counter within a JFrame -

Image
i tried searching sort of interactive jlabel . want this: i'm not sure called or find info on displaying this. want print refreshed number when +/- pressed. have working print on eclipse console unsure how print jframe . here of code: string input = joptionpane.showinputdialog("please enter number of laps."); numlaps = integer.parseint(input); //frame creation jframe f = new jframe("number of laps"); f.setsize(550, 450); f.setdefaultcloseoperation(jframe.exit_on_close); f.setlayout(null); // label creation jlabel label = new jlabel("you entered " + numlaps + " laps. press + add lap. press - subtract lap.", swingconstants.center); label.setbounds(0,0,500,300); f.add(label); //display window f.setvisible(true); //button creation add jbutton add = new jbutton ("+"); add.setbounds(350,250,50,50); add.setpreferredsize(new dimension(50,50)); add.addactio

java - Null Pointer Exception on Buffer IO -

for software engineering class group has camera stream server , send client via socket. sending images through socket. when try run our program 1 image next image turns null , therefore nullpointer exception. here userclient class. userclient receives sequence of images. null pointer comes in run method, labeled comment. /* * change license header, choose license headers in project properties. * change template file, choose tools | templates * , open template in editor. */ package communication; import java.awt.image.bufferedimage; import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstreamreader; import java.io.objectinputstream; import java.net.connectexception; import java.net.socket; import java.net.unknownhostexception; import java.util.logging.level; import java.util.logging.logger; import javax.imageio.imageio; import javax.swing.joptionpane; import userpc.rovergui; /** * simple swing-based client capitalization server. has main * f

animation - Android RotateAnimation slows down after repeating few times -

i trying make metronome needle moving upside down pendulum. have tried rotationanimation of android seems slow down after few runs. have tried both linearinterpolator , custom interpolator(metronomeinterpolator). the following code taken android how rotate needle when speed changes? , ihan jithin. rotateanimation needledeflection = new rotateanimation( this.previousangle, this.currentangle, this.pivotx, this.pivoty) { protected void applytransformation(float interpolatedtime, transformation t) { currentdegrees = previousangle + (currentangle - previousangle) * interpolatedtime; currentvalue = (((currentdegrees - minangle) * (maxvalue - minvalue)) / (maxangle - minangle)) + minvalue; if (ndl != null) ndl.ondeflect(currentdegrees, currentvalue); super.applytransformation(interpolatedtime, t); } }; needledeflection.setanima

php - Query mysql which a simple to show particular records -

i have simple db of real estate property listings. trying simple search show records. eg property location, type , price eventually. having trouble select statement if users submit blank fields. see code. there better way this? ok on bit displays records using while loop. newbie sure can tell. <form action="search.php" method="post"> <table border="0" cellpadding="10" cellspacing="0"> <tr> <td width="300"><b>reference no</b></td> <td><input type="text" name="reference_no" maxlength="20" id="reference_no" /></td> </tr> <tr> <td><b>property name</b></td> <td><input type="text" name="property_name" maxlength="30" id="property_name" /></td> </tr> <tr> <td><b>property area</b></td> <td> <

can not connect database server in mysql? -

Image
i changed max_connection value 1 / hour in mysql server.than close mysql workbench , again try open.it shows above error can can 1 tell how fix this. thanks in advance my problem solved using following way actually did wrong set max_connection_per_hour=1 in workbench settings. that's why can't open connection period of time .now solved using terminal use of following command $ mysql -u root -p then enter password root user use following command mysql>$ grant usage on . 'root'@'localhost' max_connections_per_hour 0; after can open connection out problem. i tried command many times after 1 hour works me before gives me error

wpf - How to retrieve values from multiple rows of the same column in SQL Server -

i need search booked patients given date. don"t know error in code is. retrieve 1 row table. please help string sp = textbox1.text; sqlconnection con1 = new sqlconnection(); con1.connectionstring = "data source=swathi-pc\\nm;initial catalog=clinic;persist security info=true;user id=sa;password=sqlpass"; con1.open(); string query = "select booking_dt,name patients1 booking_dt=@dt "; sqlcommand cmd = new sqlcommand(query, con1); cmd.parameters.add(new sqlparameter("@dt", sp)); sqldatareader dr = cmd.executereader(); if (dr.read()) { listview1.items.add(dr[1].tostring()); } i'd it's your if (dr.read()) { } block running once. don't know specifics of whichever language you're using, i'm guessing need along lines of while (dr.read()) { listview1.items.add(dr[1].tostring()); } which should iterate through dr.

amazon dynamodb - What is Hash and Range Primary Key? -

i not able understand range primary key here - http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/workingwithtables.html#workingwithtables.primary.key and how work? what mean - "unordered hash index on hash attribute , sorted range index on range attribute"? " hash , range primary key " means single row in dynamodb has unique primary key made of both hash , range key. example hash key of x , range key of y , primary key xy . can have multiple range keys same hash key combination must unique, xz , xa . let's use examples each type of table: hash primary key – primary key made of 1 attribute, hash attribute. example, productcatalog table can have productid primary key. dynamodb builds unordered hash index on primary key attribute. this means every row keyed off of value. every row in dynamodb have required, unique value attribute . unordered hash index means says - data not ordered , not given guarantees how data

angularjs - Ng-grid editable grid does not get focus on click -

Image
i need grid user can edit. need able add row data set, preferably grid. first of need able edit data. i thought use plain 2 way binding this. clicking on cell not make editable. have added enablecelledit:true , tried add enablecelleditonfocus. prefer having cells editable without having use template. cells contain number , date. below grid options pass grid. $scope.gridoptions = { data: 'account.interests',enablerowselection: false, enablecelleditonfocus: true, multiselect: false, columndefs: [{ field: 'rate', enablecelledit: true, width: 60 }, { field: 'date', enablecelledit: true, cellfilter: 'date:\'yyyy-mm-dd\'' }] }; and grid in view: <div ng-if="showinterestrates" > <div ui-grid="gridoptions"></div> </div> to edit future must add edit module : 'ui.grid.edit' module , must include ui-grid-edit d

assign javascript array value to angularjs variable -

obj = ['sha','abc','xyz] //javascript array function myclrt($scope) //this angular js function { $scope.one = obj[0]; // obj[0] not being assinged scope.one } this not working. try this:- obj = ['sha','abc','xyz] //javascript array function myclrt($scope) //this angular js function { $scope.one = obj[0]; // typo $scope -> $scope }

c# - System.Net.WebException not intercepted on Windows Phone 8 -

i trying call web service using restsharp (this has done wp8 onwards). this triggered method: private async void postrest() { string getsyncservice = "myservice"; var client = new restclient(ip); var request = new restrequest(getsyncservice, method.post); request.requestformat = dataformat.json; jsonobject jsongenericrequest = new jsonobject(); jsongenericrequest.add("companyid", "123"); jsongenericrequest.add("token", "123"); ... request.addparameter("genmobilerequest", jsongenericrequest); request.addheader("access-control-allow-methods", "post"); request.addheader("content-type", "application/json; charset=utf-8"); request.addheader("accept", "application/json"); try { // easy async support client.executeasync(request, response => {