w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Python - abstracting a recursion to all nth level recursion (lxml)
I would suggest using a recursive algorithm which takes a list of the 2 items to compare, and the pass number, as arguments. You would need a dictionary specifying which list to supply on each pass. You could also write an algorithm to create the dictionary of n elements, hope this helps. I could try and give example code if that'd be more helpful. EDIT: n=3 ##Depth of tree d={'0':['a.root', 'b.root', 0]} for i in range(n): d[str(i+1)]=[d[str(i)][0]+'['+chr(105+i)+']', #since ord('i')=105, start d[str(i)][1]+'['+chr(105+i)+']', # at i, j, k, etc i+1 #passNo ] print(d) def compare(points=d['0'], passNo=0): if xml.xml_compare(eval(points[0]), eval(points[1])) == False: exec('for'+str(chr(poin

Categories : Python

How can I implement this equation in python?
Before implementing your own statistical stuff, have you looked into SciPy? SciPy Stats has many modules implemented using NumPy (C written, so it's faster than Python, but callable from Python, with a Pythonic syntax). So maybe you don't need to write any code yourself.

Categories : Python

Solving equation in Python 3.3
Y, C, m, and d are all strings. You want to convert them into ints first: Y = int(f[2:4]) C = int(f[:2]) ... Are you sure that equation even works, though? It looks like it'd produce a lot of non-integer weekdays. You might've miscopied it. Also, brackets aren't a grouping operator in Python; they're the list construction syntax. You'll want to replace those brackets with parentheses in the expression for w. (Or were those brackets supposed to be the floor operator? If so, you'll want math.floor, from the math module, or just int if truncation is fine.)

Categories : Python

