Posts

Showing posts from July, 2010

javascript - trouble with delete user input -

i'm trying make array saves local storage , user can sort items, add item, delete item, , clear local storage. i'm having lot of trouble getting delete or splice user input work can please provide me advice. this code have far please forgive me if it's bad, keen know how can made better. ... <script> //lets program know books1 variable array var books1 = [] //lets program know result variable string var result = "" //checks see if localstorage key booksarray exists, if doesn't books1 has 3 books added ans stored locally key of booksarray if (localstorage.getitem("booksarray") == null) { books1 = ["book1", "book2", "book3", "m", "p"] localstorage.setitem("booksarray", json.stringify(books1)) // var thearray = json.parse("booksarray") } else { loadbooks(); //loads books array variable name listbooks }

php - Codeigniter failed to open stream permission when upload images -

code: $filename = '12345.jpeg'; $source = imagecreatefromstring($imagedata); $imagesave = imagejpeg($source,$filename,100); imagedestroy($source); $this->ftp->connect(); $this->ftp->upload($imagesave,'/public_ftp/incoming/'.$filename,'ascii', 0775); $this->ftp->close(); error: codeigniter failed open stream permission when upload images. probably permissions issue. try this: sudo chmod -r 777 path/to/public_ftp/incoming/ however, give permission everyone. localhost ok. production environment should in way. check this answer more info @edit if getting error when trying upload file form. codeigniter documentation : the upload folder you'll need destination folder uploaded images. create folder @ root of codeigniter installation called uploads , set file permissions 777. do have folder permissions set 777?

Unable to open bash profile on OSX -

i unable open bash profile. had set java , android path opening. when run echo $path displaying paths correctly. need add path bash profile. could please me? your $path wrong : /library/java/javavirtualmachines/jdk1.8.0_45.jdk/contents/home/bin:/users/qsgte‌​chnologies/library/android/sdk/platform-tools:/users/qsgtechnologies/library/andr‌​oid/sdk/tools this doesn't use standard default path, and, unless totally intentional, recommend not this. you've got fix running (note /bin:/usr/bin: ): export path=/bin:/usr/bin:/library/java/javavirtualmachines/jdk1.8.0_45.jdk/contents/home/bin:/users/qsgte‌​chnologies/library/android/sdk/platform-tools:/users/qsgtechnologies/library/andr‌​oid/sdk/tools: the next time, sure use syntax: export path=$path/yournewpath: since removed /bin:/usr/bin: unable change bash profile because bash wasn't able locate executables. fitting needs, here's current bash_profile : export java_home=$(/usr/libexec/ja

html - Detect Browser Language in PHP and set $locale accordingly -

i'm trying achieve, when visits wordpress page .po (language-) packages of pefered language loaded. @ moment possible change language adding ?lang= parameter url. want right language selected based on browser language. my code: <?php // start session session_start(); $browserlang = " ".$_server['http_accept_language']; // if there's "lang" parameter in url... if( isset( $_get[ 'lang' ] ) ) { // ...set session variable named wplang based on url parameter... $_session[ 'wplang' ] = $_get[ 'lang' ]; // ...and define wplang constant wplang session variable $locale = $_session[ 'wplang' ]; echo 'based on url parameter'; // if there isn't "lang" parameter in url... } else { // if wplang session variable set... if( isset( $_session[ 'wplang' ] ) ) { // ...define wplang constant wplang session variable $locale = $_session[

c# - Get environment variable from other proccess in Ruby -

i have following task: in c# code i'm running server random port , adding port environmentvarables via environment.setenvironmentvariable("port", convert.tostring(fixture.uri.port)); and after have port variable ruby rspec code tell tests port should use. there ways this? environment.setenvironmentvariable default sets target process. should use user or machine target: environment.setenvironmentvariable("port", convert.tostring(fixture.uri.port), environmentvariabletarget.user); msdn documentation

javascript - Removing all the eventSources in fullCalendar -

i have 2 types of events in fullcalendar. few fetched eventsources using : $('calendar').fullcalendar('addeventsource' , 'source') and few created user. using $('calendar').fullcalendar('renderevent', eventdata, true) now upon clicking button want remove events obtained eventsources , retain created user. i tried doing : $('calendar').fullcalendar('removeeventsource' , function(e){ return true ; } ) ; but doesn't work. how achieve doing job ? i did want in recent project. fullcalendar supports nonstandard fields. non-standard fields in addition fields above, may include own non-standard fields in each event object. fullcalendar not modify or delete these fields. example, developers include description field use in callbacks such eventrender. source so like //save user created event $('#calendar').fullcalendar('renderevent', { title: title

php - Cross-Origin Request Blocked : Ajax POST with header authentication -

i'm sending ajax request php api allows post requests. $.ajax({ url: '"//localhost/api/vs_1_0/availability"', data: $("#api-test").serialize(), type: "post", datatype: "json", headers: { "php_auth_user": "username", "php_auth_pw": "123" }, success: function (data) { alert("data server" + json.stringify(data)); }, error: function (jqxhr, textstatus, errorthrown) { alert("you can not send cross domain ajax requests: " + errorthrown); } }); when i'm sending request can see "cross-origin request blocked: " error in firebug , won't execute ajax request. have send username , password inside header $_server['php_auth_pw'] , $_server['php_auth_user'] variables. worked doing curl request. can s

parsing file in python -

i'm trying parse 2 pipe/comma separated files , if particular field matches in file create new entry in 3rd file. code follows: #! /usr/bin/python fo = open("c-1.txt" , "r" ) line in fo: #print line fields = line.split('|') src = fields[0] f1 = open("airport.txt", 'r') f2 = open("b.txt", "a") #with open('c.csv', 'r') f1: # line1 = f1.read() line1 in f1: reader = line1.split(',') hi = false target = reader[0] if target == src , fields[1] == 'zht': print target hi = true f2.write(fields[0]) f2.write("|") f2.write(fields[1]) f2.write("|") f2.write(fields[2]) f2.write("|") f2.write(fields[3]) f2.write("|") f2.write(fields[4]) f2.wri

java - Hibernate Skip and take some rows -

how let's 20-35 rows fromt eh table? how can select in hibernate? something that: mytable.skip(20).take(15); thanks. a combination between query#setfirstresult(int i) , query#setmaxresults(int i) skip first 20 records , fetch next 15 (as shown in example) : list<table> page3 = session.createquery( "from table") .setfirstresult(20) .setmaxresults(15).list();

Regex capture iterator method moves iterator -

i processing simple strings of format "1s:1d", "100:5000", etc regex: let retention_matcher = regex::regex::new({r"^(\d+)([smhdy])?:(\d+)([smhdy])?$"}).unwrap(); i know regex should match once want run regex captures , check number of captures. let iter = retention_matcher.captures_iter(ts); let count = iter.count(); println!("iter.count(): {}", count); let _ : vec<option<(u64,u64)>> = iter.map(|regex_match| { let retval = retention_spec_to_pair(regex_match); println!("precision_opt: {:?}", retval); retval }).collect(); the issue count() method moves iter , can no longer use it. src/bin/whisper.rs:147:42: 147:46 error: use of moved value: `iter` src/bin/whisper.rs:147 let _ : vec<option<(u64,u64)>> = iter.map(|regex_match| { ^~~~ src/bin/whisper.rs:144:21: 144:25 note: `iter` moved

javascript - cross-referencing two firebase arrays to obtain data -

Image
i wondering if there's easy way pull out value 1 array based on corresponding name. here, i've obtained user email "coupons" collection. search through "users" collection, find similar email, , output corresponding "name" ("wes haque enterprises") $scope variable. i have references both collections , $scope objects have references stored. i wanted know if there's easy way traverse through $scope.users object looking string "wes@wes.com" , extracting "wes haque enterprises" it. thanks. assuming don't want iterate (traverse?) on bunch of arrays instead query data need... you can query users node data need. in macos: fquery *allusers = [usersref queryorderedbychild:@"emailaddress"]; fquery *thisuser = [allusers queryequaltovalue:@"wes@wes.com"]; [thisuser observeeventtype:feventtypechildadded withblock:^(fdatasnapshot *snapshot) { ( fdatasnapshot *child in snapshot.

mysql - Slow performance on joining table -

Image
i trying optimize query below , have study how add index improve peformance , result still slow. query below took 20 sec run , transaction contains around 100k records , joining table transactiondetail contains around 500k records. select transaction.id .... transaction inner join agent on agent.id = transaction.agent_id inner join distributor on distributor.id = transaction.distributor_id inner join transactiondetail on transaction.id = transactiondetail.transaction_id transactiondetail.type = 'admin' , transaction.status in ('pending', 'processing', 'success', 'rejected') order issued_date desc limit 0 , 10 from query above try apply understand indexing i added 3 index because of inner join , transaction(agent_id,distributor_id) , transaction(transaction_id) from clause added transaction(status) because of order added transaction(issued_date) but doesn't show improvement below explain

shell - how to check a ssh key is copied to remote server by script -

i want use script below check if ssh key in host copied remote server: #!/usr/bin/sh ssh -q -o stricthostkeychecking=no user@server "ls >/dev/null </dev/null" if [ $? -eq 0 ] ;then echo "key copied remote server" else echo "key not copied remote server" fi but pending on password input in case, user@server's password: if there way terminate session , return error immediately? add -o pubkeyauthentication=yes , -o passwordauthentication=no ssh command in script

c# - How to move a button with a filled combobox? -

how can let button loop move if click on combobox @ number one, has same button1. if same button loop has move button1? can me? this code : private void haalop_click(object sender, eventargs e) { try { streamreader sr = new streamreader(@"d:\programeren\blokboek4\week5\week5toets\week5toets\bin\debug\bestemmingen.xml"); string line = sr.readline(); while (line != null) { combox.items.add(line); line = sr.readline(); } } catch (exception ex) { messagebox.show("error : " + ex.message); } } private void loop_tick(object sender, eventargs e) { if (true ) { } } private void combox_click(object sender, eventargs e) { if (combox == "") { } } the buttons called but1 but2 but3 but4 5 but6 , have combob

java - Which organisations let general public to use any useful non confidential data or information by providing an xml? -

i working on self made project , coded in java. right using jaxb parse xml data , mapping pojo. next objective store data in database. creation of db tables according pojo part of work. my intention complete project meaningful every other person looking @ work. decided take data (which available in xml) , use project , give visual (presenting on web page) it. i self taught , experience less, hence had post question. appreciated. how http://openweathermap.org/api ? data , api free , available everyone. can data xml using query-parameter "mode=xml"

c# - How to flip a string? -

Image
how can flip string in c# application example : " ambulance " text seen mirror image.i dont have idea start .im using c# forms application i have tried reversing string ,but there possibility flip string (like mirror images)? like : ƎƆИa⅃uá™ ma this not reversing in so post as approach outlined sergey, can use graphics.scaletransform() reflect y-axis. for example, create default windows forms application , drop following onpaint() it, run it: protected override void onpaint(painteventargs e) { base.onpaint(e); string text = "this come out backwards"; e.graphics.scaletransform(-1, 1); float w = e.graphics.measurestring(text, this.font).width; e.graphics.drawstring(text, this.font, brushes.black, -w, 0); } output: you can mess around graphics.rotatetransform() rotate text well, , use graphics.scaletransform(1, -1) invert mirror it:

java - I can't create the file -

what wrong coding? tried create file name & printout in text file package practical12; import java.io.filenotfoundexception; import java.io.printwriter; import java.util.scanner; public class q4 { public static void main (string []args) throws filenotfoundexception{ system.out.println("please input file name"); string name; //take file name scanner in; in = new scanner(system.in); name = in.nextline(); printwriter out = new printwriter(name); // create textfile out.println("hello! first program in file"); // write text out.close(); //close file } } if entered name of file instead of absolute path, created in current working directory of program. in order check current working directory using java please check getting current working directory in java

html - Display three blocks inline CSS -

i have 3 div 's, #left_sidebar , #records_list , #right_sidebar , want display them inline, when using display:inline-block , seems fine sidebars placing on bootom of page, try use float , still getting creppy behavior, this: #left_sidebar { top: 0px; width: 142px; float: left; } #records_list { width: 530px; display: inline-block; } #right_sidebar { background-image: url('../images/enstein_banner.png'); width: 174px; height: 231px; float: right; } (you see mix float 's , display ), , works fine, can explain me, if right? or need somehow else? thanks! p.s. if need more info, or little bit unclearly asking say, , try improve question. #left_sidebar { width: 10%; padding: 20px; background: red; float: left; margin-right: 1%; color: #fff; } #records_list { width: 50%; padding: 20px; background: red; float: left; margin-right: 1%; color: #fff; } #right_sidebar { backgro

What is Row Offset and Byte Offset in Hadoop Input file format? How the offsets are considered in Map-Reduce Program for Key-value Pairs? -

text format, key-value format, sequence file format 3 standard file formats considered in map-reduce program. need resolution on how row offset , byte offset considered in these 3 cases deciding key value pair. there no offset in keyvaluetextinputformat , sequencefileinputformat . offset used in textinputformat , denotes byte offset beginning of file.

php - In ios 8 push notification not showing me badges for current app -

hello friends new in push notification please me out. trying badge count app "nsdictionary userinfo" contains alert , sound . code register device push notification -(bool)application:(uiapplication *)application didfinishlaunchingwithoptions:(nsdictionary *)launchoptions { if ([[uiapplication sharedapplication] respondstoselector:@selector(registerusernotificationsettings:)]) { uiusernotificationsettings* notificationsettings = [uiusernotificationsettings settingsfortypes:uiusernotificationtypebadge |uiusernotificationtypealert | uiusernotificationtypesound categories:nil]; [[uiapplication sharedapplication] registerusernotificationsettings:notificationsettings]; [[uiapplication sharedapplication] registerforremotenotifications]; } else { [[uiapplication sharedapplication] registerforremotenotificationtypes: (uiremotenotificationtypebadge | uiremotenotificationtypealert | uiremotenotificationtypesound)]; } now when message server. -(void)appl

c++ - How parse datetime format from datebase? -

the database (sqlite) has field of type real values of form (42153.659595). how translate value in form "dd.mm.yy hh:mm:ss" if 42153.659595 = 29.05.2015 15:49:49 ? you can explicit calendar system require: http://www.sqlite.org/lang_datefunc.html select julianday('now') - julianday('1776-07-04'); in principle don't "parse" (you mean: interpret raw representation). use sqlite api/builtin sql functions you in interest of information: the date , time functions use a subset of is0-8601 date , time formats . the datetime() function returns "yyyy-mm-dd hh:mm:ss". julianday() function returns julian day - number of days since noon in greenwich on november 24, 4714 b.c. (proleptic gregorian calendar) the date() function returns date in format: yyyy-mm-dd. time() function returns time hh:mm:ss.

getLogoutUrl using facebook graph api php CodeIgniter -

i following http://benmarshall.me/facebook-sdk-php-v4-codeigniter/ tutorial. here can login url can not logout url can tell me why not getting this here facebook libaray logout function public function logout_url() { $_session = $this->helper->getsessionfromredirect(); $session = new facebooksession( $_session->gettoken() ); $next_url = 'http://localhost/ci_sdk/index.php/welcome/login'; return $this->helper->getlogouturl($session,$next_url); } here constructor in facebook library public function __construct() { $this->ci =& get_instance(); $this->permissions = $this->ci->config->item('permissions', 'facebook'); facebooksession::setdefaultapplication( $this->ci->config->item('api_id', 'facebook'), $this->ci->config->item('app_secret', 'facebook') ); $this->helper = new facebookredirectloginhelper(

jquery - how to check the string ends with space in javascript? -

i want validate if string ends space in javascript. in advance. var endspace = / \s$/; var str = "hello world "; if (endspace.test(str)) { window.console.error("ends space"); return false; } you can use endswith() . faster regex : mystr.endswith(' ') the endswith() method determines whether string ends characters of string, returning true or false appropriate. if endswith not supported browser, can use polyfill provided mdn: if (!string.prototype.endswith) { string.prototype.endswith = function(searchstring, position) { var subjectstring = this.tostring(); if (typeof position !== 'number' || !isfinite(position) || math.floor(position) !== position || position > subjectstring.length) { position = subjectstring.length; } position -= searchstring.length; var lastindex = subjectstring.lastindexof(searchstring, position); return lastindex !== -1 &a

How to use ANT to save current process run time? -

how save current process running time in text file using ant, read file , assign ant variable? you can use ant exec task . there can specify executable ps , necessary arguments (pid, options). can check argumengs here . you specify outputproperty in ant exec task output redirected property. then can put value in file using echo task .

javascript - Script to tile images not initialized until you resize the browser -

Image
i have page supposed tile images this but when first land on page see images stack behind each other if resize browser @ shift position. @ on jquery makes happen jquery var colcount = 0; var colwidth = 300; var margin = 10; var spaceleft = 0; var windowwidth = 0; var blocks = []; $(function(){ $(window).resize(setupblocks); }); function setupblocks() { windowwidth = $(window).width(); blocks = []; // calculate margin blocks evenly spaced within window colcount = math.floor(windowwidth/(colwidth+margin*2)); spaceleft = (windowwidth - ((colwidth*colcount)+(margin*(colcount-1)))) / 2; console.log(spaceleft); for(var i=0;i<colcount;i++){ blocks.push(margin); } positionblocks(); } function positionblocks() { $('.block').each(function(i){ var min = array.min(blocks); var index = $.inarray(min, blocks); var leftpos = margin+(index*(colwidth+margin)); $(this).css({ 'left':(leftpos+spaceleft)+'px',

python - Sentiment Analysis using RNTN -

i new in python , want sentiment analysis project. found codes uses rntn approach sentiment analysis of movie reviews. link: https://github.com/awni/semantic-rntn but not able run these codes. using windows, codes giving indentation error. can please provide procedure run these codes. in end, want run procedure on own dataset contain cleaned tweets. know lame ask question stuck in middle , don't have time deep study. thank in advance. the best thing avoid windows errors, install https://www.virtualbox.org , run ubuntu in virtual environment. ubuntu comes both versions of python installed default , easier work coding. also making codes work cakewalk. this fastest way stuff working.

mysql - Get current date and time in javascript of format: 2015-03-01 03:09:03 -

i want current date , time in javascript this: 2015-03-01 03:09:03 how can achieve such format? ( show 0 before number when less 9 ) actually comparing date , time mysql date , time in node.js mysql plugin. javascript date , time format must same mysql default date , time format i.e : 2015-03-01 03:09:03 currently using: var currentdate = new date(); var datetime = currentdate.getfullyear() + "-" + (currentdate.getmonth()+1) + "-"+ currentdate.getdate() + " " + currentdate.gethours() + ":" + currentdate.getminutes() + ":" + currentdate.getseconds(); mysql query in node.js: var paramupdate = {} stateobject.connection.query("update timersdb set notificationflag = '1' requesttime < '"+datetime+"' ,

how to disable special characters text field in sugarcrm? -

can me in issue. i want avoid special characters(!@#$%^&*()) in text field. actually have added javascript code this. cant enter spl characters. it's working perfect. problem is, data not going inserted after submitted. <script language="javascript" type="text/javascript"> function alpha(e) { var k; document.all ? k = e.keycode : k = e.which; return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57)); } </script> 'customcode' => '<input type="text" onkeypress="return alpha(event)">', you have missed name of textfield in customcode. customcode should like: 'customcode' => '< input type="text" onkeypress="return alpha(event)" name="your-textbox-name">',

What's the proper way to write comparator as key in Python 3 for sorting? -

i'm not sure how write comparator in python 3 cmp parameter removed. considering following code in python 3, how rewrite comparator using key? import functools def my_cmp(x, y): return x*5-y*2 l = [50, 2, 1, 9] print(sorted(l, key=functools.cmp_to_key(my_cmp))) thanks. this "comparison" function came inconsistent: should provide definite (deterministic) order, meaning, if change order of elements in list , run sorted - should same result! in case, order of elements effects sorting: import functools def my_cmp(x, y): return x*5-y*2 l = [50, 2, 1, 9] print(sorted(l, key=functools.cmp_to_key(my_cmp))) # [2, 1, 9, 50] l = [50, 1, 2, 9] print(sorted(l, key=functools.cmp_to_key(my_cmp))) # [1, 2, 9, 50] which means "comparison" function inconsistent. first provide ordering function, should not difficult convert key function. regards question raised in comments, key accepts function takes single argument - , returns "mea

c - Cache memories and memory addresses -

i have 1 class´s exercise have subroutines , check cache misses, atachment: i have create 2 subroutines s1 capacity of l1 cache 32kb , b1 line witdh 64 bytes. subroutine a: increment bytes of memory buffer containing 2*s1 bytes in order of increasing memory addresses; subroutine b: increment each b1-th byte of memory buffer containing 2*s1 bytes in order of increasing memory addresses; for subroutine think have do: char buffer[2*s1]; printf... buffer++; printf... both printf show: buffer[0]= 0x7fff36769fe0 buffer[1]= 0x7fff36769fe1 buffer[0]= 0x7fff36769fe1 buffer[1]= 0x7fff36769fe2 all bytes increassed,so, think correct,and subroutine b, have no idea...so, have subroutine b. it nice if can me. thank you! these exercises makes sense lesson in optimisation. unfortunately, they're not quite hitting figurative head of nail. programmers waste enormous amounts of time thinking about, or worrying about, speed of noncritical parts of programs, , t

Python Regex after a known string -

i have string formatted such: | birth_date = 22 january 1898 | i want write regex looks birth_date, , gets 4 digit sequence of digits after birth_date until pipe character import re print re.sub(r'\d', '', "| birth_date = 22 january 1898 |") # output => 221898 # if want last 4 digits: print re.sub(r'(\d)', '', "| birth_date = 22 january 1898 |")[-4:] # output => 1898

javascript - AngularJS - Using ngTouch within a directive for mobile devices -

i'm using ngtouch remove delay on mobile devices, on mobile devices clicking image nothing. on app, clicking image calls directive enlarge images, there no ng-click . here directive: app.directive('imagezoom', ['ngdialog', function(ngdialog) { return { restrict: 'a', scope: { image: '=' }, link: function(scope, element, attr) { attr.$observe('ngsrc',function(img) { element.bind('click', function(e) { e.stoppropagation(); if (something) { dosomething(); } else { ngdialog.open({ template here }); } }); }); } }; }]); this working fine until introduced ngtouch believe there issue element.bind('click' aspect of not registering clic

c# - Server Error in '/' Application () -

Image
i created odata ado.net framework web api testing in localhost , getting error line 19: if (!eventlog.sourceexists("myservice")) the stacktrace is: [securityexception: source not found, or event logs not searched. inaccessible logs: security.] system.diagnostics.eventlog.findsourceregistration(string source, string machinename, boolean readonly, boolean wanttocreate) +657 system.diagnostics.eventlog.sourceexists(string source, string machinename, boolean wanttocreate) +104 system.diagnostics.eventlog.sourceexists(string source) +14 how should remove error ? lot. my web.config has: <system.web> <authentication mode="windows"> <forms requiressl="true" /> </authentication> <authorization> <allow roles="myservice" /> <deny users="*" /> </authorization> <httpcookies requiressl="true" httponlycookies=&q

looping through a 2D array 3 items at a time (Java) -

i having trouble trying figure out way move through 2d array 3 items @ time because has done in specific way. the array has individuals rows , loci columns. have take 2 individuals @ time , compare them every third until end: so if there 5 individuals total individual comparisons 0,1,2, 0,1,3, 0,1,4, 1,2,3, 1,2,4 , 2,3,4 for each of these comparisons, have compare alleles @ each locus (each column represents allele, 2 columns 1 locus). looks locus1 locus2 locus3 ... 0 1 2 3 4 5 0 1 2 3 4 5 6 1 7 8 9 10 11 12 2 13 14 15 16 17 18 3 19 20 21 22 23 24 4 25 26 27 28 29 30 definite example of mean, have first set: 0,1,2. first comparison of alleles: 1,2, 7,8 , 13, 14. next comparison of alleles: 3,4, 9,10 , 15,16. last (assuming 3 loci) be: 5,6, 11,12, , 17,18. for every set of 6 alleles, have comparison. have finished code comparison testing. im not sure how loop through 2d array. thinking psuedo-code this: each pair of individua

How to stock in an Array the points of a Dice? java -

my aim stock how many times dice has faced number between 1 , 6 10 throws. it should like: 1 = 3 time(s) 2 = 4 time(s) 3 = 0 time(s) 4 = 1 time(s) 5= 1 time(s) 6 = 1 time(s) total = 10 times (or throws) i've written far code int final faces = 6; int final throws = 10; int nbtimes[] = new int[faces]; int face; ... for(int thr = 1; thr < throws ; thr++){ face = throwdice(); if (face == face) nbtimes[face] +=1; } where throwdice() gives me random number between 1 , 6. have done. the following line return true , redundant: if (face == face) if you'll remove line (and predecessor) it'll work fine (as well): ... ... int final faces = 6; int final throws = 10; int nbtimes[] = new int[faces]; int face; ... for(int thr = 0; thr < throws ; thr++){ // int thr = 0 !!! (if want 10 throws) nbtimes[throwdice()] += 1; }

javascript - JSON.parse localStorage unexpected end of input error -

this line item = json.parse(localstorage["item"]); caused error in console showing uncaught syntaxerror: unexpected end of input when localstorage has no value? how resolve issue? know empty string not valid json. if(localstorage["item"]){ item = json.parse(localstorage["item"]); }

c# - Why is the dispatcher behaving this way when I pass a parameter? -

i'm using datagridview in wpf. in roweditending event, old row (before editing ends) , call method through dispatcher new row (after edit) private void mygrid_roweditending(object sender, datagridroweditendingeventargs e) { datarowview oldrowview = e.row.item datarowview; datarow oldrow = oldrowview.row; //when put breakpoint before dispatcher called, oldrow has old row values. dispatcher.begininvoke(new action(() => onrowedit(oldrow, e)), system.windows.threading.dispatcherpriority.background); //i have passed old row onrowedit } void onrowedit(datarow oldrow, datagridroweditendingeventargs e) { //here oldrow has new row values. } the item array of oldrow before call method , array after have called method don't match. reason behind this? without a good, minimal , complete code example , it's impossible know sure issue in scenario. there's not enough context here. but likely, you're running temporal issue. is, delegat

ios - Full Text Search SQL has different effect between ios8 and ios7 -

i have use "*" symbols selecting on ios7 sqlite effect want, ios8 sqlite not supporting "*" , show "no result". fmdb problem or ios 8 not support "*" symbols? sql(with fmdb): db.executestatements("create virtual table if not exists table_1 using fts3(col_1,result)") db.executequery("select * table_1 col_1 match ?",withargumentsinarray:["*a*"]) table: +==============================+ | name: table_1 | +------------------------------+ | col_1 | result | +==============================+ | | result 1 | +------------------------------+ | b | result 2 | +------------------------------+ | aab | result 3 | +------------------------------+ ios 8 not support "*a*" , support "a*" : db.executequery("select * table_1 col_1 match ?",withargumentsinarray:[&qu

java - cannot create maven project in STS -

Image
i'm new java ee development , heard if have learn java ee spring mvc best choice learn , command of. after downloading sts 3.6 bundle i'm having troubles/issues in creating maven project. steps 1- create new project 2- error dialog it appears either don't have maven installed, or ide not aware of installation. former problem, have here . latter problem, view page ide using: eclipse

python - Trouble with QuerySelectField in Flask-WTF -

i trying have select field filled results of sqlalchemy request in flask form keep getting "typeerror: 'nonetype' object not iterable i have looked @ answer ( how use queryselectfield in flask? ) , has not me solve problem of why query(choices = course.query.all()) coming none - think issue. my models.py: class course(db.model): __tablename__ = 'courses' id = db.column(db.integer, primary_key=true) course_name = db.column(db.string, nullable=false) course_description = db.column(db.string, nullable=true) course_location = db.column(db.string, nullable=true) start_date = db.column(db.datetime, nullable=true) end_date = db.column(db.datetime, nullable=true) start_time = db.column(db.time, nullable=true) end_time = db.column(db.time, nullable=true) max_number_students = db.column(db.integer, default=8) spaces_left = db.column(db.integer, default=5) is_active = db.column(db.boolean, default=true) price = db.

asp.net mvc - Dropdown for Saving Model Not Working -

the code not save value musician entity. i'm using viewbag saving selectlist , displays content database on save null musician.primaryinstrument field when debugging. razor : <td> @html.labelfor(model => model.primaryinstrument, htmlattributes: new { @class = "control-label col-md-2" }) </td> <td> @html.dropdownlist("instrumentlist") </td> controller: public actionresult edit(string id) { if (id == null) { return new httpstatuscoderesult(httpstatuscode.badrequest); } musician musician = (musician)db.contractor.find(id); if (musician == null) { return httpnotfound(); } viewbag.instrumentlist = new selectlist(db.instrument, "id", "name"); return view(musician); } [httppost] [validateantiforgerytoken] public actionresult edit(musician musician, httppostedfilebase image) { if(modelstate.isvalid) { if (image != null) { uploadimage(music

c++ - How to return the value of a pointer in a list? -

i've got "faction" class, , vector of pointers want turn list. method it. assume i've managed turn vector of pointers list alright in first part, want print list out within method. know using '*', i'm printing out memory location opposed value, , that's code doing. list<faction*> faction::linklistfactions() { list<faction*> list_factions(factionptr_.begin(), factionptr_.end()); cout << "printing linked list:" << endl; (int = 0; < list_factions.size(); a++) { std::list<faction*>::iterator = list_factions.begin(); advance(i, a); cout << *i; cout << ","; } return list_factions; } but want print out value, not memory location. instead of cout << *i; i can like cout << i->getfactionname(); i able vector, simple enough: string faction::getfactionname() const { return factionname_; } but i'm having trouble

java - Error: Integers added together in successive uses of scanner class -

i'm doing exercises related handling exceptions. while using scanner class , following exercises check inputmismatchexceptions, got following results following code. static scanner sc = new scanner(system.in); public static void main(string[] args){ system.out.print("enter integer: "); int = getint(); system.out.print("enter second integer: "); int b = getint(); int result = + b; system.out.println(result); } public static int getint(){ while (true){ try { return sc.nextint(); } catch(inputmismatchexception e){ system.out.print("i'm sorry, that's not integer." + " please try again: "); sc.next(); } } } the output was: enter integer: 2 3 enter second integer: 5 it seems if first calling of nextint() enter "2 3", or 2 integers space between them, next time nextint() called, receives first 2 inte

ruby on rails - How to link_to correct show page from feed? -

if user clicks on: activities/valuations/_create.html.erb <%= link_to valuation_path(activity) %> <%= activity.trackable.name %> <% end %> he directed to, example, error: couldn't find valuation 'id'=24 because valuation 7. because line of code trying find valuation show page looking @ id number activity instead of id number valuation. to fix tried: <%= link_to valuation_path(@valuation) %> <%= activity.trackable.name %> <% end %> but gives error: actioncontroller::urlgenerationerror in activities#index no route matches {:action=>"show", :controller=>"valuations", :id=>nil} missing required keys: [:id] how rewrite code take user correct valuations show page? activities_controller class activitiescontroller < applicationcontroller def index @activities = activity.order("created_at desc").paginate(:page => params[:page]) end def

javascript - How do you reload a variable shown in HTML when it changes value? -

my html shows variable inside of script tag, , want reload variable. <script class="scriptclass">document.write(myobject.myproperty);</script> <button>go</button> when function runs changes value of myobject.myproperty, needs updated in html. javascript this: var myobject = { myproperty:"initial" }; function mypropertychange(){ myobject.myproperty = "somethingdifferent"; } jquery: $(document).ready(function() { $("button").click(function(){ mypropertychange(); $("script.scriptclass").empty(); $("script.scriptclass").html("document.write(myobject.myproperty);"); }); }); this doesn't work, , i've tried number variations on .replacewith , .replace. tried adding location.reload(true);, think resets whole thing. instead of reloading <script> tag, can assign <div> . this: myobject = {}; myobject.myproperty =

javascript - Save users colorpicker choice -

i'm trying allow users of site change colors within it, far, managed colors change in fact, however, when change or reload page changes disappear. then, tried store choice in cookie, don't know wrong stills doesn't work. i'm using following colorpicker: http://colpick.com/plugin and here code <script type="text/javascript"> jquery(document).ready(function(){ /* custom background-color on elements */ var custombackgroundcolor = ".thead,.go-top,.forum_offlink,.forum_on"; /* custom text color on elements */ var customtext = "a:link,.user-name,.news-header,.newsticker,.newscontroller,.patternchanger ul li a,.fixed,.fluid,.modalcontent h1,.buttons,.solservices:hover i,a.button:link,a.button:visited,a.button:active,.postbit_buttons > a:link,.postbit_buttons > a:hover,.postbit_buttons > a:visited,.postbit_buttons > a:active"; /* custom background on elements */ var custombackground = ".navhome,.h3main span,.l

java - Parcel List of List of Parcelable object -

so i've parceled lists before, i'm trying parcel gameboard object, has list<list<tile>> . tile implements parcelable, i'm not sure how parcel list<list> . here's i've tried: public class gameboard implements parcelable { private string _id; public string getid() { return _id; } public void setid(string id) { _id = id; } private list<list<tile>> _tiles; public list<list<tile>> gettiles() { return _tiles; } public void settiles(list<list<tile>> tiles) { _tiles = tiles; } public gameboard(parcel in) { _id = in.readstring(); in.readlist(_tiles, arraylist.class.getclassloader()); } public gameboard() { } @override public int describecontents() { return 0; } @override public void writetoparcel(parcel parcel, int i) { parcel.writestring(_id); parcel.writelist(_tiles); } public static final parcela

java - getName() from class Thread -

why have access getname() method? class doesn't extends class thread implements interface runnable . public class mythread implements runnable { public void run() { system.out.println("mythread running"); } public static void main(string[] args){ mythread thread1 = new mythread(); thread thr = new thread(thread1, "thread"); thr.start(); system.out.println(thr.currentthread().getname()); system.out.println(thr.getname());//why have access method? } } you're not calling getname() on instance of mythread class, you're calling on instance of thread class. should consider renaming class myrunnable because mythread seem class sort of thread class, while isn't.

javascript - java script and web service- how can I know if service.useService works -

i'm new java script , html. have web service running (i'm sure working). i have part in html- <html> <body bgcolor="#e6e6fa"> <head> <title>blog site</title> <script language="javascript"> function initializeservice(){ alert("init"); try{ service.useservice(http://localhost:7777/blogserver.asmx?wsdl,"getblogserver"); } catch(e){alert(e.message);} alert("done"); } var mailaddress, title, body; function createnewentry(){ mailaddress = document.demoform.stringmailaddress.value; title = document.demoform.stringtitle.value; body = document.demoform.stringbody.value; alert("send"); service.getblogserver.callservice("enternewinput", mailaddress, title, body); } function showserveranswertonewentry(){ alert(event.result.value); } </script> </head>