title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
profiling a method of a class in Python using cProfile?
4,492,535
19
2010-12-20T18:14:57Z
4,492,582
22
2010-12-20T18:20:03Z
[ "python", "profiler", "cprofile" ]
I'd like to profile a method of a function in Python, using cProfile. I tried the following: ``` import cProfile as profile # inside class method... profile.run("self.myMethod()", "output_file") ``` but it does not work. How can I call a self.method with "run"? Thanks.
EDIT: Sorry, didn't realise that the profile call was *in* a class method. `run` just tries to `exec` the string you pass it. If `self` isn't bound to anything in the scope of the profiler you are using, you can't use it in `run`! Use the [`runctx`](http://docs.python.org/library/profile.html#cProfile.runctx) method t...
profiling a method of a class in Python using cProfile?
4,492,535
19
2010-12-20T18:14:57Z
4,492,596
19
2010-12-20T18:21:18Z
[ "python", "profiler", "cprofile" ]
I'd like to profile a method of a function in Python, using cProfile. I tried the following: ``` import cProfile as profile # inside class method... profile.run("self.myMethod()", "output_file") ``` but it does not work. How can I call a self.method with "run"? Thanks.
Use the profilehooks decorator <http://pypi.python.org/pypi/profilehooks>
Python code to get current function into a variable?
4,492,559
27
2010-12-20T18:17:20Z
4,492,643
12
2010-12-20T18:27:58Z
[ "python", "function", "introspection" ]
How can I get a variable that contains the currently executing function in Python? I don't want the function's name. I know I can use `inspect.stack` to get the current function name. I want the actual callable object. Can this be done without using `inspect.stack` to retrieve the function's name and then `eval`ing the...
I recently spent a lot of time trying to do something like this and ended up walking away from it. There's a lot of corner cases. If you just want the lowest level of the call stack, you can just reference the name that is used in the `def` statement. This will be bound to the function that you want through lexical cl...
Python code to get current function into a variable?
4,492,559
27
2010-12-20T18:17:20Z
4,493,322
13
2010-12-20T19:53:04Z
[ "python", "function", "introspection" ]
How can I get a variable that contains the currently executing function in Python? I don't want the function's name. I know I can use `inspect.stack` to get the current function name. I want the actual callable object. Can this be done without using `inspect.stack` to retrieve the function's name and then `eval`ing the...
This is what you asked for, as close as I can come. Tested in python versions 2.4, 2.6, 3.0. ``` #!/usr/bin/python def getfunc(): from inspect import currentframe, getframeinfo caller = currentframe().f_back func_name = getframeinfo(caller)[2] caller = caller.f_back from pprint import pprint fu...
Python code to get current function into a variable?
4,492,559
27
2010-12-20T18:17:20Z
4,506,081
23
2010-12-22T04:09:27Z
[ "python", "function", "introspection" ]
How can I get a variable that contains the currently executing function in Python? I don't want the function's name. I know I can use `inspect.stack` to get the current function name. I want the actual callable object. Can this be done without using `inspect.stack` to retrieve the function's name and then `eval`ing the...
The stack frame tells us what code object we're in. If we can find a function object that refers to that code object in its `func_code` attribute, we have found the function. Fortunately, we can ask the garbage collector which objects hold a reference to our code object, and sift through those, rather than having to t...
Python code to get current function into a variable?
4,492,559
27
2010-12-20T18:17:20Z
4,511,884
7
2010-12-22T17:31:49Z
[ "python", "function", "introspection" ]
How can I get a variable that contains the currently executing function in Python? I don't want the function's name. I know I can use `inspect.stack` to get the current function name. I want the actual callable object. Can this be done without using `inspect.stack` to retrieve the function's name and then `eval`ing the...
Here's another possibility: a decorator that implicitly passes a reference to the called function as the first argument (similar to `self` in bound instance methods). You have to decorate each function that you want to receive such a reference, but "explicit is better than implicit" as they say. Of course, it has all ...
SqlAlchemy equivalent of pyodbc connect string using FreeTDS
4,493,614
14
2010-12-20T20:28:22Z
4,493,770
15
2010-12-20T20:43:34Z
[ "python", "sql-server", "sqlalchemy", "pyodbc", "freetds" ]
The following works: ``` import pyodbc pyodbc.connect('DRIVER={FreeTDS};Server=my.db.server;Database=mydb;UID=myuser;PWD=mypwd;TDS_Version=8.0;Port=1433;') ``` The following fails: ``` import sqlalchemy sqlalchemy.create_engine("mssql://myuser:mypwd@my.db.server:1433/mydb?driver=FreeTDS& odbc_options='TDS_Version=8....
I'm still interested in a way to do this in one line within the sqlalchemy `create_engine` statement, but I found the following workaround [detailed here](http://www.sqlalchemy.org/docs/05/dbengine.html#custom-dbapi-connect-arguments): ``` import pyodbc, sqlalchemy def connect(): pyodbc.connect('DRIVER={FreeTDS};...
SqlAlchemy equivalent of pyodbc connect string using FreeTDS
4,493,614
14
2010-12-20T20:28:22Z
7,399,585
15
2011-09-13T09:27:09Z
[ "python", "sql-server", "sqlalchemy", "pyodbc", "freetds" ]
The following works: ``` import pyodbc pyodbc.connect('DRIVER={FreeTDS};Server=my.db.server;Database=mydb;UID=myuser;PWD=mypwd;TDS_Version=8.0;Port=1433;') ``` The following fails: ``` import sqlalchemy sqlalchemy.create_engine("mssql://myuser:mypwd@my.db.server:1433/mydb?driver=FreeTDS& odbc_options='TDS_Version=8....
The example by @Singletoned would not work for me with SQLAlchemy 0.7.2. From the [SQLAlchemy docs for connecting to SQL Server](http://www.sqlalchemy.org/docs/dialects/mssql.html): `If you require a connection string that is outside the options presented above, use the odbc_connect keyword to pass in a urlencoded con...
Find large number of consecutive values fulfilling condition in a numpy array
4,494,404
13
2010-12-20T22:02:05Z
4,495,197
23
2010-12-21T00:11:32Z
[ "python", "search", "numpy" ]
I have some audio data loaded in a numpy array and I wish to segment the data by finding silent parts, i.e. parts where the audio amplitude is below a certain threshold over a a period in time. An extremely simple way to do this is something like this: ``` values = ''.join(("1" if (abs(x) < SILENCE_THRESHOLD) else "0...
Here's a numpy-based solution. I think (?) it should be faster than the other options. Hopefully it's fairly clear. However, it does require a twice as much memory as the various generator-based solutions. As long as you can hold a single temporary copy of your data in memory (for the diff), and a boolean array of th...
Java and Python Together in Single Google App Engine Project
4,494,539
5
2010-12-20T22:19:28Z
4,494,724
8
2010-12-20T22:44:28Z
[ "java", "python", "google-app-engine", "gae-datastore" ]
I currently have a Java application running on Google App Engine, but I want to add the features that the Python module's SearchableModel provides (for search features of course). Is it possible to run python code in the same project as Java code, just under a different version? If not, could they be two separate apps ...
It is possible to run Python and Java applications on different versions. [From](http://stackoverflow.com/questions/1085898/choosing-java-vs-python-on-google-app-engine/1087878#1087878): > Last but not least: remember that you can have different version of your app (using the same datastore) some of which are impleme...
Combine --user with --prefix error with setup.py install
4,495,120
60
2010-12-20T23:54:20Z
4,495,175
100
2010-12-21T00:07:55Z
[ "python", "installation", "distutils" ]
I was trying to install Python packages a system I recently gained access to. I was trying to take advantage of Python's relatively new [per user site-packages directory](http://docs.python.org/whatsnew/2.6.html#pep-370-per-user-site-packages-directory), and the new option `--user`. (The option is [currently undocument...
# One time workaround: ``` pip install --user --install-option="--prefix=" <package_name> ``` or ``` python setup.py install --user --prefix= ``` Note that there is no text (not even whitespace) after the `=`. Do *not* forget the `--user` flag. # Installing multiple packages: Create `~/.pydistutils.cfg` (or equi...
Nonlinear e^(-x) regression using scipy, python, numpy
4,495,127
7
2010-12-20T23:56:27Z
4,496,176
11
2010-12-21T04:02:47Z
[ "python", "statistics", "numpy", "scipy", "scientific-computing" ]
The code below is giving me a flat line for the line of best fit rather than a nice curve along the model of e^(-x) that would fit the data. Can anyone show me how to fix the code below so that it fits my data? ``` import numpy as np import matplotlib.pyplot as plt import scipy.optimize def _eNegX_(p,x): x0,y0,...
It looks like it's a problem with your initial guesses; something like (1, 1, 1, 1) works fine:![graph that looks good](http://i.stack.imgur.com/8CKyc.png) You have ``` p_guess=(np.median(x),np.min(y),np.max(y),.01) ``` for the function ``` def _eNegX_(p,x): x0,y0,c,k=p y = (c * np.exp(-k*(x-x0))) + y0 ...
Numpy vectorize, using lists as arguments
4,495,882
8
2010-12-21T02:48:05Z
4,496,449
10
2010-12-21T05:09:27Z
[ "python", "numpy", "vectorization" ]
The numpy `vectorize` function is useful, but it doesn't behave well when the function arguments are lists rather then scalars. As an example: ``` import numpy as np def f(x, A): print "type(A)=%s, A=%s"%(type(A),A) return sum(A)/x X = np.linspace(1,2,10) P = [1,2,3] f2 = np.vectorize(f) f(X,P) f2(X,P) ```...
Your question doesn't make clear precisely what output you would like to see from the vectorized function, but I'm going to assume you would like the same list (A) applied as an argument to every invocation of f() (ie once for each element in the X array) The vectorized version of a function ensures all arguments are ...
Testing a custom Django template filter
4,496,109
9
2010-12-21T03:47:59Z
4,496,734
8
2010-12-21T06:18:24Z
[ "python", "django", "django-template-filters" ]
I have a custom template filter I created under `project/app/templatetags`. I want to add some regression tests for some bugs I just found. How would I go about doing so?
Here's how I do it (extracted from [my django-multiforloop](https://github.com/gabrielgrant/django-multiforloop/blob/master/multiforloop/tests.py)): ``` from django.test import TestCase from django.template import Context, Template class TagTests(TestCase): def tag_test(self, template, context, output): t...
Python threads all executing on a single core
4,496,680
23
2010-12-21T06:09:26Z
4,496,918
33
2010-12-21T06:57:47Z
[ "python", "multithreading", "performance" ]
I have a Python program that spawns many threads, runs 4 at a time, and each performs an expensive operation. Pseudocode: ``` for object in list: t = Thread(target=process, args=(object)) # if fewer than 4 threads are currently running, t.start(). Otherwise, add t to queue ``` But when the program is run, Act...
Note that in many cases (and virtually all cases where your "expensive operation" is a calculation implemented in Python), multiple threads will not actually run concurrently due to Python's [Global Interpreter Lock (GIL)](http://en.wikipedia.org/wiki/Global_Interpreter_Lock). > The GIL is an interpreter-level lock. >...
How do I parse a website in python once I know its url?
4,496,717
2
2010-12-21T06:15:24Z
4,496,740
10
2010-12-21T06:19:46Z
[ "python" ]
If I know the url of a wiki site , How do I use python to parse the contents of it ?
This is a very broad question, but the first things to reach for are [urllib](http://docs.python.org/library/urllib.html), which will handle the downloading part, and [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/), which will do the parsing. Gluing them together and writing the code to actually extract...
AppEngine: Step-by-Step Debugging
4,497,672
18
2010-12-21T09:05:57Z
4,498,515
12
2010-12-21T10:55:47Z
[ "python", "debugging", "google-app-engine" ]
While working with AppEngine locally (i.e. using dev\_appserver.py), is there anyway to do a step-by-step debugging? It is a too old fashion to use logging.info() or similar functions to show the values of all the variables in the code and decide where the error is.
Eclipse PyDev supports debugging and AppEngine. <http://code.google.com/appengine/articles/eclipse.html>
AppEngine: Step-by-Step Debugging
4,497,672
18
2010-12-21T09:05:57Z
4,498,552
8
2010-12-21T11:00:06Z
[ "python", "debugging", "google-app-engine" ]
While working with AppEngine locally (i.e. using dev\_appserver.py), is there anyway to do a step-by-step debugging? It is a too old fashion to use logging.info() or similar functions to show the values of all the variables in the code and decide where the error is.
If the local appengine process is a normal python process you have a couple of options: 1. In your code, place "code breakpoints": `import pdb; pdb.set_trace()`. Run `dev_appserver.py` as normal, and the python debugger will break when it reaches the line with the code. 2. Run `dev_appserver.py` in pdb. From the shell...
AppEngine: Step-by-Step Debugging
4,497,672
18
2010-12-21T09:05:57Z
4,501,418
14
2010-12-21T16:21:14Z
[ "python", "debugging", "google-app-engine" ]
While working with AppEngine locally (i.e. using dev\_appserver.py), is there anyway to do a step-by-step debugging? It is a too old fashion to use logging.info() or similar functions to show the values of all the variables in the code and decide where the error is.
To expand a little bit on codeape's answer's first suggestion: Because dev\_appserver.py mucks about with stdin, stdout, and stderr, a little more work is needed to set a "code breakpoint". This does the trick for me: ``` import sys for attr in ('stdin', 'stdout', 'stderr'): setattr(sys, attr, getattr(sys, '__%s__...
Silent printing of a PDF in Python
4,498,099
8
2010-12-21T10:07:16Z
4,498,956
13
2010-12-21T11:52:53Z
[ "python", "windows", "pdf", "printing", "silent" ]
I'm trying to print a PDF with Python, without opening the PDF viewer application (Adobe, Foxit etc.). I need also to know when printing has finished (to delete the file). [Here](http://permalink.gmane.org/gmane.comp.python.windows/6558) I found this **implementation**: ``` import win32ui, dde, os.path, time from win...
I suggest you install [GSView](http://pages.cs.wisc.edu/~ghost/gsview/get49.htm) and [GSPrint](http://pages.cs.wisc.edu/~ghost/gsview/gsprint.htm) and shell out to `gsprint.exe` to print the pdf. ``` p = subprocess.Popen([r"p:\ath\to\gsprint.exe", "test.pdf"], stdout=subprocess.PIPE, stderr=subpr...
Printing without newline (print 'a',) prints a space, how to remove?
4,499,073
98
2010-12-21T12:09:42Z
4,499,126
38
2010-12-21T12:16:04Z
[ "python", "string", "printing", "python-2.x" ]
I have this code: ``` >>> for i in xrange(20): ... print 'a', ... a a a a a a a a a a a a a a a a a a a a ``` I want to output `'a'`, without `' '` like this: ``` aaaaaaaaaaaaaaaaaaaa ``` Is it possible?
You can suppress the space by printing an empty string to stdout between the `print` statements. ``` >>> import sys >>> for i in range(20): ... print 'a', ... sys.stdout.write('') ... aaaaaaaaaaaaaaaaaaaa ``` However, a cleaner solution is to first build the entire string you'd like to print and then output it w...
Printing without newline (print 'a',) prints a space, how to remove?
4,499,073
98
2010-12-21T12:09:42Z
4,499,131
30
2010-12-21T12:16:45Z
[ "python", "string", "printing", "python-2.x" ]
I have this code: ``` >>> for i in xrange(20): ... print 'a', ... a a a a a a a a a a a a a a a a a a a a ``` I want to output `'a'`, without `' '` like this: ``` aaaaaaaaaaaaaaaaaaaa ``` Is it possible?
You could print a backspace character (`'\b'`): ``` for i in xrange(20): print '\ba', ``` result: ``` aaaaaaaaaaaaaaaaaaaa ```
Printing without newline (print 'a',) prints a space, how to remove?
4,499,073
98
2010-12-21T12:09:42Z
4,499,136
106
2010-12-21T12:17:40Z
[ "python", "string", "printing", "python-2.x" ]
I have this code: ``` >>> for i in xrange(20): ... print 'a', ... a a a a a a a a a a a a a a a a a a a a ``` I want to output `'a'`, without `' '` like this: ``` aaaaaaaaaaaaaaaaaaaa ``` Is it possible?
From <http://docs.python.org/whatsnew/2.6.html#pep-3105-print-as-a-function> ``` >>> from __future__ import print_function >>> print('a', end='') ``` Obviously that only works with python 2.6 or higher.
Printing without newline (print 'a',) prints a space, how to remove?
4,499,073
98
2010-12-21T12:09:42Z
4,499,144
23
2010-12-21T12:18:05Z
[ "python", "string", "printing", "python-2.x" ]
I have this code: ``` >>> for i in xrange(20): ... print 'a', ... a a a a a a a a a a a a a a a a a a a a ``` I want to output `'a'`, without `' '` like this: ``` aaaaaaaaaaaaaaaaaaaa ``` Is it possible?
Python 3.x: ``` for i in range(20): print('a', end='') ``` Python 2.6 or 2.7: ``` from __future__ import print_function for i in xrange(20): print('a', end='') ```
Printing without newline (print 'a',) prints a space, how to remove?
4,499,073
98
2010-12-21T12:09:42Z
4,499,172
101
2010-12-21T12:21:34Z
[ "python", "string", "printing", "python-2.x" ]
I have this code: ``` >>> for i in xrange(20): ... print 'a', ... a a a a a a a a a a a a a a a a a a a a ``` I want to output `'a'`, without `' '` like this: ``` aaaaaaaaaaaaaaaaaaaa ``` Is it possible?
There are a number of ways of achieving your result. If you're just wanting a solution for your case, use [string multiplication](http://docs.python.org/library/stdtypes.html#typesseq) as [@Ant](http://stackoverflow.com/questions/4499073/print-python-whithout-n/4499087#4499087) mentions. This is only going to work if e...
Why are JITted Python implementations still slow?
4,500,232
14
2010-12-21T14:20:13Z
4,507,168
11
2010-12-22T07:49:33Z
[ "c#", "java", "python", "performance", "jit" ]
I understand why interpretation overhead is expensive, but why are JITted Python implementations (Psyco and PyPy) still so much slower than other JITted languages like C# and Java? Edit: I also understand that everything is an object, dynamic typing is costly, etc. However, for functions where types can be inferred, I...
The simplest possible answer is that PyPy is simply not yet as fast as hotspot and Psyco never will. Writing a reasonable JIT is a long and tedious process and it took for example many years for hotspot to get where it is (with a lot of funding as well). The more complex and dynamic the language is, the longer it take...
how to display python list in django template
4,500,462
3
2010-12-21T14:47:12Z
4,500,476
8
2010-12-21T14:48:28Z
[ "python", "django" ]
I am new to python and django. I want to know how can I dispaly python list in django template. The list is a list of days in weeks e.g day\_list = ['sunday','monday','tuesday']
Pass it to the template as a context and then simply iterate over it. ``` {% for day in day_list %} {{ day }} {% endfor %} ``` This is the [documentation for the `for` tag](http://docs.djangoproject.com/en/1.2/ref/templates/builtins/#std%3atemplatetag-for). I recommend you go through the [Django tutorial](http://...
Python: check whether a word is spelled correctly
4,500,752
11
2010-12-21T15:17:49Z
4,500,898
17
2010-12-21T15:30:41Z
[ "python", "spell-checking" ]
I'm looking for a an easy way to check whether a certain string is a correctly-spelled English word. For example, 'looked' would return True while 'hurrr' would return False. I don't need spelling suggestions or any spelling-correcting features. Just a simple function that takes a string and returns a boolean value.
Two possible ways of doing it: 1. Have your own file which has all the valid words. Load the file into a set and compare each word to see whether it exists in it (word in set) 2. (The better way) Use [PyEnchant](http://packages.python.org/pyenchant/), a spell checking library for Python
How can I exclude South migrations from coverage reports using coverage.py
4,500,785
21
2010-12-21T15:21:37Z
4,505,903
16
2010-12-22T03:23:47Z
[ "python", "django", "code-coverage", "coverage.py" ]
I use [coverage.py](http://nedbatchelder.com/code/coverage/) to check the test coverage of my django application. However since I use South for my database migrations, all those files show up with 0% and mess up the overall percentage. I already tried using `--omit=*migrations*` in both `run` and `report` (and both) b...
You should be able to match against the migrations directory to omit those files. Have you tried quoting the argument? Depending on your OS and shell, it may be expanding those asterisks prematurely. Try it like this: ``` --omit='*migrations*' ``` Alternately, you could put the switch into a .coveragerc file: ``` [r...
How can I exclude South migrations from coverage reports using coverage.py
4,500,785
21
2010-12-21T15:21:37Z
4,517,914
22
2010-12-23T10:32:53Z
[ "python", "django", "code-coverage", "coverage.py" ]
I use [coverage.py](http://nedbatchelder.com/code/coverage/) to check the test coverage of my django application. However since I use South for my database migrations, all those files show up with 0% and mess up the overall percentage. I already tried using `--omit=*migrations*` in both `run` and `report` (and both) b...
The solution was: ``` [run] omit = ../*migrations* ```
Class as an input in a function
4,501,403
2
2010-12-21T16:19:24Z
4,501,471
9
2010-12-21T16:26:30Z
[ "python", "class", "input" ]
I have a file `different_classes` that contains three different classes. It is something like: ``` class first(object): def __init__(x, y, z): body of the first class class second(first): def __init__(x, y, z, a=2, b=3): body of the second class class third(object): def __init__(x, y, z): bod...
Rather than passing the name of the class, why not just pass the class itself: ``` def create_blah(class_type = different_classes.first, x=x1, y=y1, z=z1): instance = class_type(x, y, z) ``` Remember that a class is just an object like anything else in Python: you can assign them to variables and pass them around...
Creating sublists
4,501,636
14
2010-12-21T16:40:01Z
4,501,720
13
2010-12-21T16:47:53Z
[ "python", "list", "grouping" ]
The opposite of list flattening. Given a list and a length n return a list of sub lists of length n. ``` def sublist(lst, n): sub=[] ; result=[] for i in lst: sub+=[i] if len(sub)==n: result+=[sub] ; sub=[] if sub: result+=[sub] return result ``` An example: If the list is: ``` [1,2...
Such a list of lists could be constructed using a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions): ``` In [17]: seq=[1,2,3,4,5,6,7,8] In [18]: [seq[i:i+3] for i in range(0,len(seq),3)] Out[18]: [[1, 2, 3], [4, 5, 6], [7, 8]] ``` There is also the [grouper idiom](http://do...
Installing Graphviz on Os X 10.5.8
4,502,006
6
2010-12-21T17:15:57Z
4,503,238
7
2010-12-21T19:41:59Z
[ "python", "graphviz", "pygraphviz" ]
I'm trying to install Graphviz 2.14.1 on osX 10.5.8 I installed Graphviz from the Universal Binary here: ``` http://www.ryandesign.com/graphviz/ $ svn co https://networkx.lanl.gov/svn/pygraphviz/trunk pygraphviz - Fingerprint: 43:8e:fa:75:00:60:67:07:fd:04:3c:e7:bf:25:86:fd:66:b3:f6:cb (R)eject, accept (t)e...
2.14.1 is a very old version of graphviz. You may have better success using the official OS X installer package for 2.26 (at this writing) [here](http://www.graphviz.org/Download_macos.php). Then you will likely need to edit the pygraphiz `setup.py` to use the proper `library_path` and `include_path`. Most likely you w...
Installing Graphviz on Os X 10.5.8
4,502,006
6
2010-12-21T17:15:57Z
13,445,789
19
2012-11-18T23:37:47Z
[ "python", "graphviz", "pygraphviz" ]
I'm trying to install Graphviz 2.14.1 on osX 10.5.8 I installed Graphviz from the Universal Binary here: ``` http://www.ryandesign.com/graphviz/ $ svn co https://networkx.lanl.gov/svn/pygraphviz/trunk pygraphviz - Fingerprint: 43:8e:fa:75:00:60:67:07:fd:04:3c:e7:bf:25:86:fd:66:b3:f6:cb (R)eject, accept (t)e...
It seems like you are missing the "pkg-config" package. You can install it with [Homebrew](http://mxcl.github.com/homebrew/) > brew install pkg-config
recursive factorial function
4,502,429
6
2010-12-21T18:06:19Z
4,502,483
11
2010-12-21T18:13:08Z
[ "python", "recursion", "factorial" ]
how can I combine these two functions in to one recursive function to have this result: ``` factorial(6) 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 ``` **these are the codes** ``` def factorial( n ): if n <1: # base case return 1 else: return n * factorial( n - 1 ) # recursive call def fac...
``` def factorial( n ): if n <1: # base case return 1 else: returnNumber = n * factorial( n - 1 ) # recursive call print(str(n) + '! = ' + str(returnNumber)) return returnNumber ```
recursive factorial function
4,502,429
6
2010-12-21T18:06:19Z
23,501,605
9
2014-05-06T17:52:30Z
[ "python", "recursion", "factorial" ]
how can I combine these two functions in to one recursive function to have this result: ``` factorial(6) 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 ``` **these are the codes** ``` def factorial( n ): if n <1: # base case return 1 else: return n * factorial( n - 1 ) # recursive call def fac...
2 lines of code: ``` def fac(n): return 1 if (n < 1) else n * fac(n-1) ``` Test it: ``` print fac(4) ``` Result: ``` 24 ```
How to sort my paws?
4,502,656
111
2010-12-21T18:32:19Z
4,543,848
118
2010-12-28T05:19:25Z
[ "python", "image-processing" ]
In [my previous question I got an excellent answer](http://stackoverflow.com/questions/4087919/how-can-i-improve-my-paw-detection/4092160#4092160) that helped me detect where a paw hit a pressure plate, but now I'm struggling to link these results to their corresponding paws: ![alt text](http://i.stack.imgur.com/1KbIz...
Alright! I've finally managed to get something working consistently! This problem pulled me in for several days... Fun stuff! Sorry for the length of this answer, but I need to elaborate a bit on some things... (Though I may set a record for the longest non-spam stackoverflow answer ever!) As a side note, I'm using th...
Python / Javascript -- integer bitwise exclusive or problem
4,503,896
2
2010-12-21T21:06:00Z
4,503,967
8
2010-12-21T21:14:07Z
[ "javascript", "python", "integer", "bit-manipulation", "xor" ]
I'm proficient with both languages... but I'm having problems with the integer bitwise exclusive or logical operator. In javascript, it gives me one result, in python it gives me another.. Go ahead, open python and execute (-5270299) ^ 2825379669 Now with javascript, do the same calculation, and alert the result or w...
JavaScript's integers are 32-bit whereas Python automatically converts to the unlimited length `long` format when values exceed 32 bits. If you explicitly force Python not to sign extend past 32 bits, or if you truncate the result to 32 bits, then the results are the same: ``` >>> (-5270299 & 0xFFFFFFFF) ^ 2825379669 ...
The Zen of Python distils the guiding principles for Python into 20 aphorisms but lists only 19. What's the twentieth?
4,504,487
32
2010-12-21T22:18:17Z
4,504,891
11
2010-12-21T23:20:39Z
[ "python" ]
From [PEP 20, The Zen of Python](http://www.python.org/dev/peps/pep-0020/): > Long time Pythoneer Tim Peters succinctly channels the BDFL's > guiding principles for Python's design into 20 aphorisms, only 19 > of which have been written down. What is this twentieth aphorism? Does it exist, or is the reference merely ...
It has to be SIGNIFICANT WHITESPACE, of course!
The Zen of Python distils the guiding principles for Python into 20 aphorisms but lists only 19. What's the twentieth?
4,504,487
32
2010-12-21T22:18:17Z
24,814,971
14
2014-07-17T23:09:17Z
[ "python" ]
From [PEP 20, The Zen of Python](http://www.python.org/dev/peps/pep-0020/): > Long time Pythoneer Tim Peters succinctly channels the BDFL's > guiding principles for Python's design into 20 aphorisms, only 19 > of which have been written down. What is this twentieth aphorism? Does it exist, or is the reference merely ...
I had the opportunity to ask Guido about this recently. According to him, this is "some bizarre Tim Peters in-joke". That, and/or (still according to him) it's an opportunity for people to provide their own addition (as largely is happening in the answers to this question :-) ).
A way to output pyunit test name in setup()
4,504,622
22
2010-12-21T22:39:54Z
4,506,296
32
2010-12-22T05:01:01Z
[ "python", "unit-testing", "pyunit" ]
Is there a way in python for a pyunit test to output the test it's currently running. Example: ``` def setUp(self): log.debug("Test %s Started" % (testname)) def test_example(self): #do stuff def test_example2(self): #do other stuff def tearDown(self): log.debug("Test %s Finished" % (testname)) ```
You can use `self._testMethodName`. This is inherited from the unittest.TestCase parent class. ``` def setUp(): print "In method", self._testMethodName ```
A way to output pyunit test name in setup()
4,504,622
22
2010-12-21T22:39:54Z
14,954,405
10
2013-02-19T09:45:56Z
[ "python", "unit-testing", "pyunit" ]
Is there a way in python for a pyunit test to output the test it's currently running. Example: ``` def setUp(self): log.debug("Test %s Started" % (testname)) def test_example(self): #do stuff def test_example2(self): #do other stuff def tearDown(self): log.debug("Test %s Finished" % (testname)) ```
``` self.id().split('.')[-1] ``` Document is found at <http://docs.python.org/library/unittest.html#unittest.TestCase.id>, as Sean pointed out.
Why does range(start, end) not include end?
4,504,662
116
2010-12-21T22:45:46Z
4,504,677
90
2010-12-21T22:48:16Z
[ "python", "range" ]
``` >>> range(1,11) ``` gives you ``` [1,2,3,4,5,6,7,8,9,10] ``` Why not 1-11? Did they just decide to do it like that at random or does it have some value I am not seeing?
Because it's more common to call `range(0, 10)` which returns `[0,1,2,3,4,5,6,7,8,9]` which contains 10 elements which equals `len(range(0, 10))`. Remember that programmers prefer 0-based indexing. Also, consider the following common code snippet: ``` for i in range(len(li)): pass ``` Could you see that if `range(...
Why does range(start, end) not include end?
4,504,662
116
2010-12-21T22:45:46Z
4,504,689
13
2010-12-21T22:49:32Z
[ "python", "range" ]
``` >>> range(1,11) ``` gives you ``` [1,2,3,4,5,6,7,8,9,10] ``` Why not 1-11? Did they just decide to do it like that at random or does it have some value I am not seeing?
Exclusive ranges do have some benefits: For one thing each item in `range(0,n)` is a valid index for lists of length `n`. Also `range(0,n)` has a length of `n`, not `n+1` which an inclusive range would.
Why does range(start, end) not include end?
4,504,662
116
2010-12-21T22:45:46Z
4,504,703
10
2010-12-21T22:51:20Z
[ "python", "range" ]
``` >>> range(1,11) ``` gives you ``` [1,2,3,4,5,6,7,8,9,10] ``` Why not 1-11? Did they just decide to do it like that at random or does it have some value I am not seeing?
It works well in combination with zero-based indexing and `len()`. For example, if you have 10 items in a list `x`, they are numbered 0-9. `range(len(x))` gives you 0-9. Of course, people will tell you it's more Pythonic to do `for item in x` or `for index, item in enumerate(x)` rather than `for i in range(len(x))`. ...
Trouble Loading scipy through PyXLL - Has Anyone Succeeded in Loading Scipy via PyXLL?
4,504,769
4
2010-12-21T23:01:28Z
4,504,948
7
2010-12-21T23:34:45Z
[ "python", "excel", "scipy", "pyxll" ]
I am using Python 2.6, Excel 2007 Professional and the latest version of PyXLL. When loading a module in PyXLL that has ``` import scipy ``` An exception is thrown and the module is not loaded. Has anyone been able to load Scipy in PyXLL? Could it be a versioning problem? The exception thrown is: ``` 2010-12-21 17:2...
I suspect this is because you are using the Enthought distribution of NumPy. The current version available has a problem that means it cannot be embedded in Excel. To fix this, you need to remove the manifest resources from the numpy pyd files using cff explorer or any other PE editor. Enthought are aware of this and...
How should I structure a Python package that contains Cython code
4,505,747
64
2010-12-22T02:44:31Z
4,515,279
38
2010-12-23T01:58:32Z
[ "python", "packaging", "cython" ]
I'd like to make a Python package containing some [Cython](http://cython.org/) code. I've got the the Cython code working nicely. However, now I want to know how best to package it. For most people who just want to install the package, I'd like to include the `.c` file that Cython creates, and arrange for `setup.py` t...
I've done this myself now, in a Python package [`simplerandom`](http://pypi.python.org/pypi/simplerandom) ([BitBucket repo](http://bitbucket.org/cmcqueen1975/simplerandom) - EDIT: now [github](https://github.com/cmcqueen/simplerandom)) (I don't expect this to be a popular package, but it was a good chance to learn Cyth...
How should I structure a Python package that contains Cython code
4,505,747
64
2010-12-22T02:44:31Z
18,418,524
12
2013-08-24T12:24:18Z
[ "python", "packaging", "cython" ]
I'd like to make a Python package containing some [Cython](http://cython.org/) code. I've got the the Cython code working nicely. However, now I want to know how best to package it. For most people who just want to install the package, I'd like to include the `.c` file that Cython creates, and arrange for `setup.py` t...
Adding to Craig McQueen's answer: see below for how to override the `sdist` command to have Cython automatically compile your source files before creating a source distribution. That way your run no risk of accidentally distributing outdated `C` sources. It also helps in the case where you have limited control over th...
How should I structure a Python package that contains Cython code
4,505,747
64
2010-12-22T02:44:31Z
19,138,055
7
2013-10-02T13:28:24Z
[ "python", "packaging", "cython" ]
I'd like to make a Python package containing some [Cython](http://cython.org/) code. I've got the the Cython code working nicely. However, now I want to know how best to package it. For most people who just want to install the package, I'd like to include the `.c` file that Cython creates, and arrange for `setup.py` t...
<http://docs.cython.org/src/reference/compilation.html#distributing-cython-modules> > It is strongly recommended that you distribute the generated .c files as well as your Cython sources, so that users can install your module without needing to have Cython available. > > It is also recommended that Cython compilation ...
what does "*" mean in Python?
4,506,388
2
2010-12-22T05:18:36Z
4,506,398
8
2010-12-22T05:20:44Z
[ "python" ]
I came across with a line in python. ``` self.window.resize(*self.winsize) ``` What does the "\*" mean in this line? I haven't seen this in any python tutorial.
One possibility is that self.winsize is list or tuple. The \* operator unpacks the arguments out of a list or tuple. See : <http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists> Ah: There is an SO discussion on this: [Keyword argument in unpacking argument list/dict cases in Python](http://stacko...
Django filter many-to-many with contains
4,507,893
34
2010-12-22T09:44:26Z
4,508,083
45
2010-12-22T10:11:23Z
[ "python", "django", "django-models", "many-to-many", "django-orm" ]
I am trying to filter a bunch of objects through a many-to-many relation. Because the trigger\_roles field may contain multiple entries I tried the contains filter. But as that is designed to be used with strings I'm pretty much helpless how i should filter this relation (you can ignore the values\_list() atm.). This ...
Have you tried something like this: ``` module.workflow_set.filter(trigger_roles__in=[self.role], allowed=True) ``` or just if `self.role.id` is not a list of pks: ``` module.workflow_set.filter(trigger_roles__id__exact=self.role.id, allowed=True) ```
Django filter many-to-many with contains
4,507,893
34
2010-12-22T09:44:26Z
18,317,340
7
2013-08-19T15:16:53Z
[ "python", "django", "django-models", "many-to-many", "django-orm" ]
I am trying to filter a bunch of objects through a many-to-many relation. Because the trigger\_roles field may contain multiple entries I tried the contains filter. But as that is designed to be used with strings I'm pretty much helpless how i should filter this relation (you can ignore the values\_list() atm.). This ...
The simplest approach to achieve this would be checking for equalty over the whole instance (instead of the id) in the `ManyToManyField`. That looks if the instance is inside the many to many relationship. Example: ``` module.workflow_set.filter(trigger_roles=self.role, allowed=True) ```
How do I use a MD5 hash (or other binary data) as a key name?
4,508,155
4
2010-12-22T10:20:02Z
4,509,581
12
2010-12-22T13:21:59Z
[ "python", "google-app-engine", "gae-datastore" ]
I've been trying to use a MD5 hash as a key name on AppEngine, but the code I wrote raises a UnicodeDecodeError ``` from google.appengine.ext import db import hashlib key = db.Key.from_path('Post', hashlib.md5('thecakeisalie').digest()) ``` I don't want to use `hexdigest()` as that is not only a kludge, but an inferi...
The App Engine [Python docs](http://code.google.com/intl/en/appengine/docs/python/datastore/keysandentitygroups.html) says: > A key\_name is stored as a Unicode > string (with str values converted as > ASCII text). The key has to be an unicode-encodeable-string. You need to change the digest() call to hexdigest(), ie...
How to log python exception?
4,508,849
36
2010-12-22T11:46:37Z
4,508,872
83
2010-12-22T11:49:52Z
[ "python", "exception-handling", "logging" ]
Coming from java, being familiar with logback I used to do ``` try { ... catch (Exception e) { log("Error at X", e); } ``` I would like the same functionality of being able to log the exception and the stacktrace into a file. How would you recommend me implementing this? Currently using boto logging infrastru...
Take a look at `logging.exception` ([Python Logging Module](http://docs.python.org/library/logging.html)) ``` import logging def foo(): try: some_code() except: logging.exception('') ``` This should automatically take care of getting the traceback for the current exception and logging it prop...
How to log python exception?
4,508,849
36
2010-12-22T11:46:37Z
4,510,206
38
2010-12-22T14:32:17Z
[ "python", "exception-handling", "logging" ]
Coming from java, being familiar with logback I used to do ``` try { ... catch (Exception e) { log("Error at X", e); } ``` I would like the same functionality of being able to log the exception and the stacktrace into a file. How would you recommend me implementing this? Currently using boto logging infrastru...
To answer your question, you can get the string version of `print_exception()` using the [`traceback.format_exception()`](http://docs.python.org/library/traceback.html#traceback.format_exception) function. It returns the traceback message as a list of strings rather than printing it to stdout, so you can do what you wa...
How to log python exception?
4,508,849
36
2010-12-22T11:46:37Z
13,621,529
32
2012-11-29T08:22:43Z
[ "python", "exception-handling", "logging" ]
Coming from java, being familiar with logback I used to do ``` try { ... catch (Exception e) { log("Error at X", e); } ``` I would like the same functionality of being able to log the exception and the stacktrace into a file. How would you recommend me implementing this? Currently using boto logging infrastru...
Logging exceptions is as simple as adding the exc\_info=True keyword argument to any log message, see entry for Logger.debug in <http://docs.python.org/2/library/logging.html>. Example: ``` try: raise Exception('lala') except Exception: logging.info('blah', exc_info=True) ``` output (depending, of course, o...
Python: find index of first digit in string?
4,510,709
20
2010-12-22T15:31:33Z
4,510,762
34
2010-12-22T15:37:03Z
[ "python", "string" ]
I suspect this is a regular expression problem - and a very basic one, so apologies. In Python, if I have a string like ``` xdtwkeltjwlkejt7wthwk89lk ``` how can I get the index of the first digit in the string? Thanks!
Use [`re.search()`](http://docs.python.org/library/re.html#re.search): ``` >>> import re >>> s1 = "thishasadigit4here" >>> m = re.search("\d", s1) >>> if m: ... print "Digit found at position %d" % m.start() ... else: ... print "No digit in that string" ... Digit found at position 13 >>> ```
Python: find index of first digit in string?
4,510,709
20
2010-12-22T15:31:33Z
4,510,773
8
2010-12-22T15:38:20Z
[ "python", "string" ]
I suspect this is a regular expression problem - and a very basic one, so apologies. In Python, if I have a string like ``` xdtwkeltjwlkejt7wthwk89lk ``` how can I get the index of the first digit in the string? Thanks!
``` import re mob = re.search('\d', 'xdtwkeltjwlkejt7wthwk89lk') if mob: print mob.start() ```
Python: find index of first digit in string?
4,510,709
20
2010-12-22T15:31:33Z
4,510,805
9
2010-12-22T15:40:59Z
[ "python", "string" ]
I suspect this is a regular expression problem - and a very basic one, so apologies. In Python, if I have a string like ``` xdtwkeltjwlkejt7wthwk89lk ``` how can I get the index of the first digit in the string? Thanks!
Here is another way without regex and which is simpler and good enough in most cases ``` s='xdtwkeltjwlkejt7wthwk89lk' for i, c in enumerate(s): if c.isdigit(): print i break ``` output: ``` 15 ``` To get all digits and their positions, a simple expression will do, Regex is overkill. ``` >>> [...
Python: find index of first digit in string?
4,510,709
20
2010-12-22T15:31:33Z
4,510,896
10
2010-12-22T15:49:01Z
[ "python", "string" ]
I suspect this is a regular expression problem - and a very basic one, so apologies. In Python, if I have a string like ``` xdtwkeltjwlkejt7wthwk89lk ``` how can I get the index of the first digit in the string? Thanks!
Seems like a good job for a parser: ``` >>> from simpleparse.parser import Parser >>> s = 'xdtwkeltjwlkejt7wthwk89lk' >>> grammar = """ ... integer := [0-9]+ ... <alpha> := -integer+ ... all := (integer/alpha)+ ... """ >>> parser = Parser(grammar, 'all') >>> parser.parse(s) (1, [('integer', 15, 16, None), ('intege...
ugettext and ugettext_lazy in Django
4,510,871
21
2010-12-22T15:47:13Z
4,510,998
36
2010-12-22T15:59:14Z
[ "python", "django" ]
Could you explain what principal difference of ugettext and ugettext\_lazy. When i'm try to ``` return HttpResponse(ugettext_lazy("Hello")) ``` i've seen nothing, but ``` return HttpResponse(ugettext("Hello")) ``` is working. Why? Thanks.
`ugettext` is used to load a translation of a string *right now*. `ugettext_lazy` returns an object that can eventually be turned into a string. You need that if the `ugettext_lazy` call is evaluated before the proper locale has been set. `ugettext_lazy` can be used where you use a Unicode object. Double-check your HT...
Is it possible to empty a job queue on a Gearman server
4,510,903
10
2010-12-22T15:50:01Z
12,482,965
10
2012-09-18T18:36:46Z
[ "python", "message-queue", "gearman" ]
Is it possible to empty a job queue on a Gearman server? I am using the python driver for Gearman, and the documentation does not have any information about emptying queues. I would imagine that this functionality should exist, possibly, with a direct connection to the Gearman server.
I came across [this method](https://groups.google.com/forum/?fromgroups=#!topic/gearman/6rfOPp_R61Q): `/usr/bin/gearman -t 1000 -n -w -f function_name > /dev/null` which basically dumps all the jobs into /dev/null.
How do you test that something is random? Or "random enough'?
4,510,937
4
2010-12-22T15:53:06Z
4,510,995
18
2010-12-22T15:59:10Z
[ "python", "unit-testing", "random" ]
I have to return a random entry from my database. I wrote a function, and since I'm using the `random` module in Python, it's probably unless I used it in a stupid way. Now, how can I write a unit test that check that this function works? After all, if it's a good random value, you can never know. I'm not paranoid, ...
There are several statistical tests listed on [RANDOM.ORG for testing randomness](http://www.random.org/analysis/). See the last two sections of the linked article. Also, if you can get a copy of [Beautiful Testing](http://rads.stackoverflow.com/amzn/click/0596159811) there's a whole chapter by [John D. Cook](http://w...
How to make HTTP DELETE method using urllib2?
4,511,598
43
2010-12-22T17:02:03Z
4,511,785
61
2010-12-22T17:20:55Z
[ "python", "urllib2" ]
Does `urllib2` support DELETE or PUT method? If yes provide with any example please. I need to use piston API.
you can do it with [httplib](http://docs.python.org/library/httplib.html): ``` import httplib conn = httplib.HTTPConnection('www.foo.com') conn.request('PUT', '/myurl', body) resp = conn.getresponse() content = resp.read() ``` also, check out this [question](http://stackoverflow.com/questions/111945/is-there-any-wa...
How to make HTTP DELETE method using urllib2?
4,511,598
43
2010-12-22T17:02:03Z
4,729,380
7
2011-01-18T21:42:44Z
[ "python", "urllib2" ]
Does `urllib2` support DELETE or PUT method? If yes provide with any example please. I need to use piston API.
You can subclass the urllib2.Request object and override the method when you instantiate the class. ``` import urllib2 class RequestWithMethod(urllib2.Request): def __init__(self, method, *args, **kwargs): self._method = method urllib2.Request.__init__(*args, **kwargs) def get_method(self): return se...
How to make HTTP DELETE method using urllib2?
4,511,598
43
2010-12-22T17:02:03Z
6,312,600
12
2011-06-10T22:14:47Z
[ "python", "urllib2" ]
Does `urllib2` support DELETE or PUT method? If yes provide with any example please. I need to use piston API.
Correction for Raj's answer: ``` import urllib2 class RequestWithMethod(urllib2.Request): def __init__(self, *args, **kwargs): self._method = kwargs.pop('method', None) urllib2.Request.__init__(self, *args, **kwargs) def get_method(self): return self._method if self._method else super(RequestWithMetho...
Connect double-click event of QListView with method in PyQt4
4,511,908
2
2010-12-22T17:34:24Z
4,514,520
7
2010-12-22T23:02:40Z
[ "python", "qt", "qt4", "pyqt", "pyqt4" ]
I’ve got a PyQt QListView object, and I want a method to run when it is double-clicked. This should be trivial, but it doesn't seem to work. My code is as follows: ``` class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) lb = QListView() self.connect(lb, SIGNAL('d...
It seems to work if: ``` self.connect(lb, SIGNAL('doubleClicked()'), self.someMethod) ``` Is replaced with the new syntax of: ``` lb.doubleClicked.connect(self.someMethod) ``` The latter is much more elegant too. I still do not know why the original syntax did not work, however.
Python Multi-lined Artificial enums using range
4,512,414
11
2010-12-22T18:32:10Z
4,512,427
8
2010-12-22T18:34:16Z
[ "python", "enums", "range", "multiline" ]
I am trying to make an enum-type class in Python but it gets so lengthly when you have to do ``` VARIABLE1, VARIABLE2, VARIABLE3, VARIABLE3, VARIABLE4, VARIABLE5, VARIABLE6, VARIABLE7, VARIABLE8, ... , VARIABLE14 = range(14) ``` and I've tried to set it up like the following, but ended up not working. ``` VARIABLE1,...
Oh, wow I just added brackets around the variables and it worked ``` (VARIABLE1, VARIABLE2, VARIABLE3, ... VARIABLE14) = range(14) ```
Python: if key in dict vs. try/except
4,512,557
52
2010-12-22T18:48:38Z
4,512,583
12
2010-12-22T18:51:10Z
[ "python", "idioms" ]
I have a question about idioms and readability, and there seems to be a clash of Python philosophies for this particular case: I want to build dictionary A from dictionary B. If a specific key does not exist in B, then do nothing and continue on. Which way is better? ``` try: A["blah"] = B["blah"] except KeyErro...
From what I understand, you want to update dict A with key,value pairs from dict B **`update` is a better choice.** ``` A.update(B) ``` Example: ``` >>> A = {'a':1, 'b': 2, 'c':3} >>> B = {'d': 2, 'b':5, 'c': 4} >>> A.update(B) >>> A {'a': 1, 'c': 4, 'b': 5, 'd': 2} >>> ```
Python: if key in dict vs. try/except
4,512,557
52
2010-12-22T18:48:38Z
4,513,009
41
2010-12-22T19:38:43Z
[ "python", "idioms" ]
I have a question about idioms and readability, and there seems to be a clash of Python philosophies for this particular case: I want to build dictionary A from dictionary B. If a specific key does not exist in B, then do nothing and continue on. Which way is better? ``` try: A["blah"] = B["blah"] except KeyErro...
Exceptions are not conditionals. The conditional version is clearer. That's natural: this is straightforward flow control, which is what conditionals are designed for, not exceptions. The exception version is primarily used as an optimization when doing these lookups in a loop: for some algorithms it allows eliminati...
Python: if key in dict vs. try/except
4,512,557
52
2010-12-22T18:48:38Z
4,513,224
20
2010-12-22T20:04:40Z
[ "python", "idioms" ]
I have a question about idioms and readability, and there seems to be a clash of Python philosophies for this particular case: I want to build dictionary A from dictionary B. If a specific key does not exist in B, then do nothing and continue on. Which way is better? ``` try: A["blah"] = B["blah"] except KeyErro...
There is also a third way that avoids both exceptions and double-lookup, which can be important if the lookup is expensive: ``` value = A.get("blah", None) if value is not None: A["blah"] = value ``` In case you expect the dictionary to contain `None` values, you can use some more esoteric constants like `NotImp...
python: TypeError: can't write str to text stream
4,512,982
13
2010-12-22T19:36:00Z
4,513,028
8
2010-12-22T19:40:29Z
[ "python", "io" ]
I must be doing something obviously wrong here. But what is it, and how do I fix? ``` Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import io >>> f1 = io.open('test.txt','w') >>> f1.write('bingo') Traceba...
Try: ``` >>> f1.write(u'bingo') # u specifies unicode ``` [Reference](http://docs.python.org/library/io.html#io.TextIOBase.write)
python: TypeError: can't write str to text stream
4,512,982
13
2010-12-22T19:36:00Z
4,513,167
25
2010-12-22T19:56:55Z
[ "python", "io" ]
I must be doing something obviously wrong here. But what is it, and how do I fix? ``` Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import io >>> f1 = io.open('test.txt','w') >>> f1.write('bingo') Traceba...
The `io` module is a fairly new python module (introduced in Python 2.6) that makes working with unicode files easier. Its documentation is at: <http://docs.python.org/library/io.html> If you just want to be writing bytes (Python 2's "str" type) as opposed to text (Python 2's "unicode" type), then I would recommend yo...
python dynamic class names
4,513,192
4
2010-12-22T20:00:43Z
4,513,214
8
2010-12-22T20:03:31Z
[ "python" ]
Trying to instantiate a class based on a string value and... failing. The `parser` object below is a `dict`, in the example let's say we have one called `foo` and here `parser['name']` is 'foo': ``` obj = parser['name']() ``` Fails, yielding `TypeError: 'str' object is not callable`. But, since I have: ``` class foo...
``` classmap = { 'foo': foo } obj = classmap[parser['name']]() ```
python dynamic class names
4,513,192
4
2010-12-22T20:00:43Z
8,299,717
8
2011-11-28T17:23:17Z
[ "python" ]
Trying to instantiate a class based on a string value and... failing. The `parser` object below is a `dict`, in the example let's say we have one called `foo` and here `parser['name']` is 'foo': ``` obj = parser['name']() ``` Fails, yielding `TypeError: 'str' object is not callable`. But, since I have: ``` class foo...
As answered in: [Python dynamic class names](http://stackoverflow.com/questions/7281110/python-dynamic-class-names) There is an easier way to do this if you know which module the classes are defined in, for example: ``` getattr(my_module, my_class_name)() ```
Random module not working. ValueError: empty range for randrange() (1,1, 0)
4,513,818
4
2010-12-22T21:16:31Z
4,513,887
9
2010-12-22T21:24:04Z
[ "python", "random", "numbers", "range" ]
In Python 2.7.1, I import the random module. when I call randint() however, I get the error: ``` ValueError: empty range for randrange() (1,1, 0) ``` This error is caused by an error in the random.py module itself. I don't know how to fix it, not does reinstalling python help. I can't change versions. can someone pl...
You called randint like this: ``` randint(1,0) ``` That tells randint to return a value starting as 1 and ending at 0. The range of numbers from 1 to zero is as you surely realize an empty range. Hence the error: ``` empty range for randrange() ```
Dynamically loading python source code
4,514,095
6
2010-12-22T21:56:50Z
4,514,398
7
2010-12-22T22:43:15Z
[ "python", "dynamic", "flask" ]
I'm currently playing with Flask and I can't figure out how the debug mechanism is working. To be more precise when I save the python file with my application I don't need to restart the server, it will be loaded automatically when I make a request. So my question is how does the running program know it was changed and...
Flask is using Werkzug's underlying `run_with_reloader` function (found in `serving.py`) ... which is itself using the `restart_with_reloader` and `reloader_loop` function created earlier in the same file. `run_with_reloader` spawns another python process (running Werkzug again with all the same arguments that you pas...
Collecting key/value pairs in Python 2.6
4,514,162
2
2010-12-22T22:07:55Z
4,514,174
10
2010-12-22T22:10:04Z
[ "python", "dictionary", "python-2.6" ]
In Python 2.7, I'm used to collect key/value pairs from an array and return it as a hash: ``` return { u.id : u.name for u in users } ``` But it turns out it does not work in Python 2.6: ``` return { u.id : u.name for u in users } ^ SyntaxError: invalid syntax ``` How can I avoid doing ...
Just pass a generator expression that constructs a sequence of tuples to the constructor for `dict` ``` return dict((u.id, u.name) for u in users) ``` This will create the same dictionary as the dictionary comprehension in later versions.
Pipe subprocess standard output to a variable
4,514,751
46
2010-12-22T23:45:47Z
4,514,776
69
2010-12-22T23:49:40Z
[ "python", "subprocess", "pipe", "python-2.6" ]
I want to run a command in `pythong`, using the subprocess module, and store the output in a variable. However, I do not want the command's output to be printed to the terminal. For this code: ``` def storels(): a = subprocess.Popen("ls",shell=True) storels() ``` I get the directory listing in the terminal, instea...
To get the output of `ls`, use [`stdout=subprocess.PIPE`](http://docs.python.org/library/subprocess.html#subprocess.PIPE). ``` >>> proc = subprocess.Popen('ls', stdout=subprocess.PIPE) >>> output = proc.stdout.read() >>> print output bar baz foo ``` The command `cdrecord --help` outputs to stderr, so you need to pipe...
Pipe subprocess standard output to a variable
4,514,751
46
2010-12-22T23:45:47Z
9,742,618
15
2012-03-16T18:25:21Z
[ "python", "subprocess", "pipe", "python-2.6" ]
I want to run a command in `pythong`, using the subprocess module, and store the output in a variable. However, I do not want the command's output to be printed to the terminal. For this code: ``` def storels(): a = subprocess.Popen("ls",shell=True) storels() ``` I get the directory listing in the terminal, instea...
If you are using python 2.7 or later, the easiest way to do this is to use the [`subprocess.check_output()`](http://docs.python.org/library/subprocess.html#subprocess.check_output) command. Here is an example: ``` output = subprocess.check_output('ls') ``` To also redirect stderr you can use the following: ``` outpu...
CvSize does not exist?
4,516,007
6
2010-12-23T05:06:57Z
6,534,684
7
2011-06-30T12:24:55Z
[ "python", "opencv", "computer-vision" ]
I have installed the official python bindings for OpenCv and I am implementing some standard textbook functions just to get used to the python syntax. I have run into the problem, however, that CvSize does not actually exist, even though it is documented on the site... The simple function: `blah = cv.CvSize(inp.width/...
It seems that they opted to eventually avoid this structure altogether. Instead, it just uses a python tuple (width, height).
Problems Opening Firefox
4,517,505
6
2010-12-23T09:39:33Z
4,520,261
10
2010-12-23T15:48:39Z
[ "python", "firefox", "browser" ]
I'm trying to write a Python script to open a URL, but I keep getting errors when I try to use it: ``` import webbrowser firefox = webbrowser.get('mozilla') ``` This is the error: ``` Traceback (most recent call last): File "C:\Users\Gelu\Documents\CSCI\Image URL Generator\src\Generator.py", line 8, in <module> ...
if you do ``` import webbrowser print webbrowser._browsers ``` you will get a list of the recognized browsers on your system.
How to round off a floating number?
4,518,641
33
2010-12-23T12:13:25Z
4,518,664
40
2010-12-23T12:16:10Z
[ "python", "floating-point" ]
Suppose I am having 8.8333333333333339 and I want to convert it to 8.84, how can I accomplish this in python ? round(8.8333333333333339 , 2) gives 8.8300000000000001 and not 8.84. I am new to python or programming in general. I don't want to print it as a string, the result will be further used. For more information o...
[This is normal](http://docs.python.org/tutorial/floatingpoint.html#tut-fp-issues) (and has nothing to do with Python) because 8.83 cannot be represented exactly as a binary float, just as 1/3 cannot be represented exactly in decimal (0.333333... ad infinitum). If you want to ensure absolute precision, you need the [`...
How to round off a floating number?
4,518,641
33
2010-12-23T12:13:25Z
4,519,044
49
2010-12-23T13:13:53Z
[ "python", "floating-point" ]
Suppose I am having 8.8333333333333339 and I want to convert it to 8.84, how can I accomplish this in python ? round(8.8333333333333339 , 2) gives 8.8300000000000001 and not 8.84. I am new to python or programming in general. I don't want to print it as a string, the result will be further used. For more information o...
`8.833333333339` (or `8.833333333333334`, the result of `106.00/12`) properly rounded to two decimal places is `8.83`. Mathematically it sounds like what you want is a [ceiling function](http://en.wikipedia.org/wiki/Floor_and_ceiling_functions). The one in Python's `math` module is named [`ceil`](http://docs.python.org...
How to round off a floating number?
4,518,641
33
2010-12-23T12:13:25Z
4,520,260
14
2010-12-23T15:48:29Z
[ "python", "floating-point" ]
Suppose I am having 8.8333333333333339 and I want to convert it to 8.84, how can I accomplish this in python ? round(8.8333333333333339 , 2) gives 8.8300000000000001 and not 8.84. I am new to python or programming in general. I don't want to print it as a string, the result will be further used. For more information o...
You want to use the decimal module but you also need to specify the rounding mode. Here's an example: ``` >>> import decimal >>> decimal.Decimal('8.333333').quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_UP) Decimal('8.34') >>> decimal.Decimal('8.333333').quantize(decimal.Decimal('.01'), rounding=decimal.ROUN...
Python unicode: why in one machine works but in another one it failed sometimes?
4,518,797
4
2010-12-23T12:36:01Z
4,518,941
12
2010-12-23T12:58:16Z
[ "python", "unicode", "python-2.x" ]
I found unicode in python really troublesome, why not Python use utf-8 for all the strings? I am in China so I have to use some Chinese string that can't represent by ascii, I use `u''` to denote a string, it works well in my ubuntu machine, but in another ubuntu machine (VPS provided by linode.com), it fails some time...
The thing with the famous `UnicodeDecodeError` is when you do some string manipulation like the one you did just now: ``` user.record["fullname"] + u" 准备好了" ``` because what you're doing is concatenating an str with unicode , so python will do an **implicit coercion** of the str to an unicode before doing the...
setuptools: package data folder location
4,519,127
40
2010-12-23T13:25:48Z
5,423,147
68
2011-03-24T17:33:29Z
[ "python", "setuptools" ]
I use setuptools to distribute my python package. Now I need to distribute additional datafiles. From what I've gathered fromt the setuptools documentation, I need to have my data files inside the package directory. However, I would rather have my datafiles inside a subdirectory in the root directory. What I would li...
**Option 1: Install as package data** The main advantage of placing data files inside the root of your Python package is that it lets you avoid worrying about where the files will live on a user's system, which may be Windows, Mac, Linux, some mobile platform, or inside an Egg. You can always find the directory `data`...
Assigning Multiple Cores to a Python Program
4,519,951
2
2010-12-23T15:11:40Z
4,519,978
9
2010-12-23T15:15:13Z
[ "python", "parallel-processing", "cpu-cores" ]
I notice when I run my heavily CPU dependant python programs, it only uses a single core. Is it possible to assign multiple cores to the program when I run it?
You have to program explicitly for multiple cores. See the Symmetric Multiprocessing options on [this page](http://wiki.python.org/moin/ParallelProcessing) for the many parallel processing solutions in Python. [Parallel Python](http://www.parallelpython.com/) is a good choice if you can't be bothered to compare the opt...
Every day,week,month,year in AppEngine cron (python)
4,521,385
8
2010-12-23T18:23:18Z
4,525,038
12
2010-12-24T08:02:38Z
[ "python", "google-app-engine", "cron" ]
I'm trying to set an appengine task to be repeated at midnight of every day, week, month, and year, for clearing a high score list for a game. My cron.yaml looks like this: ``` - description: daily clear url: /delete?off=10 schedule: every day 00:00 - description: weekly clear url: /delete?off=20 schedule: ev...
The docs you link to give examples of how you could achieve all of the results you want. ``` # Daily: every day 00:00 # Weekly: every monday 00:00 # Monthly: 1 of month 00:00 # Yearly: 1 of jan 00:00 ```
Delete blank rows from CSV?
4,521,426
10
2010-12-23T18:29:56Z
4,521,533
15
2010-12-23T18:43:47Z
[ "python", "csv", "delete-row" ]
I have a large csv file in which some rows are entirely blank. How do I use Python to delete all blank rows from the csv? After all your suggestions, this is what I have so far ``` import csv # open input csv for reading inputCSV = open(r'C:\input.csv', 'rb') # create output csv for writing outputCSV = open(r'C:\OU...
Use the `csv` module: ``` import csv ... input = open(in_fnam, 'rb') output = open(out_fnam, 'wb') writer = csv.writer(output) for row in csv.reader(input): if row: writer.writerow(row) input.close() output.close() ``` If you also need to remove rows where all of the fields are empty, change the `if row:...
How do I change the choices in a Django model?
4,521,821
3
2010-12-23T19:29:00Z
4,521,943
7
2010-12-23T19:45:26Z
[ "python", "django", "django-models", "migration", "django-south" ]
I have a Django model that uses the `choices` [attribute](http://docs.djangoproject.com/en/dev/ref/models/fields/#choices). ``` COLOR_CHOICES = ( ('R', 'Red'), ('B', 'Blue'), ) class Toy(models.Model): color = models.CharField(max_length=1, choices=COLOR_CHOICES) ``` My code is in production and now I'd l...
Django doesn't enforce choices on a database level, it only uses them for the presentation of the widgets and in validation. If you want them a bit more 'dynamic', for example to have different ones on different servers you could define them via `settings.py`: ``` from django.conf import settings COLOR_CHOICES = geta...
Python - Separate program logic and GUI code?
4,522,218
10
2010-12-23T20:24:43Z
4,522,244
10
2010-12-23T20:29:01Z
[ "pygtk", "python" ]
What would be the best way of separating program logic to the GUI code? I wanted different GUI (GTK, KDE, CLI) code using the same program logic. I was thinking of using different python module (winecellar-common, winecellar-gtk, winecellar-cli) not sure how I would do this and if its the best way. \****EDITED*\*** ...
Define functions or classes for your business logic in one module, and define your presentation in another, using those functions to get your presentation. You should almost entirely be using functions and classes from the main module in the GUI module. You should do the same thing for your CLI. That way, you can have ...
How to get Facebook Login Button To Display "Logout"
4,522,427
6
2010-12-23T20:59:58Z
7,313,186
23
2011-09-05T22:17:33Z
[ "javascript", "python", "facebook", "facebook-graph-api" ]
I apologize ahead of time if this is clearly documented somewhere on the FB developer site - but I can't find it (so please link me if appropriate). I've implemented the FB login button on a website using GAE + Python. Here is the HTML: ``` <fb:login-button></fb:login-button> <div id="fb-root"></div> <script src="htt...
Its not documented on the FB SDK [login-button page](http://developers.facebook.com/docs/reference/plugins/login/) for some reason, but you can add the `autologoutlink="true"` attribute to the tag and it will show a logout button if you are logged in rather than just making the button invisible. ``` <fb:login-button a...
How do I generate (and label) a random integer with python 3.2?
4,522,733
7
2010-12-23T21:57:16Z
4,522,753
8
2010-12-23T21:59:48Z
[ "python", "python-3.x", "random", "integer", "label" ]
Okay, so I'm admittedly a newbie to programming, but I can't determine how to get python v3.2 to generate a random positive integer between parameters I've given it. Just so you can understand the context, I'm trying to create a guessing-game where the user inputs parameters (say 1 to 50), and the computer generates a ...
Use [random.randrange](http://docs.python.org/dev/py3k/library/random.html#random.randrange) or [random.randint](http://docs.python.org/dev/py3k/library/random.html#random.randint) (Note the links are to the Python 3k docs). ``` In [67]: import random In [69]: random.randrange(1,10) Out[69]: 8 ```
3D Scene Renderer for Python
4,522,748
16
2010-12-23T21:59:20Z
4,523,262
20
2010-12-23T23:37:24Z
[ "python", "3d", "scene" ]
I'm looking for an easy to use 3D scene renderer for Python. All I'm looking for is to be able to: * Load a 3D scene model * Render it using an orthographic camera * Export the image so I can perform analysis So far the software I've found is either too low-level (like basic OpenGL bindings) or too complex (like Ogre...
Really depends exactly what you want to accomplish. How complex is your scene? What sort of render quality are you after? Do you need real-time animation, or are rendered stills good enough? First-rate, full game engines (have been used for commercial games) * Panda3d <http://www.panda3d.org/> * PyOgre <http://www.og...
Modifying a global variable inside a function
4,522,786
7
2010-12-23T22:04:45Z
4,522,836
9
2010-12-23T22:13:06Z
[ "python" ]
I have defined the following function: ``` def GMM(s1, s2, s3, s4, s5, a): """The GMM objective function. Arguments --------- si: float standard deviations of preference distribution a: float marginal utility of residutal income Paramters --------- ...
``` globalVariable = 0 def test(): global globalVariable globalVariable = 10 test() print globalVariable ``` You can edit a global variable in this way.
Modifying a global variable inside a function
4,522,786
7
2010-12-23T22:04:45Z
4,523,059
16
2010-12-23T22:57:00Z
[ "python" ]
I have defined the following function: ``` def GMM(s1, s2, s3, s4, s5, a): """The GMM objective function. Arguments --------- si: float standard deviations of preference distribution a: float marginal utility of residutal income Paramters --------- ...
There are multiple ways to achieve what you want. delta is saved across function calls in the following examples. 1- Class ``` class Example: def __init__(self, value): self.delta = value def gmm(self): self.delta += 1 return self.delta e = Example(0) print e.gmm() ``` 2- Generator ``` def gmm(): ...
PyQt signal with arguments of arbitrary type / PyQt_PyObject equivalent for new-style signals
4,523,006
5
2010-12-23T22:44:40Z
5,186,587
11
2011-03-03T21:10:37Z
[ "python", "qt", "pyqt", "signals" ]
I have an object that should signal that a value has changed by emitting a signal with the new value as an argument. The type of the value can change, and so I'm unsure of how to write the signal type. I know that I can acconmplish this using old-style signals like this: ``` self.emit(SIGNAL("valueChanged(PyQt_PyObjec...
First, the object you're emitting from needs the signal defined as an attribute of its *class*: ``` class SomeClass(QObject): valueChanged = pyqtSignal(object) ``` Notice the signal has one argument of type *object*, which should allow anything to pass through. Then, you should be able to emit the signal from wit...
chr() equivalent returning a bytes object, in py3k
4,523,505
23
2010-12-24T00:37:28Z
4,523,520
24
2010-12-24T00:41:43Z
[ "python", "unicode", "python-3.x" ]
Python 2.x has `chr()`, which converts a number in the range 0-255 to a byte string with one character with that numeric value, and `unichr()`, which converts a number in the range 0-0x10FFFF to a Unicode string with one character with that Unicode codepoint. Python 3.x replaces `unichr()` with `chr()`, in keeping with...
Try the following: ``` b = bytes([x]) ``` For example: ``` >>> bytes([255]) b'\xff' ```
Python ASCII to binary
4,523,551
6
2010-12-24T00:46:36Z
4,523,564
13
2010-12-24T00:49:50Z
[ "python", "binary", "ascii" ]
Is there a builtin function that converts ASCII to binary? For example. converts 'P' to 01010000. I'm using Python 2.6.6
How about two together? ``` bin(ord('P')) # 0b1010000 ```