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
Statistics: combinations in Python
3,025,162
73
2010-06-11T18:13:16Z
3,027,128
84
2010-06-12T01:25:40Z
[ "python", "statistics", "combinations" ]
I need to compute combinatorials (nCr) in Python but cannot find the function to do that in `math`, `numpy` or `stat` libraries. Something like a function of the type: ``` comb = calculate_combinations(n, r) ``` I need the number of possible combinations, not the actual combinations, so `itertools.combinations` does ...
Why not write it yourself? It's a one-liner or such: ``` from operator import mul # or mul=lambda x,y:x*y from fractions import Fraction def nCk(n,k): return int( reduce(mul, (Fraction(n-i, i+1) for i in range(k)), 1) ) ``` Test - printing Pascal's triangle: ``` >>> for n in range(17): ... print ' '.join(...
Statistics: combinations in Python
3,025,162
73
2010-06-11T18:13:16Z
12,115,521
8
2012-08-24T19:29:45Z
[ "python", "statistics", "combinations" ]
I need to compute combinatorials (nCr) in Python but cannot find the function to do that in `math`, `numpy` or `stat` libraries. Something like a function of the type: ``` comb = calculate_combinations(n, r) ``` I need the number of possible combinations, not the actual combinations, so `itertools.combinations` does ...
Here's another alternative. This one was originally written in C++, so it can be backported to C++ for a finite-precision integer (e.g. \_\_int64). The advantage is (1) it involves only integer operations, and (2) it avoids bloating the integer value by doing successive pairs of multiplication and division. I've tested...
Statistics: combinations in Python
3,025,162
73
2010-06-11T18:13:16Z
19,109,792
16
2013-10-01T06:54:11Z
[ "python", "statistics", "combinations" ]
I need to compute combinatorials (nCr) in Python but cannot find the function to do that in `math`, `numpy` or `stat` libraries. Something like a function of the type: ``` comb = calculate_combinations(n, r) ``` I need the number of possible combinations, not the actual combinations, so `itertools.combinations` does ...
A literal translation of the mathematical definition is quite adequate in a lot of cases (remembering that Python will automatically use big number arithmetic): ``` from math import factorial def calculate_combinations(n, r): return factorial(n) // factorial(r) // factorial(n-r) ``` For some inputs I tested (e.g...
Statistics: combinations in Python
3,025,162
73
2010-06-11T18:13:16Z
20,161,471
18
2013-11-23T11:00:15Z
[ "python", "statistics", "combinations" ]
I need to compute combinatorials (nCr) in Python but cannot find the function to do that in `math`, `numpy` or `stat` libraries. Something like a function of the type: ``` comb = calculate_combinations(n, r) ``` I need the number of possible combinations, not the actual combinations, so `itertools.combinations` does ...
If you want an exact result, use [`sympy.binomial`](http://docs.sympy.org/0.6.7/modules/functions.html#binomial). It seems to be the fastest method, hands down. ``` x = 1000000 y = 234050 %timeit scipy.misc.comb(x, y, exact=True) 1 loops, best of 3: 1min 27s per loop %timeit gmpy.comb(x, y) 1 loops, best of 3: 1.97 ...
using wild card when listing directories in python
3,025,759
7
2010-06-11T19:50:12Z
3,025,787
15
2010-06-11T19:54:02Z
[ "python", "file-io", "filesystems", "directory-structure" ]
how can I use wild cars like '\*' when getting a list of files inside a directory in Python? for example, I want something like: ``` os.listdir('foo/*bar*/*.txt') ``` which would return a list of all the files ending in .txt in directories that have bar in their name inside of the foo parent directory. how can I do ...
[glob.glob](http://docs.python.org/library/glob.html#glob.glob) for the win.
Is there a performance gain from defining routes in app.yaml versus one large mapping in a WSGIApplication in AppEngine?
3,025,921
16
2010-06-11T20:15:42Z
3,026,641
12
2010-06-11T22:24:02Z
[ "python", "performance", "google-app-engine", "yaml" ]
# Scenario 1 This involves using one "gateway" route in `app.yaml` and then choosing the `RequestHandler` in the `WSGIApplication`. ## app.yaml ``` - url: /.* script: main.py ``` ## main.py ``` from google.appengine.ext import webapp class Page1(webapp.RequestHandler): def get(self): self.response.o...
The only performance implication relates to the loading of modules: Modules are loaded on an instance when they're first used, and splitting things up requires fewer module loads to serve a page on a new instance. This is pretty minimal, though, as you can just as easily have the handler script dynamically load the ne...
What does this `_time_independent_equals` mean?
3,027,286
9
2010-06-12T02:52:45Z
3,027,306
18
2010-06-12T03:02:28Z
[ "python", "tornado" ]
In the [tornado](http://www.tornadoweb.org/).web module there is a function called `_time_independent_equals`: ``` def _time_independent_equals(a, b): if len(a) != len(b): return False result = 0 for x, y in zip(a, b): result |= ord(x) ^ ord(y) return result == 0 ``` It is used to comp...
That function does not simply compare the strings, it tries to always take the same amount of time to execute. This is useful for security tasks like comparing passwords. If the function returned on the first mismatching byte, an attacker could try all possible first bytes and know that the one that takes longest is a...
Contrary to Python 3.1 Docs, hash(obj) != id(obj). So which is correct?
3,027,838
10
2010-06-12T07:12:11Z
3,027,910
10
2010-06-12T07:43:32Z
[ "python", "hash" ]
The following is from the Python v3.1.2 documentation: From The Python Language Reference Section 3.3.1 Basic Customization: ``` object.__hash__(self) ... User-defined classes have __eq__() and __hash__() methods by default; with them, all objects compare unequal (except with themselves) and x.__hash__() returns id...
I'm guessing this was a change made in Python 3.x to improve performance. Check out [issue 5186](http://bugs.python.org/issue5186), then look a little more closely at your mismatched numbers: ``` >>> bin(11893680) '0b101101010111101110110000' >>> bin(743355) '0b10110101011110111011' >>> 11893680 >> 4 743355 ``` It's ...
Urllib's urlopen breaking on some sites (e.g. StackApps api): returns garbage results
3,028,426
10
2010-06-12T10:58:16Z
3,028,525
10
2010-06-12T11:41:12Z
[ "python", "urllib2", "urllib", "urlopen" ]
I'm using `urllib2`'s `urlopen` function to try and get a JSON result from the StackOverflow api. The code I'm using: ``` >>> import urllib2 >>> conn = urllib2.urlopen("http://api.stackoverflow.com/0.8/users/") >>> conn.readline() ``` The result I'm getting: ``` '\x1f\x8b\x08\x00\x00\x00\x00\x00\x04\x00\xed\xbd\x07...
That almost looks like something you would be feeding to pickle. Maybe something in the User-Agent string or Accepts header that urllib2 is sending is causing StackOverflow to send something other than JSON. One telltale is to look at `conn.headers.headers` to see what the Content-Type header says. And this question,...
non-uniform distributed random array
3,028,571
4
2010-06-12T11:55:09Z
3,028,629
16
2010-06-12T12:18:22Z
[ "python", "random" ]
I need to generate a vector of random float numbers between [0,1] such that their sum equals 1 and that are distributed non-uniformly. Is there any python function that generates such a vector? Best wishes
The distribution you are probably looking for is called the [Dirichlet distribution](http://en.wikipedia.org/wiki/Dirichlet_distribution). There's no built-in function in Python for drawing random numbers from a Dirichlet distribution, but [NumPy](http://www.numpy.org) contains one: ``` >>> from numpy.random.mtrand im...
Storing cookielib cookies in a database
3,028,923
4
2010-06-12T14:04:06Z
3,029,020
7
2010-06-12T14:45:05Z
[ "python", "urllib2", "cookielib" ]
I'm using the `cookielib` module to handle HTTP cookies when using the `urllib2` module in Python 2.6 in a way similar to this snippet: ``` import cookielib, urllib2 cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) r = opener.open("http://example.com/") ``` I'd like to store t...
`cookielib.Cookie`, to quote its docstring (in its [sources](http://svn.python.org/view/python/trunk/Lib/cookielib.py?revision=81466&view=markup)), > is deliberately a very simple class. > It just holds attributes. so `pickle` (or other serialization approaches) are just fine for saving and restoring each `Cookie` in...
Best style for Python programs: what do you suggest?
3,028,961
2
2010-06-12T14:22:51Z
3,029,682
8
2010-06-12T18:24:12Z
[ "python", "encryption", "coding-style" ]
A friend of mine wanted help learning to program, so he gave me all the programs that he wrote for his previous classes. The last program that he wrote was an encryption program, and after rewriting all his programs in Python, this is how his encryption program turned out (after adding my own requirements). ``` #! /us...
Since you asked about formatting and style, I'm surprised that nobody else has mentioned [PEP 8](http://www.python.org/dev/peps/pep-0008/) yet. It's nominally a guide for modules that want to be included in the standard library, but I find most of its guidance to be applicable pretty much everywhere.
Why can't I install psycopg2? (Python 2.6.4, PostgreSQL 8.4, OS X 10.6.3)
3,029,274
3
2010-06-12T16:10:09Z
3,029,361
8
2010-06-12T16:36:04Z
[ "python", "osx", "postgresql", "psycopg2" ]
**ORIGINAL MESSAGE (now outdated):** After running python setup.py install I get the following: ``` Warning: Unable to find 'pg_config' filebuilding 'psycopg2._psycopg' extension gcc-4.0 -arch ppc -arch i386 -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -O3 - DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION=...
(**See edits below for your updated question**) You don't have the "gcc4.0" compiler executable on your machine, or the right version, or installed in a location that python can't find/use. XCode/Developer Tools (which [include GCC](http://developer.apple.com/tools/gcc_overview.html)) should be on your original OSX in...
How do I get a thread safe print in Python 2.6?
3,029,816
32
2010-06-12T19:15:43Z
3,029,845
12
2010-06-12T19:26:36Z
[ "python", "multithreading" ]
`print` in Python is not thread safe according to [these](http://bramcohen.livejournal.com/70606.html) [articles](http://bramcohen.livejournal.com/70686.html). A Python 3 work-around is offered in the latter article. How do I get a thread safe `print` in Python 2.6?
I dont know if there is any better way instead this locking mechanism, but atleast it looks easy. I am also not sure if printing really isnt thread safe. Edit: Okay tested it my self now, you are right, you can get really wierd looking output. And you dont need the **future** import, its just there, because i use Pyth...
How do I get a thread safe print in Python 2.6?
3,029,816
32
2010-06-12T19:15:43Z
3,029,854
16
2010-06-12T19:29:15Z
[ "python", "multithreading" ]
`print` in Python is not thread safe according to [these](http://bramcohen.livejournal.com/70606.html) [articles](http://bramcohen.livejournal.com/70686.html). A Python 3 work-around is offered in the latter article. How do I get a thread safe `print` in Python 2.6?
The issue is that python uses seperate opcodes for the NEWLINE printing and the printing of the object itself. The easiest solution is probably to just use an explicit sys.stdout.write with an explicit newline.
How do I get a thread safe print in Python 2.6?
3,029,816
32
2010-06-12T19:15:43Z
3,030,755
28
2010-06-13T01:40:11Z
[ "python", "multithreading" ]
`print` in Python is not thread safe according to [these](http://bramcohen.livejournal.com/70606.html) [articles](http://bramcohen.livejournal.com/70686.html). A Python 3 work-around is offered in the latter article. How do I get a thread safe `print` in Python 2.6?
Interesting problem -- considering all the things that happen within a `print` statement, including the setting and checking of the `softspace` attribute, making it "threadsafe" (meaning, actually: a thread that's printing only yields "control of standard output" to another thread when it's printing a newline, so that ...
Disable logging during manage.py test?
3,030,277
4
2010-06-12T22:11:10Z
3,798,131
8
2010-09-26T14:04:20Z
[ "python", "django", "logging" ]
I utilize the standard python logging module. When I call `python manage.py test` I'd like to disable logging before all the tests are ran. Is there a signal or some other kind of hook I could use to call logging.disable? Or is there some other way to disable logging when `python manage.py test` is ran?
As an easy alternative, you can disable logging when running tests in your settings file like this: ``` if 'test' in sys.argv: logger.removeHandler(handler) logger.setLevel(logging.ERROR) ```
Disable logging during manage.py test?
3,030,277
4
2010-06-12T22:11:10Z
13,682,482
9
2012-12-03T11:39:54Z
[ "python", "django", "logging" ]
I utilize the standard python logging module. When I call `python manage.py test` I'd like to disable logging before all the tests are ran. Is there a signal or some other kind of hook I could use to call logging.disable? Or is there some other way to disable logging when `python manage.py test` is ran?
There is actually a much better way to do so, with [django-nose](https://github.com/jbalogh/django-nose) there is a kwarg: Just run: ``` ./bin/manage.py test --logging-clear-handlers ```
Writing to a file in Python inserts null bytes
3,030,343
7
2010-06-12T22:32:19Z
3,030,363
8
2010-06-12T22:38:13Z
[ "python", "file", "file-io" ]
I'm writing a todo list program. It keeps a file with a thing to do per line, and lets the user add or delete items. The problem is that for some reason, I end up with a lot of zero bytes at the start of the file, even though the item is correctly deleted. I'll show you a couple of screenshots to make sure I'm making m...
It looks to me like you're forgetting to rewind your file stream. After `f.truncate(0)`, add `f.seek(0)`. Otherwise, I think your next write will try to start at the position from which you left off, filling in null bytes on its way there. (Notice that the number of null characters in your example equals the number of...
Numpy array, how to select indices satisfying multiple conditions?
3,030,480
53
2010-06-12T23:28:05Z
3,030,662
84
2010-06-13T00:50:32Z
[ "python", "numpy" ]
Suppose I have a numpy array `x = [5, 2, 3, 1, 4, 5]`, `y = ['f', 'o', 'o', 'b', 'a', 'r']`. I want to select the elements in `y` corresponding to elements in `x` that are greater than 1 and less than 5. I tried ``` x = array([5, 2, 3, 1, 4, 5]) y = array(['f','o','o','b','a','r']) output = y[x > 1 & x < 5] # desired...
Your expression works if you add parentheses: ``` >>> y[(1 < x) & (x < 5)] array(['o', 'o', 'a'], dtype='|S1') ```
Numpy array, how to select indices satisfying multiple conditions?
3,030,480
53
2010-06-12T23:28:05Z
18,644,339
17
2013-09-05T19:23:44Z
[ "python", "numpy" ]
Suppose I have a numpy array `x = [5, 2, 3, 1, 4, 5]`, `y = ['f', 'o', 'o', 'b', 'a', 'r']`. I want to select the elements in `y` corresponding to elements in `x` that are greater than 1 and less than 5. I tried ``` x = array([5, 2, 3, 1, 4, 5]) y = array(['f','o','o','b','a','r']) output = y[x > 1 & x < 5] # desired...
IMO OP does not actually want [`np.bitwise_and()` (aka `&`)](http://docs.scipy.org/doc/numpy/reference/generated/numpy.bitwise_and.html) but actually wants [`np.logical_and()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.logical_and.html) because they are comparing logical values such as `True` and `False...
Where is the Google App Engine SDK path on OSX?
3,030,585
28
2010-06-13T00:14:37Z
3,030,645
51
2010-06-13T00:46:47Z
[ "python", "eclipse", "google-app-engine", "pydev" ]
I need to know for creating a Pydev Google App Engine Project in Eclipse.
/usr/local/google\_appengine - that's a symlink that links to the SDK.
Where is the Google App Engine SDK path on OSX?
3,030,585
28
2010-06-13T00:14:37Z
5,189,889
24
2011-03-04T05:01:26Z
[ "python", "eclipse", "google-app-engine", "pydev" ]
I need to know for creating a Pydev Google App Engine Project in Eclipse.
> `/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine`
Installing psycopg2 (postgresql) in virtualenv on windows
3,030,984
24
2010-06-13T03:42:02Z
3,705,772
15
2010-09-14T02:44:30Z
[ "python", "postgresql", "virtualenv", "psycopg2", "easy-install" ]
I installed psycopg2 in virtualenv using `easy_install psycopg2`. I did not see any errors and looks like installation went fine.. there is an egg file created in the site-packages dir for psycopg2.. but when I run import psycopg2 in the interpreter, I am getting following error.. any clue? How can I fix it.. any othe...
Edit: this solution is outdated. [Refer to this answer](http://stackoverflow.com/questions/5382801/where-can-i-download-binary-eggs-with-psycopg2-for-windows/5383266#5383266) instead. I had the same problem. Following the suggestion on [the download page](http://www.stickpeople.com/projects/python/win-psycopg/) of the...
How come string.maketrans does not work in Python 3.1?
3,031,045
10
2010-06-13T04:15:42Z
3,031,057
9
2010-06-13T04:19:04Z
[ "python", "python-3.x" ]
I'm a Python newbie. How come [this](http://www.tutorialspoint.com/python/string_maketrans.htm) doesn't work in Python 3.1? ``` from string import maketrans # Required to call maketrans function. intab = "aeiou" outtab = "12345" trantab = maketrans(intab, outtab) str = "this is string example....wow!!!"; print st...
Strings are **not** bytes. This is a simple definition in Python 3. Strings are Unicode (which are not bytes) Unicode strings use `"..."` or `'...'` Bytes are bytes (which are not strings) Byte strings use `b"..."` or `b'...'`. Use `b"aeiou"` to create a byte sequence composed of the ASCII codes for certain letters...
How come string.maketrans does not work in Python 3.1?
3,031,045
10
2010-06-13T04:15:42Z
3,031,061
17
2010-06-13T04:20:24Z
[ "python", "python-3.x" ]
I'm a Python newbie. How come [this](http://www.tutorialspoint.com/python/string_maketrans.htm) doesn't work in Python 3.1? ``` from string import maketrans # Required to call maketrans function. intab = "aeiou" outtab = "12345" trantab = maketrans(intab, outtab) str = "this is string example....wow!!!"; print st...
Stop trying to learn Python 3 by reading Python 2 documentation. > ``` > intab = 'aeiou' > outtab = '12345' > > s = 'this is string example....wow!!!' > > print(s.translate({ord(x): y for (x, y) in zip(intab, outtab)})) > ```
How come string.maketrans does not work in Python 3.1?
3,031,045
10
2010-06-13T04:15:42Z
7,463,915
22
2011-09-18T19:33:03Z
[ "python", "python-3.x" ]
I'm a Python newbie. How come [this](http://www.tutorialspoint.com/python/string_maketrans.htm) doesn't work in Python 3.1? ``` from string import maketrans # Required to call maketrans function. intab = "aeiou" outtab = "12345" trantab = maketrans(intab, outtab) str = "this is string example....wow!!!"; print st...
You don't need to use `bytes.maketrans()` when `str` would be simpler and eliminate the need for the 'b' prefix: ``` print("Swap vowels for numbers.".translate(str.maketrans('aeiou', '12345'))) ```
Python: Recursively access dict via attributes as well as index access?
3,031,219
21
2010-06-13T05:42:01Z
3,031,270
38
2010-06-13T06:08:30Z
[ "python", "oop", "dictionary", "getattr" ]
I'd like to be able to do something like this: ``` from dotDict import dotdictify life = {'bigBang': {'stars': {'planets': [] } } } dotdictify(life) #this would be the regular way: life['bigBang']['stars']['planets'] = {'earth': {'singleCellLife': {} }} #But how can we make this work? life....
Here's one way to create this kind of experience: ``` class dotdictify(dict): marker = object() def __init__(self, value=None): if value is None: pass elif isinstance(value, dict): for key in value: self.__setitem__(key, value[key]) else: ...
How do I make a defaultdict safe for unexpecting clients?
3,031,817
6
2010-06-13T10:05:04Z
3,031,915
14
2010-06-13T10:45:31Z
[ "python", "default-value" ]
Several times (even several in a row) I've been bitten by the defaultdict bug: forgetting that something is actually a defaultdict and treating it like a regular dictionary. ``` d = defaultdict(list) ... try: v = d["key"] except KeyError: print "Sorry, no dice!" ``` For those who have been bitten too, the probl...
You may still convert it to an normal dict. ``` d = collections.defaultdict(list) d = dict(d) ```
Starting a separate process
3,032,805
10
2010-06-13T15:41:51Z
3,032,818
9
2010-06-13T15:46:13Z
[ "python", "multiprocessing" ]
I want a script to start a new process, such that the new process continues running after the initial script exits. I expected that I could use `multiprocessing.Process` to start a new process, and set `daemon=True` so that the main script may exit while the created process continues running. But it seems that the sec...
From the Python docs: > When a process exits, it attempts to > terminate all of its daemonic child > processes. This is the expected behavior.
Starting a separate process
3,032,805
10
2010-06-13T15:41:51Z
3,032,939
7
2010-06-13T16:16:24Z
[ "python", "multiprocessing" ]
I want a script to start a new process, such that the new process continues running after the initial script exits. I expected that I could use `multiprocessing.Process` to start a new process, and set `daemon=True` so that the main script may exit while the created process continues running. But it seems that the sec...
Simply use the `subprocess` module: ``` import subprocess subprocess.Popen(["sleep", "60"]) ```
Why are Python Programs often slower than the Equivalent Program Written in C or C++?
3,033,329
34
2010-06-13T18:09:11Z
3,033,355
9
2010-06-13T18:12:59Z
[ "c++", "python", "c", "performance", "programming-languages" ]
Why does Python seem slower, on average, than C/C++? I learned Python as my first programming language, but I've only just started with C and already I feel I can see a clear difference.
The difference between python and C is the usual difference between an interpreted (bytecode) and compiled (to native) language. Personally, I don't really see python as slow, it manages just fine. If you try to use it outside of its realm, of course, it will be slower. But for that, you can write C extensions for pyth...
Why are Python Programs often slower than the Equivalent Program Written in C or C++?
3,033,329
34
2010-06-13T18:09:11Z
3,033,379
53
2010-06-13T18:22:31Z
[ "c++", "python", "c", "performance", "programming-languages" ]
Why does Python seem slower, on average, than C/C++? I learned Python as my first programming language, but I've only just started with C and already I feel I can see a clear difference.
Python is a higher level language than C, which means it abstracts the details of the computer from you - memory management, pointers, etc, and allows you to write programs in a way which is closer to how humans think. It is true that C code usually runs 10 to 100 times faster than Python code if you measure only the ...
Why are Python Programs often slower than the Equivalent Program Written in C or C++?
3,033,329
34
2010-06-13T18:09:11Z
3,033,387
33
2010-06-13T18:24:56Z
[ "c++", "python", "c", "performance", "programming-languages" ]
Why does Python seem slower, on average, than C/C++? I learned Python as my first programming language, but I've only just started with C and already I feel I can see a clear difference.
CPython is particularly slow because it has no Just in Time optimizer (since it's the reference implementation and chooses simplicity over performance in certain cases). [Unladen Swallow](http://en.wikipedia.org/wiki/Unladen_Swallow) is a project to add an LLVM-backed JIT into CPython, and achieves massive speedups. It...
Why are Python Programs often slower than the Equivalent Program Written in C or C++?
3,033,329
34
2010-06-13T18:09:11Z
3,033,545
7
2010-06-13T19:15:44Z
[ "c++", "python", "c", "performance", "programming-languages" ]
Why does Python seem slower, on average, than C/C++? I learned Python as my first programming language, but I've only just started with C and already I feel I can see a clear difference.
Compilation vs interpretation isn't important here: Python *is* compiled, and it's a tiny part of the runtime cost for any non-trivial program. The primary costs are: the lack of an integer type which corresponds to native integers (making all integer operations vastly more expensive), the lack of static typing (which...
SQLAlchemy automatically converts str to unicode on commit
3,033,741
3
2010-06-13T20:15:25Z
3,033,942
11
2010-06-13T21:15:05Z
[ "python", "unicode", "sqlalchemy" ]
When inserting an object into a database with SQLAlchemy, all it's properties that correspond to String() columns are automatically transformed from <type 'str'> to <type 'unicode'>. Is there a way to prevent this behavior? Here is the code: ``` from sqlalchemy import create_engine, Table, Column, Integer, String, Me...
Actually, there is a way to do that. Just execute this line of code after creating engine: engine.raw\_connection().connection.text\_factory = str
Python thread pool similar to the multiprocessing Pool?
3,033,952
180
2010-06-13T21:17:16Z
3,111,136
7
2010-06-24T14:55:06Z
[ "python", "multithreading", "missing-features" ]
Is there a Pool class for worker **threads**, similar to the multiprocessing module's [Pool class](http://docs.python.org/library/multiprocessing.html#module-multiprocessing.pool)? I like for example the easy way to parallelize a map function ``` def long_running_func(p): c_func_no_gil(p) p = multiprocessing.Poo...
Here's something that looks promising over in the Python Cookbook: [Recipe 576519: Thread pool with same API as (multi)processing.Pool (Python)](http://code.activestate.com/recipes/576519-thread-pool-with-same-api-as-multiprocessingpool/)
Python thread pool similar to the multiprocessing Pool?
3,033,952
180
2010-06-13T21:17:16Z
3,386,632
248
2010-08-02T09:52:28Z
[ "python", "multithreading", "missing-features" ]
Is there a Pool class for worker **threads**, similar to the multiprocessing module's [Pool class](http://docs.python.org/library/multiprocessing.html#module-multiprocessing.pool)? I like for example the easy way to parallelize a map function ``` def long_running_func(p): c_func_no_gil(p) p = multiprocessing.Poo...
I just found out that there actually *is* a thread-based Pool interface in the `multiprocessing` module, however it is hidden somewhat and not properly documented. It can be imported via ``` from multiprocessing.pool import ThreadPool ``` It is implemented using a dummy Process class wrapping a python thread. This t...
Python thread pool similar to the multiprocessing Pool?
3,033,952
180
2010-06-13T21:17:16Z
7,257,510
28
2011-08-31T13:23:19Z
[ "python", "multithreading", "missing-features" ]
Is there a Pool class for worker **threads**, similar to the multiprocessing module's [Pool class](http://docs.python.org/library/multiprocessing.html#module-multiprocessing.pool)? I like for example the easy way to parallelize a map function ``` def long_running_func(p): c_func_no_gil(p) p = multiprocessing.Poo...
For something very simple and lightweight (slightly modified from [here](http://code.activestate.com/recipes/577187-python-thread-pool/)): ``` from Queue import Queue from threading import Thread class Worker(Thread): """Thread executing tasks from a given tasks queue""" def __init__(self, tasks):...
Python thread pool similar to the multiprocessing Pool?
3,033,952
180
2010-06-13T21:17:16Z
11,529,742
74
2012-07-17T19:42:40Z
[ "python", "multithreading", "missing-features" ]
Is there a Pool class for worker **threads**, similar to the multiprocessing module's [Pool class](http://docs.python.org/library/multiprocessing.html#module-multiprocessing.pool)? I like for example the easy way to parallelize a map function ``` def long_running_func(p): c_func_no_gil(p) p = multiprocessing.Poo...
In Python 3 you can use [`concurrent.futures.ThreadPoolExecutor`](https://docs.python.org/dev/library/concurrent.futures.html#threadpoolexecutor), i.e.: ``` executor = ThreadPoolExecutor(max_workers=10) a = executor.submit(my_function) ``` See the [docs](http://docs.python.org/py3k/library/concurrent.futures.html) fo...
Python thread pool similar to the multiprocessing Pool?
3,033,952
180
2010-06-13T21:17:16Z
13,652,009
24
2012-11-30T19:42:33Z
[ "python", "multithreading", "missing-features" ]
Is there a Pool class for worker **threads**, similar to the multiprocessing module's [Pool class](http://docs.python.org/library/multiprocessing.html#module-multiprocessing.pool)? I like for example the easy way to parallelize a map function ``` def long_running_func(p): c_func_no_gil(p) p = multiprocessing.Poo...
Yes, and it seems to have (more or less) the same API. ``` import multiprocessing def worker(lnk): .... def start_process(): ..... .... if(PROCESS): pool = multiprocessing.Pool(processes=POOL_SIZE, initializer=start_process) else: pool = multiprocessing.pool.ThreadPool(processes=POOL_SIZE, initia...
How to apply itertools.product to elements of a list of lists?
3,034,014
19
2010-06-13T21:34:52Z
3,034,027
24
2010-06-13T21:38:40Z
[ "python", "itertools", "cartesian-product" ]
I have a list of arrays and I would like to get the cartesian product of the elements in the arrays. I will use an example to make this more concrete... itertools.product seems to do the trick but I am stuck in a little detail. ``` arrays = [(-1,+1), (-2,+2), (-3,+3)]; ``` If I do ``` cp = list(itertools.product(a...
``` >>> list(itertools.product(*arrays)) [(-1, -2, -3), (-1, -2, 3), (-1, 2, -3), (-1, 2, 3), (1, -2, -3), (1, -2, 3), (1, 2, -3), (1, 2, 3)] ``` This will feed all the pairs as separate arguments to `product`, which will then give you the cartesian product of them. The reason your version isn't working is that you a...
How to apply itertools.product to elements of a list of lists?
3,034,014
19
2010-06-13T21:34:52Z
3,034,036
29
2010-06-13T21:41:14Z
[ "python", "itertools", "cartesian-product" ]
I have a list of arrays and I would like to get the cartesian product of the elements in the arrays. I will use an example to make this more concrete... itertools.product seems to do the trick but I am stuck in a little detail. ``` arrays = [(-1,+1), (-2,+2), (-3,+3)]; ``` If I do ``` cp = list(itertools.product(a...
``` >>> arrays = [(-1,+1), (-2,+2), (-3,+3)] >>> list(itertools.product(*arrays)) [(-1, -2, -3), (-1, -2, 3), (-1, 2, -3), (-1, 2, 3), (1, -2, -3), (1, -2, 3), (1, 2, -3), (1, 2, 3)] ```
Plotting a cumulative graph of python datetimes
3,034,162
15
2010-06-13T22:34:49Z
3,034,217
10
2010-06-13T22:56:49Z
[ "python", "datetime", "graph", "matplotlib" ]
Say I have a list of datetimes, and we know each datetime to be the recorded time of an event happening. Is it possible in matplotlib to graph the frequency of this event occuring over time, showing this data in a cumulative graph (so that each point is greater or equal to all of the points that went before it), witho...
This should work for you: ``` counts = arange(0, len(list_of_dates)) plot(list_of_dates, counts) ``` You can of course give any of the usual options to the `plot` call to make the graph look the way you want it. (I'll point out that matplotlib is very adept at handling dates and times.) Another option would be the [...
How to print string in this way
3,035,239
4
2010-06-14T06:08:30Z
3,035,362
9
2010-06-14T06:35:22Z
[ "python", "regex" ]
For every string, I need to print # each 6 characters. For example: ``` example_string = "this is an example string. ok ????" myfunction(example_string) "this i#s an e#xample# strin#g. ok #????" ``` What is the most efficient way to do that ?
How about this? ``` '#'.join( [example_string[a:a+6] for a in range(0,len(example_string),6)]) ``` It runs pretty quickly, too. On my machine, five microseconds per 100-character string: ``` >>> import timeit >>> timeit.Timer( "'#'.join([s[a:a+6] for a in range(0,len(s),6)])", "s='x'*100").timeit() 4.955653905868530...
How to write a Python 2.6+ script that gracefully fails with older Python?
3,035,749
5
2010-06-14T08:02:06Z
3,477,067
8
2010-08-13T13:07:04Z
[ "python", "python-3.x" ]
I'm using the new print from Python 3.x and I observed that the following code does not **compile** due to the `end=' '`. ``` from __future__ import print_function import sys if sys.hexversion < 0x02060000: raise Exception("py too old") ... print("x",end=" ") # fails to compile with py24 ``` How can I continue ...
The easy method for Python 2.6 is just to add a line like: ``` b'You need Python 2.6 or later.' ``` at the start of the file. This exploits the fact that byte literals were introduced in 2.6 and so any earlier versions will raise a `SyntaxError` with whatever message you write given as the stack trace.
Get number of results from Django's raw() query function
3,037,273
5
2010-06-14T12:44:51Z
3,037,288
9
2010-06-14T12:46:36Z
[ "python", "django", "django-orm" ]
I'm using a raw query and i'm having trouble finding out how to get the number of results it returns. Is there a way? **edit** .count() doesnt work. it returns: 'RawQuerySet' object has no attribute 'count'
I presume you're talking about the `raw()` queryset method. That returns a queryset just like any other. So of course you can call `.count()` on it, just like you would on any other ORM query. **Edit** Shows what happens when you don't check. As you note, `.raw()` returns a RawQuerySet which doesn't have a count metho...
Get number of results from Django's raw() query function
3,037,273
5
2010-06-14T12:44:51Z
6,846,512
11
2011-07-27T14:57:40Z
[ "python", "django", "django-orm" ]
I'm using a raw query and i'm having trouble finding out how to get the number of results it returns. Is there a way? **edit** .count() doesnt work. it returns: 'RawQuerySet' object has no attribute 'count'
You can also cast it first to a list to get the length, like so: ``` results = ModelName.objects.raw("select * from modelnames_modelname") len(list(results)) #returns length ``` This is needed if you want to have the length or even the existence of entries in the RawQuerySet in templates as well. Just precalculate t...
sorting words in python
3,037,407
6
2010-06-14T13:07:14Z
3,037,485
12
2010-06-14T13:17:45Z
[ "python" ]
Is it possible in python to sort a list of words not according to the english alphabet but according to a self created alphabet.
You can normally define custom comparison methods so the sort is performed within your restrictions. I've never coded a line of Python in my life, but it's similar enough to Ruby for me to notice that the following excerpt from [this page](http://refactormycode.com/codes/179-custom-sort-a-list-of-words) might help you:...
How do I escape % from python mysql query
3,037,581
14
2010-06-14T13:31:27Z
3,037,601
17
2010-06-14T13:33:54Z
[ "python", "mysql" ]
How do I escape the % from a mysql query in python. For example ``` query = """SELECT DATE_FORMAT(date_time,'%Y-%m') AS dd FROM some_table WHERE some_col = %s AND other_col = %s;""" cur.execute(query, (pram1, pram2)) ``` gives me a "ValueError: unsupported format character 'Y'" exception. How do I get mysqldb to i...
Literal escaping is recommended by the [docs](http://mysql-python.sourceforge.net/MySQLdb.html#functions-and-attributes): > Note that any literal percent signs in the query string passed to `execute()` must be escaped, i.e. `%%`.
Python singleton pattern
3,037,914
3
2010-06-14T14:11:01Z
3,084,426
10
2010-06-21T12:04:48Z
[ "python", "singleton" ]
someone can tell me why this is incorrect as a singleton pattern: ``` class preSingleton(object): def __call__(self): return self singleton = preSingleton() # singleton is actually the singleton a = singleton() b = singleton() print a==b a.var_in_a = 100 b.var_in_b = 'hello' print a.var_in_b print ...
Singletons are actually really simple to make in Python. The trick is to have the module do your encapsulation for you and not make a class. * The module will only be initialized once * The module will not be initialized until the first time it is imported * Any attempts to re-import the module will return a pointer t...
Could random.randint(1,10) ever return 11?
3,037,952
10
2010-06-14T14:16:56Z
3,037,976
26
2010-06-14T14:19:14Z
[ "python", "random", "bounds" ]
When researching for [this question](http://stackoverflow.com/questions/3036208) and reading the sourcecode in `random.py`, I started wondering whether `randrange` and `randint` really behave as "advertised". I am very much inclined to believe so, but the way I read it, `randrange` is essentially implemented as ``` st...
From `random.py` and the docs: ``` """Get the next random number in the range [0.0, 1.0).""" ``` The `)` indicates that the interval is *exclusive* 1.0. That is, it will never return 1.0. This is a general convention in mathematics, `[` and `]` is inclusive, while `(` and `)` is exclusive, and the two types of paren...
Could random.randint(1,10) ever return 11?
3,037,952
10
2010-06-14T14:16:56Z
3,041,071
12
2010-06-14T21:26:03Z
[ "python", "random", "bounds" ]
When researching for [this question](http://stackoverflow.com/questions/3036208) and reading the sourcecode in `random.py`, I started wondering whether `randrange` and `randint` really behave as "advertised". I am very much inclined to believe so, but the way I read it, `randrange` is essentially implemented as ``` st...
Other answers have pointed out that the result of `random()` is always *strictly* less than `1.0`; however, that's only half the story. If you're computing `randrange(n)` as `int(random() * n)`, you *also* need to know that for any Python float `x` satisfying `0.0 <= x < 1.0`, and any positive integer `n`, it's true t...
What are good uses for Python3's "Function Annotations"
3,038,033
104
2010-06-14T14:25:51Z
3,038,096
63
2010-06-14T14:34:21Z
[ "python", "function", "annotations", "python-3.x" ]
Function Annotations: [PEP-3107](http://www.python.org/dev/peps/pep-3107/) I ran across a snippet of code demonstrating Python3's function annotations. The concept is simple but I can't think of why these were implemented in Python3 or any good uses for them. Perhaps SO can enlighten me? How it works: ``` def foo(a:...
I think this is actually great. Coming from an academic background, I can tell you that annotations have proved themselves invaluable for enabling smart static analyzers for languages like Java. For instance, you could define semantics like state restrictions, threads that are allowed to access, architecture limitatio...
What are good uses for Python3's "Function Annotations"
3,038,033
104
2010-06-14T14:25:51Z
3,038,157
18
2010-06-14T14:43:04Z
[ "python", "function", "annotations", "python-3.x" ]
Function Annotations: [PEP-3107](http://www.python.org/dev/peps/pep-3107/) I ran across a snippet of code demonstrating Python3's function annotations. The concept is simple but I can't think of why these were implemented in Python3 or any good uses for them. Perhaps SO can enlighten me? How it works: ``` def foo(a:...
Uri has already given a proper answer, so here's a less serious one: So you can make your docstrings shorter.
What are good uses for Python3's "Function Annotations"
3,038,033
104
2010-06-14T14:25:51Z
3,849,651
23
2010-10-03T12:09:14Z
[ "python", "function", "annotations", "python-3.x" ]
Function Annotations: [PEP-3107](http://www.python.org/dev/peps/pep-3107/) I ran across a snippet of code demonstrating Python3's function annotations. The concept is simple but I can't think of why these were implemented in Python3 or any good uses for them. Perhaps SO can enlighten me? How it works: ``` def foo(a:...
Just to add a specific example of a good use from my answer [here](http://stackoverflow.com/questions/3834263/is-clojures-multi-method-dispatch-truly-superior-say-to-what-i-can-do-in-pytho/3842928#3842928), coupled with decorators a simple mechanism for multimethods can be done. ``` # This is in the 'mm' module regis...
What are good uses for Python3's "Function Annotations"
3,038,033
104
2010-06-14T14:25:51Z
7,811,344
57
2011-10-18T17:33:45Z
[ "python", "function", "annotations", "python-3.x" ]
Function Annotations: [PEP-3107](http://www.python.org/dev/peps/pep-3107/) I ran across a snippet of code demonstrating Python3's function annotations. The concept is simple but I can't think of why these were implemented in Python3 or any good uses for them. Perhaps SO can enlighten me? How it works: ``` def foo(a:...
Function annotations are what you make of them. They can be used for documentation: ``` def kinetic_energy(mass: 'in kilograms', velocity: 'in meters per second'): ... ``` They can be used for pre-condition checking: ``` def validate(func, locals): for var, test in func.__annotations__.items(): val...
What are good uses for Python3's "Function Annotations"
3,038,033
104
2010-06-14T14:25:51Z
21,806,460
8
2014-02-16T02:19:20Z
[ "python", "function", "annotations", "python-3.x" ]
Function Annotations: [PEP-3107](http://www.python.org/dev/peps/pep-3107/) I ran across a snippet of code demonstrating Python3's function annotations. The concept is simple but I can't think of why these were implemented in Python3 or any good uses for them. Perhaps SO can enlighten me? How it works: ``` def foo(a:...
The first time I saw annotations, I thought "great! Finally I can opt in to some type checking!" Of course, I hadn't noticed that annotations are not actually enforced. So I decided to [write a simple function decorator to enforce them](https://github.com/kislyuk/ensure#enforcing-function-annotations): ``` def ensure...
What are good uses for Python3's "Function Annotations"
3,038,033
104
2010-06-14T14:25:51Z
32,158,516
16
2015-08-22T16:47:13Z
[ "python", "function", "annotations", "python-3.x" ]
Function Annotations: [PEP-3107](http://www.python.org/dev/peps/pep-3107/) I ran across a snippet of code demonstrating Python3's function annotations. The concept is simple but I can't think of why these were implemented in Python3 or any good uses for them. Perhaps SO can enlighten me? How it works: ``` def foo(a:...
This is a way late answer, but AFAICT, the best current use of function annotations is [PEP-0484](https://www.python.org/dev/peps/pep-0484/) and [MyPy](https://github.com/JukkaL/mypy). > Mypy is an optional static type checker for Python. You can add type hints to your Python programs using the upcoming standard for t...
Django template Path
3,038,459
64
2010-06-14T15:24:49Z
3,038,572
136
2010-06-14T15:38:27Z
[ "python", "django" ]
I'm following the tutorial on <http://docs.djangoproject.com/en/dev/intro/tutorial02/#intro-tutorial02> in a Windows 7 environment. My settings file is: ``` TEMPLATE_DIRS = ( 'C:/django-project/myapp/mytemplates/admin' ) ``` I got the `base_template` from the template `admin/base_site.html` from within the defaul...
I know this isn't in the Django tutorial, and shame on them, but it's better to set up relative paths for your path variables. You can set it up like so: ``` import os PROJECT_PATH = os.path.realpath(os.path.dirname(__file__)) ... MEDIA_ROOT = PROJECT_PATH + '/media/' TEMPLATE_DIRS = ( PROJECT_PATH + '/templat...
Efficiently finding the shortest path in large graphs
3,038,661
13
2010-06-14T15:50:10Z
3,038,691
16
2010-06-14T15:54:48Z
[ "python", "graph", "shortest-path", "dijkstra", "breadth-first-search" ]
I'm looking to find a way to in real-time find the shortest path between nodes in a huge graph. It has hundreds of thousands of vertices and millions of edges. I know this question has been asked before and I guess the answer is to use a breadth-first search, but I'm more interested in to know what software you can use...
[python-graph](http://code.google.com/p/python-graph/) **added:** The comments made me curious as to how the performance of pygraph was for a problem on the order of the OP, so I made a toy program to find out. Here's the output for a slightly smaller version of the problem: ``` $ python2.6 biggraph.py 4 6 biggraph ...
Efficiently finding the shortest path in large graphs
3,038,661
13
2010-06-14T15:50:10Z
3,040,843
9
2010-06-14T20:53:40Z
[ "python", "graph", "shortest-path", "dijkstra", "breadth-first-search" ]
I'm looking to find a way to in real-time find the shortest path between nodes in a huge graph. It has hundreds of thousands of vertices and millions of edges. I know this question has been asked before and I guess the answer is to use a breadth-first search, but I'm more interested in to know what software you can use...
For large graphs, try the Python interface of [igraph](http://igraph.sf.net). Its core is implemented in C, therefore it can cope with graphs with millions of vertices and edges relatively easily. It contains a BFS implementation (among other algorithms) and it also includes Dijkstra's algorithm and the Bellman-Ford al...
SQLAlchemy DetachedInstanceError with regular attribute (not a relation)
3,039,567
31
2010-06-14T17:52:13Z
3,040,164
44
2010-06-14T19:14:37Z
[ "python", "sqlalchemy" ]
I just started using SQLAlchemy and get a DetachedInstanceError and can't find much information on this anywhere. I am using the instance outside a session, so it is natural that SQLAlchemy is unable to load any relations if they are not already loaded, however, the attribute I am accessing is not a relation, in fact t...
I found the root cause while trying to narrow down the code that caused the exception. I placed the same attribute access code at different places after session close and found that it definitely doesn't cause any issue immediately after the close of query session. It turns out the problem starts appearing after closin...
Does OOP make sense for small scripts?
3,039,889
25
2010-06-14T18:38:04Z
3,039,916
26
2010-06-14T18:41:36Z
[ "python", "oop", "scripting" ]
I mostly write small scripts in python, about 50 - 250 lines of code. I usually don't use any objects, just straightforward procedural programming. I know OOP basics and I have used object in other programming languages before, but for small scripts I don't see how objects would improve them. But maybe that is just my...
Object-Oriented Programming, while useful for representing systems as real-world objects (and hopefully making large software system easier to understand) is not the silver bullet to every solution (despite what some people teach). If your system does not benefit from what OOP provides (things such as data abstraction...
Does OOP make sense for small scripts?
3,039,889
25
2010-06-14T18:38:04Z
3,039,934
7
2010-06-14T18:43:13Z
[ "python", "oop", "scripting" ]
I mostly write small scripts in python, about 50 - 250 lines of code. I usually don't use any objects, just straightforward procedural programming. I know OOP basics and I have used object in other programming languages before, but for small scripts I don't see how objects would improve them. But maybe that is just my...
If you plan to use the script independently, then no. However if you plan to `import` it and reuse some of it, then yes. In the second case, it's best to write some classes providing the functionality that's required and then have a conditional run (`if __name__=='__main__':`) with code to execute the "script" version ...
Does OOP make sense for small scripts?
3,039,889
25
2010-06-14T18:38:04Z
3,039,967
30
2010-06-14T18:46:46Z
[ "python", "oop", "scripting" ]
I mostly write small scripts in python, about 50 - 250 lines of code. I usually don't use any objects, just straightforward procedural programming. I know OOP basics and I have used object in other programming languages before, but for small scripts I don't see how objects would improve them. But maybe that is just my...
I use whatever paradigm best suits the issue at hand -- be it procedural, OOP, functional, ... program size is not a criterion, though (by a little margin) a larger program may be more likely to take advantage of OOP's strengths -- multiple instances of a class, subclassing and overriding, special method overloads, OOP...
Does OOP make sense for small scripts?
3,039,889
25
2010-06-14T18:38:04Z
3,041,386
7
2010-06-14T22:25:45Z
[ "python", "oop", "scripting" ]
I mostly write small scripts in python, about 50 - 250 lines of code. I usually don't use any objects, just straightforward procedural programming. I know OOP basics and I have used object in other programming languages before, but for small scripts I don't see how objects would improve them. But maybe that is just my...
One of the unfortunate habits developed with oop is Objectophrenia - the delusion of seeing objects in every piece of code we write. The reason why that happens is due our delusion of believing in the existence of a unified objects theorem. Every piece of code you write, you begin to see it as a template for objects ...
Python encoding for pipe.communicate
3,040,101
8
2010-06-14T19:05:01Z
3,040,117
12
2010-06-14T19:08:04Z
[ "python", "unicode", "encoding", "subprocess", "popen" ]
I'm calling `pipe.communicate` from Python's [`subprocess`](http://docs.python.org/library/subprocess.html) module from Python 2.6. I get the following error from this code: ``` from subprocess import Popen pipe = Popen(cwd) pipe.communicate( data ) ``` For an arbitrary `cwd`, and where `data` that contains unicode...
I *may* have solved this by changing: ``` pipe.communicate( data ) ``` to ``` pipe.communicate( data.encode('utf8') ) ``` Though I stand to be corrected! Brian
Python: Elegant way to check if at least one regex in list matches a string
3,040,716
24
2010-06-14T20:35:02Z
3,040,745
47
2010-06-14T20:39:30Z
[ "python", "regex", "list" ]
I have a list of regexes in python, and a string. Is there an elegant way to check if the at least one regex in the list matches the string? By elegant, I mean something better than simply looping through all of the regexes and checking them against the string and stopping if a match is found. Basically, I had this co...
``` import re regexes = [ # your regexes here re.compile('hi'), # re.compile(...), # re.compile(...), # re.compile(...), ] mystring = 'hi' if any(regex.match(mystring) for regex in regexes): print 'Some regex matched!' ```
Python: Elegant way to check if at least one regex in list matches a string
3,040,716
24
2010-06-14T20:35:02Z
3,040,797
43
2010-06-14T20:48:40Z
[ "python", "regex", "list" ]
I have a list of regexes in python, and a string. Is there an elegant way to check if the at least one regex in the list matches the string? By elegant, I mean something better than simply looping through all of the regexes and checking them against the string and stopping if a match is found. Basically, I had this co...
``` import re regexes = [ "foo.*", "bar.*", "qu*x" ] # Make a regex that matches if any of our regexes match. combined = "(" + ")|(".join(regexes) + ")" if re.match(combined, mystring): print "Some regex matched!" ```
rename keys in a dictionary
3,040,727
3
2010-06-14T20:35:57Z
3,040,834
7
2010-06-14T20:52:39Z
[ "python", "dictionary" ]
i want to rename the keys of a dictionary are which are ints, and i need them to be ints with leading zeros's so that they sort correctly. for example my keys are like: ``` '1','101','11' ``` and i need them to be: ``` '001','101','011' ``` this is what im doing now, but i know there is a better way ``` tmpDict =...
You're going about it the wrong way. If you want to pull the entries from the dict in a sorted manner then you need to sort upon extraction. ``` for k in sorted(D, key=int): print '%s: %r' % (k, D[k]) ```
Python's cPickle deserialization from PHP?
3,040,872
6
2010-06-14T20:58:14Z
3,040,887
7
2010-06-14T21:01:27Z
[ "php", "python", "json", "serialization", "pickle" ]
I have to *deserialize a dictionary* in PHP that was serialized using *cPickle in Python*. In this specific case I probably could just *regexp the wanted information*, but is there a better way? Any extensions for PHP that would allow me to deserialize more natively the whole dictionary? Apparently it is serialized i...
If you want to share data objects between programs written in different languages, it might be easier to serialize/deserialize using something like [JSON](http://www.json.org/) instead. Most major programming languages have a JSON library.
Save JSON outputed from a URL to a file
3,040,904
5
2010-06-14T21:03:15Z
3,040,917
11
2010-06-14T21:05:07Z
[ "java", "python", "ruby", "perl", "bash" ]
How would I save JSON outputed by an URL to a file? e.g from the Twitter search API (this <http://search.twitter.com/search.json?q=hi>) Language isn't important. Thanks! edit // How would I then append further updates to EOF? edit 2// Great answers guys really, but I accepted the one I thought was the most elegant...
This is easy in any language, but the mechanism varies. With wget and a shell: ``` wget 'http://search.twitter.com/search.json?q=hi' -O hi.json ``` To append: ``` wget 'http://search.twitter.com/search.json?q=hi' -O - >> hi.json ``` With Python: ``` urllib.urlretrieve('http://search.twitter.com/search.json?q=hi', ...
APT command line interface-like yes/no input?
3,041,986
98
2010-06-15T01:13:54Z
3,041,990
127
2010-06-15T01:16:00Z
[ "python" ]
Is there any short way to achieve what the APT (*Advanced Package Tool*) command line interface does in Python? I mean, when the package manager prompts a yes/no question followed by `[Yes/no]`, the script accepts `YES/Y/yes/y` or `Enter` (defaults to `Yes` as hinted by the capital letter). The only thing I find in t...
As you mentioned, the easiest way is to use `raw_input()`. There is no built-in way to do this. From [Recipe 577058](http://code.activestate.com/recipes/577058/): ``` import sys def query_yes_no(question, default="yes"): """Ask a yes/no question via raw_input() and return their answer. "question" is a string...
APT command line interface-like yes/no input?
3,041,986
98
2010-06-15T01:13:54Z
3,042,378
48
2010-06-15T03:37:47Z
[ "python" ]
Is there any short way to achieve what the APT (*Advanced Package Tool*) command line interface does in Python? I mean, when the package manager prompts a yes/no question followed by `[Yes/no]`, the script accepts `YES/Y/yes/y` or `Enter` (defaults to `Yes` as hinted by the capital letter). The only thing I find in t...
I'd do it this way: ``` # raw_input returns the empty string for "enter" yes = set(['yes','y', 'ye', '']) no = set(['no','n']) choice = raw_input().lower() if choice in yes: return True elif choice in no: return False else: sys.stdout.write("Please respond with 'yes' or 'no'") ```
APT command line interface-like yes/no input?
3,041,986
98
2010-06-15T01:13:54Z
4,741,730
27
2011-01-19T22:51:29Z
[ "python" ]
Is there any short way to achieve what the APT (*Advanced Package Tool*) command line interface does in Python? I mean, when the package manager prompts a yes/no question followed by `[Yes/no]`, the script accepts `YES/Y/yes/y` or `Enter` (defaults to `Yes` as hinted by the capital letter). The only thing I find in t...
A very simple (but not very sophisticated) way of doing this for a single choice would be: ``` msg = 'Shall I?' shall = raw_input("%s (y/N) " % msg).lower() == 'y' ``` You could also write a simple (slightly improved) function around this: ``` def yn_choice(message, default='y'): choices = 'Y/n' if default.lower...
APT command line interface-like yes/no input?
3,041,986
98
2010-06-15T01:13:54Z
14,274,466
34
2013-01-11T08:44:29Z
[ "python" ]
Is there any short way to achieve what the APT (*Advanced Package Tool*) command line interface does in Python? I mean, when the package manager prompts a yes/no question followed by `[Yes/no]`, the script accepts `YES/Y/yes/y` or `Enter` (defaults to `Yes` as hinted by the capital letter). The only thing I find in t...
There is a function `strtobool` in Python's standard library: <http://docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool> You can use it to check user's input and transform it to `True` or `False` value.
APT command line interface-like yes/no input?
3,041,986
98
2010-06-15T01:13:54Z
22,222,073
16
2014-03-06T10:44:55Z
[ "python" ]
Is there any short way to achieve what the APT (*Advanced Package Tool*) command line interface does in Python? I mean, when the package manager prompts a yes/no question followed by `[Yes/no]`, the script accepts `YES/Y/yes/y` or `Enter` (defaults to `Yes` as hinted by the capital letter). The only thing I find in t...
as mentioned by @Alexander Artemenko, here's a simple solution using strtobool ``` from distutils.util import strtobool def user_yes_no_query(question): sys.stdout.write('%s [y/n]\n' % question) while True: try: return strtobool(raw_input().lower()) except ValueError: s...
APT command line interface-like yes/no input?
3,041,986
98
2010-06-15T01:13:54Z
26,514,097
7
2014-10-22T18:03:45Z
[ "python" ]
Is there any short way to achieve what the APT (*Advanced Package Tool*) command line interface does in Python? I mean, when the package manager prompts a yes/no question followed by `[Yes/no]`, the script accepts `YES/Y/yes/y` or `Enter` (defaults to `Yes` as hinted by the capital letter). The only thing I find in t...
I know this has been answered a bunch of ways and this may not answer OP's specific question (with the list of criteria) but this is what I did for the most common use case and it's far simpler than the other responses: ``` answer = input('Please indicate approval: [y/n]') if not answer or answer[0].lower() != 'y': ...
converting hexadecimal , octal numbers into decimal form using python script
3,042,135
4
2010-06-15T02:17:57Z
3,042,289
12
2010-06-15T03:08:30Z
[ "python", "hex", "octal" ]
There are many inbulit functions like int(octal) which can be used to convert octal numbers into decimal numbers on command line but these doesn't work out in script . int(0671) returns 0671 in script, where as it represent decimal form of octal number on python command line. Help??? Thank You
There's some confusion here -- pedantically (and with computers it's always best to be pedantic;-), there are no "octal numbers", there are *strings* which are octal *representations* of numbers (and other strings, more commonly encountered, which are their decimal representations, hexadecimal representations). The und...
How to determine what user and group a Python script is running as?
3,042,304
10
2010-06-15T03:15:11Z
3,042,321
14
2010-06-15T03:20:07Z
[ "python", "unix", "permissions" ]
I have a CGI script that is getting an "IOError: [Errno 13] Permission denied" error in the stack trace in the web server's error log. As part of debugging this problem, I'd like to add a little bit of code to the script to print the user and (especially) group that the script is running as, into the error log (presum...
``` import os print os.getegid() ```
How to determine what user and group a Python script is running as?
3,042,304
10
2010-06-15T03:15:11Z
25,574,419
11
2014-08-29T18:46:15Z
[ "python", "unix", "permissions" ]
I have a CGI script that is getting an "IOError: [Errno 13] Permission denied" error in the stack trace in the web server's error log. As part of debugging this problem, I'd like to add a little bit of code to the script to print the user and (especially) group that the script is running as, into the error log (presum...
``` import os, getpass print getpass.getuser() ``` Consider the following script. ``` ---- foo.py ---- import os, getpass print "Env thinks the user is [%s]" % (os.getlogin()); print "Effective user is [%s]" % (getpass.getuser()); ``` Consider running the script. ``` $ python ./foo.py ``` results in ``` Env thin...
Downloading a picture via urllib and python
3,042,757
88
2010-06-15T05:35:53Z
3,042,778
52
2010-06-15T05:40:36Z
[ "python", "urllib2", "beautifulsoup", "urllib" ]
So I'm trying to make a Python script that downloads webcomics and puts them in a folder on my desktop. I've found a few similar programs on here that do something similar, but nothing quite like what I need. The one that I found most similar is right here (http://bytes.com/topic/python/answers/850927-problem-using-url...
``` import urllib f = open('00000001.jpg','wb') f.write(urllib.urlopen('http://www.gunnerkrigg.com//comics/00000001.jpg').read()) f.close() ```
Downloading a picture via urllib and python
3,042,757
88
2010-06-15T05:35:53Z
3,042,786
133
2010-06-15T05:42:26Z
[ "python", "urllib2", "beautifulsoup", "urllib" ]
So I'm trying to make a Python script that downloads webcomics and puts them in a folder on my desktop. I've found a few similar programs on here that do something similar, but nothing quite like what I need. The one that I found most similar is right here (http://bytes.com/topic/python/answers/850927-problem-using-url...
Using [urllib.urlretrieve](https://docs.python.org/2/library/urllib.html): ``` import urllib urllib.urlretrieve("http://www.gunnerkrigg.com//comics/00000001.jpg", "00000001.jpg") ```
Downloading a picture via urllib and python
3,042,757
88
2010-06-15T05:35:53Z
14,962,401
24
2013-02-19T16:26:24Z
[ "python", "urllib2", "beautifulsoup", "urllib" ]
So I'm trying to make a Python script that downloads webcomics and puts them in a folder on my desktop. I've found a few similar programs on here that do something similar, but nothing quite like what I need. The one that I found most similar is right here (http://bytes.com/topic/python/answers/850927-problem-using-url...
Just for the record, using requests library. ``` import requests f = open('00000001.jpg','wb') f.write(requests.get('http://www.gunnerkrigg.com//comics/00000001.jpg').content) f.close() ``` Though it should check for requests.get() error.
Downloading a picture via urllib and python
3,042,757
88
2010-06-15T05:35:53Z
15,880,288
7
2013-04-08T13:25:32Z
[ "python", "urllib2", "beautifulsoup", "urllib" ]
So I'm trying to make a Python script that downloads webcomics and puts them in a folder on my desktop. I've found a few similar programs on here that do something similar, but nothing quite like what I need. The one that I found most similar is right here (http://bytes.com/topic/python/answers/850927-problem-using-url...
I have found this [answer](http://stackoverflow.com/questions/257409/download-image-file-from-the-html-page-source-using-python/2448326#2448326) and I edit that in more reliable way ``` def download_photo(self, img_url, filename): try: image_on_web = urllib.urlopen(img_url) if image_on_web.headers....
Comparing two text files in python
3,043,026
12
2010-06-15T06:41:09Z
3,043,327
14
2010-06-15T07:38:49Z
[ "python" ]
I need to compare two files and redirect the different lines to third file. I know using diff command i can get the difference . But, is there any way of doing it in python ? Any sample code will be helpful
check out [difflib](http://docs.python.org/library/difflib.html) > This module provides classes and > functions for comparing sequences. It > can be used for example, for comparing > files, and can produce difference > information in various formats, > including HTML and context and unified > diffs[...] A command-lin...
deepcopy and python - tips to avoid using it?
3,043,369
11
2010-06-15T07:49:14Z
3,043,961
28
2010-06-15T09:26:44Z
[ "python", "deep-copy" ]
I have a very simple python routine that involves cycling through a list of roughly 20,000 latitude,longitude coordinates and calculating the distance of each point to a reference point. ``` def compute_nearest_points( lat, lon, nPoints=5 ): """Find the nearest N points, given the input coordinates.""" points...
Okay, simplest things first: 1. `deepcopy` is slow in general since it has to do a lot of internal bookkeeping to copy pathological cases like objects containing themselves in a sane way. See, for instance, [this page](http://writeonly.wordpress.com/2009/05/07/deepcopy-is-a-pig-for-simple-data/), or take a look at the...
Resident Set Size (RSS) limit has no effect
3,043,709
14
2010-06-15T08:43:31Z
3,043,778
10
2010-06-15T08:53:19Z
[ "python", "resources", "limits", "pam", "ulimit" ]
The following problem occurs on a machine running Ubuntu 10.04 with the 2.6.32-22-generic kernel: Setting a limit for the Resident Set Size (RSS) of a process does not seem to have any effect. I currently set the limit in Python with the following code: ``` import resource # (100, 100) is the (soft, hard) limit. ~100k...
Form the getrlimit manpage: > ``` > RLIMIT_RSS > Specifies the limit (in pages) of the process's resident set > (the number of virtual pages resident in RAM). This limit only > has effect in Linux 2.4.x, x < 30, and there only affects calls > to madvise(2) specifying MADV_WILLNEED. > ``` It seems this is just ...
Resident Set Size (RSS) limit has no effect
3,043,709
14
2010-06-15T08:43:31Z
6,365,534
15
2011-06-15T23:13:08Z
[ "python", "resources", "limits", "pam", "ulimit" ]
The following problem occurs on a machine running Ubuntu 10.04 with the 2.6.32-22-generic kernel: Setting a limit for the Resident Set Size (RSS) of a process does not seem to have any effect. I currently set the limit in Python with the following code: ``` import resource # (100, 100) is the (soft, hard) limit. ~100k...
You can accomplish this using cgroups. The long version is on my [blog](http://jlebar.com/2011/6/15/Limiting_the_amount_of_RAM_a_program_can_use.html), but the short version (tested on Ubuntu 11.04) is: * Install the `cgroup-bin` package. * Edit `/etc/cgconfig.config` and create a group with limited memory. For inst...
Fetching just the Key/id from a ReferenceProperty in App Engine
3,044,121
15
2010-06-15T09:53:27Z
3,044,252
25
2010-06-15T10:15:40Z
[ "python", "google-app-engine", "gae-datastore" ]
I could use a little help in AppEngine land... Using the [Python] API I create relationships like this example from the docs: ``` class Author(db.Model): name = db.StringProperty() class Story(db.Model): author = db.ReferenceProperty(Author) story = db.get(story_key) author_name = story.author.name ``` As ...
Answering my own question for the sake of helping fellow searchers... As suspected calling story.author.key().id() or even story.author.id() will result in datastore queries. The correct method [dictated by the API docs](http://code.google.com/appengine/docs/python/datastore/propertyclass.html#Property_get_value_for_d...
SQLAlchemy: How to group by two fields and filter by date
3,044,455
6
2010-06-15T10:52:54Z
3,049,352
14
2010-06-15T21:53:58Z
[ "python", "sql", "mysql", "sqlalchemy", "group-by" ]
So I have a table with a datestamp and two fields that I want to make sure that they are unique in the last month. ``` table.id table.datestamp table.field1 table.field2 ``` There should be no duplicate record with the same field1 + 2 compound value in the last month. The steps in my head are: 1. Group by the two f...
Following should point you in the right direction, also see inline comments: ``` qry = (session.query( table.c.field1, table.c.field2, # #strftime* for year-month works on sqlite; # @todo: find proper function for mysql (as in the question) ...
Multiprocessing vs Threading Python
3,044,580
276
2010-06-15T11:12:45Z
3,044,593
21
2010-06-15T11:15:29Z
[ "python", "multithreading", "multiprocessing" ]
I am trying to understand the advantages of [multiprocessing](http://docs.python.org/library/multiprocessing) over [threading](http://docs.python.org/library/threading). I know that **multiprocessing** gets around the Global Interpreter Lock, but what other advantages are there, and can **threading** not do the same th...
The key advantage is isolation. A crashing process won't bring down other processes, whereas a crashing thread will probably wreak havoc with other threads.
Multiprocessing vs Threading Python
3,044,580
276
2010-06-15T11:12:45Z
3,044,626
219
2010-06-15T11:19:25Z
[ "python", "multithreading", "multiprocessing" ]
I am trying to understand the advantages of [multiprocessing](http://docs.python.org/library/multiprocessing) over [threading](http://docs.python.org/library/threading). I know that **multiprocessing** gets around the Global Interpreter Lock, but what other advantages are there, and can **threading** not do the same th...
The threading module uses threads, the multiprocessing uses processes. The difference is that threads run in the same memory space, while processes have separate memory. This makes it a bit harder to share objects between processes with multiprocessing. Since threads use the same memory, precautions have to be taken or...
Multiprocessing vs Threading Python
3,044,580
276
2010-06-15T11:12:45Z
3,044,648
20
2010-06-15T11:22:41Z
[ "python", "multithreading", "multiprocessing" ]
I am trying to understand the advantages of [multiprocessing](http://docs.python.org/library/multiprocessing) over [threading](http://docs.python.org/library/threading). I know that **multiprocessing** gets around the Global Interpreter Lock, but what other advantages are there, and can **threading** not do the same th...
Another thing not mentioned is that it depends on what OS you are using where speed is concerned. In Windows processes are costly so threads would be better in windows but in unix processes are faster than their windows variants so using processes in unix is much safer plus quick to spawn.
Multiprocessing vs Threading Python
3,044,580
276
2010-06-15T11:12:45Z
3,045,648
91
2010-06-15T13:38:10Z
[ "python", "multithreading", "multiprocessing" ]
I am trying to understand the advantages of [multiprocessing](http://docs.python.org/library/multiprocessing) over [threading](http://docs.python.org/library/threading). I know that **multiprocessing** gets around the Global Interpreter Lock, but what other advantages are there, and can **threading** not do the same th...
Threading's job is to enable applications to be responsive. Suppose you have a database connection and you need to respond to user input. Without threading, if the database connection is busy the application will not be able to respond to the user. By splitting off the database connection into a separate thread you can...
Multiprocessing vs Threading Python
3,044,580
276
2010-06-15T11:12:45Z
3,046,201
379
2010-06-15T14:39:02Z
[ "python", "multithreading", "multiprocessing" ]
I am trying to understand the advantages of [multiprocessing](http://docs.python.org/library/multiprocessing) over [threading](http://docs.python.org/library/threading). I know that **multiprocessing** gets around the Global Interpreter Lock, but what other advantages are there, and can **threading** not do the same th...
Here are some pros/cons I came up with. # Multiprocessing ## Pros * Separate memory space * Code is usually straightforward * Takes advantage of multiple CPUs & cores * Avoids GIL limitations for cPython * Eliminates most needs for synchronization primitives unless if you use shared memory (instead, it's more of a c...
Custom headers with pycurl
3,044,782
18
2010-06-15T11:45:53Z
3,044,957
37
2010-06-15T12:11:52Z
[ "python", "header", "pycurl" ]
Can I send a *custom header* like "yaddayadda" to the server with the [pycurl](http://pycurl.sourceforge.net/) request?
I would code something like: ``` pycurl_connect = pycurl.Curl() pycurl_connect.setopt(pycurl.URL, your_url) pycurl_connect.setopt(pycurl.HTTPHEADER, ['header_name1: header_value1', 'header_name2: header_value2']) pycurl_connect.perform() ```
How to profile my code?
3,045,556
18
2010-06-15T13:27:07Z
3,068,045
61
2010-06-18T08:11:10Z
[ "python", "profiling" ]
I want to know how to profile my code. I have gone through the docs, but as there were no examples given I could not get anything from it. I have a large code and it is taking so much time, hence I want to profile and increase its speed. I havent written my code in method, there are few in between but not completely....
The standard answer to this question is to use [cProfile](http://docs.python.org/library/profile.html#instant-user-s-manual). You'll find though that **without having your code separated out into methods that cProfile won't give you particularly rich information**. Instead, you might like to try what another poster h...
How to profile my code?
3,045,556
18
2010-06-15T13:27:07Z
9,594,242
13
2012-03-07T00:50:59Z
[ "python", "profiling" ]
I want to know how to profile my code. I have gone through the docs, but as there were no examples given I could not get anything from it. I have a large code and it is taking so much time, hence I want to profile and increase its speed. I havent written my code in method, there are few in between but not completely....
# Edit: This answer has been implemented in <https://github.com/campos-ddc/cprofile_graph> # Profiling with cProfile Here's a post I wrote some time ago on profiling with cProfile with some graphical aid. cProfile is one of the most used python profilers out there, and although very powerful, the standard text outp...