Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
We can't make this file beautiful and searchable because it's too large.
conventions of importing python main programs often i write command line utilities that are only meant to be run as main. for example i might have a file that looks like this: <pre><code>#!/usr/bin/env python if __name__ == __main__ : import sys # do stuff </code></pre> in other words there is nothing going on that isn t under the if statement checking that this file is being run as main. i tried importing a file like this to see what would happen and the import was successful. so as i expected one is allowed to import files like this but what is the convention surrounding this practice is one supposed to throw an error telling the user that there is nothing to be imported or if all the contents of the file are supposed to be run as main does one need to check if the program is being run as main or is the conditional not necessary also if i have import statements should they be at the top of the file or under the conditional if the modules are only being used under the conditional it would seem to me that they should be imported under the conditional and not at the top of the file.,python
python write to file based on offset i want to create a python program which splits up a files into segments of specified width and then a consumer program takes the segments and creates a duplicate of the original file. the segments might be out of order so i intent to use the offset value to write to the file. is there a way i can achieve this with without creating a local array to hold all the data on the receiving end for example <pre><code>f = open(file wb ) f.write(data) </code></pre> the idea behind this is that the program that sends the file might not be able to finish sending the file and will resume again once it has started. i have a sample code below which the combine_bytes function throws an exception when i try placing data in the buffer location. <pre><code>import sys import os def splitfile(fname start end width): t_filesize = os.path.getsize(fname) buffdata = bytearray(t_filesize) for line offset in get_bytes(fname int(start) int(end) int(width)): combine_bytes(buffdata offset line width) nums = [ %02x % ord(c) for c in line] print .join(nums) f = open( green_copy.jpg wb ) f.write(buffdata) f.close() def combine_bytes(in_buff in_offset in_data in_width): #something like memcpy would be nice #in_buff[in_offset:in_offset + in_width] = in_data #this works but it s the mother of inefficiency i = in_offset for c in in_data: in_buff.insert(i c) i = i + 1 def get_bytes(fname start end width): t_curroffset = start t_width = width f = open(fname r+b ) if end != 0: while t_curroffset &lt; end: if (t_curroffset + t_width) &gt; end: t_width = end - t_curroffset t_data = yield t_data t_curroffset t_curroffset += t_width else: t_data = while t_data: yield t_data t_curroffset t_curroffset += t_width t_data = f.close() if __name__ == __main__ : try: splitfile(*sys.argv[1:5]) except: print unexpected error: sys.exc_info()[0] </code></pre>,python
enable a textbox on the selection of no from the drop down menu i have a drop down menu where i have three options yes no and later.and when i select no option then the textbox must enable which was previously help me with some javascript script and explain me how can i call the script from the form.,javascript
sending mms and email from within app how does one get the pop up menu selection for email mms etc which is used when an image is selected on the iphone. <img src= alt= menu > another thing how can one add things to this menu e.g. facebook share twitter share what is the name of this menu,iphone
why aren t java weak references counted as references during garbage collection why are java weak references not counted as references with respect to garbage collection,java
uiview is shown displaced at the top of the screen ok hopefully a stupid question from a newbie... i have an app that used to display fine base on xib files created in ui builder. the .xib still displays fine using the simulator direct from the uib but when compiled and run the view is displaced by 40 or 50 pixels (about 1/3 the width of a nav bar) so that i get a bar of white space at the bottom and half my title text hidden on the nav bar at the top. i have tried fiddling with various parameters for the view and main window (eg layout wants full screen and resize view from nib) but nothing seems to make any difference. i tried upgrading xcode from 3 to 4 but no difference. any pointers gratefully received...,iphone
python display several variables after % folks cant seem to remember the correct syntax for displaying 2 or more variables in the following format: <pre><code>log.debug ( %s %s % hostname % processoutput[0]) </code></pre> thanks!,python
python input string error (don t want to use raw_input) i have a menu that asks for the user to pick one of the options. since this menu is from 1 to 10 i m using input besides raw_input. my code as an if statement that if the number the user inputs is from 1 to 10 it does the option. if the user inputs any number besides that ones the else statement says to the user pick a number from 1 to 10. the problem is if the user types an string lets say for example qwert. it gives me an error because its an string. i understand why and i don want to use raw_input. what can i do to wen the user types a string it goes to my else statement and print for example only numbers are valid. pick a number from 1 to 10 i don t want to use any advanced programing to do this regards favolas <strong>edit</strong> thanks for all your answers and sorry for the late response but i had some health problems. i couldn t use try or except because my teacher didn t allow it. in the end i ve used raw_input because it was the simplest alternative but was glad to see that are many ways to solve this problem. regards favolas,python
how to encode image to base64 in javascript in the code below i m fetching a .txt file and it is getting encoded without giving an error so oi want to use the same thing and also convert an image into basse 64 <pre><code>// adding attachment function opensavedialog() { var nsifilepicker = components.interfaces.nsifilepicker; var fp = components.classes[;1 ].createinstance(nsifilepicker); fp.init(window select a file nsifilepicker.modeopen); fp.appendfilters(nsifilepicker.filterhtml | nsifilepicker.filterimages); fp.appendfilters(nsifilepicker.filtertext | nsifilepicker.filterall); var rv =; if (rv == nsifilepicker.returnok || rv == nsifilepicker.returnreplace) { var file = fp.file; var path = file:// + fp.file.path; readtextfile(path); document.getelementbyid( filename ).value = file.leafname; } } // encoding text to base64 function readtextfile(filepath) { var rawfile = new xmlhttprequest(); get filepath false); rawfile.onreadystatechange = function() { if (rawfile.readystate == 4) { if (rawfile.status == 200 || rawfile.status == 0) { var alltext = rawfile.responsetext; alert(alltext); encodedata = window.btoa(alltext); } } }; rawfile.send(null); } </code></pre>,javascript
str object is not callable. encode and decode message i am new to python and programming in general. i was trying to encode and decode a message but this mistake occurs. what does it mean how to fix it <pre><code> def main(): mes=input( enter the message to encode ). key= int(input( enter the key ). print(chr(ord(chr)+key) for chr in mes) main() </code></pre>,python
change java object type during the runtime of my programme i would like to identify the type of an object i would need to instantiate. as an example: if a user is travelling from a to b he can choose a transport method: car or push bike both will enable the user to travel but the actual work processes are different. in a car you need to shift gears to move on a bike you need to paddle. they would have a common set of methods ie: move but their implementation would be different. the rest of the programme doesn t need to know how move is implemented... imagine: <pre><code>public class transport { public object transportmethod; public transport(tmet) { if (tmet.equals( car )) { transportmethod = new car(); } else if (tmet.equals( bike )) { transportmethod = new bike(); } } public object returntransportmethod() { return transportmethod(); } } </code></pre> how can i now use the bike or car methods when i pass transportmethod back to another class thanks! chris,java
undefined when evaluating two string variables in javascript this program seems to work fine until i have two inputs that are strings. the result that is given back is undefined . why is this the case how could i get the output to be: return can\ t compare relationship because + x + and + y + are not numbers <pre><code>function getrelationship(x y) { var notdigit = isnan(x) + isnan(y); if(x==y &amp;&amp; notdigit==false){ return = ; }else if(x&gt;y &amp;&amp; notdigit==false){ return &gt; ; }else if(x&lt;y &amp;&amp; notdigit==false){ return &lt; ; }else if(notdigit==true){ return notnumber(x y); }; }; function notnumber(x y) { xnotdigit = isnan(x); ynotdigit = isnan(y); if(xnotdigit == true){ return can\ t compare relationship because + x + is not a number }else if(ynotdigit == true){ return can\ t compare relationship because + y + is not a number }else if(xnotdigit == true &amp;&amp; ynotdigit == true){ return can\ t compare relationship because + x + and + y + are not numbers }; }; console.log(getrelationship( dfad dfd )); </code></pre>,javascript
directory folder name to put user defined packages in tomcat 7 i am new to java and jsp. i have just created a small package and that package contains a simple java class. let me show what i really want to do. i am not working with servlets so please tell me about this simple example so that i can go ahead with my work. below is my code or a package class and a jsp page. <strong>my java package</strong> <pre><code>package mypack; //this is my package public class abc{ public abc(){ } public void message(){ system.out.println( my first java package ); } } </code></pre> <strong>index.jsp</strong> this is my jsp page where i need to use this package <pre><code>&lt;%@ page import= java.sql.* %&gt; &lt;%@ page import= mypack.* %&gt; &lt;% abc a = new abc(); a.messsage(); %&gt; </code></pre> i was using jdk1.5 and tomcat 3. but i want to update my system. now i have jdk1.7.0_11 and tomcat 7. i know the path of tomcat 3 to put my packages but i don t know where to put these packages in tomcat 7. <strong>tomcat 3 directory path to place packages:</strong> <pre><code>d:\java\tomcat\examples\web-inf\classes //i put my package at this path in tomcat3 </code></pre> <strong>tomcat 7 directory path to place packages:</strong> <pre><code>d:\web\tomcat 7.0\webapps\root\web-inf //trying to put my package in here but no use. </code></pre> i could not find the classes folder under the direcoty web-inf in tomcat 7. i made a folder myself named classes inside of web-inf but it does not work. even i have deleted that my classes folder and put my package in web-inf but it does not work. please tell me the path where i can put my java package in tomcat server 7. i have placed my jsp page in here: <pre><code>d:\web\tomcat 7.0\webapps\root\a //folder a contains my jsp file. index.jsp and its working </code></pre> problem is jsp page could not find the package. please help me out with this.,java
access to propertyname of object itself as string i have object define like this <pre><code>var obj = { abcdefghijkl: abcdefghijkl other_key: 1234 }; </code></pre> can i define object for get property name itself as string in javascript like this <pre><code>var obj = { abcdefghijkl: getselfpropertyname other_key: 1234 }; </code></pre> i don t want for <code>this.abcdefghijkl</code>,javascript
attaining the correct number of a characters in the string i am trying to write a small program that takes a <code>string</code> sentence (given in <code>main method</code>) and calculates the number of upper case characters and number of a s. i am having a bit of trouble with the second part. while there are no doubt multiple ways to write the program i have written <code>for loops</code> that trace through the <code>string</code> and do my work. it works fine for calculating the uppercase values but for the a s it is counting every letter as one. i may be going crazy. <pre><code>public class countcharacters { public static void main(string[] args) { charcount( how many upper case letters a s and 0-9 digits are there in this string ); } public static void charcount(string b) { int upper = 0; int a = 0; for (int i = 0; i &lt; b.length(); i++) { char v = b.charat(i); if (character.isuppercase(v)) { upper++; } } for (int i = 0; i &lt; b.length(); i++) { char t = b.charat(i); if (character.isletter( a )) { a++; } } system.out.println( there are + upper + upper case letters and + a + lower case a s in the string ); } } </code></pre>,java
will apple reject apps that make use of the device id. i have developed an app that make use of the iphone device id and sends the same to a webservcise as primarily my app uses device id to prevent unauthorised device access. but i am in doubt whether apple will reject the app bacause of this... pls can anyone clarify my doubt...,iphone
datetime to second conversion i have two datetime string like this 2010-08-31 04:35:50.176725 and 2010-09-05 04:35:50.176725 . now my question is how calculate seconds between two dates. i used time delta but its return in hour minute formate. i want compltely in seconds.,python
countdown timer is not showing in javascript i am new in javascript i want to create a countdown timer with localstorage which starts from given time and end to 00:00:00 but it s not working when i am running my code it is showing value 1506 . here is my code <pre><code>&lt;script type= text/javascript &gt; if (localstorage.getitem( counter )) { var currenttime = localstorage.getitem( counter ); } else { var hour = 3; var minute = 25; var second = 60; var currenttime = hour.tostring() + : + minute.tostring() + : + second.tostring(); } function countdown() { document.getelementbyid( lblduration ).innerhtml = currenttime; second--; if (second == -1) { second = 59; minute--; } if (minute == -1) { minute = 59; hour--; } localstorage.setitem( counter currenttime); } var interval = setinterval(function () { countdown(); } 1000); &lt;/script&gt; </code></pre>,javascript
error in sonar rule wrt below code while for below code we are getting error in sonar: <pre><code> entitybuildermap = maps.newhashmap(); </code></pre> giving error in sonar as: <blockquote> dodgy - write to static field from instance method </blockquote> can some one suggest how to fixed it out,java
tip rather than question: pseudo-push functionality through pushed email i was just wondering if anybody was using this technique: since push notifications will only be coming with os 3.0 i ve been thinking of using email pushs (exchange as a workaround: you can register a url eg. myxyappname:// for your own app in iphone. (see examples @ if you have a server and want to push something app-specific to your subscribers you can just send them an email containing a specific link eg. myxyappname://myxyappname requesttype=x&amp;id=y when the user receives the email (pushed so should be fast...) and clicks on the mentioned link your app will start on the iphone automatically (if your app registered the url correctly) and within your app you can parse the url and display the corresponding info based on the query string. old fart,iphone
settimeout doesn t work when closure is included so i have this piece of code... <pre><code> var string = qwe ; document.addeventlistener( click function(e){ function bar(b){ var a = string[b]; if (a == q ) { console.log( first ); } if (a == w ) { console.log( second ); } if (a == e ) { console.log( third ); } } settimeout( bar(0) 1000 ); }); </code></pre> problem is settimeout doesn t work. code executes right after clicking. it s weird because if i avoid using the closure it works... <pre><code>settimeout(function bar(){ var a = string[0]; //...everything else } 1000 ); </code></pre> but that would probably make the code messy/redundant since i plan on doing it 3 times. ideally the working code would be... <pre><code>settimeout( bar(0) 1000 ); settimeout( bar(1) 2000 ); settimeout( bar(2) 3000 ); </code></pre> but again setting timeout like this doesn t work for some reason :/ any ideas why,javascript
how can move from one tabviewcontroller to another tabviewcontroller i ve a problem that when i go to any viewcontroller of second tabbar button then i need to come first tabviewcontroller. but i can t in my one view of first tabbar comes to second tabbar button.pls someone help me.,iphone
onchange disable textarea php this is my form and i need to disable the textarea if the option city2 is selected and enable the textarea if the other options are selected. <pre><code>&lt;!doctype html public -//w3c//dtd xhtml 1.0 transitional//en &gt; &lt;html xmlns= &gt; &lt;head&gt; &lt;meta http-equiv= content-type content= text/html; charset=iso-8859-1 /&gt; &lt;title&gt;untitled document&lt;/title&gt; &lt;script type= text/javascript &gt; var cityselect = document.getelementbyid( city ) descriptiontextarea = document.getelementbyid( description ); cityselect.addeventlistener( change function() { descriptiontextarea.disabled = cityselect.selectedindex == 1; } false); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form method= post name= areaform id= areaform &gt; &lt;select name= city id= city &gt; &lt;option value= city1 &gt;city1&lt;/option&gt; &lt;option value= city2 &gt;city2&lt;/option&gt; &lt;option value= city3 &gt;city3&lt;/option&gt; &lt;/select&gt;&lt;br /&gt; &lt;br /&gt; &lt;textarea name= description id= description cols= rows= style= width:150px; height:50px; &gt;&lt;/textarea&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> how can i do that,javascript
suspend app option i have an app that i have and i have it set to not run in background but a number people want to option to have it resume from where they left off and a number of people just want it to start from the beginning when they tap the home button and restart to app. how do i add an on/off switch to give the user the option my app is a educational / reference app with flashcards and pdfs. thanks j,iphone
iphone sdk: how to set the initial value of a uipickerview i have a picker view that has a list of numbers to pick from. i want to be able to initialize the control at a particular row. for example if the user specifies 10 as their default then the control should be automatically positioned at that row when the control is first initialized. thanks in advance.,iphone
"concatenate variable in function name - javascript im trying to build a for loop so i dont waste code lines by repeating the same code for a function but im not doing it right i need help on how to concatenate my loop variable (i) so i can change the name of the function. here is my function code: <div class= snippet data-lang= js data-hide= false data-console= true data-babel= false >
<div class= snippet-code >
<pre class= snippet-code-js lang-js prettyprint-override ><code>&lt;script&gt;
for (i = 1; i &lt; 90; i++) {
var nome = window[ mostra + i];
function nome() {
document.getelementbyid( form +i).style.display= block ;
document.getelementbyid( texto +i).style.display= none ;
python for data analysis book chapter 2 error in reading records i am learning python for data analysis from o reilly s book <a href= rel= nofollow noreferrer >python for data analysis</a>. i am getting following error in command prompt when i am running this command <code> records = [json.loads(line) for line in open(path)] </code> <pre><code>unicodedecodeerror: utf8 codec can t decode byte 0x92 in position 6:invalid start byte </code></pre> please guide me on how to solve it. thanks.,python
how to draw a line on top of an image when finger moves on iphone i am trying to draw a line on top of a background image in my uiview tracing the movements of the user s finger. i can accomplish this by drawing the uiimage as my background and then doing my line drawing in drawrect but i have to load the image each time drawrect is called and it makes performance sluggish. alternatively if i use a uiimageview as my background image (just adding it to the view in ib or programatically) the lines disappear when it is dragged over the image. is there a way to tell the lines to draw on top of the uiimageview. thanks for your help. here is my code using the uiimage method: <pre><code>- (void)drawrect:(cgrect)rect { uiimage *imagefield = [uiimage imagenamed:@ field.jpg ]; cgrect rectforimage=cgrectmake(0 0 200 200); [imagefield drawinrect:rectforimage]; cgcontextref context = uigraphicsgetcurrentcontext(); cgcontextmovetopoint(context x1 y1); cgcontextaddlinetopoint(context x2 y2); cgcontextstrokepath(context); } </code></pre>,iphone
im trying to get key input to work by getting and setting x/y values but it isnt working i know that the the image is drawing constantly but the x/y coordinates arent changing which doesnt let the image move.. why is this happening and what can i do to fix it <pre><code>import java.awt.*; public class gamestate extends state { private player player; private int playerx = 1440/2 - 14 playery = 810/2 - 14; public gamestate(superhexagongame game) { super(game); player = new player(playerx playery); } public void tick() { player.tick(); } public player getplayer() { return player; } public void render(graphics g) { g.drawimage(assets.bg1 0 0 null); player.render(g); } } </code></pre> player class <pre><code>import java.awt.*; public class player extends creature { public player(int x int y) { super(x y); } public void tick() { } public int getx() { return x; } public int gety() { return y; } public void setx(int x) { this.x = x; } public void sety(int y) { this.y = y; } public void render(graphics g) { system.out.println(y); g.drawimage(assets.player1 x y null); } } </code></pre> key input class that checks for key input. im trying to get it to set the xy values in the player class by getting the current xy value and adding/subtracting 75 <pre><code>import java.awt.event.*; public class keyinput extends keyadapter { private player player = new player(1440 / 2 - 14 810/2 - 14); public void keypressed(keyevent e) { int key = e.getkeycode(); system.out.println(key); if (key == keyevent.vk_up) { //decrement y by 75 player.sety(player.gety() - 75); } if (key == keyevent.vk_down) { //increment y by 75 } if (key == keyevent.vk_left) { //decrement x by 75 } if (key == keyevent.vk_right) { //increment x by 75 } } } </code></pre> i know the program is getting keyboard input (arrow keys) because when pressing a key it displays the keycode into console it but it isn t setting the xy values to the new xy values for movement. i only have the code done for up arrow key because i wanted to make sure it worked before copy pasting.,java
adding /putting share buttons of facebook twitter in your iphone application have anyone worked with buttons such as share on facebook twitter email download .please reply.,iphone
python prints different value each iteration but value is not changed. i cannot wrap my head around why my python code acts in a certain way. since i do not change current the output should be the same for each iteration this is a problem because i need current to be the same so each node is generated from the same start-value. see the following code: <pre><code>class node: def __init__(self board=none): self.board = board def getboard(self): return self.board def swap(self xpos ypos): # swap with zero for a in self.board: if 0 in a: self.board[self.board.index(a)][a.index(0)] = self.board[xpos][ypos] self.board[xpos][ypos] = 0 open = [] def gen_nodes(current): for i in [7 15 11]: print(current) # &lt;-- why does this print a different value each time new = node(current) for a in new.getboard(): if i in a: xpos = new.getboard().index(a) ypos = a.index(i) new.swap(xpos ypos) open.append(new) if __name__ == __main__ : gen_nodes([[1 2 3 4] [8 5 6 7] [9 10 11 0] [12 13 14 15]]) </code></pre> output: <pre><code>[[1 2 3 4] [8 5 6 7] [9 10 11 0] [12 13 14 15]] [[1 2 3 4] [8 5 6 0] [9 10 11 7] [12 13 14 15]] [[1 2 3 4] [8 5 6 15] [9 10 11 7] [12 13 14 0]] </code></pre>,python
need javolution and jdk version i want to know the javolution and jna jar version which is supported by jdk 1.4. thanks in advance.,java
showing progress view in corresponding cell when click a download button in a tableview cell i am new to iphone.i am struck in my project at some task (i.e) i have a table view with 66 that i am placed different book names for each cell and place a download button to each requirement is when we click on download button it shows the progress view in that particular cell only but i am getting in that particular cell but when i am drag the tableview it will shows the progress views in some that cells is because of dequeue reusability concept but i dont know how to avoid this problem.i want even after drag the tableview it shows the progress view on the cell which i am click the download button (cell) here is my code below.. <pre><code>- (nsinteger)numberofsectionsintableview:(uitableview *)tableview { // return the number of sections. return 1; } - (nsinteger)tableview:(uitableview *)tableview numberofrowsinsection:(nsinteger)section { return 66; } - (uitableviewcell *)tableview:(uitableview *)_tableview cellforrowatindexpath:(nsindexpath *)indexpath { static nsstring *cellidentifier = @ cell ; uibutton *downloadbutton = nil; customcell *cell = [_tableview dequeuereusablecellwithidentifier:cellidentifier]; if (cell == nil) { //here custom cell is another class in that we have the title label declaration cell = [[customcell alloc] initwithstyle:uitableviewcellstylesubtitle reuseidentifier:cellidentifier]; downloadbutton = [uibutton buttonwithtype:uibuttontypecustom]; downloadbutton.frame = cgrectmake(220 10 50 30); [downloadbutton setimage:[uiimage imagenamed:@ download.png ] forstate:uicontrolstatenormal]; [downloadbutton addtarget:self action:@selector(downloadbuttonclicked:) forcontrolevents:uicontroleventtouchupinside]; downloadbutton.backgroundcolor = [uicolor clearcolor]; downloadbutton.userinteractionenabled = yes; downloadbutton.highlighted = yes; downloadbutton.tag = indexpath.row; nslog(@ tag is %d indexpath.row); [cell.contentview addsubview:downloadbutton]; } nsstring *titlelabel = [[appdelegate getbooknames]objectatindex:indexpath.row]; cell.titlelabel.text = titlelabel; return cell; } -(void)downloadbuttonclicked:(id)sender{ int index = [sender tag]; nslog(@ index of the cell is %d index); uibutton *button = (uibutton*)sender; uitableviewcell *cell = (uitableviewcell *)[[button superview] superview]; uilabel *titlelabel = (uilabel *)[cell viewwithtag:100]; nslog(@ label text =%@ titlelabel.text); selectedbooktitle = titlelabel.text; nsstring* documentspath = [nssearchpathfordirectoriesindomains(nsdocumentdirectory nsuserdomainmask yes) objectatindex:0]; nsmutablearray *alldownloadlinks; bibleplayerviewcontroller = [[bibleplayerviewcontroller alloc]init]; alldownloadlinks = [bibleplayerviewcontroller alldownloadlinks]; nslog(@ all download links are %@ alldownloadlinks); bibleplayerviewcontroller.indexofselectedbooktitle = [[appdelegate getbooknames]indexofobject:selectedbooktitle]; download* download = [download downloadwithtitle:selectedbooktitle url:[nsurl urlwithstring:[nsstring stringwithformat:@ [alldownloadlinks objectatindex:(bibleplayerviewcontroller.indexofselectedbooktitle)]]]pathtosave:documentspath]; [[downloadmanager shareddownloadmanager] queuedownload: download]; uitableviewcell *tableviewcell = [tableview cellforrowatindexpath:indexpath]; progressview.frame = cgrectmake(10 40 300 20); [tableviewcell.contentview addsubview:progressview]; } </code></pre> <a href= rel= nofollow >screen shot</a> of my project is [output of my above code which is in simulator],iphone
construct tuple from dictionary values given a python a list of dictionary of key-value pairs i.e. <pre><code>[{ color : red value : high } { color : yellow value : low }] </code></pre> how to construct a list of tuples from the dictionary values only: <pre><code>[( red high ) ( yellow low )] </code></pre>,python
formatting perfectly with printf in java i m trying to make my program print out a bill of three items with their names quantities and prices. everything works fine all i need is how to formate the prices and totals in order to make all the decimals line up everytime no matter how big the number. here s my code <pre><code> import java.util.scanner; class assignmentonetest { public static void main(string[] args) { scanner kb = new scanner(; // system.out.printf( $%4.2f for each %s price item); // system.out.printf( \nthe total is: $%4.2f total); //process for item one system.out.println( please enter in your first item ); string item = kb.nextline(); system.out.println( please enter the quantity for this item ); int quantity = integer.parseint(kb.nextline()); system.out.println( please enter in the price of your item ); double price = double.parsedouble(kb.nextline()); //process for item two system.out.println( please enter in your second item ); string item2 = kb.nextline(); system.out.println( please enter the quantity for this item ); int quantity2 = integer.parseint(kb.nextline()); system.out.print( please enter in the price of your item ); double price2 =double.parsedouble(kb.nextline()); double total2 = quantity2*price2; // system.out.printf( $%4.2f for each %s price2 item2); // system.out.printf( \nthe total is: $%4.2f total2); //process for item three system.out.println( please enter in your third item ); string item3 = kb.nextline(); system.out.println( please enter the quantity for this item ); int quantity3 = integer.parseint(kb.nextline()); system.out.println( please enter in the price of your item ); double price3 = double.parsedouble(kb.nextline()); double total3 = quantity3*price3; // system.out.printf( $%4.2f for each %s price3 item3); // system.out.printf( \nthe total is: $%4.2f total3); double total = quantity*price; double grandtotal = total + total2 + total3; double salestax = grandtotal*(.0625); double grandtotaltaxed = grandtotal + salestax; string amount = quantity ; string amount1 = price ; string amount2 = total ; string taxsign = % ; system.out.printf( \nyour bill: ); system.out.printf( \n\nitem ); system.out.printf( %28s %11s %11s quantity price total ); //complete item one format system.out.printf( \n%-30s item); system.out.printf( %-10d (int)quantity); system.out.printf( %-10.2f (float)price); system.out.printf( + %-10.2f (float)total); //complete item two format system.out.printf( \n%-30s item2); system.out.printf( %-10d (int)quantity2); system.out.printf( %-10.2f (float)price2); system.out.printf( + %-10.2f (float)total2); //complete item three format system.out.printf( \n%-30s item3); system.out.printf( %-10d (int)quantity3); system.out.printf( %-10.2f (float)price3); system.out.printf( + %-10.2f (float)total3); system.out.printf( \n\n\nsubtotal %47.2f grandtotal); system.out.printf( \n6.25 %s sales tax %39.2f taxsign salestax); system.out.printf( \ntotal %50.2f grandtotaltaxed); } </code></pre> the problem is that every time the prices are the same everything lines up but lets say i type in a price of 50.00 and a price of 2.50 for two different items then the items price and total decimal points don t all line up please help.,java
iphone view not visible i have the following code in my loadview method and can t understand why i can t see both different colored blocks. i thought the second self.view = was overlapping the second view so i could only see the green view. however even if i set the views alpha to 0.5 i still don t see the blue block the green one just becomes more transparent. am i missing something really stupid here <pre><code>- (void)loadview { cgrect newframe; newframe.origin = cgpointmake(100 100); newframe.size = cgsizemake(100 40); uiview *myview = [[uiview alloc] initwithframe:newframe]; myview.backgroundcolor = [uicolor bluecolor]; //myview.alpha = 0.5; self.view = myview; cgrect newframe2; newframe2.origin = cgpointmake(100 200); newframe2.size = cgsizemake(100 40); uiview *myview2 = [[uiview alloc] initwithframe:newframe2]; myview2.backgroundcolor = [uicolor greencolor]; //myview2.alpha = 0.5; self.view = myview2; </code></pre> },iphone
how can i divide two floats and get an integer i have two variables that are both floats and i want the division to return as an integer. i ve tried a few things such as math.round() and multiplying it by 1 then dividing by 1 i can t seem to get it to work. <pre><code> import java.util.scanner; public class calculator { public static void main (string[] args) { float firstnumber; float secondnumber; char operator; float answer; float answerremainder; scanner input = new scanner (; system.out.print( enter your first number ); firstnumber = input.nextint(); system.out.print( enter the operator (s for subtraction a for addition m for multiplication d for division r for division with a remainder))\n ); operator =; while (operator != s &amp;&amp; operator != a &amp;&amp; operator != m &amp;&amp; operator != d &amp;&amp; operator != r ) { system.out.print( \nyou have entered an incorrect character. enter the operator (s for subtraction a for addition m for multiplication d for division r for division with a remainder)\n ); operator =; } system.out.print( enter your second number ); secondnumber = input.nextint(); if (operator == s ) { system.out.print(firstnumber + - +secondnumber+ = +(firstnumber - secondnumber)); } else if (operator == a ) { system.out.print(firstnumber + + +secondnumber+ = +(firstnumber + secondnumber)); } else if (operator == m ) { system.out.print(firstnumber+ * +secondnumber+ = +(firstnumber * secondnumber)); } else if (operator == d ) { system.out.print(firstnumber+ / +secondnumber+ = +(firstnumber / secondnumber)); } else if (operator == r ) { answerremainder = (firstnumber / secondnumber); system.out.print(firstnumber+ / +secondnumber+ = +(answerremainder)+ with a remainder of +(firstnumber % secondnumber)); } } } </code></pre> so i want the last line answerremainder to be a whole number,java
returning an array of strings from a method - java i have a class <pre><code>package lab4; public class criticalclasses { private string course_name; private string[] critical_class = new string[3]; public criticalclasses (string course){ course_name = course; } public criticalclasses (string class0 string class1 string class2){ critical_class[0] = class0; critical_class[1] = class1; critical_class[2] = class2; } public string tostring(){ return course_name; } } </code></pre> this is my main: <pre><code>package lab4; import java.util.scanner; public class lab4 { public static void main(string[] args) { criticalclasses course; course = new criticalclasses( ingegneria ); system.out.println(course); criticalclasses classes; classes = new criticalclasses( number1 number2 number3 ); //system.out.println(java.util.arrays.tostring(classes)); //system.out.println(classes); these are comments because i dont know what to write } </code></pre> i cannot understand how to return all the inserted values in the main. i should use the tostring method but i can do that only for the element course_name. thank you in advance.,java
iterating through arraylist to get 5 largest numbers yes this is homework but i need some help with it. i have been able to make it sort through the highest number but none of the numbers are correct after that. list of numbers: <a href= rel= nofollow ></a> right now we are learning arrays so is this simply trying to shoot a fly with a cannonball <pre><code> package hw2; import; import; import java.util.arraylist; public class hw2 { public static arraylist&lt;integer&gt; nums1 = new arraylist&lt;integer&gt;(); public static int size = 0; public static void main(string[] args) throws exception { arraylist&lt;integer&gt; sortednums = new arraylist&lt;integer&gt;(); readfile(); system.out.println( name: jay bhagat + \n + email: xxxxxx ); size = nums1.size(); for(int l = 0; l&lt;=10;l++){ nums1.set(sortthis(nums1 l) 90009); system.out.println( \n\n ); } // for (int k = 0; k &lt;= size - 1; k++) { // system.out.println( number + (k + 1) + sortednums.get(k)); // // } } public static void readfile() throws exception { bufferedreader reader = new bufferedreader(new filereader( l:\\numbers.txt )); while (reader.readline() != null) { nums1.add(integer.parseint((reader.readline()))); } reader.close(); } public static int sortthis(arraylist&lt;integer&gt; current int offset) { int j = 0; int tempnum = 0; int curnum = 0; int finalindex = 0; int previndex = 0; int curindex = 0; for (j = 0; j &lt; size-offset; j++) { curindex = j; nums1.trimtosize(); curnum = current.get(j); //thread.sleep(1000); if(curnum!=90009){ if (curnum &gt; tempnum) { tempnum = curnum; system.out.println(tempnum); previndex = j; finalindex = previndex; } if (curnum &lt; tempnum) { finalindex = previndex; } } } return finalindex; } } </code></pre>,java
move class between elements with pure javascript without using jquery can you help me here with this ordinary js code as i want to move the classname active from item to another item including removing all elements class and keep it with the this.item <pre><code>function moveclass(){ var item = document.getelementsbyclassname( item ); for(var i = 0 ; i &lt; item.length ; i++){ var items = item[i]; items.onclick=function(){ items.classlist.remove( active ); this.classlist.add( active ); } } } window.addeventlistener( load moveclass) </code></pre>,javascript
how to make a diagram from arrays in java my program needs to draw a diagram like this: <pre><code> --- --- xxx --- xxx +++ --- xxx +++ --- ooo xxx +++ --- ooo xxx +++ --- ooo xxx +++ --- *** ooo xxx +++ --- *** ooo xxx +++ --- *** ooo xxx </code></pre> from this data: <pre><code>private static final int[] data = {15 21 7 12 18}; private static final int max_height = 10; private static final int column_width = 3; private static final int space_between_columns = 2; private static final char[] filler = {’+’ ’-’ ’*’ ’o’ ’x’}; </code></pre> i really need some guidlines on how to make it. thanks,java
create math function with a dummy variable to be evaluated later i am trying to create a function in python which will add a bunch of math terms together which include some arbitrary variable name to be evaluated after the entire thing has been constructed. so for example <pre><code>def transform(terms xterm): function=.5 step=terms odd=1 while step&gt;0: function+=(2/odd*np.pi)*np.sin(odd*np.pi*xterm) odd+=2 step-=1 return function test=transform(10 somexvariable) print test </code></pre> this is a fourier series for a particular function i had to do in my mechanics class. basically i want to for amount of terms (say 5) create a variable that looks like this: <pre><code>function = .5 + (2/odd*np.pi)*np.sin(odd*np.pi*xvariable) +....... </code></pre> out to however many terms i want where the variable odd is the only number that changes. the key and the difficulty to this problem is inserting some dummy variable i called xvariable so that later i can create a array like this: <pre><code>x2 = np.arange(0 10 .05) y = transform(2 x2) </code></pre> the result would be an array of those x values evaluated in the function i created with transform . i am sure i am going about this the wrong way...but i can t seem to figure out the necessary order of steps to make this work. help please. thanks!,python
javascript variable null error hi there i found an error in my javascript code using firebug <strong>b is null</strong> and my images are not changing.what i am trying to implement is 3 images swapping eventually on a webpage but standalone at the moment.currently nothing is happening with it and i have tested in 3 well known browsers. any help would be great <pre><code>&lt;script type= text/javascript &gt; var imagearr1 = new array( banner1.jpg banner2.jpg banner3.jpg ); var imageholder1 = document.getelementbyid( photo ); function rotateimages(whichholder start) { var a = eval( imagearr +whichholder); var b = eval( imageholder +whichholder); if(start&gt;=b.length) start=0; b.src = a[start]; document.getelementbyid( slidenumber ).textcontent = slide +(start+1)+ of +imagearr1.length; window.settimeout( rotateimages( +whichholder+ +(start+1)+ ) 3500); } rotateimages(1 0); &lt;/script&gt; </code></pre>,javascript
what is the value of x i have a piece of code that i wrote in tag. <pre><code>&lt;script&gt; var y = 1 x = y = typeof x; alert(x); &lt;/script&gt; </code></pre> this will alert x as undefined . please explain me how this is evaluated by javascript compiler. thanks in advance.,javascript
how to detect change on webpage without reload i found ho to detect by using perl. <a href=] >how to detect a changed webpage </a> but unfortunatelly i don t know perl. is there a way in python can you give a detailed example if you do not complicate,python
code breaks when highlighting at selectionstart equal to zero when ever i highlight at what would be selectionstart = 0; this code does not execute. however if i highlight one character in front of the first character in the textarea the code works. any ideas about getting this code to work if i highlight at the first character in the textarea <pre><code> function fontbbcode(font){ var textbox = document.getelementbyid( content ); var textselected; var fonttagopen = [font= ; var fonttagclose = [/font] ; var stringbuilder; var sel; var startselpos; var endselpos; var len; if (document.selection){//ie textbox.focus(); sel = document.selection.createrange(); textselected = sel.text; } else if (textbox.selectionstart){//mozilla startselpos = textbox.selectionstart; endselpos = textbox.selectionend; textselected = textbox.value.substring(startselpos endselpos); } alert(textselected.length); alert(textbox.value.length); if (textselected){ stringbuilder = fonttagopen.concat(font); stringbuilder = stringbuilder.concat( ] ); stringbuilder = stringbuilder.concat(textselected); stringbuilder = stringbuilder.concat(fonttagclose); if(document.selection)//ie sel.text = stringbuilder; else if(textbox.selectionstart){//mozilla len = textbox.value.length; textbox.value = textbox.value.substring(0 startselpos) + stringbuilder + textbox.value.substring(endselpos len); } } else{ stringbuilder = fonttagopen.concat(font); stringbuilder = stringbuilder.concat( ] ); stringbuilder = stringbuilder.concat(fonttagclose); textbox.value += stringbuilder; } } </code></pre>,javascript
emoji like application i want to create custom keyboard application like emoji app. i know how to enable emoji in the iphone but my question is from were the icons are coming and how i can add my own icons to emoji keyboard or i have to make my own keyboard separate. this all should work with all app like email notes etc... please advice some solution.,iphone
access object in javascript array by id or unique prop with o(1) let s say we have an array of objects like this: <pre><code>const myarray = [ { id: a label: a } { id: b label: b } ... ]; </code></pre> is there a way to access any object in this array by id with constant o(1) time complexity,javascript
iterate over nested (multi-level) hashmap i am trying to write a java program to iterate over a multi-level hashmap. for example i have a <code>hashmap &lt;string object&gt;</code> where object can be another <code>hashmap&lt;string object&gt;</code>. the level of this hashmap can be n (>5). can someone give me a hint on how to write it in java does java provide some utility thanks,java
passing array through average method resulting in low percent for some reason the average is being populated wrong when i pass the array to the method i get a really low percent. it almost seems like since the array shotsmade is only recording integers for made shots and not misses it is not calculating off the right base. <pre><code>import java.util.*; public class test { public static void main(string[] args) { int mygamecounter = 1; int shotcount = 0; int shotcount1 = 0; int [] shotsmade = new int [5]; int sum = 0; system.out.print( enter player s free throw percentage: ); scanner input = new scanner(; int percent = input.nextint(); //game #1 system.out.println( game + mygamecounter + : ); random r = new random(); mygamecounter++; shotcount = 0; for (int i = 0; i &lt; 10; ++i){ boolean in = tryfreethrow(percent); if (in) { shotcount++; system.out.print( in + ); } else { system.out.print( out + ); } } system.out.println( ); system.out.println( free throws made: + shotcount + out of 10 ); shotsmade[0]= shotcount; //game #2 system.out.println( ); system.out.println( game + mygamecounter + : ); mygamecounter++; shotcount1 = 0; for (int i = 0; i &lt; 10; ++i){ boolean in = tryfreethrow(percent); if (in) { shotcount1++; system.out.print( in + ); } else { system.out.print( out + ); } } system.out.println( ); system.out.println( free throws made: + shotcount1 + out of 10 ); shotsmade[1]= shotcount1; system.out.println( ); system.out.println( summary: ); system.out.println( best game: + max(shotsmade)); system.out.println( total free throws made: + sum(shotsmade) + + out of 20 ); system.out.println( average free throw percentage: + average(shotsmade) + % ); </code></pre> }//main <pre><code>public static boolean tryfreethrow(int percent) { random r = new random(); int number = r.nextint(100); if (number &gt; percent){ return false; } return true; } public static float average(int nums[]) { int total = 0; for (int i=0; i&lt;nums.length; i++) { total = total + nums[i]; } float f = (total / nums.length); return (float)total /(float)nums.length; } public static int sum(int nums[]) { int sum = 0; for (int i=0; i&lt;nums.length; ++i) { sum += nums[i]; } return (int)sum; } public static int max(int nums[]) { int max=nums[0]; for (int i=1; i&lt;nums.length; i++) { if (nums[i] &gt; max) max = nums[i]; } return max; } </code></pre> }//class,java
css & javascript popup not working why isn t this javascript function triggering the popup i ve tried .classlist as well as style.visibility and neither triggers the #filter div to display. <pre><code>&lt;div class= lpicon onclick= designfunction &gt; &lt;img class= lpactionicon src= file:///users/homefolder/desktop/hyperspace%20website/images/launchpad/lp%20action%20icon-%20design.png /&gt; &lt;/div&gt; &lt;div id= filter &gt; &lt;/div&gt; </code></pre> css: <pre><code>.lpicon { height: 100px; width: 50px; margin-left: 14%; margin-top: 8%; float: left; } #filter { visibility: hidden; height: 100%; width: 100%; background-color: grey; position: absolute; opacity: .7; top: 0px; } </code></pre> javascript: <pre><code>function designfunction() { document.getelementbyid( filter ).classlist.remove( block ); } </code></pre>,javascript
how to tell user how many attempts left in python i am trying to make a random number game in python where the computer has to generate a number between 1 and 20 and you have to guess it. i have limited the amount of guesses to 6. how do i print how many guesses the user has left when they get a guess wrong here is my code: <pre><code>import random attempts = 0 name = input( what is your name ) random = random.randint(1 20) print(name + i m thinking of a number between 1 and 20 what is it ) while attempts &lt; 6: number = int(input( type your guess: )) attempts = attempts + 1 int(print(attempts attemps left )) #this is the code to tell the user how many attempts left if number &lt; random: print( too low. try something higher ) if number &gt; random: print( too high. try something lower ) if number == random: break if number == random: if attempts &lt;= 3: print( well done name + ! it took you only attempts attempts ) if attempts &gt;= 4: print( well done name + ! it took you attempts attempts. athough next time try to get three attempts or lower ) if number != random: print( sorry. all your attempts have been used up. the number i was thinking of was random) </code></pre> thanks any help is greatly appreciated!,python
javascript: how can i use the filter() to filter out specific objects with a certain value i have an object with accounts example: <pre><code> { amount : 822370.71 state : me } { amount : 968817.53 state : fl } { amount : 587603.26 state : oh } { amount : 657617.83 state : oh } { amount : 657617.83 state : fl } </code></pre> let s say i want to filter out only the objects with the states of fl and oh how could i use the filter() to do that thanks.,javascript
how to use uiview transitionwithview i ve written a small multiplayer game for the iphone. once one of the players win i want to display him you win image which is in an imageview. i want to make an animation that will show this uiimageview on top of the current game view with sliding from bottom animation. this uiimageview will fill the whole screen while using transparency to make it modal so in the background i will still see the game state. how cam this be done using uiview transitionwithview,iphone
dynamically generated json order is missing with the values present inside the map datastructure i am creating a json dynamically . <strong>the json its getting created is</strong> <pre><code>{ item : { t1 : [ { name : ice creams t2 : [ { name : ice creams***stick t3 : [ { t4 : [ { name : ice creams***stick***koolcool***strawbeerry leaf : [ { crust_name : crust } ] } ] name : ice creams***stick***koolcool } ] } ] } ] } } </code></pre> the problem is that the name under t3 is being appended at some other place rather than after it which should actually be <pre><code>{ item : { t1 : [ { name : ice creams t2 : [ { name : ice creams***stick t3 : [ { name : ice creams***stick***koolcool t4 : [ { name : ice creams***stick***koolcool***strawbeerry leaf : [ { crust_name : crust } ] } ] } ] } ] } ] } } </code></pre> functionally there should be no difference between name being first or second in the property list but this json would be passed to the front end and the search functionality is breaking down if it not follows the structure could anybody please let me know how to make the name appear after t3 please see this fiddle <a href= rel= nofollow ></a> <strong>this is my java program.</strong> <pre><code>package; import java.util.linkedhashmap; import java.util.linkedlist; import java.util.list; import; import org.json.jsonarray; import org.json.jsonexception; import org.json.jsonobject; public class test { private static jsonobject processstring(string data int level string key) throws jsonexception { jsonobject json = new jsonobject(); jsonarray leafjsonarray = new jsonarray(); int index = data.indexof( ); string name = data; string remainder = ; if (index &lt; 0) { index = name.indexof( ( ); if (index &gt; 0) { name = data.substring(0 index); } } else { name = data.substring(0 index); remainder = data.substring(name.length() + 1); } string fullpath = key+ *** +name; json.put( name fullpath); jsonarray a = new jsonarray(); if (remainder.length() &gt; 0) { a.put(processstring(remainder level + 1 fullpath)); json.put( t + level a); } else { jsonobject leafjsonobj = new jsonobject(); leafjsonobj.put( crust_name crust ); leafjsonarray.put(leafjsonobj); json.put( leaf leafjsonarray); } return json; } private static jsonarray processlist(list&lt;string&gt; list int level string key) throws jsonexception { jsonarray json = new jsonarray(); for (string data : list) { json.put(processstring(data level key)); } return json; } private static jsonarray processmap(map&lt;string list&lt;string&gt;&gt; map int level) throws jsonexception { jsonarray array =new jsonarray(); for (string key : map.keyset()) { jsonobject json = new jsonobject(); json.put( name key); json.put( t + level processlist(map.get(key) level + 1 key)); array.put(json); } return array; } public static void main(string args[]) { map&lt;string list&lt;string&gt;&gt; consilatedmapmap = new linkedhashmap&lt;string list&lt;string&gt;&gt;(); list&lt;string&gt; values = new linkedlist&lt;string&gt;(); values.add( stick koolcool strawbeerry(25) ); // values.add( cone sss(25) ); /* list&lt;string&gt; values2 = new linkedlist&lt;string&gt;(); values2.add( bucket(25) ); */ //consilatedmapmap.put( popcorn values2); consilatedmapmap.put( ice creams values); try { int level = 2; jsonarray json = processmap(consilatedmapmap level); jsonobject jsont1 = new jsonobject(); jsont1.put( t1 json); jsonobject sai = new jsonobject(); sai.put( item jsont1); system.out.println(sai); } catch(jsonexception x) { x.printstacktrace(); system.exit(-1); } } } </code></pre>,java
how to get the objects in an array based on particular string i am new to iphone.i have an array which contains the objects like below 04_num <pre><code> 04_num/04num.m3u 04_num/04num001.mp3 04_num/04num002.mp3 04_num/04num003.mp3 04_num/04num004.mp3 04_num/04num005.mp3 04_num/04num006.mp3 04_num/04num007.mp3 04_num/04num008.mp3 04_num/04num009.mp3 04_num/04num010.mp3 04_num/04num011.mp3 04_num/04num012.mp3 04_num/04num013.mp3 04_num/04num014.mp3 04_num/04num015.mp3 04_num/04num016.mp3 04_num/04num017.mp3 04_num/04num018.mp3 04_num/04num019.mp3 04_num/04num020.mp3 04_num/04num021.mp3 04_num/04num022.mp3 04_num/04num023.mp3 04_num/04num024.mp3 04_num/04num025.mp3 04_num/04num026.mp3 04_num/04num027.mp3 04_num/04num028.mp3 04_num/04num029.mp3 04_num/04num030.mp3 04_num/04num031.mp3 04_num/04num032.mp3 04_num/04num033.mp3 04_num/04num034.mp3 04_num/04num035.mp3 04_num/04num036.mp3 </code></pre> but here i want the objects only which contains .mp3 extension and then i have to place those objects into another array how it is possible if any body know this please help me...,iphone
python how to display the results as expected format i am using python to manipulate the data and display as expected format currently i used empty array to append the manipulated data based on the datatype (u8 and u16) for u8 datatype:<code>value = 255</code> i am getting the result :<code>request = 2f f4 0d [ ff 0 0 0]</code> i am expecting result should be display by limiting addition bytes:<code>request = 2f f4 0d ff</code> for u16 datatype:<code>value = 260</code> i am getting the result:<code>request = 2f f4 0c [ 04 10 0 0]</code> i am expecting result should be display by limiting addition bytes:<code>request = 2f f4 0d 04 10</code> the code is as below: <pre><code>def eventonbtniocontrol(event): #called the force numeric item to open gui forcenumericitem() global value global cmd top.wait_window(subtop) request = 2f + + f4 + + 0d + + str(cmd) print request return </code></pre> my gui function: <pre><code>def forcenumericitem(): subtop.bind( &lt;return&gt; eventforcevalue) return </code></pre> clicking enter <pre><code>def eventforcevalue(event): global value value = submenutakestrint() print smiscale fscaledandoffset = ( ( value - smioffset ) / smiscale ) print fscaledandoffset if (fscaledandoffset &gt;= 0.0): iscaledandoffset = math.trunc(fscaledandoffset + 0.5) else: iscaledandoffset = math.trunc(fscaledandoffset - 0.5) print iscaledandoffset global cmd cmd = [0 0 0 0] if(smitype == u8 or smitype == s8 ): cmd[0] = hex(iscaledandoffset &amp; 0xff)[2:].zfill(2) cmdlimit = 1 print cmd elif (smitype == u16 or smitype == s16 ): cmd[0] = hex(( iscaledandoffset &gt;&gt; 8 ) &amp; 0xff)[2:].zfill(2) cmd[1] = hex(iscaledandoffset &amp; 0xff)[2:].zfill(2) cmdlimit = 2 print cmd elif (smitype == u24 ): cmd[0] = hex(( iscaledandoffset &gt;&gt; 16 ) &amp; 0xff)[2:].zfill(2) cmd[2] = hex(( iscaledandoffset &gt;&gt; 8 ) &amp; 0xff)[2:].zfill(2) cmd[3] = hex(iscaledandoffset &amp; 0xff)[2:].zfill(2) print cmd elif (smitype == u32 ): cmd[0] = hex(( iscaledandoffset &gt;&gt; 24 ) &amp; 0xff)[2:].zfill(2) cmd[1] = hex(( iscaledandoffset &gt;&gt; 16 ) &amp; 0xff)[2:].zfill(2) cmd[2] = hex(( iscaledandoffset &gt;&gt; 8 ) &amp; 0xff)[2:].zfill(2) cmd[3] = hex(iscaledandoffset &amp; 0xff)[2:].zfill(2) print cmd else: printf( invalid numeric data by id type red ) subtop.destroy() top.deiconify() return </code></pre>,python
get latest filename after iterating through filenames in a folder in python i have a list of folders. i iterate through each folder and read the filenames and extract the date from them which is in the format 21mar15. next i convert the the date to 2015-03 as string or object. i want to find out which is the latest file or rather get the latest date from each folder into a variable. i am badly stuck. please help. my code goes like this: <pre><code>folders = [] folders = ftp.nlst() folders = map(str folders) folders.sort() new_batches = [folder for folder in folders] #gets a list of folders in the ftp def folder_num(folder): ftp.cwd(folder) x=[] x=ftp.nlst() return x folder_list = len(folder) for batches in new_batches: y=folder_num(batches) if batches == abcd : for b in y: if (len(b)== 19): #print b[8:15] date = datetime.datetime.strptime(b[8:15] %d%b%y ).date().strftime( %y-%m ) print b + + date else: #print b[9:16] date = datetime.datetime.strptime(b[9:16] %d%b%y ).date().strftime( %y-%m ) print b + + date ftp.cwd( // ) elif batches == efgh : for b in y: if (len(b)== 19): #print b[8:15] date = datetime.datetime.strptime(b[8:15] %d%b%y ).date().strftime( %y-%m ) print b + + date else: #print b[19:26] date = datetime.datetime.strptime(b[19:26] %d%b%y ).date().strftime( %y-%m ) print b + + date ftp.cwd( // ) </code></pre> the output is as follows: <pre><code>abcd abcd23mar15 2015-03 abcd130apr15 2015-04 efgh efgc12apr15 2015-04 efgh115feb15 2015-02 </code></pre> <hr> i need to have <pre><code>var1_for_abcd = 2015-04 var2_for_efgh = 2015-04 </code></pre> or please help me to calculate the latest date for each folder. please help. thanks in advance,python
here is a small piece of code for searching the word in a string without using inbuilt string function contains() public class helloworld{ <pre><code> public static void main(string []args){ string s = java is easy to learn ; </code></pre> string[] s2= s.split( \s+ ); string s1= easy ; <pre><code> for(int i=0; i&lt;s2.length; i++){ if(s2[i].equals(s1)){ system.out.println( found ); break; } } } </code></pre> } can somebody help me further to find the word in above string without using equals() method as well means without using any inbuilt functions.,java
how to get the unicode format of 你 i knew that the unicode of <code>你</code> (meaning <code>you</code>) is \x4f\x60. how can i get it from my python command console <pre><code>&gt;&gt;&gt; print( 你 ) 你 &gt;&gt;&gt; print(( 你 ).encode( gbk )) b \xc4\xe3 &gt;&gt;&gt; print(( 你 ).encode( utf-8 )) b \xe4\xbd\xa0 </code></pre> i am in python3.3 .,python
why is this javascript if condition not working as expected i am doing a comparison on dates in javascript. in this case date1 is empty <code> </code> and i can see the same in firebug. as per the code below the first alert shouldn t be called because <code>date1 == </code> but for some reason the alert <code>alert( this is called.... );</code> is invoked. what is wrong here <br /> <pre><code>if(date1 != null || date1 != ){ if( (date1 != null || date2 != ) &amp;&amp; (date1 &lt; date2)){ alert( this is called.... ); break; } else{ alert( that is called.... ); break; } } </code></pre> the above if condition is inside a for loop hence the break.,javascript
triangle numbers in python i m trying to solve the problem: <blockquote> what is the value of the first triangle number to have over five hundred divisors </blockquote> <em>a triangle number is a number in the sequence of the sum of numbers i.e. 1+2+3+4+5...</em> i m pretty sure that this is working code but i don t know because my computer is taking too long to calculate it. does anybody have any idea of how to make the program a little faster.<br> thanks. <pre><code>import math def main(): l = [] one = 0 a = 1 b = 2 while one == 0: a = a + b b += 1 for x in range(1 int(a/2 + 1)): if a % x == 0: l.append(x) if len(l) &gt; 499: print a if __name__ == __main__ : main() </code></pre>,python
splitting a python list into a list of overlapping chunks hi this question is similar to this other <a href= >slicing a list into a list of sub-lists</a> but in my case i want to include the last element of the each previous sub-list as the first element in the next sub-list. and have to take into account that the last element have always to have at least two elements eg: <pre><code>list_ = [ a b c d e f g h ] </code></pre> the result for size 3 sub-list: <pre><code>resultant_list = [[ a b c ] [ c d e ] [ e f g ] [ g h ]] </code></pre>,python
my nested selection doesnt properly work. python i m making a program and i have defined the check password section but for some reason i try the check password option and the nested selection only works to a certain point. this is the section of the code that doesn t work properly: <pre><code>uppercase = set( abcdefghijklmnopqrstuvwxyz ) lowercase = set( abcdefghijklmnopqrstuvwxyz ) digits = set( 0123456789 ) allowedsymbols = set( !$%^&amp;*()-_=+ ) if any ((c in uppercase)for c in userpassword): print ( you have used at least one uppercase letter. 5 points have been awarded. ) totalscore = totalscore + 5 if any ((c in lowercase)for c in userpassword): print ( you have used at least one lowercase letter. 5 points have been awarded. ) totalscore = totalscore + 5 if any ((c in digits)for c in userpassword): print ( you hve used at least one digit. 5 points have been awarded. ) totalscore = totalscore + 5 if any ((c in allowedsymbols)for c in userpassword): print ( you have used at least one of the allowed symbols. 5 points have been awarded. ) totalscore = totalscore + 5 if any ((c in uppercase)for c in userpassword) and any ((c in lowercase)for c in userpassword) and ((c in digits)for c in userpassword) and ((c in allowedsymbols)for c in userpassword): print ( you have used at least one of all the allowed characters. 10 point have been awarded ) totalscore = totalscore + 10 else: print ( you haven t used any of the allowed characters so no points have been awarded. ) print ( the score for your password so far is totalscore) </code></pre> can someone please show me where i have gone wrong thank you.,python
im trying to make a python template with python and html is there anything wrong with this code i can t seem to find any problems i m still new to python. i m using html form action to execute the code but it appeared 500 internal server error... <pre><code>#!/usr/bin/python import mysqldb import time import cgi import cgitb cgitb.enable() localtime = time.asctime( time.localtime(time.time()) ) # open database connection db = mysqldb.connect( localhost root root tas ) # prepare a cursor object using cursor() method cursor = db.cursor() sql = select * from test_tbl where id in (select max(id) from test_tbl) print content-type: text/plain;charset=utf-8\n try: # execute the sql command cursor.execute(sql) # fetch all the rows in a list of lists. results = cursor.fetchall() for row in results: id = row[0] a1 = row[1] a2 = row[2] print wrote at: localtime print fullname: %s % (a1) print nric: %s % (a2) print sign by the willer. ]\n print our presence that involved on that day are ]\n print either by the willer request ]\n print with the willer presence ]\n print and have appointed us as ]\n print the witnesses ]\n except: print error: unable to fecth data # disconnectc from server db.close() </code></pre>,python
json framework in iphone sdk how can we implement json framework in a iphone application development,iphone
create file with javascript is it possible to create a file on localhost with javascript,javascript
indexof method using recursion i need to write a recursive method called indexof that accepts two strings as parameters and that returns the starting index of the first occurrence of the second string inside the first string (or -1 if not found). i have to solve this problem using recursion. these are some example results: <pre><code>indexof( barack obama bar ) 0 indexof( barack obama ck ) 4 indexof( barack obama a ) 1 indexof( barack obama mccain ) -1 indexof( barack obama bar ) -1 </code></pre> this is my solution but it gives me 6 for indexof( barack obama mccain )instead of -1. <pre><code>public static int indexof(string s1 string s2) { if(s1.equals(s2)) return 0; else return indexofhelper(s1 s2 0); } private static int indexofhelper(string s1 string s2 int ctr) { if(s2.length() &gt; s1.length()) return -1; if(s2.length() == 0 || s1.length() == 0) //base case return ctr; else //recursive case if(s1.charat(0) == s2.charat(0)){ //if there is a matching character if(s1.substring(0 s2.length()).equals(s2)) return ctr; //if there is a matching character and the rest of the strings match as well else return -1; //if there is a matching character but the rest of the strings don t match } else return 1 + indexofhelper(s1.substring(1) s2 ctr); </code></pre> },java
ota problem iphone mime type ota(over the air) for iphone.... i have created simple application in iphone 3.0. i want to upload my exe(file) in local webservice. now i want to download this from that site and install in iphone .... how can i did this is it possible can anyone help me thanks in advance..............,iphone
how do i write to a file without erasing the previous line everytime i re-ask the user to enter their grades i have it write a string to the file gradereport but everytime the while loop repeats the previous result is erased. how do i get several lines outputted in the file <pre><code>//open file and call writetofile method printwriter outputfile= new printwriter( gradereport.txt ); outputfile.println(s.writetofile()); outputfile.close(); </code></pre> and the method: <pre><code>public string writetofile() { decimalformat f = new decimalformat( 0.00 ); string str= name + -- + id + -- + f.format(getpercentage())+ -- + getgrade(); return str; } </code></pre>,java
empty trailing comments do they do/mean anything i m looking at some of the code in the android butterknife library and found this snippet <a href= rel= nofollow >here</a>: <pre><code> private static final list&lt;class&lt; extends annotation&gt;&gt; listeners = arrays.aslist(// oncheckedchanged.class // onclick.class // oneditoraction.class // onfocuschange.class // onitemclick.class // onitemlongclick.class // onitemselected.class // onlongclick.class // onpagechange.class // ontextchanged.class // ontouch.class // ); </code></pre> i found this a bit peculiar to have what looks like just empty comments after each line but no comment text. it reminded me a little of line continuation in c macros but i have never come across this before in java. does this actually accomplish anything / is there some convention here where this is used,java
javascript global variable is empty i have a function and created a global variable. the alert inside the function is alerting the result as expected but the variable is showing nothing. how can i fix this here s the code: <pre><code>var connectionresult = ; function checkconnection() { var networkstate = navigator.connection.type; var states = {}; states[connection.unknown] = unknown connection ; states[connection.ethernet] = ethernet connection ; states[connection.wifi] = wifi connection ; states[connection.cell_2g] = cell 2g connection ; states[connection.cell_3g] = cell 3g connection ; states[connection.cell_4g] = cell 4g connection ; states[connection.cell] = cell generic connection ; states[connection.none] = no network connection ; alert( connection type: + states[networkstate]); var connectionresult = states[networkstate]; }; checkconnection(); alert(connectionresult); // returns nothing </code></pre>,javascript
why hash the hashcode in java hashmap when i see java hashmap source code i see the code like this. <pre><code>public v put(k key v value) { if (key == null) return putfornullkey(value); int hash = hash(key.hashcode()); int i = indexfor(hash table.length); for (entry&lt;k v&gt; e = table[i]; e != null; e = { object k; if (e.hash == hash &amp;&amp; ((k = e.key) == key || key.equals(k))) { v oldvalue = e.value; e.value = value; e.recordaccess(this); return oldvalue; } } modcount++; addentry(hash key value i); return null; } </code></pre> so i don t know why we should hash the hashcode is there some problem with hashcode thinks.,java
script inserted with innerhtml not executing i m trying to ad a script and execute it on a certain place of the page but although the code displays on the page when i inspect the dom it doesn t get executed. i m calling this from the head: <pre><code>function include (selector) { document.addeventlistener( domcontentloaded function(){ var selection = document.queryselector(selector); var div = document.createelement( div ); var text = &lt;script src= myscript.js &gt;&lt;/scr + ipt&gt; + &lt;script&gt; + (function(){ + console.log( oh yes ); + myscript() + })(); + &lt;/scr + ipt&gt; ; div.innerhtml = text; if (selection.nextsibling) { selection.parentnode.insertbefore(div selection.nextsibling); } else { selection.parentnode.appendchild(div); } }); } </code></pre> i never get oh yes in my console. does anyone know why this happens i ve checked this 2 answers: <a href= >can scripts be inserted with innerhtml </a> and <a href= >executing &lt;script&gt; elements inserted with .innerhtml</a> the first one doesn t work for strings containing tags and the second one just offers a script and no explanation. i d like to understand if it is possible in this case and how to make it work or where to put that function.,javascript
distribut ios app in app store i have developped an ios application for my client with my personal individual program. now when the app is finish my client would like to distribute the application to the app store. how can i distribut it thanks for your answers,iphone
calendar sunday to sunday i m trying to get flights for 8 days starting from sunday to the next sunday. the way i have implemented it now is by displaying the 7 days starting the selected date from my form. <pre><code>// set up calendar for sunday calendar sunday = calendar.getinstance(); sunday.settime(form.getdate()); sunday.add(calendar.day_of_week -1 * (sunday.get(calendar.day_of_week) - 1)); //set up calendar for next saturday calendar saturday = calendar.getinstance(); saturday.settime(sunday.gettime()); saturday.add(calendar.day_of_week 7); </code></pre> since the max of <code>day_of_week</code> is 7 what do i need to use instead i tried changing this line: <pre><code>saturday.add(calendar.day_of_week 7); </code></pre> to the following one: <pre><code>saturday.add( 8); </code></pre> i already tried couple changes but no luck. any advice,java
javascript image change when keydown and keyup i have some problem regarding changing an image src when i press a key but i can t figure it out how to do it . i managed to change the image i have with other using <code>onmousedown</code> and <code>onmouseup</code> and changes well but i can t figure it out for the keys. my project consists of controlling and rc car using raspberry pi and my website. on the website i have 4 buttons for directions that changes it s color when clicked on them and also there position to simulate that it works. but like i said in the beginning i want to simulate the exact same thing i do with <code>onmousedown</code> and <code>onmouseup</code> using <code>onkeydown</code> and <code>onkeyup</code> for characters <code>w</code> <code>a</code> <code>s</code> <code>d</code> because i couldn t find the ascii for the arrow keys. any tips are welcomed.,javascript
this program throws an exception error when the user inputs a letter or word instead of the expected int (java) this program throws an exception error when the user inputs a letter by accident(typo) when they should enter a number. i need to make it so the user(when asked to input a die number >=1) is able to accidentally enter something other than a number and have the program act like they never entered anything and open up the keyboard again.(while also displaying a message like you entered something wrong please try again. ) heres the code: <pre><code>import java.util.scanner; public class enhancedgameofpig { public static void main(string[] args) { //scanner for taking input from keyboard scanner kb = new scanner(; int nplayer = 0; do { system.out.print( enter the number of players (between 2 to 10): ); nplayer = kb.nextint(); //validity checking for 2-10 if (nplayer&lt;2 || nplayer&gt;10) { system.out.println( ops! the no of supported players are between 2 to 10 ); system.out.println( please enter again: ); } } while(nplayer&lt;2 || nplayer&gt;10); //creating array of nplayer as supplied by the user player [] players = new player[nplayer]; for(int i=0; i&lt;nplayer;i++){ system.out.print( enter player name: ); string name = new scanner(; players[i] = new player(name); } /*starting the game*/ int round = 1; system.out.print( enter predetermined win points: ); int game_over_point = new scanner(; mark: while(true){ //start round for each player for(int i=0;i&lt;players.length;i++){ system.out.println( player name: + players[i].getname() + you are playing round: + round); system.out.print( enter no of dies (&gt;=1): ); int ndie = new scanner(; //validity checking here for die so that it is not &lt;1 if (!(ndie&gt;=1)){ system.out.println( oops! you need to enter a die that is greater than or equal to 1... ); } //datastructure for holding dies for this ith player die [] dieforplayer = new die[ndie]; //create the die objects for(int k = 0;k&lt;ndie;k++){ dieforplayer[k] = new die(); } //rolling the dies now int totalvalue = 0; boolean isthereone = false; system.out.println( rolling + ndie + for + players[i].getname()); for(int k = 0;k&lt;dieforplayer.length;k++){ int value = dieforplayer[k].roll(); system.out.println( die no: + (k+1) + value: + value); if(value==1) //atleast one 1 is there isthereone = true; totalvalue += value; } //roll is over.. now checking if (isthereone &amp;&amp; totalvalue==ndie){ //all of them 1 //reset the banked point for this player players[i].resetbankedpoint(); system.out.println(players[i].getname() + oops! all the dies showed 1 s\n + you get nothing for this round and \n + your banked point has been reset to 0 ); } else if (!isthereone){ //no one(s) rolled //add the points to the banked pont of the user players[i].addbankedpoints(totalvalue); system.out.println(players[i].getname() + great! u get total of : + totalvalue + for this round ); system.out.println( your total banked point is: + players[i].getbankedpoint()); } else{ //there is atleast one 1 get no points for this round players[i].addbankedpoints(0); system.out.println(players[i].getname() + sorry! one of the die turned with one! \n + you get nothing for this round ); system.out.println( your total banked point is: + players[i].getbankedpoint() + \n ); } if (players[i].getbankedpoint()&gt;=game_over_point){ //the game over point has been reached so breaking out of the outer while break mark; } } round++; }//end of the undeterministic while system.out.println( ================the game is over===================== ); system.out.println( total round played: + round); system.out.println( ===================================================== ); for(int i=0;i&lt;players.length;i++){ system.out.print( player name: + players[i].getname() + score: + players[i].getbankedpoint()); if(players[i].getbankedpoint()&gt;=game_over_point){ system.out.println( winner ); } else system.out.println(); } system.out.println( ====================================================== ); kb.close(); } } </code></pre>,java
valueerror: too many values to unpack in fmin_l_bfgs_b i have the following code that is running to run xfoil to get me optimum values of weights in an aerofoil. <pre><code>def four_dim_opt(x0 weight_limits cl file_path xfoil_path): opt_out = fmin_l_bfgs_b(run_xfoil_wcl x0 args = (cl file_path xfoil_path) bounds = weight_limits epsilon = 0.01 approx_grad = true) return opt_out </code></pre> where run_xfoil_wcl is a functionreturning coefficient of drag values (float). the error i keep getting is: <pre><code>traceback (most recent call last): file &lt;pyshell#13&gt; line 1 in &lt;module&gt; four_dim_opt(x0 weight_limits 1.2 file_path xfoil_path) file h:/appliedlab4 - copy(2).py line 157 in four_dim_opt opt_out = fmin_l_bfgs_b(run_xfoil_wcl x0 args = (cl file_path xfoil_path) bounds = weight_limits epsilon = 0.01 approx_grad = true) file c:\python27\lib\site-packages\scipy\optimize\ line 166 in fmin_l_bfgs_b l u = bounds[i] valueerror: too many values to unpack </code></pre>,python
custom header description in uitableview is apple using a documented method of the sdk in or is it some kind of custom cell / custom header description of a grouped tableview storage is <code>titleforheaderinsection:</code>. what is 8.6 gb available - 5.1 gb used <img src= alt= enter image description here >,iphone
summing columns of a txt file in java i have a text file that reads: 1 2 3 4 5 6 7 8 9 1 8 3 9 7 1 9 3 4 8 2 8 7 1 6 5 where each number is separated by a tab. my question is is there a simple way to sum the columns of numbers using java i want it to sum 1+6+8+9+8 2+7+3+3+7 etc. i am reading the file using: <pre><code> public static boolean testmagic(string pathname) throws ioexception { // open the file bufferedreader reader = new bufferedreader(new filereader(pathname)); // for each line in the file ... string line; while ((line = reader.readline()) != null) { // ... sum each column of numbers } reader.close(); return ismagic; } public static void main(string[] args) throws ioexception { string[] filenames = { myfile.txt }; </code></pre> },java
add new field in existing built in application of iphone hope you all are fine and are in your best of moods. i herewith one doubt to ask you kindly help me by giving its solution. i need to add one custom field in existing built in contact application of iphone. i mean i need to allow user to set different icon or logo for different contact. so i need to add one field namely icon or logo in existing application. but i don t know how to do this weather it is possible or not or is there any alternate solution for that or not kindly post your answers. thanks in advance.,iphone
"jquery single .click limit i ve been building a mobile application which scans loyalty cards and checks whether the card is registered against a database. once the barcode has been scanned it opens up an internal browser which automatically inserts the barcode number into a text field through the url that is sent to the browser (using search=123456 at the end of the url). then js checks whether the url has #click_approved in (which is present after scanning). this automatically clicks the submit button and runs the database check thus either bringing back user information if registered or tells the user that the card is not registered. i have got everything working except i m having a small problem where the submit button is constantly being clicked as if the js code is looping. i m not sure if the problem is in my js or elsewhere. any help is appreciated. <div class= snippet data-lang= js data-hide= false >
<div class= snippet-code >
<pre class= snippet-code-js lang-js prettyprint-override ><code>&lt;script&gt;
if(document.url.indexof( #click_approved ) &gt;=0){
document.getelementbyid( approved_btn ).click();
<pre class= snippet-code-html lang-html prettyprint-override ><code>&lt;script src= 3.35.4 &gt;&lt;/script&gt;</code></pre>
this is the js that i have used. i hope i have described what i m trying to achieve and what my problem is clearly. i m new to coding so please be patient with me if i m making a stupid mistake. thank you.",javascript
javascript is not working in my editor i m kind of new in javascript . here is my strange problem.<br> when i write some code in my editor <code>phpstorm</code> and want to see my effect nothating happend but when i put my code in firebug it works !!! here s my little code : <pre><code>var views = document.getelementbyid( views-row ); console.log( this is element type of : views.nodetype); console.log( this is element type of : views.innerhtml); console.log( this is element type of : views.childnodes); var mylinks = document.getelementsbytagname( a ); console.log( links mylinks.length); var views = document.getelementbyid( views-row ); views.setattribute( align right ); </code></pre> am i missing something,javascript
javascript countdown with pause & resume i have javascript countdown <pre><code>var timerscount = 0; var timercounter = setinterval(counttimers 30000); counttimers(); function counttimers() { timerscount++; var count = 26; var counter = setinterval(timer 1000); function timer() { count = count-1; if(count &lt; 0) { clearinterval(counter); return; } document.getelementbyid( timer ).innerhtml=count; } document.getelementbyid( counttimers ).innerhtml=timerscount; } </code></pre> html <pre><code>&lt;button id= pause &gt;pause&lt;/button&gt; &lt;button id= resue &gt;resume&lt;/button&gt; </code></pre> that function is running ok. but now i want to add pause and resume the countdown. is it possible to set it to my function. please help.,javascript
how do you show a js alert only once i want a message to pop up to alert users of lt ie8 that they should really upgrade their browser or they won t have the best possible web experience. however i only want this to pop up on their first visit to my site not on every page refresh. is there a way to do this thanks in advance.,javascript
mutator returning a value mutator returning a value add a new method emptymachine() to the ticketmachine class that is designed to simulate emptying the machine of money it should both return the value in total and reset the value of total to zero. paste the whole method into the space below <pre><code>public int emptymachine() { system.out.println( # + total ); total = 0; } </code></pre> i get this error: <pre><code> missing return statement } ^ 1 error the output should have been: emptymachine() returns correct value emptymachine() empties machine this is what was actually produced: exception in thread main java.lang.noclassdeffounderror: ticketmachine </code></pre>,java
how to compile apps for multiple versions of ios sdks i have an app and i want to compile it for ios 4.1 iphone system but i only have sdk 4.3 on my mac. can i compile that for 4.1 how can i configure it or so i need to install 4.1 sdk onto my mac how can i install it,iphone
method is not a function i ve tried code from here <a href= rel= nofollow noreferrer ></a> but firebug says - this.preload is not a function . why i thought that function is some sort of object.,javascript
javascript array.prototype.find second argument thisarg not working i was reading a javascript book and found this code about how to use <code>arr.find(callback[ thisarg])</code> <pre><code>class person { constructor(name) { = name; = person.nextid++; } } person.nextid = 0; const jamie = new person( jamie ) juliet = new person( juliet ) peter = new person( peter ) jay = new person( jay ); const arr = [jamie juliet peter jay]; // option 2: using this arg: arr.find(p =&gt; === juliet); // returns juliet object </code></pre> i cannot get the desired result. everytime the <code>find()</code> returns <code>undefined</code>.,javascript
using mapkit in iphone application i am using mapkit in my application i want to submit the application to appstore is there any specific procedure need to follow for submitting the mapkit enabled or used application. please help me thanks in advance.,iphone
when to use setters and when to use constructors to set variable values i see we can encapsulate instance variables with setters however constructors seem to do the same thing. <pre><code>class object1 = new class(100 100) // setting using constructor object1.setvalue(100 100) // setting using setters </code></pre> when should i use setters and when should i use constructors to initialize instance variable values,java
will scheduled task run if the user is not opening the application the situation: i have a program that records student s payments (made entirely with html css and javascript) i would like it to calculate the amount of students that stopped the lessons automatically around the end of the month (by automatically i mean without the user having to press any buttons to get that info). my question is: if for example i schedule the function to run on the 29 of every month and that day the user does not open the program does the function get executed anyway or not the program is an off line program made to be downloaded once and run always no need to connect again to the web if the user decides it. i would do something like: <pre><code>var thismoment = new date() //creates a date object currentday = thismoment.getdate(); //this would give me the day at that moment. if(currentday == 29) { }//code to be executed here </code></pre> i know i could just try it but i would have to wait for a day or rewrite the code to schedule something some minutes ahead but i would miss all the juicy information you are probably going to share here hahaha. any help appreciated! :),javascript
break a loop form another method i m having two methods one method (named a) provides loop and sends loop value to another method(named b). if the condition in method b is satisfied the loop from a should stop. how can i implement it. <pre><code>void a() { for(int i=0;i&lt;10;i++) b(i); } void b(int x) { if(x==4) //i want to stop the loop of a } </code></pre>,java
multiple variable for if else statement i have written some code to check if the user has entered a number between 1 and 5 and now i would also like my code to allow the user to enter the letters a s d or m. is there a way to combine the code where i can have it identify whether the user has entered 1-5 or a s d m how do i edit the code below so the user can enter either an integer or a character do i have to write a snippet of code underneath the loop for it to identify that a user did not enter 1-5 but did enter a s d or m as in break out of the loop or is it a separate loop all together. i am so confused! <pre><code>import java.util.inputmismatchexception; import java.util.scanner; public class selection { scanner readinput = new scanner(; int selectionone() { int inputint; do { //do loop will continue to run until user enters correct response system.out.print( please enter a number between 1 and 5 a for addition s for subtraction m for multiplication or d for division: ); try { inputint = readinput.nextint(); //user will enter a response if (inputint &gt;= 1 &amp;&amp; inputint &lt;=5) { system.out.print( thank you ); break; //user entered a number between 1 and 5 } else { system.out.println( sorry you have not entered the correct number please try again. ); } continue; } catch (final inputmismatchexception e) { system.out.println( you have entered an invalid choice. try again. ); readinput.nextline(); // discard non-int input continue; // loop will continue until correct answer is found } } while (true); return inputint; } } </code></pre>,java
variables in javascript i have two arrays sd[16][16] and gd[16][16] in javascript. i need to compare the values of the arrays. <pre><code>var score=0; document.write( &lt;table&gt; ); for(c1=0; c1&lt;16; c1++) { document.write( &lt;tr&gt; ); for(c2=0; c2&lt;16; c2++) document.write( &lt;td onclick= changecolor(this); &gt; + gd[c1][c2] + &lt;/td&gt; ); document.write( &lt;/tr&gt; ); } document.write( &lt;/table&gt; ); function changecolor(tdd) { if(tdd.bgcolor== white ) { tdd.bgcolor= red ; if (gd[c1][c2] == sd[c1][c2]) score+=5; else score-=2; } else { tdd.bgcolor= white ; } } </code></pre> however when i try to display the score later the score is not displayed. <pre><code>function scc() { document.getelementbyid( scf ).innerhtml = score; } &lt;/script&gt; &lt;br&gt;&lt;br&gt;&lt;center&gt;&lt;button type= button onclick= scc() &gt; click to see current score&lt;/button&gt; &lt;p id= scf &gt;0&lt;/p&gt; &lt;/center&gt; &lt;br&gt;&lt;br&gt; &lt;center&gt;&lt;input type= submit value= get solution /&gt;&lt;/center&gt; </code></pre> could someone please tell me what i am doing wrong,javascript
string.replace() doesnt seem to work so i have a <code>function</code> <code>guess_check(guess)</code> that is invoked by <code>prompt()</code> <code>function</code> <code>prompt()</code> invokes <code>guess_check()</code> so that guess is a one work <code>string</code> containing an alphabet character. word is a variable = <code> placeholder </code> below is the code that i m having trouble with: <pre><code>if guess in word: word.replace(guess * ) print word </code></pre> if i make guess = a i would anticipate word = pl*ceholder but it doesn t change. why does the word variable not change and how can i get it to change as i want,python
best way to make a remote database driven iphone application i have a school project that i think i can do with the concept of secure database driven application can anybody help me how to do that because i am confused with method will be best and secure. tutorial link will be good,iphone
getting the wrong answer (monte carlo) for estimation of pi i am trying to estimate the value of pi using a monte carlo simulation. i need to use two unit circles that are a user input distance from the origin. this is what i have: <pre><code>import random import math import sys def main(): numdarts=int(sys.argv[1]) distance=float(sys.argv[2]) print(montepi(numdarts distance)) def montepi(numdarts distance): width=2*(1-distance) if distance&gt;=1: return(0) incircle=0 for i in range(numdarts): x=(width*(random.random()))-width y=(random.random()) d=(x-distance)**2+(y-0)**2 d2=(x-(distance*-1))**2+(y-0)**2 if d&lt;=1 and d2&gt;=-1: incircle=incircle+1 pi=(incircle/numdarts)*(width*2) return pi main() </code></pre> this is what i should get- when distance = 0 about 3.14 when distance = .5 about 1.288 i am getting about 1.6 and .6 respectively why these are my instructions- write a program called that uses the monte carlo method to estimate the area of this shape (and prints the result). your program should take two command-line parameters: distance and numdarts. the distance parameter specifies how far away the circles are from the origin on the x-axis. so if distance is 0 then both circles are centered on the origin and completely overlap. if distance is 0.5 then one circle is centered at (-0.5 0) and the other at (0.5 0). if distance is 1 or greater then the circles do not overlap at all! in that last case your program can simply output 0. the numdarts parameter should specify the number of random points to pick in the monte carlo process. in this case the rectangle should be 2 units tall (with the top at y = 1 and the bottom at y = -1). you could also safely make the rectangle 2 units wide but this will generally be much bigger than necessary. instead you should figure out exactly how wide the shape is based on the distance parameter. that way you can use as skinny a rectangle as possible.,python
using python as the config language for a python program i d like to dynamically import various settings and configurations into my python program - what you d typically do with a .ini file or something similar. i started with json for the config file syntax then moved to yaml but really i d like to use python. it ll minimize the number of formats and allow me to use code in the config file which can be convenient. i hacked up an <code>__import__</code> based system to allow this using code that looks like: <pre><code>account_config = __import__(settings.config_dir + .account_name fromlist=[settings.config_dir]) </code></pre> it basically works but i m running into all kinds of esoteric problems - eg. if i try to import test it picks up some internal python library that s in the python path instead of my test. so i m wondering: is using python as the configuration language for a python program viable or am i asking for trouble are there examples i can steal from,python
็how to get vdo file from server i want to load a file from a server (e.g. <a href= rel= nofollow noreferrer ></a>) with my app and play it with <code>vdo mpmovieplayer</code>. however it uses <code>nsurlconnect</code> to connect to the url. how can i convert data of the type <code>nsdata</code> to <code>nsurl</code> for use in <code>vdo</code>,iphone
getting all child input elements within a div i am trying to get all the values of the input fields. the issue is all of the <code>&lt;input type=radio/&gt;</code> are dynamic and can increase or decrease at any time. so i am starting with the main di and going from there. the problem i have now is i am not getting the input radio buttons values. so here are the steps i am intending to accomplish: <ol> <li>if any radio button is selected pass its value to the checkbox value </li> <li>if the radio button is selected and the checkbox is not selected do <em>not</em> pass to the checkbox value </li> </ol> i am looking for a solution in javascript only - <strong>do not use jquery</strong> here is my <a href= rel= nofollow >jsfiddle code</a> <h3>html</h3> <pre><code>&lt;div style= display: block; id= mymaindiv class= fullfloat &gt; &lt;input type= hidden value= 1 id= startidxshmdecarwisevid name= startidxshmdecarwise &gt; &lt;div class= subtitle &gt;ups&lt;a class= fright onclick= localg( 10 false 0 false ups 1 $ ); href= javascript:void(0); &gt;show prices&lt;/a&gt;&lt;/div&gt; &lt;div style= display:none; id= wheel_ups &gt;&lt;div class= loadingcheckout &gt;&lt;/div&gt;&lt;/div&gt; &lt;div id= price_ups &gt; &lt;/div&gt; &lt;div class= wrapleft wrapclear &gt; &lt;div class= wrapleft &gt; &lt;label class= &gt; &lt;input type= radio value= 11098 id= deliverymethodid_1 name= deliverymethodid class= section data-mask= data-rev= data-rel= false data-carrier= &gt; &lt;span&gt; ups ground (order by 9:30 pm est) &lt;/span&gt; &lt;div class= wrapright &gt; &lt;div id= ups_11098 &gt; &lt;/div&gt; &lt;/div&gt; &lt;/label&gt; &lt;/div&gt; &lt;input type= text value= 1 id= ups &gt; &lt;/div&gt; &lt;input type= hidden value= 2 id= startidxshmdecarwisevid name= startidxshmdecarwise &gt; &lt;div class= subtitle &gt;standard&lt;a class= fright onclick= localg( 20 false 0 false standard 2 $ ); href= javascript:void(0); &gt;show prices&lt;/a&gt;&lt;/div&gt; &lt;div style= display:none; id= wheel_standard &gt;&lt;div class= loadingcheckout &gt;&lt;/div&gt;&lt;/div&gt; &lt;div id= price_standard &gt; &lt;/div&gt; &lt;div class= wrapleft wrapclear &gt; &lt;div class= wrapleft &gt; &lt;label class= &gt; &lt;input type= radio value= 11117 id= deliverymethodid_2 name= deliverymethodid class= section data-mask= data-rev= data-rel= false data-carrier= &gt; &lt;span&gt; standard delivery - 2-3 day delivery at ground rate (order by 9:30 pm est) &lt;/span&gt; &lt;div class= wrapright &gt; &lt;div id= standard_11117 &gt; &lt;/div&gt; &lt;/div&gt; &lt;/label&gt; &lt;/div&gt; &lt;input type= text value= 1 id= standard &gt; &lt;/div&gt; &lt;input type= hidden value= 3 id= startidxshmdecarwisevid name= startidxshmdecarwise &gt; &lt;div class= subtitle &gt;fedex&lt;a class= fright onclick= localg( 190 false 0 false fedex 3 $ ); href= javascript:void(0); &gt;show prices&lt;/a&gt;&lt;/div&gt; &lt;div style= display:none; id= wheel_fedex &gt;&lt;div class= loadingcheckout &gt;&lt;/div&gt;&lt;/div&gt; &lt;div id= price_fedex &gt; &lt;/div&gt; &lt;div class= wrapleft wrapclear &gt; &lt;div class= wrapleft &gt; &lt;label class= &gt; &lt;input type= radio value= 11088 id= deliverymethodid_3 name= deliverymethodid class= section data-mask= data-rev= data-rel= false data-carrier= &gt; &lt;span&gt; fedex ground (order by 8:00 pm est) &lt;/span&gt; &lt;div class= wrapright &gt; &lt;div id= fedex_11088 &gt; &lt;/div&gt; &lt;/div&gt; &lt;/label&gt; &lt;/div&gt; &lt;input type= text value= 1 id= fedex &gt; &lt;/div&gt; &lt;/div&gt; &lt;input type= checkbox name= shipmode id= shipmode value= onclick= getpref( mymaindiv ); &gt;get value </code></pre> <h3>js code</h3> this executes when the checkbox is clicked: <pre><code>function getpref(val) { var wr = document.getelementbyid(val); childelements = wr.childnodes; //alert(childelements); for(var i = childelements.length-1; i&gt;=0; i--){ var elem = childelements[i]; console.log(; if( &amp;&amp; _ )==0){ = block ; } } //alert(val); } </code></pre>,javascript
playing ipod library songs in audio queues not with mpmusicplayer controller i need to play songs from my music library in the background while playing video.. both audio and video will play at the same time... first i tried using mpmusicplayercontroller to play music but when i play video its stops playing song in background. after that i tried to play music using audiotoolbox. audio queues . now i can play audio and video at the same time but the song i am playing is static. i want to play song from ipod library and i need to provide the file path there so is there any way to get the library song path or any other idea please suggest..!,iphone
javascript for hiding dates i ve used a javascript for hiding concert dates on a website for a client. it works fine. now i wanted to reuse it for another site and copied it. but now it won t work and i can t find the error... the script i m using is the following and is stored in js/termine.js : <pre><code>// &lt;![cdata[ function aktualisieren() { if (!document.getelementsbytagname) return; var datum = new date(); var jahr = datum.getfullyear().tostring(); var monat = (datum.getmonth()+1).tostring(); if (monat.length == 1) monat = 0 + monat; var tag = datum.getdate().tostring(); if (tag.length == 1) tag = 0 + tag; var aktuell = parseint(jahr + monat + tag); var zeilen = document.getelementsbytagname( div ); for (var i = 0; i &lt; zeilen.length; i++) { if (zeilen[i].title) { if (parseint(zeilen[i].title) &lt; aktuell) zeilen[i].style.display = none ; } } } // ]]&gt; </code></pre> in the html-head i m linking to that file via: <pre><code>&lt;script src= js/termine.js &gt;&lt;/script&gt; </code></pre> the dates are stored in which i m including via php: <pre><code>&lt;div id= termine &gt;&lt; php include( includes/ ); &gt;&lt;/div&gt; </code></pre> can somebody give me a hint what i m missing thanks a lot!,javascript
java inheritance classes with main method i have 2 objects defined in object-1 when i reference the child object it invokes the child method m1() whereas in object-2 when i reference the child method m1() it references the parent object.. in both the cases i assume parent object will hold a child type object at runtime... object-1 <pre><code> package pkgb; class parent{ static int i = 10; void m1(){ system.out.println( in parent = + i); } static void m1(string s){ system.out.println(s +i ); } } public class child extends parent{ static int i = 20; void m1(){ system.out.println( in child + child.i); } public static void main(string[] args){ parent p = new child(); p.m1(); } } </code></pre> object-2 <pre><code>package pkgb; class drink{ public static void m1(){ system.out.println( im drink method ); } } class coffee extends drink{ public static void m1(){ system.out.println( im coffee method ); } } public class test { public static void main(string[] args) { drink d = new coffee(); d.m1(); } } </code></pre> output dobject-1: <pre><code>in child20 </code></pre> output dobject-2: <pre><code>im drink method </code></pre>,java
scribble maps set map options latitude longituude i m trying to set map options latitude and longitude to scribble maps. i m sure it can be done the same way as google maps but can t find more info in the documentation. this is my code : <pre><code>jquery(document).ready(function(){ var sm = new scribblemaps.scribblemap(document.getelementbyid( scribblemap )); }); </code></pre>,javascript
smart way of converting dictionary to key=value connection string in python i have always changing connection strings with a variable number of keys such as port timeout etc etc. i store these in a dictionary because i like to use that and it feels natural but what i would like to do is convert something which looks like: <pre><code>{ host : localhost user : postgres password : xx database : test socket_timeout :9999 ssl :false port :5432} </code></pre> into something i can insert in place of this: <pre><code>conn = dbapi.connect(host=str(dbsettings[ host ]) user=(dbsettings[ user ]) password=str(dbsettings[ password ]) database=str(dbsettings[ database ]) ssl=dbsettings[ ssl ] port=dbsettings[ port ]) </code></pre> i can build a string a process with the following: <pre><code>m = [str(k) + = + str(v) for k v in dbsettings.items()] </code></pre> but this feels like i m not getting ahead. how can i retain the k as the keyword and v as the string and build a series of relations.,python
javascript oop concept issue i have this simple code : <pre><code>// you can use either pixi.webglrenderer or pixi.canvasrenderer var renderer; var stage; var bunnytexture; var bunny; var game= {}; game.init = function() { }; game.init.prototype={ init:function(){ renderer= new pixi.webglrenderer(800 600); document.body.appendchild(renderer.view); stage= new pixi.stage; bunnytexture= pixi.texture.fromimage( img/ninja.png ); bunny= new pixi.sprite(bunnytexture); bunny.position.x = 400; bunny.position.y = 300; stage.addchild(bunny); } animate:function(){ bunny.rotation += 0.01; renderer.render(stage); requestanimationframe(this.animate); } } requestanimationframe(game.init.animate); </code></pre> i am calling the function like this : <pre><code> window.onload = function () { game.init(); }; </code></pre> a javascript error saying : <code>argument 1 of window.requestanimationframe is not an object.</code>,javascript
how to count specified word occurrence in multiple elements i have some amount of elements with class of shoutbox_text how cani count specified word occurrence in all of them (inner html of them is just plain text there isn t anymore tags inside.),javascript
making an on/off button with images i have two images sound_on.png and sound_off.png. both have the same height and dimensions. i would like to attach a javascript for the following action: <ol> <li>when the pressed images changes from sound_off.png to sound_on.png and the sound plays</li> <li>when the button is pressed again it changes back from sound_on.png to sound_off.png and the sound stops with the onclick command</li> </ol> at the moment i have these lines of code: <pre><code>&lt;a href= # onclick= playaudio(); &gt;&lt;img src= images/general/sound-on.png width= 40 height= 32 &gt;&lt;/a&gt; &lt;a href= # onclick= stopaudio(); &gt;&lt;img src= images/general/sound-off.png width= 40 height= 32 &gt;&lt;/a&gt; </code></pre> what code do i need to make them like the above example i have this part: <pre><code>&lt;style type= text/css &gt; .on {background-image:url url(images/general/sound-off.png)); background-repeat:no-repeat;} .off {background-image:url(images/general/sound-on.png); background-repeat:no-repeat;} &lt;/style&gt; &lt;script language= javascript &gt; function togglestyle(el){if(el.classname == on ) {el.classname= off ;} else {el.classname= on ;}} &lt;/script&gt; </code></pre> with this div for the button: <pre><code>div id= onoff class= playlist_btn &gt;&lt;img src= images/general/sound-off.png width= 50 height= 50 onclick= togglestyle(onoff) &gt;&lt;/div&gt; </code></pre> this makes the toggle but i have no idea so far how to connect the onclick command to get the audio playing and to stop it again. could it be something like this <pre><code>function togglestyle(el){if(el.classname == on onclick= playaudio() ) {el.classname= off onclick stopaudio() ;} else {el.classname= on ;}} </code></pre>,javascript
iphone app crashes on device file not found i see this error unable to read symbols for /developer/platforms/iphoneos.platform/devicesupport/4.3.2 (8h7)/symbols/developer/usr/lib/libxcodedebuggersupport.dylib (file not found). i ve tried this <a href= >solution</a> but it didn t work. can someone help me how to fix this issue.,iphone
want to know the exact size of a data contend in any specified url hi all i want to know that while specifying url in my iphone native application for downloading purpose it works fine but if i want to know the exact size of data either in kb or in mb coming from that url how could i do that plz guide me to do that demonstarting a sample code would be a big boost thanks,iphone
ways to get to know of key names inside a javascript object literal declare a javascript object literal <pre><code>var obja = { keya : vala } </code></pre> in the console <pre><code>obja &gt; object {keya: vala } </code></pre> the object is not an array <pre><code>obja[0] &gt; undefined </code></pre> the only way i know to get key names is to cicle on the object <pre><code>for (x in obja) { console.log(x); } &gt; keya </code></pre> do you know any other ways to get key names from object,javascript
uibutton delayed state change i have a <code>uibutton</code> subview inside of a <code>uitableviewcell</code>. when this button is touched the user must hold the button for about a half second for the button s image to change to the <code>uicontrolstatehighlighted</code> image. this means that if the user just taps the button as is usually the case the highlighted state is never shown. why does this occur and how can i fix it,iphone
create a simple gui for a minimalistic python script i wrote a small python function which takes several numerical input parameters and prints many lines with statements which going to be used in an experiment like this toy example: <pre><code> def myadd(x y z): res = x + y + z print( the result is: {0}+{1}+{2}={3} ).format(x y z res) </code></pre> i would like to create a minimalistic gui simply an overlay which calls my script where i can fill those parameters x y z and after clicking a compute button a text field occurs with the print statement. does anyone has a template i was looking into the tkinter but my attempts by manipulating other templates didn t succeed. would appreciate help thanks.,python
how to copy a specific field from a list of any classes in java let s me start describe my problem. i have a class person which is stored in mpeople list. so it does mean that the mpeople will store both name and age . but in a certain circumstance i need a list of all people s name and a list of all people s age in different list. so is there a way to copy all the data in a specific field of a class in a list to another list or somewhere else <em>note: i know i can use for loop or enhance for loop to do this but it does not look so good through this. so just curious if someone found any better solutions... and i would appreciate your help!</em> <pre><code>public class person { // fields private int age; private string name; // constructor public person( int age string name ) { this.age = age; = name; } // getter public int getage() { return age; } public string getname() { return name; } } //list of people list&lt;person&gt; mpeople = new arraylist&lt;&gt;(); mpeople.add( new person( 10 sovanara ) ); mpeople.add( new person( 20 dara ) ); </code></pre>,java
how can a class know that its super class is object i have a java class samplea . how come samplea know that its super class is object here are my answers <ol> <li> during development the configuration of jre in eclipse will automatically say that each class has super class as object </li> <li> during deployment the class loaders take the responsibility of saying that super class is object . </li> </ol> please correct me.,java
a proper way to make an hashmap with multiple value type i have an object the represent an entity. by example i have the user java object that have the followings field string name string first name string address boolean deadoralive. but now instead of having field i want to put them into a hashmap so my first reflex was to make it this way : <pre><code>private hashmap&lt;string object&gt; fieldshm; </code></pre> this would means that i have to cast my hm value when i want to use it and i don t want to make that because i need to know the type before i use my value. i want to make something like : <pre><code>set&lt;string&gt; keys = fieldshm.keyset(); for(string key : keys) { if(fieldshm.get(key).isboolean()) { // do the appropriate things } else { // do the thing for this case... } } </code></pre> i think it s possible in java would this be good to do it this way edit 1: i don t want to make a hashmap because this is not what i need. what i need is a way to browse the fields of the entity user fields by fields and depending the type of the field do the appropriate things.,java
why cant i use an iterator this way <pre><code>iterator&lt;string&gt; iterator=... //right way for (iterator&lt;string&gt; i = iterator; i.hasnext(); ){ system.out.println(; } //why can t for(string i:iterator){ } </code></pre> <strong>reference:</strong> <a href= rel= nofollow ></a> <a href= rel= nofollow ></a>,java
iphone: objc_class_name_tttabstrip symbol not found build error i am trying to implement scrollview effect in tabbar which has tabitems . i found that the good example is from facebook open source ttcatlog project tabs section. so i included all the source from it to my project and trying to build it. i have followed the following links to go ahead on this: <a href= >how to create a horizontal scrolling view on iphone </a> source: <a href= rel= nofollow noreferrer ></a> my calling code is like below: <pre><code>_tabbar1 = [[tttabstrip alloc] initwithframe:cgrectmake(10 68 300 28)]; _tabbar1.tabitems = [nsarray arraywithobjects: [[[tttabitem alloc] initwithtitle:@ item 1 ] autorelease] [[[tttabitem alloc] initwithtitle:@ item 2 ] autorelease] [[[tttabitem alloc] initwithtitle:@ item 3 ] autorelease] [[[tttabitem alloc] initwithtitle:@ item 4 ] autorelease] [[[tttabitem alloc] initwithtitle:@ item 5 ] autorelease] [[[tttabitem alloc] initwithtitle:@ item 6 ] autorelease] [[[tttabitem alloc] initwithtitle:@ item 7 ] autorelease] [[[tttabitem alloc] initwithtitle:@ item 8 ] autorelease] [[[tttabitem alloc] initwithtitle:@ item 9 ] autorelease] [[[tttabitem alloc] initwithtitle:@ item 10 ] autorelease] nil]; [self.navigationcontroller.view addsubview:_tabbar1]; </code></pre> my project folder as like below: ..../iphone/myprogram/myprogram.xcodeproj ..../iphone/three20/src/three20.... in my project settings for header search path i have ../three20/src but when i try to build it it throws the following error: objc_class_name_tttabstrip symbol not found objc_class_name_tttabitem symbol not found i see there all these files (.h and .m) are availbale there. could someone please help what s wrong there and how do i get rid of this issue and continue working with it,iphone
colon in javascript callback i m using the data layer on google maps with point geometries that occasionally use the same coordinates. to access all of the features at a given coordinate i m trying to use a port of overlappingmarkerspiderfier for the data layer instead of markers called <a href= rel= nofollow >overlappingfeaturespiderfier</a>. i m have problems adding the click handler for the data layer. in the documentation it calls for: <pre><code>ofs.addlistener( click function(event: { var thefeaturethatwasclicked = event.feature; } </code></pre> besides the missing parenthesis i can t figure out what s going on with that colon in the callback. any ideas,javascript
dynamically add instance variables via decorator to a class in python i want to instrument a class via a decorator to add some <strong>instance</strong> variables that are specified by the author of the class. i started with the following code but this just adds <strong>class</strong> variables and i want <strong>instance</strong> variables (those that are normally declared in __ init __) what is a pythonic way to do this while allowing the class author control over what they put in __ init __ <pre><code>def add_list_attributes(klass): for attribute in klass.list_attributes: setattr(klass attribute []) return klass @add_list_attributes class person(object): list_attributes = [ phone_numbers ] def __init__(self): pass p1 = person() p1.phone_numbers.append( 01234 ) print p1.phone_numbers </code></pre>,python
iphone skips over non-text form fields when using an iphone to fill out a form i hit the next button on top of the keyboard to navigate from one field to the next. non-text fields such as lookup and radio are skipped right over to the next text field. a dropdown field however can be accessed with next/previous. how to prevent this from happening any suggestions,iphone
how can i return the else statement in function in javascript it gives unexpected token else <pre><code>var sleepcheck = function (numhours) { if (sleepcheck &gt;= 8); return you re getting plenty of sleep! maybe even too much! ; else (sleepcheck &lt; 8); return get some more shut eye! ; }; sleepcheck(10); sleepcheck(5); sleepcheck(8); </code></pre>,javascript
how should i manage constants in a java project usually we manage constants in interfaces. e.g.: <pre><code>public interface commonconstant { int a_type1=0; int a_type2=1; } </code></pre> but i m thinking that if the constant belongs to a class we may just put it into that class e.g.: <pre><code>public class a { public enum type { type_one(0) type_two(1); public final int val; type(int val) { this.val = val; } } private int type; ... } </code></pre> so which way should be better,java
pattern/function finding program in python i am looking for a program in python that can find a pattern or a function for a list of numbers. for example if the input was <code>2 4 6</code> the program would output something like <code>f = 2n</code>. but the program must be able to handle very very complicated and extremely long inputs. does anyone know of any such program,python
is it possible to call a method of an object while passing that object into a function say i have a method <code>foo createfoo()</code>. i need to call the method <code>boolean</code> on the object returned by <code>foo createfoo()</code> then pass the object into a method <code>void baz(foo somefoo)</code>. is there a way to do this in one line if i didn t need to call <code>boolean</code> i could have done <pre><code>baz(createfoo()); </code></pre> but i can t do this because it doesn t call i also can t do this: <pre><code>baz(createfoo().bar()); </code></pre> because that would pass into baz the boolean returned from <code></code> not the actual foo object.,java
.pls file parsing iam creating and radio application in which i have to check the authentication and after successful login i get .pls file in which there is actual url which has to be played so anybody know how to parse .pls file and get the url inside the .pls file.,iphone
splitting the comma separated string and adding it into the list i have the below method which will return string. <pre><code> private string getexpectedlist() { return expectedslist; } </code></pre> so i am storing it in string like as shown below <pre><code>string t = this.getexpectedlist(); </code></pre> upon debugging i found that method inside t the string is like comma separated as shown below <pre><code>system.out.println(t); </code></pre> i was thinking to design a method which will take the string and then split each of them and finally add it in list and the list will be of type string so finally a method of which return type is list so i have designed a list <pre><code> list&lt;string&gt; holdvalues = new list&lt;string&gt;(); </code></pre> how can i design such a method as mentioned above,java
private api in mpmovieplayercontroller can we use private method in mpmovieplayercontroller e.g: -(void)setorientation:(int)orientation animated:(bool)value; for playing movie in portrait mode. did apple approve private api,iphone
the itunesartwork image: is this needed every time or just in ad-hoc distribution cases i am not surfe if i really need every time this 512 x 512 pixel icon since i don t plan to use ad-hoc distribution. if i get it right ad-hoc distribution is the case when you make an app that is supposed to go only on a very few company iphones and you dont want anyone to get that app. if that s true i choose the other distribution type where anyone can get the app. would i need that image in that case,iphone
how to do generic copy constructor in java could you please advise or give some hints how to do following. i have pojo lets say it is called bankhistorydata. i would like to copy data from two tables into this pojo (main table - bank and its archive - bankarchive). tables have a lot of fields which are basiclly the same so i would not like to repeat my self.<br> i googled around and found a tool that could help me with this - java generic constructor. but i am a little bit new with generics and not sure how exactly to do it.<br> i suppose i should have something like this: <pre><code>public class bankhistorydata&lt;t extends serializable&gt; { // i would like to set this fields from the object t private field1; private field2; // and many more ... t a; // source object from which to copy values public bankhistorydata(t a) { this.a = a; copydata(); } // not sure about this ... something like this public void copydata() { if(t instanceof bank) { this.field1 = ((bank)a).getsomefield(); // and so on ... } else if (t instanceof bankarchive) { this.field1 = ((bankarchive)a).getsomefield(); // and so on ... } else { trow new illegalargumentexception( not supported table ); } } } </code></pre> any suggestions are welcome. thanks! mismas [edit] i have decided not to use generic for this as i think those 2 cents from @alex where for that. instead i will do this copy logic in my business logic service layer (pojo will remain stupid ).<br> although i will make those two hibernate objects to implement common interface (only getter methods of shared fields will be here). and finally i will make a copy method on my business logic service layer and make it to take that interface parameter for copying fields.<br> hope this will help someone. also any comments are welcome.<br> cheers!,java
do while loop not working (cannot find variable) i am having trouble with my do while loop not finding my variable to test if the condition is true or not. here is my code: <pre><code>import java.util.scanner; public class loops { public static void main(string[] args){ system.out.println( programmer: jarred sylvester ); system.out.println( course: cosc 111 winter 2016 ); system.out.println( lab#: 5 ); system.out.println( due date: feb. 18 2016 ); scanner prompt = new scanner(; do{ system.out.print( \nenter a whole number: ); int num = prompt.nextint(); if(num % 2 == 0){ system.out.println(num + is even ); } else{ system.out.println(num + is odd ); } system.out.println( \nnumbers from 1 through +num+ are: ); for(int counter = 1; counter &lt;= num; counter++){ system.out.print(counter + ); } int counter = 1; system.out.println( \n\nsquare of odd numbers from 1 through + num + are: ); while(counter &lt;= num){ if(counter % 2 ==1){ system.out.print((counter * counter)+ ); } counter++; } counter = 1;int sum =0; system.out.println( \n\nsum of even numbers from 1 through +num+ is: ); while(counter &lt;= num){ if(counter % 2 == 0){ sum+=counter; } counter++; } system.out.print(sum); system.out.println( \n\nnumbers from 1 through +num+ (5 numbers per line): ); for(int count = 1; count &lt;= num; count++){ system.out.print(count + ); if(count % 5 == 0){ system.out.print( \n ); } } system.out.println( \n\ndo it again yes(or no) ); string play =; }while(play.equalsignorecase( yes )); } </code></pre> } the variable play at the end isn t being tested. am i out of scope or something i ve looked everywhere for an answer but cannot seem to find a solution to my error. thank you.,java
how to print word from from string without digit and without using arrays in java input : hi ma name is jack &amp; i am 23 years # thanks output :hi ma name is jack i am years thanks,java
urlclassloader case classnotfoundexception when classname is pass by parameter when i use urlclassloader to loader class the follow code is ok <pre><code> class c1 = classloader.loadclass( ); for(method m: c1.getdeclaredmethods()){ system.out.println(m.getname()); } </code></pre> but when i do this way it throws classnotfoundexception <pre><code>class c = classloader.loadclass(string.format( servletname)); </code></pre> why the full code of function is : <pre><code>public void process(request request response response) throws servletexception ioexception { string uri = request.geturi(); string servletname = uri.substring(uri.lastindexof( / ) + 1); string path = servletprocessor1.class.getresource( / ).tostring(); url classurl; urlclassloader classloader = null; try { classurl = new url(path+ jjzhu/study/tomcat/servlet ); system.out.println(path+ jjzhu/study/tomcat/servlet ); url[] classurls = {classurl}; classloader = new urlclassloader(classurls); // this is ok! class c1 = classloader.loadclass( ); for(method m: c1.getdeclaredmethods()){ system.out.println(m.getname()); } // but this failed class c = classloader.loadclass(string.format( servletname)); for(method m: c.getdeclaredmethods()){ system.out.println(m.getname()); } servlet servlet = (servlet)c.newinstance(); servlet.service(request response); } catch (classnotfoundexception e) { e.printstacktrace(); } catch (illegalaccessexception e) { e.printstacktrace(); } catch (instantiationexception e) { e.printstacktrace(); } } </code></pre> the exception: <pre><code>init destroy service getservletconfig getservletinfo java.lang.classnotfoundexception: at at java.lang.classloader.loadclass( at java.lang.classloader.loadclass( at at at </code></pre>,java
javascript: parsing a number with multiplication by 1.0 is it safe to parse a number from a string like this <pre><code>rate *= 1.0; straf.setdelay((rate+1)*1000); </code></pre> <code>rate</code> is a string which contains only 1 number.,javascript
how to group strings by sequential occurrence and check for values > x in another column for the following data structure i would like to use python to find the number of sequential occurrences of a pattern in column c0 >= than a threshold x and the number of corresponding values in another column prcc0 that are >= than a threshold y for the example below if thresholds x = 3 and y is 40 then the algorithm should output. rows 2:4 for string pattern b occurring >= 3 and corresponding prcc0 values >= 40 the algorithm should scan the entire data frame for such sequential patterns. <pre><code>seq nmin nuniqe n3wj prc3wj c0 prcc0 0 s00000 482 9 172 35.68 a 1.65 1 s00001 503 10 193 38.37 a 15.33 2 s00002 415 9 221 53.25 b 44.03 3 s00003 325 10 155 47.69 b 42.99 4 s00004 429 10 175 40.79 b 43.37 </code></pre>,python
iphone:storyboard issue with default labels i created views using storyboard. in one of the view controller i added a tableview as its the easy way of doing in storyboard. i am seeing two labels in each cell by default. i want to customize it now i don t want these two labels here and i want to add some image view textfield etc. the problem now is i am not able to remove this default two labels from cell. can someone guide me also please share me the apple official link where i can learn about storyboard and complete usage. thank you in advance!,iphone
run a function on first time page load not on page refresh in javascript i would like a function to be executed only on the first page load and not when page is refreshed. for example it should not execute when the user clicks on the submit button or on other page refresh. i can avoid it in .net by using the <code>ispostback</code> property but how can i do this in javascript,javascript
python: break while loop i am using a code that takes an input of image files (can be any number in the source folder) and processes them and then saves the files. i am using a <code>while loop</code> to save the files. but the problem i am facing is that once the loop processes all the images and saves them it starts all over again. how can i break the loop once all the images in the source folder have been processed and saved the code i am using is: <pre><code># construct the argument parse and parse the arguments ap = argparse.argumentparser() ap.add_argument( -i --images required=true help= path to images directory ) args = vars(ap.parse_args()) # initialize the hog descriptor/person detector hog = cv2.hogdescriptor() hog.setsvmdetector(cv2.hogdescriptor_getdefaultpeopledetector()) # loop over the image paths imagepaths = list(paths.list_images(args[ images ])) #open images in a sequence imagepaths.sort() i =1 while true: for imagepath in imagepaths: # load the image and resize it to (1) reduce detection time # and (2) improve detection accuracy image = cv2.imread(imagepath) image = imutils.resize(image width=min(700 image.shape[1])) orig = image.copy() # detect people in the image (rects weights) = hog.detectmultiscale(image winstride=(4 4) padding=(8 8) scale=1.05) # draw the original bounding boxes for (x y w h) in rects: cv2.rectangle(orig (x y) (x + w y + h) (0 0 255) 2) # apply non-maxima suppression to the bounding boxes using a # fairly large overlap threshold to try to maintain overlapping # boxes that are still people rects = np.array([[x y x + w y + h] for (x y w h) in rects]) pick = non_max_suppression(rects probs=none overlapthresh=0.65) # draw the final bounding boxes for (xa ya xb yb) in pick: cv2.rectangle(image (xa ya) (xb yb) (0 255 0) 2) # show some information on the number of bounding boxes filename = imagepath[imagepath.rfind( / ) + 1:] print( [info] {}: {} original boxes {} after suppression .format( filename len(rects) len(pick))) cv2.imwrite( %d.png % (i) image) i +=1 </code></pre>,python
finding number of changes to make 2 strings anagram i want to find the minimum number of characters of the first string that needs to be changed to enable me to make it an anagram of the second string. 1st problem it always return -1 <pre><code>function anagram(s) { if (s % 2 == 0) { var len = s.legnth; var diff = []; for (var x = 0; x &lt; len / 2; x++) { var y = s[x]++; } for (var x = len / 2; x &lt; s.legnth; x++) { var z = s[x]++; } y = y.sort().splice( ).tostring(); z = y.sort().splice( ).tostring(); for (var x = 0; i &lt; z.length; x++) { if (y[x] != z[x]) { diff.push(y[x]); } } return diff.length; } else { return -1; } } function main() { var q = parseint(readline()); for (var a0 = 0; a0 &lt; q; a0++) { var s = readline(); var result = anagram(s); process.stdout.write( + result + \n ); } } </code></pre>,javascript
superinterface in java what is super-interface is java what is the purpose of super-interface,java
create a new class and load some copies of it into the view ok i made a small application with a small ball bouncing on the screen. that was esay. now i d like to have more than one ball... so i think the best way is to create a new class : the ball. how can i do it thanks!,iphone
iphone app - show phone pad above the tabbar i am working on iphone app that has tab bar at the bottom of the screen. i need to show phone pad like the apple iphone s default phonepad when making call above the tab bar. how can i do it if it is not possible do i need images for each number to style them to look like iphone phonepad or this can be done by changing background color etc of the buttons,iphone
is it able to create folders with python i am writing a pokemon game and i want to make folders to save different types of pokemon as well as other sorts of information in. i want to use folders because it would be really messy if i were to save all my data into a single file. is it possible to create folders with a python program this would make it easier and cleaner for me when i try to import the pokemon data from external websites.,python
standard default first argument to pass to fn.apply i have recently learned about the magic of <code>fn.apply()</code> in javascript and i am using it to save function calls with all their arguments intact and call them at a later date. however in my use case i do not need the first argument the context (<code>this</code>) and i d like to avoid passing the <code>this</code> object into it somehow in order to make it clear in my code that i m not using <code>.apply()</code> for that. my first thought was passing in <code>null</code> but i read the following on <a href= rel= nofollow >mdn</a>: <blockquote> if the method is a function in non-strict mode code <code>null</code> and <code>undefined</code> will be replaced with the global object and primitive values will be boxed. </blockquote> this seems to imply that passing <code>null</code> or even <code>false</code> is bad practice. what would be an appropriately falsy empty or otherwise obviously placeholder value to put into <code>fn.apply()</code> s first argument,javascript
match divs by id and delete content inside that i have couple of divs like <pre><code>&lt;div id= rg_dia_0 &gt; zdszczxvzxvzxvc &lt;/div&gt; &lt;div id= rg_dia_1 &gt; dfgdzxczc &lt;/div&gt; &lt;div id= rg_dia_2 &gt; hfhgjhgjdj &lt;/div&gt; </code></pre> i need javascript to fetch all the divs and delete the content. i think we can use regex to match the ids as only the number that is changing.,javascript
learn python the hard way exercise 35 boolean expression i am wondering how the lines <pre><code>elif choice == taunt bear and not bear_moved: print the bear has moved from the door. you can go through it now. bear_moved = true </code></pre> ... and ... <pre><code>elif choice == taunt bear and bear_moved: dead( the bear gets pissed off and chews your leg off. ) </code></pre> ... implement the variable <code>bear_moved</code> it is already defined as <code>false</code> before the <code>while</code> loop and i am wondering why it is compared to what is entered in choice and how it checks it when you are just typing your answer. also if it says <code>not</code> <code>bear_moved</code> doesn t that make the variable true then why is it defined as true under it <pre><code>def bear_room(): print there is a bear here. print the bear has a bunch of honey. print the fat bear is in front of another door. print how are you going to move the bear bear_moved = false while true: choice = raw_input( &gt; ) if choice == take honey : dead( the bear looks at you then slaps your face off. ) elif choice == taunt bear and not bear_moved: print the bear has moved from the door. you can go through it now. bear_moved = true elif choice == taunt bear and bear_moved: dead( the bear gets pissed off and chews your leg off. ) elif choice == open door and bear_moved: gold_room() else: print i got no idea what that means. </code></pre>,python
how handle error in nspredicate when i try to match regular expression for data . sometime application crashes with error here is error description can t do regex matching reason: can t open pattern u_regex_invalid_range (string ertyu pattern [a-z] case 0 canon 0) here is my code <pre><code> - (bool)isvalidatestring:(nsstring *)instring forre:(nsstring *)inre { bool isvalidate=no; nspredicate *thepredicate= [nspredicate predicatewithformat:@ self matches %@ inre]; isvalidate= [thepredicate evaluatewithobject:instring]; return isvalidate; </code></pre> } and in this method re is getting from server.,iphone
why is my compiler giving me these two errors in java i m writing a code in java and i keep getting two errors from the compiler saying cannot find symbol. here is my code and the errors. <pre><code>public complexnumber(float a float b){ a = real; b = imaginary; } </code></pre> here are the two errors. <pre><code> error: cannot find symbol a = real; ^ symbol: variable real location: class complexnumber error: cannot find symbol b = imaginary; ^ symbol: variable imaginary location: class complexnumber 2 errors </code></pre> any advice is greatly appreciated. thanks in advance!,java
why foo .tostring() is not the same as foo ) here is a question in javascript below: <pre><code>// tested via google chrome console. var tostring = object.prototype.tostring; foo .tostring(); // foo foo ); // [object string] [].tostring(); //[]); // [object array] {}.tostring(); // syntax error{}); // [object object] </code></pre> why the result of tostring is different with <strong>updated</strong> <pre><code> foo ); // foo foo ); // [object string] </code></pre> is string.prototype.tostring not from the prototype chain like below <blockquote> tostring in string[not found] --> tostring in string.prototype[not found] <pre><code> --&gt; tostring in object.prototype[found] </code></pre> </blockquote>,javascript
webservice in iphone <blockquote> <strong>possible duplicate:</strong><br> <a href= >how to use webservice in iphone objective c </a> </blockquote> how to call webservice in iphone,iphone
how to convert ascii to hex in python how to convert ascii to hex in python i have one file need to read . but use below code it only can show ascii <pre><code>with open( hello.dat rb ) as f: data= print(data) </code></pre> it can print data in this format: <blockquote> 01201602180000020000000007000000000054000000000000\x0 </blockquote> how do i to convert this data to hex values like this: <blockquote> 30 31 32 30 31 36 30 32 31 38 30 30 30 30 30 32 30 30 30 30 30 30 30 30 30 37 30 30 30 30 30 30 30 30 30 30 35 34 30 30 30 30 30 30 30 30 30 30 30 30 5c 78 30 </blockquote>,python
passing two variables to one javascript function i have completed if i pass a variable <code>id</code> but now i want to pass <code>name</code> to the same function when i click on a image. this is my code: <pre><code> for (var i = 0; i &lt;friend_data.length; i++) { results += &lt;div class = clicker id = +friend_data[i].id+ onclick= javascript:testid( + friend_data[i].name+ ) &gt;&lt;img src= + friend_data[i].id + /picture height= 30 width= 30 &gt; + friend_data[i].name + &lt;/div&gt; ; } </code></pre> and <pre><code>function testid(id friend_data[id].name ){ alert(id); alert(friend_data[i].name); } </code></pre> the <code>alert(friend_data[i].name);</code> does not show because it s wrong. please help me to correct it. please look in even <code>onclick</code> it s the right ways to pass variable,javascript
javascript: adding ten integer variables and getting wrong totals i m building a simple order form with ten items. the user enters a number in one or more of the quantity fields. on onchange the script is supposed to add up the entries and multiply by the price. easy right if the user enters 1 for the tenth item the code works perfectly. but if he enters 1 on the ninth item the code generates 10 instead of 1. and on the eighth 1 entered gets a value of 100 and so forth. working on it for six hours and can t seem to find the problem. i have the code i d be happy to supply. help! update: got help to figure it out. added to comment below,javascript
escaping two lists in python so basically i have a really typical issue i found some solutions from stackoverflow before but this didn t really help me. i have a school task which requires me to analyze bobsleigh team. i have names their rating and weight in three separate lists and i need to pick four competitors with best ratings and their weight combined must not be over 325 kg. what i ve already done is i ve created a <code>for</code> cycle which picks out four competitors with highest rating but the issue is that they may have high ratings but their weight combined is over 325 kg. for example i have three lists: <pre><code>[ name1 name2 name3 name4 name5 name6 name7 name8 ] ## names [1 2 3 4 5 6 7 8] ##ratings [50 60 70 80 90 100 110 120] ##weights </code></pre> what i get is <code>[5 6 7 8]</code> (and every single one of them has a according weight list and name list for example for rating 5 goes competitor with weight of 90 kg and name is name 5) but their weight combined is higher than 325kg (90+100+110+120 > 325) i ve done coding so far that the minimal element (5) is removed and replaced by another lower element but the issue occurs (by issue i mean i don t know how to do it) when switching the last element is not enough and i need to try to replace element 6 and keep the element 5 in place. right now the code for switching is: <pre><code>while (kaalude_summa &gt; 325): #if weight is over 325 kg positsioon = reiting.index(max(reiting)) #position for max rating if kaalud[positsioon] &lt; kaalude_tulemused[3]: #two lists - one is for elements not in the resulting list (kaalud) and one is for the elements in resulting list (kaalude_tulemused) kaalude_tulemused[3] = kaalud[positsioon] #sets new weight in result list tulemuslist.remove(min(tulemuslist)) #removes number 5 from example list [5 6 7 8] (check above) tulemuslist.append(max(reiting)) #adds number 4 from example list kaalude_summa = kaalude_summa - vahekaal + kaalude_tulemused[3] #new calculated weight reiting.remove(max(reiting)) #removes element from list [1 2 3 4] kaalud.remove(kaalud[positsioon]) </code></pre> this works as long as the competitors with rating 1 2 3 or 4 weight + other three weights (6 7 8) isn t bigger than 325. i understand this could be done somehow with two for loops but i tried three times and failed miserably. it is compulsory to write code in estonian in our school so i apologize for not writing in english. i really hope that what i wrote is readable and you are able to help me. thank you in advance.,python
simple coding problems in the country of rahmania the cost of mailing a letter is 40 sinas for letters up to 30 grams. between 30 g and 50 g it is 55 sinas. between 50 g and 100 g it is 70 sinas. over 100 g it costs 70 sinas plus an additional 25 sinas for each additional 50 g (or part thereof). for example 101 grams would cost 70 + 25 = 95 sinas. 149 g would also cost 95 sinas because both of these packages only use the first 50 g over 100 g. write a program that prompts the user for a mass and then gives the cost of mailing a letter having that mass. this is the question and the only part i don t know how to do is the last part with the additional 25 sinas for each additional 50g. can someone show me how to write this part of the code i use netbeans btw. <pre><code>scanner input = new scanner(; double l; l = input.nextint(); x = l &gt;= 100 / 50 * 25 + 70; if (l &lt;= 30) { system.out.println( 40 sinas ); } if (l &gt; 30 &amp;&amp; l &lt; 50) { system.out.println( 55 sinas ); } if (l &gt; 50 &amp;&amp; l &lt; 100) { system.out.println( 70 sinas ); } if (l &gt;= 100) { system.out.println( ); } </code></pre> here s the important part of the code. as you can see i need help on the last part.,java
why is my iphone application crashing my application get crashing. it s loading data of all the cities and when i click its displaying my detailed view controller. when i am getting back from my controller and selecting another city my application get crashed. i am pasting my code. <pre><code>#import citynameviewcontroller.h #import cities.h #import xmlparser.h #import partytemperature_appdelegate.h #import cityeventviewcontroller.h @implementation citynameviewcontroller //@synthesize acities; @synthesize appdelegate; @synthesize currentindex; @synthesize acities; /* // the designated initializer. override if you create the controller programmatically and want to perform customization that is not appropriate for viewdidload. - (id)initwithnibname:(nsstring *)nibnameornil bundle:(nsbundle *)nibbundleornil { if ((self = [super initwithnibname:nibnameornil bundle:nibbundleornil])) { // custom initialization } return self; } */ // implement viewdidload to do additional setup after loading the view typically from a nib. - (void)viewdidload { [super viewdidload]; self.title=@ cities ; appdelegate=(partytemperature_appdelegate *)[[uiapplication sharedapplication]delegate]; } /* // override to allow orientations other than the default portrait orientation. - (bool)shouldautorotatetointerfaceorientation:(uiinterfaceorientation)interfaceorientation { // return yes for supported orientations return (interfaceorientation == uiinterfaceorientationportrait); } */ - (nsinteger)numberofsectionsintableview:(uitableview *)tableview { // return the number of sections. return 1; } - (nsinteger)tableview:(uitableview *)tableview numberofrowsinsection:(nsinteger)section { // return the number of rows in the section. return [appdelegate.citylistarray count]; } - (cgfloat)tableview:(uitableview *)tableview heightforrowatindexpath:(nsindexpath *)indexpath { return 95.0f; } - (void)tableview:(uitableview *)tableview willdisplaycell:(uitableviewcell *)cell forrowatindexpath:(nsindexpath *)indexpath { cell.accessorytype=uitableviewcellaccessorydisclosureindicator; cell.textlabel.textcolor = [[[uicolor alloc] initwithred:0.2 green:0.2 blue:0.6 alpha:1] autorelease]; cell.detailtextlabel.textcolor = [uicolor blackcolor]; cell.detailtextlabel.font=[uifont systemfontofsize:10]; if (indexpath.row %2 == 1) { cell.backgroundcolor = [[[uicolor alloc] initwithred:0.87f green:0.87f blue:0.87f alpha:1.0f] autorelease]; } else { cell.backgroundcolor = [[[uicolor alloc] initwithred:0.97f green:0.97f blue:0.97f alpha:1.0f] autorelease]; } } // customize the appearance of table view cells. - (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { static nsstring *cellidentifier = @ cell ; uitableviewcell *cell = [tableview dequeuereusablecellwithidentifier:cellidentifier]; if (cell == nil) { cell = [[[uitableviewcell alloc] initwithstyle:uitableviewcellstylesubtitle reuseidentifier:cellidentifier] autorelease]; cell.selectionstyle= uitableviewcellselectionstyleblue; // cell.accessorytype=uitableviewcellaccessorydisclosureindicator; cell.backgroundcolor=[uicolor bluecolor]; } // acities=[appdelegate.citylistarray objectatindex:indexpath.row]; // cell.textlabel.text=acities.city_name; cell.textlabel.text=[[appdelegate.citylistarray objectatindex:indexpath.row]city_name]; return cell; } - (void)tableview:(uitableview *)tableview didselectrowatindexpath:(nsindexpath *)indexpath{ // city=amsterdam&amp;latitude=52.366125&amp;longitude=4.899171 nsstring *url; acities=[appdelegate.citylistarray objectatindex:indexpath.row]; if ([appdelegate.citylistarray count]&gt;0){ url=@ city= ; url=[url stringbyappendingstring:acities.city_name]; url=[url stringbyappendingstring:@ &amp;latitude=52.366125&amp;longitude=4.899171 ]; nslog(@ url value is %@ url); [self parsecityname:[[nsurl alloc]initwithstring:url]]; } } -(void)parsecityname:(nsurl *)url{ nsxmlparser *xmlparser=[[nsxmlparser alloc]initwithcontentsofurl:url]; xmlparser *parser=[[xmlparser alloc] initxmlparser]; [xmlparser setdelegate:parser]; bool success; success=[xmlparser parse]; if (success) { nslog(@ sucessfully parsed ); cityeventviewcontroller *cityeventviewcontroller=[[cityeventviewcontroller alloc]initwithnibname:@ cityeventviewcontroller bundle:nil]; cityeventviewcontroller.index=currentindex; [self.navigationcontroller pushviewcontroller:cityeventviewcontroller animated:yes]; [cityeventviewcontroller release]; cityeventviewcontroller=nil; } else { nslog(@ try it idoit ); uialertview *alert=[[uialertview alloc] initwithtitle:@ alert! message:@ event not in radius delegate:self cancelbuttontitle:@ ok otherbuttontitles:nil]; [alert show]; [alert release]; } } - (void)didreceivememorywarning { // releases the view if it doesn t have a superview. [super didreceivememorywarning]; // release any cached data images etc that aren t in use. } - (void)viewdidunload { [super viewdidunload]; // release any retained subviews of the main view. // e.g. self.myoutlet = nil; } - (void)dealloc { [acities release]; [super dealloc]; } @end </code></pre> and the error is <pre><code>*** terminating app due to uncaught exception nsrangeexception reason: *** -[nsmutablearray objectatindex:]: index 1 beyond bounds for empty array *** call stack at first throw: </code></pre>,iphone
java.util.concurrentmodificationexception with xfire-all-1.0 version i facing problem with x-fire-all-1.0 version jar. in our application we implemented webservices for this we are using xfire-all-1.0.jar. working fine with this. but some times on our jboss console getting following exceptions. this is i am not getting always. as per my application requirement when client sends the request to get list of merchants details [our webservice returns the all the merchant details in success scenario] response document is preparing with the help of x-fire api. but some times getting following issue. how to resolve the bug in xfire-all-1.0.jar <pre><code>java.util.concurrentmodificationexception at org.jdom.contentlist$filterlistiterator.checkconcurrentmodification( at org.jdom.contentlist$filterlistiterator.nextindex( at org.jdom.contentlist$filterlistiterator.hasnext( at org.codehaus.xfire.wsdl.abstractwsdl.cleanimports( at org.codehaus.xfire.wsdl.abstractwsdl.updateimports( at org.codehaus.xfire.wsdl11.builder.wsdlbuilder.write( at org.codehaus.xfire.wsdl11.builder.wsdlbuilderadapter.write( at org.codehaus.xfire.defaultxfire.generatewsdl( at org.codehaus.xfire.transport.http.xfireservletcontroller.generatewsdl( at org.codehaus.xfire.transport.http.xfireservletcontroller.doservice( at org.codehaus.xfire.transport.http.xfireservlet.doget( at javax.servlet.http.httpservlet.service( at javax.servlet.http.httpservlet.service( at org.apache.catalina.core.applicationfilterchain.internaldofilter( at org.apache.catalina.core.applicationfilterchain.dofilter( at org.jboss.web.tomcat.filters.replyheaderfilter.dofilter( at org.apache.catalina.core.applicationfilterchain.internaldofilter( at org.apache.catalina.core.applicationfilterchain.dofilter( at org.apache.catalina.core.standardwrappervalve.invoke( at org.apache.catalina.core.standardcontextvalve.invoke( at at at org.apache.catalina.core.standardhostvalve.invoke( at org.apache.catalina.valves.errorreportvalve.invoke( at org.jboss.web.tomcat.service.jca.cachedconnectionvalve.invoke( at org.apache.catalina.core.standardenginevalve.invoke( at org.apache.catalina.connector.coyoteadapter.service( at org.apache.coyote.http11.http11processor.process( at org.apache.coyote.http11.http11protocol$http11connectionhandler.process( at$ at 19:58:05 722 error [[xfireservlet]] servlet.service() for servlet xfireservlet threw exception java.util.concurrentmodificationexception at org.jdom.contentlist$filterlistiterator.checkconcurrentmodification( at org.jdom.contentlist$filterlistiterator.nextindex( at org.jdom.contentlist$filterlistiterator.hasnext( at org.codehaus.xfire.wsdl.abstractwsdl.cleanimports( at org.codehaus.xfire.wsdl.abstractwsdl.updateimports( at org.codehaus.xfire.wsdl11.builder.wsdlbuilder.write( at org.codehaus.xfire.wsdl11.builder.wsdlbuilderadapter.write( at org.codehaus.xfire.defaultxfire.generatewsdl( at org.codehaus.xfire.transport.http.xfireservletcontroller.generatewsdl( at org.codehaus.xfire.transport.http.xfireservletcontroller.doservice( at org.codehaus.xfire.transport.http.xfireservlet.doget( at javax.servlet.http.httpservlet.service( at javax.servlet.http.httpservlet.service( at org.apache.catalina.core.applicationfilterchain.internaldofilter( at org.apache.catalina.core.applicationfilterchain.dofilter( at org.jboss.web.tomcat.filters.replyheaderfilter.dofilter( at org.apache.catalina.core.applicationfilterchain.internaldofilter( at org.apache.catalina.core.applicationfilterchain.dofilter( at org.apache.catalina.core.standardwrappervalve.invoke( at org.apache.catalina.core.standardcontextvalve.invoke( at at at org.apache.catalina.core.standardhostvalve.invoke( at org.apache.catalina.valves.errorreportvalve.invoke( at org.jboss.web.tomcat.service.jca.cachedconnectionvalve.invoke( at org.apache.catalina.core.standardenginevalve.invoke( at org.apache.catalina.connector.coyoteadapter.service( at org.apache.coyote.http11.http11processor.process( at org.apache.coyote.http11.http11protocol$http11connectionhandler.process( at$ at </code></pre>,java
create dynamic uiview i want to create a uiview with end points(not only the origin but also the 3 endpoints) specified by the position of other 3 that when i move the endpoint views this view also should it possible,iphone
automatically generated user id i am making an iphone application in which there is use of database. i want that whenever user put his or her information there should be unique id no for each user. but this id no should generate automatically. how can i do this..please help me. thanks alot.,iphone
opening an image in a popup: how to get its size when the image is loaded i am writing a script that looks for links of the kind <code>&lt;a href= image_url &gt;...&lt;/a&gt;</code> where image_url is the url of an image and then adds to those tags an <code>onclick= popupimage(this) </code> attribute to them that opens a popup displaying the image. i know how to look for those tags and my question is about writing the popupimage function. so far i have <pre><code>function popupimage(link){ image width=400 height=400 ); } </code></pre> this works pretty well but i would like to resize the popup to fit the image once it s loaded. thus i would probably need something of the kind <pre><code>function popupimage(link){ image width=400 height=400 ); w.onload = function(){ ... do something to get the size of the image... ... resize the popup (this i know how to do)... } } </code></pre> but i don t know how to access the image loaded by the window since it has no dom... the thing is that i really don t want to write some html into the popup to display the image (for some other reasons). any suggestion would be much appreciated. thanks in advance!,javascript
read digits (instead of int) from a txt file in java i have a file like this test.txt: 122352352246 12413514316134 now i want to read each digit a time and store it as one element in say a list. i tried using scanner. but it will read a line each time and outputs a long integer. that means if i want to get the digits i need to further separate the digits in that integer. i guess there must be an elegant way to directly read one digit each time. below is my code <pre><code>public class readdigits { public static void main(string[] args) throws ioexception{ list&lt;integer&gt; list = new arraylist&lt;integer&gt;(); file file = new file( test.txt ); scanner in = new scanner(file); int c; try { while (in.hasnext()){ c = in.nextint(); list.add(c); } } finally { system.out.println(list); in.close(); } } } </code></pre>,java
component reuse in common module i have two components in a java ee web application. these components differ only on two to three fields. both perform the same action i.e. save data in the database and send some mail. what would be a better way to implement them currently i have two options: <ol> <li> have a common vo pass base class to service and dao layer then based on the object type do the necessary actions in the dao class as both the modules data sit in two different tables. </li> <li> have common interfaces common vo but a separate service and dao. </li> </ol> can anybody let me know what is better and why or if there is a better way,java
dismissmodalview doesn t respond to touches in myappdelegate when a button is pressed it presents a modal view: <pre><code>- (void) showinfopanel:(id)sender { </code></pre> infoviewcontroller = [[infoviewcontroller alloc] init]; uinavigationcontroller *infonavcontroller = [[uinavigationcontroller alloc] init]; infonavcontroller.navigationbarhidden = yes; [window addsubview:infonavcontroller.view]; [infonavcontroller presentmodalviewcontroller:infoviewcontroller animated:yes]; } in infoviewcontroller i have to dismiss the modal view: <pre><code>- (void) exitinfopanel:(id)sender { [self.parentviewcontroller dismissmodalviewcontrolleranimated:yes]; </code></pre> } although it works the myappdelegate window doesn t respond to touches anymore. instead in the infoviewcontroller if: <pre><code>[self.view removefromsuperview]; </code></pre> it respond to touches but i lose the animation of dismissing the modal view. what i am doing wrong why it doesn t respond to touches when the modalview is dismissed thanks,iphone
iphone application development home button im new to iphone development.can somebody please tell me how can i putt home button to each view of my application. pressing home button user will be provided home screen. thanks,iphone
python: editing a single line in a text file i have a plain text html file and am trying to create a python script that amends this file. one of the lines reads: <pre><code>var mylatlng = new google.maps.latlng(lat long); </code></pre> i have a little python script that goes off and grabs the co-ordinates of the international space station. i then want it to amend a file to add the latitude and longitude. is it possible to use regex and parse just that one line i don t fancy parsing the entire file. if it is possible which module would be best to use and how would i point it at that line,python
"creating string out of object in javascript i am trying to assemble a certain string out of a javascript object and am having some problems. i created a function that takes the object and should return the string. the initial object looks like so: <pre><code>var testobject = { topics : [ other new1 ] other : [ try this this also ] }; </code></pre> and i would like the string to spit out this: <pre><code> topics~~other|topics~~new1|other~~try this|other~~this also </code></pre> here is what i have now: <div class= snippet data-lang= js data-hide= false >
<div class= snippet-code >
<pre class= snippet-code-js lang-js prettyprint-override ><code>var testobject = {
topics : [ other new1 ]
other : [ try this this also ]
function transformobjecttostring(activefilters) {
var newstring = ;
var checkfiltergroups = function(filtertopic) {
activefilters[filtertopic].map(function(selectedfilter) {
var tempstring = filtertopic + ~~ + selectedfilter + | ;
console.log( check string tempstring);
for (var filtergroup in activefilters) {
return newstring;
the temp string seems to be formatted correctly when i check the log but for whatever reason it looks like the <code>concat</code> is not working as i assumed it would.",javascript
python list data received from external device rfsniffer i have a program in python that receives data from an external device. <pre><code>(...) while true: s = check_output([ ./rfsniffer ]) (...) </code></pre> how can i save my data into a list or array while it is receving data,python
combine tabbar and navigation bar how to pushviewcontroller i drag a tabbar controller into mainwindow.xib then put a navigation controller into tabbar controller so one of my tab page is navigation page. i set the root view of navigation controller (navrootviewcontroller.h / .m) give me one way to call -pushviewcontroller: animated:,iphone
character validation for each newline i m trying to find a way to validate if each line being read from srcfile starts with an alpha character. i tried using the character.isletter() method but it complains about line being declared as a string and not a char array...from what i thought a string is an array of characters but appearently isletter() does not work in that way. i m wondering what method i could use. i want to filter the data from srcfile and place it a hashmap and vector but i first need to find an effective and clean way to figure out if the line starts with alpha characters. i also thought about using string.contains() because i know what specfic char sequence i m looking for but it would proce to be more verbose and possibly uneccesary way of coding and it also makes my program less generic which i want to a certain extent. <pre><code> try { scanner myscanner = new scanner(srcfile); // why not declare line outside while loop // and write cond. as (line = myscan... != null) while (myscanner.hasnextline()) { string line = myscanner.nextline(); //system.out.println(line); if (character.isletter(line[0])) { } } myscanner.close(); } catch (filenotfoundexception e) { e.printstacktrace(); } </code></pre> the rest of the condition would like this: <pre><code> //if first char start with a aplha char move to the ticket list if (char.isletter(line[0])) { ticket t = new ticket(); t.parseline(line); //logger.debug(line); tickets.add(t); } else { sbpeople sbupeople = new sbpeople(); sbupeople.parseline(line); </code></pre>,java
define myself d file type using cfbundledocumenttypes i know i can define file type using in appinfo.plist such as zip pdf etc is it possible define any type with special extension such as .mydatafiletype or .datafiletype welcome any comment,iphone
java reference variable in void ref method i am trying to figure out how to access the sb variable in the void ref method. is it possible this problem came up as i prepare for a test. <pre><code>public class x{ public void ref(string refstr stringbuilder refsb){ refstr = refstr + refsb.tostring(); refsb.append(refstr); refstr = null; refsb = null; //how can i access main variable sb here not possible //sb.append(str); } public static void main(string[] args){ string s = mystring ; stringbuilder sb = new stringbuilder( -mystringbuilder- ); new x().ref(s sb); system.out.println( s= +s+ sb= +sb); } } </code></pre>,java
what is typeof define === function && define[ amd ] used for what purpose does the following code serve what does factory function do here here root is window object. is factory a default java script function in what kind of scenarios this type of code can be used. this code is from <a href= rel= noreferrer >toggle.js from simon tabor</a>. zepto and ender are libraries. is this mostly used in libraries. <pre><code> if (typeof define === function &amp;&amp; define[ amd ]) { define([ jquery ] factory); } else { factory(root[ jquery ] || root[ zepto ] || root[ ender ] || root[ $ ]|| $); } </code></pre>,javascript
convert byte[] to base64 and ascii in python i am new to python and i m quite struggling to convert and array of byte to base64 string and/or ascii. tried googling stuff but can t seem to find a solution. i can do this easily in c# but can t seem to do this in python 2.x/3.x any help is greatly appreciated. thanks in advance.,python
fullcalendar on iphone is it possible to use fullcalendar on iphone native app reading events from servlet on a remote server features required are month week and day view. no need of adding editing or deleting events. clicking on event display the summary of the event. i would be very happy if fullcalendar is capable of the same if no what are the other solutions. expecting your guidance. thanks in advance,iphone
i need help making a loop in an if-else statement in java <pre><code>import java.util.scanner; public class phonenumberformat { public static void main(string [] args) { //create the scanner class for user input scanner keyboard = new scanner(; system.out.println( please enter your phone number: ); string number =; /* separate the number into the three categories i want * side-note: since we can assume that the phone number will be 10 digits long i don t * have to figure out the length of the number that the user will input */ string area_code = number.substring(0 3); string first_three = number.substring(3 6); string rest = number.substring(6 10); int new_number = integer.parseint(number); if (new_number &lt; 10){ system.out.println( it seems that you have entered an invalid phone number please try again! ); /* i want to make a loop here so that if the user accidentally enters more of less than * a 10 digit number it will loop the please enter your phone number: part so * java won t give an error */ } else { //concatenate the number properly so that it is formatted nicely string formatted_number = ( + area_code + ) + + first_three + - + rest; } string final_number = integer.tostring(formatted_number); //print the newly formatted number system.out.println(formatted_number); } } </code></pre> so this program is supposed to format a phone number from 1112223333 to (111) 222-3333. the assignment said that we can assume that the user will input an unformatted phone number however i want to put in a little safety so that if the user by change happens to input a number that isn t 10 digits long instead of an error it will prompt them to re-enter the number. thanks!,java
java encoding for gb2312 character ® replacing with question mark( ) i m trying to get encoded value using <code>gb2312</code> characterset but i m getting instead of ® below is my sample code: <pre><code>new string( test ® .getbytes( gb2312 )); </code></pre> but i m getting test instead of test ®. does any one faced this issue java version- <code>jdk6</code> platform: <code>window 7</code> i m not aware of chinese character encoding so need suggestion. regards mahesh,java
why does java have an int and int integer datatype and can i move data from one to another <blockquote> <strong>possible duplicate:</strong><br> <a href= >why can integer and int be used interchangably </a> </blockquote> i am trying to understand the difference between these. can i declare something to be an int for example and then compare this with a number that i put in an integer also why does java have the two. why not just combine these can someone help me by showing me a 3-4 line code example of how each is used,java
parsing owl file i have an owl file and i want to extract the classes present in the owl file.can anyone provide a sample program in java how to do this. thanks in advance,java
"is there a better method of creating a list of quarters by counting back from a given quarter i have done this function which creates an array of quarters counting back x quarters including from specified quarter. the last item in the array is the reference quarter. for example with reference quarter <code>2</code> and a count of <code>9</code> this would yield <code>[2 3 4 1 2 3 4 1 2]</code>; my function works but i would like to know if there is a simpler more elegant solution to this. <strong>code below:</strong> <div class= snippet data-lang= js data-hide= false data-console= true data-babel= false >
<div class= snippet-code >
<pre class= snippet-code-js lang-js prettyprint-override ><code>/// counts back x from specified quarter
/// parameters:
/// @param countfrom -- the reference quarter to count back from
/// @param count -- count
/// @returns array -- the array of quarters
function getquarterlist(countfrom count) {
var ret = [];
for (var i = 0; i &lt; count; i++){
var z = countfrom - i;
while (z &lt; 1) {
z = z + 4;
ret.splice(0 0 z);
return ret;
var quarterlist = getquarterlist(2 9);
purpose of maxzoom property in google maps maptype interface the google maps api guide detailing the maptypes interface states the following with regard to required properties: <blockquote> maxzoom (required) specifies the maximum zoom level at which to display tiles of this map type. </blockquote> however in the example given by google at: <a href= rel= nofollow ></a> the maxzoom property is not even included. if the code is modified to include the maxzoom property (as shown below) the property has no effect -- should it some clarification would be nice ... <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;overlay map types&lt;/title&gt; &lt;style&gt; html body #map-canvas { height: 100%; margin: 0px; padding: 0px; } &lt;/style&gt; &lt;script src= v=3.exp &gt;&lt;/script&gt; &lt;script&gt; /** @constructor */ function coordmaptype(tilesize) { this.tilesize = tilesize; this.maxzoom = 12; // &lt;--- this has no effect } coordmaptype.prototype.gettile = function (coord zoom ownerdocument) { var div = ownerdocument.createelement( div ); div.innerhtml = coord.tostring() + &lt;br&gt;zoom: + zoom.tostring(); = this.tilesize.width + px ; = this.tilesize.height + px ; = 10 ; = solid ; = 1px ; = #aaaaaa ; return div; }; var map; var chicago = new google.maps.latlng(41.850033 -87.6500523); function initialize() { var mapoptions = { zoom: 10 center: chicago }; map = new map-canvas ) mapoptions); // insert this overlay map type as the first overlay map type at // position 0. note that all overlay map types appear on top of // their parent base map. map.overlaymaptypes.insertat( 0 new coordmaptype(new google.maps.size(256 256))); } google.maps.event.adddomlistener(window load initialize); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id= map-canvas &gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>,javascript
sending function pointer with arguments with it and then add additional arguments while invoking i have a map which says maps a string to a function like : <pre><code>validator = { first_name : validate_str last_name : validate_str phone : validate_phone } </code></pre> i need to call the corresponding validate function based on the type of value i have in the map that will be fed to me as input for e.g. <pre><code>for name in elements: # validate the value of this name in the input map using the function # input is the map that has the value for each of these fields # elements is a list of all fields used to loop through one input at a time if validator[name]( input[name] ) is false: # throw validation error else: # do something else </code></pre> this works fine unless for this scenario i am not sure if it can be done: the validate_str also checks if a given string is of desired max length. <pre><code>def validate_str(str max-len): # throw error if len(str) &gt; max-len </code></pre> the max-len can differ based on the string so i need to call validate_str for first_name with say 64 characters and last name with 256 characters. i can use a different map to say that this field has this max_len but is it possible for the validator map to have pointer to the validate_str function with the max-len argument preset based on the field something like: <pre><code>validator = { first_name : validate_str(max-len=64) last_name : validate_str(max-len=256) phone : validate_phone } </code></pre> then call it for validation like: <pre><code>if validator[name]( str=input[name] ) is false: # the appropriate value for max-len goes with the function call and just the # str is appended to the argument list while invoking. </code></pre> this makes life easier so that we need not then remember again what fields will have the max-len sent along with it.,python
using arrays in constructor for function in java so i m sure this is an easy question to answer and i m new to java but i want to pass an array into an argument and i m having issues. below i create 3 shapes and i m trying to pass myshapes or that array into areacalculator but i get the error - <pre><code>cannot find symbol symbol : method areacalculator() location: class points areacalculator(); </code></pre> <hr> <pre><code>public static void main(string[] args) { shape[] myshapes = new shape[3]; areacalculator(myshapes); } class areacalculator{ public areacalculator(shape[] shapes){ } } </code></pre>,java
how to delay for loop by 1 second in javascript i am new at javascript. i want to create a for loop that iterate after 1 second. <pre><code>for(sec=60;sec&gt;0; sec--){ document.write(sec); } </code></pre> when i use above code for loop print everything immediately.i want that for loop executes every 1 second. i know it can be done by using <code>setinterval();</code> function but i don t know how to do it exactly. please suggest me best solution how to do.,javascript
give preference to js file function over html file i have two functions of the same name; let s say <code>foo()</code>. one in the html file and one in the js file which is included in the html file. the problem is i want to give preference to the js file function rather than the html file function. is there any way to do that or is there any syntax in javascript like <code>[jsfilename].foo()</code> that may perhaps call the function in the js file,javascript
how to make python response after a certain amount of time i want to make python respond to an answer after 10 seconds. i am doing the python challenge and i have to write a program that asks the user what is your question . the program should response with let me think about that and pause for 10 seconds before responding with i don t want to answer that question right now . the program should then ask the user the same question that the user entered and then look at their response. this is what i have so far: <pre><code>import time timeout=time.time()+60*10 while true: answer=str(input( what is your question )) print( let me think about that ) </code></pre> i don t really know what <code>timeout=time.time()+60*10</code> or <code>while true</code> means but when i searched the internet it seems to be the right one. all i can get python to do now is ask the question and wait for input and ask the question again without waiting. another problem is i put str before input which i think it means you can only give letters not number. but when i use number as an input python still accept it as a string.,python
why use window.onload i have tried finding an answer to this on my own but only found instructions on how to use onload events. i seem to be missing the point. i ve been taught that if i want something to happen when the page loads i should use window.onload like this: <pre><code>&lt;script&gt; window.onload = dosomething(); function dosomething() { window.alert( hello ); } &lt;/script&gt; </code></pre> but now that i am thinking on my own i wonder what the point of doing that is. because this also produces the same result: <pre><code>&lt;script&gt; dosomething(); function dosomething() { window.alert( hello ); } &lt;/script&gt; </code></pre> anything i put at the top inside <code>&lt;script&gt;</code> is going to execute anyway... so what s the point of window.onload,javascript
why i cannot parse +1 to int i am trying to parse <code>+1</code> value to an <code>int</code> value. in my code <code>+1</code> is a <code>string</code> and i am trying to convert it to <code>integer</code> using <code>integer.parseint</code> <pre><code>string num = +1 ; int convertednum = integer.parseint(num); </code></pre> but i am getting error why java is not treating <code>+1</code> as an integer value,java
detecting when nav controller popped to root here is my code: <pre><code>signupcontroller* signupcontroller = [[signupcontroller alloc] initwithnibname:@ signupcontroller bundle:nil]; [window addsubview:[navigationcontroller view]]; [window makekeyandvisible]; self.navigationcontroller.title = @ mynavcontroller ; [self.navigationcontroller pushviewcontroller:signupcontroller animated:yes]; [signupcontroller release]; </code></pre> unfortunately for me calling pushviewcontroller is not synchronous so the next line ([signupcontroller release]) is executed immediately. i need to detect hen the signupcontroller has popped back to the root so i can take the data from the signup controller and do a registration or login. any ideas thanks,iphone
javascript replace single quote with double single quote issue i have used below syntzx to replace single quote with double single quote issue <pre><code>str.replace(/ /g ); </code></pre> but it s replace everytime when it load page. like i have text test s and test s page and test s event then first time it will be test s and test s page and test s event then again test s and test s page and test s event then next loading test s and test s page and test s event can you please help to get just single to double single quote only,javascript
submitting application to apple store - application failed codesign verification i tried to upload my iphone application to the app store but received the following error: <strong>the binary you uploaded was invalid. the icon file must be in .png format.</strong> the icon file is in .png format size 57x57 so assumed it is a bug and tried to upload with application uploader when i got another error: <strong>application failed codesign verification. the signature was invalid or it was not signed with an apple submission certificate.</strong> i followed every single step and it is not working... it is driving me crazy! please advise what should i do!,iphone
how to handle single selection in uicollectionview in iphone <pre><code>- (void)collectionview:(uicollectionview *)collectionview didselectitematindexpath:(nsindexpath *)indexpath { if (shareenabled) { // determine the selected items by using the indexpath nsstring *selectedrecipe = [self.getname objectatindex:indexpath.row]; // add the selected item into the array [getimage addobject:selectedrecipe]; } } </code></pre> how to handle single selection in iphone sdk. when i press on particular cell then it should be show on big view on the same view.,iphone
need more efficient java.util.scanner i have a block of java code i m trying to run it looks like: <pre><code>import; import java.util.scanner; import java.util.regex.pattern; file f = new file( input.tsv ); scanner scanner = new scanner(f).usedelimiter(pattern.compile( ^( !.*(\\\\\\n)).*\\n$ )); import; writer writer = new printwriter( output.tsv ); while (scanner.hasnext()) writer.println( \\\\\\n )); scanner.close(); writer.close(); </code></pre> this uses a pile of memory and seems very inefficient to basically patch incoming files and remove escaped new line characters. <strong>there has to be a better way !</strong> surely nio or something can steam in and stream out etc. ps. the above was stolen from this thread here: <a href= >reading java file with escape characters for newline</a>,java
how to read string using scanner class <pre><code>import java.util.scanner; public class solution { public static void main(string[] args) { scanner scan = new scanner(; string s=scan.nextline(); system.out.println( string: + s); } } </code></pre> input: welcome to java tutorials output: welcome to java tutorials,java
return non duplicates numbers in array from method i am trying to remove duplicate numbers using method and return non-duplicate numbers actually i am stuck in method right now. this is my code : <pre><code>import javax.swing.joptionpane; public class duplicateremover{ public static void main(string[] args) { int[] array = new int[5]; for (int i=0; i&lt;array.length;i++) { string s=joptionpane.showinputdialog(null please enter an integer: integers joptionpane.question_message); array[i] = integer.parseint(s); } removeduplicates(array); for (int i=0; i&lt;array.length;i++) { joptionpane.showmessagedialog(null array[i] uniqe integers joptionpane.plain_message); } } public static int[] removeduplicates(int a []) { int []removeddup=new int[a.length]; for (int i = 0; i &lt; a.length; i++) { for (int j = i-1; j &lt; a.length; j++){ if (a[i] == a[i]) { removeddup[i] = j; break; } } </code></pre>,java
problem of subclassing uitableviewcell i have a class a that inherits uitableviewcell (to customize a table cell). it has members say x which is a uilabel. now if i want to set values like a.x.text = some text in the cellforrowatindexpath method i am getting compiler error error for member x in cell which is of non-class type uitableviewcell . could you please let me know how can i fix this problem thanks.,iphone
can one access the arguments class in javascript all other built-ins are attached to the global object: <pre><code>&gt; date) [object date] &gt; new date instanceof date true &gt; function) [object function] &gt; new function instanceof function true &gt; number) [object number] &gt; new number instanceof number true </code></pre> <code>arguments</code> however is not: <pre><code>&gt; args = null; (function() { args = arguments }()); [object arguments] &gt; new arguments instanceof arguments referenceerror: arguments is not defined </code></pre> is there any way to access it,javascript
custom tabbar: adjusting the view of the displayed view controller so it is resized to fit above the tabbar i need to create a customtabbar in one of my app. i subclassed uitabbarcontroller by adding a custom view to it. i made the tabbar hidden by setting <pre><code>self.tabbar.hidden = true; </code></pre> i added buttons on the customview and on click of these buttons am handling the switching between the tabs. the issue that am facing is that the height of my custom tabbar is not equal to (more than) the standard tabbar height so i need to clip my viewcontroller s view so that it doesn t hide behind the custom tabbar i tried setting the frame property of viewcontroller s view (see below) in viewdidload and viewdidappear methods but it doesn t work that way. <pre><code>[self.view setframe: cgrectmake(self.view.frame.origin.x self.view.frame.origin.x self.view.frame.size.width 400)] </code></pre> where 400 = 480 - height of my custom tabbar i hope am clear with my question.. thanks in advance,iphone
how to pack iphone code i created an iphone app and tested it on my simulator its working fine now i want to test the same app in another simulator . how can i do the same (i copied the whole folder but its not working ) please help,iphone
change html text input value using javascript how do you change text input value in html using javascript in my case i want to change the price input of an item when the user selects the item and inputs the quantity for example: <pre><code>&lt;html&gt; ... &lt;body&gt; quantity : &lt;input type= text id= qty /&gt; &lt;br/&gt; item : &lt;select id= item onclick= checkprice() &gt;&lt;option value= apple &gt;apple&lt;/option&gt;&lt;option value= orange &gt;orange&lt;/option&gt;&lt;/select&gt; //added onclick &lt;br/&gt; price : &lt;input type= text id= price /&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> what i would like is when the user input the quantity and item the price would be automatically inputted. i have tried this and it inputted nan (not a number) <pre><code>&lt;script type= text/javascript &gt; function checkprice() { var a = document.getelementbyid( item ).value; var b = document.getelementbyid( qty ).value; if(a = apple ){ price = 5 document.getelementbyid( price ).value=b*price }else if(a = orange ){ price = 4 document.getelementbyid( price ).value=b*price } } &lt;/script&gt; </code></pre> help please thank you.,javascript
typeerror: nonetype object is not iterable for mit opencourse assignment tried to attempt question on mit opencourseware sc 6.00. the question is on how to find combination of mcnuggets with 6 9 20 packs with total number given. currently my code is: <pre><code>def mac (): totalnumber = int (input( enter total number of mcnuggets )) num20 num6 num9= solve2(totalnumber) def solve2(numtotal): #define a new function to find and print multiple answers solutionfound = false # set up a variable to check if the solution is found for num20 in range (0 numtotal//20 + 1): for num9 in range (0 numtotal//9 +1): num6 = (numtotal-num20*20-num9*9)//6 if num6 &gt; 0: checknum = num20*20+num9*9+num6*6 if checknum == numtotal: print ( the number of 6-pack is num6) print ( the number of 9-pack is num9) print ( the number of 20-pack is num20) solutionfound = true # change the initial variable to true if not solutionfound: print ( there is no solution ) </code></pre> however when running this code it always display: <blockquote> typeerror: nonetype object is not iterable </blockquote>,python
how to handle home key/events in iphone i am developing game using iphone. when home screen button press i want to make game is in pause mode. how to handle home screen button and events (<code>incoming and outgoing events</code>).,iphone
best way to generate unique id in java i want to make java class that generate the unique id for these field when user make his id it will always be unqiue so how to do it in java <pre><code>string dairyid; string userid; string productid; string merchantid; string couponid; string eventid; </code></pre>,java
creating an ios distribution certificate i would like to create an ios distribution certificate to distribute the app to the apple store. when i create it i should put in the user email address field the email address that matches the information that was submitted when you my client have registered as an ios developer. the problem that i don t know what he has entered how i can know the mail that he has entered the same thing for the company name field. i can t contact my clients he is in holidays but i have his username and password of his apple developer account. thanks for your answer,iphone
how to call a method keep getting an error saying return type is void i am trying to call the method of menu but it says the return type is void i want the code in the method of menu to display when the sides is equal to 2 <pre><code>import java.util.scanner; class recorddice { public static void main(string[] args){ int dsides sides; scanner s = new scanner(; system.out.println( how many sides should the dice have ); sides = s.nextint(); if (sides == 2){ return menu(); } } public string menu() { system.out.println( bloody work ); } } </code></pre>,java
is float.negative_infinity.compareto(float.negative_infinity) always 0 i have a piece of code that sorts objects of type <code>float</code>. if a <code>float</code> is null then i assign <code>float.negative_infinity</code> to it and then compare. i wonder if <code>float.negative_infinity.compareto(float.negative_infinity)</code> always equals to 0 i wrote a test that does this comparisons and it returns 0. but i want to make sure that it always zero knowing how tricky it is to compare floats.,java
sqlite in a textview is it possible to display a sqlite values in a textview i have made it in a tableviewcontroller but i am not able to display the same in a textview. appdelegate.biblearray is the array that holds the sqldata.i have the same qustion in another forom .please look at this link for that question [here is the link]: <a href= >how to show sqlite datas in a textview </a> please help me to do this. thanks.,iphone
how to open kml file in iphone map applicaion i have one kml file in that there are define coordinates for routing. i want implement below things.when i touch on kml file or kml link then it shoud be open in map applicaion not in browser. i dont know how to implement that things please help me for this query edit: suppose some buddy has sent me kml file in email or kml file link..when i touch on that file or link then it must be open in iphone map applicaion,iphone
javascript execute scripts code in order inserted into dom tree not a duplicate as i have yet to found a satisfying answer on other threads: <ul> <li><a href= >load and execute javascript code synchronously</a></li> <li><a href= >loading html and script order execution</a></li> <li><a href= >load and execute javascript code synchronously</a></li> </ul> <hr> looking for <strong>native javascript</strong> answers no jquery no requirejs and so forth please :) <hr> <strong>summary of the entire question:</strong> <h2>i want to asynchronously load scripts but have ordered execution</h2> i am trying to enforce that the code in the inserted script elements execute exactly in the <strong>same order</strong> as they were added to the dom tree. that is <strong>if i insert two script tags</strong> first and second any code in first must fire before the second no matter who finishes loading first. i have tried with the <strong>async</strong> attribute and <strong>defer</strong> attribute when inserting into the head but doesn t seem to obey. i have tried with element.setattribute( defer ) and element.setattribute( async false) and other combinations. the issue i am experiencing currently has to do when including an external script but that is also the only test i have performed where there is latency. the second script which is a local one <strong>is always fired before</strong> the first one even though it is inserted afterwards in the dom tree ( head ). a) <strong>note</strong> that i am still trying to insert both script elements into the dom. ofcourse the above could be achieved by inserting first let it finish and insert the second one but i was hoping there would be another way because this might be slow. my understanding is that requirejs seems to be doing just this so it should be possible. however requirejs might be pulling it off by doing it as described in a). <strong>code if you would like to try directly in firebug just copy and paste:</strong> <pre><code> function loadscript(path callback errorcallback options) { var element = document.createelement( script ); element.setattribute( type text/javascript ); element.setattribute( src path); return loadelement(element callback errorcallback options); } function loadelement(element callback errorcallback options) { element.setattribute( defer ); // element.setattribute( async false ); element.loaded = false; if (element.readystate){ // ie element.onreadystatechange = function(){ if (element.readystate == loaded || element.readystate == complete ){ element.onreadystatechange = null; loadelementonload(element callback); } }; } else { // others element.onload = function() { loadelementonload(element callback); }; } element.onerror = function() { errorcallback &amp;&amp; errorcallback(element); }; (document.head || document.getelementsbytagname( head )[0] || document.body).appendchild(element); return element; } function loadelementonload(element callback) { if (element.loaded != true) { element.loaded = true; if ( callback ) callback(element); } } loadscript( function() { alert(1); }) loadscript( function() { alert(2); }) </code></pre> if you try the above code in like firebug most often it will fire 2 and then 1. i want to ensure 1 and then 2 but include both in the head.,javascript
how to split the url the get all the link in webpage i m doing the project <code>hyperlink crawler</code> for inspecting broken link. this is my code. so that the link give 404 error. i think my code for split url is something wrong. help me please. <pre><code>public class hinterface extends jframe { // declaring variables to be used as components in the interface private jlabel lblurl; private jtextfield inputsearch; private jbutton btnsearch; private jeditorpane outputlinks; public hinterface() { super( hyperlink crawler ); settype(type.popup); setresizable(false); getcontentpane().setbackground(; settitle( web link crawler for inspecting broken link ); flowlayout flowlayout = new flowlayout(); flowlayout.setalignment(flowlayout.left); getcontentpane().setlayout(flowlayout); // creates a label for displaying a text lblurl = new jlabel( \r\nenter url : ); lblurl.setlocation(new point(13 9)); lblurl.setdoublebuffered(true); lblurl.setalignmenty(component.bottom_alignment); lblurl.setalignmentx(component.right_alignment); lblurl.setverticalalignment(; lblurl.setforeground(color.white); lblurl.setfont(new font( tw cen mt condensed font.bold 20)); getcontentpane().add(lblurl); // creates text field for url input inputsearch = new jtextfield(); inputsearch.settext( http:// ); inputsearch.setpreferredsize(new dimension(400 32)); inputsearch.setfont(new font( sansserif font.bold 17)); getcontentpane().add(inputsearch); // creates a search button btnsearch = new jbutton( search ); btnsearch.setpreferredsize(new dimension(100 32)); btnsearch.setfont(new font( sansserif font.bold 13)); getcontentpane().add(btnsearch); // adds the results text area to a scroll-able pane jscrollpane scrolloutput = new jscrollpane (jscrollpane.vertical_scrollbar_as_needed jscrollpane.horizontal_scrollbar_never); scrolloutput.setbackground(color.gray); scrolloutput.setpreferredsize(new dimension(1100 670)); getcontentpane().add(scrolloutput); outputlinks = new jeditorpane(); outputlinks.addhyperlinklistener(new hyperlinklistener() { public void hyperlinkupdate(hyperlinkevent e) { if (hyperlinkevent.eventtype.activated.equals(e.geteventtype())) { system.out.println(e.geturl()); desktop desktop = desktop.getdesktop(); try { desktop.browse(e.geturl().touri()); } catch (exception ex) { ex.printstacktrace(); } } } }); outputlinks.settext( result ); outputlinks.setcontenttype( text/html ); outputlinks.seteditable(true); scrolloutput.setcolumnheaderview(outputlinks); outputlinks.seteditable(false); // add event handler to search button click handleevents theeventhandler = new handleevents(); inputsearch.addactionlistener(theeventhandler); btnsearch.addactionlistener(theeventhandler); } private class handleevents implements actionlistener { public void actionperformed(actionevent event) { // called when elements are triggered // preparing output variable string string stroutput = no results were found! ; if (event.getsource() == btnsearch || event.getsource() == inputsearch) { if (!inputsearch.gettext().equals( )) stroutput = crawlurl(inputsearch.gettext()); else stroutput = please enter url to crawl it s hyperlinks ; } // prints out the results outputlinks.settext(stroutput); } public string pullurl(string strurl) { string resutls = ; urlconnection connection = null; try { connection = new url(strurl).openconnection(); @suppresswarnings( resource ) scanner scanner = new scanner(connection.getinputstream()); scanner.usedelimiter( \\z ); if(scanner.hasnext()) resutls =; } catch ( exception ex ) { ex.printstacktrace(); } return resutls; } public string crawlurl(string strurl) { string results = ; // for return string protocol = http:// ; // assigns the input to the inurl variable and checks to add http string inurl = strurl; if (!inurl.tolowercase().contains( http:// .tolowercase()) &amp;&amp; !inurl.tolowercase().contains( https:// .tolowercase())) { inurl = protocol + inurl; } // pulls url contents from the web string contecturl = pullurl(inurl); if (contecturl == ) { // if it fails then try with https protocol = https:// ; inurl = protocol + inurl.split( http:// )[1]; contecturl = pullurl(inurl); } // declares some variables to be used inside loop string atagattr = ; string href = ; string msg = ; // finds a tag and stores its href value into output var string bodytag = contecturl.split( &lt;body )[1]; // find 1st &lt;body&gt; string[] atags = bodytag.split( &gt; ); // splits on every tag //to show link different from one another int index = 0; for (string s: atags) { // process only if it is a tag and contains href if (s.tolowercase().contains( &lt;a ) &amp;&amp; s.tolowercase().contains( href )) { atagattr = s.split( href )[1]; // split on href // split on space if it contains it if (atagattr.tolowercase().contains( \\s )) atagattr = atagattr.split( \\s )[2]; // splits on the link and deals with or quotes href = atagattr.split( ((atagattr.tolowercase().contains( \ )) \ : \ ) )[1]; if (!results.tolowercase().contains(href)) //results += ~~~ + href + \r\n ; /* * last touches to url before display * adds http(s):// if not exist * adds base url if not exist */ if(results.tolowercase().indexof( about ) != -1) { //contains about } if (!href.tolowercase().contains( http:// ) &amp;&amp; !href.tolowercase().contains( https:// )) { // http:// + baseurl + href if (!href.tolowercase().contains(inurl.split( :// )[1])) href = protocol + inurl.split( :// )[1] + href; else href = protocol + href; } system.out.println(href);//debug try { msg = urlheker(href); } catch (exception e) { // todo auto-generated catch block e.printstacktrace(); } // store the link in output var if (!results.tolowercase().contains(href)){ results += &lt;a href=\ ; results += href; results += \ &gt; ; results += link + (index + 1)+ : + href ; results += &lt;/a&gt; ; results += : ; results += msg; results += &lt;br&gt; ; index++; } } } system.out.println(results); return results; } } public string urlheker(string href) throws exception { string msg = ; int code = 0; url url = new url(href); urlconnection connection = url.openconnection(); if(connection instanceof httpurlconnection) { httpurlconnection httpconn=(httpurlconnection)connection; code = httpconn.getresponsecode(); msg = httpconn.getresponsemessage(); if(code == httpurlconnection.http_ok ) system.out.println( return normal response : +msg); else system.out.println(code); } msg = msg+ [ + integer.tostring(code) + ] ; return msg; } } </code></pre>,java
randomly change a letter in every 60 seconds i am trying to find a method to have a single letter change every 5 seconds. i have the random part done but cannot work out how to change it every 5 seconds. here is what i have put together so far i am hoping someone can tell me where i am going wrong. <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;script type= text/javascript &gt; function randomstring(length) { var text = ; var possible = abcdefghijklmnopqrstuvwxyz ; for( var i=0; i &lt; length; i++ ) text += possible.charat(math.floor(math.random() * possible.length)); return text; } function changingrandomstring(length) { setinterval(function(){ return randomstring(length); } 5000); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id= wrap &gt; &lt;p&gt;random changing letter : &lt;script type= text/javascript &gt;changingrandomstring(1);&lt;/script&gt;&lt;/p&gt; &lt;p&gt;random static letter : &lt;script type= text/javascript &gt;document.write(randomstring(1));&lt;/script&gt;&lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> in the ideal world i am looking to also make the changing letter fade in and out as well for those who like a challenge :-) thanks in advance for any help.,javascript
getting the last index better to use len(list)-1 or use own variable in my code below would it be better to use the i = len(scheduled_meetings)-1 or the i=0/i+=1 method i know the cost of len() is o(1) and it s probably more clear whats going on this way but it gets calculated for every m in sorted_meetings. i=0 is set once then only incremented if something is appended to the list. will there even be a difference both methods work against my test cases just wanted to get some feedback on which would be better. <pre><code>import operator def answer(meetings): # sort by earliest end time sorted_meetings = sorted(meetings key=operator.itemgetter(1)) # always select the earilest end time scheduled_meetings = [sorted_meetings[0]] i = 0 #method b for m in sorted_meetings: i = len(scheduled_meetings) - 1 #method a if m[0] &gt;= scheduled_meetings[i][1] or m[1] &lt;= scheduled_meetings[i][0]: scheduled_meetings.append(m) i += 1 #method b return len(scheduled_meetings) </code></pre>,python
how can we set a large uiimage on small uiimageview i am using imagview with size of 320x320 to display large image (350 x 783). while placing the large image into the imageview the image looks squeezed compressed something not like the quality one. my question is how can i make the large image into small with as good quality as the original image,iphone
array join() method without a separator <pre><code>var arr= [ g o o d ]; var arr2 = arr.join(); </code></pre> arr2 will be g o o d . i would like to get good . i know there are a million other ways to achieve this but was curious if there was a way with join. thanks,javascript
using the .value method to get user input from the dom (basic javascript timer) i m making a basic javascript timer. at present the number of seconds the timer runs for is set using a variable. i d like to have this variable to be set by the user but i m struggling to make it work. here s what i ve tried: html: <pre><code>&lt;input type= text placeholder= how many seconds id= set-timer &gt; </code></pre> this gives an input box. js: <pre><code>var originalcount = document.getelementbyid( set-timer ).value; </code></pre> but this doesn t seem to work. am i using .value incorrectly here s my jsfiddle to give you an idea of what i m trying to achieve: <a href= rel= nofollow noreferrer ></a> hopefully i m clear enough in my objectives. i m still wrapping my head around javascript. thanks in advance.,javascript
js: how to redirect an user to another page when user refresh the page the context is a game. when user refreshes his page (f5 or ctrl+r) i want the page to be redirect to gameover.php page. can this be done in pure js,javascript
navigation controller button left in my application i have some leftbarbutton of the navigation bar set to retour and some others set to back i would like to set all my buttons to retour how to do this please i have spend many hours to dos this. thanks,iphone
is there a good reason to have short file names for javascripts eg. why is the google analytics script ga.js instead of google-analytics.js is it convention optimisation or over optimisation,javascript
storing a printed line into a string i d like to know if there is any way to store a series of texts which are printed using system.out.print into a specific string so that it can be used to recall the line in the future. for example : <pre><code>string oldline=null; int x = 4; for (int i=0; i&lt;10; i++) { int result = x+i; system.out.print(result+ \t ); } </code></pre> the result would be then something like: <pre><code>4 5 6 7 9 10 .... </code></pre> now i d like to know if i can store this line into: <pre><code>string oldline; </code></pre> so whenever i print oldline i can print the same line as : <pre><code>4 5 6 7 9 10 .... </code></pre>,java
contentview tag question i created contentviews and assigned tags. when i click row in simulator i cannot get right tag value. tag value is always 0. what is wrong with my code <pre><code>- (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { static nsstring *cellidentifier = @ cell ; uitableviewcell *cell = (uitableviewcell *)[tableview dequeuereusablecellwithidentifier:cellidentifier]; uiimageview *imgview *imgview1; if(cell == nil) { cell = [[[uitableviewcell alloc] initwithframe:cgrectzero reuseidentifier:cellidentifier] autorelease]; cell.textlabel.text = @ test ; imgview = [[uiimageview alloc] initwithframe:cgrectmake(100 0 20 62)]; [imgview setimage:[uiimage imagenamed:@ 1.png ]]; imgview.tag = 10; [cell.contentview addsubview:imgview]; [imgview release]; imgview1 = [[uiimageview alloc] initwithframe:cgrectmake(200 0 20 62)]; [imgview1 setimage:[uiimage imagenamed:@ 2.png ]]; imgview1.tag = 20; [cell.contentview addsubview:imgview1]; [imgview1 release]; } else { imgview = (id)[cell.contentview viewwithtag:10]; imgview1 = (id)[cell.contentview viewwithtag:20]; } return cell; } - (void)tableview:(uitableview *)tableview didselectrowatindexpath:(nsindexpath *)indexpath { uitableviewcell *cell = [tableview cellforrowatindexpath:indexpath]; if (cell.contentview.tag == 10) // tag is always 0. what s wrong nslog(@ 10 ); else if (cell.contentview.tag == 20) nslog(@ 20 ); } </code></pre>,iphone
while first index is an array <em>i can tell i m falling through my while loop from frame 3 to 4.</em> <strong>am i not checking the condition in my while loop correctly </strong> <pre><code>function steamrollarray(arr) { var r2 = []; while (arr[0].isarray) { console.log(arr[0]); r2.push(arr[0]); return r2; } return r2; } steamrollarray([[[ a ]] [[ b ]]]); // should return [ a b ]. steamrollarray([1 [2] [3 [[4]]]]); // should return [1 2 3 4]. steamrollarray([1 [] [3 [[4]]]]); // should return [1 3 4]. steamrollarray([1 {} [3 [[4]]]]); // should return [1 {} 3 4]. </code></pre> <a href= rel= nofollow noreferrer >step 3 to 4</a>,javascript
does t.length >>> 0 anything in the mdn js array polyfil in the mdn array polyfils it has the following line. <pre><code>var len = t.length &gt;&gt;&gt; 0; </code></pre> does binary shift right 0 really actualy do anything or can i take this out,javascript
python google search explicit phrase i am trying to define a google search with the ajax interface using the very good function described here (a martelli) <a href= >google search from a python app</a> <pre><code>........ query = urllib.urlencode({ q : searchfor}) .... </code></pre> if i define the variable <code>searchfor = big car </code> the query generated is big+car. however i want to generate the query big car (those two words ocurring together). q1) that is i would like to define an explicit phrase in my query (in google i would enter the phrase within double quotes). q2) how can i define a query where i wxclude a certain term. (in google you enter the - sign).,python
how to disable the optionparser default help view i am using the optionparser from optparse module to parse my command that i get using the raw_input(). when i give a -h it displays the help screen and exits my application. i dont want it to display the help screen or exit the application. how can this be accomplished thanx in advance.,python
javascript inheritance - not defined . namespace issue i have a class called <code>moduleselector</code> that grabs a list of modules from a server and displays them as clickable toggle buttons. i m trying to create a class called <code>module</code> that extends the <code>togglebutton</code> class and is only visible to the <code>moduleselector</code>. the problem i m having is that the line: <code>module.prototype = new togglebutton();</code> is giving an error: <code>togglebutton is not defined</code>. i don t understand why it cannot be found because i can create new instances of togglebutton inside the <code>module</code> function for example. <b>moduleselector.js</b> <pre><code>(function() { function module(id name){ this.moduleid = id; this.modulename = name; this.topics = []; this.addtopic = function(topic){ this.topics.push(topic); } } module.prototype = new togglebutton(); module.prototype.constructor = module; var moduleselector = function (id) { this.initialize(id); }; var p = moduleselector.prototype = new createjs.container(); p.container_initialize = p.initialize; p.initialize = function (id) { this.container_initialize(); //..... }; window.moduleselector = moduleselector; }()); </code></pre> <b>togglebutton.js</b> <pre><code>(function() { var togglebutton = function(text) { this.initialize(text); //....code }; var p = togglebutton.prototype = new createjs.container(); p.container_initialize = p.initialize; p.initialize = function(text) { this.container_initialize(); }; window.togglebutton = togglebutton; }()); </code></pre>,javascript
java generic collection have the same erasure error i want to make the genericcollection generic obviously. i get this error: <pre><code>name clash: add(t) in gcollection and add(java.lang.object) in collection have the same erasure yet neither overrides the other </code></pre> collection <pre><code>public class collection { public object get(int i){ return null; } public void add(object o){ } } </code></pre> genericcollection <pre><code>public class genericcollection&lt;t&gt; extends collection { public t get(int i){ return (t) super.get(i); } public void add(t o){ super.add(o); } } </code></pre> maybe got some ideas,java
how to get the values in this object i have been trying to get the values from the below object without any luck. i know there are many answers out there but i am a visual person and they are not working for my layout. also how can i address the objects to change the values of ringalarm <pre><code>var strringalarm = { sq1 :{ringalarm: off alarmname: chime1 } sq2 :{ringalarm: no alarmname: chime2 } sq3 :{ringalarm: no alarmname: chime3 } sq4 :{ringalarm: no alarmname: chime4 } sq5 :{ringalarm: no alarmname: chime5 } sq6 :{ringalarm: no alarmname: chime6 } sq7 :{ringalarm: no alarmname: chime7 } sq8 :{ringalarm: no alarmname: chime8 } sq9 :{ringalarm: no alarmname: chime9 } sq10:{ringalarm: no alarmname: chime10 } sq11:{ringalarm: no alarmname: chime11 } sq12:{ringalarm: no alarmname: chime11 } }; object.getownpropertynames(strringalarm).foreach(function(val idx array) { console.log(val + -&gt; + val.ringalarm); } ) </code></pre>,javascript
location detail is not post on the server once network is lost and again connected in my application i am posting user s current location detail on the server at specified time interval. the issue is when network is disconnected and after some time when again reconnect then application stop posting location detail on the server. this is working perfect when i run the application from the xcode to device. but doesn t work when i directly run the application from the device. thanks reena,iphone
javascript does not execute as expected - facebook javascript sdk that is the body of a mvc 3 view that i have. it s about a facebook app that i want to create. the expected result is to have a pop-up window showing the name of the user entered the app. when i run the app nothing happens so no code is executed. so what is the mistake on this <pre><code>&lt;body&gt; &lt;div id= fb-root style= display: none &gt;&lt;/div&gt; &lt;script&gt; window.fbasyncinit = function () { fb.init({ appid: my app id // application id provided by facebook status: true // check login status cookie: true // enable cookies to allow the server access the session xfbml: true // parse xfbml }); // other initialization code here fb.api( /me function (response) { alert( your name is +; }); }; // load facebook javascript sdk asynchronously (function (d) { var js id = facebook-jssdk ref = d.getelementbytagname( script )[0]; if (d.getelementbyid(id)) { return; } js = d.createelement( script ); = id; js.async = true; js.src = // ; ref.parentnode.insertbefore(js ref); }(document)); &lt;/script&gt; @renderbody() </code></pre>,javascript
map function: anonymous function vs function expression why does passing an anonymous function into the <code>map</code> function work but attempting to pass a function expression throws an error <pre><code>arr = [2 4 6 8]; items = { return math.pow(x 2); }); console.log(items); // returns [4 16 36 64] squareit = function(x) { return math.pow(x 2); } otheritems =; console.log(otheritems); // returns uncaught referenceerror: x is not defined </code></pre>,javascript
javascript: how to copy reference properly i have array and two variables. these variables are meant to hold references to array items in fact to select new object and hold previously selected. this code makes selectedobject and prevselectedobject to be the same :( <pre><code>if(newselection) { if(this.prevselectedobject != newselection) { this.prevselectedobject = this.selectedobject; } this.selectedobject = newselection; } else { this.prevselectedobject = this.selectedobject; this.selectedobject = null; } </code></pre> guess this.prevselectedobject = this.selectedobject; actually puts in prevselectedobject variable reference to selectedobject. but i want to copy reference that is in selectedobject to prevselectedobject. there are dirty hacks for copy-by-value if value is string or int but what to do with references,javascript
js: dynamically create subproperties of non-existing property i want something like this: <pre><code>var myobj = {}; myobj[ a ][ b ].push({ c : d }); </code></pre> i want myobj to become: <code>{ a :{ b :[{ c : d }]}}</code> but i get an error <blockquote> cannot set property b of undefined </blockquote> yes i know i can create it step by step like that: <pre><code>var myobj={}; myobj[ a ]={}; myobj[ a ][ b ]=[]; myobj[ a ][ b ].push({ c : d }); </code></pre> but what if myobj already has some structure and i don t want to destroy it. e.g: <pre><code>var myobj={ a :{ e : f }}; </code></pre> if i write <code>myobj[ a ]={};</code> i ll lose data.<br> sure i can write <pre><code>if(myobj[ a ]==null){ myobj[ a ]={} } </code></pre> but it s too bulky! that would be great if i could just write smth like <code>myobj[ a ][ b ].push({ c : d });</code> without checking for null on every step.<br> any suggestions how to do this may be there is a way to override js native object or smth like that <br> thank you in advance!,javascript
view is not gone sometimes there is a very hard issue i m trying to pursue. in the <code>viewdidappear:</code> i have the following code: <pre><code>if(datasourcecount &gt; 0) { [scrollview sethidden:no]; uiview *ndview = [self.view viewwithtag:204]; [ndview removefromsuperview]; self.nodataview = nil; infobtn.hidden = no; } else { [scrollview sethidden:yes]; [[nsbundle mainbundle] loadnibnamed:@ nodataview owner:self options:nil]; self.nodataview.tag = 204; [self.view addsubview:self.nodataview]; infobtn.hidden = yes; } [super viewdidappear:animated]; </code></pre> the problem occurs on <code>if true</code> case very rarely and as a result on the device i can see the view that has been removed from superview - <code>ndview</code>. i was thinking that viewwithtag may return nil sometimes but this is not the case as i found out from debug. also tried to move <code>self.nodataview = nil</code> to <code>else</code> and found the issue again. is there any obvious or non-obvious mistake that i m doing here which i m not supposed the idea of this code snippet is to temporarily show some other view while data is not available.,iphone
what is a programmers reference book i am going to take a java application class and i have to purchase a java programming book. when i went to <a href= rel= nofollow >amazon</a> it showed that some of the people who purchased the book also bought a java reference book. what is the difference between the java programming book and a java reference book,java
how to develop iphone applications on windows platform(xp vista) hi folks can any one please let me know how to develop iphone applications on windows platform(xp vista).if so i have windows system with xp os how to install the software what is the software name and please let me know the blogs and free downloads for trail versions thank in advance jagadeesh,iphone
how to download an image from ftp using ftpclient i m using this code and try to download an png pic from server .this is code <pre><code>import java.awt.image.bufferedimage; import; import; import; import; import javax.imageio.imageio; import; public class nettest { public static void main(string[] args){ ftpclient client = new ftpclient( ); outputstream outstream; try { client.connect( server ); client.login( pass ); string remotefile = pages/page0001.png ; outstream = new fileoutputstream( c:\\asd.png ); client.retrievefile(remotefile outstream); } catch(ioexception ioe) { ioe.printstacktrace(); system.out.println( error communicating with ftp server. ); } finally { try { client.disconnect( ); } catch (ioexception e) { system.out.println( problem disconnecting from ftp server ); } } } } </code></pre> this code gives me no error but when i open the image it shows me invalid image .,java
why can t this be done <pre><code>class a { a(int x) { system.out.println( constructor a ); } } class b extends a { b() { system.out.println( constructor b ); } } public class c { public static void main(string args[]) { b b = new b(); } } </code></pre> it says constructor from class a can t be applied for given types.,java
iphone - volume/mute buttons what class is referenced in the volume/mute button popup sorry for the awful question but i can t seem to find it anywhere.,iphone
not able to install a python package from my old python version i am using old version of python (2.6) <pre><code>$ python --version python 2.6.6 </code></pre> i want to install module fabric installing from behind the proxy <pre><code>$ sudo pip install fabric==1.13.1 --proxy &lt;proxy&gt; </code></pre> getting error like <pre><code>downloading fabric-1.13.1-py2-none-any.whl (92kb) 100% |████████████████████████████████| 102kb 141kb/s collecting paramiko&lt;3.0 &gt;=1.10 (from fabric==1.13.1) using cached paramiko-2.4.0-py2.py3-none-any.whl collecting pyasn1&gt;=0.1.7 (from paramiko&lt;3.0 &gt;=1.10-&gt;fabric==1.13.1) using cached pyasn1-0.4.2-py2.py3-none-any.whl collecting bcrypt&gt;=3.1.3 (from paramiko&lt;3.0 &gt;=1.10-&gt;fabric==1.13.1) using cached bcrypt-3.1.4-cp26-cp26mu-manylinux1_x86_64.whl collecting cryptography&gt;=1.5 (from paramiko&lt;3.0 &gt;=1.10-&gt;fabric==1.13.1) using cached cryptography-2.1.4.tar.gz collecting pynacl&gt;=1.0.1 (from paramiko&lt;3.0 &gt;=1.10-&gt;fabric==1.13.1) using cached pynacl-1.2.1.tar.gz complete output from command python egg_info: download error on [errno 101] network is unreachable -- some packages may not be found! couldn t find index page for cffi (maybe misspelled ) download error on [errno 101] network is unreachable -- some packages may not be found! no local packages or working download links found for cffi&gt;=1.4.1 </code></pre> it was working previously (1 year back) i can not upgrade python due to legacy issue. looks like it is deprecated. need your help to resolve this.,python
how to remove white space characters from string in python while declaring <code>argstring</code> variable i use white spaces to format a code so it is easy to read later. so instead of typing: <pre><code>argstring= line1 line2 line3 </code></pre> i am using this instead: <pre><code>argstring= line1 line2 line3 </code></pre> the problem i have encounter is that later when <code>argstring</code> is written to output text file the extra white spaces used to format code are still preserved and written to the output text file. so the resulted output text file is written in a form: <pre><code>....line1 ....line2 ....line3 </code></pre> (where each period . represents white space character. how to remove the extra white spaces used purely for the code readability when a content of the string variable <code>argstring</code> is written to the text file <pre><code>import tempfile argstring= line1 line2 line3 writefile=tempfile.mkdtemp()+ /script.txt _file=open(writefile wb ) _file.write(argstring) _file.close() </code></pre>,python
problem with subviews of uitableviewcell i added a subviews to uitableviewcells its working fine but when i scroll up or down subviews are adding multiple times. i donno where i am wrong. here is my code: <pre><code>- (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { static nsstring *cellidentifier = @ mainpagecellview ; mainpagetablecellview *cell = (mainpagetablecellview *)[tableview dequeuereusablecellwithidentifier:cellidentifier]; if (cell == nil) { [[nsbundle mainbundle] loadnibnamed:@ mainpagetablecellview owner:self options:nil]; cell = mainpagetablecell; } [cell setnametext:[namesarray objectatindex:indexpath.row]]; [cell setpositiontext:[positionarray objectatindex:indexpath.row]]; [cell setcompanynametext:[companynamearray objectatindex:indexpath.row]]; [cell setdistancetext:[distarray objectatindex:indexpath.row]]; [cell setimageviewimage:[imagesarray objectatindex:indexpath.row]]; uiimage *halo = [uiimage imagenamed:@ h1.png ]; uiimageview *halov = [[uiimageview alloc] initwithimage:halo]; if(indexpath.row == 0) [cell addsubview: halov]; else if(indexpath.row ==2) [cell addsubview: halov]; else if(indexpath.row ==3) [cell addsubview: halov]; return cell; } </code></pre>,iphone
javascript generate a string contains 1m random number browser crash <pre><code>var text = ; var possible = 0123456789 ; for( var i=0; i &lt; 10000000; i++ ) text += possible.charat(math.floor(math.random() * possible.length)); </code></pre> each time i run this code the browser start to could i solve this because i need to use such long string to sort phone number(bitmap sorting). the forloop may works but it took a long time. so i think my problem is there any other way to make this faster than simple string concat.,javascript
subviews not loaded from nib with initwithnibname i ve got the code below in my rootviewcontroller (which is a uitableviewcontroller). this code is executed when the button in the navigation bar is clicked and then (in the simulator) the next view is shown. however the subviews (uitextlabels uibuttons) that are drawn in in the view managed by the tripdetailscontroller are not displayed. also in the navigation bar in the top of the screen the back button to the original view is not shown but when i click on the left side of the navigation bar it does transition back to the original view. <ul> <li>tripdetailscontroller.view is linked to the tripdetailsview (uiview) in interface builder</li> <li>tdcontroller does have a value so it looks as if it is loaded</li> <li>tripdetailscontroller is in a separate nib file</li> <li>using iphone sdk 2.2.1 (so not 3.0 yet)</li> </ul> code: <pre><code> tripdetailscontroller *tdcontroller = [[tripdetailscontroller alloc] initwithnibname:@ tripdetailscontroller bundle:nil]; [self.navigationcontroller pushviewcontroller:tdcontroller animated:yes]; [tdcontroller release]; </code></pre> in the tripdetailscontroller class i added the viewdidload method like this: code: <pre><code>- (void)viewdidload { [super viewdidload]; self.navigationitem.title = @ reis details ; nslog(@ subviews: %@ self.view.subviews); uilabel *l = [self.view.subviews objectatindex:0]; nslog(@ subview 0 bounds: %@ l.bounds); } </code></pre> the log messages below do show that the subviews are there but also that the bounds are not set: code: <pre><code>6/18/09 jun 18 2009 10:06:00 pm reisadvies[11226] subviews: ( &lt;uilabel: 0x56f250&gt; &lt;uilabel: 0x56f5a0&gt; &lt;uilabel: 0x56f6b0&gt; &lt;uilabel: 0x56f780&gt; ) 6/18/09 jun 18 2009 10:06:00 pm reisadvies[11226] subview 0 bounds: (null) </code></pre> in interface builder the label size tab does show values for x/y/w/h. feels like i have to trigger it to do some layout activities but call layoutsubviews in the viewdidload() does not help. any ideas what might be the problem here,iphone
array list sorting in java an array list contains some data that needs to be sorted. <pre><code>data: a1 a5 b1 a7 b3 </code></pre> after sort i need to be shown like below <pre><code>a1 a5 a7 b1 b3 </code></pre> please help on this.,java
removing more than two consecutive chars i want to remove any <code>char</code> which repeats more than two times consecutive. <pre><code>import re re.sub(r ([a-z])\1+ r \1 ffffffbbbbbbbqqq ) </code></pre> it s returning me <code>fbq</code> while i need <code>ffbbqq</code>. the goal is pre-process the string before doing a spell checking. what am i doing wrong,python
database: typeerror: cannot concatenate str and list objects <pre><code>`traceback (most recent call last): file line 317 in &lt;module&gt; crawl(initfighter=fighter k=4) file line 114 in crawl write_page_to_database(initfighterurl cur) file line 292 in write_page_to_database write_fights_to_database(fights cur) file line 211 in write_fights_to_database fightid = hash(bothfighters+fight[ event ]) typeerror: cannot concatenate str and list objects ` </code></pre> what is wrong with these lines,python
javascript check for max/min/average number from a record set <pre><code>function lab09unknownloopcountpart2() { //constants var one_hundred = 100; var zero = 0; //variables var employeehourlywage; var hourlymaximum = zero; var hourlyminimum = zero; var totalhourlywage = zero; var records; var counter = zero; var average; records = openemployeepayrollrecords(); while (records.readnextrecord()) { employeehourlywage = records.getemployeehourlywage(); totalhourlywage += employeehourlywage; counter++; average = totalhourlywage / counter; if (employeehourlywage &lt; one_hundred) { hourlymaximum = employeehourlywage; } if (employeehourlywage &lt; one_hundred) { hourlyminimum = employeehourlywage; } } document.write( average hourly wage: + average + &lt;br /&gt; ); document.write( maximum hourly wage: + hourlymaximum + &lt;br /&gt; ); document.write( minimum hourly wage: + hourlyminimum + &lt;br /&gt; ); </code></pre> } the record set is simply numbers from 15 - 30. i have to sort through them and find the maximum minimum and average. i know that my two if statements are incorrect and i m wondering how to check this <strong>without</strong> using math.min and math.max. thanks.,javascript
python module not found because import statement is in other file than the one being executed in the following structure: <pre><code>src: model: - - exceptions: - - </code></pre> i m running <code></code> from the terminal. in my <strong></strong> i have the following import: <pre><code>from exceptions.exceptions import zeroerror overlaperror argumenterror proximityerror </code></pre> this line causes an error when running <code></code>: <pre><code>traceback (most recent call last): file line 3 in &lt;module&gt; from model.boardmodel import board file /users/sahandzarrinkoub/documents/programming/pythonfun/bouncingballs/balls/src/model/ line 5 in &lt;module&gt; from exceptions.exceptions import zeroerror overlaperror argumenterror proximityerror modulenotfounderror: no module named exceptions </code></pre> what is the correct way to solve this problem should i change the import statement inside <code></code> to <code>from model.exceptions.exceptions import zeroerror....</code> that doesn t feel like a sustainable solution because what if i want to use <code></code> in another context let me her your thoughts. edit: i changed the structure to: <pre><code>src: model: - - - exceptions: - - - </code></pre> but still i get the same error.,python
twitter+linkedin issue in iphone i have an application with facebook twitter and linkedin integrating to it.but when i am using twitter and linkedin it is causing some problem.i found some results in stack saying remove the library files of linkedin sdk and add the source files of it with oauth files from twiiter sdk then it works ok for linkedin then i integrate all twitter code then project run ok without error but for twitter login interface it shows page not found but then notice that i have given the same key and secret to both linkedin and twitter after changing them it solved but can u please suggest how to do is so confusing.thats why i am going for a clear picture.any help will be greatly appreciated,iphone
error while counting number of character lines and words in java i have written the following code to count the number of character excluding white spaces count number of words count number of lines.but my code is not showing proper output. <pre><code>import*; class filecount { public static void main(string args[]) throws exception { fileinputstream file=new fileinputstream( sample.txt ); bufferedreader br=new bufferedreader(new inputstreamreader(file)); int i; int countw=0 countl=0 countc=0; do {; if((char)i==( )) countw++; else if((char)i==( \n )) countl++; else countc++; }while(i!=-1); system.out.println( number of words: +countw); system.out.println( number of lines: +countl); system.out.println( number of characters: +countc); } } </code></pre> my file sample.txt has <pre><code>hi my name is john hey whts up </code></pre> and my out put is <pre><code>number of words:6 number of lines:2 number of characters:26 </code></pre>,java
how to open maps app from my code to show directions hi.. i have to show directions between two coordinates. i d like to open maps app passing the start and end coordinates from my code. i don t want to open it in the google maps which opens in browser(safari). i tried that method. that was working perfect. <pre><code>nsstring* urlstr = [nsstring stringwithformat: @ saddr=%f %f&amp;daddr=%f %f s_lat s_long d_lat d_long]; [[uiapplication sharedapplication] openurl: [nsurl urlwithstring:urlstr]]; </code></pre> but i want to open iphone maps app. how can i do this is this possible any help will be appreciated.,iphone
unable to parse relevantdate error while parsing pkpass in ios not able to create pass <pre><code>error domain=pkpasskiterrordomain code=1 the pass cannot be read because it isn t valid. userinfo=0x1405a480 {nsunderlyingerror=0x14059950 unable to parse relevantdate 2013-12-05t06:00:00.000z as a date. we expect dates in w3c date time stamp format either complete date plus hours and minutes or complete date plus hours minutes and seconds . for example 1980-05-07t10:30-05:00. nslocalizeddescription=the pass cannot be read because it isn t valid.} </code></pre> can anyone help me on this,iphone
detecting if string iterator is a blank space i m attempting to write a small block of code that detects the most frequently occurring character. however i ve become stuck on not being able to detect if a value is blank space. below is the code i have: <pre><code>text = hello world! ## user lower() because case does not matter setlist = list(set(textlist.lower())) for s in setlist: if s.isalpha() and s != : ## do something else: setlist.remove(s) </code></pre> the problem is that set list ends with the following values: <pre><code>[ e d h l o r w ] </code></pre> i ve tried multiple ways of detecting the blank space with no luck including using strip() on the original string value. isspace() will not work because it looks for at least one character.,python
python connect 4 game <pre><code>columns = 5 rows = 4 def empty_board(): board_rows =[ | \t\t | ] * rows board_columns = [ ___ ] * columns for i in range (rows): print(board_rows[i]) print( + end= ) for i in range(columns): print(board_columns[i] end= ) print print( + ) for i in range(columns): column_number = i+1 print( + str(column_number) end = ) def column_choice(): player = 1 if player % 2 != 0 : column = input( player 1 please choose a column to make your next move ) else: column = input( player 2 please choose a column to make your next move ) player += 1 return column def new_board(column): moves = 0 column = int(column) - 1 if moves % 2 == 0: key = x else: key = o board_rows = [ | \t\t | ] * rows board_columns = [ ___ ] * columns for i in range (rows): print(board_rows[i]) board_rows.pop(column) board_rows = board_rows.insert(column key) print(board_rows) print( + end= ) for i in range(columns): print(board_columns[i] end= ) print( + ) for i in range(columns): column_number = i+1 print( + str(column_number) end = ) if __name__ == __main__ : print() print( welcome to connect 4 ) print() new_board(column_choice()) </code></pre> i have to create a connect 4 board with the given column and row dimensions (for now). i currently have the board created but i can t quite figure out how to get the <code>x</code> or <code>o</code> to go in the correct spot. for instance right now when i run the program the <code>x</code> will go in the whole column. if you could offer any help i would appreciate it!,python
internationalization in iphone application my application run vary well but now when uiswitch button is on at that time i have to convet whole application in spanish when off then convert in to english how it possible plz give any replay for that.,iphone
aggregating similar objects using comparator without consistency with equals() i have a set of immutable objects that implement equals() that strictly compare the member variables they hold. two objects are identical if the member variables are equal. hashcodes() are consitent with this. i want to be able to aggregate these objects according to looser definitions of similarity. i was thinking of using comparator for this so that i could define a bunch of ad hoc similarity rules but the javadoc states that comparator should be consistent with equals. is is ok to break the comparator contract with equals() to achieve this or is there some better method/pattern/strategy for aggregating objects according to some similarity rules examples may include: <ul> <li>locations: equals() returns true if latlng and place name exactly equal but comparator returns 0 if latlng within say 25m/50m/100m regardless of place name etc or if only place names are equal regardless of latlng.</li> <li>dates: equals() returns true if long millis are equal but comparator returns 0 if on same day/month/year etc..</li> <li>strings: equals return true if equalsignorecase is true but comparator may removes spaces/special characters to reduce to some canonical form then run equals etc.</li> </ul> many thanks in advance riz,java
how do i eliminate conditional from code how do i eliminate the ternary operator from the code below i m looking for something using only integer operators (shifts additions etc). <pre><code>a = (a &lt; 0) (-a * 2) - 1 : (a * 2) </code></pre>,java
rounding off number shows different result on positive and negative numbers i ve rounding the number into 2 decimal places: <pre><code>function round(num decimals) { var factor = math.pow(10 decimals); return math.round(num * factor) / factor; } round(-5.255 2); -5.25 function round(num decimals) { var factor = math.pow(10 decimals); return math.round(num * factor) / factor; } round(5.255 2); 5.26 </code></pre> but i ve observed that it is giving different result when it is positive or negative. why is this happening and how can this be corrected,javascript
write code that assigns to double b the result of rounding double a to the nearest integer i don t know what to do... i have two doubles and i need b to be the result of a rounded to the nearest integer... <pre><code>// enter a value to test here double a = ; double b; // enter your code here </code></pre>,java
identify datetime64 columns in a dataframe using python i need to identify which of the columns in a dataframe (having many columns) are datetime64[ns] . i imported the csv file and used df.dtype() syntax to display the datatypes.however the output shows dtype as object instead of datetime64 for the columns that have dates. please help i am a beginner (i have imported from datetime import datetime ).,python
why is 4 not an instance of number just curious: <ul> <li>4 instanceof number => false</li> <li>new number(4) instanceof number => true </li> </ul> why is this same with strings: <ul> <li><code> some string instanceof string</code> returns false</li> <li><code>new string( some string ) instanceof string</code> => true</li> <li><code>string( some string ) instanceof string</code> also returns false</li> <li><code>( some string ).tostring instanceof string</code> also returns false</li> </ul> for object array or function types the instanceof operator works as expected. i just don t know how to understand this. [<strong>new insights</strong>] <pre><code> = function() { var test = arguments.length [] : null self = this.constructor; return test !!(test.filter(function(a){return a === self}).length) : ( || (string(self).match ( /^function\s*([^\s(]+)/im ) || [0 anonymous_constructor ]) [1] ); } // usage var newclass = function(){}; // anonymous constructor function var some = function some(){}; // named constructor function (5).is(); //=&gt; number hello world .is(); //=&gt; string (new newclass()).is(); //=&gt; anonymous_constructor (new some()).is(); //=&gt; some /[a-z]/.is(); //=&gt; regexp 5 .is(number); //=&gt; false 5 .is(string); //=&gt; true </code></pre>,javascript
"why is e.preventdefault(); only working once i have a form which uses e.preventdefault to prevent it from refreshing however if i use the form to submit something again the page refreshes... i have had a look as to why this is happening but i can t figure out why it works the first time but not the second... or third... etc... i have attached my code below. thanks in advance. <div class= snippet data-lang= js data-hide= false data-console= true data-babel= false >
<div class= snippet-code >
<pre class= snippet-code-js lang-js prettyprint-override ><code>// scripts
// store element in dom
const searchbutton = document.getelementbyid( submit-button );
// add event listener to button
searchbutton.addeventlistener( click searchfornews);
// function to search for news
function searchfornews(e) {
// store element in dom
const searchform = document.getelementbyid( search-form );
// retrieve the value in the input field
const searchterm = searchform.value;
// log to console
console.log( you searched for + searchterm);
// token
const token = xxxxxxxx;
const urlarray = new array;
// create the urls to search for the news
const guardianurl = token= + token + &amp;format=json&amp;sort=crawled&amp;q= + searchterm + ;
const bbcurl = token= + token + &amp;format=json&amp;sort=crawled&amp;q= + searchterm + ;
const telegraphurl = token= + token + &amp;format=json&amp;sort=crawled&amp;q= + searchterm + ;
// push each url in to the array
// declare element
const headerwrapper = document.getelementbyid( header-wrapper );
// add class to headerwrapper
headerwrapper.classlist.add( header-small );
// templates for news sources
guardiantemplate = &lt;div id= theguardian data-source= class= news-wrapper &gt;&lt;div class= source-name &gt;&lt;p&gt;the guardian&lt;/p&gt;&lt;/div&gt;&lt;/div&gt; ;
bbctemplate = &lt;div id= bbc data-source= class= news-wrapper &gt;&lt;div class= source-name &gt;&lt;p&gt;bbc news&lt;/p&gt;&lt;/div&gt;&lt;/div&gt; ;
telegraphtemplate = &lt;div id= telegraph data-source= class= news-wrapper &gt;&lt;div class= source-name &gt;&lt;p&gt;the telegraph&lt;/p&gt;&lt;/div&gt;&lt;/div&gt; ;
var articlewrapper = document.getelementbyid( article-wrapper );
articlewrapper.innerhtml = ;
const searchedtemplate = &lt;div class= searched-for &gt;&lt;h1&gt;you searched for + searchterm + &lt;/h1&gt;&lt;/div&gt; ;
// insert template in to header wrapper element
headerwrapper.innerhtml += searchedtemplate;
// insert templates in to element
articlewrapper.innerhtml += guardiantemplate;
articlewrapper.innerhtml += bbctemplate;
articlewrapper.innerhtml += telegraphtemplate;
// for loop to go through the url array
for (let i = 0; i &lt; urlarray.length; i++) {
// declare a new request
const newsreq = new xmlhttprequest();
// open the request get urlarray[i] true);
// function to run when loading
newsreq.onload = function() {
// if the status is between 200 and 399
if (this.status &gt;= 200 &amp;&amp; this.status &lt; 400) {
// request is successful
// parse the response
const res = json.parse(this.response);
// enter the posts object
const posts = res.posts;
// for look to go through the response
for (let i = 0; i &lt; posts.length; i++) {
// get the name of the site
const source = posts[i];
// get image
const image = posts[i].thread.main_image;
// get the title post
var title = posts[i].title;
// split using the | symbol take the first string in array
var title = title.split( | )[0];
// take the string and replace = bbc news with nothing
var title = title.replace( - bbc news );
// trim excess spaces around string
var title = title.trim();
const articleurl = posts[i].thread.url
// log to console
console.log(title + | + source + | + articleurl);
var template = &lt;a class= link href= + articleurl + &gt;&lt;div class= article &gt; +
&lt;img class= image src= + image + &gt; +
&lt;div class= title &gt; + title + &lt;/div&gt; +
&lt;/div&gt;&lt;/a&gt; ;
// declare element
var newswrapper = document.queryselectorall( .news-wrapper );
// look through the newswrapper element to find elements that match source names
var currentwrapper = [...newswrapper].find((wrapper) =&gt; wrapper.dataset.source === source);
// create fragment
var articlefragment = document.createrange().createcontextualfragment(template);
// add the fragment to the correct wrapper
} else {
// we reached our target server but it returned an error
newsreq.onerror = function() {
// there was a connection error of some sort
<pre class= snippet-code-css lang-css prettyprint-override ><code>/* stylesheet */
body {
font-style: normal;
font-weight: 600;
font-size: 18px;
color: #242424;
input {
font-family: graphik ;
* {
box-sizing: border-box;
font-family: graphik ;
.header-wrapper {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100vw;
height: 100vh;
transition: height 0.5s ease;
.header-small {
height: 300px;
.logo-wrapper {
width: 100%;
max-width: 500px;
margin-bottom: 25px;
.logo {
max-width: 100%;
.search-wrapper {
width: 100%;
max-width: 500px;
.form-wrapper {
display: flex;
flex-direction: row;
position: relative;
width: 100%;
max-width: 500px;
.search-form {
width: 100%;
text-align: center;
padding: 10px;
border-radius: 50px 0 0 50px;
outline: none;
border: 1px solid lightgrey;
border-right: none;
.submit-button {
border-radius: 0 50px 50px 0;
border: 1px solid lightgrey;
border-left: none;
background-color: #fff;
padding: 10px;
width: 45px;
height: 43px;
background-image: url(/assets/images/search.svg);
background-position: center;
background-repeat: no-repeat;
background-size: 20px;
transition: 0.25s ease;
.submit-button:hover {
cursor: pointer;
background-size: 25px;
.article-wrapper {
display: flex;
flex-direction: row;
.news-wrapper {
width: 33.33%;
margin-left: 20px;
margin-right: 20px;
.source-name {
width: 100%;
text-align: center;
.image {
max-width: 100%;
.article {
margin-bottom: 20px;
.title {
padding: 10px;
.link {
text-decoration: none;
color: #242424;
@media screen and (max-width: 512px) {
.header-wrapper {
padding: 40px;
.article-wrapper {
flex-direction: column;
.news-wrapper {
width: 100%;
<pre class= snippet-code-html lang-html prettyprint-override ><code>&lt;!doctype html&gt;
&lt;html lang= en &gt;
&lt;!-- character encoding --&gt;
&lt;meta charset= utf-8 &gt;
&lt;!-- viewport --&gt;
&lt;meta name= viewport content= width=device-width initial-scale=1 &gt;
&lt;!-- optional
&lt;meta name= author content= name &gt;
&lt;meta name= description content= description here &gt;
&lt;meta name= keywords content= keywords here &gt;
&lt;!-- title of page --&gt;
&lt;link rel= stylesheet href= css/style.css type= text/css &gt;
&lt;link rel= stylesheet href= css/normalize.css type= text/css &gt;
&lt;!-- web fonts --&gt;
&lt;!-- &lt;link rel= stylesheet href= css/fonts.css type= text/css &gt; --&gt;
&lt;div id= header-wrapper class= header-wrapper &gt;
&lt;div class= logo-wrapper &gt;
&lt;img class= logo src= assets/images/logo.png alt= logo &gt;
&lt;div class= search-wrapper &gt;
&lt;div class= form-wrapper &gt;
&lt;form class= form-wrapper &gt;
&lt;input id= search-form class= search-form type= text placeholder= what s in the news today &gt;
&lt;input id= submit-button class= submit-button type= submit value= &gt;
&lt;div class= article-wrapper id= article-wrapper &gt;
&lt;!-- scripts --&gt;
&lt;script src= js/script.js type= text/javascript &gt;&lt;/script&gt;
how to force a method to be overridden in java i have to create a lot of very similar classes which have just one method different between them. so i figured creating abstract class would be a good way to achieve this. but the method i want to override (say method foo()) has no default behavior. i don t want to keep any default implementation forcing all extending classes to implement this method. how do i do this,java
defining attributes of a class in python how should i define the attributes of a class <pre><code>class example: def __init__(self n m): self.n=n self.m=m </code></pre> or in this way: <pre><code>class example: m=0 n=0 def __init__(self n m): self.n=n self.m=m </code></pre> if i define an attribute outside the constructor is it a static variable,python
javascript global property definition why is it possible to do this: <pre><code>test: { one: 1; two: 2; three: 3; } </code></pre> and not possible to do this: <pre><code>var test = { one: 1; two: 2; three: 3; } </code></pre> by default the properties are separated by comma but in the first example it is working in the second i get an error the question is why the first one is working if that is a wrong json hm,javascript
python - if a user enters \n in an input and the varible is printed the \n makes a new line for example if i did this: <pre><code>test=input( text: ) print(test) </code></pre> and then set test as<code>hello\nhow are you </code> and then call test() i want it to appear as this: <pre><code>hello how are you </code></pre> and not <pre><code>hello\nhow are you </code></pre> is this possible -darth,python
presenting modalviewcontroller turns the orientation of my app on start up i m trying to only support landscape. there s a new requirement to show this dialog box that explains some things about our app the first time. so in my first view controller that gets launched in viewdidload i have this code: <pre><code>bool showfirsttimeuse = [[nsuserdefaults standarduserdefaults] boolforkey:@ showfirsttimeuse ]; if (!showfirsttimeuse) { firstuseviewcontroller *tvc = [[firstuseviewcontroller alloc] initwithnibname:@ firstuseviewcontroller bundle:nil]; tvc.modalpresentationstyle = uimodalpresentationformsheet; tvc.modaltransitionstyle = uimodaltransitionstylefliphorizontal; [self presentmodalviewcontroller:tvc animated:yes]; [tvc release]; } </code></pre> then in the firstuseviewcontroller i have this defined: <pre><code>- (bool)shouldautorotatetointerfaceorientation:(uiinterfaceorientation)interfaceorientation { // return yes for supported orientations return uiinterfaceorientationlandscapeleft | uiinterfaceorientationlandscaperight; } </code></pre> in ib i have not changed any of the default settings. i basically just dropped a uiwebview to the upper left hand side of the screen to show my data and connected an outlet to it so i can show formatted text easily. when i run my app now the presentation of this view controller causes my app to start in portrait rather than landscape. how do i fix this thanks.,iphone
get time different (minutes) in javascript how do i calculate the difference in minutes given two strings. for example say i have <pre><code>11:00 11:30 </code></pre> but of course the second string could be 12:11 so i can t subtract just the minutes.,javascript
get all the coincidences with given value from object array i have this array of objects: <pre><code>var hola = [{key:id desc:description }]; // they are filled with data with ajax from a table </code></pre> this are the values right now <pre><code> var hola = [ {key: al-32021611 descc: 7500 } {key: al-32021612 descc: continental } {key: al-32021612 descc: r3 } {key: al-32021612 descc: 7500 } ]; </code></pre> what i need is that with a given value i get for example <pre><code> newarr= {key:al-32021612}[descc: continental r3 7500 ] </code></pre> but from this newarr i just need the key like some kind of index to get all its descc values in a var and im really lost and here is why <pre><code>$.each(newarr function (i data) { trhtml = &lt;div class= three_col_to_one_col categories &gt; + idval[i] + &lt;/div&gt; }) </code></pre> i will use this newarr as the length of this each and print its content but i just need this descc values for that its complicated and messy but im new and i might get downvotes but thanks for reading me anyway,javascript
additonal validations in onsubmithandler javascript when user clicks the submit button; i need to call a function deleteorphanrecords that prompts the user to delete them when there are any orphan records to be deleted. origional code only displays the error message for the orphan records and prevents the user from further processing. <pre><code>&lt;form onsubmit= return onsubmithandler() action= /admin/changesrecorded.html method= post id= submitform &gt; </code></pre> i added that additional function to the onsubmithandlerfunction like this - <pre><code>function onsubmithandler() { deleteorphanrecords(); // more blackbox code that only displays the alert but does not allow the user to delete the orphan records. return true; } </code></pre> the deleteorphanrecords function is working fine but i have a loading window that blocks the user from clicking the yes/no buttons on the main page when any orphan records are found. so the page eventually ends up showing the alert. how should i call the deleteorphanrecords so i can delete the records and simultaneously submit the form too. thanks in advance!,javascript
java convert from decimal to 8-bit binary i wrote simple java code to convert from decimal to 8-bit binary: sorry for this stupid question <pre><code> 1 int dec=1; 2 string result= ; 3 string reverse = ; 4 while(dec!=0) 5 { 6 result+=dec%2; 7 dec=dec/2; 8 } 9 //8-bit binary 10 system.out.println( dec length is : +result.length()); </code></pre> // int j=8-result.length(); // for(int i=0;i <pre><code> 11 for(int i=0;i&lt;(8-result.length());i++) 12 { 13 result+=0; 14 system.out.println( * ); 15 } 16 system.out.println( 8-bit before reverse: +result); 17 for(int i = result.length() - 1; i &gt;= 0; i--) 18 { 19 reverse = reverse + result.charat(i); 20 } 21 system.out.println( 8-bit representation: +reverse); </code></pre> the result was : dec length is :1 * * * * 8-bit before reverse:10000 8-bit representation:00001 but when i remove line 13 (result+=0;) the compiler print 7 asterisk(*) what is the reason for that length of result will update every time,java
how do i remove duplicate ids <pre><code>&lt;td id= table_line_0 &gt; &lt;input id= btnadd0 type= button value= + onclick= newline() &gt; &lt;/td&gt; &lt;td id= table_line_0 &gt; &lt;input id= btnadd1 type= button value= + onclick= newline() &gt; &lt;/td&gt; </code></pre> i need a javascript function to remove the two id (table_line_0)... tks!! <pre><code>function removeid(id) { ... i do not know what to do to find duplicate id .. line_table = document.getelementbyid(id); line_table.parentnode.parentnode.removechild(line_table.parentnode); } </code></pre> i have two tr with same id ... i want to remove the tr with the same id..,javascript
why is there no directory class the file class contains methods that are applicable only to directories and just return null for regular files. why are they not defined as separate classes sharing an abstract parent,java
how to dynamically create directories and output files into them python i have a python script that is trying to create a directory tree dynamically depending on the user input. this is what my code looks like so far. <pre><code>if make_directories: os.makedirs(outer_dir) os.chdir(outer_dir) for car in cars: os.makedirs(car) os.chdir(car) #create a bunch of text files and do other stuff os.chdir( ../ ) os.chdir( ../ ) </code></pre> i was wondering if there was a better way to do this i don t know if this is bad convention to keep changing directories like this. note: cars is a list of car names that the user provides outer_dir is a directory name that is also provided by the user,python
how can i let the users of my python hangman game input their own words i have been stuck on this for a while now and i can t figure out what to do. i know that it will probably involve creating an empty list and then adding the words to the list but i haven t got a clue when it comes to retrieving the words as i have never done this before. the code itself works it s just adding this new function i m having trouble with. <pre><code>import random import sys #importing both random and time modules print( hello! ) playagn = yes animalnames = [ wildebeest wolverine woodlouse woodpecker yak zebra ] #this is the list of words that the user will have to guess if they play the game multiple times while playagn == yes : secretword = random.choice(animalnames) #this line tells the computer to randomly select one of the words in the list animalnames lives = 6 #defining how many lives the user has guessedletters = [] print( okay!\n lets play hangman!! ) while lives &gt; 0: inword = false #user has not guessed word yet so the boolean value is automatically off (false) print( you have lives lives ) #tells the user how many lives they have left guessedletter = input( guess a letter: ) if len(guessedletter) &gt; 1: print( error! please only enter 1 letter at a time ) #if the user tries to guess something longer than 1 character the computer displays a message asking to only enter 1 letter at a time elif guessedletter in guessedletters: print( sorry you have already guessed this letter. try again ) #if the user tries to guess a letter that has already been guessed the computer displays a message telling the user to choose another letter as they have already chose this one else: guessedletters+=str(guessedletter) #adds the guessed letter to guessedletters variable print( you have guessed: ) for letter in guessedletters: print(letter.upper() ) #prints the letters already guessed in uppercase shownword = for letter in secretword: if letter in guessedletters: shownword +=str(letter) #if the letter is in guessedletters then add the letter to shownword(word displayed to user) if letter == guessedletter: inword = true #inword is true as the guessed letter is in the secret word else: shownword+=str( _ ) #the computer is now adding the underscores too the word being displayed to the user print(shownword) #the computer prints the word with the letters that the user has guessed so far (word including underscores for not yet guessed characters) if _ not in shownword: print( congratulations you won! the word was shownword ) #if there are no underscores(meaning the word is completed) tell the user they have won the game break elif inword == false: #the guessed word is not in the secret word so the boolean value is now off (false) print( no luck guessedletter is not in my word ) lives -= 1 #deducts a life for the wrong letter being guessed and also displays a message telling the user that the letter just guessed isn t in the secret word if lives == 0: print( you have run out of lives. the word was secretword ) #if the user runs out of lives and still hasn t guessed the word tell them they failed to beat the game and also tell them the word while true: playagn = input( would you like to play again yes/no: ) if playagn == no : print( okay\n goodbye! ) break elif playagn == yes : break </code></pre> thanks a lot to anyone who can help figure this out :),python
how do external js work from what i ve read this should work why doesn t it i m having a very simple problem understanding the scope of variables with external javascript pages. from what i read if i call an external sheet all global functions and variables should be able to be accessed. i can t seem to get it to work. knowing the right question to ask to search is the hard part and i could comb through the internet for days for a problem someone could probably explain easily and quickly. i have seen something simliar in this tutorial <a href= rel= nofollow noreferrer ></a> i searched quickly stack found this: <a href= >what is the scope of variables in javascript </a> and even as i write this i m looking for the answer. simply i have an external sheet in the same directory and the file name is trial.js. then i have an index.html simply trying to use the global function from the external trial.js to the index page. this is possible according to the tizag tutorial using a function in the button onclick attribute. also many frameworks work on this principle too right although i know they are a bit more sophisticated using $(a)&lt;~~~references or something. thanks for anyone s help i ll continue to look but hopefully the internet can help!! localhost/trial.js: <pre><code>function trysomething(){ alert( trying ); } </code></pre> localhost/index.html: <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;objects222&lt;/title&gt; &lt;script src= trial.js &gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;script type= text/javascript &gt; trysomething(); &lt;/script&gt; hello &lt;/body&gt; &lt;/html&gt; </code></pre> it was originally in resource but i wanted to make it even simplier. using firefox and chrome doesn t work for me those who say it s working upon loading the page you get an alert that says trying anyone any ideas why it might not be working locally. i cleared all my cache and tried renaming to force upload. also used chrome firefox and ie still no alert on load @ localhost.,javascript
how to launch a 32-bit java process from a 64-bit java process without hardcoding paths i have a 64-bit java application and i would like to run a particular jar application in 32-bit mode. for testing i have done this in a disposable class: <pre><code>public class invoke32bit { public static void main(string[] args) { try { runtime.getruntime().exec( \ c:\\program files (x86)\\java\\jre7\\bin\\java.exe\ -jar c:\\dev\\test.jar ); } catch (exception e) { e.printstacktrace(); } } } </code></pre> and it works...but how can i avoid hardcoding the java path the machines that will be using this application will have both 64-bit and 32-bit jre s installed (this application is used internally and we don t have to worry about anyone else using it) one approach i ve thought of is to provide a config file to allow users to enter the path to 64-bit and 32-bit java but if there was a way to automate this that would be better.,java
try-surrounded imports and catching keyboardinterrupt i m seeing a lot of the following pattern in a codebase i m checking out at the moment: <pre><code>try: import modulea import moduleb from custom.module.a import ax from custom.module.a import ay except keyboardinterrupt: sys.exit() </code></pre> haven t seen it before. what s this guarding against,python
java - looping in try-catch block i am working on writing a file reader and the idea is to have the user enter a number that represents the line number from the text file. the variable that holds this number is of type <code>int</code>. however when the user enters a <code>string</code> instead java throws the <code>inputmismatchexception</code> exception and what i want is to have a loop in the <code>catch</code> clause where i will be looping until the user enters a valid value i.e. an <code>int</code>. the skeleton looks like this: <pre><code> public void _____ throws ioexception { try { // prompting user for line number // getting number from keyboard // do something with number } catch (inputmismatchexception e) { // i want to loop until the user enters a valid input // when the above step is achieved i am invoking another method here } } </code></pre> my question is what are some possible techniques that could do the validation thank you.,java
table view property in iphone how to change the colour of text of each row in tableview in iphone anyone know about it then please give me the guidance. thanks in advance.,iphone
implementing uitableview sections from an nsdictionary objects i want to use an nsdictionary to populate a table view. are there any tutorials to show me how this is done.,iphone
to hide the panel based on text the below mentioned script working properly (1) but if i put elseif condition its not working(2) how can i use elseif condition step 1 <pre><code>function cl_indexchange(sender eventargs) { var pnl = document.getelementbyid( pnlschedule ); var item = eventargs.get_item(); if (item.get_text() == call back later (cbl) ) { = block ; } else { = none ; } } </code></pre> step 2 <pre><code>function cl_indexchange(sender eventargs) { var pnl = document.getelementbyid( pnlschedule ); var item = eventargs.get_item(); if (item.get_text() == call back later (cbl) ) { = block ; } else (item.get_text() == call back after explanation (cbe) ) { = block ; } elseif (item.get_text() == call back after explanation (cbe) ) { = block ; }elseif { = none ; } } </code></pre>,javascript
highlight a text in web view i am using a html page in the web view. i want to track the location of the html page when i tap on the webview.basically i want to mark the selected text in the html page.please help me out as soon as possible. thanks in advance.,iphone
javascript solution for anagram of a palindrome i was asked to implement the same question as this in an interview recently: <a href= ></a> i could not provide an answer but am interested to know the javascript solution.,javascript
when using compareto for strings returns 10 all the time compareto don t give me -10 for bigger argument. (when the string is equal with argument then i get 0). <pre><code> string str2 = strings are immutable ; string str3 = int is a ; int result = str3.compareto( str2 ); system.out.println(result); result = str2.compareto( str3 ); system.out.println(result); </code></pre> if you change the size of str2 or str3 the return number is the same. why is that,java
how to add activity indicator as subview to uibutton can we add activity indicator as subview to uibutton if yes then plz tell me how to do that i used [button addsubview:activityindicator]; not working...,iphone
operation on different data types i ve been trying to figure out what is the result of for example adding <code>int</code> and <code>float</code> parameters together or <code>log2(x) + abs(y)</code> <code>sqrt(x) + true</code> etc. how does python deal with those kind of operations and why where can i find information about this,python
send message to server java i m creating chat program. at first i send message to server from client and server should get message but the message is not sent to the server until i shut down client. <em>here is my code:</em> <strong>client:</strong> <pre><code> private socket client; private thread runclient; private jbutton send; private int port=8000; private string host= localhost ; public void init() {//here we connecting to server send=new jbutton(); send.setfont(new font( times new roman font.bold 15)); send.setlocation(575 text.getheight()+15);//395 send.setbordercolor(color.cyan); send.setforeground(color.white); send.settext( send ); send.setsize(30 70); send.addactionlistener(new actionlistener() { @override public void actionperformed(actionevent e) { sendbutton_click(e); } }); try { inetaddress address = inetaddress.getbyname(host); client = new socket(address port); system.out.println( client started. port: +port+ \n ); }catch(exception e){ system.out.println( error: +e); } } public void sendbutton_click(actionevent e) {//here we sending message to server string sendmessage = hi ; try { sendmessagetoserver(client sendmessage);//sending message to server } catch (ioexception e1) { e1.printstacktrace(); } system.out.println( message sent to the server : +sendmessage); } } private void sendmessagetoserver(socket socket string message) throws ioexception { bufferedwriter writer = new bufferedwriter(new outputstreamwriter(socket.getoutputstream())); writer.write(message); writer.flush(); } </code></pre> <strong>here is server:</strong> <pre><code> private int port=8000; public void init() {//here we starting server and starting thread try { serversocket = new serversocket(port); system.out.println( server on. port: +port+ \n ); } catch (ioexception e1) { e1.printstacktrace(); } runserver = new thread() { public void run() { serverloop(); } }; runserver.start(); } public void serverloop() {//here we should receive message.. while(true) { system.out.println( server loop ); try { socket clientsocket = serversocket.accept(); inputstreamreader inputstreamreader = new inputstreamreader(clientsocket.getinputstream()); bufferedreader bufferedreader = new bufferedreader(inputstreamreader); printwriter printwriter = new printwriter(clientsocket.getoutputstream() true); string line = ; boolean done = false; while (((line = bufferedreader.readline()) != null) &amp;&amp;(!done)){ system.out.println( received from client: + line); if (line.comparetoignorecase( exit ) == 0) done = true; } } catch (exception e){ e.printstacktrace(); } } } </code></pre>,java
get json data from a posted uri in postman in java i have been trying to get <code>json</code> data but it seems i am using the wrong syntax. what syntax is appropriate this is my code <pre><code>@path( /jsondata ) @post @consumes( application/json ) @produces( application/json ) public jsonobject personal(@jsonparam( )jsonobject json) throws jsonexception{ string name = json.getstring( name ); string age = json.getstring( age ); string msg = you entered two things ; string doc = {\ name\ :\ +name+ \ \ age\ :\ +age+ \ \ msg\ :\ +msg+ \ } ; jsonobject outjson = new jsonobject(doc); return outjson; } </code></pre> am getting error on the fifth line at <code>@jsonparam</code>. what should i do. and how do i get the name and age from the json,java
#pragma omp critical vs cpu 100% usage i have wrote a program with open-mp in visual studio 2012 and i have some problem.this is my code: <pre><code> #pragma omp parallel num_threads(4) private(k) { #pragma omp for for(k=0x20ac6e12af3e4db0;k&lt;=maxint64;k++) { u.k=k; init(); decrypt(s1); decrypt(s2); } } </code></pre> above code compiled and my cpu usage was 100% but output was wrong .when i change code to this: <pre><code> #pragma omp parallel num_threads(4) private(k) { #pragma omp for for(k=0x20ac6e12af3e4db0;k&lt;=maxint64;k++) { u.k=k; init(); #pragma omp critical { decrypt(s1); decrypt(s2); } } } </code></pre> outputs become correct but in this case my cpu usage is not 100% and i lost parallelism actually! what can i do,iphone
android custom click listener inline vs field decleration why if i set a custom click listener within the method decleration it works. but if i define the custom click listener as a private field and set it it doesn t work. why <pre><code>public class customview { private view mview; private button mbutton; public customview() { mbutton = new button(); mview = new view(); // this works mview.setonclicklistener(new customclicklistener() { @override public void onclick() { mbutton.settext( xyz ); } }); // this doesn t work as in nothing happens. mview.setonclicklistener(mcustomlistener); } private customclicklistener mcustomlistener = new customclicklistener() { @override public void onclick() { mbutton.settext( xyz ); } }; } </code></pre>,java
jsonignore not working i am trying to make it so these properties don t get serialized but for some reason no matter what i do they are still getting serialized and sent down to the client. i have tried using just <code>@jsonignoreproperties({ dobefore doafter doaftercomplete })</code> i have tried using just <code>@jsonignore</code> on the getters and i have tried both together and it doesn t seem to make a difference. here s what my class looks like: <pre><code>@jsonignoreproperties({ dobefore doafter doaftercomplete }) public class action { //for reordering actions with the default actions private string dobefore; private string doafter; private string doaftercomplete; private string eventid; private list&lt;actionargument&gt; arguments; //action to perform when this action is done private list&lt;action&gt; oncompleteactions; public action() {} public action(string eventid list&lt;actionargument&gt; arguments list&lt;action&gt; oncompleteactions) { this.eventid = eventid; this.arguments = arguments; this.oncompleteactions = oncompleteactions; } public string geteventid() { return eventid; } public void seteventid(string eventid) { this.eventid = eventid; } public list&lt;actionargument&gt; getarguments() { return arguments; } public void setarguments(list&lt;actionargument&gt; arguments) { this.arguments = arguments; } public list&lt;action&gt; getoncompleteactions() { return oncompleteactions; } public void setoncompleteactions(list&lt;action&gt; oncompleteactions) { this.oncompleteactions = oncompleteactions; } @jsonignore public string getdobefore() { return dobefore; } public void setdobefore(string dobefore) { this.dobefore = dobefore; } @jsonignore public string getdoafter() { return doafter; } public void setdoafter(string doafter) { this.doafter = doafter; } @jsonignore public string getdoaftercomplete() { return doaftercomplete; } public void setdoaftercomplete(string doaftercomplete) { this.doaftercomplete = doaftercomplete; } } </code></pre>,java
sum of two numbers coming from the command line i know it s a very basic program but i am getting an error of list out of range. here is the program to take two numbers as command-line arguments (while invoking the script) and display sum (using python): <pre><code>import sys a= sys.argv[1] b= sys.argv[2] sum=str( a+b) print sum is sum </code></pre>,python
glob on non existant file with pattern matching i have this snippet which basically checks if a file exists with pattern matching. please help me with a better way to do this. <pre><code>import glob for afile in glob.glob( *.non-existant-file ): print afile try: if afile: print ok except: print come back later </code></pre>,python
python subprocess stdout iterator always blocks i want to capture the output while printing it but i m blocking forever without reading even a single line. <strong>what s going on </strong> i m using python2. generator script: <pre><code>#!/usr/bin/env python2.7 import random import time while true: print(random.random()) time.sleep(1) </code></pre> sample generator output: <pre><code>$ ./ 0.334835137212 0.896609571236 0.833267988558 0.55456332113 ^ctraceback (most recent call last): </code></pre> reader script: <pre><code>import subprocess cmd = [ ./ ] p = subprocess.popen(cmd stdout=subprocess.pipe) for line in p.stdout: print(line) print( looping ) p.wait() </code></pre> i ve also tried: <pre><code>import subprocess import sys cmd = [ ./ ] p = subprocess.popen(cmd stdout=subprocess.pipe) while true: line = p.stdout.readline() print(line) print( looping ) p.wait() </code></pre> ...and: <pre><code>import sys import subprocess import select import time cmd = [ ./ ] p = subprocess.popen(cmd stdout=subprocess.pipe) s = select.poll() s.register(p.stdout select.pollin) while true: if s.poll(1): line = else: p.poll() if p.returncode is not none: break print( looping ) time.sleep(1) p.wait() </code></pre>,python
how to listen to back key event to android back button using java script in webapp i have created a web base app for android device but back button does not work i want that by pressing back button it navigate to index.html i tried <pre><code>document.addeventlistener( backbutton dosomething false); function dosomething(e) { windows.load( index.html ) e.preventdefault(); } </code></pre>,javascript
to find data from one of the many collection and to return true value in python pymongo i m new to python and have mongo db and im using pymongo to find an data in one of the many collection and if i found one i want to stop the and return true,python
js object which should store list of objects as property if i have one object <code>myobj</code> and i want that object to have property clients which will hold list of clientobjects with id and name properties <pre><code>var client= { id: name: }; var myobj= { clients: } </code></pre> how can i populate client properties and use it in myobj.clients,javascript
java: inheritance: **the issue i am having is with public class documentdemo the problem i am having is with public class is telling me the method containskeyword cannot be declared static; static methods can only be declared in a static or top level type for the boolean part.<br> also it is telling me the same for the public static void main. same error message. i feel there is a easy fix but cannot find it any help would be awesome. <pre><code>public class document { private string text; public document(){ text = ; } public document(string text){ this.text = text; } public string tostring(){ return text; } public class email extends document{ private string sender; private string recipient; private string title; public email(string body string sender string recipient string title){ super(body); this.sender = sender; this.recipient = recipient; this.title = title; } public string getsender(){ return sender; } public void setsender(){ this.sender = sender; } public string getrecipient(){ return recipient; } public void setrecipient(){ this.recipient = recipient; } public string gettitle(){ return title; } public void settitle(){ this.title = title; } public string tostring(){ return sender + sender + recipient + recipient + title + title + + super.tostring(); } public class file extends document{ private string pathname; public file(){ super(); pathname = ; } public file(string body string pathname){ super(body); this.pathname = pathname; } public string getpathname(){ return pathname; } public void setpathname(string s){ pathname = s; } public string tostring(){ return pathname + pathname + body + super.tostring(); } public class documentdemo{ public static boolean containskeyword(document docobject string keyword){ if(docobject.tostring().indexof(keyword 0) &gt;= 0) return true; else return false; } public static void main(string[] args){ email e1 = new email( i am not sure if this is working jarvis professor an attempt at programming in java. ); email e2 = new email( please let this work jarvis my family i am feel lost but i understand the concept ); file f1 = new file( it 2650 java file.txt ); file f2 = new file( getting by file.txt ); system.out.println( which one contains the word java ); if(containskeyword(e1 java )) system.out.println( email 1 ); if(containskeyword(e2 java )) system.out.println( email 2 ); if(containskeyword(f1 java )) system.out.println( file 1 ); if(containskeyword(f2 java )) system.out.println( file 2 ); } } } } } </code></pre>,java
iphone app store. client submitting question i am writing an application which will be submitted by my client. i don t want to give them my source code what must i do,iphone
java code to download a file or a zip file i am using below code to download a file and it works fine for small files but when i tried to download a file whose size > 11gb code is not working and giving <code>java.lang.negativearraysizeexception</code> exception <pre><code>public string downloaddirectory() { outputstream myout = null; fileinputstream fileinputstream = null; file downzip = new file(dirname+ / +dir+ .zip ); getservletresponse().setcontenttype( text/html ); getservletresponse().setheader( content-disposition attachment; filename=\ + dir + .zip + \ ); getservletresponse().setcontentlength((int)downzip.length()); system.out.println( length +(int)downzip.length()); //read data from file byte[] dataread = new byte[(int)downzip.length()]; fileinputstream = new fileinputstream(downzip); 0 (int)downzip.length()); //write data to outfile myout = getservletresponse().getoutputstream(); myout.write(dataread); if (fileinputstream != null) { fileinputstream.close(); } } catch(exception e) { e.printstacktrace(); execute.rmdirscript(dirname); return exception ; } finally{ system.out.println( finally downloaddir ); if(myout!=null){ try{ myout.close();} catch(exception e){ e.printstacktrace();; } } if (fileinputstream != null) { try{ fileinputstream.close();} catch(exception e){ e.printstacktrace();; } } } } </code></pre> the error is at this line: <pre><code>byte[] dataread = new byte[(int)downzip.length()]; </code></pre> the value <code>(int)downzip.length()</code> becomes negative for big files and gives <code>java.lang.negativearraysizeexception</code> exception.,java
why does 4294967295 >> 24 == -1 in javascript i am calculating luminosity in javascript using: <pre><code>luminosity = (5036060 * + 9886846 * + 1920103 * &gt;&gt; 24; </code></pre> for the case where the color is white ie all 3 rgb values are 255 i am getting a result of -1. i tested explicitly and in javascript the value 4294967295 >> 24 is -1. why,javascript
how to delete a local notification in iphone i am making an application that sets a local notification. thankfully i was able to set the local notification but i don t know how to delete the notification which is set by my application. the xcode does provide functionality of delete with <code>removeallnotifications</code> but you cannot remove specific notifications set by the application. thanks a lot.,iphone
java code taking input is taking a long time to execute <pre><code>import java.util.*; public class main { public static void main(string [] args){ scanner input = new scanner(; int x = input.nextint(); int sum = 0; for(int i = 1; i &lt;= x ; i ++){ if(x % i ==0){ sum += i ; } } system.out.println ( the sum of the factors is + sum); } } </code></pre> the program is supposed to take in a number and print out the sum of its factors. however it is hanging. i replaced the input code to a simple (int x=10) code and i got the desired answer (18).,java
refactoring the creation of a variable number of planets in java i have to assign a random amount of objects in this program and currently the only way i know to do this is something like this: <pre><code> if (star.returnzones() == 1) { this.createplanet(planet1 star); } else if (star.returnzones() == 2) { this.createplanet(planet1 star); this.createplanet(planet2 star); } else if (star.returnzones() == 3) { this.createplanet(planet1 star); this.createplanet(planet2 star); this.createplanet(planet3 star); } else if (star.returnzones() == 4) { this.createplanet(planet1 star); this.createplanet(planet2 star); this.createplanet(planet3 star); this.createplanet(planet4 star); } else if (star.returnzones() == 5) { this.createplanet(planet1 star); this.createplanet(planet2 star); this.createplanet(planet3 star); this.createplanet(planet4 star); this.createplanet(planet5 star); } </code></pre> i am sure this is a far more efficent way to do this where each one does something along the lines of this. i will be using the term asaboveplus to mean everything above plus one more thing. <pre><code>if (star.returnzones() == 1) { this.createplanet(planet1 star); } else if (star.returnzones() == 2) { asaboveplus this.createplanet(planet2 star); } </code></pre> is there a way to do something like this in java it would really help out.,java
if loop is not working can anyone help me <pre><code>public class meaingcompare { public static void main(string[] args) { int cnt = 0; string st1 u st2; st2 = funny ; int n = 5; system.out.println( enter the string ); scanner in=new scanner(; st1 = in.nextline(); string[] v = st1.split( \\s+ ); for(int i = 0; i &lt; st1.length(); i++) { if(v[i].equalsignorecase(st2)) cnt++; } if(cnt&gt;=4) system.out.println( match found ); } } </code></pre> i am just a beginner in java.i want to get the output as match found if the no: of words in the input string match the word funny is greater than 4 but the if loop is not working.,java
how do i get touch event on webview hope you all are fine and also in one of your best moods!! i have one problem in map based application. kindly go through it and post your suggestion. thing at glance: i need to integrate map in my application. application shows map based on passing parameter as state and city. i am using yahoo map image for that. i.e. pass parameter as following: state : ca city : loss angelous. it shows image of map perfectly that i load on webview. now issue is here: i need to put button at selected city.. i don t know how do i put. because on clicking button i need to load another view that contains details of that city. i don t know how do i do this. kindly give your suggestion. thank you. arun thakkar.,iphone
how to write an if statement that searches for a value within an inherited class i m wiring an assignment that involved inheritance and i am trying to write an if statement that searches if a specific value is true or not. if the value is true to what the if statement is looking for i want to throw an exception if it is not i just want to return that value. here is my code so far: <strong>sub class</strong> <pre><code>public class carnivore extends animal { public food eat(food x) throws exception { if (x.equals( plants )) { throw new exception( carnivores only eat meat! ); } else { return x; } } public void makenoise() { noise = null; } public string getnoise() { return noise; } } </code></pre> <strong>super class</strong> <pre><code>abstract public class animal { string name; int age; string noise; abstract public void makenoise(); public string getname() { return name; } public void setname(string newname) { name = newname; } abstract public food eat(food x) throws exception; } </code></pre> the part in which i am stuck on is rephrasing this: <pre><code>if (x.equals( plants )) { throw new exception( carnivores only eat meat! ); } else { return x; } </code></pre> <strong>food class</strong> <pre><code>public class food { //field that stores the name of the food public string name; //constructor that takes the name of the food as an argument public food(string name){ = name; } public string getname() { return name; } } </code></pre> i want to make it so if the value of x is plants (this is typed in string format) then an exception is thrown else the value is returned. any help would be appreciated thanks.,java
python combine while loop with for loop to iterate through some data i am new to python and in general to programming. i am trying to combine while loop with for loop to iterate through some list but i am getting infinite loops. here is the code <pre><code>l=[0 2 3 4] lo=0 for i in range(len(l)): while (true): lo+=1 if lo+l[i]&gt;40: break print(lo) </code></pre> similarly with this code i got the same endless loop i want an output when the condition lo+ l[i] is greater than 40 stops looping and gives the final lo output or result. i tried every method of indentation of the print line but could not get what i wanted. please comment on this code. thanks in advance.,python
using a list in a string.format in python 2.7 let s assume i have a explicitly defined list with a known number of (numeric) elements say <code>aa=[1 2 3 4 5]</code> - and i d like to print these in a specific string. i m aware i can do this: <pre><code>$ python python 2.7.6 (default nov 23 2017 15:49:48) [gcc 4.8.4] on linux2 type help copyright credits or license for more information. &gt;&gt;&gt; aa=[1 2 3 4 5] &gt;&gt;&gt; print %dx%d+%d+%dx%d %tuple(aa) 1x2+3+4x5 </code></pre> ... but i m not very fond of how the format string <code> %dx%d+%d+%dx%d </code> looks like and i d much rather use <code>string.format</code> kind of specifiers. then i m aware i can use this: <pre><code>&gt;&gt;&gt; print {}x{}+{}+{}x{} .format(aa[0] aa[1] aa[2] aa[3] aa[4]) 1x2+3+4x5 </code></pre> ... but i find writing all the arguments for <code>string.format</code> expanded as <code>aa[0] aa[1] aa[2] aa[3] aa[4]</code> a bit overkill since in this case i explicitly know i have enough <code>{}</code> specifiers for all the elements of the array/list so i d much rather just throw <code>aa</code> in there as in: <pre><code>&gt;&gt;&gt; print {}x{}+{}+{}x{} .format(aa) traceback (most recent call last): file &lt;stdin&gt; line 1 in &lt;module&gt; indexerror: tuple index out of range </code></pre> ... but unfortunately that doesn t work. so what would be a way - if there is one - to just refer to a list like <code>aa</code> in the argument of <code>string.format</code> without having to specifically expand each of its elements as a separate argument,python
is there any mechanism provided by apple store to make the user sign-up to my website before he/she can download the application i am creating an iphone application that requires the users to have an account at my website. but if i have to distribute it through apple store how should i make the users of this iphone application first create an account with my website. there could be a few options like : 1) ask the user to create an account when he/she tries to run the application on iphone. 2) provide a sign-up page in the iphone application itself. my question is is there any mechanism provided by apple store to make the user sign-up to my website before he/she can download the application . kindly give in your suggestions for the same. which would be the best approach for solving my problem. thanks lg,iphone
rights protected photo on iphone i ve been tasked with writing an iphone application that displays a set of images (think powerpoint slideshow). the content of these images need to be protected from forwarding this task seems quite simple with one exception - i d like to prevent the user from taking a screenshot it s not like i m protecting the crown jewels here so i m not looking for military grade super ninja protection. but on the iphone it s so common and easy to take a snapshot... thoughts,iphone
exc_bad_access when returning a cgrect in iphone i have a class which must return a cgrect from one of its methods: <pre><code>-(cgrect)myrect { cgrect rect = cgrectmake(self.mysprite.position.x self.mysprite.position.y self.mysprite.texturerect.size.width self.mysprite.texturerect.size.height); return rect; } </code></pre> i get an exc_bad_access as soon as i try to access the mysprite ivar. thing is if i call it the instance variable mysprite is full of garbage. but if i change the function to return void self.mysprite does contain the correct data. <pre><code>-(void)myrect { cgrect rect = cgrectmake(self.mysprite.position.x self.mysprite.position.y self.mysprite.texturerect.size.width self.mysprite.texturerect.size.height); return rect; } </code></pre> that does not crash when accessing mysprite...,iphone
cannot pass uitouch behind scrollview without disabling scrollview user interaction i subclassed uiscrollview and overrode the touch began method to pass touch events to a button object behind the scroll view(the scroll view is transparent). for some reason only if user interaction of the scrollview is disabled does the event get passed through. does anyone know how to pass events up the responder chain with scroll view without disabling the user interaction thanks david,iphone
getting multiple properties associated with click events i m rank new to javascript thus the question. i m using data-id to pass an idea associated with a click event. <pre><code>&lt;a href= # onclick={this.handleclick} data-id={}&gt; </code></pre> this is my handle click method <pre><code>handleclick(event){ event.preventdefault(); let mediaid = event.currenttarget.attributes[ data-id ].value; this.props.handleclick(mediaid); } </code></pre> now i want to capture one more attribute which is the image.src where do i place that data and how do i get the data in my click event handler.,javascript
codingbat hasbad stringindexoutofboundsexception hey guys i was hoping someone could explain to me the error in this code i m just having a little trouble understanding why it s throwing that exception. <img src= alt= screenshot from codingbat >,java
how to define instantiated function s behavior in javascript using es2015 i want to extend <code>function</code> class and use its instance as a callable function. <pre class= lang-js prettyprint-override ><code>class foo extends function { // how to wite behavior } let foo = new foo(); foo();; // this is callable but no behavior defined </code></pre> how can i let <code>foo</code> have its specific behavior in its declaration,javascript
trying to de-increment only a positive number the form code: <pre><code> &lt;td&gt;&lt;form action= cart.php method= get &gt; &lt;input type= button onclick= buttonsubtract1() name= subtract1 value= - /&gt; &lt;input type= text size= 4 id= qty1 name= quantity1 value= 0 /&gt; &lt;input type= button onclick= buttonadd1() name= add1 value= + /&gt; &lt;input type= submit name= product1 value= add /&gt; </code></pre> the javascript: <pre><code>var i = 0; var qty1 = document.getelementbyid( qty1 ).value; function buttonadd1() { document.getelementbyid( qty1 ).value = ++i; } function buttonsubtract1() { if (qty1 &gt; 0) { document.getelementbyid( qty1 ).value = --i;} } </code></pre> i changed the code to increment and de-increment using javascript which worked fine so i tried to make it so that de-incrementation only works if the number is positive but now incrementing is working fine but it is not allowing de-incrementation of any number. why is this,javascript
reading csv file from panda and plotting i have 1000 files in which the data is stored in comma separation. the description of a file is given below: the values are comma separated <code>-9999</code> values should be ignored and if it can be read all the values of row and column should be stored in numbers as it has to used in plotting. the shape of file is [<strong>104 rows x 15 columns</strong>]. the few lines of the files are as follows: <pre><code>0 9.8597e+00 129.944 1.071 6.7433e-06 1.0911e-05 -9999 -9999 3.7134e-07 3.5245e-05 -9999 -9999 26.295 -86.822 -123.017 0 8.7012e+00 130.908 0.966 1.9842e-06 1.0799e-05 -9999 -9999 3.5888e-07 7.8133e-05 -9999 -9999 27.140 -86.818 -122.322 </code></pre> after reading into numeric values i need to plot it into subplot also. like col1 vs col2 col3 vs col5 and so on.... any idea how to achieve it <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt df1=pd.read_csv( small_file_106.txt header=1) print(df1) </code></pre>,python
i m using java theadpool but i got a error i can t understand <pre><code>&lt;bean id= threadpooltaskexecutor class= org.springframework.scheduling.concurrent.threadpooltaskexecutor &gt; &lt;property name= corepoolsize value= 6 /&gt; &lt;property name= maxpoolsize value= 6 /&gt; &lt;property name= queuecapacity value= 5 /&gt; &lt;property name= keepaliveseconds value= 120 /&gt; &lt;property name= threadnameprefix value= mythread_ /&gt; &lt;/bean&gt; </code></pre> <hr> <pre><code> public static void main(string[] args) { applicationcontext context = new classpathxmlapplicationcontext( spring.xml ); threadpooltaskexecutor executor = (threadpooltaskexecutor) context.getbean( threadpooltaskexecutor ); list&lt;integer&gt; list = new arraylist&lt;integer&gt;(); for(int i=0;i&lt;1000;i++){ list.add(i); if(6 == list.size()){ dowork(list executor); list.clear(); } } if(list.size() &gt; 0) dowork(list executor); system.out.println( all work finished ); } static void dowork(list&lt;integer&gt; list threadpooltaskexecutor executor){ final countdownlatch latch = new countdownlatch(list.size()); for(final int i:list){ executor.execute(new runnable() { @override public void run() { try { thread.sleep(200); latch.countdown(); } catch (interruptedexception e) { e.printstacktrace(); } } }); } try { latch.await(); } catch (interruptedexception e) { e.printstacktrace(); } } </code></pre> above is my code. when i set queuecapacity 6 or lager than 6 it works well but when queuecapacity is less than 6 the program will got error: <pre><code>&gt; exception in thread main &gt; org.springframework.core.task.taskrejectedexception: executor &gt; [java.util.concurrent.threadpoolexecutor@1f7911b[running pool size = &gt; 6 active threads = 0 queued tasks = 5 completed tasks = 18]] did &gt; not accept task:$1@1de8526; nested exception &gt; is java.util.concurrent.rejectedexecutionexception: task &gt;$1@1de8526 rejected from &gt; java.util.concurrent.threadpoolexecutor@1f7911b[running pool size = &gt; 6 active threads = 0 queued tasks = 5 completed tasks = 18] at &gt; org.springframework.scheduling.concurrent.threadpooltaskexecutor.execute( &gt; at at &gt; at &gt; sun.reflect.nativemethodaccessorimpl.invoke0(native method) at &gt; sun.reflect.nativemethodaccessorimpl.invoke( &gt; at &gt; sun.reflect.delegatingmethodaccessorimpl.invoke( &gt; at java.lang.reflect.method.invoke( at &gt; com.intellij.rt.execution.application.appmain.main( &gt; caused by: java.util.concurrent.rejectedexecutionexception: task &gt;$1@1de8526 rejected from &gt; java.util.concurrent.threadpoolexecutor@1f7911b[running pool size = &gt; 6 active threads = 0 queued tasks = 5 completed tasks = 18] at &gt; java.util.concurrent.threadpoolexecutor$abortpolicy.rejectedexecution( &gt; at &gt; java.util.concurrent.threadpoolexecutor.reject( &gt; at &gt; java.util.concurrent.threadpoolexecutor.execute( &gt; at &gt; org.springframework.scheduling.concurrent.threadpooltaskexecutor.execute( &gt; ... 7 more </code></pre> who can tell me why when a put a task to therad pool the poll firt put the task to workqueue,java
what s the difference between live and not live collection in javascript selectors how can i know what is the difference between live and not live collection. <em>according to my research:</em> a <strong>live</strong> is: when the changes in the dom are reflected in the collection. the content suffers the change when a node is modified. a <strong>not live</strong> is : when any change in the dom does not affect the content of the collection. document.getelementsbyclassname() is an htmlcollection and is live. document.getelementsbytagname() is an htmlcollection and is live. document.getelementsbyname() is a nodelist and is live. document.queryselectorall() is a nodelist and is not live. <strong>why document.queryselectorall is not live </strong> <em>i know that :</em> <strong>htmlcollection</strong> only contains elements nodes <strong>nodelist</strong> contains element nodes and text nodes.,javascript
\n is not working in plist i created array.plist file where i am storing key value pair e.g key = my_first_message value = welcome\n i am happy to serve you. in xml format welcome\n i am happy to serve you. i received this sting in dictionary and display in textview like below code textview.text = [mydict objectforkey:my_first_message]; but i am not able to get newline. it should be look like below welcome i am happy to serve you but i got it like welcome\n i am happy to serve you on textview view i debug this problem my got string from plist is like welcome\n i am happy to serve you. please suggest me how to remove \n from string which are from plist i tried \n /n /\n all combination. thanks manu,iphone
converting button into integer i have two buttons and i had taken one button tag and want to compare with the another button like this <pre><code>if ([sender tag] != ((uibutton*)[self.view viewwithtag:[self number]])) </code></pre> then the warning is comparison between nsinteger and pointer type is not possible. so please help me how to convert pointer to integer any help would be appreciated. thanks in advance.,iphone
iphone sdk: interact with images i was making an app for the iphone and part of what i want to do is that whenever the user touches a certain spot (let s say a circle) the app should react and do something. how do i pinpoint that one spot as a button or is there a different way to do this i have a uiscrollview with a subview of a uiimageview. thanks in advance! guy,iphone
lazy.js how to select distinct (uniq) by two fields we are using lazy.js. if i have selected one field i know i can use the <code>uniq(fieldname)</code> function to get distinct results. for example: <pre><code>var uniquevalues = lazy(somearray) .map(function (e) { return e.fieldname }) .uniq() .value(); </code></pre> how do you do the same operation on two fields this is what i tried: <pre><code>var uniquevalues = lazy(somearray) .map(function (e) return { fieldname1 : e.fieldname1 fieldname2 : e.fieldname2 }) .uniq(); .value(); </code></pre> but it s not making it distinct by both fields.,javascript
error in asihttp class i am using asihttp class.i am using non-arc code structure.and also using libasilib.a instead of implementation file. i am getting error:<code>undefined symbols for architecture i386: _objc_class_$_asiformdatarequest referenced from:</code> i am able to run in device but not able to run in simulator.please help me.thanking you in advance...,iphone
adding time to a date in javascript i have this script; <pre><code>showdiff(); function showdiff() { var date1 = new date( 2016/03/14 00:00:00 ); var date2 = new date(); var diff = (date2 - date1); var diff = math.abs(diff); var result; if (diff &gt; 432000000) { result = 100 + % ; } else { result = (diff/4320000) + % ; } document.getelementbyid( showp ).innerhtml = result; document.getelementbyid( pb ).style.width = result; settimeout(showdiff 1000); } </code></pre> now i want to get exactly one week added to date1 when atleast one week has passed since that time. that date has to be saved so that one week later another week can be added to date1. so basically every monday there has to be one week added to date1. how do i this,javascript
setting uinavigationbar properties in viewdidload does nothing i ve tried setting the style of the uinavigationbar to be a translucent style in the viewdidload method of my controller. but nothing is changed. why i set the property using the standard code like <pre><code>self.navigationcontroller.navigationbar.barstyle = uibarstyleblacktranslucent; </code></pre>,iphone
call a c library from python i ve found a library which is in c ( ) that i want to try from python: <a href= rel= nofollow ></a> i d like to see if i can store compressed files on disk and decompress them in memory for faster full-file reading times. i m new to using external code from python. how can i create a python function that uses this library with a little overhead as possible (i will work with windows or linux),python
what is the best way to memorize all method names and their related classes and interfaces in java hi i am new to java and facing difficulties in learning methods and their parameters tell me the best way of memorizing all methods interfaces names etc,java
can t override nsurlconnection canauthenticateagainstprotectionspace and didreceiveauthenticationchallenge delegate methods i am simply trying to ignore an unsigned ssl certificate and am i am directly following examples i found online of how to override two delegate methods of nsurlconnection as follows to allow my app to use an https connection to a server which has a self-signed certificate: <pre><code>- (bool)connection:(nsurlconnection *)connection canauthenticateagainstprotectionspace:(nsurlprotectionspace *)protectionspace { nslog( @ canauthenticateagainstprotectionspace() called ); return( [protectionspace.authenticationmethod isequaltostring:nsurlauthenticationmethodservertrust] ); } - (void)connection:(nsurlconnection *)connection didreceiveauthenticationchallenge:(nsurlauthenticationchallenge *)challenge { nslog( @ didreceiveauthenticationchallenge() called ); nsarray *trustedhosts = [nsarray arraywithobject:@ ]; if( [challenge.protectionspace.authenticationmethod isequaltostring:nsurlauthenticationmethodservertrust] ) { if( [trustedhosts] ) { [challenge.sender usecredential:[nsurlcredential credentialfortrust:challenge.protectionspace.servertrust] forauthenticationchallenge:challenge]; } } [challenge.sender continuewithoutcredentialforauthenticationchallenge:challenge]; } </code></pre> the above 2 methods are never called in spite of the fact that the signatures are identical to those in nsurlconnection.h and my implementation of didfailwitherror below is called: <pre><code>- (void)connection:(nsurlconnection *)connection didfailwitherror:(nserror *)error { nslog( @ didfailwitherror() ); nsdictionary *userinfo = error.userinfo; nsarray *keys = userinfo.allkeys; nsarray *values = userinfo.allvalues; for( int i = 0; i &lt; keys.count; i++ ) { nslog( @ nsurlconnection.didfailwitherror: %@: %@ (nsstring *) [keys objectatindex:i] (nsstring *) [values objectatindex:i] ); } badconnection = yes; asyncdone = yes; } </code></pre> the rest of my nsurlconnection delegate methods work perfectly when i use the same class to access a non secure url. i am utterly stumped as to why just these two delegate methods are not cooperating. thanks rick,iphone
iphone:play .asf streaming audio file on iphone programmatically i am trying to play a streaming audio from a link where i get .asf file. but my program is unable to play it. i found the below link where they are talking about the samething.. <a href= rel= nofollow noreferrer ></a> seems like some apps are able to play it. i got confused now. could someone guide me whether it is possible to play *.asf file or not on iphone if yes how can i achieve it thank you.,iphone
html forms not working with python i ve created a html page with forms which takes a name and password and passes it to a python script which is supposed to print the persons name with a welcome message. however after i post the values i m just getting the python code displayed in the browser and not the welcome message. i have stored the html file and python file in the cgi-bin folder under apache 2.2. if i just run a simple hello world python script in the browser the hello world message is being displayed. i m using winxp python 2.5 apache 2.2. the code that i m trying to run is the following: <pre><code>#!c:\python25\python.exe import cgi import cgitb; cgitb.enable() form = cgi.fieldstorage() reshtml = content-type: text/html\n &lt;html&gt; &lt;head&gt;&lt;title&gt;security precaution&lt;/title&gt;&lt;/head&gt; &lt;body&gt; print reshtml user = form[ username ].value pass = form[ password ].value if user == gold and pass == finger : print &lt;big&gt;&lt;big&gt;welcome print mr. goldfinger !&lt;/big&gt;&lt;/big&gt;&lt;br&gt; print &lt;br&gt; else: print sorry incorrect user name or password print &lt;/body&gt; print &lt;/html&gt; </code></pre> the answer to it might be very obvious but its completely escaping me. i m very new to python so any help would be greatly appreciated. thanks.,python
can web apps in iphone call inapp for virtual things purchase if i would like to write a web apps that users can purchase some virtual things can i call the iphone inapp or i can use other payment methods,iphone
do/while loop not returning to the top recently started computer programming and i am stuck on a homework assignment. i created a loop but instead of going back to the top it starts 1 step ahead of where i intended it to. (it s all listed in the comments i made in the coding. i have been trying to figure this out for the past 6 hours so it would greatly appreciated if someone can help me. <pre><code>import java.util.scanner; import java.text.decimalformat; public class election { public static void main (string[] args) { decimalformat f = new decimalformat( ##.00 ); decimalformat n = new decimalformat( ## ); float votesforpolly; float votesforernest; float totalpolly = 0; float totalernest = 0; string response; int precinctsforpolly = 0; int precinctsforernest = 0; int precinctsties = 0; scanner scan = new scanner(; system.out.println (); system.out.println ( election day vote counting program ); system.out.println (); do { //point a system.out.println( do you wish to enter more votes enter y:n ); response =; if (response.equals( y )) { //point b system.out.println( enter votes for polly: ); votesforpolly = scan.nextint(); system.out.println( enter votes for ernest: ); votesforernest = scan.nextint(); totalpolly = totalpolly + votesforpolly; totalernest = totalernest + votesforernest; system.out.println( do you wish to add precincts enter y:n ); response =; while (response.equals( y )) { system.out.println( how many precincts voted for polly: ); precinctsforpolly = scan.nextint(); system.out.println( how many precincts votes for ernest: ); precinctsforernest = scan.nextint(); system.out.println( how many were ties: ); precinctsties = scan.nextint(); break; //not returning to point a instead it returns to point b } if (response.equals( n )) { break; } if (response.equals( n )) { break; } } } while (response.equals( n )); system.out.println( final tally ); system.out.println( polly received:\t + n.format(totalpolly) + votes\t + f.format((totalpolly/(totalpolly + totalernest))*100) + %\t + precinctsforpolly + precincts ); system.out.println( ernest received: + n.format(totalernest) + votes\t + f.format((totalernest/(totalpolly + totalernest))*100) + %\t + precinctsforernest + precincts ); system.out.println( \t\t\t\t\t + precinctsties + precincts tied ); } } </code></pre> my guess is that the string response has already been determine to be y at the end of the loop which is why it skips the first step and jumps right back into the loop assuming my answer is already y.,java
add linkedin and twitter in application i need to add twitter and linkedin in my application. bith twitter and linkedin use oauth files so i cannot able to add then only can add one of them. when i try to use same files for both then only linkedin work and get error the token is expire for twitter. can any one know how to add both in same application.,iphone
how to remove keys for list of objects in javascript i have list of objects created like this: <pre><code>for(var i = 0; i &lt; retrievedcontactsarr.length; i++){ for(var k = 0; k &lt; result.length; k++){ if(retrievedcontactsarr[i] &amp;&amp; retrievedcontactsarr[i] === result[k]{ retrievedcontactsarr.splice(i 1); } } retrievedcontactsobj[i] = retrievedcontactsarr[i]; } </code></pre> but they are created with keys <code> 0 1 </code> like this: <pre><code>{ 0 : { contact : { address : { home : office : } } name : test3 } 1 : { contact : { address : { home : office : } } name : test2 } } </code></pre> how do i remove the keys for the above object,javascript
expression tokenizer i m attempting to create a tokenizer that reads an expression. when it get the token i print the type and the lexeme which is either a number of an operator. it currently prints each character individually but i need it to print double digit and decimal numbers together. here is my code. <pre><code> public class tokenizer { string type; string lexeme; /** * @param args the command line arguments */ void gettoken(string expression int i) { if (expression.charat(i) == + ) { type = operator ; lexeme = + ; } else if (expression.charat(i) == - ) { type = operator ; lexeme = - ; } else if (expression.charat(i) == * ) { type = operator ; lexeme = * ; } else if (expression.charat(i) == / ) { type = operator ; lexeme = / ; } else if (expression.charat(i) == ) { ; //empty statement. does nothing if the character is white space } else { type = number ; lexeme = character.tostring(expression.charat(i)); } } public static void main(string[] args) { // todo code application logic here string expression = 3+66*2.5 ; tokenizer tokenizer = new tokenizer(); for (int i = 0; i &lt; expression.length(); i++) { tokenizer.gettoken(expression i); system.out.print( type: + tokenizer.type + \t + lexeme: + tokenizer.lexeme + \n ); } } } </code></pre> <h3>sample output - actual</h3> <pre><code>type: number lexeme: 3 type: operator lexeme: + type: number lexeme: 6 type: number lexeme: 6 type: operator lexeme: * type: number lexeme: 2 type: number lexeme: . type: number lexeme: 5 </code></pre> <h3>sample output - expected</h3> <pre><code>type: number lexeme: 3 type: operator lexeme: + type: number lexeme: 66 type: operator lexeme: * type: number lexeme: 2.5 </code></pre>,java
string function to accept the 10 digit mobile no. discards any no. less than 10 digits trims zeroes at the beginning when we enter a no like 00982787878 (having 9 digits and zeros) the output should not be displayed after the zeros are trimmed. <h2>problem:</h2> there is some problem in while loop as the output is a number with just one 0 trimmed. <h2>code:</h2> <pre><code>public static string trimzeros(string mobnumber) { boolean exitloop = true; int count = 0; while (exitloop &amp;&amp; mobnumber.substring(count) == 0 ) mobnumber = mobnumber.substring(0); if (mobnumber.charat(count) != 0 ) { exitloop = false; } count++; mobnumber = mobnumber.replaceall( ); mobnumber = mobnumber.length() &lt; 10 mobnumber.substring(mobnumber .length()) : mobnumber.substring(mobnumber.length() - 10); return mobnumber; } </code></pre>,java
what is bus error when it comes in my application bus error is showing and application crash ..i want to know when this error comes . what mean by bus error in my application page on diffrent id i have to calling libxml parsing . in many times calling ones it crash .,iphone
c++ development for iphone i know about <a href= rel= nofollow noreferrer ></a> but is there other tools that i can use to write c++ for iphone is there a book maybe,iphone
cannot validate query results <pre><code> query = select serialno from registeredpcs where ipaddress = usercheck = query + %s %fromip #print( query + - +usercheck) print(usercheck) rs = cursor.execute(usercheck) print(rs) row = rs #print(row) #rs = cursor.rowcount() if int(row) == 1: query = select report1 from registeredpcs where serialno = firstreport = query + %s %rs result = cursor.execute(firstreport) print(result) elif int(row) == 0: query_new = select * from registeredpcs cursor.execute(query_new) newrow = cursor.rowcount()+1 print(new row) </code></pre> what i am trying to do here is fetch the <em>serialno</em> values from the db when it matches a certain <em>ipaddress</em>. this query if working fine. as it should the query result set <code>rs</code> is 0. now i am trying to use that value and do something else in the if else construct. basically i am trying to check for unique values in the db based on the <em>ipaddress</em> value. but i am getting this error <pre><code>error: uncaptured python exception closing channel smtpd.smtpchannel connected at 0x2e47c10 (**class typeerror : int object is not callable** [c:\python34\lib\|read|83] [c:\python34\lib\|handle_read_event|442] [c:\python34\lib\|handle_read|171] [c:\python34\lib\|found_terminator|342] [c:/users/dev- p/pycharmprojects/cr server local/lrs|process_message|43]) </code></pre> i know i am making some very basic mistake. i think it s the part in bold thats causing the error. but just can t put my finger on to it. i tried using the <code>rowcount()</code> method didn t help.,python
arraylist gives null. i have written an observer pattern but notification is not working <pre><code>package p; public interface observer { public void update(float interest); } </code></pre> <hr> <pre><code>package p; public interface subject { public void registerobserver(observer obj); public void removeobserver(observer obj); public void notifyobervers(); } </code></pre> <hr> <pre><code>package p; import java.util.arraylist; import java.util.list; public class loan { private float interest; public float getinterest() { return interest; } public void setinterest(float interest) { system.out.println( interest received : notifying listener +interest); this.interest = interest; subject.notifyobervers(); } public list&lt;observer&gt; observerlist = new arraylist&lt;observer&gt;(); subject subject = new subject() { @override public void removeobserver(observer obj) { observerlist.remove(obj); } @override public void registerobserver(observer obj) { observerlist.add(obj); } @override public void notifyobervers() { for (observer obj : observerlist) { obj.update(getinterest()); } } }; } </code></pre> <hr> <pre><code>package p; public class news { observer observer = new observer() { @override public void update(float interest) { system.out.println( news : received interest +interest); } }; } </code></pre> <hr> <pre><code>package p; public class internet { observer observer = new observer() { @override public void update(float interest) { system.out.println( internet : received update on interest : +interest); } }; } </code></pre> <hr> <pre><code>package p; public class observersmain { public static void main(string[] args) { observer observer1 = new internet().observer; observer observer2 = new news().observer; subject loan = new loan().subject; loan.registerobserver(observer1); loan.registerobserver(observer2); new loan().setinterest(6.7f); system.out.println( notified listeners ::: ); } } </code></pre>,java
background streaming effect make other view not performing well i am developing one application that playes audio file and video from server. for that i have used avplayer view controller. but my problem is that when the audio or video song is playing then i go to the next view in that i have song list that is comming from server and displayed in the uitableview but tableview not scrolling well when i scroll it scroll after some times. may be because of the player.,iphone
is there any window management library in javascript i have many browser windows opened from javascript. and i want to manage them - place cascade tile and resize them all at the same time. are there any libraries that can help me,javascript
storing letters in java in a way allowing them to change i am currently making a noughts and crosses game in console and i ve run into a problem since both chars and strings are constant their values can t be changed and i ve therefore searched all over the web for a way to store letters in such a way i can change them. i would really appreciate some help or alternative methods of doing this. thanks.,java
how to invert the entire screen in python as you all know it is april fools today and i am working on this prank. i already asked a question about this but that one is probably deep in the registers by now. so all my research is right here: <a href= >keeping the script running when closing the window and opening a text editor in python</a> if you could tell me how to invert the entire screen that would be great! thanks. edit 1: yes i did find python pil but that was only for inverting images i need the entire screen to be inverted. edit 2: guys i am begging you help me it needs to be done today!!! edit 3: i am working with windows 10/8,python
javascript uncaught referenceerror: parameter is not defined i have some javascript code: <pre><code>function addrow(tableid rowid) { var table = document.getelementbyid(tableid); var rowposition = document.getelementbyid(rowid).rowindex; //etc. } </code></pre> but this throws a javascript error <blockquote> uncaught referenceerror: rowid is not defined </blockquote> though looking on firebug i can see that the functions receives a correct row identifier but once the code reaches the second line inside the function the parameter <code>rowid</code> seems unknown. can anyone help,javascript
how to create a list of n dictionaries i m learning python and for practicing purposes i m writing a script that reads a file (containing a graph in <a href= rel= nofollow >trivial graph format</a>) and runs a couple of graph algorithms on the graph. i thought about storing the graph in a list of n dictionaries where n is the number of vertexes and all the edges of a vertex would be stored in a dictionary. i tried this <pre><code>edges = [{} for i in xrange(num_vertexes)] for line in file: args = line.split( ) vertex1 = int(args[0]) vertex2 = int(args[1]) label = int(args[2]) edges[vertex1][vertex2] = label </code></pre> but i m getting this error for the last line: <blockquote> indexerror: list index out of range </blockquote>,python
what happens if we try to use object removed from an nsarray ar nsmutable array i ve searched it alot but most of the times found answer related to releasing objects not for removing object. any help would be highly appreciated.,iphone
uiscrollview issues with uitableview i have one uitableview and uicutsom cell. in that uitableview i populate data using web services. i change background color and font color of cell. when i scroll up and down of that tableview cell background color and label color also change on another cells. <pre><code>- (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { static nsstring *simpletableidentifier = @ fieldinventorycell ; // uitableviewcell *cell = [tableview dequeuereusablecellwithidentifier:simpletableidentifier]; fieldinventorycell *cell=(fieldinventorycell *)[tableview dequeuereusablecellwithidentifier:simpletableidentifier]; if (cell == nil) { nsarray *nib=[[nsbundle mainbundle] loadnibnamed:@ fieldinventorycell owner:self options:nil]; cell=[nib objectatindex:0]; } nsarray *ar = [[arr objectatindex:indexpath.row]componentsseparatedbystring:@ | ]; cell.status.text=[ar objectatindex:1]; cell.serialnumber.text=[ar objectatindex:0];[ar objectatindex:2]; if([cell.serialnumber.text isequaltostring:@ grand total ]) { cell.contentview.backgroundcolor=[uicolor bluecolor]; cell.serialnumber.textcolor=[uicolor whitecolor]; } if ([cell.serialnumber.text isequaltostring:@ inv_fld status total ]) { //cell.contentview.backgroundcolor=[uicolor bluecolor]; cell.serialnumber.textcolor=[uicolor orangecolor]; } return cell; } </code></pre>,iphone
java subclasses constructors with expanding parameters i was wondering if it is possible to expand the constructors parameters for each subclass of the superclass. for example: <pre><code>public class car{ protected string regnum; protected car(string regnum){ this.regnum = regnum; } } public class gascar extends car{ protected double gasemissions; protected gascar(double ge){ gasemissions = ge; } } </code></pre> is there a way where i could use the parameters in the car constructor in the gascar constructor by inheritance,java
a pythonstartup file for a specific directory i ve heard about the pythonstartup file as a way to automatically load specified modules and other code when starting python. but pythonstartup is a global thing for all instances of python. is there such a thing as pythonstartup that i can place in a specific directory and runs only when i start python in that directory,python
combining multiple sets of letters in python i am trying to figure out how to print all the combinations there are for multiple sets of letters without repetition. an example: a b c and x y z the combinations would be: ax ay az bx by bz cx cy cz,python
java adding two arrays of objects done quite a but of digging but cant seem to find an answer. i have 2 object arrays. these objects are session counts which contain data about our servers. each <code>sessioncount</code> object has: <ul> <li>date</li> <li>hour</li> <li>number of connections</li> </ul> so of the two <code>sessioncount</code> arrays i need to match up the objects date and hour then use that to add the number of connections for that time. any ideas,java
separating loading data and ui via threading in objecive c/cocoa i m currently developing an iphone application that loads data via a webservice into a table. right now i have it loading the data and creating/displaying my cells via [tableview cellforrowatindexpath] on two separate threads. my problem is that i need the data to create my cells. so currently i load my data into an array on one thread and lock the cell creation part on the other thread until completion. once completed i go back to my main thread unlock the cell creation part and continue. this actually makes the whole process slower. i m trying to figure out a design so that i can speed up this process. can someone help thank you to all that reply.,iphone
convert attributes of an object to a string in python i have a list of of objects defined by <pre><code>class track(object): def __init__(self title artist album source dest): self.title = title self.artist = artist self.album = album self.source = source self.dest = dest </code></pre> on a gui i have a button that i tied to an event. the output is supposed to print the contents of the list to the command line (not the gui) <pre><code>def onprintbtn(self event): print onprintbtn for track in self.trackolv: print(track) </code></pre> for some reason this ended in a infinite loop of (class <strong>main</strong>.track ) i understand that my problem is that the attributes are as part of the object but what i don t know how to do is to convert them to string values so i can print them out as needed. per request here is the entire code for my program. <pre><code>#boa:frame:frame1 import wx import os import glob import shutil import datetime from mutagen.mp3 import mp3 from mutagen.easyid3 import easyid3 import mutagen.id3 import unicodedata from objectlistview import objectlistview columndefn ######################################################################## class track(object): def __init__(self title artist album source dest): self.title = title self.artist = artist self.album = album self.source = source self.dest = dest def __str__(self): return %s by %s on teh ablum %s \nsource: %s\ndest: %s % \ (self.title self.artist self.album self.source self.dest) def __unicode__(self): return unicode(str(self)) class action(object): def __init__(self timestamp action result): self.timestamp = timestamp self.action = action self.result = result ######################################################################## # non gui ######################################################################## def selectfolder(smessage): print select folder dlg = wx.dirdialog(none message = smessage) if dlg.showmodal() == wx.id_ok: # user has selected something get the path set the window s title to the path filename = dlg.getpath() else: filename = none selected dlg.destroy() return filename def getlist(sourcedir): print getlist listoffiles = none print -list set to none listoffiles = glob.glob(sourcedir + /*.mp3 ) return listoffiles def getlistrecursive(sourcedir): print getlistrecursive listoffiles = none listoffiles = [] print -list set to none for root dirs files in os.walk(sourcedir): for file in files: if file.endswith( .mp3 ): listoffiles.append(os.path.join(root file)) #print listoffiles return listoffiles def strip_accents(s): print strip_accents return .join((c for c in unicodedata.normalize( nfd s) if unicodedata.category(c) != mn )) def replace_all(text): print replace_all + text dictionary = { \\ : : / : ... : : : &amp; : and } print text print text.decode( utf-8 ) text = strip_accents(text.decode( utf-8 )) for i j in dictionary.iteritems(): text = text.replace(i j) return text def gettitle(filename): print gettitle audio = mp3(filename) try: stitle = str(audio[ tit2 ]) except keyerror: stitle = os.path.basename(filename) frame.lvactions.append([ filename title tag does not exist set to filename ]) # todo: offer to set title to filename ## if filename != filename then ## prompt user for action ## offer y/n/a stitle = replace_all(stitle) return stitle def getartist(filename): print get artist audio = mp3(filename) try: sartist = str(audio[ tpe1 ]) except keyerror: sartist = unkown frame.lvactions.append([ filename artist tag does not exist set to unkown ]) #replace all special chars that cause dir path errors sartist = replace_all(sartist) #if name = the beatles change to beatles the if sartist.lower().find( the ) == 0: sartist = sartist.replace( the ) sartist = sartist.replace( the ) sartist = sartist + the return sartist def getablum(filename): print get album audio = mp3(filename) try: salbum = str(audio[ talb ]) except keyerror: salbum = unkown frame.lvactions.append([ filename album tag does not exist set to unkown ]) #replace all special chars that cause dir path error salbum = replace_all(salbum) return salbum ######################################################################## # gui ######################################################################## class mainpanel(wx.panel): #---------------------------------------------------------------------- def __init__(self parent): wx.panel.__init__(self parent=parent id=wx.id_any) self.trackolv = objectlistview(self wx.id_any style=wx.lc_report|wx.sunken_border) self.settracks() # allow the cell values to be edited when double-clicked self.trackolv.celleditmode = objectlistview.celledit_singleclick self.actionsolv = objectlistview(self wx.id_any style=wx.lc_report|wx.sunken_border) self.setactions() # create browse to source button sourcebtn = wx.button(self wx.id_any browse source ) sourcebtn.bind(wx.evt_button self.onbrowsesource) # create source txt box self.txsource = wx.textctrl(self wx.id_any name=u txsource value=u ) # create browse dest button destbtn = wx.button(self wx.id_any browse destination ) destbtn.bind(wx.evt_button self.onbrowsedest) # create dest txt box self.txdest = wx.textctrl(self wx.id_any name=u txdest value=u ) # create move files button movebtn = wx.button(self wx.id_any move files ) movebtn.bind(wx.evt_button self.onmovefiles) # print list button - debug only printbtn = wx.button(self wx.id_any print list ) printbtn.bind(wx.evt_button self.onprintbtn) # create check box to include all sub files self.cbsubfolders = wx.checkbox(self wx.id_any label=u include subfolders name=u cbsubfolders style=0) self.cbsubfolders.setvalue(true) self.cbsubfolders.bind(wx.evt_checkbox self.oncbsubfolderscheckbox) # create check box to repace file names self.cbreplacefilename = wx.checkbox(self wx.id_any label=u replace filename with title tag name=u cbreplacefilename style=0) self.cbreplacefilename.setvalue(false) self.cbreplacefilename.bind(wx.evt_checkbox self.oncbreplacefilenamecheckbox) # create some sizers mainsizer = wx.boxsizer(wx.vertical) feedbacksizer = wx.boxsizer(wx.vertical) sourcesizer = wx.boxsizer(wx.horizontal) btnsizer = wx.boxsizer(wx.horizontal) feedbacksizer.add(self.trackolv 1 wx.all|wx.expand 2) feedbacksizer.add(self.actionsolv 1 wx.all|wx.expand 2) sourcesizer.add(sourcebtn 0 wx.all 2) sourcesizer.add(self.txsource 1 wx.all|wx.expand 2) sourcesizer.add(destbtn 0 wx.all 2) sourcesizer.add(self.txdest 1 wx.all|wx.expand 2) btnsizer.add(printbtn) btnsizer.add(movebtn 0 wx.all 2) btnsizer.add(self.cbsubfolders 0 wx.all 2) btnsizer.add(self.cbreplacefilename 0 wx.all 2) mainsizer.add(feedbacksizer 1 wx.all|wx.expand 2) mainsizer.add(sourcesizer 0 wx.all|wx.expand 2) #mainsizer.add(destsizer 0 wx.all|wx.expand 2) #mainsizer.add(destsizer 0 wx.all|wx.expand 2) mainsizer.add(btnsizer 0 wx.all 2) self.setsizer(mainsizer) #---------------------------------------------------------------------- # set the gui column headers and width #---------------------------------------------------------------------- def settracks(self data=none): self.trackolv.setcolumns([ columndefn( title left 100 title ) columndefn( artist left 100 artist ) columndefn( album left 100 album ) columndefn( source left 300 source ) columndefn( destination left 300 dest ) ]) def setactions(self data=none): self.actionsolv.setcolumns([ columndefn( time left 100 timestamp ) columndefn( action left 450 action ) columndefn( result left 450 result ) ]) #---------------------------------------------------------------------- # gui events #----------------------------------------------------------------------- eventlist = [action] #select source of files def onbrowsesource(self event): print onbrowsesource source = selectfolder( select the source directory ) print source self.txsource.setvalue(source) self.anevent = [action( source set as source dir )] self.actionsolv.addobjects(self.anevent) self.populatelist() #select source of files def onbrowsedest(self event): print onbrowsedest dest = selectfolder( select the destination directory ) print dest self.txdest.setvalue(dest) self.anevent = [action( dest set as destination dir )] self.actionsolv.addobjects(self.anevent) self.populatelist() def oncbsubfolderscheckbox(self event): print cbsubfolder self.populatelist() def oncbreplacefilenamecheckbox(self event): print cbreplacefilename self.populatelist() def onmovefiles(self event): print onmovefiles self.movefiles() def onprintbtn(self event): print onprintbtn for track in self.trackolv: print (track) #------------- #computations #------------- def definedestfilename(self sfulldestpath): print define dest icopyx = 0 bexists = false sorigname = sfulldestpath #if the file does not exist return original path/filename if os.path.isfile(sfulldestpath) == false: print - + sfulldestpath + is valid return sfulldestpath #add .copyx.mp3 to the end of the file and retest until a new filename is found while bexists == false: sfulldestpath = sorigname icopyx += 1 sfulldestpath = sfulldestpath + .copy + str(icopyx) + .mp3 if os.path.isfile(sfulldestpath) == false: print - + sfulldestpath + is valid self.lvactions.append([ desitnation filename changed since file exists sfulldestpath]) bexists = true #return path/filename.copyx.mp3 return sfulldestpath def populatelist(self): print populatelist ssource = self.txsource.value sdest = self.txdest.value #initalize list to reset all values on any option change self.initiallist = [track] self.trackolv.setobjects(self.initiallist) #create list of files if self.cbsubfolders.value == true: listoffiles = getlistrecursive(ssource) else: listoffiles = getlist(ssource) print listoffiles #prompt if no files detected if listoffiles == []: self.anevent = [action( parse source for .mp3 files no .mp3 files in source directory )] self.actionsolv.addobjects(self.anevent) #populate list after both source and dest are chosen if len(sdest) &gt; 1 and len(sdest) &gt; 1: print -iterate listoffiles for file in listoffiles: (ssource sfilename) = os.path.split(file) print ssource print sfilename #sfilename = os.path.basename(file) stitle = gettitle(file) try: sartist = getartist(file) except unicodedecodeerror: print unicode sartist = unkown salbum = getablum(file) # make path = sdest + artist + album sdestdir = os.path.join (sdest sartist) sdestdir = os.path.join (sdestdir salbum) #if file exists change destination to *.copyx.mp3 if self.cbreplacefilename.value == true: sdestdir = self.definedestfilename(os.path.join(sdestdir stitle)) else: sdestdir = self.definedestfilename(os.path.join(sdestdir sfilename)) # populate listview with drive contents #ssource = self.txsource.value sdest = self.txdest.value # todo: make source = exact source of track not parent source # todo: seperate dest and filename self.atrack = [track(stitle sartist salbum ssource sdestdir)] self.trackolv.addobjects(self.atrack) self.update() #populate list to later use in move command #self.validatedmove.append([file sdestdir]) print -item added to sourcedest list else: print -list not iterated def movefiles (self): print move files #for track in self.trackolv: # print -iterate sourcedest # #create dir # (sdest filename) = os.path.split(self.trackolv) # print -check dest # # if not os.path.exists(sdest): # print -created dest # os.makedirs(sdest) # self.lvactions.append([ sdest created ]) # self.update() # self.lvactions.ensurevisible(self.lvactions.getitemcount() -1) # # #move file # print -move file # shutil.move(sourcedest[0] sourcedest[1]) # self.lvactions.append([ filename moved ]) # self.update() # self.lvactions.ensurevisible(self.lvactions.getitemcount() -1) # #self.lvactions.append([ move complete success ]) #self.update() #self.lvactions.ensurevisible(self.lvactions.getitemcount() -1) ######################################################################## class mainframe(wx.frame): #---------------------------------------------------------------------- def __init__(self): wx.frame.__init__(self parent=none id=wx.id_any title= mp3 manager size=(1024 768)) #w by h panel = mainpanel(self) ######################################################################## class genapp( #---------------------------------------------------------------------- def __init__(self redirect=false filename=none): redirect filename) #---------------------------------------------------------------------- def oninit(self): # create frame here frame = mainframe() return true #---------------------------------------------------------------------- def main(): run the demo app = genapp() app.mainloop() if __name__ == __main__ : main() </code></pre>,python
why is my java method called twice this is the code called twice: <pre><code> public static defaultlistmodel getfriends(int nameoruser) { try { friend[] allfriends = skype.getcontactlist().getallfriends(); system.out.println( skype contact list lenght: + allfriends.length); for (friend friend : allfriends) { string fullname = friend.getfullname(); string username = friend.tostring(); if (fullname.isempty()) { fullname = friend.getid(); } fulllistmodel.addelement(fullname); userlistmodel.addelement(username); } } catch (skypeexception ex) { logger.getlogger(utils.class.getname()).log(level.severe null ex); } if (nameoruser == 0) { return fulllistmodel; } else if (nameoruser == 1) { return userlistmodel; } else { system.out.println( you must specify a valid data type. ); } return null; } </code></pre> the problem is that when i assign that to a jlist the jlist contains the contact list twice :/ hope i explained it well and sorry if my english was bad. edit: here s the calling code: <pre><code>fulllist.setmodel(utils.getfriends(0)); </code></pre>,java
assistance with a simple code for python basically i m working on a python fill in the letters type of game (kind of like hangman). the problem is i can t seem to get the program to record duplicate points. what i mean is: the program asks the user for a word. that word let s is converted into a masked string (ex. <strong><em>*</em>*</strong>) then it continually asks the user for letter inputs. let s say the user enters: f o t b a l and then it fills out the word. for each letter that is guessed correctly the user is awarded one point. but the problem is that for a word like football only 6 points are awarded because some of the letters are duplicates. basically the way i ve coded it each time a correct letter is guessed another point is added on top of the overall total points. is there a better way of doing this that can include the duplicate letters,python
how to create makefile in javascript <blockquote> <strong>possible duplicate:</strong><br> <a href= >make file for javascript</a> </blockquote> actually i am writing some javascript for testing purpose. i want to use multiple javascripts in which functions are defined. is there any way to achieve this i think make file is the way. but i don t know that also. i want to generate make file. can any body suggest me how is to be done,javascript
how to transform tuple of string(object locations) to dictionary of objects in python i would like to transform a tuple: <pre><code>test_classes = ( common.test.testclass ) </code></pre> to <pre><code>test_classes = { test : common.test.testclass } </code></pre> how to make a dictionary is simple but i have a problem with conversion from string to object. could anybody help me please thanks!,python
url in iphone sms content i m developing an iphone application where sms native application should open when the user clicks the button. this is working fine and i am also able to copy the content to clipboard when the user clicks on the button. but i want to provide a url in the sms content which i am copying so that the user click on the url to open it in the browser. can anyone suggest me how to provide clickable url in sms content,iphone
oauth for iphone sdk i have project which wants to login with oauth authentication link the twitter and facebook oauth. is there any library available for oauth in ios for the login purpose. if any one know how to do or where to get this library please help me. i tried a lot to create a library with the help of twitter oauth but no luck.,iphone
array elements being cleared after pushing from json file i have a function that reads integers from a json file and returns an array of those numbers. when i print the data it s all there. however when i check the length of the array before returning i get a size of 0. why <pre><code>function readjson() { var arr = []; $.getjson( foo.json function(obj) { for(i = 0; i &lt; obj.length; i++) { arr.push(obj[i][ _bar ]); // prints: 1 2 3 4 5 console.log(obj[i][ _bar ]); } }); // prints 0 console.log(arr.length); return arr; } </code></pre>,javascript
how can i used the “” to get file(.exe) version i want to used python to get the executed file version and i know the <a href= rel= nofollow noreferrer ></a> how to used it to do this notes: the executed file may be not completely.,python
how to store/retrieve application data incase application deleted accidentally i am having an application in which i am having sqlite database too ..if i delete that application accidentally. is there any way to get back the same application with the same database. or is there any way to keep database alone in a separate place inside iphone memory so that we can recover after application delete if needed. please tell me how to achieve the above . regards v.k.,iphone
how to give sketch effect on image in iphone i am implementing an iphone application in which i have implemented the following functionalities: <ol> <li>select photo</li> <li>capture photo</li> <li>now i want to give a sketch effect to that photo like <a href= mt=8 rel= nofollow >this one.</a></li> </ol> how could i do this,iphone
passing option constants as arguments to a class i have a python class that takes an arguments to set the state of an object. this argument must be one option in a list of available options; for example a traffic light can either be red green or orange. i have two approaches to handle this problem. i can use a string to set the state but then i ll have to do additional error checking and it is unclear without looking at the code what states are available. alternatively i can create a class that acts as an enum. which of these methods (or what other method) should i use example with strings: <pre><code>class light(object): def __init__(self color): self.color = color def turn_on(self): if self.color == red : self.turn_on_red_light() if self.color == green : self.turn_on_green_light() if self.color == orange : self.turn_on_orange_light() def turn_on_red_light(): # do stuff return def turn_on_green_light(): # do stuff return def turn_on_orange_light(): # do stuff return light = light( red ) light.turn_on() </code></pre> alternative using simple enum : <pre><code>class colors(object): red green orange = range(3) class light(object): def __init__(self color): self.color = color def turn_on(self): if self.color == self.turn_on_red_light() # as above if self.color == self.turn_on_green_light() # as above if self.color == self.turn_on_orange_light() # as above light = light( light.turn_on() </code></pre> maybe this is not the best example as you can just call <code>light.turn_on_red_light()</code> but then that logic to decide what function to call must sit somewhere else. let s pretend that is not an option. i come across this situation often. frequently i use it to define settings within the class. i d be interested to know what is the preferred method in python or any other ways it can be improved,python
how to make xcode generated coredata model class to use nsinteger for int32 column seems silly to me that it generates nsnumber when i specify the column as int. this makes calculations and updates tedius... e.g. x = [nsnumber numberwithinteger:([x intvalue] + 1)]; there is the use primitive types checkbox but it uses char array instead of nsstring which is not what i want. so is it possible to tell it to generate nsinteger if if i manually change the code to use nsinteger will it work,iphone
trying to start javascript koans - can t even load the first codeset here is my error: <pre><code>jasmine.expectationresult@file:///e:/dropbox/---%20javascript%20---/javascript-koans-master/lib/jasmine/jasmine.js:94 @file:///e:/dropbox/---%20javascript%20---/javascript-koans-master/koans/aboutexpects.js:5 </code></pre> so is the problem that i have spaces in my filepath or is it those colons i see after each .js file the js files definitely don t have those colons when i look in the directories in github. <a href= rel= nofollow ></a>,javascript
java println method error i am trying to print times that it takes to do certain methods. i use <blockquote> double t0 = 0.01 * system.currenttimemillis(); i have 3 times like that one. and when i print it like this: </blockquote> <pre><code>system.out.println( %7d %10.7f %10.7f amount (t1 - t0) (t2 - t1)); </code></pre> i get an error: <blockquote> no suitable method found for println(string int double double) </blockquote> why is that where does that string parameter come from,java
cm to inch converting program python hello i am trying to make a converting program but i can t get it to work i am going to convert multiply different things but i start with cm to inch. i get error typeerror: unsupported operand type(s) for /: str and float . here is some of the code: <pre><code> print( press the number of the one you want to convert: ) number = input() inch = float(2.54) if number == 1 : print( how many inch ) print( there are %s .format(number / inch)) here is the whole code: print( welcome to the converting program ) print( what of these do you want to convert ) print( \nhow many centimeters in inches 1 \nhow many milliliters in a pint 2 \nhow many acres in a square-mile 3 \nhow many pounds in a metric ton 4 \nhow many calories in a btu 5 ) print( press the number of the one you want to convert: ) number = float(input()) inch = float(2.54) if number == 1 : print( how many inch ) print( there are {0} .format(number / inch)) elif number == 2 : print( millimeters ) elif number == 3 : print( acres ) elif number == 4 : print( pounds ) elif number == 5 : print( calories ) </code></pre>,python
object methods of same class have same id <pre><code>class parent(object): @classmethod def a_class_method(cls): print in class method %s % cls @staticmethod def a_static_method(): print static method def useless_func(self): pass p1 p2 = parent() parent() id(p1) == id(p2) // false id(p1.useless_func) == id(p2.useless_func) // true </code></pre> in the above code i dont understand why is the useless_func has same id when it belongs to two different objects,python
how can i split a long function into separate steps while maintaining the relationship between said steps i have a very long function <code>func</code> which takes a browser handle and performs a bunch of requests and reads a bunch of responses in a specific order: <pre><code>def func(browser): # make sure we are logged in otherwise log in # make request to /search and check that the page has loaded # fill form in /search and submit it # read table of response and return the result as list of objects </code></pre> each operation require a large amount of code due to the complexity of the dom and they tend to grow really fast. what would be the best way to refactor this function into smaller components so that the following properties still hold: <ul> <li>the execution flow of the operations and/or their preconditions is guaranteed just like in the current version</li> <li>the preconditions are not checked with asserts against the state as this is a very costly operation</li> <li><code>func</code> can be called multiple times on the browser</li> </ul>,python
javascript getting an array from an array in an object i have an object <code>myobject</code> and one of its properties <code>itemids</code> is an array of ints. i want to get a new array <code>pageitemids</code> that contains only part of the ints. it s for a pager; i pass in the page number <code>pagenumber</code> and i get the ids of the items on the page. suppose the page size is 20 items. this is what i tried. it doesn t work because js works with references so i end up changing the array of the object. <pre class= lang-js prettyprint-override ><code>pageitemids = myobject.itemsid; pageitemids = pageitemids.splice(pagenumber * 20 20); </code></pre> and instead of getting the itemids in the page i end up with the itemids not in the page. i know i m not that far off but if you can help that d be nice. thanks. edit: when i do <pre><code>pageitemids = pageitemids.slice((pagenumber -1) * 20 20); </code></pre> it works for page 1 but for every other page it returns an empty array. ok i got it nevermind. <pre><code> pageitemids = pageitemids.slice(pagenumber * 20 pagenumber * 20); </code></pre>,javascript
return a list by reading a text file i am reading a text file separated by space the file looks like: first line:hello 2928977 [1.2 9.7] second line: apple 6723547 [8.2 3.1] .... i want to return a list like[(hello 1.2 9.7) (apple 8.2 3.1) ...] how do i do this i know the first step is to set an empty list and then do <pre><code> output =[] inputfile = open( text.txt r ) for eachline in inputfile: l=line.strip() s=l.split( ) output.append((s[0] float(s[2][0]) float(s[2][1])) return output </code></pre> but this doesn t work... it says invalid syntax....can someone help me also i tried with another file with this method but it says strings cannot be converted into float... i can t get this working i would really appreaciate your help!thanks!!!!!!!,python
prototype library use of !! operator <blockquote> <strong>possible duplicates:</strong><br> <a href= >what does this expression mean &ldquo;!!&rdquo;</a><br> <a href= >what does the !! operator (double exclamation point) mean in javascript </a> </blockquote> here is a snippet from prototype javascript library : <pre><code> browser: (function(){ var ua = navigator.useragent; var isopera = == [object opera] ; return { ie: !!window.attachevent &amp;&amp; !isopera opera: isopera webkit: ua.indexof( applewebkit/ ) &gt; -1 gecko: ua.indexof( gecko ) &gt; -1 &amp;&amp; ua.indexof( khtml ) === -1 mobilesafari: /apple.*mobile/.test(ua) } })() </code></pre> this is all good and i understand the objective of creating a browser object. one thing that caught my eye and i haven t been able to figure out is the use of double not operator <strong>!!</strong> in the ie property. if you read through the code you will find it at many other places. i dont understand whats the difference between <code>!!window.attachevent</code> and using just <code>window.attachevent</code>. is it just a convention or is there more to it that s not obvious,javascript
how can i make my python script run forever i have a python script (excerpt shown below) that reads a sensor value. unfortunately it runs only for 5 - 60 minutes at a time and then suddenly stops. is there a way i can efficiently make this run forever is there any reason why a python script like this couldn t run forever on a raspberry pi or does python automatically limit the duration of a script <pre><code> while true: current_reading = readadc(current_sensor spiclk spimosi spimiso spics) current_sensed = (1000.0 * (0.0252 * (current_reading - 492.0))) - correction_factor values.append(current_sensed) if len(values) &gt; 40: values.pop(0) if reading_number &gt; 500: reading_number = 0 reading_number = reading_number + 1 if ( reading_number == 500 ): actual_current = round((sum(values)/len(values)) 1) # open up a cosm feed pac = eeml.datastream.cosm(api_url api_key) #send data pac.update([ actual_current)]) # send data to cosm pac.put() </code></pre>,python
effect of having use strict ; in file scope but not at the top i understand it shouldn t be done take this as an academic question.<br/> if i was to say concatenate several javascript files some with <code> use strict ;</code> at the top and some without what would be the outcome i know that if you put the phrase at the top of the file it enables strict mode for the entire file and if it is at the start of a function it is scoped to that function.<br/> but what if the first <code> use strict ;</code> is mid-way down i guess you can extrapolate this quest to function-scoped uses as well. will it; <ul> <li>have no effect </li> <li>enable strict mode for the whole file or</li> <li>somehow enable strict mode for only the remaining length of the code </li> </ul> e.g. <pre class= lang-js prettyprint-override ><code>/*from file1.js*/ function bob() { willthiserror = because of use strict mode below ; } /*from file2.js*/ use strict ; function bob2() { var thisauthor = likes to enable strict mode ; } </code></pre> or <pre class= lang-js prettyprint-override ><code>//midway through function function test() { willthiserror = ; use strict ; var orwillit = have no effect ; } </code></pre> i guess i could just test it myself but i m interested in a spec reference or something and not to get caught up in browsers individual interpretations on strict mode declaration.,javascript
iphone: find phone number in text what i need is find in text phones numbers and make it colored and clickable and when click on that it s should call by this there on iphone ready solution for that or i should write regular expression to find phones numbers than make it colored an clickable the reason i m asking is that android have ready method for that and i don t need to do anything... thanks...,iphone
is calling buffer.flip() twice in a row problematic flip sets limit to position and then position to 0. if you call flip twice does limit get set to 0 sometimes i don t know whether a method that takes a buffer should be responsible for flipping the buffer or should the method caller do it. i would like to be able to call .flip in the method just incase the methodcaller did not do it. but does this cause a problem,java
selecting number of id s using loop in javascript i have 5 different id s as below: <pre><code>&lt;div id = box1 &gt;&lt;/div&gt; &lt;div id = box2 &gt;&lt;/div&gt; &lt;div id = box3 &gt;&lt;/div&gt; &lt;div id = box4 &gt;&lt;/div&gt; &lt;div id = box5 &gt;&lt;/div&gt; </code></pre> is there any way to call each id using for loop in javascript <pre><code>for(int i=0; i&lt;5; i++){ //i want to call those ids each at a time. at first box1 then box2... } </code></pre>,javascript
what happens if we split by a delimiter yet have multiple of those delimiters in a row say i have a string <code> word1 word2 word3 word4 etc </code> however instead of there being only one space between the words the amount of spaces is random greater than 1. how does <code>split( )</code> work in such cases,python
decompose a string into array of long or list of long without loop in java i want to decompose a string array into long array or list. i don t want to use loop. is there any java method to do this.,java
how to wait indefinitely for the dom load the function: <pre><code>window.addeventlistener( domcontentloaded function(){}); </code></pre> or <pre><code>window.addeventlistener( load function(){}); </code></pre> it allows me to do anything as fast as it loads the dom with some particularities between both methods. this is <code> as soon as </code> but how can i wait indefinitely to load the dom and just load the dom execute the function let me explain: imagine i have a function anyone. <pre><code>cube cube = n =&gt; math.pow (n 3); if (document.readystate === complete ) cube (3); </code></pre> suppose the cube function is fundamental in my code. but if the dom has not loaded the function will not have been executed. so how can i wait indefinitely until the dom loads and postpone another function which acts in response to this main function (cube) so if my script reached that point and the dom did not load all those functions would not have any value. my focus instead of <blockquote> if this happens do this </blockquote> is: <blockquote> wait for this to happen and do this </blockquote>,javascript
assigning functions as attributes of an object then calling without the implied self arguement python allows you to assign a pre-defined function to a class as an attribute such as <pre><code>def fish_slap(fish): # do something class dance(object): dance_move=fish_slap </code></pre> however if we try do say <pre><code>d=dance() d.dance_move( halibut ) </code></pre> we get the get the following error <pre><code>typeerror: fish_slap() takes exactly 1 arguement (2 given) </code></pre> python seems to be viewing this as a object method and providing the implied self argument. fair enough it seems i ve just learned that assigning a function as an attribute in this way is equivalent to defining the function directly within the class. i can see that this is a useful feature. however in this case this is not what i want. in my application i have statistical models encoded as different classes which also have their own train methods for training the model parameters against supplied data. in order to do this an objective function that you wish to minimize (or maximize) the value of needs to be supplied. an example simple objective function is say <pre><code>def rmse(predicted observed): root mean squared error return sp.sqrt(sp.mean((predicted-observed)**2)) </code></pre> where scipy has been imported as sp. these objective functions are defined in a single .py file and used throughout my code and naturally exists as standalone functions rather than as class methods with the implied self argument. i want to be able to set the desired objective function as an attribute so that any subsequent work a model object does uses that function for instance <pre><code>some_model=somemodel(initial_parameter_values_guess) some_model.objective_function = rmse some_model.train(training_data) predictions_rmse = some_model.predict() some_mode.objective_function = mae predictions_mae = some_model.predict() </code></pre> in this example is seems i could just pass the objective function as an argument to train however in my application there is a lot more one would want to do and it seems to make more sense to be able to set/get the objective function rather than repeatedly providing it as an argument. there are any number of workarounds to achieve this basic behavior but what is the most pthonic approach note that my current code is python2 and python3 compliant. if there are version specific solutions please point that out. i am running with python2 in order to be able to use matplotlib however i am trying to ensure the code is python3 compatible apart from that module.,python
pulsating blue circle and dot in mapkit - iphone sdk how can i add the pulsating blue circle in my gps application. currently i am fetching my current location by cclocationmanager. i am using mapview.showsuserlocation = true but this only display a pin at my current location. how can i get that blue circle as in the default maps app. update: many app does this. for example - thanks,iphone
javascript error on href getelementbyid when null i have a popup that lets the user change a href if set or not. if not set i display optional web link as field title. however i m getting a javascript error on the if line that href is null. how can i get href or test it without the error getting in the way in this application href will be null at times so i need my script to deal with it somehow. <pre><code>if (document.getelementbyid( sidebarhref- +id).href == ) { var href = document.getelementbyid( sidebarhref- +id).href; } else { var href = optional web link ; } </code></pre>,javascript
python simple for loop issue currently learning python. normally a c++ guy. <pre><code>if wallpaper == y : charge = (70) print ( you would be charged £70 ) wallpaperlist.append(charge) elif wallpaper == n : charge = (0) else: wallpaper () surfacearea totalpapers = 0 for item in range (len(wallpaperlist)): totalpapers += wallpaperlist[item] </code></pre> i am trying do a for loop for the if statement. in c++ this will just be a simple <pre><code>for (i=0; i&lt;prooms; i++){ } </code></pre> i am trying to add the above code in a for loop but i seem to fail. thanks,python
error in string index out of range: maf file to fasta file context: i am trying to convert a maf file (multiple alignment file) to individual fasta file. i keep running into the same error that i m not sure how to fix and this may be because i m relatively new to python. my code is below: <pre><code>open_file = open( c:/users/danielle/desktop/maf_file.maf r ) for record in open_file: print(record[2:7]) if (record[2] == z ): new_file = open(record[2:7]+ .fasta w ) header = &gt; +record[2:7]+ \n sequence = record[46:len(record)] new_file.write(header) new_file.write(sequence) new_file.close() else: print( not correct isolate. ) open_file.close() </code></pre> the error i get is: <pre><code>indexerror traceback (most recent call last) 2 for record in open_file: 3 print(record[2:7]) ----&gt; 4 if (record[2] == z ): 5 new_file = open(record[2:7]+ .fasta w ) 6 header = &gt; +record[2:7]+ \n indexerror: string index out of range </code></pre> if i remove the if else statement it works as i expect but i would like to filter for specific species that start with the character z. if anyone could help explain why i can t select for only strings that start with the character z this way that would be great! thanks in advance.,python
ios sdk: how to get the date out of a uidatepicker i need to retrieve the date from a uidatepicker (preferably i would also like to be specify the format as well. for example mmdd would output the string 1209. any string that reasonably parsed would work as well. thanks in advance.,iphone
how to add native library .so file in java netbeans how to link native library .so file in netbeans exception in thread main java.lang.unsatisfiedlinkerror: no lib in java.library.path,java
javascript onclick even on a div not working i have a div and when a user clicks on it using the <code>onclick</code> event i m calling a function: <pre><code> function test(a) { alert(a); } &lt;div onclick= javascript:test( zaswde ); &gt;sdfasdasdadasdasds&lt;/div&gt;​ </code></pre> <strong>update</strong> <pre><code> &lt;ul&gt; &lt;li&gt; &lt;div&gt; &lt;div onclick= javascript:alert( v ); &gt;&lt;/div&gt; &lt;/div&gt; &lt;div &gt;&lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> can t i use <code>onclick</code> on the div element ​,javascript
java: throws runtimeexception how is the below one correct i expected compiler to tell me to use <code>throws exception</code> or <code>throws runtimeexception</code> <pre><code>public void method1() throws nullpointerexception { throw new runtimeexception(); } </code></pre> why i think its not correct -> bcoz a npe is a rte but a rte is not a npe how is this correct i expected compiler to tell me to use <code>throws exception</code> or <code>throws runtimeexception</code> or <code>throws numberformatexception</code> <pre><code>public void method2() throws nullpointerexception { throw new numberformatexception(); } public void method3() throws exception { // this is fine as expected throw new runtimeexception(); } public void method4() throws runtimeexception { // this is fine as expected throw new nullpointerexception(); } public void method5() throws exception { // this is fine as expected throw new nullpointerexception(); } </code></pre> <strong>answer:</strong> for rte even if u don t add <code>throws</code> clause to the method compiler won t say anything <pre><code>public void method6() { // no compile time errors!! throw new nullpointerexception(); } </code></pre> but when we explicitly say that <code>throw new nullpointerexception();</code> why compiler ignores it it is same as <code>throw new sqlexception()</code>; it is not thrown on runtime say some object was evaluated to null and invoked an action on that null object. normally a function must declare all the exceptions that it can throw but rte s is bypassing it! rte s are unchecked exceptions. but when you say throw new rte still unchecked ! <strong>question</strong> - isn t this a flaw or please correct me in understanding why is it like that <ul> <li><strong>update:</strong></li> </ul> please note that this question is <strong>not about difference between</strong> checked exception and unchecked exception. the question is not about difference between any type of exception or error. the question is why an explicitly marked runtimeexception is not handled or left without forcing the compiler to handle it. eg: <pre><code>public void methoda() { // methoda is not forced to handle the exception. methodb(); } public void methodb() throws runtimeexception { } </code></pre>,java
calculating the average number in a nesting loop java does anyone knows how to calculate the average in a loop. every time i calculated the average i received 0 or 1. i know that i need use average = (sum) / (salary_annually); but i can t get it to work. thanks in advance. <pre><code> import java.util.scanner; public class midterm { public static void main(string args[]) { scanner kb = new scanner(; int max = integer.min_value; int min = integer.max_value; int sum = 0; int average=0; int count = 0; int salary_annually = 0; for(int employee =1; employee &lt;= 2; employee++) { system.out.println( employee: + employee); for(int year=1; year &lt;= 2; year++) { system.out.println( please enter the salary for year: + year); salary_annually = kb.nextint(); sum += salary_annually ; if (min &gt;= salary_annually) { min = salary_annually; } if (max &lt;=salary_annually) { max = salary_annually; } average = (sum) / (salary_annually); } system.out.println( the average is + average); system.out.println( the higher number + max); system.out.println( the the lowest number + min); } } } </code></pre>,java
how to print all the list values in the mail body without square bracket in java here is my code : inside the sendmail() method am not able to get all the file names without square bracket. please help me to solve this. here finalvalue is an arraylist. if i use .get() am getting outofboundexception. <pre><code>simpledateformat sdf1 = new simpledateformat( dd mmm yyyy z ); string lastmodifieddate=sdf1.format(file1.lastmodified()); dateformat formatter = new simpledateformat( dd mmm yyyy z ); formatter.settimezone(timezone.gettimezone( cet )); if(sdf1.format(file1.lastmodified()).compareto(formatter.format(date))==0){ strfilenamemodifieddate=filesinsidefolder+ : +lastmodifieddate; system.out.println(strfilenamemodifieddate); list.add(strfilenamemodifieddate); system.out.println( final: +list); totalelements = list.size(); system.out.println( total elements: +totalelements); for(index=0; index &lt;totalelements; index++) { //system.out.println(index); system.out.println( currently modified files1: +list.get(index)); finalvalue.add(path2.get(index)); } message.settext(config_applbody+ \n +finalvalue+ \n\n + config_applsig); </code></pre>,java
securing iphone + web app i have an iphone app that retrieves and send data to a server that uses python. what measures could i take in order to prevent security risks i an not handling extremely sensitive data but i wouldn t want people sniffing the contents. is using ssl enough to prevent most risks thanks,iphone
java-what is the best way to check if a string contain alphanumeric characters or not i am new to regular expression can any one tell me what is the best option to check if a string is containing only alphanumeric characters and why <code>value.matches( ^[a-za-z0-9]*$ );</code> or <code>value.matches( \\w+ );</code>,java
python values in lists i am using python 3.0 to write a program. in this program i deal a lot with lists which i haven t used very much in python. i am trying to write several if statements about these lists and i would like to know how to look at just a specific value in the list. i also would like to be informed of how one would find the placement of a value in the list and input that in an if statement. here is some code to better explain that: <pre><code>count = list.count(1) if count &gt; 1 (this is where i would like to have it look at where the 1 is that the count is finding) </code></pre> thank you!,python
javascript beginner : do while loop for repeat i have no idea why the do while code cannot repeat ask the question...and after i put the do while ...there is no function at all... <pre class= lang-js prettyprint-override ><code>&lt;script type= text/javascript &gt; var done; do{ var num = prompt( enter number 0 ) //prompt user to enter the number number = parseint(num); //parse the num to number var i; document.write( &lt;table border= 1 cellspacing= 0 &gt; ); for(i=1;i&lt;=12;i++) { document.write( &lt;tr&gt;&lt;td&gt; + i + x + number + = + number*i + &lt;/td&gt;&lt;/tr&gt; ); } document.write( &lt;/table&gt; ); }while(window.confirm( do you want to enter another number to show another multiplication table ) &lt;/script&gt; </code></pre>,javascript
uipickerview on uiscrollview in my app i have a uipickerview on uiscrollview. when i check the delaycontenttouches in ib the uiscrollview scrolls but uipickerview do not scrolls smoothly. and if i uncheck it then my uipickerview scrolls smoothly but uiscrollview do not. uiscrollview is added as subview to my view. all controls are on the uiscrollview. i am unable to figure it out why its behaving like this. please guide me. is i am missing something or doing wrong thanks panache.,iphone
can anybody tell me the procedure of debugging in java i am new to the java can anybody tell me the debugging procedure in eclipse.. i.e. how to perform a debugging on a program.. thanks in adavance..,java
after addition two variables in javascript returning some garbage values hi i have two variables in js like: <pre><code>var a = 223620.42 var b = 1200.1234 </code></pre> i am using calculation like: <pre><code>var c = parsefloat(a) + parsefloat(b); </code></pre> so the result should be = <code>224820.5434</code> but it returning <code>224820.54340000002</code> please suggest me what i am doing wrong here. thanks in advance,javascript
reduce image size without changing the dimensions programmatically in iphone does any one how to reduce image size without changing the dimensions of that image programmaticallyin iphone,iphone
"how can a read only property(element.classlist) can be modified or assigned to some other value in javascript <div class= snippet data-lang= js data-hide= false data-console= true data-babel= false >
<div class= snippet-code >
<pre class= snippet-code-js lang-js prettyprint-override ><code>window.addeventlistener( keydown function(e) {
const key= document.queryselector(`div[data-key= ${e.keycode} ]`);
key.classlist=[ ajay dish ];
<pre class= snippet-code-html lang-html prettyprint-override ><code>&lt;div data-key= 65 class= key ajay &gt;
<img src= alt= enter image description here > above is a screenshot of chrome devtools with values modified. i read on <a href= rel= nofollow noreferrer >mdn</a> that <code>element.classlist</code> is read only property but can be modified by <code>add()</code> etc. i assigned it to some other array and that is working too. in other cases whenever i tried to modify/assign read only property it always gave <code>typeerror</code>.",javascript
event listener not responding - javascript i am trying to write a quiz in pure javascript that loads new questions from an array and fills a table when the user clicks next. a seemingly simple problem i have is that i cannot get an event listener to work when the user clicks the next button. on jsfiddle it works but it won t work on my end and i have no idea why. just as a test i have it alerting if the button is pressed. i have also tested multiple different ways of checking if the document has loaded before executing to no avail. html <pre><code>&lt;body&gt; &lt;table class= center &gt; &lt;tr&gt; &lt;th id= question colspan= 2 &gt;question&lt;/th&gt; &lt;td colspan= 2 &gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td id= answer0 &gt;choice 1&lt;/td&gt; &lt;td&gt;&lt;input id= radio0 type= radio name=que_1 value= 1 required/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td id= answer1 &gt;choice 2&lt;/td&gt; &lt;td&gt;&lt;input id= radio01 type= radio name=que_1 value= 1 /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td id= answer2 &gt;choice 3&lt;/td&gt; &lt;td&gt;&lt;input id= radio02 type= radio name=que_1 value= 1 /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td id= answer3 &gt;choice 4&lt;/td&gt; &lt;td&gt;&lt;input id= radio03 type= radio name=que_1 value= 1 /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;div&gt; &lt;input type= button id= next value= next &gt; &lt;/div&gt; &lt;/body&gt; </code></pre> javscript <pre><code>document.getelementbyid( next ).addeventlistener( click function() { alert( works ); }); </code></pre> thank you in advanced.,javascript
how to kill setinterval() function in javascript i have this finction: <pre><code> var msec = 100; setinterval(function () { if (childnodedocument.readystate == complete ) { parent.parent.mapframe.hidemodal; alert( complete ); clearinterval(); } } msec); </code></pre> when this condition is satisfied: <pre><code>childnodedocument.readystate == complete </code></pre> i want to stop executing setinterval(). but the way i am doing above not working. any idea what i am missing,javascript
is it the best way to compare python objects considering these classes <pre><code>class foo(object): def __init__(self owner): self.owner = owner self.a = none self.b = [] object = foo(mike) </code></pre> each hour i need to check if foo is updated (object.a or object.b has changed) how can i do do i need to create a new object object2=foo(mike) and parse attribute to compare with object put the difference into a list or is there a pythonic way to do it if a create two objects parse them to build 2 lists and compare them is a good idea,python
weakreference symbol cannot be found already import the weakreference but the compiler cannot find the symbol what wrong there a memory leak in i thought weakreference might free after used <pre><code>import java.lang.ref.weakreference; receiver r = new dumpreceiver(system.out); weakreference&lt;receiver&gt; wr = new weakreference&lt;dumpreceiver&gt;(r); cannot find symbol symbol : constructor weakreference(javax.sound.midi.receiver) location: class java.lang.ref.weakreference&lt;dumpreceiver&gt; weakreference&lt;receiver&gt; wr = new weakreference&lt;dumpreceiver&gt;(r); ^ </code></pre>,java
javascript how `length` is implemented you know that in javascript you can access the length of an text/array with length property: <pre><code>var obj = [ robert smith john mary susan ]; // obj.length returns 5; </code></pre> i want to know how this is implemented. does javascript calculates the length property when it is called or it is just a static property which is changed whenever the array is changed. my question is asked due to the following confusion in best-practices with javascript: <pre><code>for(var i = 0; i &lt; obj.length; i++) { } </code></pre> <strong>my problem:</strong> if it is a static property then accessing the length property in each iteration is nothing to be concerned but if it is calculated on each iteration then it cost some memory. i have read the following definition given by ecmascript but it doesn t give any clue on how it is implemented. i m afraid it might give a whole instance of array with the length property calculated in run-time that if turns out to be true then the above <code>for()</code> is dangerous to memory and instead the following should be used: <pre><code>var count = obj.length; for(var i = 0; i &lt; count; i++) { } </code></pre>,javascript
how do i run iometer using python i am trying to setup test automation. i would like to run several different sets of iometer tests without individually hitting go for all of them. how do i do that using python if you know a different method that would work too. i just have the rest of the test automation setup with python. side note: can iometer record data every 5 seconds for a 30min test,python
js - find x y of middle of black square in image i have a bunch of images like this one: <a href= rel= nofollow noreferrer ></a> i need to find the x y of the middle of the dark square. i currently have the following code: <a href= rel= nofollow noreferrer ></a> <pre><code>function rgbtohsl(r g b) { r /= 255 g /= 255 b /= 255; var max = math.max(r g b) min = math.min(r g b); var h s l = (max + min) / 2; if (max == min) { h = s = 0; // achromatic } else { var d = max - min; s = l &gt; 0.5 d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g &lt; b 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return ({ h: h s: s l: l }); } function solve_darkest(url callback) { var image = new image(); image.crossorigin = anonymous ; image.src = url; image.onload = function(){ var canvas = document.createelement( canvas ); var width = image.width; var height = image.height; canvas.width = width; canvas.height = height; var context = canvas.getcontext( 2d ); context.drawimage(image 0 0); document.body.appendchild(canvas); var imgdata = context.getimagedata(0 0 width height); var pixel = 0; var darkest_pixel_lightness = 100; var darkest_pixel_location = 0; for (var i = 0; i &lt;; i += 4 pixel++) { red =[i + 0]; green =[i + 1]; blue =[i + 2]; alpha =[i + 3]; if (alpha &lt; 230) { continue; } console.log(math.floor(pixel / width) + i % width); var hsl = rgbtohsl(red green blue); var lightness = hsl.l; if (lightness &lt; darkest_pixel_lightness) { darkest_pixel_lightness = lightness; darkest_pixel_location = pixel; } } var y = math.floor(darkest_pixel_location / width); var x = darkest_pixel_location % width; callback(x y); }; } image_url = ; solve_darkest(image_url function(x y) { settimeout(function() { alert( x: +x+ y: +y); } 100); }); </code></pre> but it is not giving me the results i am expecting. it loops through all the pixels and then returns the x and y of the darkest pixel. however it appears that the darkest pixel doesn t reside in the dark square area. what can i do to make it return the x y of the middle of the darker square,javascript
how can i move continuos enemy sprite top to bottom here is some problem which i can not understand... i want to move one enemy sprite top to bottom but enemy sprite is in different class and can not move it. here is code of add sprite in gamescene through enemyscene this is code of enemy.m <pre><code>#import enemy.h #import gamescene.h @implementation enemy @synthesize thegame newsprite lasttimefired firingspeed fireinterval movementspeed launched hp maxhp; -(id)initwithgame:(gamelayer *)game { self=[super init]; if(self !=nil) { cgsize size=[[ccdirector shareddirector]winsize]; self.thegame=game; self.lasttimefired=0; nslog(@ enemy init ); int random=arc4random()%3+1; newsprite=[ccsprite spritewithfile:[nsstring stringwithformat:@ enemy%d.png random]]; newsprite.position=ccp(100 200); [thegame addchild:newsprite]; switch (random) { case 1: movementspeed=5; fireinterval=-1; break; case 2: movementspeed=10; fireinterval=-1; break; case 3: movementspeed=7; fireinterval=-1; break; case 4: movementspeed=3; fireinterval=-1; break; default: movementspeed=5; fireinterval=-1; break; } } return self; } </code></pre> and i want to move this enemy sprite into gamescene layer and here is the code gamescene.m <pre><code>#import gamescene.h #import hero.h #import enemy.h #define starting_lives 3; @implementation gamescene -(id) init { self =[super init]; if(self !=nil) { [self addchild:[gamelayer node]]; } return self; } -(void) dealloc { [super dealloc]; } @end @implementation gamelayer -(id)init { if(self=[super init]) { hero *hero=[[hero alloc]initwithgame:self]; enemy *e=[[enemy alloc]initwithgame:self]; lasttimeenemylaunched=0; enemyinterval=20; lives=3; [self schedule:@selector(dothis)]; nslog(@ after schedule ); } return self; } -(void)dothis { enemy *e; [e update]; } @end </code></pre> please help me i am new in cocos2d game development... when i am run this code in simulator than it gives on error this code gives exc_bad_access <pre><code> -(void) update: (cctime) dt { if( elapsed == - 1) elapsed = 0; else elapsed += dt; if( elapsed &gt;= interval ) { impmethod(target selector elapsed); //this code gives exc_bad_access elapsed = 0; } } </code></pre> please help me.... thanks,iphone
iphone: how to find out which object was touched on my uiviewcontroller i have different uiviews and some of them are my custom uiviews. how to know which uiview was touched my custom or not,iphone
how to create .ipa file & how to install .ipa in iphone/ipad i have developed a mobile native app using jquerymobile. now i want to deploy that app on <code>iphone</code>. for this one i want <strong>.ipa</strong> file. how to create <code>.ipa</code> &amp; install <strong>.ipa</strong> file in the <code>iphone</code>,iphone
"what is the prototype linkage for objects created via the object literal notation in javascript my first post on stack overflow and so a complete newbie here and i am still getting used to the rules / annotations followed on this forum and so please do excuse this aspiring developer ;-) while reading through crockford s <em>good parts</em> i came across a line that said: <blockquote> <h2>every object is linked to a prototype object from which it can inherit properties. all objects created from object literals are linked to object.prototype an object that comes standard with javascript.</h2> </blockquote> so to test this out i wrote the following jscript code: <pre><code>var student = {} console.log(student.isprototypeof(object.prototype)) </code></pre> note: <ol> <li>i am executing this via the <strong>browser console</strong> and hence the function - <code>console.log(...)</code>.</li> <li>i am guessing the way the student variable declared here is using the <em>object literal notation</em> . isn t that correct </li> </ol> so the second line - <pre><code>console.log(student.isprototypeof(object.prototype)) </code></pre> returned a <strong>false</strong> instead of a <strong>true</strong>. shouldn t that display a <strong>true</strong> instead of a <strike>false</strike> well doesn t that contradict the lines from the book that i mentioned above so here is the snippet in action - <div class= snippet data-lang= js data-hide= false >
<div class= snippet-code >
<pre class= snippet-code-js lang-js prettyprint-override ><code>var student = {};
<em>i am sure that i missing something here for sure!</em>",javascript
i am unable to create temporary file i am trying to create a temporary files using java.but when i run my codes it shows the following error. <pre><code> cannot find symbol symbol : class path location: class number path tempfile = files.createtempfile(null .txt ); ^ cannot find symbol symbol : method createtempfile(&lt;nulltype&gt; java.lang.string) location: class files path tempfile = files.createtempfile(null .txt ); ^ 2 errors </code></pre> and here s the code and when i import;.then it show error package does not exist <pre><code>import*; public class number{ public static void main(string args[]) {try { path tempfile = files.createtempfile(null .txt ); system.out.format( the temporary file + has been created: %s%n tempfile); } catch (ioexception x) { system.err.format( ioexception: %s%n x); } }} </code></pre>,java
iphone - uiview inside uiscroller... view not passing touches to parent i have a uiview (lets call it myview) inside a uiscroller. myview has elements that can be dragged on it. when one of these elements are touched the scroller is locked to prevent the whole thing from scrolling. the elements have exclusivetouch = yes. i need the whole thing to scroll when just myview is touched. i had this working with touchesbegan touchesmoved etc. but i am converting this class to gestures. the new class has two gestures attached to it: uipangesturerecognizer and uitapgesturerecognizer. something like: <pre><code> uipangesturerecognizer *pangesture = [[uipangesturerecognizer alloc] initwithtarget:self action:@selector(drag:)]; [pangesture setmaximumnumberoftouches:1]; [pangesture setdelegate:self]; [myview addgesturerecognizer:pangesture]; [pangesture release]; uitapgesturerecognizer *singletap = [[uitapgesturerecognizer alloc] initwithtarget:self action:@selector(tapadd:)]; [singletap setdelegate:self]; [singletap setnumberoftapsrequired:1]; [myview addgesturerecognizer:singletap]; [singletap release]; </code></pre> when this class used the old methods (touchesbegan etc.) i simply forwarded the touches using something like <pre><code>[self.nextresponder touchesbegan: touches withevent:event]; </code></pre> but how do i do that using gestures i mean the uipangesturerecognizer will in my case run a method called drag: and this method receives a gesture... how do i forward the touch to its scroller parent so the whole thing scrolls thanks,iphone
how can i use the string variable transferred as the command parameter to a instance of another class in java how can i use the string variable transferred as the command parameter to a instance of another class in java like this: <pre><code>public class nbody { public static void main(double t double dt string filename) { in filename = new in(); filename.readint(); } } </code></pre> it notified as: <blockquote> filename is already defined in main(double double java.lang.string) in filename = new in(); </blockquote>,java
check if a div has controls javascript i use alert to check if a div has any child controls: <pre><code>alert(document.getelementbyid( maincontent_imgcontainer ).haschildnodes()); </code></pre> and this always returns true even if the maincontent_imgcontainer div doesn t have any child controls please tell me what is the better way to determine if a div has child controls.. thanks,javascript
ipad leak - nspushautoreleasepool we are getting a sizable leak (16kb) that is proving very difficult to eliminate. the responsible library is foundation and the responsible frame is nspushautoreleasepool. this leak does not appear on the iphone only the ipad. we get the following stack trace: <pre><code> 9 libsystem.b.dylib thread_assign_default 8 libsystem.b.dylib _pthread_start 7 webcore runwebthread(void*) 6 corefoundation cfrunloopruninmode 5 corefoundation cfrunlooprunspecific 4 corefoundation __cfrunloopdoobservers 3 webcore webrunlooplock(__cfrunloopobserver* unsigned long void*) 2 foundation nspushautoreleasepool 1 foundation _nsapaddpage 0 libsystem.b.dylib malloc </code></pre> we re getting a similar one in the frame nsautoreleasepool. we ve checked everywhere in the code we create an autoreleasepool to make sure we re releasing it. since none of this is our code i m not sure how to proceed. thanks in advance.,iphone
can someone explain how to use str.index and str.find and why the following code is wrong i m very new to python and have been trying out codewars. some problems pretty difficult for me. what i m trying to accomplish is to know the index of the vowels in a given word for example there are two vowels in the word super (the second and fourth letters). i don t really understand how to use index and/or find. i need to know i can edit this code to find the positions of the vowels in any given word. <pre><code>def vowel_indices(word): word.index( a i o u e y ) word.find( a i o u e y ) </code></pre>,python
converting string to int: python i have a series dataobject which have dtype as object. it contains int in str format as well as many strings. i want to convert only int to int type and del rest. example: <pre><code> 1 3 sd34 4 r5 </code></pre> result: <pre><code>[1 3 4] </code></pre>,python
program allows you specify points in n-dimensional space so here is the gist of the assignment i am having difficulty with: <ul> <li> write a java class called point to represent a n-dimensional point (with coordinates that are double) <ul> <li>the constructor should take any number of coordinates</li> <li>the class should have accessor method for any coordinates</li> <li>write tostring() and copy() and equals() helper methods</li> <li> keep track of every created poin </li> <li> write a java class called line to represent a line (with a starting point and an ending point) </li> <li>the constructor arguments are the start and end points</li> <li>the constructor must throw an error when the 2 points are not of the same dimension</li> <li>write a tostring() and copy() and equals() helper method</li> <li>provide a getlinelength() method - look up euclidian distance on wiki</li> <li>keep track of every created line</li> </ul></li> </ul> so i have created my line and point class but i am not sure if i am creating my line or point class correctly. i already have my main method designed to take input from the console and store that input into two different arrays for the coordinates. when i try to call this method in my main to print the coordinates and distance i get back the output: the distance between ( 4.0 5.0 ) ( 2.0 3.0 ) ( 0.0 0.0 ) is> so i was hoping i could get help in clarifying if i am creating my constructor and everything else correctly. here is my code for both classes thus far: <pre><code>public class point{ private double[] coordinate1; private double[] coordinate2; public point(double[] array1 double[] array2){ this.coordinate1 = array1; this.coordinate2 = array2; } //method to get array inputs and copy them public void copy(double[] points1 double[] points2){ double[] coordinate1 = new double[points1.length +1]; for(int copyindex = 0; copyindex &lt; points1.length; copyindex++){ coordinate1[copyindex] = points1[copyindex]; } points1 = coordinate1; double[] coordinate2 = new double[points2.length +1]; for(int copyindex = 0; copyindex &lt; points2.length; copyindex++){ coordinate2[copyindex] = points2[copyindex]; } points2 = coordinate2; } //method to print the coordinates public void printarray(){ double array1 = coordinate1.length; double array2 = coordinate2.length; for (int i = 0; i &lt; array1 &amp;&amp; i &lt; array2; i++) { system.out.println( ( + coordinate1[i] + + coordinate2[i] + ) ); } } } public class line{ private double[] coordinate1; private double[] coordinate2; private double distance; public line(double[] array1 double[] array2){ this.coordinate1 = array1; this.coordinate2 = array2; } public double getline(double[] coordinate1 double[] coordinate2){ double diffsquaresum = 0.0; for(int i=0;i&lt;coordinate1.length;i++) { diffsquaresum += (coordinate1[i] - coordinate2[i]) * (coordinate1[i] - coordinate2[i]); } distance = math.sqrt(diffsquaresum); return distance; } public string tostring(){ return the distance is + distance; } } </code></pre> please let me know if i need to clarify or expand on my question. appreciate any help. thank you. here is the output expected from the program once ran: example: enter point # 1 dimension # 1 or random or exit or help or blank line to proceed: 3.14 enter point # 1 dimension # 2 or random or exit or help or blank line to proceed: 0 enter point # 1 dimension # 3 or random or exit or help or blank line to proceed: enter point # 2 dimension # 1 or random or exit or help or blank line to proceed: 0 enter point # 2 dimension # 2 or random or exit or help or blank line to proceed: hel <ul> <li>this program allows you specify points in n-dimensional space: <ul> <li>each point can have different number of non-zero coordinate</li> <li>you may request a random number for any coordinate by typing random </li> <li>when you are finished entering the cordinate just press the key</li> </ul></li> <li>pairs of point are used to create a lines <ul> <li>if the 2 points have mismatched dimensions and error will be shown</li> <li>when a line is created the line distance is provided</li> </ul></li> <li>when you are done specifying points and lines type exit to display final operation statistics</li> <li>all key words are case insensitive and can be abreviated</li> <li>random number will be scaled between -1 000.00 and +1 000.00</li> </ul> enter point # 2 dimension # 2 or random or exit or help or blank line to proceed: 2.71 enter point # 2 dimension # 3 or random or exit or help or blank line to proceed: the distance between ( 3.14 0.0) and ( 0.0 2.71) is 4.147734321289154 enter point # 1 dimension # 4 or random or exit or help or blank line to proceed: random --> -75.1234 enter point # 1 dimension # 5 or random or exit or help or blank line to proceed: enter point # 2 dimension #1 or random or help or exit or blank line to proceed: ra --> 38.12851983534693 enter point # 2 dimension #2 or random or help or exit or blank line to proceed: rand --> 74.31366638262983 enter point # 2 dimension #3 or random or help or exit or blank line to proceed: ouch - you tried to create a line with points of disimilar dimension! enter point # 1 dimension # 1 or random or exit or help or blank line to proceed: exit you created 4 points: ( 3.14 0.0 ) ( 0.0 2.71 ) ( -75.1234 ) ( 38.12851983534693 74.31366638262983 ) you created 1 lines: ( 3.14 0.0 ) to ( 0.0 2.71 ) with length 4.147734321289154 so it keeps asking for coordinate doubles and creates a line and then prints out all lines made once program closes. hope that helps clarify what the assignment requires,java
what entities are visible in cross <script> block in javascript i was trying to figure out what entities (ex. variable property function object etc.) defined in one <code>&lt;script&gt;</code> block would be visible to other <code>&lt;script&gt;</code> block. after some study it seems to me that: <ol> <li> from one <code>&lt;script&gt;</code> block only the variables/properties that are attached with global <code>window</code> object are accessible to other <code>&lt;script&gt;</code> block. </li> <li> for a function/object or expression to be accessed to other <code>&lt;script&gt;</code> block it must be attached to the <code>window</code> object by means of a variable/property. </li> <li> variables that are defined outside any function scope with/without <code>var</code> keyword become part of <code>window</code> object/global context. </li> <li> variables defined inside a function without <code>var</code> keyword become part of <code>window</code> object/global context. </li> <li> <strong>there is no other ways to be inside the <code>window</code> object/global context</strong> and thus accessible to cross <code>&lt;script&gt;</code> block. </li> </ol> i know the fifth point is pretty bold but it seemed correct to me. <strong>is this correct </strong> if not what s wrong,javascript
python - i need a collection with negative indices i am parsing a 3d mesh collecting repeating loops. the point of entry is not precisely known to me but my algorithm walks the mesh in in two directions. first from 0 up then from 0 down. i then need to convert collected information into a simple ordered collection. i ve managed to achieve a dict[int somecontainerfor3d] with keys ranging from -i to j. can i somehow sort it now and output into a 0-based collection or is there an easier way to go about it all edit: because i can t attach the whole 3d mesh along with the actual algorithm i built a model of the problem as mcve: <pre><code>import random condo = [ stoker laundryboy receptionist mr z mr j the s family the m family mr rich ] entry_point = random.randint(0 len(condo)-1) occupants_map = {} :type : dict [int string] def burglar(current): unknownlocation = entry_point+current if unknownlocation &lt; len(condo) and unknownlocation &gt;= 0: doorlabel = condo[unknownlocation] occupants_map[current] = doorlabel return true else: return false current = 0 while burglar(current) == true: current += 1 current = -1 while burglar(current) == true: current -= 1 print(occupants_map) </code></pre> it prints out oddly enough positive keys in order then negative keys in a weird unordered fashion. next i will try to sort the dict and output the same occupants map to a sorted collection with only positive indices. i would still appreciate help with this.,python
calleventhandler not invoked in objective c i have to get call status on the end of the call but my event is not invoked following like line always return false [callcenter setcalleventhandler: ^(ctcall* call) here is my code <pre><code>ctcallcenter *callcenter = [[ctcallcenter alloc] init]; callcenter.calleventhandler=^(ctcall* call) { if(call.callstate == ctcallstatedialing) { //the call state before connection is established when the user initiates the call. nslog(@ call is dailing ); } if(call.callstate == ctcallstateincoming) { //the call state before connection is established when a call is incoming but not yet answered by the user. nslog(@ call is coming ); } if(call.callstate == ctcallstateconnected) { //the call state when the call is fully established for all parties involved. nslog(@ call connected ); } if(call.callstate == ctcallstatedisconnected) { //the call state ended. nslog(@ call ended ); } }; </code></pre> any help will be greatly appriciated,iphone
how to mask an view with an black-white image i ve heard that it s possible to mask views with black/white images where black means fully transparent and white means view is visible. the big difference to clipstobounds is that the view could be clipped in funny shapes like circles or stars. how could i do that,iphone
"no output from the object functions this question is from an written test for a company. it looks very confusing. i thought it will print whatever <code></code> is set to. bu when i typed the code it shows nothing. i have little knowledge about closures and i think it is related to the problem. i want a little explanation here. <div class= snippet data-lang= js data-hide= false data-console= true data-babel= false >
<div class= snippet-code >
<pre class= snippet-code-js lang-js prettyprint-override ><code>function dd(name) { = name;
this.go = function() {
setinterval(function() {
} 2000)
var tt = new dd( corolla );
iphone provesion provision profile outdated no renew button do you have to renew the provision profile before it becomes outdated i do not see a renew button in the provision profile portal. allso if i creat a new provision profile can i use it to update my app instad of the new one,iphone
how to detect that the end of a scrollable element has been reached i am displaying 10 wordpress post titles in a list followed by a load more button that loads the next 10 results. how would i automatically trigger that button (let s make it a javascript event) when reaching the end of the scrollable parent of that list is it possible to detect the position of the scrollbar or the visibility of the last list item on the screen what is the most failprove method thanks you for your tips and tricks guys! p.s. i do not work with jquery so no need to suggest solutions that are using it :).,javascript
python standard library to get total memory size i m wondering if there is a module in python standard library i can use to get the total physical memory size. i know i can use psutil but it would be great if my python script can run without installing external module. thanks! edited: sorry guys i forgot to mention that i m using a mac osx. thanks for all the windows solutions tho!,python
converting log file line to dictionary i have a log file generated by an external program i can t control that consists of a key-value pairs separated by spaces and i can t find a simple way to parse this. for example a line would contain something like <pre><code>time= 2017-10-03t15:13:34z level=info msg= some information message time= 2017-10-03t15:13:35z level=warn msg= some basic message err= more details on error </code></pre> i can t split on spaces because of the strings and i m not entirely sure how to deal with this using regex because not everything is bounded in quotes. is there a simple way to convert a single line into a dictionary (or json),python
best way to write this on iphone this is the output i want <strong> select * from wateat_tbl where name like %love% or desc like %love% ;</strong> where <strong>love is a text enterted by use</strong>r now i want to write this in effective way right now i am doing this lame code <pre><code> mystringprt1=@ select * from wateat_tbl where name like % nsstring *trimmedstring1 = [mystringprt1 stringbytrimmingcharactersinset: [nscharacterset whitespaceandnewlinecharacterset]]; mystringprt2=usertext;// user input love nsstring *mystringprt3=@ % or desc like % ; nsstring *mystringprt4=@ % ; trimmedstring1=[trimmedstring1 stringbyappendingstring:mystringprt2]; trimmedstring1=[ trimmedstring1 stringbyappendingstring:mystringprt3]; trimmedstring1=[ trimmedstring1 stringbyappendingstring:mystringprt2]; trimmedstring1=[ trimmedstring1 stringbyappendingstring:mystringprt4]; nslog(@ my string is now = %@ trimmedstring1); </code></pre>,iphone
access json to dict in python i have the next json in js <pre><code>var intervalos= { operandos :[{ extremoinferior :$(edit_numvar).context.value extremosuperior :$(edit_numvar2).context.value } { extremoinferior :$(edit_numvar3).context.value extremosuperior :$(edit_numvar4).context.value }] }; </code></pre> and i did <code>parsed_input = json.loads(self.intervalos)</code> but now i don t know how to access to my dict. i tried with <pre><code>intervalos[operandos][extremoinferior]) </code></pre> but it returns an error. could you help me for accessing to any element of my dict,python
instant search depending on a uitextview content i want to display results instantly while user enters some information (like google search). for now i am doing this using a button. is there a way to do it instantly thanks for any help.,iphone
what exactly is causing these undefined methods errors i have a <code>phonebook</code> class that extends <code>abstractcollection&lt;contact&gt;</code> in which i have overwritten <code>add</code> <code>size</code> and <code>iterator</code> methods. in the main function i create a new instance of the <code>phonebook</code> class and attempt to add a <code>contact</code> to it using the <code>add</code> method. apparently everything compiles fine however i get an exception at runtime saying: <pre><code>exception in thread main java.lang.error: unresolved compilation problems: the method add(contact) is undefined for the type phonebook the method add(contact) is undefined for the type phonebook the method size() is undefined for the type phonebook </code></pre> i don t know why this is happening and my searches didn t bring up any useful information. the code that s causing the error: <pre><code>public class phonebook extends abstractcollection&lt;contact&gt; { private hashset&lt;contact&gt; contacts = new hashset&lt;&gt;(); @override public boolean add(contact newcontact) { return contacts.add(newcontact); } @override public int size() { return contacts.size(); } @override public iterator&lt;contact&gt; iterator() { return contacts.iterator(); } } public class application { public static void main(string[] args) { phonebook book = new phonebook(); book.add(new contact( marco polo )); book.add(new contact( pablo cablo )); book.size(); system.out.println(book); } } </code></pre> what exactly am i doing wrong,java
prevent user from entering the same input twice i am making a game similar to text twist on python and i was wondering how to prevent the user being able to input the same word twice. here is what i have so far... <pre><code>import random correct = 0 incorrect = 0 usedwords = [] print welcome to text twist you have 14 guesses to get 7 words made up of 4 5 or 6 letters. good luck! for i in range(14): print your letters are e p l b e b what is your guess answer = raw_input() if answer in usedwords: print sorry you ve already used this word if answer == belle or answer == bleep or answer == pebble or answer == beep or answer == bell or answer == peel or answer == peep : if answer in usedwords: print nice that was one of the words! usedwords.append(answer) correct = correct + 1 if answer != belle and answer != bleep and answer != pebble and answer != beep and answer != bell and answer != peel and answer != peep : print sorry that was not one of the words. incorrect = incorrect + 1 print your final score was correct correct and incorrect wrong. </code></pre>,python
how to change uiimageview image on previous and next button click i have an nsmutablearray with 10 different images. initially i am displaying first three images from that array. now what i want is to display next images from that array when the next button click. also previous images when previous button is clicked. i am able to display different images when next button gets clicked but it comes only on the last uiimageview. <pre><code>- (ibaction)nextimage:(id)sender { nslog(@ count is :%d%d count coursearry.count); if ((count+1) &gt; coursearry.count) { count = 0; } starimageview.image = [uiimage imagenamed:[coursearry objectatindex:count]]; count++; } -(ibaction)previousimage:(id)sender { if ((count-1) &gt; coursearry.count) { count = 0; } starimageview.image = [uiimage imagenamed:[coursearry objectatindex:count]]; count++; } </code></pre>,iphone
how to change default value with click function <pre><code>function navigation() { var navigation = { value:1 }; return navigation.value; $( #cookie_outside ).click( function() { var navigation = { value:0 }; return navigation.value; }); $( #cookie_inside ).click( function() { var navigation = { value:1 }; return navigation.value; }); } swiper = new swiper( .swiper-container { slidesperview: auto parallax: false initialslide: navigation() grabcursor: true resistanceratio: .00000000000001 }); </code></pre> how can i change default value with click function. initialslide: navigation() . my default value is 1 i want it change when i clicked #cookie_inside or #cookie_outside. it can be possible instant change,javascript
uri escaping n number of slashes in javascript i m trying to set up a replace for all %2f strings specifically for a search term. i have already run the search term through encudeuricomponent(search_term) and need to double escape only the %2fs. if the search term is ac/dc i want the result to be: ac%252fdc. i can do this quickly like this: <pre><code>search_term = encodeuricomponent(search_term); search_term = search_term.replace( %2f %252f ); </code></pre> however this doesn t work for ac//dc which returns: <pre><code>ac%252f%2fdc </code></pre> when what i want is: <pre><code>ac%252f%252fdc </code></pre> i can solve this by running a replace like so... <pre><code>search_term = search_term.replace( %2f%2f %252f%252f ); </code></pre> this isn t scalable. i m wondering why doing the first replace isn t replacing both %2f strings. thank you.,javascript
how to encrypt/decrypt the video url i have video urls in my app. i want to encrypt/decrypt those urls. i m trying so much but i could not find any way to do this. please . thanks in advance.,iphone
javascript input tag not setting id or class i have a table with input rows created from a mysql query. the user can alter those rows but he/she might also wish to add a new row. so i created a javascript function to add a new row when a button is clicked. the new row is being created correctly but the input tag is not getting its id or class. <pre><code> function addrow(id) { var tableref = document.getelementbyid(id); var nextseq = document.getelementbyid( maxseq ).value; var newrow = tableref.insertrow(2); var rowid = tr +nextseq; //first cell var cell1 = newrow.insertcell(0) ; var text1 = document.createtextnode(nextseq); cell1.appendchild(text1); var id1 = cell + nextseq + 1 ; = id1; //second cell var id2 = cell + nextseq + 2 ; var cell2 = newrow.insertcell(1).innerhtml = &lt;input type = text id = id2 class = xxx style = width:100px value = 1001-01-01 &gt; ; // var test = document.getelementbyid(id2); //alert( test is + test); ...more stuff which is working fine ... } </code></pre> the alert on test gives test is null so i gather the id is not being set. i also tried <pre><code>var abc = document.getelementsbyclassname( xxx ); alert( abc is + abc); </code></pre> and the alert says abc is [object htmlcollection] how can i fix this so that the id and class are functioning,javascript
javascript to select multiple select list i have following select list from which user can select multiple option <pre><code>&lt;select size= 6 onblur= validatevalumethod() multiple= id= valumethod[] name= valumethod[] &gt; &lt;option value= 0 &gt;select asset&lt;/option&gt; &lt;option value= oc &gt;original cost&lt;/option&gt; &lt;option value= ocuip &gt;original cost using indexed prices&lt;/option&gt; &lt;option value= rc &gt;replacement cost&lt;/option&gt; &lt;option value= occr &gt;original cost considering revaluation&lt;/option&gt; &lt;option value= ocuipcr &gt;original cost using indexed prices &amp; considering revaluation&lt;/option&gt; &lt;option value= rccr &gt;replacement cost considering revaluation&lt;/option&gt; &lt;/select&gt; </code></pre> i need to fetch the value selected by user in javascript but dont know how to do this please help me.,javascript
cost of looking up a tuple in a list of tuple suppose i have a list of tuples of the form <code>list = [(key1 value1) (key2 value2)]</code> then is it fast/good to look up if a tuple exists in the list like this: <code>(key_x value_x) in list</code> also how does python search the list ! does it compare pointers or how ! i m new to python coming from java.,python
simple calculator cant get past println so here s my code. <a href= rel= nofollow ></a> <pre><code> system.out.println( setcaculatorinput ); scanner sc = new scanner(; int z = sc.nextint(); system.out.println( setvaluea ); int a = sc.nextint(); system.out.println( setvalueb ); </code></pre> the main problem is that i cant get past system.out.println( setcaculatorinput ) as it crashes right after that line.,java
javascript error : expected helo all im setting json-like data format to ne used by a js libray called fusioncharts. at the bottom is a section called data and in there the error is happening at the second object: <code>totalfundedvalue</code> ok here is a snippet of my rendered html: <pre><code>var totalfunded = 109321734.06 ; var totalfundedvalue; var totalfundedlabel; var totalfundedtext; if (totalfunded != null) { totalfundedlabel.push({ label : funded }); totalfundedvalue.push({ value : 109321734.06 }); totalfundedtext.push({ tooltext : $109 321 734.06 }); } data :[{ totalfundedlabel totalfundedvalue totalfundedtext } ] </code></pre> js: <pre><code>var totalfunded = ${totalfunded} ; var totalfundedvalue; var totalfundedlabel; var totalfundedtext; if (totalfunded != null) { totalfundedlabel.push({ label : funded }); totalfundedvalue.push({ value : &lt;tld-msst:fc-value var= ${totalfunded} /&gt; }); totalfundedtext.push({ tooltext : &lt;fmt:formatnumber value= ${totalfunded} type= currency groupingused= true /&gt; }); } </code></pre> just for clarification this is what it looks like without using the push methods: <pre><code> data: [{ label : funded value : ${totalfunded} tooltext : &lt;fmt:formatnumber value= ${totalfunded} type= currency groupingused= true /&gt; } </code></pre>,javascript
starting web programming in java i ve been programming in php and for a while now. when doing php i ve always used xampp to test my websites. i m wondering (since i m learning java) if there are equivalent services around furthermore i know this is sort of an open question but how would you make a basic page in java just a basic hello world web page.,java
how to run java class or debug <pre><code>package com.sample; import java.sql.drivermanager; import com.mysql.jdbc.connection; public class connectionclass { public static void main(string args) { system.out.println( mysql connect example ); connection conn = null; string url = jdbc:mysql://localhost:3306/ ; string dbname = testdatabase ; string driver = com.mysql.jdbc.driver ; string username = root ; string password = root ; try { class.forname(driver).newinstance(); conn = (connection) drivermanager.getconnection(url + dbname username password); system.out.println( connected to the database ); conn.close(); system.out.println( disconnected from database ); } catch (exception e) { e.printstacktrace(); } } } </code></pre> this code connects to a database and gives no syntax error. i am doing this in eclipse and when i run the project it asks which class we need to run but my class is not there.,java
getting distance on roads between 2 locations hello how can an iphone user find the distance on roads between two locations using an in app solution preferably using two text fields i tried google maps. however i m not sure if there is a mapkit tool to do this build in or a google maps api i am trying to use this value in order to do some calculations afterwards.,iphone
js how to sum/average i have an object and need to sum/average of each dynamic span. can t seem to convert those to numbers though. please help. <a href= rel= nofollow noreferrer title= console >console log</a><br> <a href= rel= nofollow noreferrer title= code sample >code sample</a> <pre><code>expand/collapse created : 1/3/2017 ‎&lt;span&gt;(10)‎&lt;/span&gt; expand/collapse created : 1/4/2017 ‎&lt;span&gt;(38)‎&lt;/span&gt; expand/collapse created : 1/5/2017 ‎‎&lt;span&gt;(13)&lt;/span&gt; expand/collapse created : 1/6/2017 ‎‎&lt;span&gt;(35)&lt;/span&gt; expand/collapse created : 1/9/2017 ‎‎&lt;span&gt;(46)&lt;/span&gt; expand/collapse created : 1/10/2017 ‎‎&lt;span&gt;(17)&lt;/span&gt; expand/collapse created : 1/11/2017 ‎‎&lt;span&gt;(27)&lt;/span&gt; var arr = []; $( .ms-gb span ).each(function(index elem){ arr.push($(this).text()); }); $( #result ).text(arr.join( + )); // (10)+‎(38)+‎(13)+‎(35)+‎(46)+‎(17)+‎(27) var allnumbers = document.getelementbyid( result ).innertext; // (10)+‎(38)+‎(13)+‎(35)+‎(46)+‎(17)+‎(27) allnumbers = allnumbers.replace(/[ ()]/g ); // ‎‎10+‎38+‎13+‎35+‎46+‎17+‎28 var newstring = allnumbers.split( + ); // object - [ ‎10 ‎38 ‎13 ‎35 ‎46 ‎17 ‎27 ] </code></pre>,javascript
how to play youtube video in webview in iphone how to remove default done button of mpmoviecontroller in iphone,iphone
do python dictionaries have all memory freed when reassigned working in python. i have a function that reads from a queue and creates a dictionary based on some of the xml tags in the record read from the queue and returns this dictionary. i call this function in a loop forever. the dictionary gets reassigned each time. does the memory previously used by the dictionary get freed at each reassignment or does it get orphaned and eventually cause memory problems <pre><code>def readq(): qtags = {} # omitted code to read the queue record get xml string domify it qtags[ result ] = success qtags[ call_offer_time ] = get_node_value_by_name(audio_dom call_offer_time ) # more omitted code to extract the rest of the tags return qtags while signals.sigterm_caught == false: tags = readq() if tags[ result ] == empty : time.sleep(sleep_time) continue # do stuff with the tags </code></pre> so when i reassign tags each time in that loop will the memory used by the previous assignment get freed before being allocated by the new assignment,python
python error : tuple object has no attribute upper i wanna make word count and list how many times word counted. but <hr> <pre><code> f = open( les.miserable.txt r ) words = words.sort() wordcount = () for i in range(len(words)): words[i] = words[i].replace( . ) ( ) ( / ) ( ) ( ! ) words[i] = words[i].upper() if words[i] not in wordcount: wordcount[words[i]] = 1 else: wordcount[words[i]] += 1 </code></pre> i can see error message tuple object has no attribute upper in <pre><code>words[i] = words[i].upper() </code></pre> here and also error message tuple object does not support item assignment in wordcountint[words[i]] = 1 please let me know know what is the problem,python
how javascript execute the code and define variables i have just started to learn js and trying to understand how it executes the code. if i run following code: <pre><code> console.log(a); var a = hello world console.log(a); </code></pre> the output for first line is undefined and second line hello world . my question is why js didnt do either of these: 1) throw me an error at first line that a is not defined and then output hello world . 2) i understand js has two phases creation and execution then in this case at the end of the creation phase js knew that a value has been defined as hello world . why it didn t give out as hello world for both console.log thanks,javascript
why wont my clone work. java i have a class of objects called item but the clone function won t work. <pre><code>item newitem = addeditem.clone(); </code></pre> please help : ( added: <pre><code>public abstract class item extends gameobjectscls implements cloneable item newitem = (item)addeditem.clone(); </code></pre> and added the public clone method but now am asked for try catch statement. is that ok public <code>object clone() throws clonenotsupportedexception {</code>,java
java programming exercise debug program i want to say thank you for reviewing my post and any contributions to my problem i am having. i am fairly new to java so i was wondering if you guys could please help me debug this program. <pre><code>import java.util.scanner; public class debugexercise { public static void main(string[] args) { scanner input = new scanner(; string area instr; int pages; system.out.println( please enter your city ); area = input.nextline(); system.out.println( please enter page number + area + s phone book ); pages = input.nextint(); phonebook phonebook = new phonebook(area pages); phonebook.display(); } } class phonebook extends book { private string area; private string size; phonebook(int pages string city) { super(); area = city; if (pages &gt; 300) { size = big ; } else { size = small ; } } public display() { system.out.println( area + pages + size); } } class book { protected int pages; public book(int pages) { pages = pages; } public int getpages() { return pages; } } </code></pre>,java
programmatically change device orientation in iphone i have navigation based app when i click on any row in root view the next view should come in landscape mode. i am not able to find a proper way to implement this. what i tried is: <pre><code>- (bool)shouldautorotatetointerfaceorientation:(uiinterfaceorientation)interfaceorientation { return uiinterfaceorientationislandscape(interfaceorientation); } </code></pre> but this is not working. the view should open only in landscape mode (not when user rotate it). can any one help me. thanks,iphone
screenshots app store: status bar or no status bar i am about to submit my app to the app store for review. the app is running on iphone requires ios 7 or later and it s optimised for iphone 5 6 and 6 plus which means i have to submit screenshots for all these devices. with the 6 and 6 plus sizes i am ok. 5.5in (iphone 6 plus): 1242 × 2208px portrait (with status bar) 4.7in (iphone 6): 750 × 1334px portrait (with status bar) what about the 4in do i crop the status bar and submit 640 × 1096px portrait (without status bar) or do i leave it and submit 640 × 1136px portrait (full screen) thanks,iphone
java 7 sun.* classes with java 8 i am using some library which inside itself use* classes. and i m using it as dependency in my project which is java 8. in java 8 some methods removed from sun classes which my library need. i understand that messing up with sun.* packages is not good idea but i don t want to downgrade my project to java 7 so is there any workaround to make my project run in java 8 environment but use sun.* classes from java 7,java
any suggestion if i need to write an iphone/ipad app to show html5 content is there any reference about writing an application on ipad/iphone to show html5 content <ul> <li>any reference book</li> <li>sample source codes</li> <li>which components should i use </li> </ul> million thanks.,iphone
python sum array of objects into objects i have a list (name=carpet) of objects type mini_carpet. mini_carpet contains a list of objects called packages. packages has various properties the one interesting to me is nr_buys. what i want to do is to sum the various nr_buys that are within a mini_carpet within a carpet. this is what i have done so far: <pre><code>for d in range(0 carpet.__len__() - 1 +1): nr_total = sum(carpet[d].packages[i].nr_buys for i in carpet[d].packages) </code></pre> this is giving me an error because list indices must be integers. any help thanks!,python
python syntaxerror when creating a list using a generator i m relatively new to python and i m just trying to get to grips with some of the common features. i tried to write a simple script to get all the whole number square roots of numbers between 0 and 100. this is what i came up with: <pre><code>mylist = [n for n*n in xrange(0 101)] </code></pre> i got a syntaxerror when i ran it and as far as i can tell it s not liking the n for n*n in bit. am i right in deducing that this is just not possible is there a way to achieve this or do i need a sqrt() function thanks,python
using two build_opener at once i m a newbie with python and i m trying to build a simple script to download a remote html file for parsing the content. i need to use the both a proxy as well as a cookie enabled enviroment to authenticate with the remore system. as long as i use just one handler everything is fine. however as soon as i try to use the combination of the cookie handler and the proxy handler at the first connection the python script raise an exception. <pre><code>self.cj = cookiejar() proxy_support = urllib2.proxyhandler({ http : }) self.opener = urllib2.build_opener(proxy_support urllib2.httpcookieprocessor(self.cj)) urllib2.install_opener(self.opener) ).read() </code></pre> and in the console i get the following messages. pydev debugger: unable to find real location for: /system/library/frameworks/python.framework/versions/2.7/lib/python2.7/ pydev debugger: unable to find real location for: /system/library/frameworks/python.framework/versions/2.7/lib/python2.7/ pydev debugger: unable to find real location for: /system/library/frameworks/python.framework/versions/2.7/lib/python2.7/ there are some other errors like this as soon as the script starts the execution but without using the proxy everything runs fine. also after a while the script ends with this urllib2.httperror: http error 500: internal server error which is pretty self-explanatory but i can t understand what the problem is as i ve been granted to the use of that proxy server on ip basis (meaning that only me in the office can use that address). any help,python
why do classes in the python threading module expose factory functions instead of constructors in the <code>threading</code> module names like <a href= >rlock</a> <a href= >semaphore</a> and <a href= >event</a> are all factory functions while the name of implementation classes are prefixed by underscores. the factory functions just pass all arguments they received to the underlying constructors. so what s the benefit of doing this,python
how to print last two digits of given integer a=1234 in java if i m giving values like a=1234 i want to print last two digits 34 only.. can anyone give me solution for this... <pre><code>int a=1234; system.out.print(a); </code></pre>,java
why can two variables have the same name i execute the following code and i get no errors and in the output i see the <code>success!</code> message. can you please explain this strange behaviour. <pre><code>public class main { public static void main(string[] args) { int р = 0; int p = 1; if(р == 0 &amp;&amp; p == 1) { system.out.println( success! ); } } </code></pre> <hr> <a href= rel= nofollow noreferrer >you can check the online demo</a>,java
generate date of birth from id number for people born after 2000 i am looking for a function to generate/ populate date of birth for id numbers of people born after 2000. this is my code right now but it doesn t extend to after 2000 <pre><code> var year = idnumber.substring(0 2); var month = idnumber.substring(2 4) var day = idnumber.substring(4 6) var dob = 19 + year + / + month + / + day; </code></pre> how can i modify this to accommodate > 2000,javascript
how to create login form using sqlite in iphone view based application i want to create login form using sqlite in iphone view based application please help me.give any idea about sqlite in iphone and any sqlite tutorial for iphone application development..,iphone
how to calculate the path to a child node in a tree i have a tree like this: <pre><code>var tree = [ { type: folder children: [ { type: folder children: [ { type: document id: 1 children: [] } ] } ] } { type: folder children: [] } ]; </code></pre> the leafs of this tree always have an empty <code>children</code> array. i need to construct a function which will return the path of indices to the node which satisfies the given condition. the function would be called like this: <pre><code>getpathtonode(tree function (node) { return node.type === document &amp;&amp; === 1; }) </code></pre> and would return the following: <pre><code>[0 0 0] </code></pre> which describes the path to that node: <pre><code>tree[0].children[0].children[0] </code></pre> this recursive function is what i got so far: <pre><code>function getpathtonode(tree fn) { return tree.reduce(function (path node i) { if (fn(node)) { return path.concat(i); } if (node.children.length &gt; 0) { const pathtonode = getpathtonode(node.children fn); return pathtonode.length &gt; 0 path.concat(i pathtonode) : []; } return []; } []); } </code></pre> i think the function needs to build a path while traversing then if it reaches a leaf without finding the node delete only the part of that path which belonged to the branch where the node wasn t found then continue with other branches.,javascript
return location of value from a sorted list i hope i m describing this correctly: i am looking to update the state of an object based upon the object s current state a transition matrix and a random variable ( rv ). as an illustration suppose i have a matrix of n elements with three states (say solid liquid gas). each state has it s own probability of changing states. a threshold value when compared to a rv determines the state. eg <pre><code> solid liquid gas solid .50 .75 1.00 liquid .25 .50 1.00 gas .15 .35 1.00 </code></pre> i would like to write a function which given this transition matrix a current state and an rv returns the new state in as efficient a manner as possible (i am running many simulations and the actual matrix is much larger than 3x3). here s my code where value is the rv and list is a sorted list of a selected row containing the values expressed above. eg for solid the list is: [.50 .75 1.0] <pre><code>def return_location(value list): # returns location i from sorted list where value is &gt;= i and &lt; i+1 len = length(list) for i in range(0 (len-1)): if value &lt; list[i] return(i) break; </code></pre> any thoughts appreciated!,python
relative positioning (iphone sdk) given two labels (or views) how would you automatically move (reposition) the lower one relative to the changing vertical size of the upper one.,iphone
python calculate student statistics i am trying to calculate student statistics using python. everything seems to be working fine except for the standard deviation part at the end. i thought i interpreted the formula right but clearly it s not. i keep getting 6.63 instead of the actual 7.48. help will be highly appreciated. update: i did the math. turns out the summation should actually be 279 while my code generates summation= 220. maybe that ll help some of you including me to try and find the issue. <pre><code>nums=[] total= 0 count= 0 x = int(input( enter a number (enter -1 to terminate): )) while x &gt;= 0: if x &lt;= 100: total = total + x count+=1 nums.append(x) if x&gt;100: print( invalid entry. ) x = int(input( enter a number (enter -1 to terminate): )) print(nums) print( number of scores: count) idx=0 while idx &lt; count: newindex = idx+1 maximum = nums[idx] while newindex &lt; count: if(nums[newindex] &lt; maximum): maximum = nums[newindex] newindex+=1 if maximum &lt; nums[idx]: temp = nums[idx] nums[idx] = maximum nums[newindex-1] = temp idx+=1 print( maximum score: maximum) idx= 0 while idx&lt; count: newindex= idx+1 minimum= nums[idx] while newindex &lt; count: if (nums[newindex]&gt; minimum): minimum= nums[newindex] newindex+=1 if minimum&gt; nums[idx]: temp= nums[idx] nums[idx]= minimum nums[newindex-1]= temp idx+=1 print( minimum score: minimum) average=total/count print ( average score: average) summation=0 idx=0 while idx&lt; count: value= nums[idx] if idx&lt;count: summation += ((value-average)**2) idx+=1 print( standard deviation: int(summation/count)**0.5) </code></pre>,python
face detection through webcam using java in ubuntu linux i am working on a project which requires face detection through webcam.suggest me any libraries that i can use to do this.i found one named opencv but it is for windows only.plz suggest some other methods also.thank you.,java
iphone:recording conversation feature i want to develop an iphone application which has to record the phone conversation. can some one give me the instruction how can i achieve this thank you.,iphone
making object eligible to be cleaned up i have very simple question but the answer is still not clear. if i have class person and inside class person there is one attribute which references to other object(ex: account). if person object is eligible for gc so either that attribute will be eligible to be cleaned up,java
is this mixins code an error of book the principles of object-oriented javascript in mixins chapter there is an example code <pre><code>function mixin(receiver supplier) { for (var property in supplier) { if (supplier.hasownproperty(property)) { receiver[property] = supplier[property] } } return receiver; } function eventtarget(){ } eventtarget.prototype = { add: function(){console.log( add );} }; function person(name) { = name; } mixin(person.prototype new eventtarget()); mixin(person.prototype { constructor: person sayname: function() { console.log(;{ type: namesaid name: name }); } }); var person = new person( nicholas ); </code></pre> for my understanding this is trying to copy properties from eventtarget.prototype into person.prototype. so the code: <pre><code>mixin(person.prototype new eventtarget()); </code></pre> should be <pre><code>mixin(person.prototype eventtarget.prototype); </code></pre> am i right of this piece of code,javascript
best way to procedurally add power-up items to an iphone game to better explain this i ll use doodle jump as an example. assuming that the platforms are recycled when the character jumps up and the new platforms appear (by scrolling down) there is occasionally a propeller hat on one of them. is there a recommended method to manage this new object should i instantiate a single one of these power-ups in the game level s init method and then set a boolean to flag whether it appears in my render method and update methods or should i instantiate it at the time that i want it to appear (i.e. just before the new platform scrolls down from its position just above the screen) and release it when it s a) grabbed by the character sprite or b) moves off the screen untouched thanks! <ul> <li>scott</li> </ul>,iphone
_ in python returns me last function result ok i have something for you guys i type this code in fresh new python terminal: <pre><code>&gt;&gt;&gt; print _ traceback (most recent call last): file &lt;stdin&gt; line 1 in &lt;module&gt; nameerror: name _ is not defined &gt;&gt;&gt; magic [::2] mgc &gt;&gt;&gt; print _ mgc &gt;&gt;&gt; magic [::-1] cigam &gt;&gt;&gt; print _ cigam </code></pre> or: <pre><code>&gt;&gt;&gt; def foo(x): ... return x * x ... &gt;&gt;&gt; print _ traceback (most recent call last): file &lt;stdin&gt; line 1 in &lt;module&gt; nameerror: name _ is not defined &gt;&gt;&gt; foo(3) 9 &gt;&gt;&gt; print _ 9 </code></pre> is this normal python behavior,python
open file in python without file s full name i am trying to execute <code>f = open( filename )</code> in python. however i dont know the full name of the file. all i know is that it starts with s12 and ends with .ka i know the folder where it s located and i know it is the only file in that folder that starts and ends with s12 and .ka . is there a way to do this,python
what does << means in javascript i am looking at some code in javascript <pre><code>var numcombos = 1&lt;&lt;numactive; </code></pre> numactive = 8 returns numcombos = 256 what does &lt;&lt; means,javascript
strange loops and append functions within them i a currently trying to understand the code of a python program which in essence is a pacman game. while i was reading the code i found a strange loop which seems to reset a list to empty followed by appending a value to this list. here is what i mean: <pre><code>def drawfood(self foodmatrix ): foodimages = [] color = food_color for xnum x in enumerate(foodmatrix): if self.capture and (xnum * 2) &lt;= foodmatrix.width: color = team_colors[0] if self.capture and (xnum * 2) &gt; foodmatrix.width: color = team_colors[1] imagerow = [] foodimages.append(imagerow) for ynum cell in enumerate(x): if cell: # there s food here screen = self.to_screen((xnum ynum )) dot = circle( screen food_size * self.gridsize outlinecolor = color fillcolor = color width = 1) imagerow.append(dot) else: imagerow.append(none) print( foodimages + str(foodimages)) return foodimages </code></pre> although <code>foodimages = []</code> and <code>imagerow = []</code> are both reset to empty in every iteration of the loop the foodimages list seems to continue growing. is it possible that the because we append dot to <code>imagerow</code> and <code>imagerow</code> to the list <code>foodimages</code> that the <code>foodimages</code> list continues to grow although <code>imagerow</code> was set to empty,python
how to create nxn matrix/array in javascript i want to create an array or matrix with non-fixed number of rows like <br> <pre><code>var matrix=[[0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0]] </code></pre> how can i do that,javascript
function is causing on page video to not load and cant seem to delay i m trying to make a troll page that plays a video in the background then goes through an endless alertbox loop my code <pre><code>&lt;/div&gt;&lt;video autoplay= true class= stretchtofit id= lol loop= true &gt; &lt;source src= ./stream.mp4 type= video/mp4 &gt;&lt;/video&gt; &lt;script&gt; function show_alert(){ alert( enjoy the stream ); alert(show_alert().repeat(0)); } show_alert(); &lt;/script&gt; </code></pre> the issue is that the function is called before the video loads and therefore doesnt play. when i try to add a delay to the function it causes the video to cutout almost immediately. my goal is for it to play the video in the background and have the alertbox loop going.,javascript
change settings from outside a module i think it s not possible but i ask anyway maybe i ll learn something. suppose i have a piece of a code from an external module i want to use: <pre><code>from __future__ import print_function import webbrowser import time from .api import twitter json from .oauth import oauth write_token_file from .oauth2 import oauth2 write_bearer_token_file try: _input = raw_input except nameerror: _input = input def oauth_dance(app_name consumer_key consumer_secret token_filename=none): perform the oauth dance with some command-line prompts. return the oauth_token and oauth_token_secret. provide the name of your app in `app_name` your consumer_key and consumer_secret. this function will open a web browser to let the user allow your app to access their twitter account. pin authentication is used. if a token_filename is given the oauth tokens will be written to the file. print( hi there! we re gonna get you all set up to use %s. % app_name) twitter = twitter( auth=oauth( consumer_key consumer_secret) format= api_version=none) oauth_token oauth_token_secret = parse_oauth_tokens( twitter.oauth.request_token(oauth_callback= oob )) print( in the web browser window that opens please choose to allow access. copy the pin number that appears on the next page and paste or type it here: ) oauth_url = ( oauth_token= + oauth_token) print( opening: %s\n % oauth_url) try: r = time.sleep(2) # sometimes the last command can print some # crap. wait a bit so it doesn t mess up the next # prompt. if not r: raise exception() except: print( uh i couldn t open a browser on your computer. please go here to get your pin: + oauth_url) oauth_verifier = _input( please enter the pin: ).strip() twitter = twitter( auth=oauth( oauth_token oauth_token_secret consumer_key consumer_secret) format= api_version=none) oauth_token oauth_token_secret = parse_oauth_tokens( twitter.oauth.access_token(oauth_verifier=oauth_verifier)) if token_filename: write_token_file( token_filename oauth_token oauth_token_secret) print() print( that s it! your authorization keys have been written to %s. % ( token_filename)) return oauth_token oauth_token_secret </code></pre> i m calling the interesting function like this: <pre><code>twitter.oauth_dance( my app name consumer_key consumer_secret my_twitter_creds) </code></pre> i would like to change the input method (see the beginning of the code in the try block) but without changing the code of the module. i want to do it from the user side. is it possible edit: a not working example: <pre><code>import twitter twitter.oauth_dance._input = none # twitter._input = none consumer_key = hi consumer_secret = hello my_twitter_creds = ./config/twitter_credentials if not os.path.exists(my_twitter_creds): twitter.oauth_dance( my app name consumer_key consumer_secret my_twitter_creds) oauth_token oauth_secret = twitter.read_token_file(my_twitter_creds) tweet = twitter.twitter(auth=twitter.oauth(oauth_token oauth_secret consumer_key consumer_secret)) tweet.statuses.update(status= hello world! ) </code></pre>,python
how do i get a java file object without creating a corresponding file i have an interface that takes java file object but i have a string i want to send to it. without writing to disk how would i create an object suitable to send to that interface i have the necessary data/metadata like length timestamp content and filename and i want to include them in the file.,java
iphone - multiple instances of an application running when i start my app for the first time after installing it and exit before the splash screen disappears from then on launching from the multitasking menu it comes up with a black screen. if i click on it from the home screen it loads fine but every time i try from the multitasking menu it is a black screen until i terminate it. if i add the uiapplcationexitonsuspend property to the properties list the black screen continually appears until i restart the device. any help is appreciated. thanks sj,iphone
python dict comprehension summing from objects given a setup like this: <pre><code>class foo(): state = x amount = 1 a = foo() b = foo() c = foo() c.state = y foos = [a b c] </code></pre> i want to get a dict that has keys = <code>object.state</code> values = <code>sum(object.amounts of objects with that state)</code>. in this case: <pre><code>{ x : 2 y : 1} </code></pre> i want to do this automatically so i don t need to know the different possible states in advance. for sure i could iterate through in some boring manner like this: <pre><code>my_dict = {} for foo in foos: try: my_dict[foo.state] += foo.value except (keyerror typeerror): my_dict[foo.state] = foo.value </code></pre> but that is a bit verbose and i m wondering if there s a nicer way to do it maybe with dict comprehensions or something but my efforts so far have been in vain.,python
replacing of numbers to zero in a sum i have to define a function <code> func(a b c) </code> in which there are 3 variables it calculates their sum. i have to check if there value is greater than <code> 13 </code> then the number becomes <code> 0 </code> eg. <code> def func(3 4 14) </code> ---> 7 (3+4+0) i ve tried this code below: <pre><code>def no_teen_sum(a b c): if(a&gt;13): a=0 elif(b&gt;13): b=0 elif(c&gt;13): c=0 return a+b+c </code></pre> but it didn t work. am i doing wrong somewhere please suggest me the correct way to do it...,python
generate unit tests for hashcode equals and tostring methods is there any tool/library which can automatically generate the tests for my hashcode and equals methods looking at the instance variables involved in these methods,java
why does if type(x) not list return an error i would like to use <code>if type(x) not list</code><br>instead of <code>if not isinstance(x list)</code><br>am i missing something <code>if not isinstance(x list)</code> seems excessive<br>since i m not checking for class inheritance.,python
is the visiblerect method also available on iphone how do i find it out apple says that there is a visiblerect method on the mac (<a href= rel= nofollow noreferrer >source</a>) that helps doing graphic operations only in the visible content rectangle from an view. when i try to access that method xcode gives me no completion hint so it seems that this one is not available on iphone. how could i find that out,iphone
iphone app: how was emoji programmed how was emoji programmed i m assuming the app downloads and installs a language pack in the core operating library then the app simply instructs the user how to enable multiple languages..,iphone
sum elements of a list in python i have a list like this: <pre><code>a = [1 2 3] </code></pre> i want to add all elements and form: <pre><code>a = [6] or a = 6 </code></pre>,python
forcing focus to remain on a form text element until the value is numeric i have a form which has input fields that expect numbers only. i m using javascript to validate the form when the value of the field changes. if the value is numeric do nothing. if the value is not numeric set it to zero and put focus in that text field. essentially i m trying to trap the cursor in that field until a numeric value is entered. for some unknown reason focus is not being placed on that form element. <code>cell.focus()</code> does not work. i ve even tried <code>document.getelementbyid(cel.getattribute( id )).focus();</code> what might i be doing wrong <pre><code>&lt;html&gt; &lt;head&gt; &lt;script&gt; function nan(cell){ if (cell.value != ) { var re = /^(0|[1-9][0-9]*)$/; if (re.test(cell.value) == false) { alert( you must supply a numeric value greater than 0. ); cell.value = 0 ; cell.focus(); } } } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;input type= text name= num value= onchange= nan(cell) /&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>,javascript
possible class error <pre><code>class randomagain { public static void main(string args[]){ scanner tuna = new scanner(; boom boomobj = new boom(); system.out.println( ~~calculator~~ ); system.out.print( enter your 1st number: ); int first_num = tuna.nextint(); system.out.print( enter your 2nd number: ); int second_num = tuna.nextint(); system.out.print( what do you want to do [plus sub mult div]: ); string choice = tuna.nextline(); if (choice == plus ) boomobj.addition(first_num second_num); if (choice == sub ) boomobj.subtraction(first_num second_num); if (choice == mult ) boomobj.multiply(first_num second_num); if (choice == div ) boomobj.division(first_num second_num); else {system.out.println( please check the fields again!! );} } } </code></pre> boom class: <pre><code>public class boom { private int sub_final add_final multi_final div_final; public void addition(int a int b){ add_final = a + b; system.out.println(a+ + +b+ = +add_final); } public void subtraction(int a int b){ sub_final = a - b; system.out.println(a+ - +b+ = +sub_final); } public void multiply(int a int b){ multi_final = a * b; system.out.println(a+ * +b+ = +multi_final); } public void division(int a int b){ div_final = a + b; system.out.println(a+ / +b+ = +add_final); } } </code></pre> when i run it in the 3rd command it is like : <pre><code>what do you want to do [plus sub mult div]: please check the fields again!! </code></pre> and i can t type anything as its reply.,java
iphone 3.0 beta - what effects does it have on the iphone i am currently developing applications on the 2.2.1 sdk and considering to upgrading my iphone to sdk 3.0. can my phone still be used to run old version programs (2.1 2.2 etc) call send sms and so on or will it be restricted to only be used to test 3.0 developed programs thanks hans espen,iphone
how to create tuple from materialgroupmaster objects i have a data structure like this : <pre><code>[&lt;materialgroupmaster: test&gt; &lt;materialgroupmaster: test material&gt; &lt;materialgroupmaster: last&gt;] </code></pre> how would i get this as follows <pre><code>( test test material last ) </code></pre>,python
email authentications hey can any one suggest me is there any api or example for authenticating email addresses in iphone app,iphone
get query string from href attribute via javascript i m building an interface that uses ajax with an html fallback. i m setting up all my <code>&lt;a&gt;</code> tags to work without ajax first and if javascript is enabled each link will have an onclick function attached to it that sends the same exact query string to a different page on my server. my original link will look like this: <pre><code>&lt;a class= ajax href= key1=value1&amp;key2=value2 &gt;link&lt;/a&gt; </code></pre> how do i retrieve key1=value1&amp;key2=value2 as a string from the above href link via javascript i will be making ajax requests that look like <code> key1=value1&amp;key2=value2</code>.,javascript
binding a specific context to a function: why does my hack work in secrets of javascript ninja listing 5.7(pg 100) the assertion fails: <pre><code>&lt;body&gt; &lt;button id= test &gt;click me!&lt;/button&gt; &lt;script&gt; var button = { clicked = false; click: function(){ this.clicked = true; assert(button.clicked the button has been clicked ); } }; var elem = document.getelementbyid( test ); elem.addeventlistener( click false); &lt;/script </code></pre> the author s solution was binding the context to an event handler in the listing 5.8. however i found editing the click function in the following ways worked. <pre><code> click: function(){ button.clicked = true; assert(button.clicked the button has been clicked ); } click: function(){ this.clicked = true; assert(this.clicked the button has been clicked ); } </code></pre> i don t understand why it works an answer to this that expands my javascript knowledge would be appreciated.,javascript
python decorator variable access i have a decorator function <code>my_fun(i k)</code> and it is applied to a function <code>add(x y)</code> as such <pre><code>@my_fun(4 5) def add(x y): return x+y </code></pre> i am new to python would like to know if i am writing the <code>my_fun</code> function <ol> <li>how can i access <code>x y</code> in the add method in <code>my_fun</code> </li> <li>how can i access the return value of add in the decorator function </li> </ol> i am a little confused on syntax and concepts any explanation would be help.,python
java jna unsatisfiedlinkerror i am following this tutorial : <a href= rel= nofollow ></a> . the difference is that my class is called main.c not ctest.c. i ve created a library inside the project folder as it says there. on the next step i created the java file with this line modified : <pre><code>ctest ctest = (ctest) native.loadlibrary( ctest ctest.class); </code></pre> to <pre><code>ctest ctest = (ctest) native.loadlibrary( main ctest.class); </code></pre> i have imported jna-4.1.0.jar to my project. on run it gives me this error : <pre><code>exception in thread main java.lang.unsatisfiedlinkerror: unable to load library main : native library (win32-x86-64/main.dll) not found in resource path ([file:/d:/eclipse/workspace/rxtx/bin/ file:/d:/eclipse/workspace/rxtx/lib/rxtxcomm.jar file:/c:/users/angelo/downloads/jna-4.1.0.jar]) at com.sun.jna.nativelibrary.loadlibrary( at com.sun.jna.nativelibrary.getinstance( at com.sun.jna.library$handler.&lt;init&gt;( at com.sun.jna.native.loadlibrary( at com.sun.jna.native.loadlibrary( at helloworld.main( </code></pre> where do i place my main.c and what do i do with the file,java
simple time parsing of a string in the below code i need to get a parse exception.but the program somehow converts it to a valid date. but if i give dthours as 07:0567 it is giving parse how to keep the exact format shown. can anyone tell me what to do to throw an error if the date string deviates from the given format ( hh:mm:ss ) even by a single character. <pre><code>public static void main(string[] args) { string dthours= 07:4856:35563333 ; simpledateformat df = new simpledateformat( hh:mm:ss ); try { date d = df.parse(dthours); system.out.println( d +d); } catch (parseexception e) { system.out.println( parseerror ); } </code></pre>,java
printf error: int cant be object i have this simple java code: <pre><code>package cal; import java.util.scanner; public class cal { public static void main(string[] args) { scanner input = new scanner(; int n1 n2 sum; system.out.print( enter first: ); n1 = input.nextint(); system.out.print( enter second: ); n2 = input.nextint(); sum = n1 + n2; system.out.printf( sum is %d\n sum); } } </code></pre> the error is at printf it requires (string object[]) my sum is int but cant it be considered as an object actually first this code ran well but after i made some change in the path to workplace the code started to have this error,java
use javascript to unhide cursor when users are typing browsers today will automatically hide the cursor when detecting typing. this is a probability when i set up keyboard shortcut on my web applications. the cursor is hidden after users press any key on the keyboard - and only become visible after they move the mouse around. this is a big problem to shortcuts that meant to trigger while some elements are being hovered. i ve noticed gmail effectively unhides the cursor when typing keyboard shortcuts on the keyboard (you will see a blink). does anyone know how it was done,javascript
compile java source from string without writing to file <a href= >here</a> i have found some good example: <pre><code>// prepare source somehow. string source = package test; public class test { static { system.out.println(\ hello\ ); } public test() { system.out.println(\ world\ ); } } ; // save source in .java file. file root = new file( /java ); // on windows running on c:\ this is c:\java. file sourcefile = new file(root test/ ); sourcefile.getparentfile().mkdirs(); new filewriter(sourcefile).append(source).close(); // compile source file. javacompiler compiler = toolprovider.getsystemjavacompiler(); null null sourcefile.getpath()); // load and instantiate compiled class. urlclassloader classloader = urlclassloader.newinstance(new url[] { root.touri().tourl() }); class&lt; &gt; cls = class.forname( test.test true classloader); // should print hello . object instance = cls.newinstance(); // should print world . system.out.println(instance); // should print test.test@hashcode . </code></pre> <strong>question</strong>: is it possible to achieve exactly the same thing without writing to a file <strong>@edit:</strong> to be more exact: i know how to compile from string (overloading javafileobject). but after doing this i have no idea how to load the class. i probably missed the output-write part but this also a thing i would like not to do. <strong>@edit2</strong> for anyone interested i created this small project to implement discussed feature: <a href= rel= nofollow noreferrer ></a>,java
overriding the python help() function behaviour i ve created a python proxy class that calls methods on a remote object. i ve used a closure to override the <strong>doc</strong> attribute on my dynamically created methods so that <pre><code>help(obj.method) </code></pre> gives me the help on my remote object method. i then decided that i wanted to do the same thing for the object attributes. i have in my class something like: <pre><code>class proxy: def __getattr__(self name): # do stuff to get remote attribute </code></pre> now when calling code like this: <pre><code>help(obj.attribute) </code></pre> i of course get the doc string of the queried value type (string int or whatever was returned). the only way i can think to avoid this is to get a stack dump inside <code>__getattr__()</code> identify and look for the help() call and conditionally return object/class instead of the remotely queried value. this is obviously non-ideal because there are quite a few ways one could specify the same thing however it would help me from the command-line which is the most likely place i am to use this so perhaps better than nothing. is there a better way,python
anyway to close this window is there anyway to get the to close after 20 seconds code at <a href= rel= nofollow ></a> <strong>basically i want a button that goes to a page. that page loads a list of urls after a certain amount of time and then closes them after a certain amount of time.</strong>,javascript
area of a rectangular in a plane i am new to programming and i have difficulties with solving a problem. i am coding it in python. may i have some help please so the condition says: a rectangular is set on 2 of its opposite angles (x1 x2) and (y1 y2). find the <strong>area</strong> and the <strong>perimeter</strong> of the rectangular. the input is read from the console. the numbers <code>x1 x2 y1 y2</code> are given one by one on a line. inputs and outputs: <a href= rel= nofollow noreferrer ><img src= alt= enter image description here ></a> an example: <a href= rel= nofollow noreferrer ><img src= alt= enter image description here ></a> my code: <pre><code>x1 = float(raw_input( x1 = )) y1 = float(raw_input( y1 = )) x2 = float(raw_input( x2 = )) y2 = float(raw_input( y2 = )) if x1 &gt; x2 and y1 &lt; y2: a = x1 - x2 b = y2 - y1 else: a = x2 - x1 b = y1 - y1 area = a * b perimeter = 2 * (a + b) print area print perimeter </code></pre>,python
can java classes be outsourced like php with include can java classes be outsourced i have e.g. a huge database java with over 1000 lines and much methods to do database stuff such as insert update etc. i want move similar methods to another file to get a clear file. php can do that with include(filename) . how can java do that,java
call viewdiddisappear in tabbar based application i am using tab bar based iphone application.i have set <code>nstimer</code> in first two tabs.i want to invalidate this timer. so i am invalidating in <code>viewdiddisappear</code>. but when i am clicking on different tab it will never call <code>viewdiddisappear</code>. i don t know how to call this method please help me...thanking you in advance...,iphone
polymorphism has been lost with casting i have a class named <code>student</code> and subclass called <code>athletestudent</code>: <pre><code>public class student { protected string name; protected string age; public void hello () { system.out.println( hello i m student ); } } public class athletestudent extends student { protected string sport; public void hello () { system.out.println( hello i m athletestudent ); } public void changedepartement() { ..... } } </code></pre> now let s take these test cases: <pre><code>athletestudent ats = new athletestudent( test 22 karate ); student std; std = ats; // upcasting ok /* ats and std point to the same object i.e athletestudent */ ats.hello(); /* hello i m athletestudent =&gt; polymorphism ok */ std.hello(); /* hello i m athletestudent =&gt; polymorphism ok */ </code></pre> what i do not understand here is this one: even though <code>std</code> references a <code>athletestudent</code> i cannot access the method <code>changedepartement()</code>. <pre><code>std.changedepartement(); // doesn t work </code></pre> only when we cast this object like this one it works <pre><code>((athletestudent) std).changedepartement(); // ok </code></pre> why we need to force <code>std</code> to be an <code>athletestudent</code> object knowing that it is treated as a <code>athletestudent</code> object with the first example <code>std.hello()</code> prints the one from <code>athletestudent</code> implementation without problems.,java
how to print the result of a method in a different class i want to print my method compute located in the class computedivisor in the divisors class. how do i get it to who the divisors <pre><code>public static void main(string[] args) { scanner s = new scanner(; computedivisors cd = new computedivisors(); system.out.println( enter an integer: ); int num = s.nextint(); system.out.println( the divisors of + num + are: ); cd.compute(); //why doesn t it print s.close(); } </code></pre> - <pre><code>public void compute(){ for (i = 2; i &lt;= num / 2; i++) { if (num % i == 0) { system.out.print(i + ); } } } </code></pre> },java
how to test localized string on simulator i am using nslocalizedstring(); function for my localized strings. even though i change my preferred language in simulator settings my string still get shown up in english. can we test the nslocalizedstring(); from simulator if so how can any one guide me through this please -- regards u suf,iphone
check if the second element of tuples in list of tuples are all the same i would like to check if the second element of tuples in list of tuples are all the same <pre><code>features = [(a b) (c b) (a d)] </code></pre> the first element of the tuple can be different. <pre><code>x = [] for feature geom_type in features: x.append(geom_type) y = collections.counter(x) print len([i for i in y if y[i]&gt;1]) </code></pre>,python
how to make asynchronous call using nsthread i have made one list of images + respective data in tableview. it takes long time while loading i want to make multithreading two methods 1> <strong>parsing of data</strong> 2> <strong>parsing of images</strong> i want to execute <strong>parsing of data</strong> first after that i can select any of rows listed even though images not been loaded(/parsed) because the images is parsed after the parsing of data and it takes long time. from where should i call these both the methods. and how enable the selection on row after parsing of the data... how to do multithread both the methods waiting for your great responce thanking in advance,iphone
rounding a percentage in python <pre><code>if act == block and enemy_decision != 2: percentage_blocked = (enemy_attack - block)/(enemy_attack) * 100 print( you have blocked %s percent of the enemy s attack. % percentage_blocked) </code></pre> from this i am getting numbers such as 82.113124523242323. how can i round this percentage to the 10th place e.g. 82.1.,python
disable keyboard for one of the text fields in a table view hi i am new to the iphone developement.kindly help me out. i want to disable the keyboard for one of text field in a table view.i have assigned a pickerview to that particular i need just the pickerview and not the keyboard.,iphone
get responsebody as characters i am trying to get response from a website. i am using <code>httpurlconnection</code> class. this is my code: <pre><code> bufferedreader in = null; in = new bufferedreader(new inputstreamreader(httpcon.getinputstream())); string line; while ((line= in.readline()) != null) { system.out.println(line); } </code></pre> all i get is : �q�u����0�_������q�j��r衔�j1�4q�ȓ��d�%�ޑl/��^�0�ϯ�7�[6@~ȟ�k��s��+u how can i decode it thank you.,java
location.href is decoding the url i have a javascript function: <pre><code>function quotebegone(url) { location.href = url; } </code></pre> the url that is passed is encoded for example <code> name%3djohn%27s%2bproject</code> but when the new page loads the url is unencoded - <code> name=john s+project</code>. the apostrophe is messing up the page so i would like to keep it encoded in the url but it doesn t seem to stay that way. i assume the location.href function is interpreting the url before passing it along. any suggestions,javascript
"call callback from created <script> in created <iframe> i have a js code which should create a new <em>iframe</em> then create a new <em>script</em> with a code and insert the created <em>script</em> into created <em>iframe</em>. everything works fine except <em>callback</em> which is defined in main s page js and which i should call from the inserted <em>script</em> because it isn t defined in the created <em>script</em>. my code looks like: <div class= snippet data-lang= js data-hide= false data-console= true data-babel= false >
<div class= snippet-code >
<pre class= snippet-code-js lang-js prettyprint-override ><code>(function(){
function makeiframe(adelement callback){
var iframe = document.createelement( iframe );
adelement.parentnode.insertbefore(iframe adelement);
function createscripttag(){
var scripttag = document.createelement( script );
scripttag.innerhtml = getfunctionbodyasstring(innercode);
return scripttag;
function innercode(){
function getfunctionbodyasstring(fun){
return fun.tostring().match(/function[^{]+\{([\s\s]*)\}$/)[1];
makeiframe(document.getelementbyid( sth-id ) function(){
alert( works! )
<pre class= snippet-code-html lang-html prettyprint-override ><code>&lt;!doctype html&gt;
&lt;div id= sth-id &gt;&lt;/div&gt;
&lt;script src= test.js &gt;&lt;/script&gt;
my question is how can i call <em>callback</em> function from the creted <em>script</em> in the created <em>iframe</em> ps. i m not very experienced with js any suggestion to present code will be hopefull :) <strong>update 1:</strong> the only place where i can define my <em>callback</em> function it s in the js <em>script</em> (test.js) and also from this place i should call function (in example <em>makeiframe</em>) which runs all other logic.",javascript
when is it okay to attach properties to window while browsing i frequently take a look at the source code of webpage to check how certain things have been realized. one thing i frequently see is stuff like: <code>window.myapp.apikey = 12345;</code> or <code>window.myapp.welcomemsg = hello there! ;</code> i always was under the impression that it s bad practice to attach properties to the window object (like explained in this <a href= >accepted answer</a>) but it looks like <code>myapp</code> is used as a kind of namespace &amp; since it s often the brand name it s unlikely to clash with anything. still – how is it okay to do it this way are there any indicators for that (i.e. when i know no 3rd libraries will be used in the project which can change quickly in real life).,javascript
background image size iphone normal background image is 320x480 pixels. and for retina is 640x960 pixels. now i have to put my background image and i have status bar(20) and navigation bar (44). so i have to reduce 64(20+44) from 480(normal) or from 960(retina) <ol> <li>if i reduce 64 from normal then normal image will be 320x416 pixels and retina will be 640x832 pixels.</li> <li>if i reduce 64 from retina then normal will be 320x448 and retina will be 640x896 .</li> </ol> it is confusing me.. this 64(20+44) i reduce from which image type because other one will be exactly half or double of it.,iphone
when running my program nothing is shown in the console <pre><code>public class quartz { public static void main (string[] args) { int i = 0; int sum = 0; int[] n1 = {54 40 37 64 81 15 65 72 61 57 83 3 67 12 30 54 11 51 3 78 48 31 68 77 64 68 95 68 35 82 57 26 67 41 47 80 36 88 5 9 55 87 77 8 65 31 7 79 49 22 32 94 34 12 20 30 91 12 57 77 37 96 22 29 17 76 36 56 80 33 20 65 57 40 50 97 20 92 25 14 19 84 12 62 20 42 99 52 88 29 75 48 27 73 46 72 48 84 19 55}; while (i &lt; n1.length) sum += n1[i]; i = 0; system.out.println( sum: + sum + . ); system.out.println( average: + (sum/n1.length) + . ); double[] ne = {-0.6179074665219488 0.012080423982449795 -0.21346000509541063 0.08299652983289585 2.44401680106775 4.902778859313734 1.7132831483350532 -4.2004763396051725 -4.043856195861675 -2.6728507023602326 5.181911533071974 -2.1235877432845354 7.603895698367564 -5.6730748575837975 -3.5868701412258464 8.50824673494424 1.9530312960520657 1.4057711751329447 -6.6010520166956885 -0.8889270825881894 -3.066437913144831 -1.047977711607209 -0.6183425325427638 -1.9567474971238643 -1.6108985491087715 -3.4762343504063105 -0.7819967483948718 1.2787199500848474 -1.724036624119682 4.134045084705252 -4.302090407212001 4.522452909896921 -9.510982189042458 4.483571903648103 4.734972592935479 1.3007048393668028 -1.5733757395516363 -1.9343054344201707 6.787212280236046 -0.35603892339489995 -1.3414921239899753 -0.9393551256779856 -1.9298884254368263 6.043295105337908 2.9330671137121733 2.8561036619044047 -0.8293767467550212 6.123622142714353 -2.2350961485598777 7.20722805161423 5.515389689089437 -2.7666432567169745 -4.344590134196103 3.3453531590362613 10.413288779778698 0.3986583788822756 1.8156402784897105 -6.495232639280744 -2.5586148068696852 2.456750085945401 -2.0241915465317994 2.6640207424833706 -3.221638093253812 -0.13291701098446618 4.525894152095317 3.833943185257407 -2.892260297173234 -3.247865929061468 6.129696012756685 4.451839001858698 -3.142375819178058 -1.0758596832313212 -7.85705595464708 -3.376343621066232 -3.993944532318441 13.146850947670861 -1.3900676627648902 3.8600378751921256 3.9652071948870447 -2.4382860496298324 3.0864605092488304 -10.769089293963074 1.9773754511588617 4.826841112732377 7.9219782116860324 -3.266132871461332 1.8118819669439024 0.698579723806034 7.119629551067371 -0.9141128559070014 1.5143207368301361 -8.587596597534729 -0.9387144566983379 2.5641381148921805 10.628593146418485 3.794317923770138 6.2802756227726615 -0.05171930511667566 0.8736426098894451 0.6226851580000003}; double[] nw = {9.631212195521316 -2.1235831279282698 3.7468670477204773 -4.559878135521824 3.2444286767576545 6.2877828741148605 6.520597627024687 2.642307472836288 1.2002893113069557 0.32620641006622675 -3.368962812990781 -2.588868228199504 4.356518441561512 -0.5955112302723241 0.3875648501871751 -2.9311051175998064 2.0095554763173666 -1.228769483871199 5.900445902470515 0.41527619439744434 2.9752128071432145 4.805920315662717 -4.797853823364673 5.752192282393844 2.9073605365834556 2.4870719041084497 -1.7994046436584152 7.79554996548367 4.4174973514255536 2.084039895979635 0.6281302992116424 -3.1466915662704524 3.646400672147826 0.9609952887592054 -6.070082172976056 -0.9392599054917704 0.904301836858967 5.926867039519574 3.238559698585232 -4.439332575192746 1.352444182896236 -0.24594080100384297 -1.6395807550351367 3.591208179788307 4.15757174804611 -3.5334824535956173 0.5302366137985215 9.564674975899017 4.175389023096817 -0.9827335882191762 4.305890552392608 3.059083687714633 2.3224548745551488 0.1934380213592375 1.0235814 1.1716370685853148 -2.931711339626567 -4.214035402157694 -1.0093422753964358 -4.843082160061708 -7.148710177896536 -1.910725804980465 -0.22905523068711164 3.8200222938181367 -1.744095856344644 1.354958988184811 0.9933832752568843 0.8820951391051288 -2.062035935350486 -7.633897329029599 0.49911238393151325 -1.1684033502541722 4.090099097765502 4.566828839384462 0.6901115935421007 -4.30695891725898 -5.637531096381548 2.6920329212478507 -1.522395621132775 6.351734133984433 0.4895678835360122 -4.755548841958967 -2.826990702897114 1.974618789378563 -6.999938959339396 0.6289774718852977 3.2732671487606266 -1.2781272997669557 6.725303989648547 -7.163688015215646 5.547683884070125 -3.0189942298996213 -0.2487963910538069 -0.46314538549764894 5.3913279138183645 -4.018219623545416 6.491084381355617 -1.5629014732514819 -6.557894883162792 -3.856421007612216}; int sumeeven = 0 sumeodd = 0 sumweven = 0 sumwodd = 0; while (i &lt; 99) { sumeeven += ne[i]; sumeodd += ne[i+1]; i += 2; } i = 0; while (i &lt; 99) { sumweven += nw[i]; sumwodd += nw[i+1]; i += 2; } system.out.println( front coordinates: ); system.out.println( latitude: + sumeeven + longitude: + sumeodd); system.out.println(); system.out.println( back coordinates: ); system.out.println( latitude: + sumweven + longitude: + sumwodd); } } </code></pre> this code has no errors and runs but the console is empty. i have my run configurations set up correctly so not sure what the issue is. i also made sure that my console was linked to this project and not another and it is. i m running eclipse neon if that changes anything. some info about the project although seemingly irrelevant: n1 calculates the sum of that array of ints and then take the average of the sum ne and nw calculate the sum of the even parts of each array and the odd parts of each array and adds each up individually and they end up being latitudinal and longitudinal coordinates.,java
javascript issue my div won t move yesterday in class my teacher put up some code for us to test at home but i can t seem to get the code to work. what the code is suppose to do is move a div while holding the mouse down. i showed my friend and we think the problem is here: <pre><code> = getstyle(calculator top ); = getstyle(calculator left ); function getstyle(object stylename) { if (window.getcomputedstyle) { return document.defaultview.getcomputedstyle(object null).getpropertyvalue(stylename); } else if (object.currentstyle) { return object.currentstyle[stylename]; } } </code></pre> but we still can t seem to make it work. help would be extremely appreciated. also here is the full code just in case you need to see it: <pre><code>diffx = null; diffy = null; off = document.getelementbyid( buttonoff ); on = document.getelementbyid( calcbutton ); calculator = document.getelementbyid( calculator ); = getstyle(calculator top ); = getstyle(calculator left ); function getstyle(object stylename) { if (window.getcomputedstyle) { return document.defaultview.getcomputedstyle(object null).getpropertyvalue(stylename); } else if (object.currentstyle) { return object.currentstyle[stylename]; } } function grabcalculator(e) { var evt = e || window.event; calculator = || evt.srcelement; var mousex = evt.clientx; var mousey = evt.clienty; diffx = parseint( – mousex; diffy = parseint( – mousey; addevent(document mousemove movecalculator false); addevent(document mouseup dropcalculator false); } function movecalculator(e) { var evt = e || window.event; var mousex = evt.clientx; var mousey = evt.clienty; = mousex + diffx + px ; = mousey + diffy + px ; } function addevent(obj eventtype fnname cap) { if (obj.attachevent) { obj.attachevent( on + eventtype fnname); } else { obj.addeventlistener(eventtype fnname cap); } } function removeevent(obj eventtype fnname cap) { if (obj.attachevent) { obj.detachevent( off + eventtype fnname); } else { obj.removeeventlistener(eventtype fnname cap); } } function dropcalculator(e) { removeevent(document mousemove movecalculator false); removeevent(document mouseup dropcalculator false); } function main() { alert( test ); //store top and left values of calculator = getstyle(calculator top ); = getstyle(calculator left ); calcbuttonstate = true; } window.onload = main; </code></pre> thanks again! sandro <hr> edit: added jsfiddle link: <a href= rel= nofollow ></a> (also the output looks horrible because its not suppose to be resized to that small),javascript
how to call all of the xib/nib files properties i created a tabbarcontroller application for the iphone that has a mainview.xib with a tabbar two tabbar buttons and two additional views. the additional views have a uimapkit and a uitableview. what i want to do is in the tableview i want to invoke the uimapkit view when ever a user tabs on a row. what i did: -(void)tableview:(uitableview *)tableview didselectrowatindexpath:(nsindexpath *)indexpath { <pre><code>mapviewcontroller *nview = [[mapviewcontroller alloc] initwithnibname:nil bundle:[nsbundle mainbundle]]; [self presentmodalviewcontroller:nview animated:yes]; </code></pre> } which creates an action for the rows. my problem is that it only shows the uimapkit and not the tabbarcontroller. the tabbarcontroller is in the mainwindow. is there some code that i m missing,iphone
404 error document not found for javascript file when installing instafeed onto wordpress site i uploaded the file <code>instafeed.min.js</code> to my websites server. i then added the <code>instafeed script</code> to the very end of the <code>&lt;body&gt;</code>. this is the exact script: <pre><code>&lt;script src= /wp-admin/js/instafeed.min.js ver=4.4 type= text/javascript &gt;&lt;/script&gt; &lt;script type= text/javascript &gt; var feed = new instafeed ({ get: tagged tagname: awesome clientid: my-id template: &lt;a href= {{link}} &gt;&lt;img src= {{image}} /&gt;&lt;/a&gt; });; &lt;/script&gt; </code></pre> within the page i have added this as the directions say to: <pre><code>&lt;div id= instafeed &gt;&lt;/div&gt; </code></pre> nothing shows up on the page. <a href= rel= nofollow ></a> i inspected the element and i get two errors: <pre><code>uncaught referenceerror: instafeed is not defined </code></pre> and <pre><code>get wp-admin/js/instafeed.min.js 404 (not found) </code></pre> i contacted my host to check the file root and it is indeed there. any ideas on how to get this to work laura,javascript
iphone: how to find string in a complete string how to get the a certain string from a complete string. for ex: i have a complete string like below. <pre><code> ; </code></pre> i need to get album.wav from the above string. the name varies with different url string. how to get it thanks.,iphone
where i get the life cycle between uiview uinaviagtioncontroller and uiviewcontroller i am a beginner in iphone development. i very confused on the behaviour or life cycle between uiview uinavigationcontroller and uiviewcontroller. please suggest me any documentation on it which has to be fully understandable diagrammatically.,iphone
why is the dict.keys not iterable <code>node_name</code> is a string. shouldn t this return a list of keys in the node_list dictionary which can be iterated over why does the error say it is not iterable <pre><code>class graph: def __init__(self): self.node_list = {} self.number = 0 def node(self node_name): if node_name in self.node_list.keys: ... file line 10 in node if node_name in self.node_list.keys: #returns list of keys typeerror: argument of type builtin_function_or_method is not iterable </code></pre>,python
iphone how to create scrollable filter like mashable app i d like to create a scrollable filter just below the navigation bar like in the mashable iphone app. here s what it looks like: <a href= mt=8 rel= nofollow > mt=8</a> <a href= rel= nofollow ></a> does anyone know how to do this,iphone
object.keys in reverse order i have interesting task. i solved the half of it but can t to find the solution to solve the rest. hope someone can point me to the right direction. i found the <a href= >solution</a> close to mine task. but mine is slightly different and use es6. there is nested object. <pre><code>let somelist = { value: 1 next: { value: 2 next: { value: 3 next: { value: 4 next: null } } } }; </code></pre> i received all values. <pre><code>function reverseprint(linkedlist) { object.keys(linkedlist).map(key =&gt; { let mykey = linkedlist[key]; typeof mykey == object console.log(reverseprint(mykey)) : console.log(mykey); }); } reverseprint(somelist); </code></pre> but the problem is: how i can get all values in reverse order fiddle: <a href= rel= nofollow noreferrer ></a> i tried use reduce for to make array and reverse it but every value was in separate array. fiddle <a href= rel= nofollow noreferrer ></a> any help will be greatly appriciated.,javascript
is there a way to determine the setting of the ring/silent switch on the iphone i am trying to figure out from my code whether the ring/silent switch is on ring or silent. is there a way to determine this from my program. thanks,iphone
iphone: get uilabel width in cellforrowatindexpath i have a uitableview with a custom row. on my custom row i have uilabel with autosizing by width mask that is why in portrait it has one width and in landscape another. in my cellforrowatindexpath i should get label width: <pre><code>- (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath: (nsindexpath *)indexpath { uilabel *mylabel = (uilabel *)[cell viewwithtag:2]; float width = mylabel.frame.size.width; } </code></pre> and when i run application everything is fine and width is good. but when i rotate device to landscape cellforrowatindexpath called before uilabel changed its frame and i v got the same width as in portrait. so how to be how to get right width when i rotate device the one idea that comes on my mind is to reload tableview in there any other solutions thanks... <strong>update:</strong> one more thing when i start application in landscape mode width is still like in portrait. why how to fix that,iphone
how to create viewbased application in xcode 4.2 without using storyboard i am a neewbie in iphone develement i am trying to create single view application using xcode 4.2 i want to move from one view to another view . is there any way to push view from one to other without using storyboard,iphone
javascript - making 2 setinterval() be synchronous i have 2 functions calling setinterval but i need them to be synchronous. here is my code(yes they are really simple). <pre><code>var number1 = 0; function caller(){ go(); come(); } function go() { anim1 = setinterval( doactiongo() 20); } function come() { anim2 = setinterval( doactioncome() 20); } function doactiongo(){ if(number1 &lt; 1023) { number1++; } else { clearinterval(anim1); } } function doactioncome() { if (number1 &gt; 0) { number1 = number1 - 1 } else { clearinterval(anim2); } </code></pre> functions doactiongo() and doactioncome() would be any code. does anybody know how to solve it regards!,javascript
show the option of triggering my app i noticed that there are some apps can show the option of triggering them when i touch and hold seconds over email attachment. just wonder how can i do like these welcome any comment,iphone
obtain filesize without using filesystemobject in javascript i am working on a project in in which i want to get the filesize using javascript. actually i got the solution and that is as like the following <pre><code>&lt;script language= javascript &gt; var fo =new activexobject( scripting.filesystemobject ); var filename=new string(); function trim(input) { var lre = /^\s*/; var rre = /\s*$/; input = input.replace(lre ); input = input.replace(rre ); return input; } function getsize(filepath) { try { var thefile = fo.getfile(filepath); var size = thefile.size; return size; } catch(err){} } function gettype(filepath) { try { var thefile = fo.getfile(filepath); var filetype = thefile.type; return filetype; } catch(err){} } function showerrorpnl(tblpnl) { document.getelementbyid(tblpnl).style.visibility= visible ; document.getelementbyid(tblpnl).style.backgroundcolor= yellow ; document.getelementbyid(tblpnl).style.bordercolor= silver ; } function uploadfile_checktype(fileuploadctrl messagectrl hfieldctrl tblpnl) { try { var file = document.getelementbyid(fileuploadctrl); var filename=file.value; document.getelementbyid(messagectrl).innertext= ; document.getelementbyid(tblpnl).style.visibility= hidden ; document.getelementbyid(hfieldctrl).value= ; // file can be uploaded. //checking for file browsed or not if((getsize(filename)/1024)&gt;500) { document.getelementbyid(messagectrl).innertext= file size is exceeding 500k ; document.getelementbyid(hfieldctrl).value= 0 ; // file cannot upload. showerrorpnl(tblpnl); file.focus(); return false; } if(gettype(filename)!= microsoft office word 97 - 2003 document &amp;&amp; gettype(filename)!= adobe acrobat document ) { document.getelementbyid(messagectrl).innertext= (document.getelementbyid(messagectrl).innertext== only doc and pdf file can be upload!!! : document.getelementbyid(messagectrl).innertext + \n + only doc and pdf file can be upload!!! ); showerrorpnl(tblpnl); document.getelementbyid(hfieldctrl).value= 0 ; // file cannot upload. file.focus(); return false; } } catch(err){} } &lt;/script&gt; </code></pre> it is working perfectly unless making some setting in internet explorer properties. in internet properties - > select security tab - > local internet - > click on custom level button - > initialize and script activex controls not marked as safe for scripting - > make it enable save settings and execute program. this is working but i want to get filesize without using <code>var fo =new activexobject( scripting.filesystemobject );</code>,javascript
iphone:server response parsing issues the below is my server response. i would like to parse and use it further. responsestring: <pre><code>{ status : 1 mydata : [ { value : 1 name : david musicurl : imageurl : } { value : 2 name : martin musicurl : http: // imageurl : http: // } { value : 3 name : steve musicurl : http: // imageurl : http: // } ] } </code></pre> the below is my code for trying further to parse and use it. but the issue is its not getting parsed from nsjsonserialization instead i m getting null. printing as responsedict:(null) ; jsonerror: (null). <strong>please note</strong> when i m doing like this->nsstring *responsestring = [[nsstring alloc] initwithdata:theresponsedata encoding:nsutf8stringencoding]; i m getting response string as the above output. but i want it as nsdictionary for my further use. please help to resolve this issue. nsmutabledata *webdata; <pre><code>-(void)connection:(nsurlconnection *)connection didreceiveresponse:(nsurlresponse *)response { [webdata setlength: 0]; // [self callgetgroup]; } -(void)connection:(nsurlconnection *)connection didreceivedata:(nsdata *)data { [webdata appenddata:data]; } -(void)connectiondidfinishloading:(nsurlconnection *)connection { nsdata *theresponsedata = [[nsdata alloc] initwithdata:webdata]; if (theresponsedata) { //nsstring *responsestring = [[nsstring alloc] initwithdata:theresponsedata encoding:nsutf8stringencoding]; //nslog(@ responsestring:%@ ; responsestring); nserror *jsonerror; nsdictionary *responsedict = [nsjsonserialization jsonobjectwithdata:theresponsedata options:0 error:&amp;jsonerror]; nslog(@ responsedict:%@ ; jsonerror: %@ responsedict jsonerror); // printing as responsedict:(null) ; jsonerror: (null) [self handleresponse :responsedict]; } } -(void) handleresponse :(nsdictionary *) responsedata { nsstring* value = null; for (id key in responsedata) { nsdictionary *currentdict = (nsdictionary *) [responsedata objectforkey:key]; value = (nsstring*)[currentdict objectforkey:@ status ]; if ( [value intvalue]==1) // success { } } } </code></pre>,iphone
iphone - preventing attachments from showing i am using mfmailcomposeviewcontroller to compose a message on a view. if i attach a pdf or an png jpeg or gif image to the message the image is shown on the mail composition view. if the image is huge it is very difficult for the user to type the message. is there a way to attach a known document to a mfmailcomposeviewcontroller view and prevent the attachment from being opened i want to be able to show the attachment as an attached file icon. i don t want to see its contents opened on the window. is this possible thanks,iphone
how to create a pay roll in which i can add employees without using an array here is the description of my assignment implement a class called employee. an employee has a name and gets a salary. every pay period each employee gets an additional amount in bonus. in your solution include a constructor that accepts the name and salary of an employee. provide a mutator method that accepts the bonus amount and adds it to the salary. provide necessary accessor methods to return the name the salary before the bonus was applied the bonus and the salary after the bonus has been applied. i have all of that done except that when i try to add another employee it just overwrites the variable and prints only the last employee added. heres my code: <pre><code> package employeetester; import java.util.scanner; public class employeetester { public static void main(string[] args) { string employee = ; string continue; string printchart; double salary = 0; double bonus = 0; double totalsalary = 0; scanner user_input = new scanner( ); employeepayroll epr = new employeepayroll(employee salary); system.out.print( would you like to add an employee to the pay roll ); continue =; while (continue.equalsignorecase( yes ) || continue.equalsignorecase( y )){ system.out.println( what is the name of the employee ); employee =; epr.employee(employee); system.out.println( \nwhat is the salary of + employee + ); salary = user_input.nextdouble(); epr.salary(salary); system.out.println( \nwhat is the bonus of + employee + ); bonus = user_input.nextdouble(); epr.bonus(bonus); system.out.print( would you like to add an employee to the pay roll ); continue =; } system.out.println( \nwould you like to print out the pay roll chart ); printchart =; if (printchart.equalsignorecase( yes ) || printchart.equalsignorecase( y )){ //employeepayroll epr = new employeepayroll(employee salary); epr.totalsalary(bonus); epr.printchart(); } } } </code></pre> here s the second part <pre><code>package employeetester; public class employeepayroll { private string employee; private double salary; private double bonus; private double totalsalary; public employeepayroll (string employee double salary){ this.employee = employee; this.salary = salary; } public void employee(string emp){ employee = emp; } public void salary(double slry){ salary = slry; } public void bonus(double bnus){ bonus = bnus; } public double totalsalary(double bonus){ this.bonus = bonus; double totalsalary = salary + bonus; this.totalsalary = totalsalary; return totalsalary; } public void printchart(){ system.out.println( \npayroll ); system.out.println( -------- employee -------- ); system.out.println( name: \t + employee); system.out.println( salary: \t + salary); system.out.println( bonus: \t + bonus); system.out.println( total: \t + totalsalary); system.out.println(); } } </code></pre> how do i print out every employee added the only thing i can think of is using an arraylist but we re not allowed to use that.,java
put the javascript code between the <head> tags i want to put the script between the <code>&lt;head&gt;</code> tags using the anonymous function and i add the onclick event to change the contents of the tag p but after i click nothing happens. is there anything wrong from my script please help me. thank you <pre><code>&lt;!doctype html&gt; &lt;html lang= en &gt; &lt;head&gt; &lt;title&gt;web&lt;/title&gt; &lt;script&gt; window.onload=function(){ function rubah1(){ document.getelementbyid( text1 ).innerhtml= sudah berubah text 1 ; } } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;p id= text1 &gt;teks 1 sebelum di rubah&lt;/p&gt; &lt;button type= button onclick= rubah1(); &gt;rubah text 1&lt;/button&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>,javascript
npe when checking for object so i feel like an idiot but i m trying to implement collision detection and i need to check if there is a tile next to the player. when i go to check for one first i see if the tile i m looking for is actually there. if it is i proceed to select the tile and create a new object out of it. if it s not i don t touch the tile. however i m getting a npe when just trying to check for the tile! here s the checking code (just a small section that s relevant): <pre><code>if (world.tiles[(int) getx() / 32][(int) gety() / 32] != null) { tile t = world.tiles[(int) getx() / 32][(int) gety() / 32]; </code></pre> and here s the tile array in the world class which i pass in to the player: <pre><code> public tile[][] tiles; </code></pre> and how i create them: <pre><code>tiles = new tile[mx][my]; for (int x = 0; x &lt; mx; x++) { for (int y = 0; y &lt; my; y++) { if (rand.nextint(2) == 0) { tiles[x][y] = new tile(x * 32 y * 32 32); }else if(y == 0){ tiles[x][y] = new tile(x * 32 y * 32 32); } } } </code></pre> as you can see i get the player position and then divide by the tile size (32) to get the tile coordinates and then check to see if the tile is null. i know i m passing in the world to the player so that isn t the issue. the issue is that when i look for the tile its null! why,java
java search functionality there is a requirement in my java project where the user will enter the customer name/ number in the front-end screen and hit search button the system should display all the matching customer names with links to the customer details. i have been asked to write a web service to implement this functionality which will fetch the customer records from the database and display it in the front-end. please help me how to do this. thanks in advance!!,java
do some functions take return and other not in python i m trying to figure out why some statements require and return and others do not like below i wrote this and l1.append(val) doesn t need a return but for example l1[val] does does it just depend on the variable <pre><code>l = [1 3 5 7 9 11 2] print original list = l def change_list(l1 val decision): if decision == append : return l1[val] elif decision == ret : l1.append(val) elif decision == instance : return l1.count(val) elif decision == sort : l1.sort() return l1 res=change_list(l 2 append ) print output = res </code></pre> however if i change it to the following (remove the return) it breaks! wh does this happen given some of the conditions need a return to work some do not : l = [1 3 5 7 9 11 2] <pre><code>print original list = l def change_list(l1 val decision): if decision == append : l1[val] elif decision == ret : l1.append(val) elif decision == instance : return l1.count(val) elif decision == sort : l1.sort() return l1 res=change_list(l 2 append ) print output = res </code></pre>,python
java code doesn t work hey guys i am have a problem in java coding. i am using eclipse and my code is as following: <pre><code>public class application { public static void main(string[] args){ int loop = 100; int looop = 90; while(loop &gt; looop) system.out.println(looop); looop = looop + 1; } } </code></pre> the output should be like this: <pre><code>90 91 92 93 94 95 96 97 98 99 </code></pre> but it keeps on printing 90 and doesn t stop the loop.,java
how to bring bigdecimal to fractional power bigdecimal was the choice to store numbers that have up to 5 digits after decimal point. i need to raise the bigdecimal to fractional power (up to 2 digits after decimal point). for example i have to bring 9.09671 to power of 1.51. do i need some conversions from/to bigdecimal how to do it <strong>edit:</strong> i cannot use 3rd party libraries as described in <a href= >java s bigdecimal.power(bigdecimal exponent): is there a java library that does it </a> is there more elegant succint way for this case than described in <a href= >how to do a fractional power on bigdecimal in java </a>,java
python loop to print asterisks based on user input i m trying to create a python program to print a certain number of asterisks based on user input. my code is below <pre><code>num_stars = 3 num_printed = 0 while num_printed &lt;= num_stars: print( * ) </code></pre> the output is an infinite loop. i want to print the number of stars variable as asterisks.,python
what version of xcode will support ios 3.0 i want my app to support the largest audience possible. i am thinking this would be ios 3.0 to ios 7.0. i originally wrote the app using xcode 5.0 but because i used storyboarding i could only support users that had ios 5.0 or higher at the time. at this point i am thinking of reworking the app so it no longer uses storyboarding and using a lower version of xcode. i am also wondering how to support ios 7.0 as while supporting ios 3.0 users was wondering if someone could point me in the right direction thanks in advance!,iphone
scanner java: - how to read what type of data user entered i am very new to programming and what i started doing is writing a code that converts different units in metric system. for example the program asks the user to enter x-amount of kilometer and then it converts that value to miles etc. of course km &amp; miles can only be positive values. however i don t seem to get around of telling the program: if entered value is an alphabetic value then ask user to reenter the value. i seem to get it working for negative values but not for alphabetic characters please help. <strong>here is my code:</strong> <pre><code> //method for converting kilometer to mile. will be invoked in main method public static void kmtomiles(double k double mi) { scanner scan = new scanner(; system.out.println( convert kilometer to mile: ); k = scan.nextdouble(); mi = k / 1.609344; if(mi &lt; 0) { do { system.out.println( entered value can not be negative. enter a positive value: ); k = scan.nextdouble(); mi = k / 1.609344; } while (mi &lt; 0); } bigdecimal bd = new bigdecimal(mi); bd = bd.setscale(1 roundingmode.ceiling); system.out.println((int) k + kilometer(s) =: + bd + miles ); system.out.println( *****************************************\n ); scan.close(); } </code></pre>,java
all events that would trigger the applicationwillresignactive & applicationdidbecomeactive i know pressing command-l can trigger <strong>applicationwillresignactive:</strong> from forum here. 1) is it only applied to ios4 2) besides in the real scenario with the device what would trigger the <strong>applicationwillresignactive:</strong> &amp; <strong>applicationdidbecomeactive:</strong> i searched answers in this forum. some said it depends the reply of a call some said sms some said only an app which pops up a view. is there a list of events i can find,iphone
syntax error unrecognized expression after putting js code in a js file i ve this code in my aspx file which uses jquery-1.9.1.js and the app runs fine: <pre><code>&lt;script type= text/javascript &gt; $(function () { $( #&lt;%=datepickerstart.clientid%&gt; ).datepicker(); $( #&lt;%=datepickerend.clientid%&gt; ).datepicker(); }); &lt;/script&gt; &lt;asp:textbox id= datepickerstart runat= server &gt;start date&lt;/asp:textbox&gt; &lt;asp:hiddenfield id= hiddendatestart runat= server /&gt; </code></pre> when i put the js code in a js file like this: <pre><code>$(document).ready(function() { $( #&lt;%=datepickerstart.clientid%&gt; ).datepicker(); $( #&lt;%=datepickerend.clientid%&gt; ).datepicker(); }); </code></pre> i got this error message: syntax error unrecognized expression: <pre><code>#&lt;%=datepickerstart.clientid%&gt; </code></pre> any suggestions would be greatly appreciated.,javascript
object() takes no parameters in python 3.4.0 why do i get this error when trying to run the following code <blockquote> cobj1 = car( ford black ) typeerror: object() takes no parameters </blockquote> <pre><code>class car(object): numwheels = 4 def display(self): print( make: self.make) print( colour: self.colour) print( wheels: car.numwheels) #main program cobj1 = car( ford black ) cobj1.display() </code></pre>,python
incorrect output when finding number of repeated digits in an ineger i am trying to find the number of duplicate (repeated) digits in a number for each unique digit. eg. for 21311243 there would be 3 1 s and 2 2 s and 2 3 s so i would just need [3 2 2] where order doesn t matter. i am trying to do this as follows where <code>number_list = [ 2 1 3 1 1 2 4 3 ]</code>. the code below works for the above number and i get that <code>repeated_numbers = [2 2 3]</code> as expected. however for 213112433 <code>repeated_numbers = [2 3 3 2]</code> for some reason and i don t know why this is and how to rectify the code below as such: <pre><code>repeated_numbers = [] #the number of repeated digits for each unique digit for a in number_list: i = 0 for b in number_list: if (a == b): i = i + 1 if i &gt; 1: #if the particular digit is repeated repeated_numbers.append(i) number_list.remove(a) #get rid of the digit that gets repeated from the list </code></pre> also i am open to better ways of doing this as my way has <code>o(n^2)</code> complexity but need that <code>number_list</code> is considered as a list of characters.,python
relation between two lists in java i have two sets of different types of objects. each element of one set is related to one element of the other and the two lists are in two different classes. i have a function that iterates over one set and check if this element must be removed and when it does i must delete the associated element in the other set. what kind of collection and methodology must i use to do so,java
what is the meaning of if (this [x]) in javascript i m using a javascript game engine called panda and i m getting an error in the console (uncaught class bg already created). and when i explore the source code of the engine i found the code that is throwing the error (below). my question is in the second if statement what is the meaning of (this[name]) i don t understand what exactly its saying. any help would be appreciated. thanks in advanced. <pre><code>createclass: function(name extend content) { if (typeof name === object ) return this.class.extend(name); if (this[name]) throw class + name + already created ; if (typeof extend === object ) { content = extend; extend = class ; } </code></pre>,javascript
most effective way of drawing 4 lines in an iphone app basic question but i m unsure. not looking for code as an answer. i want to draw 4 short lines 1px lines on a view. what is the best way to approach this task options:- <ul> <li>load an image of the line then create 4 uiimageviews with it.</li> <li>create my own subclass of a uiview that draws a line in the draw rect method.</li> <li>draw elsewhere on another view another uiimageview that has an uiimage inside it (is this possible )</li> <li>another way </li> </ul> thanks ross,iphone
cannot seem to find what is wrong <pre><code>import; import; import java.util.arraylist; import java.util.scanner; public class salaries { public static void main(string[] args) throws filenotfoundexception { string filename = args[0]; scanner in = new scanner(new file(filename)); int sum = 0; in.nextline(); while(in.hasnextline()) { int totalsalary = 0; string line = in.nextline(); string[] linearray = in.nextline().split( \\s+ ); for(int i = 0; i &lt;= linearray[i].length(); i++) { string arrayints = linearray[i]; if(linearray[i].contains( $ )) { arrayints = arrayints.replace( $ ); arrayints = arrayints.replace( ); totalsalary = integer.parseint(arrayints); sum = sum + totalsalary; } } } system.out.printf( $% d\n sum); sum = 0; } } </code></pre> i can not figure out why i keep getting an out of bounds error. my code is supposed to go through a text file and gather the numbers and create totals. text file below: <pre class= lang-none prettyprint-override ><code>campus president salary housing auto allowance bakersfield horace mitchell $285 000 $50 000 $12 000 channel island richard r. rush $275 000 $60 000 $12 000 chico paul j. zingg $279 500 $50 000 $12 000 dominguez hills mildred garcia $295 000 provided $12 000 east bay mohammad h. qayoumi $276 055 $60 000 $12 000 fresno john welty $299 000 provided $12 000 fullerton milton a. gordon $295 000 provided $12 000 humboldt rollin c. richmond $297 870 $50 000 $12 000 long beach f. king alexander $320 329 provided $12 000 los angeles james rosser $325 000 $60 000 $12 000 maritime william b. eisenhardt $258 680 provided $12 000 monterey bay diane f. harrison $270 315 provided $12 000 northridge jolene koester $295 000 provided $12 000 pomona j. michael ortiz $292 000 provided $12 000 sacramento alexander gonzalez $295 000 $60 000 $12 000 san bernardino albert k. karnig $290 000 $50 000 $12 000 san diego stephen l. weber $299 435 provided $12 000 san francisco robert a. corrigan $298 749 $60 000 $12 000 san jose don w. kassing $328 209 provided $12 000 san luis obispo jeffrey d. armstrong $350 000 $60 000 $12 000 san marcos karen s. haynes $270 568 $60 000 $12 000 sonoma ruben arminaña $291 179 $60 000 $12 000 stanislaus hamid shirvani $270 000 $50 000 $12 000 </code></pre>,java
how to resign the .ipa file i already have an ipa file &amp; want to resign . when ever i do so the size of generated ipa do not match the actual size . can anyone help i have tried using iresign os x application &amp; also using terminal &amp; the generated ipa doesn t install on iphone .,iphone
python store lines from stdin directly to list objects in researching the answer to this question here on stackoverflow i ve learned a lot of new things but have so far been unable to close the deal. my python process will be receiving one line of input via stdin e.g. <pre><code>[{ name : ry age :28} { name : bo age :11} { name : ed age :99}] </code></pre> ...and i d like to be able to store this line directly to a list object that i can then iterate over e.g. <pre><code>for i in list: print i[ age ] i[ name ] </code></pre> ...but i just cannot get this to work whether i use <code>sys.stdin()</code> or the <code>fileinput</code> module. for example even when i explicitly create a list with <code>x = list(stdin.readline())</code> it ends up making each character a separate item in the list not parsing the text in the way i want it to. anyway.. back to searching. (thanks for reading.),python
java- formatted input how can i accept input from stdin in the format <strong>hh:mm:ssam</strong> <strong>here in place of am pm can also be there</strong> and display output in the form <strong>hh:mm:ss</strong>,java
given two square points (x y) find the other two to draw the square i m having difficulties to draw a square given two points only. for example if i have a (4 4) and b (5 0) i need to draw the square by pressing shift (the orientation of the square is given by the position of the mouse after sfhit has been click). i have the equation y = m*x + b of the line (4 4) -> (5 0) and i can know if the mouse is above or below the line in that specific moment. my diffculty is to find the other two vertices so that i can draw the lines and have a square. i know that this is more maths than programming or better is all about maths but i would apreciate if someone can help me. thanks,java
iphone uitableview shows one cached view in it s uitablecellview the last one added! i have an object that return a cached image view (uiimageview) which do the loading showing the loading image and then populate the view with the loaded image. in my case the tableview shows multiple rows where the same user photo might appears more than once and i noticed that because it is cached it shown in the last cell it is been added to. i ve tried to construct the uiimageview each time the table ask for a cell it works so the problem is with the cached image view! but i don t know why! hints,iphone
error ( expected on line 5 here is my program code. i am getting an error which says <blockquote> ( expected on line 5 [below public void work on d braces]. </blockquote> i don t understand what is to be corrected there. <pre><code>import java.util.*; class matrix { public void work { scanner scan= new scanner(; int n i j; char a b c; system.out.println( enter size: ); n=scan.nextint(); int m[][]= new int[n][n]; system.out.println( first character ); a= scan.nextchar(); system.out.println( second character ); b= scan.nextchar(); system.out.println( third character ); c= scan.nextchar(); if(n&lt;=10) { for(i=0; i&lt;n; i++) { for(j=0; j&lt;n; j++) { if((i==j)||(i+j==n-1)) { system.out.print(c); } else if(((i&gt;j)&amp;&amp;((j==0)||(j==1))) || ((i&lt;j)&amp;&amp;((j==n-2)||(j==n-1)))) { system.out.print(b); } else if(((i&lt;j)&amp;&amp;((i==0)||(i==1))) || ((i&gt;j)&amp;&amp;((i==n-2)||(i==n-1)))) { system.out.print(a); } } } } else system.out.println( size out of range ); } } </code></pre>,java
getmessage is not defined why does this: <pre><code>function conditionstarifairesform_required () { this.a0 = new array( datedebutdevaliditeduplandaffaires getmessage( errors.required date de début ) new function ( varname this.datepattern= yyyy/mm/dd ; return this[varname]; )); this.a1 = new array( datefindevaliditeduplandaffaires getmessage( errors.required date&amp;nbsp;de&amp;nbsp;fin ) new function ( varname this.datepattern= yyyy/mm/dd ; return this[varname]; )); this.a2 = new array( tarifenvigueur getmessage( errors.required tarif en vigueur ) new function ( varname return this[varname]; )); this.a3 = new array( datedebuttarif getmessage( errors.required date de début ) new function ( varname this.datepattern= yyyy/mm/dd ; return this[varname]; )); if(document.getelementsbyname( delaidepaiementfacture )[0].disabled == false) { this.a4 = new array( delaidepaiementfacture getmessage( errors.required délai&amp;nbsp;de&amp;nbsp;paiement ) new function ( varname return this[varname]; )); }else { if(document.getelementsbyname( delaidepaiement.value )[0].selectedindex == 7 || document.getelementsbyname( delaidepaiement.value )[0].selectedindex == 0) { this.a4 = new array( delaidepaiement getmessage( errors.required délai&amp;nbsp;de&amp;nbsp;paiement ) new function ( varname return this[varname]; )); } } } </code></pre> produce this error message: <blockquote> uncaught referenceerror: getmessage is not defined </blockquote>,javascript
iphone add support for backgrounder i m trying to create a app for my personal use that uses backgrounder. are there any prerequisite that the app can be used by backgrounder as it refuses to put my app in background. i have seen the wiki and google code page of backgrounder and it states if you wish to run a non-appstore 3rd-party application in the background it is suggested that you contact the author of the application and request that proper background support be added. but there is no additional info about it... and mailing list is ... where joining the group is also a mystery. what constitutes a proper background support,iphone
"javascript click event listener not firing i am trying to make a calculator and i need to assign the click event to the inputs. however i am new to javascript and i am not able to figure out why it is not working. <div class= snippet data-lang= js data-hide= false data-console= true data-babel= false >
<div class= snippet-code >
<pre class= snippet-code-js lang-js prettyprint-override ><code>onload = function assign() {
var c = document.queryselectorall( .click );
for (i = 0; i &lt; c.length; i++) {
c[i].addeventlistener( click );
alert( bob );
<pre class= snippet-code-html lang-html prettyprint-override ><code>&lt;div style= max-width: 960px; margin: 0px auto; background-color: green; &gt;
&lt;section id= cal-container &gt;
&lt;form name= calculator &gt;
&lt;input type= text name= answer &gt;
&lt;input class= click id= 1 type= button value= 1 &gt;
&lt;input class= click id= 2 type= button value= 2 &gt;
&lt;input class= click id= 3 type= button value= 3 &gt;
&lt;input class= click id= + type= button value= + &gt;
&lt;input class= click id= 4 type= button value= 4 &gt;
&lt;input class= click id= 5 type= button value= 5 &gt;
&lt;input class= click id= 6 type= button value= 6 &gt;
&lt;input class= click id= - type= button value= - &gt;
&lt;input class= click id= 7 type= button value= 7 &gt;
&lt;input class= click id= 8 type= button value= 8 &gt;
&lt;input class= click id= 9 type= button value= 9 &gt;
&lt;input class= click id= * type= button value= * &gt;
&lt;input class= click id= v type= button value= c &gt;
&lt;input class= click id= 0 type= button value= 0 &gt;
&lt;input class= click id= = type= button value= = &gt;
&lt;input class= click id= / type= button value= / &gt;
unable to execute for loop i m new to java and just wrote a program for learning purpose. i have two arrays of strings and i want to compare the length of both string arrays.if lengths are equal then compare the values of each first string array with the values of each second array .if value got matched then print that value. not able to rectify where the problem is <pre><code> package com.equal.arrat; import java.util.arraylist; import java.util.list; public class arrayequal { public static void main(string[] args) { string s[] = { anuj kr chaurasia }; string s1[] = { anuj kr chaurasia }; if (s.length==s1.length) { system.out.println(s.length); for (int i =0 ; i&gt;=s.length;i++) { for (int j =0 ;j&gt;=s1.length;j++) { system.out.println( test ); if (s[i].equals(s1[j])) { system.out.println( ok + s[i]); } else{ system.out.println( not ok ); } } } } else{ system.out.println( length not equal ); } } } </code></pre>,java
default.png shows but not for long lots of default.png q s but i didn t read one like this: i see default.png but then the screen goes blank but no error messages no abort. what am i missing sdk 4.3 iphone only no nib no schemes no orientation other than portrait up/down. nav controller 4 tabs. app abc works fine. clone xyz doesn’t. info.plist seems identical including the half dozen icon files; neither app has an entry that contains “mainwindow.” analyze and both generate “build succeeded.” run and both display “attaching to process blah-blah-blah.” any combo of reboot and/or restart mac/xcode/simulator/device doesn’t do a dang thing. there is one difference though: the drop-down for abc shows the full device name two 4.2’s and two 4.3’s; xyz shows only “ios device” and the two 4.3’s. abc shows all the nslogs. xyz shows none of them. and in both cases the first nslog is right after <pre><code>- (bool)application:(uiapplication *)application didfinishlaunchingwithoptions:(nsdictionary *)launchoptions { </code></pre> clean all targets made no difference. i’m thinking “clone not.” <hr> xjones here s the code you requested. i ve whacked it down as much as i could. <pre><code>-(bool)application:(uiapplication *)application didfinishlaunchingwithoptions:(nsdictionary *)launchoptions { nslog(@ app delegate cgrect ); cgrect framemain = [uiscreen mainscreen].applicationframe; glbl_height = framemain.size.height; glbl_width = framemain.size.width; nslog(@ app delegate background ); uicolor *bluegreenbackground = [[uicolor alloc] initwithpatternimage:[uiimage imagenamed:@ default.png ]]; self.window.backgroundcolor = bluegreenbackground; [bluegreenbackground release]; nslog(@ app delegate 3 ); method01_vc *method01vc = [[[method01_vc alloc] init] autorelease]; // more controllers method01vc.title = nslocalizedstring(@ title 1 method 1 @ (title 1) ); // more titles uinavigationcontroller *method01nav = [[[uinavigationcontroller alloc] initwithrootviewcontroller:method01vc] autorelease]; // more controllers nslog(@ app delegate prior to tabbar init ); _tabbarcontroller = [[uitabbarcontroller alloc] init]; nsarray *sections = [nsarray arraywithobjects:method01nav method02nav method03nav method04nav nil]; [_tabbarcontroller setviewcontrollers:sections]; cgrect frame = cgrectmake(0.0 0.0 320 48); // 48 uiview *tabbarview = [[uiview alloc] initwithframe:frame]; [tabbarview setbackgroundcolor:[uicolor colorwithred:0.07 green:0.14 blue:0.04 alpha:0.8]]; nsarray *tabs = _tabbarcontroller.viewcontrollers; uiviewcontroller *tab1 = [tabs objectatindex:0]; tab1.tabbaritem.image = [uiimage imagenamed:@ tabicon01.png ]; tab1.tabbaritem.title = @ ; uiviewcontroller *tab2 = [tabs objectatindex:1]; tab2.tabbaritem.image = [uiimage imagenamed:@ tabicon02.png ]; tab2.tabbaritem.title = @ ; nslog(@ app delegate prior to tabbar insert ); [[_tabbarcontroller tabbar] insertsubview:tabbarview atindex:0]; tabbarview.autoresizessubviews = yes; [tabbarview release]; _tabbarcontroller.delegate = self; [self.window addsubview:_tabbarcontroller.view]; // self.tabbarcontroller.selectedindex = 1; ---- makes no difference // self.window.rootviewcontroller = self.tabbarcontroller; --- ditto nslog(@ app delegate prior to makekeyandvisible ); [self.window makekeyandvisible]; nslog(@ app delegate about to return yes ); return yes; // implement loadview to create a view hierarchy programmatically without using a nib. - (void)loadview { nslog(@ method01 cgrect ); cgrect framemain = [uiscreen mainscreen].applicationframe; uiview *view = [[uiview alloc] initwithframe:framemain]; self.view = view; self.view.autoresizingmask = uiviewautoresizingflexiblewidth | uiviewautoresizingflexibleheight; self.view.autoresizessubviews = yes; </code></pre> after the above all the usual labels and text fields follow. thanks again for taking the time to slog through it. i ve got my hopes set on a duh!,iphone
string s split returning unexpected value <pre><code>system.out.println(arrays.tostring( 1.1.1 .split( . ))); </code></pre> this prints out an empty array. what gives to me it should print out [1 1 1] . instead it prints out [] . it doesn t make sense to me.,java
example code from javascript textbook giving unexpected error preface - not relevant to problem first off i am a noob to javascript and am in the process of learning it. i have read a lot of eloquent javascript but towards the end found it to be too advanced for my level. i was recommended to start reading professional javascript for web developers by nicholas zakas. problem now i m attempting to just try and run objecttypeexample04.htm which i ve included here: <pre><code>function displayinfo(args) { var output = “”; if (typeof == “string”){ output += “name: “ + + “\n”; } if (typeof args.age == “number”) { output += “age: “ + args.age + “\n”; } alert(output); } displayinfo({ name: “nicholas” age: 29 }); displayinfo({ name: “greg” }); </code></pre> from what i can understand it ll just print the object defined in the call to displayinfo and it ll do this through appending the output variable inside that function. i don t get why i m getting this error <blockquote> exception: syntaxerror: illegal character </blockquote> when running it in a javascript code runner (don t know the technical name). but basically i tried using jsfiddle to no luck and i don t understand what s wrong because i copied and pasted it out of a textbook.,javascript
simple java program can not be run i am trying to compile and run helloworld on linux machin with java version 1.6. i get it compiled but can not run it. i know that the program is at least correct. can anybody tell me how to get the silly program run i know even this problem had been metioned several times but nowhere found the fix of that problem. compile command i used: <code>javac</code>. run command i used: <code>java exampleprogram</code> <pre><code>//a very simple example class exampleprogram { public static void main(string[] args){ system.out.println( i m a simple program ); } } </code></pre> the error: <pre><code>java -classpath . exampleprogram exception in thread main java.lang.unsupportedclassversionerror: exampleprogram : unsupported major.minor version 51.0 at java.lang.classloader.defineclass1(native method) at java.lang.classloader.defineclasscond( at java.lang.classloader.defineclass( at at at$000( at$ at method) at at java.lang.classloader.loadclass( at sun.misc.launcher$appclassloader.loadclass( at java.lang.classloader.loadclass( could not find the main class: exampleprogram. program will exit. </code></pre>,java
retrieve data from toc i aim to convert the toc of <a href= rel= nofollow noreferrer >the python language reference — python 3.6.3 documentation</a> to a structured data with the following steps: 1.copy contents to a <code></code> file <pre><code>in [1]: with open( ) as file: ...: content = in [2]: content out[2]: \n\n- \\1. introduction\n - [1.1. alternate implementations] (\n - [1.2. notation](\n- \\2. lexical analysis\n - [2.1. line structure] (\n - [2.2. other tokens](\n </code></pre> 2.get chapters <pre><code>in [47]: chapters = content.split( \n- \\ ) ...: #subtract the unqualified part ...: chapters = chapters[1:] in [50]: chapters[0] out[50]: 1. introduction\n - [1.1. alternate implementations]( \n - [1.2. notation]( </code></pre> 3.separate chapter name and section name in each chapters <pre><code>chapter_details = chapters[0].split( \n - ) sections = chapter_details[1:] chapter = chapter_details[0] in [54]: chapter out[54]: 1. introduction in [55]: sections out[55]: [ [1.1. alternate implementations]( [1.2. notation]( ] </code></pre> 4.convert section <pre><code>def convert_section(s): start = s.index( [ ) + 1 end = s.index( ] ) return s[start:end] in [57]: print(convert_section( [1.1. alternate implementations]( ...: ntroduction.html#alternate-implementations) )) 1.1. alternate implementations sections = map(convert_section sections) sections = list(sections) </code></pre> 5.create a dict <pre><code>key = chapter {key:sections} { 1. introduction :[ 1.1. alternate implementations 1.2. notation ]} </code></pre> 6.encapsulate codes in a class and get the result <pre><code>class toc: def __init__(self filename): self.filename = filename def read(self filename): with open (filename) as file: content = return content def convert_section(self s): start = s.index( [ ) + 1 end = s.index( ] ) return s[start:end] def get_chapters(self filename): content = chapters = content.split( \n- \\ ) #subtract the unqualified part chapters = chapters[1:] return chapters def create_chapter_dict(self chapter): chapter_details = chapter.split( \n - ) sections = chapter_details[1:] key = chapter_details[0] value = map(self.convert_section sections) return {key: list(value)} def get_chapters_dict(self): chapters = self.get_chapters(self.filename) chapters_dict = {} for chapter in chapters: chapter_dict = self.create_chapter_dict(chapter) chapters_dict.update(chapter_dict) return chapters_dict </code></pre> run and get the result <pre><code>in [89]: toc( ).get_chapters_dict() out[89]: { 1. introduction : [ 1.1. alternate implementations 1.2. notation ] 2. lexical analysis : [ 2.1. line structure 2.2. other tokens 2.3. identifiers and keywords 2.4. literals 2.5. operators 2.6. delimiters ] 3. data model : [ 3.1. objects values and types 3.2. the standard type hierarchy 3.3. special method names 3.4. coroutines ] </code></pre> this solution is a bit too much for a daily common operation is there a standard or easy method for such a task,python
how can i compare if old date time is less than 20 minutes off current dates i have got two dates. <code>olddate</code> and current date as shown below <pre><code>package com; import java.text.dateformat; import java.text.parseexception; import java.text.simpledateformat; import java.util.calendar; import; public class test { public static void main(string args[]) throws parseexception { // for old date string olddate = 2014-10-01 17:26:12 ; dateformat formatter = null; date converteddate = null; formatter = new simpledateformat( yyyy-mm-dd hh:mm:ss ); converteddate = (date) formatter.parse(olddate); //system.out.println(converteddate.getminutes()); // for new date calendar currentdate1 = calendar.getinstance(); simpledateformat formatter1 = new simpledateformat( yyyy-mm-ddhh:mm:ss ); string currentdate = formatter1.format(currentdate1.gettime()); system.out.println( newdate + currentdate); } } </code></pre>,java
uinavigationcontroller back button custom text the back button by default shows the title of the last view in the stack is there a way to have custom text in the back button instead,iphone
"in this code i want to add values by clicking the value buttons i want to add values by clicking the value buttons by each and every by the following function <div class= snippet data-lang= js data-hide= false data-console= true data-babel= false >
<div class= snippet-code >
<pre class= snippet-code-js lang-js prettyprint-override ><code>function sum() {
var txtfirstnumbervalue = document.getelementbyid( txt1 ).value;
var txtsecondnumbervalue = document.getelementbyid( txt2 ).value;
var txtthirdnumbervalue = document.getelementbyid( txt3 ).value;
var txtfourthnumbervalue = document.getelementbyid( txt4 ).value;
var result = parseint(txtfirstnumbervalue) + parseint(txtsecondnumbervalue);
var result = parseint(txtfirstnumbervalue) + parseint(txtthirdnumbervalue);
var result = parseint(txtfirstnumbervalue) + parseint(txtfourthnumbervalue);
if (!isnan(result)) {
document.getelementbyid( txt1 ).value = result;
// here i gave the other two events to add to the text field by the id names</code></pre>
<pre class= snippet-code-html lang-html prettyprint-override ><code>&lt;!-- here i gave the three value buttons and on click function --&gt;
&lt;input type= text id= txt1 value= 10 /&gt;
&lt;input type= button id= txt2 value= 10 onclick= sum(); /&gt;
&lt;input type= button id= txt3 value= 20 onclick= sum(); /&gt;
&lt;input type= button id= txt4 value= 30 onclick= sum(); /&gt;</code></pre>
finding text child of an element using javascript i would like to find the text snippet this is for testing selector from the following dom structure using plain javascript. <pre><code>&lt;html&gt; &lt;body&gt; &lt;div class= breadcrumb &gt; &lt;a title= home href= &gt; home&lt;/a&gt; &lt;span class= arrow &gt;»&lt;/span&gt; &lt;a title= abc href= &gt;test1&lt;/a&gt; &lt;span class= arrow &gt;»&lt;/span&gt;&lt;a title= xyz href= &gt;test2&lt;/a&gt; &lt;span class= arrow &gt;»&lt;/span&gt; this is for testing selector &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>,javascript
calculating the number of seconds since 1601 howto calculate the seconds since january 1 1601,python
no audio after phone call ends how to resume audio after the phone call ends. here is my code but it is not working don t know why <pre><code>@interface mainviewcontroller : uiviewcontroller &lt;infodelegate avaudioplayerdelegate&gt; </code></pre> in m file <pre><code>-(void)audioplayerbegininterruption:(avaudioplayer *)audioplayer; { } -(void)audioplayerendinterruption:(avaudioplayer *)audioplayer; { [self.audioplayer play]; } </code></pre> any ideas what is it i m doing wrong or missing from code. please help.,iphone
send sms by pre schedule sms in sqlite table i am working on sms pre schedule app in iphone where i am using sqlite table to store date time phone no message. i want to send sms by the time that it saved in sqlite table using pre schedule time. please help me out by suggest me code to send sms using nstimer. and also upadte timer to the next nearest time in sqlite table automatically.,iphone
how to determine the current iphone os version at runtime and compare version strings how can you determine and compare (> &lt; etc.) the current os version of the iphone that the app is running on there is a certain bug in 3.0 but not in 3.1+ so i d like to be able to skip out a bit of code if the current os version is not >= 3.1. this needs to be at runtime not compile time!,iphone
how to parse a string in string into multiple variables for each word how do you parse a string of a <strong>sentence</strong> into multiple <strong>variables</strong>. for example the string could say the red car but how would you <strong>parse</strong> each word of the string into separate variables,java
how does listiterator work <pre><code>linkedlist&lt;string&gt; names=new linkedlist&lt;&gt;(); listiterator&lt;string&gt; iterator=names.listiterator(); </code></pre> then we can perform operations using <code>iterator.hasnext()</code> <code></code> etc. if <code>listiterator</code> is an interface how could we access methods on its reference variable iterator as interface should have only abstract methods does <code>names.listiterator()</code> returns object reference of some class if so which class object reference it returns can someone clarify this,java
is it possible to kick off an app from another iphone app i d like to start up the app store from within my iphone app. is this possible - and how thanks.,iphone
for in in lists i m trying to do something like that in a nutshell... <pre><code>house = [ yes no maybe ] x = range(3) for x in house print[x] </code></pre> <hr> i want to loop over a list but i got type error: list indices must be integers not tags. how can i achieve this,python
indexerror while extracting data from files i have a hundred files each with three columns. in a python script i extract the three columns for each file : <pre><code>for i in range(1 100) # extract data os.chdir( directory/to/files ) filename = file +str(i).dat f = open(filename) c1 = [l.split()[0] for l in f] f.close() f = open(filename) c2 = [l.split()[1] for l in f] f.close() f = open(filename) c3 = [l.split()[2] for l in f] f.close() doanalysis() </code></pre> surprisingly i have an <code>indexerror</code> at iteration 15 pointing at line 12 of the above code saying : <code>list index out of range</code>. i thought python is thinking that my file15.dat has less then 3 columns so i added this just before line 12 : <pre><code>if i==15: c3if = [] for l in f: print(len(l.split()) c3if.append(l.split()[2]) </code></pre> the <code>c3if</code> list seems to contain the third column of file15.dat entirely and l.split is always of length 3. i don t understand why the comprehension list c3 fails at a specific iteration while the two other comprehension lists do not.,python
filenotfounderror: [winerror 2] the system cannot find the file specified -mongo import i want to import a large amounts of data using mongoimport (anaconda -windows platform).i built a mongoimport command and i used to execute. here is my code <pre><code> # build mongoimport command collection = cal_data[:cal_data.find( . )] #print collection working_directory = /users/ json_file = cal_data + .json #print json_file mongoimport_cmd = mongoimport --db + db_name + \ --collection + collection + \ --file + working_directory + json_file #print mongoimport_cmd # before importing drop collection if it exists if collection in db.collection_names(): print ( dropping collection ) db[collection].drop() # execute the command print ( executing: + mongoimport_cmd) </code></pre> <hr> here is the error i get <h2>executing: mongoimport --db osm --collection chattanooga --file /users/chattanooga.osm.json</h2> filenotfounderror traceback (most recent call last) in () 16 # execute the command 17 print ( executing: + mongoimport_cmd) ---> 18 c:\users\mmedouani\appdata\local\continuum\anaconda3\lib\ in call(timeout *popenargs **kwargs) 558 retcode = call([ ls -l ]) 559 --> 560 with popen(*popenargs **kwargs) as p: 561 try: 562 return p.wait(timeout=timeout) c:\users\mmedouani\appdata\local\continuum\anaconda3\lib\ in <strong>init</strong>(self args bufsize executable stdin stdout stderr preexec_fn close_fds shell cwd env universal_newlines startupinfo creationflags restore_signals start_new_session pass_fds) 948 c2pread c2pwrite 949 errread errwrite --> 950 restore_signals start_new_session) 951 except: 952 # cleanup if the child failed starting. c:\users\mmedouani\appdata\local\continuum\anaconda3\lib\ in _execute_child(self args executable preexec_fn close_fds pass_fds cwd env startupinfo creationflags shell p2cread p2cwrite c2pread c2pwrite errread errwrite unused_restore_signals unused_start_new_session) 1218 env 1219 cwd -> 1220 startupinfo) 1221 finally: 1222 # child is launched. close the parent s copy of those pipe filenotfounderror: [winerror 2] the system cannot find the file specified,python
what is the meaning of broken pipe exception what is the meaning of broken pipe exception and when it will come,java
guessing game python binary search i can t figure out what s wrong with my code here. i am trying to have the user think of a number between 1 and 100 and then this program will be able to guess it. the program adds the high and low numbers of the range and divides by two and uses that as the guess. the user enters a 1 if the number the program guess is higher than their number -1 if it is lower and 0 if the guess is correct. after at most 7 guesses the number guessed should be right. when i run my code it constantly prints out the guess as 50 and never changes. it seems to never be running through the if statements. it should be running through the program and finding a new guess. <pre><code>def main(): import random print( guessing game ) print( ) print( think of a number 1 and 100 inclusive.\nand i will guess what it is in 7 tries or less. ) print( ) ready = input( are you ready (y/n): ) print( ) if ready != y and ready != n : ready = input( are you ready (y/n): ) if ready == n : print( bye ) if ready == y : lo = 0 hi = 100 guess_high = 1 guess_same = 0 guess_low = -1 a = random.randint(1 100) num_list = [] for i in range(1 100): num_list.append(i) while (lo &lt;= hi): guess_count = 0 for guess_count in range(1 8): guess_count += 1 guess = (lo + hi) // 2 print( guess guess_count : the number you thought was guess) user_response = input( enter 1 if my guess was high -1 if low and 0 if correct: ) if (user_response == 1): hi = guess - 1 guess_count += 1 guess = (lo + hi) // 2 elif (user_response == -1): lo = guess + 1 guess_count += 1 guess = (lo + hi) // 2 elif (user_response == 0): print( thank you for playing the guessing game. ) main() </code></pre>,python cannot run program java : error=2 no such file or directory <pre><code>package; import; import; public class helloworld { public static void main(string args[]){ for(int i = 0; i&lt;5 ; i++){ system.out.println( helloo ); } process process = null; processbuilder pb = new processbuilder(new string[]{ java + + }); try { process = pb.start(); } catch (ioexception e) { e.printstacktrace(); } try { process.waitfor(); } catch (interruptedexception e) { e.printstacktrace(); } int exitval = process.exitvalue(); system.out.println(exitval); } } </code></pre> and <pre><code>package; public class helloworld2 { public static void main(string[] args){ system.out.println( main 2..testing ); } } </code></pre> <blockquote> cannot run program java : error=2 no such file or directory at java.lang.processbuilder.start( at caused by: error=2 no such file or directory at java.lang.unixprocess.forkandexec(native method) at java.lang.unixprocess.( at java.lang.processimpl.start( at java.lang.processbuilder.start( ... 1 more exception in thread main java.lang.nullpointerexception at </blockquote>,java
cloc how to sum the results iam developing a program to analyze the source code of programs. now i m having a trouble counting results here comes my source code: <pre><code>public void walk(string path) throws filenotfoundexception { file root = new file(path); file[] list = root.listfiles(); int countfiles = 0; if (list == null) { return; } for (file f : list) { if (f.isdirectory()) { walk(f.getabsolutepath()); } if (f.getname().endswith( .java )) { system.out.println( file: + f.getname()); countfiles++; scanner sc = new scanner(f); int count = 0; while (sc.hasnextline()) { count++; sc.nextline(); } scanner sc2 = new scanner(f); int lower = 0; int upper = 0; int digit = 0; int whitespace = 0; while (sc2.hasnextline()) { string str = sc2.nextline(); for (int i = 0; i &lt; str.length(); i++) { if (character.islowercase(str.charat(i))) { lower++; } else if (character.isuppercase(str.charat(i))) { upper++; } else if (character.isdigit(str.charat(i))) { digit++; } else if (character.iswhitespace(str.charat(i))) { whitespace++; } } } system.out.println( your code contains: + count + lines! out of them: ); system.out.println( lower case: + lower); system.out.println( upper case: + upper); system.out.println( digits: + digit); system.out.println( white spaces: + whitespace); } system.out.println( you have in total: + countfiles); } } </code></pre> first question: when it comes to countfiles ( which is supposed to tell how many .java files or classes you have in your code) its counting and printing results like the following: you have in total= 1 file you have in total= 2 file so how can i make it to print me the final result directly which is 2 in this case second question: how can i print the sum of the lines in the code in totally instead of showing them for each class by it self thanks,java
changing language of tab bar elements we re developing an iphone application to be distributed in spain. it contains a tab bar but we re not quite sure how to change more and edit into spanish. i m sure there s a simple solution... anybody know a way to do it ==== edit 1 ==== this is how we add the tabbar. as you see we create a tabbaritem for each button but the more button comes automatically when there are more than 5 (as should be expected). <pre><code>for (int i = 0; i &lt; [buttonnames count]; i++) { switch (i) { case 1: viewcontroller = [[fotos alloc] init]; break; case 2: viewcontroller =[[videos alloc] init]; break; case 3: viewcontroller =[[deportes alloc] init]; break; default: viewcontroller = [[myappviewcontroller alloc] initwithcategory:i strcategory:[tempnames objectatindex:i]]; break; } uinavigationcontroller *nav = [[uinavigationcontroller alloc] initwithrootviewcontroller:viewcontroller]; uitabbaritem *tabbaritem = [[uitabbaritem alloc] initwithtitle:[buttonnames objectatindex:i] image:[uiimage imagenamed:[imgnames objectatindex:i]] tag:i]; nav.tabbaritem = tabbaritem; [controllers addobject:nav]; [viewcontroller release]; [nav release]; [tabbaritem release]; } // create the toolbar and add the view controllers tabbarcontroller = [[uitabbarcontroller alloc] init]; [tabbarcontroller setviewcontrollers:controllers animated:yes]; tabbarcontroller.customizableviewcontrollers = controllers; tabbarcontroller.delegate = self; // set up the window [window addsubview:tabbarcontroller.view]; [window makekeyandvisible]; </code></pre> ==== solved ==== all i needed was a es.lproj directory in my project. i create a new file in xcode (file > new file... > mac os x / other > strings file) i name it localizable.strings and save it in es.lproj. any strings that need to be localized need to be defined in this file but all other strings generated by the os (the more edit and done buttons in the tabbar video controls etc.) will be automatically translated.,iphone
how to open yahoo messenger link from iphone app how can i open the following yahoo messenger link from an iphone app ymsgr:sendim testlink thanks,iphone
writing to module-wide variable lets say i have these 3 (tiny) python files - <strong></strong> <pre><code>myvar = a </code></pre> <strong></strong> <pre><code>import a import c myvar = b </code></pre> <strong></strong> <pre><code>from a import myvar def pr(): print myvar </code></pre> now if i execute <code></code> i get output <pre><code>a </code></pre> but i really want output to be as <pre><code>b </code></pre> so please tell me how can i restructure/modify the programs so that the <em>module-wide</em> <code>myvar</code> can be assigned a different value.,python
python trouble shooting machine needs fixing the following code is designed to be an automated troubleshooter in python. <pre><code># welcoming the user to the program print( hello this is a automated mobile phone troubleshooter ) print( the code will ask you a few questions try to answer them to the best of your ability ) # explaining what the code will do # a list storing all the questions the code will ask the user questions = [ is there a problem with your hardware or is do you need technical assistance. please type technical assistance or hardware have you dropped your phone recently please type yes or no is your phone able to charge please type yes or no is your phone a iphone please type yes or no does your phone keep freezing please type yes or no can your phone connect to wifi please type either yes or no have you gotten your phone wet is the phone s screen cracked or broken is there a problem with the camera is the problem with phone fixed ] # a list containing all the solutions that will be given to the user solutions = [ this troubleshooter is only for hardware problems please call 01474 709853 for technical assistance please try turning it off and on again try changing the cable you charge the phone with please hold the lock button and home button for 5 seconds this causes a force restart try deleting some data to make your phone run faster e.g. delete applications try restarting your router put your phone in a bowl of rice overnight take the phone to the manufacturer s store uninstall any third party apps or applications that you have downloaded since the camera has not been working please take the phone to your local phone manufacturers store and ask them for help ] answers = [ technical assistance yes no yes yes no yes yes yes no ] validation = [ hardware no yes no no yes no no no yes ] answer = a # creating a loop and making the variable loop go from 0 to 9 for loop in range(0 10): while answer != answers[loop] and answer != validation[loop]: answer = input(questions[loop]) # turning the user s answer and turning it to lowercase making sure the if statement gets the right answer answer = answer.lower() if answer == answers[loop]: # prints the solution the problem print(solutions[loop]) else goto print( thank you for using the automated troubleshooting program goodbye ) </code></pre> i can t get this code to run properly as it can take a max input of two questions before it ends is there any way someone can help,python
how to modify xslt stylesheet using java i want to modify some element values like font size color in xslt through java. i tried with following java code <pre><code>file xslfile = new file( d:/header.xsl ); system.out.println(xslfile.getpath()); javax.xml.transform.source xsltsource = new; javax.xml.transform.transformerfactory transformerfactory = javax.xml.transform.transformerfactory.newinstance(); javax.xml.transform.transformer xslttransformer = transformerfactory.newtransformer(xsltsource); xslttransformer.setparameter( clr red ); </code></pre> the java code building successfully but the value is not reflecting into xsl stylesheet.,java
new to python programming could somebody please explain the fault with this program i am very new to python programming i am writing a simple fighting game at the moment (text based) that is extremely simple as i m just learning the basics at the moment. i have placed the code for my game below (it is not finished) my problem is that every time i run the program when you enter which character you d like to play as this error occurs. <pre><code>traceback (most recent call last): file c:\python26\ line 60 in &lt;module&gt; first_player.attack(second_player) typeerror: int object is not callable </code></pre> here is the code for my game (don t worry it s not very big!). <pre><code>import time import random class player(object): def __init__(self name): self.account = name = random.randint(50 100) self.attack = random.randint(30 40) self.alive = true def __str__(self): if self.alive: return %s (%i health %i attack) % (self.account self.attack) else: return self.account is dead! def attack(self enemy): print self.account attacks enemy.account with %s attack! % self.attack -= self.attack if &lt;= 0: enemy.die() def die(self): print self.account dies! alive_players = 2 name1 = raw_input( enter a name: ) name2 = raw_input( enter another name: ) player_list = { a :player(name1) b :player(name2)} while alive_players == 2: print for player_name in sorted(player_list.keys()): print player_name player_list[player_name] print player1 = raw_input( who would you like to play as (a/b): ).lower() try: first_player=player_list[player1] except keyerror wrong_name: print wrong_name does not exist! continue if first_player==player(name1): second_player=player(name2) else: second_player=player(name1) time.sleep(1) print print * * 30 first_player.attack(second_player) second_player.attack(first_player) </code></pre> i know there are workarounds like appending the characters to the list after the player picks the names although i would like to have a further understanding of classes and want to know why this does not work! if possible could somebody please explain the fault and how i can fix it i have been looking at this for three days i could do it differently and make it work but i would like to understand why this doesn t work first! thanks in advance! -charlie,python
building pyspotify in 32bit python osx mavericks i m trying to build <code>pyspotify</code> but after installation and <code>&gt;&gt;import spotify</code> i get: <pre><code>import _cffi_backend as backend importerror: dlopen(/usr/local/lib/python2.7/site-packages/ 2): no suitable image found. did find: /usr/local/lib/python2.7/site-packages/ mach-o but wrong architecture </code></pre> my <code>uname -p</code> gets <code>i386</code> and i guess <code>pyspotify</code> it is not prebuilt for this architecture. documentations says: in that case you’ll need a c compiler python development headers and libffi development headers to build pyspotify how do i do that,python
calling [super scrollviewdidscroll]; on subclass of uiwebview crashes i m not sure how this works. i was following this post: <a href= >check if uiwebview scrolls to the bottom</a> i want to know when the scrollviewscrolls to do some custom things. i subclasses uiwebview. all i did was this so far: <pre><code>- (void)scrollviewdidscroll:(uiscrollview *)scrollview { [super scrollviewdidscroll:scrollview]; nslog(@ %s __function__); } </code></pre> it crashes on the <code>[super scrollviewdidscroll:scrollview]</code> method. when i delete that line it works fine. i don t want to take away the superclass implementation of this method. i just wanted to add some custom functionality to it (place a toolbar above the webview like the facebook app). is there a reason why this is crashing thanks.,iphone
wizard style navigation dismissing a view and showing another one i m making a set of screens similar to a wizard and i d like to know how to make a view dismiss itself and its parent view and immediately show a donescreen without worrying about resource leaks. my views look like the following: <pre><code>base -&gt; level1 -&gt; donescreen -&gt; level2 -&gt; donescreen </code></pre> the level1 controller is a navigation controller created with a view.xib and shown with <pre><code>[self presentmodalviewcontroller ...] </code></pre> by the base controller. the level1 controller is also responsible for creating the donescreen which may be shown instead of the level2 screen based on a certain criteria. when the user taps a button on the screen the level1 controller instantiates the the level2 controller and it displays it via <pre><code>[self.navigationcontroller pushviewcontroller ..] </code></pre> and level2 controller s view has a next button. when the use hits the next button in the level2 screen i need to dismiss the current level2 s view as well as the level1 s view and display the donescreen which would have been created and passed in to the level2 controller from level1. (partly to reduce code duplication and partly to separate responsibilities among the controllers) in the level2 controller if i show the donescreen first and dismiss itself with <pre><code>[self.navigationcontroller popviewcontrolleranimated:yes]; </code></pre> then the level1 controller s modal view is still present above the base but under the done screen. what s a good way to clear out all of these views except the base and then show the donescreen any good suggestions on how to get this done in a simple but elegant manner,iphone
python simple network scanner for open port i am trying to create a simple port scanner in python without the use of nmap. the below code is what have so far: <pre><code> import socket sys optparse netaddr #input parser = optparse.optionparser( usage: --ip &lt;network you want to scan including mask in cidr format&gt; -p &lt;target port&gt; ) parser.add_option( --ip dest= ip type= string help= specify network to scan including /mask e.g ) parser.add_option( -p dest= port type= int help= specify target port ) (options args) = parser.parse_args() port = str(options.port) ip = str(options.ip) if (ip == none) | (port == none): print parser.usage print you must specify a target network including subnet mask and port. exit(0) #create a socket try: s = socket.socket(socket.af_inet socket.sock_stream) except socket.error err_msg: print socket creation failed. error code: + str(err_msg[0]) + error mesage: + err_msg[1] sys.exit() #port scan targetlist = netaddr.ipnetwork(ip) targetlist = list(targetlist) for x in range (int(len(targetlist))): target_ip = targetlist[x] try: s = socket.socket(socket.af_inet socket.sock_stream) s.settimeout(2) result = s.connect(str(target_ip) int(port)) if not result : print str(target_ip) + port + str(port) + open! s.close() except: print str(target_ip)+ port + str(port) + closed! s.close() print scanning finished </code></pre> it does not seem to work as i am getting a port closed for every single ip or network i try to scan even though i am sure the particular port is open.. most probably my mistake is in the way port scanning is defined but i cannot seem to put my finger on it. i am at a beginner level so any suggestions are welcome! thanks in advance!,python
printwriter.write( string ) never throws an ioexception so what s the right way to know if an error has occured when writing through a printwriter,java
iphone view strategy i am developing an app but have yet to get the optimal navigation flow working. to give you an idea of the structure of my app i have a main view that allows the user to start a new game or view high scores. at the end of a game i would like to give the user the choice of viewing high scores or going back to the main menu - i have a game over view for this. the hierarchy looks something like this: <pre><code>main view | +--game view | | | +--game over view | | | +--high scores view | +--high scores view </code></pre> i am using the presentmodalviewcontroller method to switch from the game view to the game over view. this is fine but when i want to go back to the main view i have two layers of views to navigate through (i want to close the game over view and the game view to return straight to the main view). to close views i am using dismissmodalviewcontrolleranimated but this is not ideal for traversing more than one view. is there a way of replacing the current model view rather than opening a new one on top i hope this makes sense. please let me know if you need anymore details. thanks in advance for any help. alan,iphone
java - empty int array i need to pass an empty int array. <code>new int[]{}</code> -> this works. but is there anyway with the below approach <code>collections.emptylist().toarray()</code> -> i am unable to cast this to int[] array. the method signature <pre><code>public void checkversions(final int[] versions) </code></pre> this is the method to be called. there are case where i need to pass some empty int[]. thanks,java
"uncaught syntax error : unexpected token im making a pong clone with js and i am using windows.onload fucnction and it says that there is a period that isn t supposed to be there idk where they could be talking about and it says its on the windows.onload function line <div class= snippet data-lang= js data-hide= false data-console= true data-babel= false >
<div class= snippet-code >
<pre class= snippet-code-html lang-html prettyprint-override ><code>&lt;canvas id= pg width = 800 height = 600 &gt;
var c;
var cc;
var ballx = 50;
var bally = 50;
window.onload = function(){
c = document.getelementbyid( pg );
cc = c.getcontext( 2d );
var fps = 180;
setinterval(draw 1000/fps)
function draw(){
ballx += 1.5;
cc.fillstyle = black ;
cc.fillrect(0 0 c.width c.height);
cc.fillstyle = white ;
cc.fillrect(ballx bally 10 10);
cc.fillrect(10 210 100 25);
python input validation while loop i need my program to validate the user input. so far i have defined a range of validletters and validnumbers : <pre><code>validletters = ( abcdefghijklmnopqrstuvwxyz ) validnumbers = [ 0 1 2 3 4 5 6 7 8 9 ] </code></pre> however it should then validate like this: <pre><code>name = input( what is your name \n ).lower() while name == or name in validnumbers: name = input( what is your name \n ).lower() strinput0 = name char_only0 = for char in strinput0: if char in validletters: char_only0 += char name = char_only0 </code></pre> <strong>the problem lies with the in part of the statement it only works if the input is a single number (eg. 6 ) but it accepts two or more numbers (eg. 65 ) because 65 (unlike 6 ) is not in validnumbers.</strong> i want it to scan the entire input and ask again if it only consists of numbers as you can see it takes these out (plus any special characters) at the end. there are .isalpha() solutions however they don t allow whitespaces which are required if the user inputs their full name! i have been chipping away at this problem for hours know someone out there is probably able to solve this for me. thanks in advance.,python
how to programmatically know who (other java files/classes) is using my java class i want to get a list of all java class which are dependent on my class. is there a library which exposes intended api api is expected to return list of java classes using my java class.,java
get value from <select> and write output i want to use the value from standings to determine what is printed out in leaderboard i can t seem to figure out where i am going wrong. i think this is the closest i have come to getting it to work. how can i pass the local variable team from inside the function to leaderboard <pre><code>&lt;!doctype html public -//w3c//dtd xhtml 1.0 strict//en http-// &gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;jose cuervo pbv&lt;/title&gt; &lt;link href= rosters.css rel= stylesheet type= text/css /&gt; &lt;meta http-equiv= content-type content= text/html; charset=utf-8 /&gt; &lt;script type= text/javascript &gt; var teams = new array(5); teams[0] = jenny kropp whitney pavlik ; teams[1] = jennifer fopma brooke sweat ; teams[2] = kristen batt raquel ferreira ; teams[3] = emily day heather hughes ; teams[4] = christal engle tealle hunkus ; function listteam(sel) { var i = document.getelementbyid( standings ).value; var team = teams[i]; } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;img src = ./images/cuervo_logo.jpg alt = cuervo pbv logo /&gt; &lt;select id= standings name= standings onchange= listteam(this) &gt; &lt;option value= 0 &gt;first place&lt;/option&gt; &lt;option value= 1 &gt;second place&lt;/option&gt; &lt;option value= 2 &gt;third place&lt;/option&gt; &lt;option value= 3 &gt;fourth place&lt;/option&gt; &lt;option value= 4 &gt;fifth place&lt;/option&gt; &lt;/select&gt; &lt;select id= leaderboard name= leaderboard multiple= multiple size= 1 style= width: 300px; &gt; &lt;option&gt; &lt;script type= text/javascript &gt; document.write(team); &lt;/script&gt; &lt;/option&gt; &lt;/select&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>,javascript
range of primitive numerics - double i am learning about the range of primitive types and i have question about type <code>double</code>. if we know that <code>double</code> has 8 bytes (64 bits) - why is it impossible to determine minimum and maximum range of <code>double</code> <code>long</code> has 8 bytes as well but we can determine minimum and maximum.,java
java: stackoverflowerror i am working on inner class concepts and write the below code_ <pre><code>public class innerclassconcepts { private int x = 11; public static void main(string... args) { // method local x variable int x = new innerclassconcepts().new innera().new innerb().x; innerclassconcepts in = new innerclassconcepts(); innera innera = innera(); innera.innerb xx = innera().new innerb(); system.out.println( innerclassconcepts`s x = + in.x); system.out.println( innerb`s x = + xx.x); system.out.println( main`s x(local variable) = + x); // system.out.println( innera`s x = + innera.x); system.out.println( innera`s y = + innera.y); } /** * local inner class. */ class innera { int y = 10; /* * java.lang.stackoverflowerror coming over here... i don`t * understand why */ // int x=new innerclassconcepts().new innera().new innerb().x;//line-29 /** * inner class inside an another inner class. */ class innerb { private int x = 22; int z = innera.this.y; } } } </code></pre> <code>output_</code> <pre><code>innerclassconcepts s x = 11 innerb s x = 22 main s x(local variable) = 22 innera s y = 10 </code></pre> i am wondering why <code>stackoverflowerror</code> is coming on <code>line-29</code> when i uncomment <em>line-29</em>. where as the same is working in <code>main</code> method. <blockquote> can somebody please help me where i am wrong or what concept is behind this </blockquote>,java
class scope variabile visibility if i have: <pre><code>class a { void foo() { int a = count; } void bar() { int a = c; // here error int c = 10; } private int count = 10; } </code></pre> here in <code>foo</code> <code>count</code> is used without problem also if it s declared after the use.<br> the same is not true in method <code>bar</code> where the variable <code>c</code> must be declared before its use. which are the class scope rules how they differs from method scope rules p.s. my doubt is because the common scope resolutions rules: when the compiler find <code>count</code> it should try to find it back to its use but back there is <code>class a...</code> so maybe <code>private int count</code> is hoisting at beginning of <code>class a</code>,java
how do i break out of a series of string replace( ) i have a collection of short strings in the form [a][z] where a and z are (component) substrings. the strings that can go in [z] are limited to about 100 and only one of them can appear in the whole input string. now i need to replace the [z] string into another string. given the data format as soon as i find a match i know i can stop looking. i want to return the replaced string. my approach is suboptimal because i loop through all possibilities before returning the modified string. i d like to know if there s a way to break the search possibly using the fact that the input string is changed when there s a match how can i tell that the replacement happened i need to run this function about 1000 times per page load so i think that any improvement will be noticed. thanks in advance! <a href= rel= nofollow ></a> <pre><code>function replaceend(input) { // bb cc and d are what i call [z] input = input.replace( bb bob ); input = input.replace( ccc carl ); input = input.replace( d dave ); return input; } document.write(replaceend( aabb ) + &lt;br&gt; ); document.write(replaceend( eaccc ) + &lt;br&gt; ); document.write(replaceend( uoid ) + &lt;br&gt; ); </code></pre> outputs: <pre><code>aabob eacarl uoidave </code></pre>,javascript
iphone standby button is there an event when the user presses the standby button i can disable auto standby (autolock) - which i do because my app is some kind of a routing application. but how about the standby button the problem - if the iphone goes standby the gps is turned off. so my app thinks it has a gps problem. this is in fact wrong - it s only standby which means a different handling should be done as if i do it when gps problems occure in running mode (the users sees the app). i couldn t find an event for this situation (neither going standby - nor awaiking from it),iphone
app quits in iphone 4 i am using this but if i start my app again on iphone 4 then it quits problem is it dont know indexpath.row now how to solve this isuee / <pre><code>- (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { int j=indexpath.row; if(j==0) { uiimage *bgimage = [uiimage imagenamed:@ logo_jurong.png ]; uiimageview *bgimageview = [[uiimageview alloc] initwithimage:bgimage]; [bgimageview setframe:cgrectmake(7 13 30 30)]; //finally give this imageview to the cell [cell.contentview addsubview:bgimageview]; [bgimage release]; } } </code></pre>,iphone
how to make and iframe like preview how do i make an iframe like using javascript and iframe dom element. here is the site reference. look at the top black line. and the whole website is loaded under it. <pre><code> </code></pre>,javascript
python how to append new data by literately checking the existing data i am working on machine learning project and would like to append data to the current table by literately checking the current data: to be specific <pre><code>x y = form_results(results) // x &amp; y are numpy arrays </code></pre> the current data set looks like the following: <pre><code>x[0] x[1] y 1 4 1 2 5 3 3 6 4 </code></pre> how could i make it into the set as below: <pre><code>x[0] x[1] y 1 4 1 1 5 0 1 6 0 2 4 0 2 5 3 2 6 0 3 4 0 3 5 0 3 6 4 </code></pre> explanation: list out all the possibility match of x[0] &amp; x[1] and if the match does not exist in the original table append one row with the new match of x[0] &amp; x[1] and make the value of y to be 0. current rough though: // but this does not work <pre><code>new_data = [] for x in enumerate(x) y: for i j in x: if x[i] x[j]not in x: new_data.append(x[0] x[1] y) x = numpy.vstack(x new_data) </code></pre> i am sorry to ask this kind of stupid questions but i could not find a way out. thanks in advance for your kindness.,python
not all arguments converted during string formatting taking modulus where isnumeric() is true <pre><code>while true: ans = input( enter a number : ) if ans.isalpha(): if ans == q : break elif ans.isnumeric(): if ans == 1 or ans == 0: print( not even nor odd number ) elif ans % 2 == 0: print( even number ) else: print( odd number ) </code></pre> and goes error like this: <pre><code>traceback (most recent call last): file c:/users/ line 9 in &lt;module&gt; elif ans % 2 == 0: typeerror: not all arguments converted during string formatting </code></pre>,python
how does the following works <pre><code>public static void main(string[] args) { int h = 30; h ^= (h &gt;&gt;&gt; 20) ^ (h &gt;&gt;&gt; 12); system.out.println(h); } </code></pre> if int h = 30 whose binary is 0001 1110. after operation what value will stored in h,java
what are the custom url schemes for tweetdeck and seesmic does tweetdeck or seesmic have a custom url scheme that can be used within an iphone application if so what are the structures of these url schemes,iphone
reading strings instead of characters from a stream i have a <code>arraylist</code> class and trying to save it to a file. i m writing a little test method to save string to a file then load them. i found a method in the <code>filewriter</code> class to write a string. i could not find any methods in the <code>filereader</code> to read in strings. is there a way to do this,java
access to the method without static i have 2 class class b and a <pre><code>public class b private car fiat; public boolean trueorfalse() { return fiat.methodfromclasscar(); } </code></pre> in class a i want to use this result from this boolean something like: <pre><code>public class a public int xyz(){ if (trueorfalse()==true){ dosomething(); } } </code></pre> always i making static all but now i cant do this. is there better way create a new object in class a: <pre><code>car cr = new car(); </code></pre> and then using <pre><code>cr.trueorfalse(); </code></pre> is good way but what i code wrong here,java
python dictionary w/ 2 keys can i have a python dictionary with 2 same keys but with different elements,python
why i get cannot set property na0 of undefined error this is my code: <pre><code>var places = { }; var x = 0; for (var k in { var contentid =[k].contentid; var contenttype =[k].contenttype; var key = contenttype + _ + contentid; var address =[k].address; var topics =[k].topic; var research_theme =[k].research_theme; places[key][ na + x]= [address topics research_theme]; x++; } </code></pre> however it says uncaught typeerror: cannot set property na0 of undefined why i want to have na0 na1 and so on. how can i do that,javascript
python: removing outliers from a list. what s wrong with this code the following code snippet is from one of my functions which is passed a list of numbers and is supposed to remove outliers (i.e. very large or very small numbers) from the list. the code does not seem to work as intended as the output confirms: <pre><code>extrema_cutoff_threshold=3.0 if list_values: avg_val = sum(list_values)/float(len(list_values)) print debug: before: min(list_values) max(list_values) avg_val list_values = [x for x in list_values if math.fabs(x - avg_val)/float(avg_val) &lt; extrema_cutoff_threshold] list_values_len = len(list_values) if (list_values_len &gt; 0) and (min_sample_size &gt; 0) and (list_values_len &lt; min_sample_size): print debug: insufficient data for stats calculation for row elif (list_values_len &gt; 0): print debug: after: min(list_values) max(list_values) avg_val </code></pre> <strong>output:</strong> <pre><code>debug: before: 11.0 302.0 113.897260274 debug: after: 11.0 302.0 113.897260274 debug: before: 12.5 273.0 108.382352941 debug: after: 12.5 273.0 108.382352941 debug: before: 2.5 245.5 69.9166666667 debug: after: 2.5 245.5 69.9166666667 debug: before: 136.5 499.5 363.775 debug: after: 136.5 499.5 363.775 debug: before: 39.5 422.5 166.035759097 debug: after: 39.5 422.5 166.035759097 debug: before: 39.5 422.0 152.305007587 debug: after: 39.5 422.0 152.305007587 debug: before: 20.5 331.0 84.41015625 debug: after: 20.5 331.0 84.41015625 debug: before: 7.0 267.5 155.810126582 debug: after: 7.0 267.5 155.810126582 </code></pre> why are the extreme values not being filtered out,python
gzip: stdin: input/output error /bin/sh: line 1: /logfo/dynamo.log-20150317.gz: permission denied <pre><code>import subprocess g_rep = zgrep i_d /logfo/dynam* f = open( fi.txt r ) for i in f: g_rep = zgrep + i + /logfo/dynam* print g_rep k = subprocess.popen([ zgrep + i + /logfo/dynamo* ] shell=true) print k g_rep = zgrep + i + /logfo/dynam* print g_rep </code></pre> when i am executing the script i got the output as: <pre><code>zgrep 211043369013 /logfo/dynam* &lt;subprocess.popen object at 0xabe190&gt; zgrep 211043369013 /logfo/dynam* </code></pre> but actual output should be.. <code>zgrep 211043369013 /logfo/dynam*</code> please help me how to bring in single line,python
obtaining string from urlpath in nsstring in ipnone apps hi i am new to iphone development. i want to obtain string from url path for example the relative path: 90-000000-general_motors<br> i want to extract: general motors<br> if path is 90-000000-general_motors/5.jpg<br> i want to extract: 5 how can i acheive using simple coding,iphone
how do i measure the speed of another object relative to the iphone i would like to measure the speed of another vehicle on a road (not one that the iphone currently is in). how would you go about measuring the speed of that other moving object,iphone
checking keyboard or mouse events are done in a div how can i check if a keyboard or mouse event is done inside of a div once i check the onmousemove() event of a div it works but onkeyup onkeypress etc are not working for the div. what is the reason for that <pre><code>&lt;div onmousemove= alert(1); onkeypress= alert(2); &gt; </code></pre> here alert(1) will be displayed but alert(2) is not displayed.,javascript
what s wrong with uicolor *clr = [uicolor colorwithred:1.0 green:1.0 blue:1.0 alpha:1.0]; <pre><code>uicolor *clr = [uicolor colorwithred:1.0 green:1.0 blue:1.0 alpha:1.0]; </code></pre> i have compiler errors at above line. <ol> <li>expected ] before numeric constant</li> <li> uicolor may not respond to +colorwithred:green: </li> </ol> if i comment out that line i don t have compiler error. maybe i have this problem after i added below line in my prefix.pch. <pre><code>#define rgb(r g b) [uicolor colorwithred:r/255.0 green:g/255.0 blue:b/255.0 alpha:1] </code></pre> i had the same compiler errror. so i deleted that line from .pch and i cleaned all target in build menu and recompiled. i even rebooted. i retyped. it is useless.,iphone
setvalue wont work though there is a value to use hi im trying to get a progress bar to work i have a value and cann access the property here is my code just the form because i know progress being past because i can print it out useing getvalue here is my code <pre><code> /* * to change this license header choose license headers in project properties. * to change this template file choose tools | templates * and open the template in the editor. */ package mashisgood; import; import; import java.util.logging.level; import java.util.logging.logger; import javax.swing.jfilechooser; import javax.swing.jprogressbar; /** * * @author brett */ public class mashform extends javax.swing.jframe { private jprogressbar progressbar; /** * creates new form mashform */ public mashform() { initcomponents(); } /** * this method is called from within the constructor to initialize the form. * warning: do not modify this code. the content of this method is always * regenerated by the form editor. */ @suppresswarnings( unchecked ) // &lt;editor-fold defaultstate= collapsed desc= generated code &gt; private void initcomponents() { filechooser = new javax.swing.jfilechooser(); jbutton1 = new javax.swing.jbutton(); jtextfield1 = new javax.swing.jtextfield(); jprogressbar1 = new javax.swing.jprogressbar(); jbutton2 = new javax.swing.jbutton(); setdefaultcloseoperation(javax.swing.windowconstants.exit_on_close); jbutton1.settext( jbutton1 ); jbutton1.addactionlistener(new java.awt.event.actionlistener() { public void actionperformed(java.awt.event.actionevent evt) { jbutton1actionperformed(evt); } }); jtextfield1.settext( add afile to compile ); jprogressbar1.settooltiptext( ); jprogressbar1.setborder(javax.swing.borderfactory.createbevelborder(javax.swing.border.bevelborder.raised)); jprogressbar1.setstringpainted(true); jbutton2.settext( jbutton2 ); jbutton2.addactionlistener(new java.awt.event.actionlistener() { public void actionperformed(java.awt.event.actionevent evt) { jbutton2actionperformed(evt); } }); javax.swing.grouplayout layout = new javax.swing.grouplayout(getcontentpane()); getcontentpane().setlayout(layout); layout.sethorizontalgroup( layout.createparallelgroup(javax.swing.grouplayout.alignment.leading) .addgroup(layout.createsequentialgroup() .addcontainergap() .addgroup(layout.createparallelgroup(javax.swing.grouplayout.alignment.leading) .addcomponent(jprogressbar1 javax.swing.grouplayout.default_size javax.swing.grouplayout.default_size short.max_value) .addgroup(layout.createsequentialgroup() .addcomponent(jbutton1) .addgap(18 18 18) .addcomponent(jtextfield1 javax.swing.grouplayout.default_size 289 short.max_value)) .addgroup(layout.createsequentialgroup() .addcomponent(jbutton2) .addgap(0 0 short.max_value))) .addcontainergap()) ); layout.setverticalgroup( layout.createparallelgroup(javax.swing.grouplayout.alignment.leading) .addgroup(layout.createsequentialgroup() .addcontainergap() .addgroup(layout.createparallelgroup(javax.swing.grouplayout.alignment.baseline) .addcomponent(jbutton1) .addcomponent(jtextfield1 javax.swing.grouplayout.preferred_size javax.swing.grouplayout.default_size javax.swing.grouplayout.preferred_size)) .addgap(18 18 18) .addcomponent(jprogressbar1 javax.swing.grouplayout.preferred_size javax.swing.grouplayout.default_size javax.swing.grouplayout.preferred_size) .addgap(29 29 29) .addcomponent(jbutton2) .addcontainergap(175 short.max_value)) ); jprogressbar1.getaccessiblecontext().setaccessiblename( mystatusbar ); pack(); }// &lt;/editor-fold&gt; private void jbutton1actionperformed(java.awt.event.actionevent evt) { // todo add your handling code here: int returnval = filechooser.showopendialog(this); if (returnval == jfilechooser.approve_option) { file file = filechooser.getselectedfile(); jtextfield1.settext(file.getabsolutepath()); } else { system.out.println( file access cancelled by user. ); } } private void jbutton2actionperformed(java.awt.event.actionevent evt) { //mashisgood goodo = new mashisgood(); string[] arguments = new string[] { 1234 }; try { mashisgood.main(arguments); } catch (ioexception ex) { logger.getlogger(mashform.class.getname()).log(level.severe null ex); } } void setpgvalue(int progress) { jprogressbar1.setvalue(progress); system.out.println( get value: + +jprogressbar1.getvalue()); jprogressbar1.setvalue(69); setbar(progress); } public void setbar(int goods){ jprogressbar1.setvalue(goods); //system.out.println(); //return } /** * @param args the command line arguments */ public static void main(string args[]) { /* set the nimbus look and feel */ //&lt;editor-fold defaultstate= collapsed desc= look and feel setting code (optional) &gt; /* if nimbus (introduced in java se 6) is not available stay with the default look and feel. * for details see */ try { for (javax.swing.uimanager.lookandfeelinfo info : javax.swing.uimanager.getinstalledlookandfeels()) { if ( nimbus .equals(info.getname())) { javax.swing.uimanager.setlookandfeel(info.getclassname()); break; } } } catch (classnotfoundexception | instantiationexception | illegalaccessexception | javax.swing.unsupportedlookandfeelexception ex) { java.util.logging.logger.getlogger(mashform.class.getname()).log(java.util.logging.level.severe null ex); } //&lt;/editor-fold&gt; //&lt;/editor-fold&gt; /* create and display the form */ java.awt.eventqueue.invokelater(() -&gt; { new mashform().setvisible(true); }); } // variables declaration - do not modify private javax.swing.jfilechooser filechooser; private javax.swing.jbutton jbutton1; private javax.swing.jbutton jbutton2; public static javax.swing.jprogressbar jprogressbar1; private javax.swing.jtextfield jtextfield1; // end of variables declaration } </code></pre> here is the second class <pre><code>/* * to change this license header choose license headers in project properties. * to change this template file choose tools | templates * and open the template in the editor. */ package mashisgood; import*; import java.util.scanner; import java.util.regex.pattern; import javafx.application.application; import javafx.stage.stage; /** * * @author brett */ public class mashisgood extends application { public static void main(string[] args) throws ioexception { processbuilder pb = new processbuilder( ffmpeg -i c:\\users\\brett\\documents\\telegraph_road.mp4 c:\\users\\brett\\documents\\out.mp4 ); final process p = pb.start(); // create a new thread to get progress from ffmpeg command override // it s run method and start it! new thread() { @override public void run() { scanner sc = new scanner(p.geterrorstream()); // find duration pattern durpattern = pattern.compile( ( &lt;=duration: )[^ ]* ); string dur = sc.findwithinhorizon(durpattern 0); if (dur == null) { throw new runtimeexception( could not parse duration. ); } string[] hms = dur.split( : ); double totalsecs = integer.parseint(hms[0]) * 3600 + integer.parseint(hms[1]) * 60 + double.parsedouble(hms[2]); system.out.println( total duration: + totalsecs + seconds. ); // find time as long as possible. pattern timepattern = pattern.compile( ( &lt;=time=)[\\d:.]* ); string match; string[] matchsplit; while (null != (match = sc.findwithinhorizon(timepattern 0))) { matchsplit = match.split( : ); double progress = (integer.parseint(matchsplit[0]) * 3600 + integer.parseint(matchsplit[1]) * 60 + double.parsedouble(matchsplit[2])) / totalsecs; // system.out.printf( progress: %.2f%%%n progress * 100); mashform pgbar = new mashform(); int prog = (int)(progress * 100); pgbar.setpgvalue(prog); pgbar.setbar(prog); } } }.start(); } @override public void start(stage primarystage) throws exception { throw new unsupportedoperationexception( not supported yet. ); //to change body of generated methods choose tools | templates. } } </code></pre>,java
accessing nsmutablearray in class in class1 i create an object of class2. i then use a method on this object to set its nsmutablearray <pre><code>-(void) clonearray: (nsmutablearray *) array{ pictures = [nsmutablearray arraywitharray:array]; } </code></pre> class2 is a viewcontroller which has a uiimageview. i present the class2 object after creating it. this class then has its own methods which display the next image when a swipe is detected. <pre><code>-(void) nextimageselector{ if (counter == [pictures count]-1) { counter = 1; asset = [pictures objectatindex:counter]; alassetrepresentation *assetrepresentation = [asset defaultrepresentation]; uiimage *fullscreenimage = [uiimage imagewithcgimage:[assetrepresentation fullscreenimage] scale:[assetrepresentation scale] orientation:[assetrepresentation orientation]]; photo.image = fullscreenimage; } </code></pre> the app crashes when calling the line <blockquote> if (counter == [pictures count]-1) </blockquote> so i think it is crashing because the array is created for an object and then the next array is trying to be checked is for the class instance itself. how can i fix this so that i can copy an array for this class2 to use in its own methods like the nextimageselector,iphone
how to save an xml file i am developing an application. in it i want to create an xml file with some data. i want to save the xml file and retrieve it at some other time. is it possible to save and retrieve an xml file on the iphone if so how,iphone
adding event listeners through for loop i m having some issues with some javascript code. what i am trying to do is add event listeners to elements in an array. the problem is that after the code is ran only the last element in the array gets the eventlistener working the rest of the elements are returning errors. i m assuming this is because of the logic i m using with the for loop and the eventlisteners. what would be an effective way to achieve the desired result <pre><code>function addslider(config) { var controls = ` &lt;div id= next &gt; next &lt;/div&gt; &lt;div id= previous &gt; previous &lt;/div&gt;`; var s_wrapper = config.wrapper; var controls_html = document.createelement( div ); controls_html.setattribute( id ctrl ); controls_html.innerhtml = controls; var arraydata = config.wrapper.split( ); for (i = 0; i &lt; arraydata.length; i++) { (function(index) { document.queryselector(arraydata[i]).appendchild(controls_html); var parent = document.queryselector(arraydata[index]); console.log(i index arraydata[index] parent); document.queryselector(arraydata[index]).addeventlistener( mouseover function(){ this.queryselector( #ctrl ).style.display = block ; }) document.queryselector(arraydata[index]).addeventlistener( mouseout function(){ this.queryselector( #ctrl ).style.display = none ; }) })(i); } </code></pre> },javascript
what is the equivalent keyword for extern in java i have one public static variable in one file and how can i export the same variable to other files for ex:- <pre><code>public final static int buf = 256; </code></pre> how can i access the variable buf in this file,java
how to pass class method as a parameter before the instance is declared what i want to do is like this. my question is how can i call tm.test in inner. <pre><code>// testmain is a class implemented handler public void outer() { inner(testmain::test); // call inner } public void inner(handler h) { testmain tm = new testmain(); //invoke tm.h() i.e. invoke tm.test() in this example } public interface handler&lt;m&gt; { void entityselector(); } </code></pre> <ul> <li>i know how to call tm.test in inner if tm is declared in method outer i.e. pass the function as tm::test</li> <li>but i have to declare the instance every time i call inner.</li> </ul>,java
pythonic way of returning none if input itself is none what s the best way to write a <em>null-check</em> in python <code>try-except</code> blocks <code>if</code> blocks... given a function that returns <code>none</code> if the input is <code>none</code> a valid input what s the best approach to deal with this situation take this function for example: <pre><code>def urlify(path): if path is none: return none return &lt;a href=\ {0!s}\ &gt;{0!s}&lt;/a&gt; .format(path) </code></pre>,python
how to get python program to read and print with tiered data i am still a newbie developer with not much time under my belt with this. i have a .csv file that i constructed that contains facility id sequence for the facility and the nsn for the sequence. i have a .csv that contains every value possible for facility sequence and nsn along with a a file that just has a facility a lightly structured product that i need. there is a total of 476 different facilities 2935 sequences. there are multiple nsns per sequence but not every sequence has an nsn and not every facility requires a sequence. what i desire is a .csv output with facility sequence and nsn for every line there is an nsn. *data is just simplified examples <pre><code> desired output input |||| vvvv facility sequence nsn 104b 104b 22a 55-51a 22a 104b 22a 63-42c 55-51a 104b 24x 55-50a 63-42c 209c 22a 55-50a 24x 209c 39g 63-12l 55-50a 632f 99y 44-10q </code></pre> my problem is i only have a rough idea of what needs to be done and i think the direction i am going currently will only produce one facility sequence and nsn before moving onto the next facility to repeat. this is only a rough draft edits/simple ideas are greatly appreciated advance suggestions should be explained in great depth on how they work or a complete example because i would not know what to do with it other wise. *note the quantity is something extra that probably wont make it to the end of dev because it has already been compiled. def main(): import os <pre><code>filelist = list() filewrite = open( nsn.txt w ) class facility: represents facility filefacilitysource = open ( facility.csv r ) def __init__ (self facilityid): self.facilityid=facilityid #facilityid is the facility id number self.seqlist=list() def addseq(self seq): self.seqlist.append(seq) def findseq(self seq): for s in self.seqlist: if s.seqid==seqidtofind: return s class sequence: sequence filesequencesource = open ( sequence.csv r ) def __init__(self seqid id): self.seqid=seqid #seqid is the sequence for the facility #id is the id number associated with the sequence for its place self.nsnlist=list() def addnsn(self nsn): self.nsnlist.append(nsn) class nsn: nsn filensnsource = open ( nsn.csv r ) def __init__ (self nsnid qty): self.nsnid=nsnid #nsnid is the nsn for the sequence self.qty=qty #qty is the quantity associated with the nsn def search(): for keywords in filensnlist: if facility in line: if sequence in line: if nsn in line: print facility sequence nsn filelist.append(line) thestring = .join(filelist) searchfile.close() filewrite.write(thestring) filewrite.close() main() </code></pre>,python
how to speed-up drawrect i m coding a map app for <strong>iphone</strong> like google maps but with my own maps. what i have so far is working but sadly slower than i would like. i m basically drawing the correct map tiles in each <code>drawrect</code>:<br> <code>[image drawatpoint:cgpointmake(x y)];</code> x and y are being calculated in each call to <code>drawrect</code><br> ( these calcs are not very expensive ). the maximum number of images being drawn at a time is 4.<br> each image is <code>512 x 512</code>. i feel that some kind of optimization is lacking here. can anyone help with something <br> thanks you all.,iphone
detecting movement with an iphone can the iphone detect its movement in terms of distance would one be able to use a built in function on an iphone to determine the distance the phone has moved so that the speed of movement can be calculated basically my question is can an iphone detect its position and distance moved without using the gps thanks,iphone
adding a function to a prototype does not work i am trying to add a function to prototype like this <pre><code>function dog(name breed) { = name; this.breed = breed; } function barkwithme() { console.log( woof woof i am +; } dog.prototype.bark = barkwithme(); var snoopy = new dog(); snoopy.bark(); </code></pre> but it displays an error <pre><code>uncaught typeerror: snoopy.bark is not a function </code></pre> please tell me where am i wrong. thanks.,javascript
my python wumpus game not ending i m doing the wumpus game from hello python. unfortunately whether the player wastes his only arrow or the wumpus eats him the game does not end. i ve tried fiddling with the code but to be honest i m just a beginner and still learning. here is the code <pre><code> from random import choice import random cave_numbers = range(0 20) caves =[] for i in cave_numbers: caves.append([]) unvisited_caves = range(0 20) visited_caves = [0] #unvisited caves == [] unvisited_caves.remove(0) while unvisited_caves != []: i = choice(visited_caves) if len(caves[i]) &gt;= 3: break next_cave = choice(unvisited_caves) caves[i].append(next_cave) caves[next_cave].append(i) visited_caves.append(next_cave) unvisited_caves.remove(next_cave) for number in cave_numbers: print number : caves[number] print ---------- for i in cave_numbers: while len(caves[i]) &lt; 3: passage_to = choice(cave_numbers) caves[i].append(passage_to) for i in cave_numbers: while len(caves[i]) &lt; 3: passage_to = choice(cave_numbers) caves[i].append(passage_to) for number in cave_numbers: print number : caves[number] print ---------- for i in cave_numbers: for j in range(3): passage_to = choice(cave_numbers) caves[i].append(passage_to) print caves wumpus_location = choice(cave_numbers) player_location = choice(cave_numbers) #while player_location == wumpus_location player_location = choice(cave_numbers) print welcome to hunt the wumpus! print you can see len(cave_numbers) caves print to play just type the number print of the cave you wish to enter next while true: def print_location(player_location): tell the player where they are print you are in cave player_location print from here you can see caves: print caves[player_location] if wumpus_location in caves[player_location]: print i smell and horrible wumpus! def setup_caves(cave_numbers): create the starting list of caves caves = [] for cave in cave_numbers: caves.append([]) return caves def link_caves(): make sure all of the caves are conneceted with two-way tunnels while unvisited_caves != []: this_cave = choose_cave(visited_caves) next_cave = choose_cave(unvisited_caves) create_tunnel(this_cave next_cave) visit_cave(next_cave) def finish_caves(): link the rest of the caves with one-way tunnels for cave in cave_numbers: while len(caves[cave]) &lt; 3: passage_to = choose_cave(cave_numbers) caves[cave].append(passage_to) def ask_for_cave(): ask the player to choose a cave from their current_location. player_input = raw_input( which cave ) if (not player_input.isdigit() or int(player_input) not in caves[player_location]): print player_input + print that s not a direction that i can see! else: return int(player_input) def get_action(): find out what the player wants to do next. print what do you do next print m) move print a) fire an arrow action = raw_input( &gt; ) if action == m or action == a : return action else: print action + print that s not an action that i know about return none def do_movement(): print moving.... new_location = ask_for_cave() if new_location is none: return player_location else: return new_location def do_shooting(): print firing... shoot_at = ask_for_cave() if shoot_at is none: return false if shoot_at == wumpus_location: print kapow! well done buddy you shot the mighty wumpus! print you are the mighty wumpus hunter. else: print twang... clatter clatter! print you wasted your only arrow! print empty handed you begin the print long trek back to your village. a failure. return true #... while 1: print_location(player_location) action = get_action() if action is none: continue if action == m : player_location = do_movement() if player_location == wumpus_location: print argh the wumpus ate you! print game over bro game over! break if action == a : game_over = do_shooting() if game_over: break </code></pre>,python
iphone application crash my application works fine on all my devices. but it crashes on clients devices. below is the crash log. can anyone help.. i am lost... <pre><code>incident identifier: 8c60587c-4152-4e29-a1f1-ac780b63bb45 crashreporter key: 09cad4f13a4c6b81b63d81504cd8b58e5eea4fd7 hardware model: iphone3 1 process: cadoinpiedi [73] path: /var/mobile/applications/4074dcae-e48f-443a-9215-1498c2940984/ identifier: cadoinpiedi version: ( ) code type: arm (native) parent process: launchd [1] date/time: 2011-03-10 10:10:16.637 +0100 os version: iphone os 4.3 (8f190) report version: 104 exception type: exc_crash (sigabrt) exception codes: 0x00000000 0x00000000 crashed thread: 0 thread 0 name: dispatch queue: thread 0 crashed: 0 libsystem_kernel.dylib 0x315fca1c 0x315eb000 + 72220 1 libsystem_c.dylib 0x36b193b4 0x36ae6000 + 209844 2 libsystem_c.dylib 0x36b11bf8 0x36ae6000 + 179192 3 libstdc++.6.dylib 0x34df0a64 0x34dac000 + 281188 4 libobjc.a.dylib 0x36f8406c 0x36f7e000 + 24684 5 libstdc++.6.dylib 0x34deee36 0x34dac000 + 273974 6 libstdc++.6.dylib 0x34deee8a 0x34dac000 + 274058 7 libstdc++.6.dylib 0x34deef5a 0x34dac000 + 274266 8 libobjc.a.dylib 0x36f82c84 0x36f7e000 + 19588 9 corefoundation 0x32d3f48a 0x32ca1000 + 648330 10 corefoundation 0x32d3f4c4 0x32ca1000 + 648388 11 corefoundation 0x32cb19d0 0x32ca1000 + 68048 12 cadoinpiedi 0x0000bc7c 0x1000 + 44156 13 foundation 0x3299d388 0x32907000 + 615304 14 libxml2.2.dylib 0x371f620e 0x371eb000 + 45582 15 libxml2.2.dylib 0x371febba 0x371eb000 + 80826 16 foundation 0x3299cd5e 0x32907000 + 613726 17 cadoinpiedi 0x0000b528 0x1000 + 42280 18 foundation 0x329192ee 0x32907000 + 74478 19 foundation 0x32919270 0x32907000 + 74352 20 cfnetwork 0x3684040a 0x36831000 + 62474 21 cfnetwork 0x36834f42 0x36831000 + 16194 22 cfnetwork 0x36834e34 0x36831000 + 15924 23 cfnetwork 0x36834de6 0x36831000 + 15846 24 cfnetwork 0x36834d58 0x36831000 + 15704 25 cfnetwork 0x36834cd6 0x36831000 + 15574 26 corefoundation 0x32d16a72 0x32ca1000 + 481906 27 corefoundation 0x32d18758 0x32ca1000 + 489304 28 corefoundation 0x32d194e4 0x32ca1000 + 492772 29 corefoundation 0x32ca9ebc 0x32ca1000 + 36540 30 corefoundation 0x32ca9dc4 0x32ca1000 + 36292 31 graphicsservices 0x30f51418 0x30f4d000 + 17432 32 graphicsservices 0x30f514c4 0x30f4d000 + 17604 33 uikit 0x35f1fd62 0x35ef1000 + 191842 34 uikit 0x35f1d800 0x35ef1000 + 182272 35 cadoinpiedi 0x00002210 0x1000 + 4624 36 cadoinpiedi 0x00002190 0x1000 + 4496 thread 1: 0 libsystem_kernel.dylib 0x315fd3ec 0x315eb000 + 74732 1 libsystem_c.dylib 0x36b1a6d8 0x36ae6000 + 214744 2 libsystem_c.dylib 0x36b1abbc 0x36ae6000 + 215996 thread 2 name: dispatch queue: thread 2: 0 libsystem_kernel.dylib 0x315fdfbc 0x315eb000 + 77756 1 libdispatch.dylib 0x328fa094 0x328f4000 + 24724 2 libdispatch.dylib 0x328fb04a 0x328f4000 + 28746 3 libdispatch.dylib 0x328fa60a 0x328f4000 + 26122 4 libsystem_c.dylib 0x36b1a58a 0x36ae6000 + 214410 5 libsystem_c.dylib 0x36b1abbc 0x36ae6000 + 215996 thread 3: 0 libsystem_kernel.dylib 0x315fd3ec 0x315eb000 + 74732 1 libsystem_c.dylib 0x36b1a6d8 0x36ae6000 + 214744 2 libsystem_c.dylib 0x36b1abbc 0x36ae6000 + 215996 thread 4 name: webthread thread 4: 0 libsystem_kernel.dylib 0x315fac00 0x315eb000 + 64512 1 libsystem_kernel.dylib 0x315fa758 0x315eb000 + 63320 2 corefoundation 0x32d172b8 0x32ca1000 + 484024 3 corefoundation 0x32d19562 0x32ca1000 + 492898 4 corefoundation 0x32ca9ebc 0x32ca1000 + 36540 5 corefoundation 0x32ca9dc4 0x32ca1000 + 36292 6 webcore 0x31a0037a 0x319fa000 + 25466 7 libsystem_c.dylib 0x36b1930a 0x36ae6000 + 209674 8 libsystem_c.dylib 0x36b1abb4 0x36ae6000 + 215988 thread 5: 0 libsystem_kernel.dylib 0x315fac00 0x315eb000 + 64512 1 libsystem_kernel.dylib 0x315fa758 0x315eb000 + 63320 2 corefoundation 0x32d172b8 0x32ca1000 + 484024 3 corefoundation 0x32d19562 0x32ca1000 + 492898 4 corefoundation 0x32ca9ebc 0x32ca1000 + 36540 5 corefoundation 0x32ca9dc4 0x32ca1000 + 36292 6 foundation 0x329317f6 0x32907000 + 174070 7 foundation 0x32924382 0x32907000 + 119682 8 foundation 0x329965c6 0x32907000 + 587206 9 libsystem_c.dylib 0x36b1930a 0x36ae6000 + 209674 10 libsystem_c.dylib 0x36b1abb4 0x36ae6000 + 215988 thread 6 name: thread 6: 0 libsystem_kernel.dylib 0x315fcc60 0x315eb000 + 72800 1 corefoundation 0x32d1c8f2 0x32ca1000 + 506098 2 libsystem_c.dylib 0x36b1930a 0x36ae6000 + 209674 3 libsystem_c.dylib 0x36b1abb4 0x36ae6000 + 215988 thread 0 crashed with arm thread state: r0: 0x00000000 r1: 0x00000000 r2: 0x00000001 r3: 0x00000000 r4: 0x3fcca48c r5: 0x00000006 r6: 0x0019bc6c r7: 0x2fdfe658 r8: 0x3f60dbf8 r9: 0x00000065 r10: 0x361eafd8 r11: 0x361e82f0 ip: 0x00000148 sp: 0x2fdfe64c lr: 0x36b193bb pc: 0x315fca1c cpsr: 0x000f0010 binary images: 0x1000 - 0x19fff +cadoinpiedi armv7 &lt;d248922f1069f2847106e98c1e5a11ba&gt; /var/mobile/applications/4074dcae-e48f-443a-9215-1498c2940984/ 0x2fe00000 - 0x2fe25fff dyld armv7 &lt;8dbdf7bab30e355b81e7b2e333d5459b&gt; /usr/lib/dyld 0x30e94000 - 0x30e98fff assetslibraryservices armv7 &lt;2e841b3daf303b38bbd82e0954659af4&gt; /system/library/privateframeworks/assetslibraryservices.framework/assetslibraryservices 0x30f1e000 - 0x30f4cfff mime armv7 &lt;a9fa461fb9e7378789a3091b69504a09&gt; /system/library/privateframeworks/mime.framework/mime 0x30f4d000 - 0x30f59fff graphicsservices armv7 &lt;c37066a0784335d189f009ff4965717d&gt; /system/library/privateframeworks/graphicsservices.framework/graphicsservices 0x30f5a000 - 0x30f5cfff mobileinstallation armv7 &lt;94b6d6c5d9883175af26764567528127&gt; /system/library/privateframeworks/mobileinstallation.framework/mobileinstallation 0x3106e000 - 0x3106efff libdnsinfo.dylib armv7 &lt;21415179ffa03f949fa8cc851c6c31c7&gt; /usr/lib/system/libdnsinfo.dylib 0x31157000 - 0x3115ffff mobilebluetooth armv7 &lt;d0167be199b234f5bd233380111b2735&gt; /system/library/privateframeworks/mobilebluetooth.framework/mobilebluetooth 0x31160000 - 0x3117ffff bom armv7 &lt;b178e3efb4d733c694bd5a55e57a314f&gt; /system/library/privateframeworks/bom.framework/bom 0x31256000 - 0x31259fff actorkit armv7 &lt;f7aa6cdd654231988aafcf448978f450&gt; /system/library/privateframeworks/actorkit.framework/actorkit 0x3125a000 - 0x31263fff itsync armv7 &lt;dc57c003aad83864827ccf95fc579563&gt; /system/library/privateframeworks/itsync.framework/itsync 0x31268000 - 0x312aafff coreaudio armv7 &lt;d45e275525ef3c32b36e0f1020cad705&gt; /system/library/frameworks/coreaudio.framework/coreaudio 0x312ab000 - 0x312aefff captivenetwork armv7 &lt;fc834fd33a18341ea7506587ad895703&gt; /system/library/privateframeworks/captivenetwork.framework/captivenetwork 0x312c9000 - 0x312d3fff accountsettings armv7 &lt;d083fb384dc7311eb6766b9b2d2dd9c8&gt; /system/library/privateframeworks/accountsettings.framework/accountsettings 0x31304000 - 0x31337fff storeservices armv7 &lt;a74659288dea34bca7a7911c19cf2c28&gt; /system/library/privateframeworks/storeservices.framework/storeservices 0x31338000 - 0x31339fff coresurface armv7 &lt;7b83cd757da73e6e826693c29296d3fa&gt; /system/library/privateframeworks/coresurface.framework/coresurface 0x3143a000 - 0x3143bfff libsystem_blocks.dylib armv7 &lt;ccc041df3de73eafb7a59e74cdb1702b&gt; /usr/lib/system/libsystem_blocks.dylib 0x31543000 - 0x31547fff libgfxshared.dylib armv7 &lt;2c61a8f7e7bf32d890e957d768d769ce&gt; /system/library/frameworks/opengles.framework/libgfxshared.dylib 0x31548000 - 0x3157bfff quicklook armv7 &lt;29d2d981d1d6358381f5716ee37314b4&gt; /system/library/frameworks/quicklook.framework/quicklook 0x3157c000 - 0x3157ffff libmacho.dylib armv7 &lt;0479a171c00d3f629d639713acb72b5b&gt; /usr/lib/system/libmacho.dylib 0x315b0000 - 0x315d0fff appleaccount armv7 &lt;4e0ac5cf93b338ab8c5f34ba3c5e2ee4&gt; /system/library/privateframeworks/appleaccount.framework/appleaccount 0x315eb000 - 0x31602fff libsystem_kernel.dylib armv7 &lt;29eb602b615b3c3b95722868100a2d1c&gt; /usr/lib/system/libsystem_kernel.dylib 0x31658000 - 0x3165dfff libnotify.dylib armv7 &lt;9d7198e91de9386a9e5ea43608a66a57&gt; /usr/lib/system/libnotify.dylib 0x3168a000 - 0x316bdfff appsupport armv7 &lt;0217468bd9f839229a47910b7816b3d5&gt; /system/library/privateframeworks/appsupport.framework/appsupport 0x316ee000 - 0x3173ffff libsqlite3.dylib armv7 &lt;8a41cc6a6d9332308bc415d27577fd24&gt; /usr/lib/libsqlite3.dylib 0x31784000 - 0x31790fff springboardservices armv7 &lt;c78c28a259ad35ddb01512beb5fcea95&gt; /system/library/privateframeworks/springboardservices.framework/springboardservices 0x31795000 - 0x31832fff addressbookui armv7 &lt;e354aeb3d96e30338e90cc3638ffe81b&gt; /system/library/frameworks/addressbookui.framework/addressbookui 0x3183d000 - 0x31844fff libmobilegestalt.dylib armv7 &lt;55f29184efcc3046bb833dd72a4487e1&gt; /usr/lib/libmobilegestalt.dylib 0x31845000 - 0x31999fff audiotoolbox armv7 &lt;3b599e96ffe93b1ea2aa6026dee809dc&gt; /system/library/frameworks/audiotoolbox.framework/audiotoolbox 0x3199a000 - 0x3199ffff libcopyfile.dylib armv7 &lt;a19b1caf96c73568b14a1660f147ae2f&gt; /usr/lib/system/libcopyfile.dylib 0x319a0000 - 0x319f9fff eventkit armv7 &lt;0d4e597ee229337183e96e921a72e30a&gt; /system/library/frameworks/eventkit.framework/eventkit 0x319fa000 - 0x32002fff webcore armv7 &lt;9c7e4a156f6a381ea02f99ece48a46fe&gt; /system/library/privateframeworks/webcore.framework/webcore 0x32005000 - 0x32007fff crashreportersupport armv7 &lt;4d521bd4a1be3448a7d2bac1d09c5ff9&gt; /system/library/privateframeworks/crashreportersupport.framework/crashreportersupport 0x32008000 - 0x32017fff mobiledevicelink armv7 &lt;f258d39dc7d93faa9c9ff5cf81c5dcbd&gt; /system/library/privateframeworks/mobiledevicelink.framework/mobiledevicelink 0x32020000 - 0x32021fff libsystem_network.dylib armv7 &lt;39bf0f48bd8539169a77f8f61cdcd4c9&gt; /usr/lib/system/libsystem_network.dylib 0x320de000 - 0x320e3fff mobilekeybag armv7 &lt;8c35c090bc373cb181fc26b961b8dba5&gt; /system/library/privateframeworks/mobilekeybag.framework/mobilekeybag 0x3220b000 - 0x32214fff mobilewifi armv7 &lt;5b634ed28af339719e3c279224531ccb&gt; /system/library/privateframeworks/mobilewifi.framework/mobilewifi 0x32216000 - 0x3224afff videotoolbox armv7 &lt;aec2e22a2055380e82d4d0279faad0a7&gt; /system/library/privateframeworks/videotoolbox.framework/videotoolbox 0x32267000 - 0x3227cfff libresolv.9.dylib armv7 &lt;e92cfbb83f7b330db19181e797bb3f7b&gt; /usr/lib/libresolv.9.dylib 0x322b2000 - 0x323d3fff coregraphics armv7 &lt;54e27b8aa66c32b48ffeadadcc514331&gt; /system/library/frameworks/coregraphics.framework/coregraphics 0x323d4000 - 0x3241afff coretelephony armv7 &lt;2b9ebb05fdea38938dde802c8280b3ea&gt; /system/library/frameworks/coretelephony.framework/coretelephony 0x32426000 - 0x32428fff libgcc_s.1.dylib armv7 &lt;a2631ac302f4310dae8367939e16b7c2&gt; /usr/lib/libgcc_s.1.dylib 0x32450000 - 0x32450fff libcvmspluginsupport.dylib armv7 &lt;68322643de8030978c862de530055bd9&gt; /system/library/frameworks/opengles.framework/libcvmspluginsupport.dylib 0x325cb000 - 0x325dafff notes armv7 &lt;d9c976ca976e3d029f69febd48f17601&gt; /system/library/privateframeworks/notes.framework/notes 0x325dd000 - 0x325e8fff libz.1.dylib armv7 &lt;ac706bee36593dc683fd5a96a389d72e&gt; /usr/lib/libz.1.dylib 0x325eb000 - 0x3262efff managedconfiguration armv7 &lt;ffab9d7f5b5b315085783caf030932bf&gt; /system/library/privateframeworks/managedconfiguration.framework/managedconfiguration 0x3262f000 - 0x326d5fff celestial armv7 &lt;1d37083fe4253a2fb271c0ca0a42e283&gt; /system/library/privateframeworks/celestial.framework/celestial 0x326dd000 - 0x326e0fff applepushservice armv7 &lt;015c68c15621348db9f6a012499170e1&gt; /system/library/privateframeworks/applepushservice.framework/applepushservice 0x32758000 - 0x32765fff libbsm.0.dylib armv7 &lt;0a1e2bb78d5138419ecad8ba0fe42fdd&gt; /usr/lib/libbsm.0.dylib 0x32766000 - 0x327adfff messageui armv7 &lt;35a81f5d4eb03467a1447db80337e570&gt; /system/library/frameworks/messageui.framework/messageui 0x327be000 - 0x328c6fff coredata armv7 &lt;9843a401dd1d322383e3e40021cc8b95&gt; /system/library/frameworks/coredata.framework/coredata 0x328ee000 - 0x328f3fff libsystem_dnssd.dylib armv7 &lt;1eaf25ddd98e3a249bca536671c5819d&gt; /usr/lib/system/libsystem_dnssd.dylib 0x328f4000 - 0x32901fff libdispatch.dylib armv7 &lt;6c4eeb08757b365f8429ef6747f89ad3&gt; /usr/lib/system/libdispatch.dylib 0x32907000 - 0x32a26fff foundation armv7 &lt;60d1a3b3937c3c7ab21d701fb337346c&gt; /system/library/frameworks/foundation.framework/foundation 0x32a36000 - 0x32a36fff veclib armv7 &lt;0c60cd0a60f43d2791d36cb357d30e3c&gt; /system/library/frameworks/accelerate.framework/frameworks/veclib.framework/veclib 0x32a6b000 - 0x32a6cfff datamigration armv7 &lt;42e9e87a4e0735c3837e27d4f2adcf55&gt; /system/library/privateframeworks/datamigration.framework/datamigration 0x32c22000 - 0x32c42fff printkit armv7 &lt;e5a01ca9083a36afacc08611a398e2ad&gt; /system/library/privateframeworks/printkit.framework/printkit 0x32c71000 - 0x32ca0fff systemconfiguration armv7 &lt;1d73b8a159363f96bb9c039655c5eae6&gt; /system/library/frameworks/systemconfiguration.framework/systemconfiguration 0x32ca1000 - 0x32d86fff corefoundation armv7 &lt;4f643539f91f330790f112ea7150b3a8&gt; /system/library/frameworks/corefoundation.framework/corefoundation 0x32fab000 - 0x33040fff imageio armv7 &lt;d520e3241d1130e8ac1375ee0f2c1095&gt; /system/library/frameworks/imageio.framework/imageio 0x33046000 - 0x33049fff iosurface armv7 &lt;ad50e71624583d06b891344d832f9b08&gt; /system/library/privateframeworks/iosurface.framework/iosurface 0x33137000 - 0x3313dfff protocolbuffer armv7 &lt;c9798b4dd29335248000d698dea938bd&gt; /system/library/privateframeworks/protocolbuffer.framework/protocolbuffer 0x34bf1000 - 0x34c60fff proofreader armv7 &lt;6d843c6aecdd37ae84baa40af8ad7e65&gt; /system/library/privateframeworks/proofreader.framework/proofreader 0x34d02000 - 0x34d39fff security armv7 &lt;163414ba17df347ca76088015010e2c4&gt; /system/library/frameworks/security.framework/security 0x34d56000 - 0x34d92fff libglimage.dylib armv7 &lt;79d00adb09de3da991ed21f48f27adb4&gt; /system/library/frameworks/opengles.framework/libglimage.dylib 0x34d9b000 - 0x34d9bfff accelerate armv7 &lt;7d5ad465049136afaa1f0d89aac600bc&gt; /system/library/frameworks/accelerate.framework/accelerate 0x34dac000 - 0x34df6fff libstdc++.6.dylib armv7 &lt;b2cac408951c3f3c9ba3cf563e54ce81&gt; /usr/lib/libstdc++.6.dylib 0x34e23000 - 0x34e27fff libcache.dylib armv7 &lt;36e96d0a7dda330281a43172d0ada49a&gt; /usr/lib/system/libcache.dylib 0x34e2d000 - 0x34e3dfff webbookmarks armv7 &lt;6956561235333e74b8ff316cb2edc93e&gt; /system/library/privateframeworks/webbookmarks.framework/webbookmarks 0x3532c000 - 0x35446fff libicucore.a.dylib armv7 &lt;bada0c2725bb31a483d5adf9aaf1f8df&gt; /usr/lib/libicucore.a.dylib 0x3549e000 - 0x354f3fff libvdsp.dylib armv7 &lt;0221caba81a235c5a896a835e2aac047&gt; /system/library/frameworks/accelerate.framework/frameworks/veclib.framework/libvdsp.dylib 0x35667000 - 0x3569ffff libcgfreetype.a.dylib armv7 &lt;ccea634795153164a681f0f311f4461d&gt; /system/library/frameworks/coregraphics.framework/resources/libcgfreetype.a.dylib 0x356b9000 - 0x357bdfff javascriptcore armv7 &lt;f63386018d703534b766514e4bbbd1d8&gt; /system/library/privateframeworks/javascriptcore.framework/javascriptcore 0x357be000 - 0x357cefff dataaccessexpress armv7 &lt;66d9047da79a31daa887e6d84c42ecb2&gt; /system/library/privateframeworks/dataaccessexpress.framework/dataaccessexpress 0x357cf000 - 0x357d1fff iomobileframebuffer armv7 &lt;de8392b1117135e592a16e1cb6d26af5&gt; /system/library/privateframeworks/iomobileframebuffer.framework/iomobileframebuffer 0x35a0e000 - 0x35a41fff icalendar armv7 &lt;e52c54abaab734e8b0278f358217c4b5&gt; /system/library/privateframeworks/icalendar.framework/icalendar 0x35a42000 - 0x35a5ffff libsystem_info.dylib armv7 &lt;48016be86e3f3cd9aeee1c6590e1ac6f&gt; /usr/lib/system/libsystem_info.dylib 0x35a60000 - 0x35aaefff gmm armv7 &lt;03cb1e098c4932e58b0933dfc58f9116&gt; /system/library/privateframeworks/gmm.framework/gmm 0x35ab8000 - 0x35d9ffff liblapack.dylib armv7 &lt;652c97e211553d4e84968a61f62a0ac5&gt; /system/library/frameworks/accelerate.framework/frameworks/veclib.framework/liblapack.dylib 0x35da1000 - 0x35da2fff libdyld.dylib armv7 &lt;41a7b5e5d9983449ab33affed0f635ad&gt; /usr/lib/system/libdyld.dylib 0x35dba000 - 0x35dbafff libsystem_sandbox.dylib armv7 &lt;f47c01d627853b328e088b3fdd08e87d&gt; /usr/lib/system/libsystem_sandbox.dylib 0x35dbb000 - 0x35e02fff corelocation armv7 &lt;565c18af7dfc3c92a63cc4c249913650&gt; /system/library/frameworks/corelocation.framework/corelocation 0x35e65000 - 0x35e7bfff eap8021x armv7 &lt;b755ecad7b6a3009a5f4a0fdc5f9bdd7&gt; /system/library/privateframeworks/eap8021x.framework/eap8021x 0x35e80000 - 0x35ea9fff contentindex armv7 &lt;f5a3613ec5b6392995d7ed0742f7419f&gt; /system/library/privateframeworks/contentindex.framework/contentindex 0x35ebb000 - 0x35ef0fff addressbook armv7 &lt;64500984cfb13a098c3c687c37a80fff&gt; /system/library/frameworks/addressbook.framework/addressbook 0x35ef1000 - 0x3627efff uikit armv7 &lt;bc8d14fa59e136b6a28ac025384daf08&gt; /system/library/frameworks/uikit.framework/uikit 0x362d1000 - 0x3630efff coretext armv7 &lt;fb6a72faec2330c4b2cd33c2e9c59588&gt; /system/library/frameworks/coretext.framework/coretext 0x36310000 - 0x36315fff liblaunch.dylib armv7 &lt;f5ccc8234aea3ebd9a88bd37f0fa23ae&gt; /usr/lib/system/liblaunch.dylib 0x36316000 - 0x3631ffff corevideo armv7 &lt;ea847e6dba2d36b1826b255c73b39539&gt; /system/library/frameworks/corevideo.framework/corevideo 0x36320000 - 0x36327fff aggregatedictionary armv7 &lt;ab9777b39e8e3026ad64dc90323cad7e&gt; /system/library/privateframeworks/aggregatedictionary.framework/aggregatedictionary 0x36328000 - 0x36356fff dataaccess armv7 &lt;3a2e67aa1d8834b7a8fc2fbb56654b15&gt; /system/library/privateframeworks/dataaccess.framework/dataaccess 0x3671f000 - 0x36726fff libbz2.1.0.dylib armv7 &lt;0a082e1d475432959ba93aa3dbf7fb31&gt; /usr/lib/libbz2.1.0.dylib 0x3672e000 - 0x3673cfff opengles armv7 &lt;f02d1c50f0f33991adb1a2caed02eb77&gt; /system/library/frameworks/opengles.framework/opengles 0x36741000 - 0x36780fff libsystem.b.dylib armv7 &lt;b5735b0f3dba32c087c5b58aa48ae592&gt; /usr/lib/libsystem.b.dylib 0x36781000 - 0x36830fff quartzcore armv7 &lt;ef9632c9781f3101916b65e9faae1579&gt; /system/library/frameworks/quartzcore.framework/quartzcore 0x36831000 - 0x368f0fff cfnetwork armv7 &lt;84a2d312145e3dbf97aea052927dcdb9&gt; /system/library/frameworks/cfnetwork.framework/cfnetwork 0x3691c000 - 0x36945fff mobilecoreservices armv7 &lt;57fef84bdc17301d8bf53ba0fb967fe6&gt; /system/library/frameworks/mobilecoreservices.framework/mobilecoreservices 0x36946000 - 0x3695ffff librip.a.dylib armv7 &lt;4825c3e392983aba947eca06555e4480&gt; /system/library/frameworks/coregraphics.framework/resources/librip.a.dylib 0x36a37000 - 0x36a95fff libblas.dylib armv7 &lt;d3f7360687333cad987890c314ae0d6f&gt; /system/library/frameworks/accelerate.framework/frameworks/veclib.framework/libblas.dylib 0x36aad000 - 0x36aaefff libremovefile.dylib armv7 &lt;5f077c4d204d3cd7b04452c42d41f763&gt; /usr/lib/system/libremovefile.dylib 0x36ae6000 - 0x36b67fff libsystem_c.dylib armv7 &lt;caa1846ad2583d1b84c1a15c50c126a2&gt; /usr/lib/system/libsystem_c.dylib 0x36c62000 - 0x36d4ffff libiconv.2.dylib armv7 &lt;f4146ce07e3031ea8a81fa5516fd77d0&gt; /usr/lib/libiconv.2.dylib 0x36d55000 - 0x36d58fff certui armv7 &lt;9060fe03a4943ef295531feced9a17dd&gt; /system/library/privateframeworks/certui.framework/certui 0x36e81000 - 0x36e83fff mailservices armv7 &lt;adbbafb0ea513e00ae3c6ec8f0251410&gt; /system/library/privateframeworks/mailservices.framework/mailservices 0x36e84000 - 0x36ebcfff iokit armv7 &lt;80ae313ad69d3363935c88e51a11862d&gt; /system/library/frameworks/iokit.framework/versions/a/iokit 0x36ebd000 - 0x36f47fff message armv7 &lt;e2a583f640503bdba0eac23e7a919f84&gt; /system/library/privateframeworks/message.framework/message 0x36f7e000 - 0x37042fff libobjc.a.dylib armv7 &lt;f855251d90a53bdbb5d5a39fdbde6d9b&gt; /usr/lib/libobjc.a.dylib 0x37048000 - 0x37088fff coremedia armv7 &lt;66ee3ed5265f3d49a274dc9a07d27d52&gt; /system/library/frameworks/coremedia.framework/coremedia 0x3709a000 - 0x370bafff mobilesync armv7 &lt;4df400c4559435889eccd88db77a110c&gt; /system/library/privateframeworks/mobilesync.framework/mobilesync 0x3711a000 - 0x3711cfff libaccessibility.dylib armv7 &lt;d55f1553d14831a2a5435ae27ef75ef4&gt; /usr/lib/libaccessibility.dylib 0x37139000 - 0x371eafff webkit armv7 &lt;8f2fd63295d83121b1db9097938ad31f&gt; /system/library/privateframeworks/webkit.framework/webkit 0x371eb000 - 0x37294fff libxml2.2.dylib armv7 &lt;5538d3f2c7d83b88b06168488fe6326b&gt; /usr/lib/libxml2.2.dylib 0x37295000 - 0x3729bfff liblockdown.dylib armv7 &lt;14c89b7346433c1f8675f454531f6ca3&gt; /usr/lib/liblockdown.dylib 0x3731d000 - 0x37469fff mediatoolbox armv7 &lt;46c1dd5571de3f7dae97dcde85ca933c&gt; /system/library/privateframeworks/mediatoolbox.framework/mediatoolbox 0x3759b000 - 0x375aefff libmis.dylib armv7 &lt;529ea6e3a87230ce9f6cf3285c22429c&gt; /usr/lib/libmis.dylib 0x375af000 - 0x375fcfff coremotion armv7 &lt;e0349aa7dd1c3454a970ea1939279801&gt; /system/library/frameworks/coremotion.framework/coremotion 0x37614000 - 0x37626fff persistentconnection armv7 &lt;6d30b5ef735f36a79cfc82c9b6606db9&gt; /system/library/privateframeworks/persistentconnection.framework/persistentconnection </code></pre>,iphone
what does it mean by having 2 equal classes <pre><code> public boolean isafraidof(animal animal) { //compare the class of this animal to bird if (animal.getclass() == bird.class) { return false; } else { return true; } </code></pre> <strong>animal is the super class and bird is the subclass i need to know the differentiator on which they compare the two classes and thanks in advance</strong>,java
the this keyword in a function i have a function in javascript: <pre><code>function main() { console.log(this); } </code></pre> how come this logs <code>document</code> surely it should log <code>function main</code> if not then how do i declare a variable within <code>main</code> to be accessed by the rest of the code as <code>main.varname</code> thank you!,javascript
break outside of loop when in loop my script returns an error saying <code>break</code> is outside of a loop when the <code>break</code> is inside an if statement. why how do i fix this writing a script out of a book <pre><code>if hook_address: hooks.add(dbg hook_address 2 ssl_sniff none) print [*] nspr4.pr_write hooked at: 0x%o8x %hook_address break else: print [!] error: couldn t resolve hook address! sys.exit(-1) </code></pre> <blockquote> c:\0xic-zex\python> file c:\0xic-zex\python\ line 32 break syntaxerror: break outside loop </blockquote> whats wrong my <code>break</code> is in the <code>if</code> loop.,python
is it acceptable if actual and formal parameters have the same name like this: <pre><code>mymethod(first second) public void mymethod(int first int second) </code></pre> my teacher said it s preferred not to name them the same. but i don t see the reason why is he wrong,java
java input and out put hi my code should do this instruction below but am not getting it at all <strong>the user can enter as many positive floating-point numbers on the console as desired. zero (or a negative numbers) signals end of input (no more numbers can be entered). after input the program displays  the smallest number entered (min)  the largest number entered (max)  the mean of all numbers entered (mean) do not use arrays for this assignment even if you know them.</strong> sample should look like this <blockquote> enter numbers: \n 1 2 3 4 5 6 0 \n numbers entered: 6 \n minimum: 1.00 \n maximum:6.00 \n mean: 3.50\n enter numbers: \n 0 \n no number entered. </blockquote> <pre><code>public class loopstatistics { public static void main(string[] args) { double max min sum=0 input mean=0; int counter = 0; textio.putln( enter numbers: ); do { input = textio.getdouble(); min = input; max = input; counter++; if (input &gt; max) max = input; if ( input &lt; min) min = input; sum = sum + input; } while( input != 0); mean = sum / counter; textio.putf( numbers entered:%d\n counter); textio.putf( minimum:%f\n min); textio.putf( maximum:%f\n max); textio.putf( mean:%f mean); } } </code></pre>,java
default parseint radix to 10 one of the bad parts of javascript is that if you use parseint with something that begins with 0 then it could see the number as a octal. <pre><code>i = parseint(014); // answer: 12 </code></pre> q: how can i redefine parseint so that it defaults to radix 10 i m assuming you would use the prototype method. edit: maybe i should do this: <pre><code>$.fn.extend({ parseint:function(x) { return parseint(x 10); } }); </code></pre>,javascript
assigning image views to background image of button i am trying to combine two image views and put them into another image view which i am assigning to background image of a button.somehow this is not working.could someone please check and let me know what exactly is wrong here. <pre><code> uiimageview * image1 = [[uiimageview alloc] initwithimage:[uiimage imagenamed:@ homesmall.png ]]; uiimageview * image2 = [[uiimageview alloc] initwithimage:[uiimage imagenamed:@ update.png ]]; [image1 setframe:cgrectmake(16 0 16 16)]; [image2 setframe:cgrectmake(0 0 16 16)]; uiimageview *cellacc = [[uiimageview alloc] initwithframe:cgrectmake(0 0 32 16)]; [cellacc addsubview:image1]; [cellacc addsubview:image2]; uiimage *image = [cellacc image]; uibutton *button = [uibutton buttonwithtype:uibuttontypecustom]; cgrect frame = cgrectmake(0.0 0.0 image.size.width image.size.height); button.frame = frame; [button setbackgroundimage:image forstate:uicontrolstatenormal]; </code></pre>,iphone
how to write values in a properties file through java code i have an issue. i have a properties file. i want to store some values in that file and will implement in the code whenever it is required. is there any way to do that i am using <code>properties</code> class to do that..,java
convert image obtained from url into inputstream. then read that inputstream to convert it into image & display on my jsp <pre><code>package imagebyte; import java.awt.image.bufferedimage; import; import; import; import; import; import; import java.util.iterator; import javax.imageio.imageio; import javax.imageio.imagereader; import; public class imagebyte { // private static final logger log = logger.getlogger(imagebyte.class); public static void main(string args[]) throws malformedurlexception ioexception { getimageandtypefrominputstream(); } public static byte[] getimageandtypefrominputstream() throws malformedurlexception ioexception { string format = null; bufferedimage bufferedimage = null; inputstream input = null; urlconnection openconnection = new url( ).openconnection(); openconnection.addrequestproperty( user-agent mozilla/5.0 (windows nt 6.3; win64; x64) applewebkit/537.36 (khtml like gecko) chrome/61.0.3163.100 safari/537.36 ); input = openconnection.getinputstream(); system.out.println( input : + input.tostring()); system.out.println( input : + input.getclass()); sys