Wrong answer with equation in python
Integer division. 4/3 evaluates to 1 as it is rounded down. Use 4.0 instead to force floating point arithmetic: >>> 4.0/3 * 6.67*1e-11*3.14*6378000*5515 9.822550047279998 or use Python 3, where floating point division is the default, or use from __future__ import division to achieve the same in Python 2: Python 2.7.5 (default, May 22 2013, 12:00:45) [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from __future__ import division >>> 4/3 * 6.67*1e-11*3.14*6378000*5515 9.822550047279998 This behaviour is documented under the Binary arithmetic operators section: The / (division) and // (floor division) operators yield the quotient of their arguments.

Categories : Python

Python suds "RuntimeError: maximum recursion depth exceeded while calling a Python object"
After more testing, it seems that (unfortunately) suds has trouble interpreting Java Collection objects serialized as XML. I ended up using SOAPpy instead to avoid this issue. If someone can suggest a fix, that would be awesome! I really like suds for its other merits over SOAPpy.

Categories : Python

How Do i Properly execute a for loop?
The problem is as Selvin states above. "~1~2".split("~") eq new String[] { "", "1", "2" } not eq new String[] { "1", "2" } A way of getting around this is by using a List and removing all the elements in the List which are blank i.e. "" List<String>tokens = new ArrayList(Arrays.asList(user_comments.split("~~~"))); tokens.removeAll(Arrays.asList("")); Your for loop will be as follows: for(int k = 0; k < tokens.size(); k++ ) { String[] one_comment = tokens.get(k).split("#=#"); map.put("Avatar", one_comment[0]); Log.e("Avatar", one_comment[0].toString()); map.put("Name",one_comment[1] ); Log.e("Name", one_comment[1].toString()); map.put("Comment",one_comment[2] ); Log.e("Comment", one_comment[2].toString()); map.put("CommentDate",o

Categories : Java

gcc compiler in cygwin does not execute properly (gives up?)
You have various options. The problem is the wrong /usr/local/bin/cygz.dll Either delete your rogue /usr/local/bin/cygz.dll (preferred), or fix you PATH $ export PATH=/usr/bin:/usr/local/bin:/cygdrive/c/WINDOWS/system32:/cygdrive/c/WINDOWS Explanation: On windows the library search path has . before $PATH. So when you are in /bin the right cygz.dll will be found. Otherwise the broken one from your path will be found first.

Categories : C

Im making a quadratic equation solver with python and easygui but i cant enter negative numbers. Is there any way around this
Try changing the default parameters of the function integerbox when you call it. Specifically, the one you'll want to change to allow negative numbers is lowerbound. Here is the full definition of integerbox so you can see all the parameters. integerbox(msg='', title=' ', default='', lowerbound=0, upperbound=99, image=None, root=None, **invalidKeywordArguments) The minimum value for an integer on any platform can be accessed through the following method: import sys a=eg.integerbox(msg='enter a', lowerbound = -sys.maxint - 1) The upperbound for an int can be accessed through sys.maxint.

Categories : Python

Python Recursion within Class
Each method of a class has to have self as a first parameter, i.e. do this: def recur(self, num): and it should work now. Basically what happens behind the scene is when you do instance.method(arg1, arg2, arg3, ...) Python does method(instance, arg1, arg2, arg3, ....)

Categories : Python

Understanding cmp in python and recursion
Where two names reference the same object, they are equal by definition (edit: at least as far as cmp is concerned, where "equal" really means "neither greater than nor less than").

Categories : Python

Recursion not working in python
Your function doesn't return the recursive call: if n > 3: robLan(n -1) * robLan(n - 2) Without a return statement here, your function ends without an explicit return and None is returned instead: >>> robLan(4) is None True The above should have returned 4 (roblan(3) * roblan(2) gives 2 * 2 is 4). For any starting value of 5 or over the function uses more than one level of recursion and a None return value ends up being used for multiplication. Add return: if n > 3: return robLan(n - 1) * robLan(n - 2) Your statements can be simplified: def robLan(n): if n > 2: return robLan(n - 1) * robLan(n - 2) return n Your sample loop then generates: [1, 2, 2, 4, 8, 32, 256, 8192, 2097152]

Categories : Python

counting iterations in recursion python
def recursive_thing(calls=1): # "calls" argument keeps track of recursion depth if keep_recursing(): # pass a higher count to the recursive call recursive_thing(calls + 1) else: print calls return Give your function an argument that keeps track of the recursion depth, or put the recursion in a helper function with such an argument.

Categories : Python

Global variables in recursion. Python
count in lenRecur is not a global. It is a scoped variable. You'll need to use Python 3 before you can make that work in this way; you are looking for the nonlocal statement added to Python 3. In Python 2, you can work around this limitation by using a mutable (such as a list) for count instead: def lenRecur(s): count = [0] # ... def leng(s): if len(s)==0: return count[0] else: count[0] += 1 return lenIter(s[1:]) Now you are no longer altering the count name itself; it remains unchanged, it keeps referring to the same list. All you are doing is altering the first element contained in the count list. An alternative 'spelling' would be to make count a function attribute: def lenRecur(s): # ... def leng(s):

Categories : Python

Recursion in Python with Beautiful Soup
You do not get the content of the page. BeautifulSoup won't retrieve the html content for you, you have to retrieve it yourself. You should pass the content of the page or the file object to BeautifulSoup: import urllib2 f = urllib2.urlopen(new_link) soup = BeautifulSoup(f) # or soup = BeautifulSoup(f.read())

Categories : Python

Python recursion with compound interest
I assume you're doing it recursively as a programming exercise - it can also be done with Maths™. It looks to me like you're not calling compound_interest_recursive() anywhere recursively. Recursion is (and I'm simplifying a little here) a call to a function from within itself. Looks to me like you just want this: def compound_interest_recursive(principal, rate, years): if years == 0: return principal else: return compound_interest_recursive(principal * rate, rate, years-1) This code assumes that rate is expressed as a ratio - for example, 15% would be 1.15. This is the coding equivalent of the following statements: The compound after zero years is the same as the principal. The compound interest after N years is the compound interest after N-1 years multip

Categories : Python

outvariable scope and recursion in python
I believe the issue you're having is due to using a global variable for current_id. When you create a child in the recursive call, current_id gets updated for the parent's call too. Here's a simpler example: x = 0 def foo(level=0): global x print(" "*level+str(x)) x += 1 if level < 3: foo(level+1) print(" "*level+str(x)) foo() This will print: 0 1 2 3 4 4 4 4 The indentation indicates the level of recursion, thanks to the level parameter. The value of x gets increased by each recursive call, but it doesn't go back down when the calls unwind. That's because it's a global variable, so the changes made by the inner levels of recursion are seen by the outer levels. In your code, you can fix this by keeping a reference to the o

Categories : Python

Howto have maven surefire execute JUnit and TestNG test properly?
I haven't done it myself, but you could try to configure two different executions of the maven-surefire-plugin and configure one of these executions to only run JUnit tests and the other to only run testNG tests. To differentiate between JUnit und testNG tests you should either put the tests in different directories or use a distinguishable name scheme and configure each of the executions with suitable inclusion and exclusion patterns. In theory this should work :)

Categories : Java

Finding a Node in a Tree using recursion in python
I think the immediate fix would be to change this for node in self.children: return node.find(person) To this for node in self.children: res = node.find(person) if res is not None: return res

Categories : Python

Python suds - Recursion error in wsdl.py
I am the developer working on the other side of this web service. There was indeed a circular reference in the WSDL. I have since fixed that issue and Mike is no longer seeing the recursion error. On my side, the service is being built on the .NET framework using WCF. The issue was due to my attempt to get rid of the http://tempuri.org namespace in the WSDL. I had added the correct Namespace to the ServiceContract, DataContract, and ServiceBehavior attributes on the appropriate service classes, but did not know about the bindingNamespace configuration value on the server endpoint element. This caused Visual Studio to generate two WSDL files which referenced eachother, one for the elements belonging in the correct namespace and one for the binding information which was in the tempuri.

Categories : Python

for loop creates & labels button properly, but doesnt execute proper command
You are always calling the command with the variable 'attr', not with the contents of attr. The quick fix is : pm.button(label=attr, command='createRamp("%s")' % attr) which will make the button use the correct string. The right thing to do in the long term is not to use strings when calling button callbacks - this will probably run into issues if you execute it outside the listener or from another script because it will no longer know what 'attr' means when the callback fires. Some related discussions: http://tech-artists.org/forum/showthread.php?2861-Seeing-root-space-python-instances-from-another-class-instance&highlight=callback http://tech-artists.org/forum/showthread.php?3205-why-scriptJob-doesnt-work-in-case-of-attrControlGrp&highlight=callback http://tech-artists.

Categories : Misc

Change color based on recursion depth Python Turtle
try this. from turtle import * colors = ['green', 'red'] def drawzig2(depth,size): if depth == 0: pass elif depth: pencolor(colors[depth % len(colors)]) left(90) fd(size/2) right(90) fd(size) left(45) drawzig2(depth-1,size/2) right(45) fd(-size) left(90) fd(-size) right(90) fd(-size) left(45) drawzig2(depth-1,size/2) right(45) fd(size) left(90) fd(size/2) right(90) drawzig2(4,100)

Categories : Python

Python - quick sort - maximum recursion depth exceeded
this = lower = upper = [] Assignment never creates copies in Python. This line doesn't create 3 lists; it creates 1 list, and makes this, lower, and upper all refer to that list. Make 3 lists. this = [] lower = [] upper = []

Categories : Python

recursion print error nested dict() object in python
In the for loop, it seems like you're using the name node for two different things: for key in node: print(key,":",node.get(key)) node = node.get(key) print_rec(node) When in the first iteration, you change the value of node. In the second iteration, when you do node.get(key), you're using the new node, but you want to be using the original node. This should help: for key in node: print(key,":",node.get(key)) successor = node.get(key) print_rec(successor) It can be written even more concisely like this: for key, successor in node.items(): print(key,":",successor) print_rec(successor)

Categories : Python

Python Import Statement and Recursion- need function available in module namespace
The easy answer is move foo() to foo.py and import from there or move it to create.py and import it from there into main.py - if there are things in main.py that it needs the move the too. Your other option is to pass foo from main into create as a function parameter where it is needed.

Categories : Python

An asyncTask launched from an onPostExecute of another AsyncTask does not execute properly in API 10
The solution is simple, in the postExecute of DownloadDataAsyncTask, simple do this: @Override protected void onPostExecute(final JSONObject[] result) { if (result[0] != null && result[1] != null) { runOnUiThread(new Runnable() { @Override public void run() { new UpdateDbAsyncTask().execute(result[0], result[1]); } }); } else { displayFailureToast(); } }

Categories : Android

Can't execute python script from php
Your problem is this: When launching the php script through the console, you are launching php with the permissions of your current user. When a process is executed through opening it in the browser, it will have the permissions of the user of your web-server-process. Your group permissions will have to be 7 no matter what. Either change the python scripts permissions to 777 (read-write-execute for everybody) or change it to 770 and make sure that your web-servers user is inside the group set to the file.

Categories : PHP

Python: Why does this code execute?
This is the output I get: 1 2 2 1 3 0 4 -1 5 -2 6 -3 7 -4 8 -5 9 -6 10 -7 Your question as to why it runs. Your outer most conditional is a while loop, which is true upon the first execution, however it runs right into a nested for loop. When this happens the while, will not be checked until the for loop finishes its first execution (which is why p = -7). What you want is this: p = 2 for i in range(10): if p <= 0: break print i+1 , p p-=1 which gives output: 1 2 2 1

Categories : Python

execute main through if condition in python
Make it an independent function. def run_main(): .... if __name__ == "__main__": run_main() And you can call run_main() from another file.

Categories : Python

Execute python in a php script using shell_exec()
I think kernel not able to find the path for python where it is installed..if you can do echo $PATH..it will show all the paths where to be search a command if given add your python part there and then it may work or you can give absolute path(other than /usr/bin/) see if it works..I need to test it too.

Categories : PHP

How to execute awk command by python code
While I agree that this is actually best done in Python, rather than invoking awk. If you really need to do this, then the actual error is with your awk. #!/usr/bin/env python import subprocess as sp args = ["awk", r'{OFS=" "; print $2,$4,$5,$6}', "B3LYPD.txt"] p = sp.Popen(args, stdin = sp.PIPE, stdout = sp.PIPE, stderr = sp.PIPE ) print(p.readline()) # will give you the first line of the awk output Edit: Fixed missing quote.

Categories : Python

Execute .sql schema in psycopg2 in Python
You can just use execute: with self.connection as cursor: cursor.execute(open("schema.sql", "r").read()) though you may want to set psycopg2 to autocommit mode first so you can use the script's own transaction management. It'd be nice if psycopg2 offered a smarter mode where it read the file in a statement-at-a-time and sent it to the DB, but at present there's no such mode as far as I know. It'd need a fairly solid parser to do it correctly when faced with $$ quoting (and its $delimiter$ variant where the deimiter may be any identifier), standard_conforming_strings, nested function bodies, etc. Note that this will not work with: anything containing psql backslash commands COPY .. FROM STDIN ... and therefore won't work with dumps from pg_dump

Categories : Python

Python: rasing from except causes finally to execute?
finally is executed no matter the try block succeeds or the except block is run due to exceptions! even if your except block raises an exception the new exception will be handled by another try catch handler but after executing the finally block, instead of forming a recursive loop: try: try: [...] except: raise Exception([...]) #this is line number xyz finally: [code] except: [...] #this code will be running after line number xyz

Categories : Python

How to execute commands through pipe in Python?
Piping is a shell function. Therefore your Popen call needs shell=True on it. Otherwise your | wc is going to be passed to find, which won't know what to do with it (and is probably sending an error to that effect into err... which you're not printing). But why shell out at all? Just do all that stuff in Python (e.g. os.walk to replace find) It'll be easier to read and maintain. Something like: import os, re for dirpath, dirnames, filenames in os.walk(rootpath): for filename in filenames: if filename.endswith(".cc"): with open(os.path.join(dirpath, filename)) as infile: text = infile.read() chars = len(text) lines = sum(1 for x in re.finditer(r" ", text)) lines += not text.endswith(" ") # count last

Categories : Python

Execute python script in localhost
Google App Engine SDK for Python includes a local web server application that simulates the App Engine environment. It allows for instant server script changes by just saving the file and refreshing the browser. The development tutorial is here Once you have your web site working locally, it is easy to deploy it live on Google's App Engine servers.

Categories : Python

return statement doesnt return anything in python recursion
Here: find_and_remove_functions( string[ function_end + 1: ], found_functions ) should be return find_and_remove_functions( string[ function_end + 1: ], found_functions )

Categories : Python

How to execute code when a Python script is closed out?
import MySQLdb con = MySQLdb.connect(...) cursor = con.cursor() try: # do stuff with your DB finally: con.close() The finally clause is executed on success as well as on error (exception). If you hit Ctrl-C, you get a KeyboardInterrupt exception.

Categories : Python

In Python, how do you execute objects that are functions from a list?
Make all of them lists and then iterate over the list executing each in turn. for actionVal,actionDesc,actionFunctions in validActions: if ctx["newAction"] == actionVal: for actionFunction in actionFunctions: actionFunction()

Categories : Python

Execute python script using urllib2 from PHP behind Proxy
You could try passing explicit proxy settings to your Python script to see if that clears up the problem for you. I recently wrote a script that allows you to set proxy settings with command line arguments that might be useful for this case. The important parts of the script are below: # Import the required libraries from urllib import urlencode from urllib2 import Request, urlopen, URLError, ProxyHandler, build_opener, install_opener import argparse # Set up our argument parser parser = argparse.ArgumentParser(description='Does stuff through a proxy') parser.add_argument('webAddr', type=str, help='Web address of target server') parser.add_argument('--proxServ', metavar='SERV', type=str, help='Web address of proxy server, i.e. http://proxy.server.com:80') parser.add_argument('--proxType'

Categories : PHP

crontab: python script being run but does not execute OS Commands
Two things: Your cd will set the directory for that subprocess, which immediately exits: subprocess.call(["cd", "/home/atweb/Documents/opengrok"]) In other words, it's a wasted step. The next subprocess doesn't know anything about the previous one's environment: subprocess.call(["./stop_website"]) ...so it won't be able to run. If you want all of your programs to run in that directory, use: os.chdir("/home/atweb/Documents/opengrok") before any of the subprocess.call() lines.

Categories : Python

Execute Shell Script from python with variable
Like this ? subprocess.call(['test.sh', str(domid)]) Documentation is available on the python website

Categories : Python



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.