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 |
|---|---|---|---|---|---|---|---|---|---|
Python - animation with matplotlib.pyplot | 2,546,780 | 15 | 2010-03-30T16:16:12Z | 22,010,022 | 10 | 2014-02-25T09:37:06Z | [
"python",
"matplotlib"
] | How can one create animated diagrams using popular matplotlib library? I am particularly interested in animated gifs. | This question is kind of old but nevertheless I will answer just in case someone crash here and this can be useful.
So nowadays it seems that the best way to go in matplotlib is to use the functionality that they provide:
<http://matplotlib.org/api/animation_api.html#module-matplotlib.animation>
They also include so... |
Why is python decode replacing more than the invalid bytes from an encoded string? | 2,547,262 | 24 | 2010-03-30T17:33:46Z | 2,547,364 | 8 | 2010-03-30T17:50:46Z | [
"python",
"security",
"unicode",
"screen-scraping"
] | Trying to decode an invalid encoded utf-8 html page gives different results in
python, firefox and chrome.
The invalid encoded fragment from test page looks like `'PREFIX\xe3\xabSUFFIX'`
```
>>> fragment = 'PREFIX\xe3\xabSUFFIX'
>>> fragment.decode('utf-8', 'strict')
...
UnicodeDecodeError: 'utf8' codec can't decode ... | **the 0xE3 byte is one (of the possible) first bytes indicative of a 3-bytes character.**
Apparently Python's decode logic takes these three bytes and tries to decode them. They turn out to not match an actual code point ("character") and that is why Python produces a UnicodeDecodeError and emits a substitution charac... |
Why is python decode replacing more than the invalid bytes from an encoded string? | 2,547,262 | 24 | 2010-03-30T17:33:46Z | 2,548,480 | 7 | 2010-03-30T20:31:45Z | [
"python",
"security",
"unicode",
"screen-scraping"
] | Trying to decode an invalid encoded utf-8 html page gives different results in
python, firefox and chrome.
The invalid encoded fragment from test page looks like `'PREFIX\xe3\xabSUFFIX'`
```
>>> fragment = 'PREFIX\xe3\xabSUFFIX'
>>> fragment.decode('utf-8', 'strict')
...
UnicodeDecodeError: 'utf8' codec can't decode ... | You know that your S is valid, with the benefit of both look-ahead and hindsight :-) Suppose there was originally a legal 3-byte UTF-8 sequence there, and the 3rd byte was corrupted in transmission ... with the change that you mention, you'd be complaining that a spurious S had not been replaced. There is no "right" wa... |
Why does a JRuby application on App Engine take so long to start (versus a Python app)? | 2,547,498 | 4 | 2010-03-30T18:11:20Z | 2,547,521 | 10 | 2010-03-30T18:15:12Z | [
"java",
"python",
"ruby",
"google-app-engine",
"jruby"
] | I'm considering using JRuby on App Engine but have heard that Juby app on App Engine have a long startup lag versus a Python app. Why is this?
Is it because the JRuby jar files are so large that a cold startup requires them to be loaded into memory before the app can start serving? That would be my guess but I'm not s... | That's basically it. When your app hasn't been used in a while, App Engine swaps it out until another request comes in.
When that happens, it loads all the JARs your app requires, which may take a very long time, upwards of 10-15+ seconds in some cases.
I don't have any experience with JRuby in particular, but [this ... |
Official multiple Python versions on the same machine? | 2,547,554 | 40 | 2010-03-30T18:19:35Z | 2,547,577 | 42 | 2010-03-30T18:23:27Z | [
"python"
] | Is there official documentation on the Python website somewhere, on how to install and run multiple versions of Python on the same machine on Linux?
I can find gazillions of blog posts and answers, but I want to know if there is a "standard" official way of doing this?
Or is this all dependent on OS? | I think it is totally independent. Just install them, then you have the commands e.g. `/usr/bin/python2.5` and `/usr/bin/python2.6`. Link `/usr/bin/python` to the one you want to use as default.
All the libraries are in separate folders (named after the version) anyway.
If you want to compile the versions manually, t... |
Official multiple Python versions on the same machine? | 2,547,554 | 40 | 2010-03-30T18:19:35Z | 2,547,801 | 16 | 2010-03-30T18:51:13Z | [
"python"
] | Is there official documentation on the Python website somewhere, on how to install and run multiple versions of Python on the same machine on Linux?
I can find gazillions of blog posts and answers, but I want to know if there is a "standard" official way of doing this?
Or is this all dependent on OS? | On Windows they get installed to separate folders, "C:\python26" and "C:\python31", but the executables have the same "python.exe" name.
I created another "C:\python" folder that contains "python.bat" and "python3.bat" that serve as wrappers to "python26" and "python31" respectively, and added "C:\python" to the `PATH... |
How to sort a dictionary having keys as a string of numbers in Python | 2,548,000 | 5 | 2010-03-30T19:17:30Z | 2,548,252 | 7 | 2010-03-30T19:58:19Z | [
"python"
] | I have a dictionary:
```
a = {'100':12,'6':5,'88':3,'test':34, '67':7,'1':64 }
```
I want to sort this dictionary with respect to key so it looks like:
```
a = {'1':64,'6':5,'67':7,'88':3, '100':12,'test':34 }
``` | Like everyone else has pointed out, dictionaries have their own ordering and you can't just sort them like you would a list.
One thing I would like to add is that, if you just want to go through the elements of a dictionary in sorted order, that's just:
```
for k in sorted(a):
print k, a[k] # or whatever.
```
If... |
How do I get the "id" after INSERT into MySQL database with Python? | 2,548,493 | 85 | 2010-03-30T20:33:32Z | 2,548,531 | 98 | 2010-03-30T20:37:02Z | [
"python",
"mysql",
"database"
] | I execute an INSERT INTO statement
```
cursor.execute("INSERT INTO mytable(height) VALUES(%s)",(height))
```
and I want to get the primary key.
My table has 2 columns:
```
id primary, auto increment
height this is the other column.
```
How do I get the "id", after I just inserted this? | Use `cursor.lastrowid` to get the last row ID inserted on the cursor object, or `connection.insert_id()` to get the ID from the last insert on that connection. |
How do I get the "id" after INSERT into MySQL database with Python? | 2,548,493 | 85 | 2010-03-30T20:33:32Z | 3,790,542 | 86 | 2010-09-24T19:59:58Z | [
"python",
"mysql",
"database"
] | I execute an INSERT INTO statement
```
cursor.execute("INSERT INTO mytable(height) VALUES(%s)",(height))
```
and I want to get the primary key.
My table has 2 columns:
```
id primary, auto increment
height this is the other column.
```
How do I get the "id", after I just inserted this? | Also, `cursor.lastrowid` (a dbapi/PEP249 extension supported by MySQLdb):
```
>>> import MySQLdb
>>> connection = MySQLdb.connect(user='root')
>>> cursor = connection.cursor()
>>> cursor.execute('INSERT INTO sometable VALUES (...)')
1L
>>> connection.insert_id()
3L
>>> cursor.lastrowid
3L
>>> cursor.execute('SELECT la... |
How do I get the "id" after INSERT into MySQL database with Python? | 2,548,493 | 85 | 2010-03-30T20:33:32Z | 4,581,359 | 29 | 2011-01-03T00:45:28Z | [
"python",
"mysql",
"database"
] | I execute an INSERT INTO statement
```
cursor.execute("INSERT INTO mytable(height) VALUES(%s)",(height))
```
and I want to get the primary key.
My table has 2 columns:
```
id primary, auto increment
height this is the other column.
```
How do I get the "id", after I just inserted this? | Python DBAPI spec also define 'lastrowid' attribute for cursor object, so...
```
id = cursor.lastrowid
```
...should work too, and it's per-connection based obviously. |
How to find the filename of a script being run when it is executed from a symlink on linux | 2,548,936 | 4 | 2010-03-30T21:36:54Z | 2,548,964 | 7 | 2010-03-30T21:42:24Z | [
"python",
"linux",
"filenames",
"symlink"
] | If I have a python script that is executed via a symlink, is there a way that I can find the path to the script rather than the symlink? I've tried using the methods suggested in [this](http://stackoverflow.com/questions/1296501/python-find-path-to-file-being-run) question, but they always return the path to the symlin... | You want the `os.path.realpath()` function. |
Exit python program when argument is less than 0 | 2,549,300 | 3 | 2010-03-30T23:01:16Z | 2,549,311 | 10 | 2010-03-30T23:04:30Z | [
"python"
] | I'd like the program to exit if the input number is less than 0, but sys.exit() isn't doing the trick. This is what I have now:
```
if len( sys.argv ) > 1:
number = sys.argv[1]
if number <= 0:
print "Invalid number! Must be greater than 0"
sys.exit()
``` | Your test is failing because number is a string.
```
>>> '-1' <= 0
False
```
You need to convert `number` to an integer:
```
number = int(sys.argv[1])
```
Note that in Python 3.0 your code would have given an error, allowing you to find your mistake more easily:
```
>>> '-1' <= 0
Traceback (most recent call last):... |
What is the difference between AF_INET and PF_INET constants? | 2,549,461 | 26 | 2010-03-30T23:43:54Z | 2,549,477 | 19 | 2010-03-30T23:50:19Z | [
"python",
"c",
"unix",
"sockets"
] | Looking at examples about socket programming, we can see that some people use `AF_INET` while others use `PF_INET`. In addition, sometimes [both of them are used at the same example](http://stackoverflow.com/questions/2384562/double-udp-socket-binding-in-linux/2384605#2384605). The question is: Is there any difference ... | I think the [Wikipedia notes on this](http://en.wikipedia.org/wiki/Berkeley_sockets#Protocol_and_address_families) sum it up pretty well:
> The original design concept of the socket interface distinguished between protocol types (families) and the specific address types that each may use. It was envisioned that a prot... |
Get signal names from numbers in Python | 2,549,939 | 29 | 2010-03-31T01:51:47Z | 2,549,950 | 21 | 2010-03-31T01:55:40Z | [
"python",
"signals"
] | Is there a way to map a signal number (e.g. signal.SIGINT) to its respective name (i.e. "SIGINT")?
I'd like to be able to print the name of a signal in the log when I receive it, however I cannot find a map from signal numbers to names in Python, i.e.:
```
import signal
def signal_handler(signum, frame):
logging.... | There is none, but if you don't mind a little hack, you can generate it like this:
```
import signal
dict((k, v) for v, k in reversed(sorted(signal.__dict__.items()))
if v.startswith('SIG') and not v.startswith('SIG_'))
``` |
Get signal names from numbers in Python | 2,549,939 | 29 | 2010-03-31T01:51:47Z | 8,527,643 | 10 | 2011-12-15T22:39:19Z | [
"python",
"signals"
] | Is there a way to map a signal number (e.g. signal.SIGINT) to its respective name (i.e. "SIGINT")?
I'd like to be able to print the name of a signal in the log when I receive it, however I cannot find a map from signal numbers to names in Python, i.e.:
```
import signal
def signal_handler(signum, frame):
logging.... | The Python Standard Library By Example shows this function in the chapter on signals:
```
SIGNALS_TO_NAMES_DICT = dict((getattr(signal, n), n) \
for n in dir(signal) if n.startswith('SIG') and '_' not in n )
```
You can then use it like this:
```
print "Terminated by signal %s" % SIGNALS_TO_NAMES_DICT[signal_num... |
Get signal names from numbers in Python | 2,549,939 | 29 | 2010-03-31T01:51:47Z | 35,996,948 | 10 | 2016-03-14T20:00:56Z | [
"python",
"signals"
] | Is there a way to map a signal number (e.g. signal.SIGINT) to its respective name (i.e. "SIGINT")?
I'd like to be able to print the name of a signal in the log when I receive it, however I cannot find a map from signal numbers to names in Python, i.e.:
```
import signal
def signal_handler(signum, frame):
logging.... | With the addition of the [`signal.Signals`](https://docs.python.org/3/library/signal.html) [`enum`](https://docs.python.org/3/library/enum.html#enum.IntEnum) in Python 3.5 this is now as easy as:
```
>>> import signal
>>> signal.SIGINT.name
'SIGINT'
>>> signal.SIGINT.value
2
>>> signal.Signals(2).name
'SIGINT'
>>> sig... |
Purpose of SQLAlchemy over MySQLdb | 2,550,292 | 6 | 2010-03-31T03:19:34Z | 2,550,304 | 9 | 2010-03-31T03:22:16Z | [
"python",
"sql",
"mysql",
"sqlalchemy"
] | Why do people use SQLAlchemy instead of MySQLdb? What advantages does it offer? | Easier portability among different DB engines (say that tomorrow you decide you want to move to sqlite, or PostgreSQL, or...), and higher level of abstraction (and thus potentially higher productivity).
Those are some of the *good* reasons. There are also some bad reasons for using an ORM, such as not wanting to learn... |
Purpose of SQLAlchemy over MySQLdb | 2,550,292 | 6 | 2010-03-31T03:19:34Z | 2,550,364 | 8 | 2010-03-31T03:43:47Z | [
"python",
"sql",
"mysql",
"sqlalchemy"
] | Why do people use SQLAlchemy instead of MySQLdb? What advantages does it offer? | You don't use SQLAlchemy instead of MySQLdbâyou use SQLAlchemy to access something like MySQLdb, oursql (another MySQL driver that I hear is nicer and has better performance), the sqlite3 module, psycopg2, or whatever other database driver you are using.
An ORM (like SQLAlchemy) helps abstract away the details of th... |
Correct way to put long function calls on multiple lines | 2,550,439 | 11 | 2010-03-31T04:07:44Z | 2,550,482 | 19 | 2010-03-31T04:22:35Z | [
"python",
"multiline"
] | I have a long function, as seen below:
```
hash_correct = hashlib.md5(salt + password)).digest().encode("base64")
```
I'd like to split it up into two lines but am not sure of the correct way to do this in Python?
Thanks. | The coding guidelines limiting length of lines is there, in part, to make the code more readable. In your case of chained method calls, the meaning is not clear. You should pick some temporary variable names for the intermediate values so that a reader of the code can understand the chain easily.
One example might be:... |
Which programming language or a library can process Infinite Series? | 2,552,213 | 26 | 2010-03-31T10:51:38Z | 2,552,256 | 18 | 2010-03-31T10:59:46Z | [
"python",
"math",
"programming-languages",
"functional-programming",
"series"
] | Which programming language or a library is able to process infinite series (like geometric or harmonic)? It perhaps must have a database of some well-known series and automatically give proper values in case of convergence, and maybe generate an exception in case of divergence.
For example, in Python it could look lik... | Most functional languages which evaluate lazily can simulate the processing of infinite series. Of course, on a finite computer it is not possible to process infinite series, as I am sure you are aware. Off the top of my head, I guess *Mathematica* can do most of what you might want, I suspect that *Maple* can too, may... |
Which programming language or a library can process Infinite Series? | 2,552,213 | 26 | 2010-03-31T10:51:38Z | 2,552,379 | 15 | 2010-03-31T11:18:16Z | [
"python",
"math",
"programming-languages",
"functional-programming",
"series"
] | Which programming language or a library is able to process infinite series (like geometric or harmonic)? It perhaps must have a database of some well-known series and automatically give proper values in case of convergence, and maybe generate an exception in case of divergence.
For example, in Python it could look lik... | One place to look might be the Wikipedia category of [Computer Algebra Systems](http://en.wikipedia.org/wiki/Category%3aComputer_algebra_systems). |
Which programming language or a library can process Infinite Series? | 2,552,213 | 26 | 2010-03-31T10:51:38Z | 2,552,419 | 7 | 2010-03-31T11:24:18Z | [
"python",
"math",
"programming-languages",
"functional-programming",
"series"
] | Which programming language or a library is able to process infinite series (like geometric or harmonic)? It perhaps must have a database of some well-known series and automatically give proper values in case of convergence, and maybe generate an exception in case of divergence.
For example, in Python it could look lik... | For Python check out [SymPy](http://code.google.com/p/sympy/) - clone of Mathematica and Matlab.
There is also a heavier Python-based math-processing tool called [Sage](http://www.sagemath.org/). |
Which programming language or a library can process Infinite Series? | 2,552,213 | 26 | 2010-03-31T10:51:38Z | 2,552,469 | 12 | 2010-03-31T11:32:07Z | [
"python",
"math",
"programming-languages",
"functional-programming",
"series"
] | Which programming language or a library is able to process infinite series (like geometric or harmonic)? It perhaps must have a database of some well-known series and automatically give proper values in case of convergence, and maybe generate an exception in case of divergence.
For example, in Python it could look lik... | Maxima can calculate some infinite sums, but in this particular case it doesn't seem to find the answer :-s
```
(%i1) sum((-1)^k/(2*k), k, 1, inf), simpsum;
inf
==== k
\ (- 1)
... |
Which programming language or a library can process Infinite Series? | 2,552,213 | 26 | 2010-03-31T10:51:38Z | 2,555,525 | 13 | 2010-03-31T18:36:19Z | [
"python",
"math",
"programming-languages",
"functional-programming",
"series"
] | Which programming language or a library is able to process infinite series (like geometric or harmonic)? It perhaps must have a database of some well-known series and automatically give proper values in case of convergence, and maybe generate an exception in case of divergence.
For example, in Python it could look lik... | There are two tools available in Haskell for this beyond simply supporting infinite lists.
First there is a module that supports looking up sequences in OEIS. This can be applied to the first few terms of your series and can help you identify a series for which you don't know the closed form, etc. The other is the 'CR... |
Which programming language or a library can process Infinite Series? | 2,552,213 | 26 | 2010-03-31T10:51:38Z | 3,507,368 | 8 | 2010-08-17T22:08:16Z | [
"python",
"math",
"programming-languages",
"functional-programming",
"series"
] | Which programming language or a library is able to process infinite series (like geometric or harmonic)? It perhaps must have a database of some well-known series and automatically give proper values in case of convergence, and maybe generate an exception in case of divergence.
For example, in Python it could look lik... | You can solve the series problem in [Sage](http://sagemath.org) (a free Python-based math software system) exactly as follows:
```
sage: k = var('k'); sum((-1)^k/(2*k+1), k, 1, infinity)
1/4*pi - 1
```
Behind the scenes, this is really using Maxima (a component of Sage). |
Which files to distribute using cx_Freeze? | 2,553,110 | 2 | 2010-03-31T13:07:40Z | 2,553,685 | 9 | 2010-03-31T14:19:07Z | [
"python",
"distutils",
"cx-freeze"
] | I'm using cx\_freeze to freeze a Python script for distribution to other windows systems. I did everything as instructed and cx\_freeze generated a `build\exe.win32-2.6` folder in the folder containing my sources. This directory now contains a a bunch of PYD files, a library.zip file, the python DLL file and the main e... | You need all of them. |
How to get a variable name as a string in Python? | 2,553,354 | 112 | 2010-03-31T13:39:10Z | 2,553,399 | 10 | 2010-03-31T13:44:03Z | [
"python",
"string",
"variables"
] | I would like to be able to get the name of a variable as a string but I don't know if Python has that much introspection capabilities. Something like:
```
>>> print(my_var.__name__)
'my_var'
```
I want to do that because I have a bunch of vars I'd like to turn into a dictionary like :
```
bar = True
foo = False
>>> ... | This is not possible in Python, which really doesn't have "variables". Python has names, and there can be more than one name for the same object. |
How to get a variable name as a string in Python? | 2,553,354 | 112 | 2010-03-31T13:39:10Z | 2,553,481 | 65 | 2010-03-31T13:54:20Z | [
"python",
"string",
"variables"
] | I would like to be able to get the name of a variable as a string but I don't know if Python has that much introspection capabilities. Something like:
```
>>> print(my_var.__name__)
'my_var'
```
I want to do that because I have a bunch of vars I'd like to turn into a dictionary like :
```
bar = True
foo = False
>>> ... | As unwind said, this isn't really something you do in Python - variables are actually name mappings to objects.
*However*, here's one way to try and do it:
```
>>> a = 1
>>> for k, v in list(locals().iteritems()):
if v is a:
a_as_str = k
>>> a_as_str
a
>>> type(a_as_str)
'str'
``` |
How to get a variable name as a string in Python? | 2,553,354 | 112 | 2010-03-31T13:39:10Z | 2,553,524 | 8 | 2010-03-31T13:58:45Z | [
"python",
"string",
"variables"
] | I would like to be able to get the name of a variable as a string but I don't know if Python has that much introspection capabilities. Something like:
```
>>> print(my_var.__name__)
'my_var'
```
I want to do that because I have a bunch of vars I'd like to turn into a dictionary like :
```
bar = True
foo = False
>>> ... | This is a hack. It will not work on all Python implementations distributions (in particular, those that do not have `traceback.extract_stack`.)
```
import traceback
def make_dict(*expr):
(filename,line_number,function_name,text)=traceback.extract_stack()[-2]
begin=text.find('make_dict(')+len('make_dict(')
... |
How to get a variable name as a string in Python? | 2,553,354 | 112 | 2010-03-31T13:39:10Z | 2,553,532 | 17 | 2010-03-31T13:59:54Z | [
"python",
"string",
"variables"
] | I would like to be able to get the name of a variable as a string but I don't know if Python has that much introspection capabilities. Something like:
```
>>> print(my_var.__name__)
'my_var'
```
I want to do that because I have a bunch of vars I'd like to turn into a dictionary like :
```
bar = True
foo = False
>>> ... | Are you trying to do this?
```
dict( (name,eval(name)) for name in ['some','list','of','vars'] )
```
Example
```
>>> some= 1
>>> list= 2
>>> of= 3
>>> vars= 4
>>> dict( (name,eval(name)) for name in ['some','list','of','vars'] )
{'list': 2, 'some': 1, 'vars': 4, 'of': 3}
``` |
How to get a variable name as a string in Python? | 2,553,354 | 112 | 2010-03-31T13:39:10Z | 6,486,008 | 31 | 2011-06-26T18:50:52Z | [
"python",
"string",
"variables"
] | I would like to be able to get the name of a variable as a string but I don't know if Python has that much introspection capabilities. Something like:
```
>>> print(my_var.__name__)
'my_var'
```
I want to do that because I have a bunch of vars I'd like to turn into a dictionary like :
```
bar = True
foo = False
>>> ... | I've wanted to do this quite a lot. This hack is very similar to rlotun's suggestion, but it's a one-liner, which is important to me:
```
blah = 1
blah_name = [ k for k,v in locals().iteritems() if v is blah][0]
``` |
Setting `axes.linewidth` without changing the `rcParams` global dict | 2,553,521 | 7 | 2010-03-31T13:58:18Z | 2,557,264 | 7 | 2010-03-31T23:49:01Z | [
"python",
"matplotlib",
"plot",
"graphing"
] | So, it seems one cannot do the following (it raises an error, since `axes` does not have a `set_linewidth` method):
```
axes_style = {'linewidth':5}
axes_rect = [0.1, 0.1, 0.9, 0.9]
axes(axes_rect, **axes_style)
```
and has to use the following old trick instead:
```
rcParams['axes.linewidth'] = 5 # set the value g... | Yes, there's an easy and clean way to do this.
Calling '**axhline**' and '**axvline**' from an axis instance appears to be the technique endorsed in the MPL Documentation.
In any event, it is simple and gives you fine-grained control over the appearance of the axes.
So for instance, this code will create a plot and ... |
Setting `axes.linewidth` without changing the `rcParams` global dict | 2,553,521 | 7 | 2010-03-31T13:58:18Z | 20,703,611 | 23 | 2013-12-20T12:25:31Z | [
"python",
"matplotlib",
"plot",
"graphing"
] | So, it seems one cannot do the following (it raises an error, since `axes` does not have a `set_linewidth` method):
```
axes_style = {'linewidth':5}
axes_rect = [0.1, 0.1, 0.9, 0.9]
axes(axes_rect, **axes_style)
```
and has to use the following old trick instead:
```
rcParams['axes.linewidth'] = 5 # set the value g... | The above answer does not work, as it is explained in the comments. I suggest to use spines.
```
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
# you can change each line separately, like:
#ax.spines['right'].set_linewidth(0.5)
# to change all, just write:
for axis in ['top','bottom','... |
How can i bundle other files when using cx_freeze? | 2,553,886 | 40 | 2010-03-31T14:44:12Z | 2,892,707 | 73 | 2010-05-23T17:31:24Z | [
"python",
"distutils",
"cx-freeze"
] | I'm using Python 2.6 and cx\_Freeze 4.1.2 on a Windows system. I've created the setup.py to build my executable and everything works fine.
When cx\_Freeze runs it moves everything to the build directory. I have some other files that I would like included in my build directory. How can I do this? Here's my structure.
... | Figured it out.
```
from cx_Freeze import setup,Executable
includefiles = ['README.txt', 'CHANGELOG.txt', 'helpers\uncompress\unRAR.exe', , 'helpers\uncompress\unzip.exe']
includes = []
excludes = ['Tkinter']
packages = ['do','khh']
setup(
name = 'myapp',
version = '0.1',
description = 'A general enhance... |
Exponential distribution in Python | 2,553,994 | 5 | 2010-03-31T14:58:03Z | 2,554,032 | 11 | 2010-03-31T15:03:14Z | [
"python",
"exponential-distribution"
] | What's the easiest way to draw a random number from an exponential distribution in Python? | [random.expovariate](http://docs.python.org/library/random.html?highlight=random#random.expovariate) of course. |
How do I access session data in Jinja2 templates (Bottle framework on app engine)? | 2,554,174 | 7 | 2010-03-31T15:19:58Z | 2,554,466 | 10 | 2010-03-31T16:01:47Z | [
"python",
"google-app-engine",
"session",
"jinja2",
"beaker"
] | I'm running the micro framework [Bottle](http://bottle.paws.de/page/docs) on Google App Engine. I'm using [Jinja2](http://jinja.pocoo.org/2/) for my templates. And I'm using [Beaker](http://pypi.python.org/pypi/Beaker/0.9.4) to handle the sessions. I'm still a pretty big Python newbie and am pretty stoked I got this fa... | You can add things to the Jinja2 [environment globals](http://jinja.pocoo.org/2/documentation/api#jinja2.Environment.globals) if you want them to be accessible to all templates. See [this page](http://jinja.pocoo.org/2/documentation/api#global-namespace) for additional information.
**Update:**
A simple example is, fo... |
Match groups in Python | 2,554,185 | 24 | 2010-03-31T15:21:06Z | 2,554,238 | 12 | 2010-03-31T15:28:43Z | [
"python",
"regex"
] | Is there a way in Python to access match groups without explicitely creating a match object (or another way to beautify the example below)?
Here is an example to clarify my motivation for the question:
Following perl code
```
if ($statement =~ /I love (\w+)/) {
print "He loves $1\n";
}
elsif ($statement =~ /Ich... | Less efficient, but simpler-looking:
```
m0 = re.match("I love (\w+)", statement)
m1 = re.match("Ich liebe (\w+)", statement)
m2 = re.match("Je t'aime (\w+)", statement)
if m0:
print "He loves",m0.group(1)
elif m1:
print "Er liebt",m1.group(1)
elif m2:
print "Il aime",m2.group(1)
```
The problem with the Perl s... |
Match groups in Python | 2,554,185 | 24 | 2010-03-31T15:21:06Z | 2,555,047 | 23 | 2010-03-31T17:20:10Z | [
"python",
"regex"
] | Is there a way in Python to access match groups without explicitely creating a match object (or another way to beautify the example below)?
Here is an example to clarify my motivation for the question:
Following perl code
```
if ($statement =~ /I love (\w+)/) {
print "He loves $1\n";
}
elsif ($statement =~ /Ich... | You could create a little class that returns the boolean result of calling match, *and* retains the matched groups for subsequent retrieval:
```
import re
class REMatcher(object):
def __init__(self, matchstring):
self.matchstring = matchstring
def match(self,regexp):
self.rematch = re.match(r... |
What is the analog for .Net InvalidOperationException in Python? | 2,554,722 | 11 | 2010-03-31T16:37:53Z | 2,554,816 | 7 | 2010-03-31T16:47:22Z | [
".net",
"python",
"exception",
"invalidoperationexception"
] | What is the analog for .Net `InvalidOperationException` in `Python`? | There's no direct equivalent. Usually `ValueError` or `TypeError` suffices, perhaps a `RuntimeError` or `NotImplementedError` if neither of those fit well. |
How to replace the last occurence of an expression in a string | 2,556,108 | 49 | 2010-03-31T20:07:23Z | 2,556,252 | 84 | 2010-03-31T20:29:35Z | [
"python"
] | Is there a quick way in Python to replace strings by starting from the end? For example:
```
>>> def rreplace(old, new, occurence)
>>> ... # Code to replace the last occurences of old by new
>>> '<div><div>Hello</div></div>'.rreplace('</div>','</bad>',1)
>>> '<div><div>Hello</div></bad>'
``` | ```
>>> def rreplace(s, old, new, occurrence):
... li = s.rsplit(old, occurrence)
... return new.join(li)
...
>>> s
'1232425'
>>> rreplace(s, '2', ' ', 2)
'123 4 5'
>>> rreplace(s, '2', ' ', 3)
'1 3 4 5'
>>> rreplace(s, '2', ' ', 4)
'1 3 4 5'
>>> rreplace(s, '2', ' ', 0)
'1232425'
``` |
What to put in a python module docstring? | 2,557,110 | 65 | 2010-03-31T23:04:34Z | 2,557,196 | 75 | 2010-03-31T23:28:02Z | [
"python",
"documentation",
"module"
] | Ok, so I've read both [PEP 8](http://www.python.org/dev/peps/pep-0008/) and [PEP 257](http://www.python.org/dev/peps/pep-0257/), and I've written lots of docstrings for functions and classes, but I'm a little unsure about what should go in a module docstring. I figured, at a minimum, it should document the functions an... | Think about somebody doing `help(yourmodule)` at the interactive interpreter's prompt -- what do they **want** to know? (Other methods of extracting and displaying the information are roughly equivalent to `help` in terms of amount of information). So if you have in `x.py`:
```
"""This module does blah blah."""
class... |
What to put in a python module docstring? | 2,557,110 | 65 | 2010-03-31T23:04:34Z | 7,373,383 | 21 | 2011-09-10T17:30:14Z | [
"python",
"documentation",
"module"
] | Ok, so I've read both [PEP 8](http://www.python.org/dev/peps/pep-0008/) and [PEP 257](http://www.python.org/dev/peps/pep-0257/), and I've written lots of docstrings for functions and classes, but I'm a little unsure about what should go in a module docstring. I figured, at a minimum, it should document the functions an... | To quote the [specifications](http://www.python.org/dev/peps/pep-0257/#multi-line-docstrings):
> The docstring of a **script**
> (a stand-alone program) should be usable as its "usage" message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a "-h" option, for "help"). Such a do... |
python dict.fromkeys() returns empty | 2,557,193 | 2 | 2010-03-31T23:27:09Z | 2,557,202 | 11 | 2010-03-31T23:30:05Z | [
"python",
"dictionary",
"fromkeys"
] | I wrote the following function. It returns an empty dictionary when it should not. The code works on the command line without function. However I cannot see what is wrong with the function, so I have to appeal to your collective intelligence.
```
def enter_users_into_dict(userlist):
newusr = {}
newusr.fromkeys... | fromkeys is a class method, meaning
```
newusr.fromkeys(userlist, 0)
```
is exactly the same as calling
```
dict.fromkeys(userlist, 0)
```
Both which *return* a dictionary of the keys in userlist. You need to assign it to something. Try this instead.
```
newusr = dict.fromkeys(userlist, 0)
return newusr
``` |
delete Task / PeriodicTask in celery | 2,557,424 | 8 | 2010-04-01T00:30:08Z | 2,558,783 | 15 | 2010-04-01T07:23:25Z | [
"python",
"rabbitmq",
"celery"
] | How can I delete a regular Task or PeriodicTask in celery? | You `revoke` the task: See [documentation](http://docs.celeryproject.org/en/latest/reference/celery.app.control.html#celery.app.control.Control.revoke):
```
Control.revoke(task_id, destination=None, terminate=False, signal='SIGTERM', **kwargs)
Tell all (or specific) workers to revoke a task by id.
If a task i... |
Search and get a line in Python | 2,557,808 | 8 | 2010-04-01T02:39:10Z | 2,557,837 | 13 | 2010-04-01T02:45:57Z | [
"python",
"string",
"search",
"line"
] | Is there a way to search, from a string, a line containing another string and retrieve the entire line?
For example:
```
string =
qwertyuiop
asdfghjkl
zxcvbnm
token qwerty
asdfghjklñ
retrieve_line("token") = "token qwerty"
``` | you mentioned "entire line" , so i assumed mystring is the entire line.
```
if "token" in mystring:
print mystring
```
however if you want to just get "token qwerty",
```
>>> mystring="""
... qwertyuiop
... asdfghjkl
...
... zxcvbnm
... token qwerty
...
... asdfghjklñ
... """
>>> for item in... |
How can I parse HTML with html5lib, and query the parsed HTML with XPath? | 2,558,056 | 12 | 2010-04-01T04:04:03Z | 2,558,254 | 19 | 2010-04-01T05:13:30Z | [
"python",
"parsing",
"xpath",
"lxml",
"html5lib"
] | I am trying to use html5lib to parse an html page in to something I can query with xpath. html5lib has close to zero documentation and I've spent too much time trying to figure this problem out. Ultimate goal is to pull out the second row of a table:
```
<html>
<table>
<tr><td>Header</td></tr>
<tr>... | Lack of documentation is a good reason to avoid a library IMO, no matter how cool it is. Are you wedded to using html5lib? Have you looked at [lxml.html](http://lxml.de/lxmlhtml.html)?
Here is a way to do this with lxml:
```
from lxml import html
tree = html.fromstring(text)
[td.text for td in tree.xpath("//td")]
```... |
How can I parse HTML with html5lib, and query the parsed HTML with XPath? | 2,558,056 | 12 | 2010-04-01T04:04:03Z | 5,073,316 | 15 | 2011-02-22T02:03:29Z | [
"python",
"parsing",
"xpath",
"lxml",
"html5lib"
] | I am trying to use html5lib to parse an html page in to something I can query with xpath. html5lib has close to zero documentation and I've spent too much time trying to figure this problem out. Ultimate goal is to pull out the second row of a table:
```
<html>
<table>
<tr><td>Header</td></tr>
<tr>... | What you want to use is the `namespaceHTMLElements` argument, which for some reason defaults to True.
```
doc = html5lib.parse('''<html>
<table>
<tr><td>Header</td></tr>
<tr><td>Want This</td></tr>
</table>
</html>
''', treebuilder='lxml', namespaceHTMLElements=False)
print lxml.html.tostring(... |
How can I get the expire time for the particular item in memcached | 2,558,706 | 6 | 2010-04-01T07:10:35Z | 9,970,657 | 7 | 2012-04-02T03:45:43Z | [
"python",
"memcached"
] | In runtime, I want to retrieve the expire time info about some items in memcached. I didn't find any related interface on memcached. Can I do this? something like:
mc.get\_expire\_time('key')
Thank you | Python memcache API doesn't provide such functionalities. However you can telnet into memcached to dump all keys and expiration time.
```
> telnet localhost 11211
```
`stats items` show the slabs that contain your data.
```
stats items
STAT items:12:number 1108
...
END
```
Then use `stats cachedump slab_id count` t... |
I/O error(socket error): [Errno 111] Connection refused | 2,558,801 | 12 | 2010-04-01T07:28:46Z | 2,560,472 | 10 | 2010-04-01T13:00:58Z | [
"python",
"sockets",
"urllib"
] | I have a program that uses urllib to periodically fetch a url, and I see intermittent
errors like :
I/O error(socket error): [Errno 111] Connection refused.
It works 90% of the time, but the othe r10% it fails. If retry the fetch immediately after it fails, it succeeds. I'm unable to figure out why this is so. I trie... | Getting an ECONNREFUSED errno means that *your* kernel was refused a connection at the other end, so if it's a bug, it's either in your kernel or in the other end.
What you can do is to trap the error in a very specific way and try again in a little while, since this seems to work:
```
# This is Python > 2.5 code
impo... |
I/O error(socket error): [Errno 111] Connection refused | 2,558,801 | 12 | 2010-04-01T07:28:46Z | 2,560,509 | 32 | 2010-04-01T13:05:49Z | [
"python",
"sockets",
"urllib"
] | I have a program that uses urllib to periodically fetch a url, and I see intermittent
errors like :
I/O error(socket error): [Errno 111] Connection refused.
It works 90% of the time, but the othe r10% it fails. If retry the fetch immediately after it fails, it succeeds. I'm unable to figure out why this is so. I trie... | Use a packet sniffer like [Wireshark](http://www.wireshark.org/) to look at what happens. You need to see a SYN-flagged packet outgoing, a SYN+ACK-flagged incoming and then a ACK-flagged outgoing. After that, the port is considered open on the local side.
If you only see the first packet and the error message comes af... |
Python check if object is in list of objects | 2,559,083 | 11 | 2010-04-01T08:35:15Z | 2,559,100 | 7 | 2010-04-01T08:38:19Z | [
"python"
] | I have a list of objects in Python. I then have another list of objects. I want to go through the first list and see if any items appear in the second list.
I thought I could simply do
```
for item1 in list1:
for item2 in list2:
if item1 == item2:
print "item %s in both lists"
```
However thi... | In case the objects are not the same instance, you need to implement the `__eq__` method for python to be able to tell when 2 objects are actually equal.
Of course that most library types, such as strings and lists already have `__eq__` implemented, which may be the reason comparing titles works for you (are they stri... |
Python check if object is in list of objects | 2,559,083 | 11 | 2010-04-01T08:35:15Z | 2,559,113 | 20 | 2010-04-01T08:40:54Z | [
"python"
] | I have a list of objects in Python. I then have another list of objects. I want to go through the first list and see if any items appear in the second list.
I thought I could simply do
```
for item1 in list1:
for item2 in list2:
if item1 == item2:
print "item %s in both lists"
```
However thi... | Assuming that your object has only a `title` attribute which is relevant for equality, you have to implement the `__eq__` method as follows:
```
class YourObject:
[...]
def __eq__(self, other):
return self.title == other.title
```
Of course if you have more attributes that are relevant for equality, y... |
Accessing a JET (.mdb) database in Python | 2,559,659 | 12 | 2010-04-01T10:21:59Z | 2,783,311 | 11 | 2010-05-06T18:00:17Z | [
"python",
"database",
"jet"
] | Is there a way to access a JET database from Python? I'm on Linux. All I found was a .mdb viewer in the repositories, but it's very faulty. Thanks | [MDB Tools](http://sourceforge.net/projects/mdbtools/) is a set of open source libraries and utilities to facilitate exporting data from MS Access databases (mdb files) without using the Microsoft DLLs. Thus non Windows OSs can read the data. Or, to put it another way, they are reverse engineering the layout of the MDB... |
Python equivalent of mysql_real_escape_string, for getting strings safely into MySQL? | 2,561,178 | 12 | 2010-04-01T14:41:10Z | 2,561,254 | 35 | 2010-04-01T14:51:29Z | [
"python",
"mysql"
] | Is there a Python equivalent of PHP's `mysql_real_escape_string`?
I'm trying to insert some strings into a MySQL db direct from Python, and keep getting tripped up by quotes in the strings.
```
mysql_string = "INSERT INTO candidate (name, address) VALUES "
for k, v in v_dict.iteritems():
mysql_string += " ('" +... | If you are using mysql-python, just try
```
MySQLdb.escape_string(SQL)
```
Example
```
>>> import MySQLdb
>>> MySQLdb.escape_string("'")
"\\'"
``` |
Python equivalent of mysql_real_escape_string, for getting strings safely into MySQL? | 2,561,178 | 12 | 2010-04-01T14:41:10Z | 2,561,275 | 10 | 2010-04-01T14:53:05Z | [
"python",
"mysql"
] | Is there a Python equivalent of PHP's `mysql_real_escape_string`?
I'm trying to insert some strings into a MySQL db direct from Python, and keep getting tripped up by quotes in the strings.
```
mysql_string = "INSERT INTO candidate (name, address) VALUES "
for k, v in v_dict.iteritems():
mysql_string += " ('" +... | ```
cursor.executemany('INSERT INTO candidate (name, address) VALUES (%s, %s)',
[(v_dict['name'], v_dict['address'])] * len(v_dict))
```
should do what your code appears to attempt -- inserting the **same** identical values N times (you're looping on `v_dict.iteritems()` but completely ignoring the ... |
Learning Python coming from PHP | 2,561,362 | 21 | 2010-04-01T15:05:31Z | 2,562,788 | 14 | 2010-04-01T18:44:56Z | [
"php",
"python"
] | My dynamic language experience is solely PHP. I want to learn Python now to broaden my career opportunities and just because I like programming. :)
When learning Java, I used a site (lost the URL/real name now), something like "Java for PHP developers" that had all on one side of the page the PHP code, and on the othe... | The OP's question is simple enough, but as @Pekka mentioned (or hijacked), this could be a much deeper question (requiring a more substantial answer). Yes, Python's syntax is easy enough to learn without a book, but like any other language, it still takes quite a bit of time to master.
The suggest of Dive Into Python ... |
How to comment out a block of Python code in Vim | 2,561,418 | 155 | 2010-04-01T15:14:46Z | 2,561,449 | 49 | 2010-04-01T15:18:10Z | [
"python",
"vim",
"editor"
] | I was wondering if there was any key mapping in Vim to allow me to indent certain lines of code (whether those lines have been selected in visual mode, or *n* lines above/below current cursor position).
So basically something that converts the following
```
def my_fun(x, y):
return x + y
```
to
```
#def my_fun(... | one way manually
```
:set number
:10,12s/^/#
``` |
How to comment out a block of Python code in Vim | 2,561,418 | 155 | 2010-04-01T15:14:46Z | 2,561,497 | 323 | 2010-04-01T15:24:14Z | [
"python",
"vim",
"editor"
] | I was wondering if there was any key mapping in Vim to allow me to indent certain lines of code (whether those lines have been selected in visual mode, or *n* lines above/below current cursor position).
So basically something that converts the following
```
def my_fun(x, y):
return x + y
```
to
```
#def my_fun(... | **Step 1:** Go to the the first column of the first line you want to comment.

**Step 2:** Press: `Ctrl`+`v` and select the lines you want to comment:

**Ste... |
How to comment out a block of Python code in Vim | 2,561,418 | 155 | 2010-04-01T15:14:46Z | 2,561,523 | 19 | 2010-04-01T15:26:01Z | [
"python",
"vim",
"editor"
] | I was wondering if there was any key mapping in Vim to allow me to indent certain lines of code (whether those lines have been selected in visual mode, or *n* lines above/below current cursor position).
So basically something that converts the following
```
def my_fun(x, y):
return x + y
```
to
```
#def my_fun(... | There are some good plugins to help comment/uncomment lines. For example [The NERD Commenter](http://www.vim.org/scripts/script.php?script_id=1218). |
How to comment out a block of Python code in Vim | 2,561,418 | 155 | 2010-04-01T15:14:46Z | 2,565,136 | 19 | 2010-04-02T05:30:15Z | [
"python",
"vim",
"editor"
] | I was wondering if there was any key mapping in Vim to allow me to indent certain lines of code (whether those lines have been selected in visual mode, or *n* lines above/below current cursor position).
So basically something that converts the following
```
def my_fun(x, y):
return x + y
```
to
```
#def my_fun(... | I usually sweep out a visual block (`<C-V>`), then search and replace the first character with:
```
:'<,'>s/^/#
```
(Entering command mode with a visual block selected automatically places '<,'> on the command line) I can then uncomment the block by sweeping out the same visual block and:
```
:'<,'>s/^#//
``` |
How to comment out a block of Python code in Vim | 2,561,418 | 155 | 2010-04-01T15:14:46Z | 2,567,010 | 7 | 2010-04-02T14:02:15Z | [
"python",
"vim",
"editor"
] | I was wondering if there was any key mapping in Vim to allow me to indent certain lines of code (whether those lines have been selected in visual mode, or *n* lines above/below current cursor position).
So basically something that converts the following
```
def my_fun(x, y):
return x + y
```
to
```
#def my_fun(... | I have the following lines in my `.vimrc`:
```
" comment line, selection with Ctrl-N,Ctrl-N
au BufEnter *.py nnoremap <C-N><C-N> mn:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR>:noh<CR>`n
au BufEnter *.py inoremap <C-N><C-N> <C-O>mn<C-O>:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR><C-O>:noh<CR><C-O>`n
au BufEnter *.py vnoremap <C-N><C-... |
How to comment out a block of Python code in Vim | 2,561,418 | 155 | 2010-04-01T15:14:46Z | 14,692,524 | 26 | 2013-02-04T17:53:46Z | [
"python",
"vim",
"editor"
] | I was wondering if there was any key mapping in Vim to allow me to indent certain lines of code (whether those lines have been selected in visual mode, or *n* lines above/below current cursor position).
So basically something that converts the following
```
def my_fun(x, y):
return x + y
```
to
```
#def my_fun(... | You could add the following mapping to your .vimrc
```
vnoremap <silent> # :s/^/#/<cr>:noh<cr>
vnoremap <silent> -# :s/^#//<cr>:noh<cr>
```
Highlight your block with:
```
Shift+v
```
`#` to comment your lines from the first column.
`-#` to uncomment the same way. |
How to comment out a block of Python code in Vim | 2,561,418 | 155 | 2010-04-01T15:14:46Z | 16,863,673 | 14 | 2013-05-31T18:34:52Z | [
"python",
"vim",
"editor"
] | I was wondering if there was any key mapping in Vim to allow me to indent certain lines of code (whether those lines have been selected in visual mode, or *n* lines above/below current cursor position).
So basically something that converts the following
```
def my_fun(x, y):
return x + y
```
to
```
#def my_fun(... | Highlight your block with: `Shift+v`
Comment the selected block out with: `:norm i#` (lower case i)
To uncomment, highlight your block again, and uncomment with: `:norm ^x`
The `:norm` command performs an action for every selected line. Commenting will insert a `#` at the start of every line, and uncommenting will d... |
fabric and svn password | 2,561,472 | 7 | 2010-04-01T15:20:36Z | 2,593,618 | 7 | 2010-04-07T15:13:26Z | [
"python",
"svn",
"fabric"
] | Assuming that I cannot run something like this with Fabric:
`run("svn update --password 'password' .")`
how's the proper way to pass to Fabric the password for the remote interactive command line?
The problem is that the repo is checked out as svn+ssh and I don't have a http/https/svn option | Try SSHkey. It allows you to connect to the server without password.
In this case, you will have to setup a sshkey between your remote server and the repo.
At remote server: Generate key pair
```
$ ssh-keygen -t dsa
```
Leave the passphase empty!
This will generate 2 files
* ~/.ssh/id\_dsa (private key)
* ~/.ssh/i... |
Configuring Eclipse with wxPython | 2,561,542 | 2 | 2010-04-01T15:28:36Z | 2,562,141 | 7 | 2010-04-01T16:59:04Z | [
"python",
"eclipse",
"wxpython"
] | I've been browsing documentation, but haven't been able to find a straightforward tutorial, so I apologize if this is a really simple question.
Anyway, I have eclipse with pydev installed on MAC OSX, and I want configure wxPython to work with eclipse, how do I do this? Once I've downloaded wxpython, what steps do I ta... | Vinay's answer above is correct. However, if code completion is not picking it up, you might need to add the WX directory to the Pydev's interpreter library path.
> Window | Preferences | Pydev |
> Interpreter - Python | Libraries
If wx is not present, New Folder and select the install directory. |
Python - Execute Process -> Block till it exits & Supress Output | 2,561,902 | 9 | 2010-04-01T16:20:25Z | 2,561,918 | 7 | 2010-04-01T16:24:07Z | [
"python",
"subprocess"
] | I'm using the following to execute a process and hide its output from Python. It's in a loop though, and I need a way to block until the sub process has terminated before moving to the next iteration.
```
subprocess.Popen(["scanx", "--udp", host], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
... | Use [`subprocess.call()`](http://docs.python.org/library/subprocess.html#subprocess.call). From the docs:
> subprocess.call(\*popenargs, \*\*kwargs)
> Run command with arguments. Wait for command to complete, then
> return the returncode attribute.
> The arguments are the same as for the
> Popen constructor.
**Edit... |
Integer to byte conversion | 2,562,308 | 2 | 2010-04-01T17:29:22Z | 2,562,340 | 12 | 2010-04-01T17:35:40Z | [
"python",
"byte",
"casting"
] | Say I've got an integer, 13941412, that I wish to separate into bytes (the number is actually a color in the form 0x00bbggrr). How would you do that? In c, you'd cast the number to a BYTE and then shift the bits. How do you cast to byte in Python? | Use bitwise mathematical operators, the "bytes" are already there:
```
def int_to_rgb(n):
b = (n & 0xff0000) >> 16
g = (n & 0x00ff00) >> 8
r = (n & 0x0000ff)
return (r, g, b)
``` |
python: send a list/dict over network | 2,562,359 | 4 | 2010-04-01T17:39:00Z | 2,562,371 | 11 | 2010-04-01T17:40:17Z | [
"python",
"serialization"
] | I'm looking for an easy way of packing/unpacking data structures for sending over the network:
on client just before sending:
```
a = ((1,2),(11,22,),(111,222))
message = pack(a)
```
and then on server:
```
a = unpack(message)
```
Is there a library that could do pack/unpack magic?
Thanks in advance | Looks like [JSON](http://www.json.org/) might fit the bill. It's simple, and [it's in the Python standard library](http://docs.python.org/library/json.html).
It might not be too happy about the tuples, though:
```
>>> import json
>>> a = ((1,2),(11,22,),(111,222))
>>> print a
((1, 2), (11, 22), (111, 222))
>>> messag... |
Python UTF-8 can't decode byte on 32-bit machine | 2,562,674 | 4 | 2010-04-01T18:28:28Z | 2,562,881 | 7 | 2010-04-01T19:00:03Z | [
"python",
"encoding",
"string",
"utf-8"
] | it works fine on 64 bit machines but for some reason will not work on python 2.4.3 on a 32-bit instance.
i get the error
```
'utf8' codec can't decode bytes in position 76-79: invalid data
```
for the code
```
try:
str(sourceresult.sourcename).encode('utf8','replace')
except:
raise Exception( repr(... | We need the following, and we need the *exact* output:
```
type(sourceresult.sourcename) # I suspect it's already a UTF-8 encoded string
repr(sourceresult.sourcename)
```
Like I said, I'm almost certain that your `sourceresult.sourcename` is already a UTF-8 encoded string.
Perhaps [this](http://stackoverflow.com/qu... |
MATLAB-like variable editor in Python | 2,562,697 | 4 | 2010-04-01T18:31:19Z | 2,567,042 | 8 | 2010-04-02T14:10:25Z | [
"python",
"matlab",
"numpy",
"ipython"
] | Is there a data viewer in Python/IPython like the variable editor in MATLAB? | You should try spiderlib:
<http://code.google.com/p/spyderlib/>
it's a dev environment a la matlab. |
Is there a multithreaded map() function? | 2,562,757 | 10 | 2010-04-01T18:40:07Z | 2,562,799 | 10 | 2010-04-01T18:47:06Z | [
"python",
"multithreading"
] | I have a function that is side effect free and I would like to run for every element in an array and return an array with all of the results. I'm wondering if python has something built into to generate all of the values.
Thank you. | Try the Pool.map function from multiprocessing:
<http://docs.python.org/library/multiprocessing.html#using-a-pool-of-workers>
It's not multithreaded per-se, but that's actually good since multithreading is severely crippled in Python by the GIL. |
Google App Engine (python): TemplateSyntaxError: 'for' statements with five words should end in 'reversed' | 2,563,365 | 6 | 2010-04-01T20:16:15Z | 2,563,544 | 13 | 2010-04-01T20:44:12Z | [
"python",
"django",
"google-app-engine",
"django-templates"
] | This is using the web app framework, not Django.
The following template code is giving me an **TemplateSyntaxError: 'for' statements with five words should end in 'reversed'** error when I try to render a dictionary. I don't understand what's causing this error. Could somebody shed some light on it for me?
```
{% for... | > This is using the web app framework,
> not Django.
But framework apart, you must be using Django's templating -- and apparently in an old version, which does not support the "automatic unpacking" style of `for` -- probably the [0.96](http://www.djangoproject.com/documentation/0.96/templates/#for) version that's the ... |
How do you composite an image onto another image with PIL in Python? | 2,563,822 | 26 | 2010-04-01T21:29:45Z | 2,563,883 | 42 | 2010-04-01T21:42:48Z | [
"python",
"image-processing",
"python-imaging-library"
] | I need to take an image and place it onto a new, generated white background in order for it to be converted into a downloadable desktop wallpaper. So the process would go:
1. Generate new, all white image with 1440x900 dimensions
2. Place existing image on top, centered
3. Save as single image
In PIL, I see the `Imag... | This can be accomplished with an Image instance's `paste` method:
```
from PIL import Image
img = Image.open('/pathto/file', 'r')
img_w, img_h = img.size
background = Image.new('RGBA', (1440, 900), (255, 255, 255, 255))
bg_w, bg_h = background.size
offset = ((bg_w - img_w) / 2, (bg_h - img_h) / 2)
background.paste(img... |
python: how to terminate a thread when main program ends | 2,564,137 | 39 | 2010-04-01T22:44:52Z | 2,564,161 | 25 | 2010-04-01T22:51:56Z | [
"python",
"multithreading"
] | If have a thread in infinite loop, is there a way to terminate it when main program ends (for example, when I press `ctrl+C`)? | Check this question. The correct answer has great explanation on how to terminate threads the right way:
<http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python>
To make the thread stop on Keyboard Interrupt signal (ctrl+c) you can catch the exception "KeyboardInterrup" and cleanup befor... |
python: how to terminate a thread when main program ends | 2,564,137 | 39 | 2010-04-01T22:44:52Z | 2,564,282 | 44 | 2010-04-01T23:35:24Z | [
"python",
"multithreading"
] | If have a thread in infinite loop, is there a way to terminate it when main program ends (for example, when I press `ctrl+C`)? | If you make your worker threads daemon threads, they will die when all your non-daemon threads (e.g. the main thread) have exited.
<http://docs.python.org/library/threading.html#threading.Thread.daemon> |
python: how to terminate a thread when main program ends | 2,564,137 | 39 | 2010-04-01T22:44:52Z | 2,564,768 | 9 | 2010-04-02T02:43:04Z | [
"python",
"multithreading"
] | If have a thread in infinite loop, is there a way to terminate it when main program ends (for example, when I press `ctrl+C`)? | Use the [atexit](http://docs.python.org/library/atexit.html?highlight=atexit#module-atexit) module of Python's standard library to register "termination" functions that get called (on the main thread) on any reasonably "clean" termination of the main thread, including an uncaught exception such as `KeyboardInterrupt`. ... |
Dynamic variable name in python | 2,564,140 | 4 | 2010-04-01T22:45:03Z | 2,564,157 | 10 | 2010-04-01T22:50:19Z | [
"python",
"django"
] | I'd like to call a query with a field name filter that I wont know before run time... Not sure how to construct the variable name ...Or maybe I am tired.
```
field_name = funct()
locations = Locations.objects.filter(field_name__lte=arg1)
```
where if funct() returns name would equal to
```
locations = Locations.obje... | You can create a dictionary, set the parameters and pass this to the function by [unpacking the dictionary as keyword arguments](http://docs.python.org/tutorial/controlflow.html#tut-unpacking-arguments):
```
field_name = funct()
params = {field_name + '__lte': arg1, # field_name should still contain string
... |
Python mysql check for duplicate before insert | 2,564,568 | 2 | 2010-04-02T01:09:50Z | 2,564,587 | 8 | 2010-04-02T01:18:13Z | [
"python",
"mysql",
"insert",
"no-duplicates"
] | here is the table
```
CREATE TABLE IF NOT EXISTS kompas_url
(
id BIGINT(20) NOT NULL AUTO_INCREMENT,
url VARCHAR(1000),
created_date datetime,
modified_date datetime,
PRIMARY KEY(id)
)
```
I am trying to do INSERT to kompas\_url table only if url is not exist yet
any idea?
thanks | You can either find out whether it's in there first, by `SELECT`ing by `url`, or you can make the `url` field unique:
```
CREATE TABLE IF NOT EXISTS kompas_url
...
url VARCHAR(1000) UNIQUE,
...
)
```
This will stop MySQL from inserting a duplicate row, but it will also report an error when you try and ins... |
WxPython Incompatible With Snow Leopard? | 2,565,201 | 18 | 2010-04-02T05:51:09Z | 2,565,220 | 25 | 2010-04-02T05:59:54Z | [
"python",
"eclipse",
"wxpython",
"pydev"
] | Recently I upgraded to Snow Leopard, and now I can't run programs built with wxPython. The errors I get are (from Eclipse + PyDev):
```
import wx
File "/var/tmp/wxWidgets/wxWidgets-13~231/2.6/DSTROOT/System/Library/Frameworks
/Python.framework/Versions/2.6/Extras/lib/
python/wx-2.8-mac-unicode/wx/__init__.py"... | The problem is that WxPython is only available on the Mac in 32-bit mode; however, by default, Python will start up in 64-bit mode. To fix this problem, create the following shell script named `python_32`:
```
#! /bin/bash
export VERSIONER_PYTHON_PREFER_32_BIT=yes
/usr/bin/python "$@"
```
Make the script executable (... |
WxPython Incompatible With Snow Leopard? | 2,565,201 | 18 | 2010-04-02T05:51:09Z | 4,036,767 | 15 | 2010-10-27T19:12:41Z | [
"python",
"eclipse",
"wxpython",
"pydev"
] | Recently I upgraded to Snow Leopard, and now I can't run programs built with wxPython. The errors I get are (from Eclipse + PyDev):
```
import wx
File "/var/tmp/wxWidgets/wxWidgets-13~231/2.6/DSTROOT/System/Library/Frameworks
/Python.framework/Versions/2.6/Extras/lib/
python/wx-2.8-mac-unicode/wx/__init__.py"... | While I see this is already answered, the answer is slightly wrong. The 2.9 series DOES have a Mac 64-bit build, albeit only for Python 2.7. See <http://wxpython.org/download.php> and look for the Cocoa build. From what I gather on the wxPython mailing list and IRC channel, you'll want to download a Python 64-bit build... |
Python In-memory table | 2,565,415 | 4 | 2010-04-02T06:52:33Z | 2,565,540 | 7 | 2010-04-02T07:32:39Z | [
"python",
"table",
"row"
] | What is the right way to forming in-memory table in python with direct lookups for rows and columns.
I thought of using dict of dicts this way,
```
class Table(dict):
def __getitem__(self, key):
if key not in self:
self[key]={}
return dict.__getitem__(self, key)
table = Table()
table... | I'd use an [in-memory database](http://www.sqlite.org/inmemorydb.html) with [SQLite](http://docs.python.org/library/sqlite3.html) for this. The sqlite module is even in the standard library since Python 2.5, which means this doesn't even add much to your requirements. |
Python In-memory table | 2,565,415 | 4 | 2010-04-02T06:52:33Z | 2,567,221 | 7 | 2010-04-02T14:41:43Z | [
"python",
"table",
"row"
] | What is the right way to forming in-memory table in python with direct lookups for rows and columns.
I thought of using dict of dicts this way,
```
class Table(dict):
def __getitem__(self, key):
if key not in self:
self[key]={}
return dict.__getitem__(self, key)
table = Table()
table... | > Now how do I do lookup if 'column1'
> has 'value11'
`any(arow['column1'] == 'value11' for arow in table.iteritems())`
> Is this method of forming tables
> wrong?
No, it's just very "exposed", perhaps too much -- it could usefully be encapsulated in a class which exposes the methods you need, then the issue of how ... |
algorithm for python itertools.permutations | 2,565,619 | 18 | 2010-04-02T07:54:06Z | 2,567,451 | 19 | 2010-04-02T15:24:45Z | [
"python",
"algorithm",
"permutation"
] | Can someone please explain algorithm for `itertools.permutations` routine in Python standard lib 2.6? I don't understand why it works.
Code is:
```
def permutations(iterable, r=None):
# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
# permutations(range(3)) --> 012 021 102 120 201 210
poo... | You need to understand the mathematical theory of [permutation cycles](http://mathworld.wolfram.com/PermutationCycle.html), also known as "orbits" (it's important to know both "terms of art" since the mathematical subject, the heart of [combinatorics](http://en.wikipedia.org/wiki/Combinatorics), is quite advanced, and ... |
find nearest value in numpy array | 2,566,412 | 132 | 2010-04-02T11:38:23Z | 2,566,508 | 214 | 2010-04-02T12:01:01Z | [
"python",
"search",
"numpy"
] | is there a numpy-thonic way, e.g. function, to find the 'nearest value' in an array?
example:
```
np.find_nearest( array, value )
``` | ```
import numpy as np
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return array[idx]
array = np.random.random(10)
print(array)
# [ 0.21069679 0.61290182 0.63425412 0.84635244 0.91599191 0.00213826
# 0.17104965 0.56874386 0.57319379 0.28719469]
value = 0.5
print(find_nearest(... |
find nearest value in numpy array | 2,566,412 | 132 | 2010-04-02T11:38:23Z | 10,465,997 | 20 | 2012-05-05T21:07:59Z | [
"python",
"search",
"numpy"
] | is there a numpy-thonic way, e.g. function, to find the 'nearest value' in an array?
example:
```
np.find_nearest( array, value )
``` | With slight modification, the answer above works with arrays of arbitrary dimension (1d, 2d, 3d, ...):
```
def find_nearest(a, a0):
"Element in nd array `a` closest to the scalar value `a0`"
idx = np.abs(a - a0).argmin()
return a.flat[idx]
```
Or, written as a single line:
```
a.flat[np.abs(a - a0).argmi... |
find nearest value in numpy array | 2,566,412 | 132 | 2010-04-02T11:38:23Z | 17,678,303 | 12 | 2013-07-16T13:47:32Z | [
"python",
"search",
"numpy"
] | is there a numpy-thonic way, e.g. function, to find the 'nearest value' in an array?
example:
```
np.find_nearest( array, value )
``` | Here's an extension to find the nearest vector in an array of vectors.
```
import numpy as np
def find_nearest_vector(array, value):
idx = np.array([np.linalg.norm(x+y) for (x,y) in array-value]).argmin()
return array[idx]
A = np.random.random((10,2))*100
""" A = array([[ 34.19762933, 43.14534123],
[ 48.7955... |
find nearest value in numpy array | 2,566,412 | 132 | 2010-04-02T11:38:23Z | 26,026,189 | 30 | 2014-09-24T20:48:09Z | [
"python",
"search",
"numpy"
] | is there a numpy-thonic way, e.g. function, to find the 'nearest value' in an array?
example:
```
np.find_nearest( array, value )
``` | *IF* your array is sorted and is very large, this is a much faster solution:
```
def find_nearest(array,value):
idx = np.searchsorted(array, value, side="left")
if idx > 0 and (idx == len(array) or math.fabs(value - array[idx-1]) < math.fabs(value - array[idx])):
return array[idx-1]
else:
r... |
How to make a simple cross-platform webbrowser with Python? | 2,566,720 | 4 | 2010-04-02T12:54:48Z | 2,568,140 | 9 | 2010-04-02T17:34:12Z | [
"python",
"winapi",
"cross-platform",
"webkit"
] | The <http://code.google.com/p/pywebkitgtk/> looks great but it seems to be running on linux only.
Does anybody know if there is something similar but cross-platform?
If not what can be the alternatives to make with Python a simple web-browser that can run on Windows, MAC os and linux?
Thanks in advance
Update: Does... | Qt (which has Python bindings with [PyQt](http://www.riverbankcomputing.co.uk/software/pyqt/intro) or [PySide](http://www.pyside.org/)) offers [Webkit](http://webkit.org/) (the same engine as Safari). Making a simple cross-platform browser is [trivially implemented](http://www.rkblog.rk.edu.pl/w/p/webkit-pyqt-rendering... |
Browser simulation - Python | 2,567,738 | 7 | 2010-04-02T16:16:12Z | 2,567,841 | 12 | 2010-04-02T16:36:21Z | [
"python",
"session",
"browser",
"cookies"
] | I need to access a few HTML pages through a Python script, problem is that I need COOKIE functionality, therefore a simple urllib HTTP request won't work.
Any ideas? | check out [Mechanize](http://wwwsearch.sourceforge.net/mechanize/). "Stateful programmatic web browsing in Python".
It handles cookies automagically.
```
import mechanize
br = mechanize.Browser()
resp = br.open("http://www.mysitewithcookies.com/")
print resp.info() # headers
print resp.read() # content
```
mecha... |
Can I use HTTP Post Requests for SOAP? - SOAP and Django | 2,568,175 | 4 | 2010-04-02T17:40:12Z | 2,568,347 | 8 | 2010-04-02T18:17:08Z | [
"python",
"django",
"http",
"soap",
"post"
] | I am wondering if I could use simply use HTTP POST Requests in order to implement a SOAP API.
If so how should I format and treat the requests? | Yep, I have done this in certain cases where SOAPpy did not work with a given schema. This should get you started.
```
import httplib
from xml.dom import minidom
http.request("POST", "/path/to/my/webservice", body=xml, headers = {
"Host": "myservername",
"Content-Type": "text/xml; charset=UTF-8",
"Content... |
Nested generator functions in python | 2,568,396 | 2 | 2010-04-02T18:26:48Z | 2,568,422 | 8 | 2010-04-02T18:31:44Z | [
"python",
"generator",
"list-comprehension"
] | Consider a tuple `v = (a,b,c)` and a generator function `generate(x)` which receives an item from the tuple and generates several options for each item.
What is the pythonic way of generating a set of all the possible combinations of the result of `generate(x)` on each item in the tuple?
I could do this:
```
v = (a,... | Python 2.6 has the function [`itertools.product()`](http://docs.python.org/library/itertools.html#itertools.product) that does what you want:
```
import itertools
v = (a, b, c)
for d, e, f in itertools.product(*(generate(x) for x in v)):
print d, e, f
```
From the docs:
> Cartesian product of input iterables.
>
> ... |
Inverse dictionary lookup - Python | 2,568,673 | 45 | 2010-04-02T19:18:27Z | 2,568,694 | 28 | 2010-04-02T19:21:10Z | [
"python",
"dictionary"
] | is there any straight forward way of finding a key by knowing the value within a dictionary?
all I can think of is this:
```
key = [key for key, value in dict_obj.items() if value == 'value'][0]
```
---
Any ideas? | There is none. Don't forget that the value may be found on any number of keys, including 0 or more than 1. |
Inverse dictionary lookup - Python | 2,568,673 | 45 | 2010-04-02T19:18:27Z | 2,569,074 | 26 | 2010-04-02T20:40:25Z | [
"python",
"dictionary"
] | is there any straight forward way of finding a key by knowing the value within a dictionary?
all I can think of is this:
```
key = [key for key, value in dict_obj.items() if value == 'value'][0]
```
---
Any ideas? | There are cases where a dictionary is a one:one mapping
Eg,
```
d = {1: "one", 2: "two" ...}
```
Your approach is ok if you are only doing a single lookup. However if you need to do more than one lookup it will be more efficient to create an inverse dictionary
```
ivd = {v: k for k, v in d.items()}
```
If there is... |
Inverse dictionary lookup - Python | 2,568,673 | 45 | 2010-04-02T19:18:27Z | 2,569,076 | 35 | 2010-04-02T20:40:49Z | [
"python",
"dictionary"
] | is there any straight forward way of finding a key by knowing the value within a dictionary?
all I can think of is this:
```
key = [key for key, value in dict_obj.items() if value == 'value'][0]
```
---
Any ideas? | Your list comprehension goes through all the dict's items finding all the matches, then just returns the first key. This generator expression will only iterate as far as necessary to return the first value:
```
key = (key for key,value in dd.items() if value=='value').next()
```
where dd is the dict. Will raise StopI... |
Inverse dictionary lookup - Python | 2,568,673 | 45 | 2010-04-02T19:18:27Z | 11,658,633 | 19 | 2012-07-25T21:06:16Z | [
"python",
"dictionary"
] | is there any straight forward way of finding a key by knowing the value within a dictionary?
all I can think of is this:
```
key = [key for key, value in dict_obj.items() if value == 'value'][0]
```
---
Any ideas? | This version is 26% shorter than [yours](http://stackoverflow.com/q/2568673/623735) but functions identically, even for redundant/ambiguous values (returns the first match, as yours does). However, it is probably twice as slow as yours, because it creates a list from the dict twice.
```
key = dict_obj.keys()[dict_obj.... |
Python: why does `random.randint(a, b)` return a range inclusive of `b`? | 2,568,783 | 28 | 2010-04-02T19:38:00Z | 2,568,810 | 10 | 2010-04-02T19:42:36Z | [
"python",
"random"
] | It has always seemed strange to me that `random.randint(a, b)` would return an integer in the range `[a, b]`, instead of `[a, b-1]` like `range(...)`.
Is there any reason for this apparent inconsistency? | I guess `random.randint` was just the first attempt at implementing this feature. It seems that the Python developers also felt that this was a problem, which is why in v1.5.2 they added another method [randrange](http://docs.python.org/library/random.html#random.randrange) with more standard parameters:
> ```
> rando... |
Python: why does `random.randint(a, b)` return a range inclusive of `b`? | 2,568,783 | 28 | 2010-04-02T19:38:00Z | 2,568,917 | 61 | 2010-04-02T20:08:31Z | [
"python",
"random"
] | It has always seemed strange to me that `random.randint(a, b)` would return an integer in the range `[a, b]`, instead of `[a, b-1]` like `range(...)`.
Is there any reason for this apparent inconsistency? | I tried to get to the bottom of this by examining some old sources. I *suspected* that `randint` was implemented before Python's long integer: meaning that if you wanted a random number that included `INT_MAX`, you would have needed to call `random.randrange(0, INT_MAX + 1)` which would have overflowed and resulted in ... |
How do I most efficienty check the unique elements in a list? | 2,569,578 | 5 | 2010-04-02T22:43:29Z | 2,569,584 | 8 | 2010-04-02T22:45:10Z | [
"python",
"list",
"dictionary",
"performance"
] | let's say I have a list
```
li = [{'q':'apple','code':'2B'},
{'q':'orange','code':'2A'},
{'q':'plum','code':'2A'}]
```
What is the most efficient way to return the count of unique "codes" in this list?
In this case, the unique codes is 2, because only *2B* and *2A* are unique.
I could put everything in a... | Probably the most efficient simple way is to create a set of the codes, which will filter out uniques, then get the number of elements in that set:
```
count = len(set(d["code"] for d in li))
```
As always, I advise to not worry about this kind of efficiency unless you've measured your performance and seen that it's ... |
socket.accept error 24: To many open files | 2,569,620 | 6 | 2010-04-02T22:56:37Z | 4,578,356 | 16 | 2011-01-02T12:26:38Z | [
"python",
"exception",
"file",
"sockets"
] | I have a problem with open files under my Ubuntu 9.10 when running server in Python2.6
And main problem is that, that i don't know why it so..
I have set
ulimit -n = 999999
net.core.somaxconn = 999999
fs.file-max = 999999
and lsof gives me about 12000 open files when server is running.
And also i'm using epoll.
... | Params that configure max open connections.
at /etc/sysctl.conf
add:
```
net.core.somaxconn=131072
fs.file-max=131072
```
and then:
```
sudo sysctl -p
```
at /usr/include/linux/limits.h
change:
```
NR_OPEN = 65536
```
at /etc/security/limits.conf
add:
```
* soft nofile 65535
* ... |
Output alternatives in Python | 2,570,269 | 2 | 2010-04-03T04:56:40Z | 2,570,272 | 7 | 2010-04-03T04:58:12Z | [
"python"
] | Is there any alternatives to the print statement for output in Python.
Also, how can I format my output text to be color-coded?
I'm a beginner programmer, pretty new to it.
Thanks | ```
sys.stdout.write()
```
Is one alternative. You can also write to `sys.stderr`. Personally, I use `sys.stdout` when I need to pass a generic "stream" to some function that will write to it. And open file is a stream, and `sys.stdout` is a stream. This way my function can be parametrized to write either to output or... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.