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 |
|---|---|---|---|---|---|---|---|---|---|
Does converting json to dict with eval a good choice? | 7,282,905 | 5 | 2011-09-02T11:43:07Z | 7,282,959 | 13 | 2011-09-02T11:48:00Z | [
"python",
"json",
"dictionary",
"eval"
] | I am getting a json object from a remote server, and converting it to a python string like this:
```
a = eval(response)
```
Is this stupid in any way, or do I have a better option? | Using `eval` is not a good way to process JSON:
1. JSON isn't even valid Python, because of `true`, `false`, and `null`.
2. `eval` will execute arbitrary Python code, so you are at the mercy of malicious injection of code.
Use the `json` module available in the standard library instead:
```
import json
data = json.l... |
perform multiple for loops simultaneously | 7,283,110 | 2 | 2011-09-02T12:02:30Z | 7,283,140 | 9 | 2011-09-02T12:04:39Z | [
"python",
"for-loop",
"simultaneous"
] | Is it possible to perform multiple loops simultaneously in python.
Like(syntax error, of course):
```
for a,b in list_of_a,list_of_b:
//do some thing
```
By *simultaneously*, I am **not** meaning the thread or process sense.
I mean, they share the same index or cursor during the iteration.
What I can think o... | ```
for a,b in zip(list_of_a, list_of_b):
# Do some thing
```
If you're using Python 2.x, are worried about performance, and/or using iterators instead of lists, consider [`itertools.izip`](http://docs.python.org/library/itertools.html#itertools.izip) instead of [`zip`](http://docs.python.org/library/functions.html#... |
Python traversing two lists | 7,283,599 | 3 | 2011-09-02T12:45:40Z | 7,283,629 | 13 | 2011-09-02T12:47:56Z | [
"python",
"list",
"traversal"
] | I found this nice statement in a tutorial:
```
for x,y in [(x,y) for x in listA for y in listB]:
```
Now, as for me, I understood, that that statment will traverse listA and listB and x is a value of list A and y is a value from listB. But in this example the two lists had the same length. Will this statement als... | The code computes the cartesian product ([`itertools.product`](http://docs.python.org/library/itertools.html#itertools.product)), not [`zip`](http://docs.python.org/library/functions.html#zip) as you suggested.
For example, if the inputs are `[1,2,3]` and `[4,5]`, the result is:
```
(1,4)
(1,5)
(2,4)
(2,5)
(3,4)
(3,5... |
Embedding Python into C - importing modules | 7,283,964 | 4 | 2011-09-02T13:14:38Z | 7,284,293 | 13 | 2011-09-02T13:41:48Z | [
"python",
"c",
"python-c-api",
"python-embedding"
] | I am having problems using the Embedded Python for C as per the [Documentation](http://docs.python.org/extending/embedding.html "documentation") - Whenever I try using imported modules I get an :
> Unhandled exception at 0x1e089e85 in PythonIncl.exe: 0xC0000005:
> Access violation reading location 0x00000004.
The err... | Check the result of the `PyImport_ImportModule` call: It fails and returns `NULL`. That is because by default, the current directory is not in the search path. Add
```
PySys_SetPath("."); // before ..
mymod = PyImport_ImportModule("reverse");
```
to add the current directory to the module search path and make your ex... |
Python's multiprocessing Does Not Play Nicely With threading.local? | 7,285,541 | 7 | 2011-09-02T15:14:04Z | 7,285,933 | 7 | 2011-09-02T15:44:16Z | [
"python",
"multithreading",
"multiprocessing",
"python-multithreading"
] | I have two processes (see sample code) that each attempt to access a threading.local object. I would expect the below code to print "a" and "b" (in either order). Instead, I get "a" and "a". How can I elegantly and robustly reset the threading.local object when I startup whole new processes?
```
import threading
impor... | Both operating systems you mentioned are Unix/Linux based and therefore implement the same `fork()`ing API.
A `fork()` completely duplicates the process object, along with its memory, loaded code, open file descriptors and threads. Moreover, the new process usually shares the very same process object within the kernel ... |
How to convert an associative array in python? | 7,286,111 | 4 | 2011-09-02T15:58:32Z | 7,286,144 | 14 | 2011-09-02T16:01:19Z | [
"python",
"for-loop"
] | I am really new to python and I can't find any information about this. I have an associative array `item`,
```
item['id'] = 0
item['title'] = 'python'
```
I want to validate the contents of item but I dont want to use the index name like `'title'` but just have a for loop and iterate over all entries in item regardle... | In Python, associative arrays are called [dictionaries](http://docs.python.org/library/stdtypes.html#mapping-types-dict).
A good way to iterate through a dict is to use [`.iteritems()`](http://docs.python.org/library/stdtypes.html#dict.iteritems):
```
for key, value in item.iteritems():
print key, value
```
If y... |
Using Python to break a continuous string into components? | 7,286,139 | 3 | 2011-09-02T16:00:48Z | 7,286,244 | 8 | 2011-09-02T16:08:00Z | [
"python"
] | This is similar to what I want to do: [breaking a 32-bit number into individual fields](http://stackoverflow.com/questions/2139377/breaking-a-32-bit-number-into-individual-fields)
This is my typical "string" 00000000110000000000011000000000
I need to break it up into four equal parts:
00000000
11000000
00000110
0... | This should do what you want. See [comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) for more details.
```
>>> s = "00000000110000000000011000000000"
>>> [s[i:i+8] for i in xrange(0, len(s), 8)]
['00000000', '11000000', '00000110', '00000000']
``` |
Print a list in reverse order with range()? | 7,286,365 | 154 | 2011-09-02T16:12:58Z | 7,286,366 | 238 | 2011-09-02T16:17:52Z | [
"python"
] | How can you produce the following list with `range()` in Python?
```
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
``` | Use the 'range' built-in function. The signature is `range(start, stop, step)`. This produces a sequence that yields numbers, starting with `start`, and ending if `stop` has been reached, excluding `stop`.
```
>>> range(9,-1,-1)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> range(-2, 6, 2)
[-2, 0, 2, 4]
```
In Python... |
Print a list in reverse order with range()? | 7,286,365 | 154 | 2011-09-02T16:12:58Z | 7,286,465 | 227 | 2011-09-02T16:26:47Z | [
"python"
] | How can you produce the following list with `range()` in Python?
```
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
``` | use `reversed()` function:
```
reversed(range(10))
```
It's much more meaningful.
**Update:**
If you want it to be a list (as btk pointed out):
```
list(reversed(range(10)))
``` |
Print a list in reverse order with range()? | 7,286,365 | 154 | 2011-09-02T16:12:58Z | 21,714,738 | 29 | 2014-02-11T22:44:42Z | [
"python"
] | How can you produce the following list with `range()` in Python?
```
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
``` | You could use`range(10)[::-1]`which is the same thing as`range(9, -1, -1)`and arguably more readable (if you're familiar with the common`sequence[::-1]`Python idiom). |
paramiko Incompatible ssh peer (no acceptable kex algorithm) | 7,286,929 | 10 | 2011-09-02T17:08:57Z | 32,691,055 | 7 | 2015-09-21T08:56:48Z | [
"python",
"ssh",
"paramiko",
"cisco"
] | I'm getting the following error when trying to ssh to a Cisco ACS device using the paramiko library. I've used paramiko in python without issue, and I can ssh to this box from the command line, or using putty without issue. I've turned on debugging and copied the info here. Please let me know if you can help me out.
`... | I was having similar issue with Debian 8 and OpenSSH on the server side.
As a quick fix, the following Cipher/MACs/KexAlgorithms settings on the server side fixes the issue:
**In /etc/ssh/sshd\_config:**
```
Ciphers aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes128-ctr
MACs hmac-sha2-512-etm@openssh.co... |
Python: Get relative path from comparing two absolute paths | 7,287,996 | 70 | 2011-09-02T18:52:42Z | 7,288,019 | 94 | 2011-09-02T18:54:21Z | [
"python"
] | Say, I have two absolute paths. I need to check if the location referring to by one of the paths is a descendant of the other. If true, I need to find out the relative path of the descendant from the ancestor. What's a good way to implement this in Python? Any library that I can benefit from? | [os.path.commonprefix()](http://docs.python.org/library/os.path.html#os.path.commonprefix) and [os.path.relpath()](http://docs.python.org/library/os.path.html#os.path.relpath) are your friends:
```
>>> print os.path.commonprefix(['/usr/var/log', '/usr/var/security'])
'/usr/var'
>>> print os.path.commonprefix(['/tmp', ... |
Python: Get relative path from comparing two absolute paths | 7,287,996 | 70 | 2011-09-02T18:52:42Z | 7,288,073 | 31 | 2011-09-02T19:00:00Z | [
"python"
] | Say, I have two absolute paths. I need to check if the location referring to by one of the paths is a descendant of the other. If true, I need to find out the relative path of the descendant from the ancestor. What's a good way to implement this in Python? Any library that I can benefit from? | [`os.path.relpath`](http://docs.python.org/library/os.path.html#os.path.relpath):
> Return a relative filepath to path either from the current directory or from an optional start point.
```
>>> from os.path import relpath
>>> relpath('/usr/var/log/', '/usr/var')
'log'
>>> relpath('/usr/var/log/', '/usr/var/sad/')
'..... |
Python: Get relative path from comparing two absolute paths | 7,287,996 | 70 | 2011-09-02T18:52:42Z | 7,288,086 | 12 | 2011-09-02T19:00:53Z | [
"python"
] | Say, I have two absolute paths. I need to check if the location referring to by one of the paths is a descendant of the other. If true, I need to find out the relative path of the descendant from the ancestor. What's a good way to implement this in Python? Any library that I can benefit from? | Another option is
```
>>> print os.path.relpath('/usr/var/log/', '/usr/var')
log
``` |
Best way to install pygame on OS X Lion? | 7,288,571 | 16 | 2011-09-02T19:51:12Z | 7,386,681 | 11 | 2011-09-12T10:47:13Z | [
"python",
"pygame"
] | I tried to install pygame via pip but this fails. Based on my google searches, it sounds like easy\_install also fails.
I also checked out: <http://www.pygame.org/wiki/MacLionCompile> but the solution is incomplete.
I'm running python 2.7.1 bundled with Lion.
Suggestions? Appreciate the help. | You could try the [binary package](http://www.pygame.org/ftp/pygame-1.9.2pre-py2.7-macosx10.7.mpkg.zip) for Lion, available on the [pygame website](http://www.pygame.org/download.shtml).
It worked for me (OSX 10.7.1 with bundled Python 2.7.1) |
Best way to install pygame on OS X Lion? | 7,288,571 | 16 | 2011-09-02T19:51:12Z | 10,125,655 | 7 | 2012-04-12T14:27:52Z | [
"python",
"pygame"
] | I tried to install pygame via pip but this fails. Based on my google searches, it sounds like easy\_install also fails.
I also checked out: <http://www.pygame.org/wiki/MacLionCompile> but the solution is incomplete.
I'm running python 2.7.1 bundled with Lion.
Suggestions? Appreciate the help. | Just for the sake of anyone that googles this question, my lab has a wiki set up with instructions for installing Pygame with just about any configuration:
<http://smash.psych.nyu.edu/labwiki/PyGameSetup> |
Best way to install pygame on OS X Lion? | 7,288,571 | 16 | 2011-09-02T19:51:12Z | 14,433,315 | 8 | 2013-01-21T06:22:09Z | [
"python",
"pygame"
] | I tried to install pygame via pip but this fails. Based on my google searches, it sounds like easy\_install also fails.
I also checked out: <http://www.pygame.org/wiki/MacLionCompile> but the solution is incomplete.
I'm running python 2.7.1 bundled with Lion.
Suggestions? Appreciate the help. | See the answer from this question: [PyGame in a virtualenv on OS X with brew?](http://stackoverflow.com/questions/8458911/pygame-in-a-virtualenv)
Essentially, the PyGame in PyPy hasn't been updated for a while.
The version in the repository has updated build scripts that handle Pythonbrew, virtualenv and other utiliti... |
Store and reload matplotlib.pyplot object | 7,290,370 | 24 | 2011-09-03T00:27:30Z | 12,734,723 | 25 | 2012-10-04T19:45:27Z | [
"python",
"matplotlib"
] | I work in an psudo-operational environment where we make new imagery on receipt of data. Sometimes when new data comes in, we need to re-open an image and update that image in order to create composites, add overlays, etc. In addition to adding to the image, this requires modification of titles, legends, etc.
Is there... | As of 1.2 matplotlib ships with experimental pickling support. If you come across any issues with it, please let us know on the mpl mailing list or by opening an issue on github.com/matplotlib/matplotlib
HTH
**EDIT**: Added a simple example
```
import matplotlib.pyplot as plt
import numpy as np
import pickle
ax = p... |
Write a string of 1's and 0's to a binary file? | 7,290,943 | 10 | 2011-09-03T03:20:34Z | 7,290,967 | 18 | 2011-09-03T03:28:48Z | [
"java",
"python",
"c",
"bash"
] | I want to take a string of 1's and 0's and convert it into an actual binary file(simply writing the string of 1's and 0's to a file would just make it either ascii file containing "00110001"s and "00110000"s ). I would prefer to do this in python or directly from a bash shell, but java or C is fine too. this is probabl... | In Python, use the `int` built-in function to convert the string of 0s and 1s to a number:
```
>>> int("00100101", 2)
37
```
Then use the `chr` built-in to convert a 8-bit integer (that is, in the inclusive range 0-255) to a character.
```
>>> chr(_)
'%'
```
The result of `chr` can be simply written to a file (open... |
Python and unicode code point extraction | 7,291,120 | 19 | 2011-09-03T04:12:47Z | 7,291,170 | 20 | 2011-09-03T04:28:20Z | [
"python",
"unicode"
] | In Python API, is there a way to extract the unicode code point of a single character?
%%
Edit: In case it matters, I'm using Python 2.7. | ```
>>> ord(u"Ä")
263
>>> u"café"[2]
u'f'
>>> u"café"[3]
u'\xe9'
>>> for c in u"café":
... print repr(c), ord(c)
...
u'c' 99
u'a' 97
u'f' 102
u'\xe9' 233
``` |
Python and unicode code point extraction | 7,291,120 | 19 | 2011-09-03T04:12:47Z | 7,291,199 | 18 | 2011-09-03T04:39:09Z | [
"python",
"unicode"
] | In Python API, is there a way to extract the unicode code point of a single character?
%%
Edit: In case it matters, I'm using Python 2.7. | If I understand your question correctly, you can do this.
```
>>> s='ã²'
>>> s.encode("unicode_escape")
b'\\u3232'
```
Shows the unicode escape code as a source string. |
Python: script's directory | 7,293,601 | 7 | 2011-09-03T14:08:54Z | 7,293,629 | 15 | 2011-09-03T14:13:35Z | [
"python",
"directory"
] | I was looking for a solution, but have not found what I need.
Script path: */dir/to/script/script.py* or *C:\dir\script.py*
Excepted result:
```
$ ./script.py
output: /dir/to/script
$ cd .. && ./script/script.py
output: /dir/to/script
```
Is there any function in os module or something?
---
I mixed solutions and ... | os.path.realpath will give you the result:
```
os.path.dirname(os.path.realpath(__file__))
``` |
Python regex: how to replace each instance of an occurrence with a different value? | 7,293,750 | 8 | 2011-09-03T14:36:46Z | 7,293,794 | 17 | 2011-09-03T14:43:33Z | [
"python",
"regex"
] | Suppose I have this string:
`s = "blah blah blah"`
Using Python regex, how can I replace each instance of "blah" with a different value (e.g. I have a list of values `v = ("1", "2", "3")` | You could use a [`re.sub` callback](http://docs.python.org/library/re.html#re.sub):
```
import re
def callback(match):
return next(callback.v)
callback.v=iter(('1','2','3'))
s = "blah blah blah"
print(re.sub(r'blah',callback,s))
```
yields
```
1 2 3
``` |
Python regex: how to replace each instance of an occurrence with a different value? | 7,293,750 | 8 | 2011-09-03T14:36:46Z | 7,293,797 | 7 | 2011-09-03T14:43:51Z | [
"python",
"regex"
] | Suppose I have this string:
`s = "blah blah blah"`
Using Python regex, how can I replace each instance of "blah" with a different value (e.g. I have a list of values `v = ("1", "2", "3")` | You could use [`re.sub`](http://docs.python.org/library/re.html#re.sub), which takes a string or function and applies it to each match:
```
>>> re.sub('blah', lambda m, i=iter('123'): next(i), 'blah blah blah')
<<< '1 2 3'
``` |
You are not allowed to edit '...' package information | 7,293,777 | 33 | 2011-09-03T14:40:19Z | 7,349,905 | 24 | 2011-09-08T14:44:31Z | [
"python",
"pypi"
] | I just registered a new package in PyPI. Once I uploaded it and it's appears to be already published on a website.
Next, I slightly changed source code, bumped to a new version and performed
```
python setup.py sdist upload
```
command from the shell. And this is a result:
```
Submitting dist/...-0.2.2.tar.gz to ht... | I investigated, experimented and found that this happend because I uploaded package, but havent registered it prior to uploading. Because I manually created .pypirc and registered account on the website, first upload was successful. After I deleted package, registered it and uploaded again, everything looks ok. |
You are not allowed to edit '...' package information | 7,293,777 | 33 | 2011-09-03T14:40:19Z | 23,552,217 | 35 | 2014-05-08T20:47:55Z | [
"python",
"pypi"
] | I just registered a new package in PyPI. Once I uploaded it and it's appears to be already published on a website.
Next, I slightly changed source code, bumped to a new version and performed
```
python setup.py sdist upload
```
command from the shell. And this is a result:
```
Submitting dist/...-0.2.2.tar.gz to ht... | You need to register it first.
```
python setup.py register
```
Then you can
```
python setup.py sdist upload
``` |
repeat an iteration of for loop | 7,293,978 | 7 | 2011-09-03T15:22:12Z | 7,293,992 | 14 | 2011-09-03T15:24:35Z | [
"python",
"for-loop"
] | if for some reason i want to repeat the same iteration how i can do it in python?
```
for eachId in listOfIds:
#assume here that eachId conatins 10
response = makeRequest(eachId) #assume that makeRequest function request to a url by using this id
if response == 'market is closed':
time.sleep(24*60*6... | Do it like this:
```
for eachId in listOfIds:
successful = False
while not successful:
response = makeRequest(eachId)
if response == 'market is closed':
time.sleep(24*60*60) #sleep for one day
else:
successful = True
```
The title of your question is the... |
Python cross-module logging | 7,294,127 | 6 | 2011-09-03T15:50:47Z | 7,294,147 | 8 | 2011-09-03T15:56:07Z | [
"python",
"logging",
"module"
] | I've googled and looked at the default documentation, but I can't figure out why this doesn't produce three lines of logging:
```
# main.py
import logging
import apple
import banana
log = logging.getLogger('main')
log.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = loggin... | The handler (`StreamHandler`) was not setup until after the imports. So the logging commands in the imported modules do not produce any output. Some handlers print to files, others communicate over a network, and some print to a console. There's no way the logging statements inside the imported modules could know what ... |
vim compiles with wrong python version (and not working with needed version) | 7,294,554 | 22 | 2011-09-03T17:06:00Z | 9,566,769 | 7 | 2012-03-05T12:37:45Z | [
"python",
"osx",
"vim",
"compilation"
] | ### In brief:
I have a problem with compiling vim with preferred python version.
When I use `--enable-pythoninterp` it compiles with system OSX python version.
When I use `--enable-pythoninterp=dynamic` I get an error in vim while trying `:py import sys`
### Here is what I was doing in more detail:
```
% git clo... | I had the same problem. I compiled *Macvim* from source and tried to use the python version 2.7 from macports in:
```
/opt/local/bin/python
```
Some modules were not found, for example the os module. The reason for this was that the PYTHONPATH variable **inside** macvim is wrong!
To test, open macvim and type:
```
... |
Django: session database table cleanup | 7,296,159 | 10 | 2011-09-03T22:10:46Z | 7,296,233 | 12 | 2011-09-03T22:26:18Z | [
"python",
"django",
"django-sessions"
] | Does this table need to be purged or is it taken care automatically by Django? | Django does NOT provide automatic purging. There is however a handy command available to help you do it manually: <https://docs.djangoproject.com/en/dev/topics/http/sessions/#clearing-the-session-store> |
AttributeError: 'unicode' object has no attribute '_sa_instance_state' | 7,296,296 | 9 | 2011-09-03T22:40:21Z | 7,296,507 | 8 | 2011-09-03T23:40:49Z | [
"python",
"sqlalchemy"
] | I'm just learning how to use SQLAlchemy. I'm trying to do the following, but storing title and link in two separate tables:
```
temp = Submissions(title=u'Facebook Homepage', link=u'http://facebook.com')
session.add(temp)
session.flush()
transaction.commit()
```
via:
```
class Links(Base):
__tablename__ = 'links... | You can't quite do that with `relationship`.
You need to arrange for the `Link` to be looked up in some way.
The most obvious is to just look it up directly.
```
submission_link = session.query(Links) \
.filter(Links.link == u'http://facebook.com') \
.first()
if subm... |
Django - Understanding X-Sendfile | 7,296,642 | 19 | 2011-09-04T00:20:03Z | 7,297,298 | 16 | 2011-09-04T03:47:43Z | [
"python",
"django",
"download",
"x-sendfile",
"protected-resource"
] | I've been doing some research regarding file downloads with access control, using Django. My goal is to completely block access to a file, except when accessed by a specific user. I've read that when using Django, X-Sendfile is one of the methods of choice for achieving this (based on other SO questions, etc). My rudim... | 1. Yes, that's just how it works.
2. The exact implementation depends on the webserver but in the case of nginx, it's recommended to mark the location as internal to prevent external access.
3. Nginx can asynchronously serve files while with Django you need one thread per request which can get problematic for higher nu... |
what is dict_keys, dict_items and dict_values | 7,296,716 | 18 | 2011-09-04T00:41:42Z | 7,297,095 | 22 | 2011-09-04T02:37:30Z | [
"python",
"list",
"dictionary"
] | I came across these three types when I used `collections.Counter`'s viewkeys(),viewitems() and viewvalues() method.
The value those three methods returned are of type `dict_keys`, `dict_items` and `dict_values`.
They are iterable, as I have noticed.
But my question is:
* why do these three types exist? Or what's th... | The [What's new in 2.7](http://docs.python.org/dev/whatsnew/2.7.html#pep-3106-dictionary-views) document is one place these are introduced. These "views" were introduced (proposed [here](http://www.python.org/dev/peps/pep-3106/)) for Python 3 (and backported to 2.7, as you've seen) to serve as a best-of-all-worlds for ... |
Django: Foreign Key relation with User Table does not validate | 7,296,848 | 11 | 2011-09-04T01:18:14Z | 7,296,897 | 30 | 2011-09-04T01:31:27Z | [
"python",
"django",
"django-models",
"django-admin"
] | Consider the following django model
```
from django.db import models
from django.contrib import auth
class Topic(models.Model):
user = models.ForeignKey('auth.models.User') ... | ```
from django.db import models
from django.contrib.auth.models import User
class Topic(models.Model):
user = models.ForeignKey(User)
```
`'auth.User'` would have worked, too. It's not Pyt... |
Django: Foreign Key relation with User Table does not validate | 7,296,848 | 11 | 2011-09-04T01:18:14Z | 13,209,045 | 7 | 2012-11-03T12:10:06Z | [
"python",
"django",
"django-models",
"django-admin"
] | Consider the following django model
```
from django.db import models
from django.contrib import auth
class Topic(models.Model):
user = models.ForeignKey('auth.models.User') ... | Even I faced same issue,
The error message is clear: you haven't installed the User model.
```
Add "django.contrib.auth" to INSTALLED_APPS in your settings.py.
```
That all..Hope it will solve this issue, worked fine for me. |
"Proper way" to manage multiple versions of Python on archlinux | 7,297,094 | 14 | 2011-09-04T02:37:08Z | 7,301,477 | 12 | 2011-09-04T18:59:08Z | [
"python",
"python-3.x",
"archlinux"
] | So I have read this - <https://wiki.archlinux.org/index.php/Python>
And it is clear from this wiki that I can install Python 2.7.2 via
```
pacman -S python2
```
Is it reasonable for me to create a symlink to python2
```
ln -s python2 /usr/bin/python
```
if I don't forsee myself switching to python 3.0 any time soo... | I would argue you shouldn't create any symlinks like this at all. Especially if you are going to distribute some of your python code, you should not assume a user has python2 or python3 at /usr/bin/python.
If your script requires python2, just use:
```
#!/usr/bin/env python2
```
If your script requires python3, use:... |
putting glade interface in python | 7,297,886 | 9 | 2011-09-04T07:19:51Z | 7,373,669 | 10 | 2011-09-10T18:16:00Z | [
"python",
"gtk",
"pygtk",
"glade"
] | I've made a gui in glade that I want to put in a python program. I was adapting the instructions from a tutorial I found online to load in my glade file (http://www.pygtk.org/articles/pygtk-glade-gui/Creating\_a\_GUI\_using\_PyGTK\_and\_Glade.htm). When I had problems I tried something basic (one button) calling it the... | Try with this code:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pygtk
pygtk.require("2.0")
import gtk
import gtk.glade
class HellowWorldGTK:
def __init__(self):
self.gladefile = "helloworld.glade"
self.glade = gtk.Builder()
self.glade.add_from_file(self.gladefile)
s... |
Django models: mutual references between two classes and impossibility to use forward declaration in python | 7,298,326 | 13 | 2011-09-04T09:30:53Z | 7,298,386 | 26 | 2011-09-04T09:48:23Z | [
"python",
"django",
"model",
"foreign-keys",
"forward-declaration"
] | I have defined two models where each one references the other, like so:
```
class User(models.Model):
# ...
loves = models.ManyToManyField(Article, related_name='loved_by')
class Article(models.Model):
# ...
author = models.ForeignKey(User)
```
You see, the problem is both classes references each oth... | You can find the solution in the [docs](https://docs.djangoproject.com/en/1.8/ref/models/fields/#foreignkey):
> If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself:
>
> ```
> class Car(models.Model):
> manufacturer = ... |
Calculating user, nice, sys, idle, iowait, irq and sirq from /proc/stat | 7,298,646 | 7 | 2011-09-04T10:41:43Z | 7,299,268 | 10 | 2011-09-04T12:38:35Z | [
"python",
"c",
"linux",
"kernel",
"procfs"
] | /proc/stat shows ticks for user, nice, sys, idle, iowait, irq and sirq like this:
`cpu 6214713 286 1216407 121074379 260283 253506 197368 0 0 0`
How can I calculate the individual utilizations (in %) for user, nice etc with these values? Like the values that shows in 'top' or 'vmstat'. | This code calculates user utilization spread over all cores.
```
import os
import time
import multiprocessing
def main():
jiffy = os.sysconf(os.sysconf_names['SC_CLK_TCK'])
num_cpu = multiprocessing.cpu_count()
stat_fd = open('/proc/stat')
stat_buf = stat_fd.readlines()[0].split()
user, nice, sys... |
Programming on samsung chromebook | 7,299,685 | 37 | 2011-09-04T14:02:45Z | 7,299,835 | 15 | 2011-09-04T14:25:58Z | [
"python",
"linux",
"google-app-engine",
"google-chrome-os",
"chromebook"
] | I would like to use my samsung chromebook to develop for app engine using python, unfortunately now it is not possible as I only have browser there.
There are online IDE's like [codule](https://codulo.us) but they are not good enough yet.
So in this regards I have 3 questions:
1. Is there a way to hack into chrome o... | Just enable [Developer Mode](http://www.chromium.org/chromium-os/developer-information-for-chrome-os-devices/samsung-series-5-chromebook), and you will get the access to the [shell](http://www.chromium.org/chromium-os/poking-around-your-chrome-os-device). |
Programming on samsung chromebook | 7,299,685 | 37 | 2011-09-04T14:02:45Z | 7,304,227 | 11 | 2011-09-05T05:41:09Z | [
"python",
"linux",
"google-app-engine",
"google-chrome-os",
"chromebook"
] | I would like to use my samsung chromebook to develop for app engine using python, unfortunately now it is not possible as I only have browser there.
There are online IDE's like [codule](https://codulo.us) but they are not good enough yet.
So in this regards I have 3 questions:
1. Is there a way to hack into chrome o... | Let me try and answer each of your 3 questions:
1. In dev mode you can hit **`ctrl`+`alt`+`T`** and get the shell. However, it's a trim/secure shell that won't let you do what you wish...
2. You can load any type of OS from usb and install it. I have few friends that did it with ubuntu but each and everyone of them - ... |
Programming on samsung chromebook | 7,299,685 | 37 | 2011-09-04T14:02:45Z | 10,678,702 | 7 | 2012-05-21T01:44:04Z | [
"python",
"linux",
"google-app-engine",
"google-chrome-os",
"chromebook"
] | I would like to use my samsung chromebook to develop for app engine using python, unfortunately now it is not possible as I only have browser there.
There are online IDE's like [codule](https://codulo.us) but they are not good enough yet.
So in this regards I have 3 questions:
1. Is there a way to hack into chrome o... | These days, you can easily set up [IPython Notebook](http://ipython.org/notebook.html) on a VM with any of a number of cloud service providers. EC2 has been done a bunch of times and is well documented, but pretty much any service that you can run a full Linux VM on should work.
It works like a regular webapp. Your co... |
Programming on samsung chromebook | 7,299,685 | 37 | 2011-09-04T14:02:45Z | 14,540,088 | 7 | 2013-01-26T18:24:56Z | [
"python",
"linux",
"google-app-engine",
"google-chrome-os",
"chromebook"
] | I would like to use my samsung chromebook to develop for app engine using python, unfortunately now it is not possible as I only have browser there.
There are online IDE's like [codule](https://codulo.us) but they are not good enough yet.
So in this regards I have 3 questions:
1. Is there a way to hack into chrome o... | Here is a guide for the new Samsung Chromebook that was introduced in October 2012 with flash memory. It will detail how to install Ubuntu onto an SSD drive to allow for dual boot without needing to modify the internal ChromeOS. To boot into Ubuntu after install you type Ctrl-U.
link:
<http://techfoobar.blogspot.com/2... |
Programming on samsung chromebook | 7,299,685 | 37 | 2011-09-04T14:02:45Z | 15,261,253 | 23 | 2013-03-07T01:06:02Z | [
"python",
"linux",
"google-app-engine",
"google-chrome-os",
"chromebook"
] | I would like to use my samsung chromebook to develop for app engine using python, unfortunately now it is not possible as I only have browser there.
There are online IDE's like [codule](https://codulo.us) but they are not good enough yet.
So in this regards I have 3 questions:
1. Is there a way to hack into chrome o... | You can also use [crouton](https://github.com/dnschneid/crouton) to install a chroot jail and then you are free to apt-get install any library that's compiles to armv7.
I have a Samsung Chromebook and I have installed the GAE python sdk , emacs and clozure common lisp for development.
Its super easy to set this up:
... |
Python: How can I parse { apple: "1" , orange: "2" } into Dictionary? | 7,300,050 | 4 | 2011-09-04T15:02:04Z | 7,300,115 | 13 | 2011-09-04T15:11:54Z | [
"python",
"json",
"dictionary"
] | I have received an output , it likes this.
```
{
orange: '2',
apple: '1',
lemon: '3'
}
```
I know it is not a standard JSON format, but is it still possible to parse into Python Dictionary type? Is it a must that **orange , apple , lemon** must be quoted?
Thanks you | This is valid [YAML](http://en.wikipedia.org/wiki/YAML) (a superset of JSON). Use [PyYAML](http://pyyaml.org/) to parse it:
```
>>> s = '''
... {
... orange: '2',
... apple: '1',
... lemon: '3'
... }'''
>>> import yaml
>>> yaml.load(s)
{'orange': '2', 'lemon': '3', 'apple': '1'}
```
More, since there is a... |
Inheriting from Frame or not in a Tkinter application | 7,300,072 | 17 | 2011-09-04T15:04:11Z | 7,300,221 | 7 | 2011-09-04T15:27:24Z | [
"python",
"tkinter"
] | I've seen two basic ways of setting up a tkinter program. Is there any reason to prefer one to the other?
```
from Tkinter import *
class Application():
def __init__(self, root, title):
self.root = root
self.root.title(title)
self.label = Label(self.root, text='Hello')
self.label... | A Frame is usually used as a [geometry master for other widgets](http://effbot.org/tkinterbook/frame.htm).
Since an application usually has numerous widgets, you'll often want to contain them all in a Frame, or at least use the Frame to add some `borderwidth`, padding, or other nicety.
Many example snippets you might ... |
Inheriting from Frame or not in a Tkinter application | 7,300,072 | 17 | 2011-09-04T15:04:11Z | 7,301,250 | 19 | 2011-09-04T18:24:03Z | [
"python",
"tkinter"
] | I've seen two basic ways of setting up a tkinter program. Is there any reason to prefer one to the other?
```
from Tkinter import *
class Application():
def __init__(self, root, title):
self.root = root
self.root.title(title)
self.label = Label(self.root, text='Hello')
self.label... | The option I prefer\* is to inherit from the class Tk. I think it is the more reasonable choice since the window is, in effect, your application. Inheriting from `Frame` doesn't make any more sense to me then inheriting from `Button` or `Canvas` or `Label`. Since you can only have a single root, it makes sense that tha... |
Is there anything like VirtualEnv for Java? | 7,300,148 | 23 | 2011-09-04T15:15:35Z | 7,300,200 | 22 | 2011-09-04T15:23:24Z | [
"java",
"python",
"virtualenv",
"jvm-languages"
] | Is there anything similar to Python [virtualenv](http://www.virtualenv.org/en/latest/index.html#virtualenv) for Java or JVM Languages? | From what I understand, virtualenv enables you to have separate library installation paths, effectively separate "virtual" Python installations.
Java doesn't have the concept of a "system-wide installed" library(\*): It always searches the classpath for the libraries to be loaded. Since the classpath can be (and needs... |
Using list as a data type in a column (SQLAlchemy) | 7,300,230 | 7 | 2011-09-04T15:28:42Z | 7,300,417 | 12 | 2011-09-04T15:59:17Z | [
"python",
"sqlalchemy"
] | I want to store a list of rss feed urls in an sqlite db. I'm using SQLAlchemy and was wondering how to store these. I can't seem to find any documentation about lists, and was wondering if this was legal for a column:
Column('rss\_feed\_urls', List)
Or is there an array type that I could use? | If you really must you could use the [PickleType](http://www.sqlalchemy.org/docs/core/types.html#sqlalchemy.types.PickleType). But what you probably want is another table (which consists of a *list* of rows, right?). Just create a table to hold your RSS feeds:
```
class RssFeed(Base):
__tablename__ = 'rssfeeds'
... |
South won't generate or apply migrations for existing app, with changes to migrate | 7,300,316 | 8 | 2011-09-04T15:41:46Z | 7,301,239 | 9 | 2011-09-04T18:22:30Z | [
"python",
"django",
"migration",
"django-south"
] | I'm using South to generate and apply migrations, rather than managing that myself. Unfortunately, South is refusing to actually *do* anything. Transcript below:
```
[graffias:~/testing.tustincommercial.com/oneclickcos]$ python ./manage.py schemamigration mainapp --auto
You cannot use --auto on an app with no migratio... | I guess you got yourself in trouble by not starting out with `./manage.py convert_to_south mainapp`. Maybe you can correct this by doing :
(1) Make South believe you didn't perform the first migration, so go to zero
`./manage.py migrate --fake mainapp zero`
(2) Migrate for real to the first migration.
`./manage.py ... |
How to use Python's pip to download and keep the zipped files for a package? | 7,300,321 | 59 | 2011-09-04T15:42:36Z | 7,300,619 | 81 | 2011-09-04T16:37:06Z | [
"python",
"pip"
] | If I want to use the `pip` command to download a package (and its dependencies), but *keep* all of the zipped files that get downloaded (say, django-socialregistration.tar.gz) - is there a way to do that?
I've tried various command-line options, but it always seems to unpack and *delete* the zipfile - or it gets the z... | The `--download-cache` option should do what you want:
```
pip install --download-cache="/pth/to/downloaded/files" package
```
However, when I tested this, the main package downloaded, saved and installed ok, but the the dependencies were saved with their full url path as the name - a bit annoying, but all the `tar.g... |
How to use Python's pip to download and keep the zipped files for a package? | 7,300,321 | 59 | 2011-09-04T15:42:36Z | 18,989,214 | 39 | 2013-09-24T18:23:53Z | [
"python",
"pip"
] | If I want to use the `pip` command to download a package (and its dependencies), but *keep* all of the zipped files that get downloaded (say, django-socialregistration.tar.gz) - is there a way to do that?
I've tried various command-line options, but it always seems to unpack and *delete* the zipfile - or it gets the z... | I always do this to download the packages:
`pip install --download /path/to/download/to_packagename`
OR
`pip install --download=/path/to/packages/downloaded -r requirements.txt`
And when I want to install all of those libraries I just downloaded, I do this:
`pip install --no-index --find-links="/path/to/downloaded... |
Preserve code readability while optimising | 7,300,903 | 18 | 2011-09-04T17:25:41Z | 7,301,080 | 15 | 2011-09-04T17:52:23Z | [
"python",
"performance",
"algorithm",
"optimization",
"code-readability"
] | I am writing a scientific program in Python and C with some complex physical simulation algorithms. After implementing algorithm, I found that there are a lot of possible optimizations to improve performance. Common ones are precalculating values, getting calculations out of cycle, replacing simple matrix algorithms wi... | Just as a general remark (I'm not too familiar with Python): I would suggest you **make sure that you can easily exchange the slow parts** of the 'reference implementation' with the 'optimized' parts (e.g., use something like the [Strategy](http://en.wikipedia.org/wiki/Strategy_pattern) pattern).
This will allow you t... |
add column to SQLAlchemy Table | 7,300,948 | 9 | 2011-09-04T17:32:43Z | 7,300,966 | 7 | 2011-09-04T17:35:40Z | [
"python",
"terminal",
"sqlalchemy"
] | I made a table using SQLAlchemy and forgot to add a Column. I basically want to do this:
```
users.addColumn('user_id', ForeignKey('users.user_id'))
```
What's the syntax for this, I couldn't find it in the docs? | This is referred to as database migration (SQLAlchemy doesn't support migration out of the box). You can look at using [sqlalchemy-migrate](http://code.google.com/p/sqlalchemy-migrate/) to help in these kinds of situations, or you can just `ALTER TABLE` through your chosen database's command line utility, |
add column to SQLAlchemy Table | 7,300,948 | 9 | 2011-09-04T17:32:43Z | 10,329,471 | 7 | 2012-04-26T08:07:55Z | [
"python",
"terminal",
"sqlalchemy"
] | I made a table using SQLAlchemy and forgot to add a Column. I basically want to do this:
```
users.addColumn('user_id', ForeignKey('users.user_id'))
```
What's the syntax for this, I couldn't find it in the docs? | See this section of the SQLAlchemy documentation: <http://docs.sqlalchemy.org/en/latest/core/schema.html#altering-schemas-through-migrations>
[Alembic](http://alembic.readthedocs.org/) is the latest software to offer this type of functionality and is made by the same author as SQLAlchemy. |
add column to SQLAlchemy Table | 7,300,948 | 9 | 2011-09-04T17:32:43Z | 17,243,132 | 7 | 2013-06-21T19:42:54Z | [
"python",
"terminal",
"sqlalchemy"
] | I made a table using SQLAlchemy and forgot to add a Column. I basically want to do this:
```
users.addColumn('user_id', ForeignKey('users.user_id'))
```
What's the syntax for this, I couldn't find it in the docs? | I have the same problem, and a thought of using migration library only for this trivial thing makes me
tremble. Anyway, this is my attempt so far:
```
def add_column(engine, table_name, column):
column_name = column.compile(dialect=engine.dialect)
column_type = column.type.compile(engine.dialect)
engine.... |
Why does "return list.sort()" return None, not the list? | 7,301,110 | 38 | 2011-09-04T17:58:28Z | 7,301,126 | 42 | 2011-09-04T18:00:31Z | [
"python",
"list",
"sorting",
"return"
] | Purpose:
1. Accept a file name
2. Print out the unique words alphabetically
Problem:
The file runs, and I've been able to verify that the `findUniqueWords` does result in a sorted list. However, it does not return the list to the `main()` method.
I can't seem to find out why this is. Any ideas?
Thanks!
Lee
```
def ... | `list.sort` sorts the list in place, i.e. it doesn't return a new list. Just write
```
newList.sort()
return newList
``` |
Why does "return list.sort()" return None, not the list? | 7,301,110 | 38 | 2011-09-04T17:58:28Z | 7,301,129 | 48 | 2011-09-04T18:00:51Z | [
"python",
"list",
"sorting",
"return"
] | Purpose:
1. Accept a file name
2. Print out the unique words alphabetically
Problem:
The file runs, and I've been able to verify that the `findUniqueWords` does result in a sorted list. However, it does not return the list to the `main()` method.
I can't seem to find out why this is. Any ideas?
Thanks!
Lee
```
def ... | The problem is here:
```
answer = newList.sort()
```
`sort` does not return the sorted list; rather, it sorts the list in place.
Use:
```
answer = sorted(newList)
``` |
Why does "return list.sort()" return None, not the list? | 7,301,110 | 38 | 2011-09-04T17:58:28Z | 12,699,808 | 30 | 2012-10-02T23:16:34Z | [
"python",
"list",
"sorting",
"return"
] | Purpose:
1. Accept a file name
2. Print out the unique words alphabetically
Problem:
The file runs, and I've been able to verify that the `findUniqueWords` does result in a sorted list. However, it does not return the list to the `main()` method.
I can't seem to find out why this is. Any ideas?
Thanks!
Lee
```
def ... | [Here](http://mail.python.org/pipermail/python-dev/2003-October/038855.html) is an email from Guido van Rossum in python's dev list explainig why he choose not to return `self` on operations that affects the object and don't return a new one.
> This comes from a coding style (popular in various other languages, I
> be... |
Using GET and POST with Authorization HTTP header in Python | 7,301,593 | 5 | 2011-09-04T19:23:57Z | 7,301,747 | 7 | 2011-09-04T19:53:40Z | [
"python",
"http",
"http-headers",
"google-api"
] | I am trying to get the list of Maps created by me in Google Maps, and the Maps API says the following:
---
**Retrieving a List of Maps**
The Maps Data API provides a feed that lists the maps created by a particular user; this feed is known as a "metafeed". A typical Maps Data API metafeed is a GET request of the fol... | Using urllib2 will make everything easier:
```
import urllib2
request = urllib2.Request('http://maps.google.com/maps/feeds/maps/default/full')
request.add_header('Authorization', 'GoogleLogin auth=%s' % authorization_token)
urllib2.urlopen(request).read()
```
BTW, isn't the Google Maps Data API deprecated? <http://g... |
OperationalError: (OperationalError) unable to open database file None None | 7,302,619 | 14 | 2011-09-04T22:52:06Z | 7,306,123 | 27 | 2011-09-05T09:23:08Z | [
"python",
"sqlite3",
"terminal",
"sqlalchemy"
] | Trying to format a database using SQLAlchemy but when I run create\_all on the metadata, I get the above error. I created the engine using the following path for user Tyre77:
```
engine = create_engine('sqlite:////tyre77/OmniCloud/database.db')
```
I've walked through and there is a file 'database.db' at that path, b... | You mention that it is a path to user tyre77 on OS X, so shouldn't that be `sqlite:////Users/tyre77/OmniCloud/database.db`?
Also, three slashes for relative paths, four for absolute paths. |
_shutdown AttributeError (ignored) when linting code that uses M2Crypto | 7,302,769 | 9 | 2011-09-04T23:32:12Z | 7,410,517 | 16 | 2011-09-14T02:06:07Z | [
"python",
"m2crypto",
"pylint"
] | I'm running lint as follows:
```
$ python -m pylint.lint m2test.py
```
with this code:
```
import M2Crypto
def f():
M2Crypto.RSA.new_pub_key("").as_pem(cipher=None).split("\n")
```
The lint output ends with:
```
Exception AttributeError: '_shutdown' in <module 'threading' from '/usr/lib/python2.7/site-packages... | The exception that you are seeing is caused by a bug in the `astng` package (presumably âAbstract Syntax Tree, Next Generationâ?) which is a toolkit on which `pylint` depends, written by the same people. I should note in passing that I always encourage people to use `pyflakes` instead of `pylint` when possible, bec... |
TextField missing in django.forms | 7,302,889 | 31 | 2011-09-05T00:03:48Z | 7,302,919 | 56 | 2011-09-05T00:13:23Z | [
"python",
"django"
] | ```
from django import forms
class UserForm(forms.ModelForm):
first_name = forms.TextField(label=_(u'First name'), required=False)
last_name = forms.TextField(label=_(u'Last name'))
```
It gives me an "**AttributeError: 'module' object has no attribute 'TextField'**.
Everything seems to be ok, except the miss... | [`CharField`](https://docs.djangoproject.com/en/stable/ref/forms/fields/#charfield) might be what you are looking for.
**EDIT:** To clarify, the docs mention [`TextField`](https://docs.djangoproject.com/en/stable/ref/models/fields/#textfield) as a model field type. You cannot use it as form field. The [table](https://... |
TextField missing in django.forms | 7,302,889 | 31 | 2011-09-05T00:03:48Z | 15,464,419 | 25 | 2013-03-17T18:20:22Z | [
"python",
"django"
] | ```
from django import forms
class UserForm(forms.ModelForm):
first_name = forms.TextField(label=_(u'First name'), required=False)
last_name = forms.TextField(label=_(u'Last name'))
```
It gives me an "**AttributeError: 'module' object has no attribute 'TextField'**.
Everything seems to be ok, except the miss... | If you want a textarea you can use the forms.CharField with the forms.TextArea widget.
```
class ContactForm(forms.Form):
message = forms.CharField(widget=forms.Textarea)
``` |
python saving the excess of a float to int conversion | 7,302,928 | 4 | 2011-09-05T00:15:50Z | 7,302,989 | 7 | 2011-09-05T00:31:19Z | [
"python"
] | ```
x=10.5
if x==10.5:
x=int(x)+1
y= .5
```
ok i have x=10.5 i want to round up to 11 but say the .5 to use later is there any way to do this when i dont know what x will be all the time?
i have to real place to start or even if its possible i do know how to change it to an int but i want to store... | One fell swoop:
```
>>> divmod(10.5,1)
(10.0, 0.5)
```
The docs for `divmod` can be found [here](http://docs.python.org/library/functions.html#divmod). |
What is the preferred way to implement 'yield' in Scala? | 7,303,166 | 15 | 2011-09-05T01:19:53Z | 7,303,297 | 16 | 2011-09-05T01:58:27Z | [
"python",
"scala",
"generator",
"yield",
"text-processing"
] | I am doing writing code for PhD research and starting to use Scala. I often have to do text processing. I am used to Python, whose 'yield' statement is extremely useful for implementing complex iterators over large, often irregularly structured text files. Similar constructs exist in other languages (e.g. C#), for good... | > 'yield' sucks, continuations are better
Actually, Python's `yield` *is* a continuation.
What is a continuation? A continuation is saving the present point of execution with all its state, such that one can *continue* at that point later. That's precisely what Python's `yield`, and, also, precisely how it is impleme... |
What is the preferred way to implement 'yield' in Scala? | 7,303,166 | 15 | 2011-09-05T01:19:53Z | 7,303,497 | 27 | 2011-09-05T02:50:18Z | [
"python",
"scala",
"generator",
"yield",
"text-processing"
] | I am doing writing code for PhD research and starting to use Scala. I often have to do text processing. I am used to Python, whose 'yield' statement is extremely useful for implementing complex iterators over large, often irregularly structured text files. Similar constructs exist in other languages (e.g. C#), for good... | The premise of your question seems to be that you want exactly Python's yield, and you don't want any other reasonable suggestions to do the same thing in a different way in Scala. If this is true, and it is that important to you, why not use Python? It's quite a nice language. Unless your Ph.D. is in computer science ... |
How to log smtp debug information to a file? | 7,303,351 | 4 | 2011-09-05T02:16:47Z | 7,303,587 | 9 | 2011-09-05T03:09:02Z | [
"python",
"email",
"smtp",
"cmd",
"smtplib"
] | As you know, python smtplib has a debug level.When I set it a true param, it will print some send information.
The problem is, I try to get the debug info to log into a file, but They just stay on my cmd console.
How can I do to log them?
Info like this:
```
connect: ('192.168.1.101', 25)
connect: (25, '192.168.1.1... | The `smtplib` prints directly to `stderr`, e.g. line 823 in smtplib.py:
```
print>>stderr, 'connect fail:', host
```
You'd have to either monkey patch sys.stderr **before** you import `smtplib` **or** `smtplib.stderr` **before** you run your mail code.
I might also suggest patching `smtplib.stderr` with a custom obj... |
Split filenames with python | 7,304,117 | 2 | 2011-09-05T05:20:40Z | 7,304,165 | 17 | 2011-09-05T05:28:54Z | [
"python",
"file"
] | I have files that I want only 'foo' and 'bar' left from split.
```
dn = "C:\\X\\Data\\"
```
files
```
f= C:\\X\\Data\\foo.txt
f= C:\\X\\Dats\\bar.txt
```
I have tried `f.split(".",1)[0]`
I thought since dn and .txt are pre-defined I could subtract, nope.
Split does not work for me. | how about using the proper path handling methods from os?:
```
f= 'C:\\X\\Data\\foo.txt'
>>> import os
>>> os.path.basename(f)
'foo.txt'
>>> os.path.dirname(f)
'C:\\X\\Data'
>>> os.path.splitext( f )
('C:\\X\\Data\\foo', '.txt')
>>> os.path.splitext( os.path.basename(f))
('foo', '.txt')
``` |
How should I write tests for Forms in Django? | 7,304,248 | 59 | 2011-09-05T05:45:07Z | 7,304,658 | 156 | 2011-09-05T06:50:23Z | [
"python",
"django",
"django-testing"
] | I'd like to simulate requests to my views in Django when I'm writing tests. This is mainly to test the forms. Here's a snippet of a simple test request:
```
from django.tests import TestCase
class MyTests(TestCase):
def test_forms(self):
response = self.client.post("/my/form/", {'something':'something'})
... | I think if you just want to test the form, then you should just test the form and not the view where the form is rendered. Example to get an idea:
```
from django.test import TestCase
from myapp.forms import MyForm
class MyTests(TestCase):
def test_forms(self):
form_data = {'something': 'something'}
... |
How should I write tests for Forms in Django? | 7,304,248 | 59 | 2011-09-05T05:45:07Z | 7,312,418 | 44 | 2011-09-05T20:19:51Z | [
"python",
"django",
"django-testing"
] | I'd like to simulate requests to my views in Django when I'm writing tests. This is mainly to test the forms. Here's a snippet of a simple test request:
```
from django.tests import TestCase
class MyTests(TestCase):
def test_forms(self):
response = self.client.post("/my/form/", {'something':'something'})
... | <https://docs.djangoproject.com/en/stable/topics/testing/tools/#django.test.SimpleTestCase.assertFormError>
```
from django.tests import TestCase
class MyTests(TestCase):
def test_forms(self):
response = self.client.post("/my/form/", {'something':'something'})
self.assertFormError(response, 'form'... |
Invert keys and values of the original dictionary | 7,304,980 | 5 | 2011-09-05T07:25:33Z | 7,305,070 | 11 | 2011-09-05T07:34:01Z | [
"python",
"dictionary",
"inverse"
] | For example, I call this function by passing a dictionary as parameter:
```
>>> inv_map({'a':1, 'b':2, 'c':3, 'd':2})
{1: ['a'], 2: ['b', 'd'], 3: ['c']}
>>> inv_map({'a':3, 'b':3, 'c':3})
{3: ['a', 'c', 'b']}
>>> inv_map({'a':2, 'b':1, 'c':2, 'd':1})
{1: ['b', 'd'], 2: ['a', 'c']}
```
If
```
map = { 'a': 1, 'b':2 }... | You can use a defaultdict with list:
```
>>> from collections import defaultdict
>>> m = {'a': 2, 'b': 1, 'c': 2, 'd': 1}
>>> dd = defaultdict(list)
>>> for k, v in m.iteritems():
... dd[v].append(k)
...
>>> dict(dd)
{1: ['b', 'd'], 2: ['a', 'c']}
```
If you don't care if you have an dict or defaultdict, you can... |
Combining itertools and multiprocessing? | 7,306,522 | 9 | 2011-09-05T10:05:03Z | 7,307,325 | 9 | 2011-09-05T11:22:32Z | [
"python",
"multiprocessing",
"itertools"
] | I have a `256x256x256` Numpy array, in which each element is a matrix. I need to do some calculations on each of these matrices, and I want to use the `multiprocessing` module to speed things up.
The results of these calculations must be stored in a `256x256x256` array like the original one, so that the result of the ... | All `multiprocessing.Pool.map*` methods consume iterators fully[(demo code)](http://stackoverflow.com/questions/7047918/why-in-python-map-and-multiprocessing-pool-map-got-different-answers/7048202#7048202) as soon as the function is called. To feed the map function chunks of the iterator one chunk at a time, use `group... |
Methods for entering equations while programming in C/C++ , Python or Fortran | 7,307,191 | 12 | 2011-09-05T11:12:22Z | 7,308,518 | 15 | 2011-09-05T13:04:49Z | [
"python",
"numpy",
"fortran",
"scipy",
"scientific-computing"
] | I am writing a code which had long mathematical equations with many trigonometric and other identities. Is there a way of visualising the same expression in latex and making a C or python expression from it or the other way around.
How do you enter and check mathematical expressions to see if the brackets etc are in t... | Have you looked at ***Sympy***? It has a module for generating LaTeX from python code, but it's actually quite a bit more.
[Sympy](http://code.google.com/p/sympy/), as you can probably guess from the name, is a python library for *symbolic computation*.
The Sympy library also includes it's own *built-in interpreter* ... |
How can I upload static files in GAE(python) with app.yaml? | 7,307,878 | 3 | 2011-09-05T12:10:19Z | 7,308,478 | 7 | 2011-09-05T13:00:22Z | [
"python",
"google-app-engine",
"file-upload",
"twitter",
"yaml"
] | I'm making a project using GAE, and have a terrible problem.
I wanted to make a twitter bot, so I started the first step with posting tweets. I made the 'tweets.txt' in the same folder as the 'dailybasic.py'.
Here's some parts of the codes.
```
#app.yaml
application: mathgirlna
version: 1
runtime: python
api_versio... | Static files can only be served directly to the user at the URL specified in app.yaml. They cannot be read by your application, as they are deployed to servers that only serve static files, and not to the infrastructure that runs your application.
If you only need to read the files from your script, just upload them a... |
Asterisk art in python | 7,308,344 | 5 | 2011-09-05T12:50:01Z | 7,308,393 | 13 | 2011-09-05T12:53:37Z | [
"python",
"string",
"ascii-art"
] | I would like to produce this picture in python!
```
*
**
***
****
*****
******
*******
********
*********
**********
```
I entered this:
```
x=1
while x<10:
print '%10s' %'*'*x
x=x+1
```
Which sadly seems to produce something composed of the right number of dots as ... | ```
'%10s' %'*'*x
```
is being parsed as
```
('%10s' % '*') * x
```
because the `%` and `*` operators have the same precedence and group left-to-right[[docs](http://docs.python.org/reference/expressions.html#summary)]. You need to add parentheses, like this:
```
x = 1
while x < 10:
print '%10s' % ('*' * x)
... |
Asterisk art in python | 7,308,344 | 5 | 2011-09-05T12:50:01Z | 7,308,395 | 8 | 2011-09-05T12:53:41Z | [
"python",
"string",
"ascii-art"
] | I would like to produce this picture in python!
```
*
**
***
****
*****
******
*******
********
*********
**********
```
I entered this:
```
x=1
while x<10:
print '%10s' %'*'*x
x=x+1
```
Which sadly seems to produce something composed of the right number of dots as ... | string object has `rjust` and `ljust` methods for precisely this thing.
```
>>> n = 10
>>> for i in xrange(1,n+1):
... print (i*'*').rjust(n)
...
*
**
***
****
*****
******
*******
********
*********
**********
```
or, alternatively:
```
>>> for i in reversed(xrange(n)... |
Periodically call a function in pygtk's main loop | 7,309,782 | 4 | 2011-09-05T14:59:42Z | 7,309,951 | 11 | 2011-09-05T15:19:14Z | [
"python",
"pygtk"
] | What's the pygtk equivalent for after method in tkinter?
I want to periodically call a function in the main loop.
What is the better way to achieve it? | Use [gobject.timeout\_add](http://www.pygtk.org/pygtk2reference/gobject-functions.html#function-gobject--idle-add):
```
import gobject
gobject.timeout_add(milliseconds, callback)
```
For example here is a progress bar that uses `timeout_add` to update the progress (`HScale`) value:
```
import gobject
import gtk
cla... |
How to create downloading progress bar in ttk? | 7,310,511 | 11 | 2011-09-05T16:14:17Z | 7,310,778 | 12 | 2011-09-05T16:44:02Z | [
"python",
"tkinter",
"ttk"
] | I want to show a progress bar while downloading a file from the web using the `urllib.urlretrive` method.
How do I use the `ttk.Progressbar` to do this task?
Here is what I have done so far:
```
from tkinter import ttk
from tkinter import *
root = Tk()
pb = ttk.Progressbar(root, orient="horizontal", length=200, mo... | For determinate mode you do not want to call `start`. Instead, simply configure the `value` of the widget or call the `step` method.
If you know in advance how many bytes you are going to download (and I assume you do since you're using determinate mode), the simplest thing to do is set the `maxvalue` option to the nu... |
Why won't re.groups() give me anything? | 7,312,020 | 19 | 2011-09-05T19:24:43Z | 7,312,049 | 14 | 2011-09-05T19:28:48Z | [
"python",
"regex",
"object",
"match"
] | When I run this code:
```
print re.search(r'1', '1').groups()
```
I get a result of `()`. However, `.group(0)` gives me the match.
Shouldn't `groups()` give me something containing the match?
Update: Thanks for the answers. So that means if I do `re.search()` with no subgroups, I *have* to use `groups(0)` to get a ... | groups is empty since you do not have any capturing groups - <http://docs.python.org/library/re.html#re.MatchObject.groups>. group(0) will always returns the whole text that was matched regardless of if it was captured in a group or not
Edited. |
Why won't re.groups() give me anything? | 7,312,020 | 19 | 2011-09-05T19:24:43Z | 7,312,122 | 15 | 2011-09-05T19:39:44Z | [
"python",
"regex",
"object",
"match"
] | When I run this code:
```
print re.search(r'1', '1').groups()
```
I get a result of `()`. However, `.group(0)` gives me the match.
Shouldn't `groups()` give me something containing the match?
Update: Thanks for the answers. So that means if I do `re.search()` with no subgroups, I *have* to use `groups(0)` to get a ... | To the best of my knowledge, `.groups()` returns a tuple of *remembered groups*. I.e. those groups in the regular expression that are enclosed in parentheses. So if you were to write:
```
print re.search(r'(1)', '1').groups()
```
you would get
```
('1',)
```
as your response. In general, `.groups()` will return a t... |
Haystack in INSTALLED_APPS results in Error: cannot import name openProc | 7,312,374 | 16 | 2011-09-05T20:14:10Z | 7,312,455 | 17 | 2011-09-05T20:24:20Z | [
"python",
"django-haystack"
] | I am pretty stuck right now. I have a Django project that's been working great until I tried to add Haystack/Whoosh for search. I've had this same stack in other projects working fine.
Whenever I have "haystack" in my settings.INSTALLED\_APPS and I try `manage.py runserver` or `manage.py shell` I get 'Error: cannot im... | It turns out I was able to get it working by installing the latest source code using `pip install git+git://github.com/toastdriven/django-haystack.git`
Something was wrong with the version I got doing `pip install haystack` |
Asyncore loop and raw_input problem | 7,312,977 | 7 | 2011-09-05T21:42:00Z | 7,320,026 | 9 | 2011-09-06T12:35:47Z | [
"python",
"loops",
"raw-input",
"asyncore"
] | I'm trying to learn asyncore module. So I decided to develop a chat program. I have to listen the network and broadcast udp packages same time. But problem is while user typing a message, user cannot see other messages that sent by another users. What should I do? My code:
```
#!/usr/bin/python
# -*- coding: utf-8 -*-... | The `raw_input` call is blocking, but you can use asyncore on it too.
You need to add an third player i.e. like this:
```
class CmdlineClient(asyncore.file_dispatcher):
def __init__(self, sender, file):
asyncore.file_dispatcher.__init__(self, file)
self.sender = sender
def handle_read(self):
... |
How would I succinctly transpose nested lists? | 7,313,194 | 6 | 2011-09-05T22:19:40Z | 7,313,210 | 24 | 2011-09-05T22:23:13Z | [
"python"
] | I am writing code to parse a tilemap map from a config file. The map is in the format:
```
1|2|3|4
1|2|3|4
2|3|4|5
```
where the numbers represent tiles.
I then make this into an integer array:
```
[[int(tile) for tile in row.split("|")] for row in "1|2|3|4\n1|2|3|4\n2|3|4|5".lstrip("\n").split("\n")]
```
This pro... | use `mylist = zip(*mylist)`:
```
>>> original = [[1, 2, 3, 4], [1, 2, 3, 4], [2, 3, 4, 5]]
>>> transposed = zip(*original)
>>> transposed
[(1, 1, 2), (2, 2, 3), (3, 3, 4), (4, 4, 5)]
>>> original[2][3]
5
>>> transposed[3][2]
5
```
How it works: [`zip(*original)`](http://docs.python.org/library/functions... |
How do I add two integers together with Twisted? | 7,313,761 | 42 | 2011-09-06T00:08:12Z | 7,313,862 | 35 | 2011-09-06T00:23:48Z | [
"python",
"asynchronous",
"twisted",
"addition",
"arithmetic-expressions"
] | I have two integers in my program; let's call them "`a`" and "`b`". I would like to add them together and get another integer as a result. These are regular Python `int` objects. I'm wondering; how do I add them together with Twisted? Is there a special `performAsynchronousAddition` function somewhere? Do I need a `Def... | OK, to be clear.
Twisted doesn't do anything about *[cpu bound tasks](http://en.wikipedia.org/wiki/CPU_bound)* and for good reason. there's no way to make a compute bound job go any quicker by reordering subtasks; the only thing you could possibly do is add more compute resources; and even that wouldn't work out in py... |
I want to return a value AND raise an exception, does this mean I'm doing something wrong? | 7,313,893 | 7 | 2011-09-06T00:30:55Z | 7,313,921 | 7 | 2011-09-06T00:38:14Z | [
"python",
"design",
"exception",
"architecture",
"exception-handling"
] | I have a number of functions that parse data from files, usually returning a list of results.
If I encounter a dodgy line in the file, I want to soldier on and process the valid lines, and return them. But I also want to report the error to the calling function. The reason I want to report it is so that the calling fu... | Nobody says the *only* valid way to treat an "error" is to throw an exception.
In your design the caller wants two pieces of information: (1) the valid data, (2) whether an error occurred (and probably something about what went wrong where, so it can format a useful error message). That is a completely valid and above... |
Python Interpreter not installed after installing Aptana Studio3 | 7,314,139 | 4 | 2011-09-06T01:31:17Z | 7,314,164 | 17 | 2011-09-06T01:39:12Z | [
"windows-7",
"aptana",
"pydev",
"python"
] | I was under the impression that installing Aptana Studio 3 also installed the python interpreter. when I try to create a PyDev project it says that "Project Interpreter not specified" So it will not let me proceed. Is there any documentation on how to proceed configuring the interpreter for Studio 3? I am using the lat... | I'd probably recommend you just download Python from the official site, and configure Aptana to find it.
You can download the latest version of Python from here:
<http://www.python.org/download/>
You didn't specify whether you were using Python 2.x or Python 3.x? For compatibility reasons, I'd probably go with Pytho... |
python imaplib to get gmail inbox subjects titles and sender name | 7,314,942 | 16 | 2011-09-06T04:29:13Z | 7,316,295 | 12 | 2011-09-06T07:23:04Z | [
"python",
"gmail",
"imaplib",
"email-headers"
] | I'm using pythons imaplib to connect to my gmail account. I want to retrieve the top 15 messages (unread or read, it doesn't matter) and display just the subjects and sender name (or address) but don't know how to display the contents of the inbox.
Here is my code so far (successful connection)
```
import imaplib
ma... | ```
c.select('INBOX', readonly=True)
for i in range(1, 30):
typ, msg_data = c.fetch(str(i), '(RFC822)')
for response_part in msg_data:
if isinstance(response_part, tuple):
msg = email.message_from_string(response_part[1])
for header in [ 'subject', 't... |
MSSQL in python 2.7 | 7,317,195 | 32 | 2011-09-06T08:46:30Z | 7,317,653 | 44 | 2011-09-06T09:24:22Z | [
"python",
"sql-server",
"sql-server-2008",
"python-2.7",
"pymssql"
] | Is there a module available for connection of MSSQL and python 2.7?
I downloaded pymssql but it is for python 2.6. Is there any equivalent module for python 2.7?
I am not aware of it if anyone can provide links.
---
Important note: in the meantime there is a pymssql module available. Don't miss to read the answer a... | You can also use [pyodbc](http://code.google.com/p/pyodbc/) to connect to MSSQL from Python. The most recent version is available for Python 2.6 and 2.7 [here](http://code.google.com/p/pyodbc/downloads/list).
From the [getting started](http://code.google.com/p/pyodbc/wiki/GettingStarted) guide:
```
import pyodbc
cnxn... |
MSSQL in python 2.7 | 7,317,195 | 32 | 2011-09-06T08:46:30Z | 25,749,269 | 13 | 2014-09-09T16:03:42Z | [
"python",
"sql-server",
"sql-server-2008",
"python-2.7",
"pymssql"
] | Is there a module available for connection of MSSQL and python 2.7?
I downloaded pymssql but it is for python 2.6. Is there any equivalent module for python 2.7?
I am not aware of it if anyone can provide links.
---
Important note: in the meantime there is a pymssql module available. Don't miss to read the answer a... | If you're coming across this question through a web search, note that `pymssql` nowadays ***does*** support Python 2.7 (and 3.3) or newer. No need to use ODBC.
From the `pymssql` requirements:
> Python 2.x: 2.6 or newer. Python 3.x: 3.3 or newer.
See <http://pymssql.org/>. |
How to correctly install pyGTK using macports? | 7,317,921 | 2 | 2011-09-06T09:45:15Z | 7,319,796 | 7 | 2011-09-06T12:18:32Z | [
"python",
"pygtk",
"macports"
] | My python code uses GTK for some GUI and now i need to run some of it on OSX (10.6 Snow Leopard and 10.7 Lion). Unfortunately, unofficial pyGTK [build](http://stackoverflow.com/questions/1164949/where-is-pygtk-for-mac-os-x) crashes on window GTK windows resize, so i decided to test macports version. I installed python ... | Port name was incorrect. Correct ports are `py25-gtk` / `py26-gtk` / `py27-gtk`.
Updated: recently renamed to `py25-pygtk` / `py26-pygtk` / `py27-pygtk` |
Xpath like query for nested python dictionaries | 7,320,319 | 15 | 2011-09-06T13:01:44Z | 16,508,093 | 7 | 2013-05-12T13:53:52Z | [
"python",
"xpath",
"jmespath"
] | Is there a way to define a XPath type query for nested python dictionaries.
Something like this:
```
foo = {
'spam':'eggs',
'morefoo': {
'bar':'soap',
'morebar': {'bacon' : 'foobar'}
}
}
print( foo.select("/morefoo/morebar") )
>> {'bacon' : 'foobar'}
```
I also ne... | There is an easier way to do this now.
<http://github.com/akesterson/dpath-python>
```
$ easy_install dpath
>>> dpath.util.search(YOUR_DICTIONARY, "morefoo/morebar")
```
... done. Or if you don't like getting your results back in a view (merged dictionary that retains the paths), yield them instead:
```
$ easy_inst... |
Xpath like query for nested python dictionaries | 7,320,319 | 15 | 2011-09-06T13:01:44Z | 26,050,704 | 11 | 2014-09-26T01:34:19Z | [
"python",
"xpath",
"jmespath"
] | Is there a way to define a XPath type query for nested python dictionaries.
Something like this:
```
foo = {
'spam':'eggs',
'morefoo': {
'bar':'soap',
'morebar': {'bacon' : 'foobar'}
}
}
print( foo.select("/morefoo/morebar") )
>> {'bacon' : 'foobar'}
```
I also ne... | One of the best libraries I've been able to identify, which, in addition, is very actively developed, is an extracted project from boto: [JMESPath](https://jmespath.readthedocs.org/en/latest/). It has a very powerful syntax of doing things that would normally take pages of code to express.
Here are some examples:
```... |
Since when does the bytes() function exist in Python? | 7,320,696 | 3 | 2011-09-06T13:28:19Z | 7,320,974 | 7 | 2011-09-06T13:46:41Z | [
"python",
"python-3.x",
"compatibility",
"backwards-compatibility"
] | Since which version does the bytes() function exist in Python? I'm writing some code that has to be compatible with as much versions of python as possible, so this kind of information is very important to me. Is there a good source to find the answer to such questions easily? | [PEP 3112](http://www.python.org/dev/peps/pep-3112/) added support for bytes literal in Python3. Python 3 adopted Unicode as the languageâs fundamental string type and denoted 8-bit literals either as `b'string'` or using a `bytes` constructor.
For future compatiblity, bytes was introduced in Python2.6. But note tha... |
Python: missing class attribute __module__ when using type()? | 7,320,705 | 7 | 2011-09-06T13:29:03Z | 7,320,926 | 12 | 2011-09-06T13:43:35Z | [
"python",
"django"
] | I'm attempting to dynamically construct some classes which are subclasses of django's models.Model. My code looks like this:
```
MyModel = type('MyModel', (models.Model,), {
'field': models.BooleanField()
})
```
When Django tries to load this, it gives the following exception:
```
Traceback (most recent call... | May be [metaclasses](http://docs.python.org/reference/datamodel.html#customizing-class-creation) is best choice for you needs than low-level `type()`?
But in most cases you can use `__name__` as a value for `__module__` like
```
MyModel = type('MyModel', (models.Model,), {
'field': models.BooleanField(),
'__m... |
SHA-256 implementation in Python | 7,321,694 | 9 | 2011-09-06T14:40:03Z | 7,323,113 | 14 | 2011-09-06T16:25:00Z | [
"python",
"sha256"
] | I'm looking for an implementation of the SHA-256 hash function written in Python. I want to use it to get a better understanding of how the SHA-256 function works, and I think Python is the ideal language for this. Pseudo-code has the limitation that I can't run/test it, to see what my modifications of the code do to t... | PyPy's source contains a pure-python implementation of SHA-256 [here](https://bitbucket.org/pypy/pypy/src/tip/lib_pypy/_sha256.py). Poking around in that directory, you'll probably also find pure-python implementations of other standard hashes. |
How to replace uppercase with underscore? | 7,322,028 | 4 | 2011-09-06T15:03:48Z | 7,322,356 | 7 | 2011-09-06T15:28:53Z | [
"python",
"regex",
"string",
"replace",
"uppercase"
] | I'm new to Python and I am trying to replace all uppercase-letters within a word to underscores, for example:
```
ThisIsAGoodExample
```
should become
```
this_is_a_good_example
```
Any ideas/tips/links/tutorials on how to achieve this? | Here's a regex way:
```
import re
example = "ThisIsAGoodExample"
print re.sub( '(?<!^)(?=[A-Z])', '_', example ).lower()
```
This is saying, "Find points in the string that *aren't* preceeded by a start of line, and *are* followed by an uppercase character, and substitute an underscore. Then we lower()case the whole ... |
How to use Python Pip install software, to pull packages from Github? | 7,322,334 | 29 | 2011-09-06T15:27:38Z | 7,322,505 | 46 | 2011-09-06T15:40:16Z | [
"python",
"pip"
] | I'm trying to install a package from Github, using Pip, using the following syntax
```
pip install -e git+https://github.com/facebook/python-sdk.git#egg=FacebookSDK
```
and getting the error "cannot find command git". [This Question](http://stackoverflow.com/q/3610639/78409) has (unchecked) answers saying that Git ne... | If I'm not mistaken, you would need the git client to be install on your machine. In the event that you don't have git installed, try this:
```
pip install https://github.com/facebook/python-sdk/zipball/master
```
or
```
pip install https://github.com/facebook/python-sdk/tarball/master
```
---
You need to install ... |
IntegrityError: (1062, Duplicate entry for key) | 7,323,434 | 2 | 2011-09-06T16:56:24Z | 7,324,244 | 7 | 2011-09-06T18:09:51Z | [
"python",
"mysql",
"django"
] | I was trying to purge my database, `mydb`, and repopulate it to see the effects of some changes to my Django model. Then all this happened. I rolled back to my earlier model set-up, but I *still* get the errors.
I am no MySQL pro, and I canât quite figure out the problem and what to do about it; I tried creating a n... | Django automatically [creates few default permissions](https://docs.djangoproject.com/en/dev/topics/auth/#default-permissions) on every model, these are: `add`, `delete` and `change`. You are getting integrity error because you are trying to create permissions with the same name. Just remove `delete_***` from your Meta... |
Python generator pre-fetch? | 7,323,664 | 3 | 2011-09-06T17:20:10Z | 7,323,715 | 7 | 2011-09-06T17:24:26Z | [
"python",
"generator"
] | I have a generator that takes a long time for each iteration to run. Is there a standard way to have it yield a value, then generate the next value while waiting to be called again?
The generator would be called each time a button is pressed in a gui and the user would be expected to consider the result after each but... | No. A generator is not asynchronous. This isn't multiprocessing.
If you want to avoid waiting for the calculation, you should use the `multiprocessing` package so that an independent process can do your expensive calculation.
You want a separate process which is calculating and enqueueing results.
Your "generator" c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.