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 |
|---|---|---|---|---|---|---|---|---|---|
Using module 'subprocess' with timeout | 1,191,374 | 198 | 2009-07-28T00:41:23Z | 10,768,774 | 13 | 2012-05-26T18:30:19Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] | Here's the Python code to run an arbitrary command returning its `stdout` data, or raise an exception on non-zero exit codes:
```
proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
```
`communicate` is used to wait for the process to ... | I've modified **sussudio** answer. Now function returns: (`returncode`, `stdout`, `stderr`, `timeout`) - `stdout` and `stderr` is decoded to utf-8 string
```
def kill_proc(proc, timeout):
timeout["value"] = True
proc.kill()
def run(cmd, timeout_sec):
proc = subprocess.Popen(shlex.split(cmd), stdout=subprocess.P... |
Using module 'subprocess' with timeout | 1,191,374 | 198 | 2009-07-28T00:41:23Z | 12,698,328 | 75 | 2012-10-02T21:06:25Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] | Here's the Python code to run an arbitrary command returning its `stdout` data, or raise an exception on non-zero exit codes:
```
proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
```
`communicate` is used to wait for the process to ... | In Python 3.3+:
```
from subprocess import STDOUT, check_output
output = check_output(cmd, stderr=STDOUT, timeout=seconds)
```
`output` is a byte string that contains command's merged stdout, stderr data.
This code raises `CalledProcessError` on non-zero exit status as specified in the question's text unlike `proc.... |
Using module 'subprocess' with timeout | 1,191,374 | 198 | 2009-07-28T00:41:23Z | 29,763,091 | 9 | 2015-04-21T04:43:41Z | [
"python",
"multithreading",
"timeout",
"subprocess"
] | Here's the Python code to run an arbitrary command returning its `stdout` data, or raise an exception on non-zero exit codes:
```
proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
```
`communicate` is used to wait for the process to ... | surprised nobody mentioned using `timeout`
`timeout 5 ping -c 3 somehost`
This won't for work for every use case obviously, but if your dealing with a simple script, this is hard to beat.
Also available as gtimeout in coreutils via `homebrew` for mac users. |
Sorting and indexing into a list in a Django template? | 1,191,439 | 5 | 2009-07-28T01:07:41Z | 1,216,920 | 11 | 2009-08-01T16:17:19Z | [
"python",
"django",
"django-templates"
] | How can you perform complex sorting on an object before passing it to the template? For example, here is my view:
```
@login_required
def overview(request):
physicians = PhysicianGroup.objects.get(pk=physician_group).physicians
for physician in physicians.all():
physician.service_patients.order_by('bed__room__... | As others have indicated, both of your problems are best solved outside the template -- either in the models, or in the view. One strategy would be to add helper methods to the relevant classes.
Getting a sorted list of a physician's patients:
```
class Physician(Model):
...
def sorted_patients(self):
ret... |
Hierarchical Bayes for R or Python | 1,191,689 | 11 | 2009-07-28T02:43:03Z | 1,191,708 | 13 | 2009-07-28T02:55:08Z | [
"python",
"statistics"
] | Hierarchical Bayes models are commonly used in Marketing, Political Science, and Econometrics. Yet, the only package I know of is `bayesm`, which is really a companion to a book (*Bayesian Statistics and Marketing*, by Rossi, et al.) Am I missing something? Is there a software package for R or Python doing the job out ... | There's OpenBUGS and R helper packages. Check out Gelman's site for his book, which has most of the relevant links:
* <http://www.stat.columbia.edu/~gelman/software/>
* [Example of computation in R and Bugs](http://www.stat.columbia.edu/~gelman/bugsR/software.pdf)
On the Python side, I only know of PyMC:
* <http://c... |
Hierarchical Bayes for R or Python | 1,191,689 | 11 | 2009-07-28T02:43:03Z | 1,192,044 | 8 | 2009-07-28T05:17:52Z | [
"python",
"statistics"
] | Hierarchical Bayes models are commonly used in Marketing, Political Science, and Econometrics. Yet, the only package I know of is `bayesm`, which is really a companion to a book (*Bayesian Statistics and Marketing*, by Rossi, et al.) Am I missing something? Is there a software package for R or Python doing the job out ... | Here are four books on hierarchical modeling and bayesian analysis written with R code throughout the books.
Hierarchical Modeling and Analysis for Spatial Data (Monographs on Statistics and Applied Probability) (Hardcover)
[http://www.amazon.com/gp/product/158488410X](http://rads.stackoverflow.com/amzn/click/15848841... |
SQLAlchemy: Operating on results | 1,192,269 | 5 | 2009-07-28T06:45:37Z | 1,192,439 | 8 | 2009-07-28T07:38:52Z | [
"python",
"sql",
"sqlalchemy"
] | I'm trying to do something relatively simple, spit out the column names and respective column values, and possibly filter out some columns so they aren't shown.
This is what I attempted ( after the initial connection of course ):
```
metadata = MetaData(engine)
users_table = Table('fusion_users', metadata, autoload=... | You can use `results` instantly as an iterator.
```
results = s.execute()
for row in results:
print row
```
Selecting specific columns is done the following way:
```
from sqlalchemy.sql import select
s = select([users_table.c.user_name, users_table.c.user_country], users_table.c.user_name == username)
for use... |
SQLAlchemy: Operating on results | 1,192,269 | 5 | 2009-07-28T06:45:37Z | 1,194,760 | 8 | 2009-07-28T15:05:24Z | [
"python",
"sql",
"sqlalchemy"
] | I'm trying to do something relatively simple, spit out the column names and respective column values, and possibly filter out some columns so they aren't shown.
This is what I attempted ( after the initial connection of course ):
```
metadata = MetaData(engine)
users_table = Table('fusion_users', metadata, autoload=... | A SQLAlchemy [RowProxy](http://www.sqlalchemy.org/docs/05/reference/sqlalchemy/connections.html#sqlalchemy.engine.base.RowProxy) object has dict-like methods -- `.items()` to get all name/value pairs, `.keys()` to get just the names (e.g. to display them as a header line, then use `.values()` for the corresponding valu... |
What's a good way to replace international characters with their base Latin counterparts using Python? | 1,192,367 | 5 | 2009-07-28T07:21:11Z | 1,192,471 | 7 | 2009-07-28T07:45:57Z | [
"python",
"string",
"internationalization"
] | Say I have the string `"blöt träbåt"` which has a few `a` and `o` with umlaut and ring above. I want it to become `"blot trabat"` as simply as possibly. I've done some digging and found the following method:
```
import unicodedata
unicode_string = unicodedata.normalize('NFKD', unicode(string))
```
This will give m... | It would be better if you created an explicit table, and then used the unicode.translate method. The advantage would be that transliteration is more precise, e.g. transliterating "ö" to "oe" and "Ã" to "ss", as should be done in German.
There are several transliteration packages on PyPI: [translitcodec](http://pypi.... |
Making tabulation look different than just whitespace | 1,192,480 | 9 | 2009-07-28T07:47:21Z | 1,192,516 | 16 | 2009-07-28T07:55:37Z | [
"python",
"vim"
] | How to make tabulation look different than whitespace in vim (highlighted for example).
That would be useful for code in Python. | I use something like this:
```
set list listchars=tab:»·,trail:·,precedes:â¦,extends:â¦,nbsp:â
```
Requires Vim7 and I'm not sure how well this is going to show up in a browser, because it uses some funky Unicode characters. It's good to use some oddball characters so that you can distinguish a tab from someth... |
Making tabulation look different than just whitespace | 1,192,480 | 9 | 2009-07-28T07:47:21Z | 1,195,534 | 7 | 2009-07-28T17:26:06Z | [
"python",
"vim"
] | How to make tabulation look different than whitespace in vim (highlighted for example).
That would be useful for code in Python. | Many others have mentioned the 'listchars' and 'list' options, but just to add another interesting alternative:
```
if &expandtab == 0
execute 'syn match MixedIndentationError display "^\([\t]*\)\@<=\( \{'.&ts.'}\)\+"'
else
execute 'syn match MixedIndentationError display "^\(\( \{' . &ts . '}\)*\)\@<=\t\+"'
e... |
python stdout flush and tee | 1,192,870 | 2 | 2009-07-28T09:07:35Z | 7,251,469 | 8 | 2011-08-31T00:52:17Z | [
"python",
"tee"
] | The following code ends with broken pipe when piped into tee, but behave correctly when not piped :
```
#!/usr/bin/python
import sys
def testfun():
while 1:
try :
s = sys.stdin.readline()
except(KeyboardInterrupt) :
print('Ctrl-C pressed')
sys.stdout.flush()
... | Nope, hitting Ctrl-C does NOT terminate both processes. It terminates the tee process only,
the end of the tee process close the pipe between your script and tee, and hence your script dies with the broken pipe message.
To fix that, tee has an option to pass the Ctrl-C to its previous process in the pipe: -i
try: man... |
Can someone explain this Python re.sub() unexpected output? | 1,192,918 | 3 | 2009-07-28T09:19:45Z | 1,192,965 | 7 | 2009-07-28T09:28:36Z | [
"python",
"regex"
] | I am using Python 2.6 and am getting [what I think is] unexpected output from re.sub()
```
>>> re.sub('[aeiou]', '-', 'the cat sat on the mat')
'th- c-t s-t -n th- m-t'
>>> re.sub('[aeiou]', '-', 'the cat sat on the mat', re.IGNORECASE)
'th- c-t sat on the mat'
```
If this output is what is expected, what is the logi... | Yes, the fourth parameter is count, not flags. You're telling it to apply the pattern twice (re.IGNORECASE = 2). |
Python - Get relative path of all files and subfolders in a directory | 1,192,978 | 22 | 2009-07-28T09:31:08Z | 1,193,171 | 8 | 2009-07-28T10:10:39Z | [
"python"
] | I am searching for a good way to get relative paths of files and (sub)folders within a specific folder.
For my current approach I am using `os.walk()`. It is working but it does not seem "pythonic" to me:
```
myFolder = "myfolder"
fileSet = set() # yes, I need a set()
for root, dirs, files in os.walk(myFolder):
... | ```
myFolder = "myfolder"
fileSet = set()
for root, dirs, files in os.walk(myFolder):
for fileName in files:
fileSet.add( os.path.join( root[len(myFolder):], fileName ))
``` |
Python - Get relative path of all files and subfolders in a directory | 1,192,978 | 22 | 2009-07-28T09:31:08Z | 13,617,120 | 37 | 2012-11-29T01:00:36Z | [
"python"
] | I am searching for a good way to get relative paths of files and (sub)folders within a specific folder.
For my current approach I am using `os.walk()`. It is working but it does not seem "pythonic" to me:
```
myFolder = "myfolder"
fileSet = set() # yes, I need a set()
for root, dirs, files in os.walk(myFolder):
... | Use [`os.path.relpath()`](http://docs.python.org/2/library/os.path.html#os.path.relpath). This is exactly its intended use.
```
import os
rootDir = "myfolder"
fileSet = set()
for dir_, _, files in os.walk(rootDir):
for fileName in files:
relDir = os.path.relpath(dir_, rootDir)
relFile = os.path.jo... |
What is the multiplatform alternative to subprocess.getstatusoutput (older commands.setstatusoutput() from Python? | 1,193,583 | 7 | 2009-07-28T11:47:02Z | 1,193,824 | 7 | 2009-07-28T12:37:16Z | [
"python",
"redirect",
"process"
] | The code below is outdated in Python 3.0 by being replaced by `subprocess.getstatusoutput()`.
```
import commands
(ret, out) = commands.getstatusoutput('some command')
print ret
print out
```
The real question is what's the multiplatform alternative to this command from Python because the above code does fail ugly un... | I wouldn't really consider this *multiplatform*, but you can use `subprocess.Popen`:
```
import subprocess
pipe = subprocess.Popen('dir', stdout=subprocess.PIPE, shell=True, universal_newlines=True)
output = pipe.stdout.readlines()
sts = pipe.wait()
print sts
print output
```
---
Here's a drop-in replacement for `ge... |
Is there a standard pythonic way to treat physical units / quantities in python? | 1,193,890 | 17 | 2009-07-28T12:51:20Z | 1,193,902 | 9 | 2009-07-28T12:53:28Z | [
"python",
"physics",
"units-of-measurement"
] | Is there a standard pythonic way to treat physical units / quantities in python? I saw different module-specific solutions from different fields like physics or neuroscience. But I would rather like to use a standard method than "island"-solutions as others should be able to easily read my code. | The best solution is the [Unum](http://home.scarlet.be/be052320/Unum.html) package. a de-facto standard, imho. |
Is there a standard pythonic way to treat physical units / quantities in python? | 1,193,890 | 17 | 2009-07-28T12:51:20Z | 1,204,146 | 9 | 2009-07-30T02:27:36Z | [
"python",
"physics",
"units-of-measurement"
] | Is there a standard pythonic way to treat physical units / quantities in python? I saw different module-specific solutions from different fields like physics or neuroscience. But I would rather like to use a standard method than "island"-solutions as others should be able to easily read my code. | [quantities](https://launchpad.net/python-quantities) seems to be gaining a lot of traction lately. |
Forward declaration - no admin page in django? | 1,194,723 | 3 | 2009-07-28T15:00:56Z | 1,194,800 | 12 | 2009-07-28T15:11:35Z | [
"python",
"django",
"database-design",
"circular-dependency",
"forward-declaration"
] | This is probably a db design issue, but I couldn't figure out any better. Among several others, I have these models:
```
class User(models.Model):
name = models.CharField( max_length=40 )
# some fields omitted
bands = models.ManyToManyField( Band )
```
and
```
class Band(models.Model):
creator = models.Forei... | See: <http://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey>, which says:
> 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 = models.ForeignKey('Manu... |
How to update manytomany field in Django? | 1,194,737 | 10 | 2009-07-28T15:02:37Z | 1,195,759 | 8 | 2009-07-28T18:10:14Z | [
"python",
"django"
] | Here's an example:
If I have these classes
```
class Author(models.Model):
name = models.CharField(max_length=45)
class Book(models.Model):
name = models.CharField(max_length=45)
authors = models.ManyToManyField(Author)
```
In the database I have one Author with the name "George" and another one with th... | With the auto-generated through table, you can do a two-step insert and delete, which is nice for readability.
```
george = Author.objects.get(name='George')
georfe = Author.objects.get(name='Georfe')
book.authors.add(george)
book.authors.remove(georfe)
assert george in book.authors
```
If you have an explicitly def... |
How to update manytomany field in Django? | 1,194,737 | 10 | 2009-07-28T15:02:37Z | 1,195,768 | 10 | 2009-07-28T18:11:54Z | [
"python",
"django"
] | Here's an example:
If I have these classes
```
class Author(models.Model):
name = models.CharField(max_length=45)
class Book(models.Model):
name = models.CharField(max_length=45)
authors = models.ManyToManyField(Author)
```
In the database I have one Author with the name "George" and another one with th... | **Note:** This code will *delete* the bad 'georfe' author, as well as updating the books to point to the correct author. If you don't want to do that, then use `.remove()` as @jcdyer's answer mentions.
Can you do something like this?
```
george_author = Author.objects.get(name="George")
for book in Book.objects.filte... |
Installing Django with mod_wsgi | 1,195,260 | 3 | 2009-07-28T16:33:46Z | 1,197,411 | 7 | 2009-07-29T00:04:32Z | [
"python",
"django",
"apache",
"mod-wsgi"
] | I wrote an application using Django 1.0. It works fine with the django test server. But when I tried to get it into a more likely production enviroment the Apache server fails to run the app.
The server I use is [WAMP2.0](http://www.wampserver.com "WAMPServer's WebSite"). I've been a PHP programmer for years now and I'... | You have:
```
WSGIScriptAlias / /C:/Users/Marcos/Documents/mysite/apache/django.wsgi
```
That is wrong as RHS is not a valid Windows pathname. Use:
```
WSGIScriptAlias / C:/Users/Marcos/Documents/mysite/apache/django.wsgi
```
That is, no leading slash before the Windows drive specifier.
Other than that, follow the... |
Python scoping problem | 1,195,577 | 3 | 2009-07-28T17:38:30Z | 1,195,696 | 9 | 2009-07-28T17:58:36Z | [
"python",
"scoping"
] | I have a trivial example:
```
def func1():
local_var = None
def func(args):
print args,
print "local_var:", local_var
local_var = "local"
func("first")
func("second")
func1()
```
I expect the output to be:
```
first local_var: None
second local_var: local
```
However, my ... | The assignment to `local_var` in `func` makes it local **to `func`** -- so the `print` statement references that "very very local" variable before it's ever assigned to, as the exception says. As jtb says, in Python 3 you can solve this with `nonlocal`, but it's clear from your code, using `print` statements, that you'... |
Web Services with Google App Engine | 1,195,893 | 6 | 2009-07-28T18:31:01Z | 1,195,949 | 9 | 2009-07-28T18:38:23Z | [
"java",
"python",
"web-services",
"google-app-engine"
] | I see that Google App Engine can host web applications that will return html, etc. But what about web services that communicate over http and accept / return xml?
Does anyone know how this is being done in Goggle App Engine with Python or for that matter in Java (JAS-WX is not supported)? Any links o samples or articl... | Google App Engine allows you to write web services that return any type of HTTP response content. This includes xml, json, text, etc.
For instance, take a look at the [guestbook sample project](http://code.google.com/appengine/docs/java/gettingstarted/) offered by Google which shows the HTTP response coming back as te... |
How to start a background process in Python? | 1,196,074 | 135 | 2009-07-28T18:56:50Z | 1,196,112 | 24 | 2009-07-28T19:02:59Z | [
"python",
"process",
"daemon"
] | I'm trying to port a shell script to the much more readable python version. The original shell script starts several processes (utilities, monitors, etc.) in the background with "&". How can I achieve the same effect in python? I'd like these processes not to die when the python scripts complete. I am sure it's related... | You probably want the answer to ["How to call an external command in Python"](http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python/92395#92395).
The simplest approach is to use the `os.system` function, e.g.:
```
import os
os.system("some_command &")
```
Basically, whatever you pass to the... |
How to start a background process in Python? | 1,196,074 | 135 | 2009-07-28T18:56:50Z | 1,196,122 | 46 | 2009-07-28T19:05:23Z | [
"python",
"process",
"daemon"
] | I'm trying to port a shell script to the much more readable python version. The original shell script starts several processes (utilities, monitors, etc.) in the background with "&". How can I achieve the same effect in python? I'd like these processes not to die when the python scripts complete. I am sure it's related... | **Note**: This answer is less current than it was when posted in 2009. Using the `subprocess` module shown in other answers is now recommended [in the docs](https://docs.python.org/2/library/os.html?highlight=os#os.spawnl)
> (Note that the subprocess module provides more powerful facilities for spawning new processes ... |
How to start a background process in Python? | 1,196,074 | 135 | 2009-07-28T18:56:50Z | 1,196,162 | 8 | 2009-07-28T19:12:06Z | [
"python",
"process",
"daemon"
] | I'm trying to port a shell script to the much more readable python version. The original shell script starts several processes (utilities, monitors, etc.) in the background with "&". How can I achieve the same effect in python? I'd like these processes not to die when the python scripts complete. I am sure it's related... | You probably want to start investigating the os module for forking different threads (by opening an interactive session and issuing help(os)). The relevant functions are fork and any of the exec ones. To give you an idea on how to start, put something like this in a function that performs the fork (the function needs t... |
How to start a background process in Python? | 1,196,074 | 135 | 2009-07-28T18:56:50Z | 7,224,186 | 198 | 2011-08-28T21:47:04Z | [
"python",
"process",
"daemon"
] | I'm trying to port a shell script to the much more readable python version. The original shell script starts several processes (utilities, monitors, etc.) in the background with "&". How can I achieve the same effect in python? I'd like these processes not to die when the python scripts complete. I am sure it's related... | While [jkp](http://stackoverflow.com/questions/1196074/starting-a-background-process-in-python/1196122#1196122)'s solution works, the newer way of doing things (and the way the documentation recommends) is to use the `subprocess` module. For simple commands its equivalent, but it offers more options if you want to do s... |
How to start a background process in Python? | 1,196,074 | 135 | 2009-07-28T18:56:50Z | 13,593,257 | 10 | 2012-11-27T21:19:09Z | [
"python",
"process",
"daemon"
] | I'm trying to port a shell script to the much more readable python version. The original shell script starts several processes (utilities, monitors, etc.) in the background with "&". How can I achieve the same effect in python? I'd like these processes not to die when the python scripts complete. I am sure it's related... | I found this [here](http://stackoverflow.com/questions/89228/calling-an-external-command-in-python#2251026):
On windows (win xp), the parent process will not finish until the `longtask.py` has finished its work. It is not what you want in CGI-script. The problem is not specific to Python, in PHP community the problems... |
How can I take a screenshot/image of a website using Python? | 1,197,172 | 26 | 2009-07-28T22:48:13Z | 1,197,604 | 7 | 2009-07-29T01:12:48Z | [
"python",
"screenshot",
"webpage",
"backend"
] | What I want to achieve is to get a website screenshot from any website in python.
Env: Linux | On the Mac, there's [webkit2png](http://www.paulhammond.org/webkit2png/) and on Linux+KDE, you can use [khtml2png](http://khtml2png.sourceforge.net/). I've tried the former and it works quite well, and heard of the latter being put to use.
I recently came across [QtWebKit](http://www.blogs.uni-osnabrueck.de/rotapken/2... |
How can I take a screenshot/image of a website using Python? | 1,197,172 | 26 | 2009-07-28T22:48:13Z | 12,031,316 | 29 | 2012-08-20T01:21:49Z | [
"python",
"screenshot",
"webpage",
"backend"
] | What I want to achieve is to get a website screenshot from any website in python.
Env: Linux | Here is a simple solution using webkit:
<http://webscraping.com/blog/Webpage-screenshots-with-webkit/>
```
import sys
import time
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
class Screenshot(QWebView):
def __init__(self):
self.app = QApplication(sys.argv)
QWeb... |
How can I take a screenshot/image of a website using Python? | 1,197,172 | 26 | 2009-07-28T22:48:13Z | 18,068,097 | 24 | 2013-08-05T21:30:57Z | [
"python",
"screenshot",
"webpage",
"backend"
] | What I want to achieve is to get a website screenshot from any website in python.
Env: Linux | Here is my solution by grabbing help from various sources. It takes full web page screen capture and it crops it (optional) and generates thumbnail from the cropped image also. Following are the requirements:
Requirements:
1. Install NodeJS
2. Using Node's package manager install phantomjs: `npm -g install phantomjs`... |
Matching blank lines with regular expressions | 1,197,600 | 5 | 2009-07-29T01:12:14Z | 1,197,642 | 16 | 2009-07-29T01:29:46Z | [
"python",
"regex"
] | I've got a string that I'm trying to split into chunks based on blank lines.
Given a string `s`, I thought I could do this:
```
re.split('(?m)^\s*$', s)
```
This works in some cases:
```
>>> s = 'foo\nbar\n \nbaz'
>>> re.split('(?m)^\s*$', s)
['foo\nbar\n', '\nbaz']
```
But it doesn't work if the line is completel... | Try this instead:
```
re.split('\n\s*\n', s)
```
The problem is that "$ \*^" actually only matches "spaces (if any) that are alone on a line"--not the newlines themselves. This leaves the delimiter empty when there's nothing on the line, which doesn't make sense.
This version also gets rid of the delimiting newlines... |
Actions triggered by field change in Django | 1,197,674 | 19 | 2009-07-29T01:42:07Z | 1,197,708 | 11 | 2009-07-29T01:56:36Z | [
"python",
"django",
"django-models"
] | How do I have actions occur when a field gets changed in one of my models? In this particular case, I have this model:
```
class Game(models.Model):
STATE_CHOICES = (
('S', 'Setup'),
('A', 'Active'),
('P', 'Paused'),
('F', 'Finished')
)
name = models.CharField(max_length... | Django has a nifty feature called [signals](http://docs.djangoproject.com/en/dev/topics/signals/), which are effectively triggers that are set off at specific times:
* Before/after a model's save method is called
* Before/after a model's delete method is called
* Before/after an HTTP request is made
Read the docs for... |
Actions triggered by field change in Django | 1,197,674 | 19 | 2009-07-29T01:42:07Z | 1,197,738 | 8 | 2009-07-29T02:07:19Z | [
"python",
"django",
"django-models"
] | How do I have actions occur when a field gets changed in one of my models? In this particular case, I have this model:
```
class Game(models.Model):
STATE_CHOICES = (
('S', 'Setup'),
('A', 'Active'),
('P', 'Paused'),
('F', 'Finished')
)
name = models.CharField(max_length... | Basically, you need to override the `save` method, check if the `state` field was changed, set `started` if needed and then let the model base class finish persisting to the database.
The tricky part is figuring out if the field was changed. Check out the mixins and other solutions in this question to help you out wit... |
Convert html entities to ascii in Python | 1,197,981 | 4 | 2009-07-29T04:00:35Z | 1,582,036 | 8 | 2009-10-17T11:53:40Z | [
"python",
"ascii"
] | I need to convert any html entity into its ASCII equivalent using Python. My use case is that I am cleaning up some HTML used to build emails to create plaintext emails from the HTML.
Right now, I only really know how to create unicode from these entities when I need ASCII (I think) so that the plaintext email reads c... | Here is a complete implementation that also handles unicode html entities. You might find it useful.
It returns a unicode string that is not ascii, but if you want plain ascii, you can modify the replace operations so that it replaces the entities to empty string.
```
def convert_html_entities(s):
matches = re.fi... |
Tkinter locks python when Icon loaded and tk.mainloop in a thread | 1,198,262 | 5 | 2009-07-29T05:57:59Z | 1,198,288 | 15 | 2009-07-29T06:09:46Z | [
"python",
"winapi",
"tkinter",
"green-threads"
] | Here's the test case...
```
import Tkinter as tk
import thread
from time import sleep
if __name__ == '__main__':
t = tk.Tk()
thread.start_new_thread(t.mainloop, ())
# t.iconbitmap('icon.ico')
b = tk.Button(text='test', command=exit)
b.grid(row=0)
while 1:
sleep(1)
```
This code works... | I believe you should not execute the main loop on a different thread. AFAIK, the main loop should be executed on the same thread that created the widget.
The GUI toolkits that I am familiar with (Tkinter, .NET Windows Forms) are that way: You can manipulate the GUI from one thread only.
On Linux, your code raises an ... |
How to set the encoding for the tables' char columns in django? | 1,198,486 | 10 | 2009-07-29T07:07:51Z | 1,198,675 | 15 | 2009-07-29T07:59:37Z | [
"python",
"mysql",
"django"
] | I have a project written in Django. All fields that are supposed to store some strings are supposed to be in UTF-8, however, when I run
```
manage.py syncdb
```
all respective columns are created with cp1252 character set (where did it get that -- I have no idea) and I have to manually update every column...
Is ther... | Django does not specify charset and collation in `CREATE TABLE` statements. Everything is determined by database charset. Doing `ALTER DATABASE ... CHARACTER SET utf8 COLLATE utf8_general_ci` before running `syncdb` should help.
For connection, Django issues `SET NAMES utf8` automatically, so you don't need to worry a... |
Split a list into parts based on a set of indexes in Python | 1,198,512 | 33 | 2009-07-29T07:16:24Z | 1,198,876 | 36 | 2009-07-29T08:55:27Z | [
"python",
"list"
] | What is the best way to split a list into parts based on an arbitrary number of indexes? E.g. given the code below
```
indexes = [5, 12, 17]
list = range(20)
```
return something like this
```
part1 = list[:5]
part2 = list[5:12]
part3 = list[12:17]
part4 = list[17:]
```
If there are no indexes it should return the ... | This is the simplest and most pythonic solution I can think of:
```
def partition(alist, indices):
return [alist[i:j] for i, j in zip([0]+indices, indices+[None])]
```
if the inputs are very large, then the iterators solution should be more convenient:
```
from itertools import izip, chain
def partition(alist, i... |
Double Iteration in List Comprehension | 1,198,777 | 75 | 2009-07-29T08:30:49Z | 1,198,788 | 44 | 2009-07-29T08:34:28Z | [
"python",
"list-comprehension"
] | In Python you can have multiple iterators in a list comprehension, like
```
[(x,y) for x in a for y in b]
```
for some suitable sequences a and b. I'm aware of the nested loop semantics of Python's list comprehensions.
My question is: Can one iterator in the comprehension refer to the other? In other words: Could I ... | Gee, I guess I found the anwser: I was not taking care enough about which loop is inner and which is outer. The list comprehension should be like:
```
[x for b in a for x in b]
```
to get the desired result, and yes, one current value can be the iterator for the next loop :-). Sorry for the noise. |
Double Iteration in List Comprehension | 1,198,777 | 75 | 2009-07-29T08:30:49Z | 1,198,794 | 74 | 2009-07-29T08:36:21Z | [
"python",
"list-comprehension"
] | In Python you can have multiple iterators in a list comprehension, like
```
[(x,y) for x in a for y in b]
```
for some suitable sequences a and b. I'm aware of the nested loop semantics of Python's list comprehensions.
My question is: Can one iterator in the comprehension refer to the other? In other words: Could I ... | To answer your question with your own suggestion:
```
>>> [x for b in a for x in b] # Works fine
```
While you asked for list comprehension answers, let me also point out the excellent itertools.chain():
```
>>> from itertools import chain
>>> list(chain.from_iterable(a))
>>> list(chain(*a)) # If you're using python... |
Double Iteration in List Comprehension | 1,198,777 | 75 | 2009-07-29T08:30:49Z | 26,480,506 | 10 | 2014-10-21T06:47:04Z | [
"python",
"list-comprehension"
] | In Python you can have multiple iterators in a list comprehension, like
```
[(x,y) for x in a for y in b]
```
for some suitable sequences a and b. I'm aware of the nested loop semantics of Python's list comprehensions.
My question is: Can one iterator in the comprehension refer to the other? In other words: Could I ... | ThomasH has already added a good answer, but I want to show what happens:
```
>>> a = [[1, 2], [3, 4]]
>>> [x for x in b for b in a]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
>>> [x for b in a for x in b]
[1, 2, 3, 4]
>>> [x for x in b for b in a]
[3, ... |
Python: Mapping from intervals to values | 1,199,053 | 9 | 2009-07-29T09:33:42Z | 1,199,113 | 29 | 2009-07-29T09:47:54Z | [
"python",
"range",
"intervals"
] | I'm refactoring a function that, given a series of endpoints that implicitly define intervals, checks if a number is included in the interval, and then return a corresponding (not related in any computable way).
The code that is now handling the work is:
```
if p <= 100:
return 0
elif p > 100 and p <= 300:
ret... | ```
import bisect
bisect.bisect_left([100,300,500,800,1000], p)
``` |
combine javascript files at deployment in python | 1,199,470 | 13 | 2009-07-29T11:06:42Z | 1,199,481 | 21 | 2009-07-29T11:09:46Z | [
"javascript",
"python",
"deployment",
"buildout",
"jscompress"
] | I'm trying to reduce the number of scripts included in our website and we use buildout to handle deployments. Has anybody successfully implemented a method of combining and compressing scripts with buildout? | Here's a Python script I made that I use with all my heavy JavaScript projects. I'm using YUICompressor, but you can change the code to use another compressor.
```
import os, os.path, shutil
YUI_COMPRESSOR = 'yuicompressor-2.4.2.jar'
def compress(in_files, out_file, in_type='js', verbose=False,
temp_fil... |
Cython and numpy speed | 1,199,972 | 13 | 2009-07-29T12:39:52Z | 1,228,914 | 35 | 2009-08-04T17:40:00Z | [
"python",
"numpy",
"cython"
] | I'm using cython for a correlation calculation in my python program. I have two audio data sets and I need to know the time difference between them. The second set is cut based on onset times and then slid across the first set. There are two for-loops: one slides the set and the inner loop calculates correlation at tha... | **Edit:**
There's now [`scipy.signal.fftconvolve`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.fftconvolve.html) which would be the preferred approach to doing the FFT based convolution approach that I describe below. I'll leave the original answer to explain the speed issue, but in practice use ... |
python interpolation | 1,200,644 | 17 | 2009-07-29T14:25:01Z | 1,200,722 | 25 | 2009-07-29T14:35:04Z | [
"python",
"numpy"
] | I have a set of data's as,
```
Table-1
X1 | Y1
------+--------
0.1 | 0.52147
0.02 | 0.8879
0.08 | 0.901
0.11 | 1.55
0.15 | 1.82
0.152 | 1.95
Table-2
X2 | Y2
-----+------
0.2 | 0.11
0.21 | 0.112
0.34 | 0.120
0.33 | 1.121
```
I have to interpolat... | [numpy.interp](http://docs.scipy.org/doc/numpy/reference/generated/numpy.interp.html) seems to be the function you want: pass your X1 as the first argument x, your X2 as the second argument xp, your Y2 as the third argument fp, and you'll get the Y values corresponding to the X1 coordinates (looks like you want to comp... |
Importing files in Python from __init__.py | 1,201,115 | 11 | 2009-07-29T15:29:26Z | 1,201,151 | 11 | 2009-07-29T15:33:20Z | [
"python",
"import",
"module"
] | Suppose I have the following structure:
```
app/
__init__.py
foo/
a.py
b.py
c.py
__init__.py
```
a.py, b.py and c.py share some common imports (logging, os, re, etc). Is it possible to import these three or four common modules from the `__init__.py` file so I don't have to import them in every one... | No, they have to be put in each module's namespace, so you have to import them somehow (unless you pass `logging` around as a function argument, which would be a weird way to do things, to say the least).
But the modules are only imported once anyway (and then put into the `a`, `b`, and `c` namespaces), so don't worry... |
Importing files in Python from __init__.py | 1,201,115 | 11 | 2009-07-29T15:29:26Z | 1,201,177 | 13 | 2009-07-29T15:38:32Z | [
"python",
"import",
"module"
] | Suppose I have the following structure:
```
app/
__init__.py
foo/
a.py
b.py
c.py
__init__.py
```
a.py, b.py and c.py share some common imports (logging, os, re, etc). Is it possible to import these three or four common modules from the `__init__.py` file so I don't have to import them in every one... | You can do this using a common file such as `include.py`, but it goes against recommended practices because it involves a wildcard import. Consider the following files:
```
app/
__init__.py
foo/
a.py
b.py
c.py
include.py <- put the includes here.
__init__.py
```
Now, in `a.py`, etc., do:
```
... |
Cannot insert data into an sqlite3 database using Python | 1,201,522 | 4 | 2009-07-29T16:36:23Z | 1,201,594 | 19 | 2009-07-29T16:46:56Z | [
"python",
"sqlite",
"sqlite3"
] | I can successfully use Python to create a database and run the execute() method to create 2 new tables and specify the column names. However, I cannot insert data into the database. This is the code that I am trying to use to insert the data into the database:
```
#! /usr/bin/env python
import sqlite3
companies = ('... | Try to add
```
db.commit()
```
after the inserting. |
Adding a field to a structured numpy array | 1,201,817 | 18 | 2009-07-29T17:24:12Z | 1,208,039 | 16 | 2009-07-30T17:18:58Z | [
"python",
"numpy"
] | What is the cleanest way to add a field to a structured numpy array? Can it be done destructively, or is it necessary to create a new array and copy over the existing fields? Are the contents of each field stored contiguously in memory so that such copying can be done efficiently? | If you're using numpy 1.3, there's also numpy.lib.recfunctions.append\_fields().
For many installations, you'll need to `import numpy.lib.recfunctions` to access this. `import numpy` will not allow one to see the `numpy.lib.recfunctions` |
get request data in Django form | 1,202,839 | 34 | 2009-07-29T20:29:51Z | 1,204,136 | 48 | 2009-07-30T02:24:04Z | [
"python",
"django"
] | Is it possible to get request.user data in a form class? I want to clean an email address to make sure that it's unique, but if it's the current users email address then it should pass.
This is what I currently have which works great for creating new users, but if I want to edit a user I run into the problem of their ... | As ars and Diarmuid have pointed out, you can pass `request.user` into your form, and use it in validating the email. Diarmuid's code, however, is wrong. The code should actually read:
```
from django import forms
class UserForm(forms.Form):
email_address = forms.EmailField(widget = forms.TextInput(attrs = {'clas... |
get request data in Django form | 1,202,839 | 34 | 2009-07-29T20:29:51Z | 14,656,536 | 17 | 2013-02-01T23:01:56Z | [
"python",
"django"
] | Is it possible to get request.user data in a form class? I want to clean an email address to make sure that it's unique, but if it's the current users email address then it should pass.
This is what I currently have which works great for creating new users, but if I want to edit a user I run into the problem of their ... | Here's the way to get the user in your form when using generic views:
In the view, pass the `request.user` to the form using `get_form_kwargs`:
```
class SampleView( View ):
def get_form_kwargs( self ):
kwargs = super( SampleView, self ).get_form_kwargs()
kwargs['user'] = self.request.user
... |
Python - tempfile.TemporaryFile cannot be read; why? | 1,202,848 | 13 | 2009-07-29T20:31:34Z | 1,202,917 | 7 | 2009-07-29T20:43:00Z | [
"python",
"file",
"io",
"temporary-files"
] | The [official documentation for TemporaryFile](http://docs.python.org/library/tempfile.html#tempfile.TemporaryFile) reads:
> The mode parameter defaults to 'w+b'
> so that the file created **can be read
> and written without being closed**.
Yet, the below code does not work as expected:
```
import tempfile
def play... | `read()` does not return anything because you are at the end of the file. You need to call [`seek()`](http://docs.python.org/library/stdtypes.html#file.seek) first before `read()` will return anything. For example, put this line in front of the first `read()`:
```
f.seek(-10, 1)
```
Of course, before writing again, b... |
Python - tempfile.TemporaryFile cannot be read; why? | 1,202,848 | 13 | 2009-07-29T20:31:34Z | 1,202,998 | 25 | 2009-07-29T20:58:55Z | [
"python",
"file",
"io",
"temporary-files"
] | The [official documentation for TemporaryFile](http://docs.python.org/library/tempfile.html#tempfile.TemporaryFile) reads:
> The mode parameter defaults to 'w+b'
> so that the file created **can be read
> and written without being closed**.
Yet, the below code does not work as expected:
```
import tempfile
def play... | You must put
```
f.seek(0)
```
before trying to read the file (this will send you to the beginning of the file), and
```
f.seek(0, 2)
```
to return to the end so you can assure you won't overwrite it. |
Python CSV DictReader/Writer issues | 1,202,855 | 2 | 2009-07-29T20:32:42Z | 1,202,875 | 11 | 2009-07-29T20:35:26Z | [
"python",
"csv"
] | I'm trying to extract a bunch of lines from a CSV file and write them into another, but I'm having some problems.
```
import csv
f = open("my_csv_file.csv", "r")
r = csv.DictReader(f, delimiter=',')
fieldnames = r.fieldnames
target = open("united.csv", 'w')
w = csv.DictWriter(united, fieldnames=fieldnames)
while Tr... | I don't know either, but since all you're doing is copying lines from one file to another why are you bothering with the `csv` stuff at all? Why not something like:
```
f = open("my_csv_file.csv", "r")
target = open("united.csv", 'w')
f.readline()
f.readline()
for line in f:
target.write(line)
``` |
Python CSV DictReader/Writer issues | 1,202,855 | 2 | 2009-07-29T20:32:42Z | 3,595,110 | 11 | 2010-08-29T14:27:34Z | [
"python",
"csv"
] | I'm trying to extract a bunch of lines from a CSV file and write them into another, but I'm having some problems.
```
import csv
f = open("my_csv_file.csv", "r")
r = csv.DictReader(f, delimiter=',')
fieldnames = r.fieldnames
target = open("united.csv", 'w')
w = csv.DictWriter(united, fieldnames=fieldnames)
while Tr... | To clear up the confusion about the error: you get it because `r.fieldnames` is only set once you read from the input file for the first time using `r`. Hence the way you wrote it, `fieldnames` will always be initialized to `None`.
You may initialize `w = csv.DictWriter(united, fieldnames=fieldnames)` with `r.fieldnam... |
recursive lambda-expressions possible? | 1,203,292 | 17 | 2009-07-29T21:54:24Z | 1,203,297 | 18 | 2009-07-29T21:55:53Z | [
"python",
"recursion",
"lambda"
] | I'm trying to write a lambda-expression that calls itself, but i can't seem to find any syntax for that, or even if it's possible.
Essentially what I wanted to transfer the following function into the following lambda expression: (I realize it's a silly application, it just adds, but I'm exploring what I can do with l... | Maybe you need a Y combinator?
**Edit** - make that a Z combinator (I hadn't realized that Y combinators are more for call-by-name)
Using the definition of the Z combinator from [Wikipedia](http://en.wikipedia.org/wiki/Fixed%5Fpoint%5Fcombinator)
```
>>> Z = lambda f: (lambda x: f(lambda *args: x(x)(*args)))(lambda ... |
recursive lambda-expressions possible? | 1,203,292 | 17 | 2009-07-29T21:54:24Z | 1,203,337 | 7 | 2009-07-29T22:06:29Z | [
"python",
"recursion",
"lambda"
] | I'm trying to write a lambda-expression that calls itself, but i can't seem to find any syntax for that, or even if it's possible.
Essentially what I wanted to transfer the following function into the following lambda expression: (I realize it's a silly application, it just adds, but I'm exploring what I can do with l... | First of all recursive lambda expressions are completely unnecessary. As you yourself point out, for the lambda expression to call itself, it needs to have a name. But lambda expressions is nothing else than anonymous functions. So if you give the lambda expression a name, it's no longer a lambda expression, but a func... |
recursive lambda-expressions possible? | 1,203,292 | 17 | 2009-07-29T21:54:24Z | 1,203,499 | 7 | 2009-07-29T22:41:29Z | [
"python",
"recursion",
"lambda"
] | I'm trying to write a lambda-expression that calls itself, but i can't seem to find any syntax for that, or even if it's possible.
Essentially what I wanted to transfer the following function into the following lambda expression: (I realize it's a silly application, it just adds, but I'm exploring what I can do with l... | Perhaps you should try the [Z combinator](http://en.wikipedia.org/wiki/Fixed_point_combinator), where this example is from:
```
>>> Z = lambda f: (lambda x: f(lambda *args: x(x)(*args)))(lambda x: f(lambda *args: x(x)(*args)))
>>> fact = lambda f: lambda x: 1 if x == 0 else x * f(x-1)
>>> Z(fact)(5)
120
``` |
How to write an application for the system tray in Linux | 1,203,451 | 20 | 2009-07-29T22:31:39Z | 1,203,476 | 11 | 2009-07-29T22:37:45Z | [
"c++",
"python",
"c",
"linux",
"system-tray"
] | How do I write my application so it'll live in the system tray on Linux? In fact, just like [CheckGmail](http://checkgmail.sourceforge.net/).
As with CheckGmail, I'd also like some sort of popup box to appear when I hover the tray icon.
Is there an API, class or something for doing this? All I'm able to find seems to... | This might help:
<http://standards.freedesktop.org/systemtray-spec/systemtray-spec-latest.html> |
How to write an application for the system tray in Linux | 1,203,451 | 20 | 2009-07-29T22:31:39Z | 1,203,482 | 8 | 2009-07-29T22:38:30Z | [
"c++",
"python",
"c",
"linux",
"system-tray"
] | How do I write my application so it'll live in the system tray on Linux? In fact, just like [CheckGmail](http://checkgmail.sourceforge.net/).
As with CheckGmail, I'd also like some sort of popup box to appear when I hover the tray icon.
Is there an API, class or something for doing this? All I'm able to find seems to... | # python-eggtrayicon
here's the example that comes with the debian package `python-eggtrayicon` in debian/testing...
```
#!/usr/bin/python
import pygtk
pygtk.require("2.0")
import gtk
import egg.trayicon
t = egg.trayicon.TrayIcon("MyFirstTrayIcon")
t.add(gtk.Label("Hello"))
t.show_all()
gtk.main()
```
It just shows ... |
How to write an application for the system tray in Linux | 1,203,451 | 20 | 2009-07-29T22:31:39Z | 1,203,504 | 24 | 2009-07-29T22:42:12Z | [
"c++",
"python",
"c",
"linux",
"system-tray"
] | How do I write my application so it'll live in the system tray on Linux? In fact, just like [CheckGmail](http://checkgmail.sourceforge.net/).
As with CheckGmail, I'd also like some sort of popup box to appear when I hover the tray icon.
Is there an API, class or something for doing this? All I'm able to find seems to... | The Qt framework contains a [QSystemTrayIcon](http://doc.qt.io/qt-5/qsystemtrayicon.html) class. This means that you can write an application in C++ or Python (or any other [language with Qt bindings](http://www.qtsoftware.com/products/programming-language-support), including C#, Ada, Pascal, Perl, PHP and Ruby) and ru... |
Django equivalent of New Relic RPM for Rails? | 1,203,494 | 7 | 2009-07-29T22:41:10Z | 7,374,925 | 7 | 2011-09-10T21:49:58Z | [
"python",
"django"
] | Does Django have anything equivalent to the New Relic RPM performance monitoring app for Rails (<http://www.newrelic.com/>)?
Looking to do an app in Django, but would really like to be able to use something like New Relic for monitoring performance. | YES! We (New Relic) just announced our Python agent at DjangoCon this week. Sign up at newrelic.com and enjoy! |
Getting total/free RAM from within Python | 1,204,378 | 9 | 2009-07-30T03:52:42Z | 1,204,410 | 12 | 2009-07-30T04:06:21Z | [
"python",
"wxpython"
] | From within a Python application, how can I get the total amount of RAM of the system and how much of it is currently free, in a cross-platform way?
Ideally, the amount of free RAM should consider only physical memory that can actually be allocated to the Python process. | Have you tried [SIGAR - System Information Gatherer And Reporter](http://support.hyperic.com/display/SIGAR/Home)?
After install
```
import os, sigar
sg = sigar.open()
mem = sg.mem()
sg.close()
print mem.total() / 1024, mem.free() / 1024
```
Hope this helps |
Filter by property | 1,205,375 | 44 | 2009-07-30T09:06:23Z | 1,205,389 | 41 | 2009-07-30T09:09:45Z | [
"python",
"django"
] | Is it possible to filter by property?
i have a method in my model:
```
@property
def myproperty(self):
[..]
```
and now i want to filter by this property like:
```
MyModel.objects.filter(myproperty=[..])
```
is this somehow possible? | Nope. Django filters operate at the database level, generating SQL. To filter based on Python properties, you have to load the object into Python to evaluate the property--and at that point, you've already done all the work to load it. |
Filter by property | 1,205,375 | 44 | 2009-07-30T09:06:23Z | 1,205,416 | 19 | 2009-07-30T09:15:41Z | [
"python",
"django"
] | Is it possible to filter by property?
i have a method in my model:
```
@property
def myproperty(self):
[..]
```
and now i want to filter by this property like:
```
MyModel.objects.filter(myproperty=[..])
```
is this somehow possible? | I might be misunderstanding your original question, but there is a [filter](http://docs.python.org/library/functions.html#filter) builtin in python.
```
filtered = filter(myproperty, MyModel.objects)
```
But it's better to use a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensi... |
Listing serial (COM) ports on Windows? | 1,205,383 | 23 | 2009-07-30T09:08:22Z | 25,539,425 | 20 | 2014-08-28T01:37:32Z | [
"python",
"c",
"windows",
"winapi",
"serial-port"
] | I'm looking for a robust way to list the available serial (COM) ports on a Windows machine. There's [this post about using WMI](http://stackoverflow.com/questions/1081871/how-to-find-available-com-ports), but I would like something less .NET specific - I want to get the list of ports in a Python or a C++ program, witho... | Using pySerial with Python:
```
import serial.tools.list_ports
ports = list(serial.tools.list_ports.comports())
for p in ports:
print p
``` |
Django - Repeating a form field n times in one form | 1,205,626 | 4 | 2009-07-30T10:00:57Z | 1,205,767 | 8 | 2009-07-30T10:34:46Z | [
"python",
"django",
"django-forms"
] | I have a Django form with several fields in it one of which needs to be repeated n times (where n is not known at design time) how would I go about coding this (if it is possible at all)?
e.g. instead of :-
```
Class PaymentsForm(forms.form):
invoice = forms.CharField(widget=ValueHiddenInput())
total = forms.... | You can create the repeated fields in the `__init__` method of your form:
```
class PaymentsForm(forms.Form):
invoice = forms.CharField(widget=forms.HiddenInput())
total = forms.CharField(widget=forms.HiddenInput())
def __init__(self, *args, **kwargs):
super(PaymentsForm, self).__init__(*args, **k... |
How do I get monotonic time durations in python? | 1,205,722 | 38 | 2009-07-30T10:23:55Z | 1,205,762 | 59 | 2009-07-30T10:33:40Z | [
"python",
"linux",
"benchmarking",
"clock"
] | I want to log how long something takes in real walltime. Currently I'm doing this:
```
startTime = time.time()
someSQLOrSomething()
print "That took %.3f seconds" % (time.time() - startTime)
```
But that will fail (produce incorrect results) if the time is adjusted while the SQL query (or whatever it is) is running.
... | That function is simple enough that you can use ctypes to access it:
```
#!/usr/bin/env python
__all__ = ["monotonic_time"]
import ctypes, os
CLOCK_MONOTONIC_RAW = 4 # see <linux/time.h>
class timespec(ctypes.Structure):
_fields_ = [
('tv_sec', ctypes.c_long),
('tv_nsec', ctypes.c_long)
]
... |
How do I get monotonic time durations in python? | 1,205,722 | 38 | 2009-07-30T10:23:55Z | 4,486,117 | 8 | 2010-12-20T01:03:00Z | [
"python",
"linux",
"benchmarking",
"clock"
] | I want to log how long something takes in real walltime. Currently I'm doing this:
```
startTime = time.time()
someSQLOrSomething()
print "That took %.3f seconds" % (time.time() - startTime)
```
But that will fail (produce incorrect results) if the time is adjusted while the SQL query (or whatever it is) is running.
... | As pointed out in [this question](http://stackoverflow.com/questions/3657289/linux-clock-gettimeclock-monotonic-strange-non-monotonic-behavior), avoiding NTP readjustments on Linux requires CLOCK\_MONOTONIC\_RAW. That's defined as 4 on Linux (since 2.6.28).
Portably getting the correct constant #defined in a C header ... |
How do I get monotonic time durations in python? | 1,205,722 | 38 | 2009-07-30T10:23:55Z | 14,416,514 | 19 | 2013-01-19T16:49:11Z | [
"python",
"linux",
"benchmarking",
"clock"
] | I want to log how long something takes in real walltime. Currently I'm doing this:
```
startTime = time.time()
someSQLOrSomething()
print "That took %.3f seconds" % (time.time() - startTime)
```
But that will fail (produce incorrect results) if the time is adjusted while the SQL query (or whatever it is) is running.
... | Now, in Python 3.3 you would use [time.monotonic](http://www.python.org/dev/peps/pep-0418/#time-monotonic). |
How can I get non-blocking socket connect()'s? | 1,205,863 | 9 | 2009-07-30T10:58:16Z | 1,205,978 | 8 | 2009-07-30T11:21:52Z | [
"python",
"sockets",
"asynchronous",
"nonblocking"
] | I have a quite simple problem here. I need to communicate with a lot of hosts simultaneously, but I do not really need any synchronization because each request is pretty self sufficient.
Because of that, I chose to work with asynchronous sockets, rather than spamming threads.
Now I do have a little problem:
The async... | Use the [`select`](http://docs.python.org/library/select.html) module. This allows you to wait for I/O completion on multiple non-blocking sockets. Here's [some more information](http://www.amk.ca/python/howto/sockets/sockets.html#SECTION000600000000000000000) on select. From the linked-to page:
> In C, coding `select... |
Django ORM for desktop application | 1,206,793 | 11 | 2009-07-30T13:58:56Z | 1,206,820 | 11 | 2009-07-30T14:05:39Z | [
"python",
"django",
"orm"
] | Recently, I have become increasingly familiar with Django. I have a new project that I am working on that will be using Python for a desktop application. Is it possible to use the Django ORM in a desktop application? Or should I just go with something like [SQLAlchemy](http://www.sqlalchemy.org/)? | The Django people are sensible people with a philosophy of decoupling things. So yes, in theory you should be perfectly able to use Django's ORM in a standalone application.
Here's one guide I found: [Django ORM as a standalone component](http://jystewart.net/process/2008/02/using-the-django-orm-as-a-standalone-compon... |
Is there a Python shortcut for variable checking and assignment? | 1,207,333 | 6 | 2009-07-30T15:23:27Z | 1,207,353 | 7 | 2009-07-30T15:27:20Z | [
"python",
"django",
"idioms"
] | I'm finding myself typing the following a lot (developing for Django, if that's relevant):
```
if testVariable then:
myVariable = testVariable
else:
# something else
```
Alternatively, and more commonly (i.e. building up a parameters list)
```
if 'query' in request.POST.keys() then:
myVariable = request.POS... | The first instance is stated oddly... Why set a boolean to another boolean?
What you may mean is to set myVariable to testVariable when testVariable is not a zero length string or not None or not something that happens to evaluate to False.
If so, I prefer the more explicit formulations
```
myVariable = testVariable... |
Is there a Python shortcut for variable checking and assignment? | 1,207,333 | 6 | 2009-07-30T15:23:27Z | 1,207,359 | 24 | 2009-07-30T15:28:59Z | [
"python",
"django",
"idioms"
] | I'm finding myself typing the following a lot (developing for Django, if that's relevant):
```
if testVariable then:
myVariable = testVariable
else:
# something else
```
Alternatively, and more commonly (i.e. building up a parameters list)
```
if 'query' in request.POST.keys() then:
myVariable = request.POS... | Assuming you want to leave myVariable untouched to its previous value in the "not exist" case,
```
myVariable = testVariable or myVariable
```
deals with the first case, and
```
myVariable = request.POST.get('query', myVariable)
```
deals with the second one. Neither has much to do with "exist", though (which is ha... |
Remove items from a list while iterating in Python | 1,207,406 | 447 | 2009-07-30T15:36:42Z | 1,207,427 | 117 | 2009-07-30T15:38:32Z | [
"python",
"iteration"
] | I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria.
```
for tup in somelist:
if determine(tup):
code_to_remove_tup
```
What should I use in place of `code_to_remove_tup`? I can't figure out how to remove the item in this fashion. | You need to take a copy of the list and iterate over it first, or the iteration will fail with what may be unexpected results.
For example (depends on what type of list):
```
for tup in somelist[:]:
etc....
```
An example:
```
>>> somelist = range(10)
>>> for x in somelist:
... somelist.remove(x)
>>> someli... |
Remove items from a list while iterating in Python | 1,207,406 | 447 | 2009-07-30T15:36:42Z | 1,207,460 | 39 | 2009-07-30T15:41:30Z | [
"python",
"iteration"
] | I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria.
```
for tup in somelist:
if determine(tup):
code_to_remove_tup
```
What should I use in place of `code_to_remove_tup`? I can't figure out how to remove the item in this fashion. | Your best approach for such an example would be a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions)
```
somelist = [tup for tup in somelist if determine(tup)]
```
In cases where you're doing something more complex than calling a `determine` function, I prefer constructing a... |
Remove items from a list while iterating in Python | 1,207,406 | 447 | 2009-07-30T15:36:42Z | 1,207,461 | 359 | 2009-07-30T15:41:33Z | [
"python",
"iteration"
] | I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria.
```
for tup in somelist:
if determine(tup):
code_to_remove_tup
```
What should I use in place of `code_to_remove_tup`? I can't figure out how to remove the item in this fashion. | You can use a list comprehension to create a new list containing only the elements you don't want to remove:
```
somelist = [x for x in somelist if not determine(x)]
```
Or, by assigning to the slice `somelist[:]`, you can mutate the existing list to contain only the items you want:
```
somelist[:] = [x for x in som... |
Remove items from a list while iterating in Python | 1,207,406 | 447 | 2009-07-30T15:36:42Z | 1,207,485 | 58 | 2009-07-30T15:44:59Z | [
"python",
"iteration"
] | I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria.
```
for tup in somelist:
if determine(tup):
code_to_remove_tup
```
What should I use in place of `code_to_remove_tup`? I can't figure out how to remove the item in this fashion. | ```
for i in xrange(len(somelist) - 1, -1, -1):
if some_condition(somelist, i):
del somelist[i]
```
You need to go backwards otherwise it's a bit like sawing off the tree-branch that you are sitting on :-) |
Remove items from a list while iterating in Python | 1,207,406 | 447 | 2009-07-30T15:36:42Z | 1,207,500 | 29 | 2009-07-30T15:46:46Z | [
"python",
"iteration"
] | I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria.
```
for tup in somelist:
if determine(tup):
code_to_remove_tup
```
What should I use in place of `code_to_remove_tup`? I can't figure out how to remove the item in this fashion. | For those that like functional programming:
```
somelist[:] = filter(lambda tup: not determine(tup), somelist)
```
or
```
from itertools import ifilterfalse
somelist[:] = list(ifilterfalse(determine, somelist))
``` |
Remove items from a list while iterating in Python | 1,207,406 | 447 | 2009-07-30T15:36:42Z | 1,208,792 | 376 | 2009-07-30T19:28:27Z | [
"python",
"iteration"
] | I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria.
```
for tup in somelist:
if determine(tup):
code_to_remove_tup
```
What should I use in place of `code_to_remove_tup`? I can't figure out how to remove the item in this fashion. | The answers suggesting list comprehensions are ALMOST correct -- except that they build a completely new list and then give it the same name the old list as, they do NOT modify the old list in place. That's different from what you'd be doing by selective removal, as in @Lennart's suggestion -- it's faster, but if your ... |
Remove items from a list while iterating in Python | 1,207,406 | 447 | 2009-07-30T15:36:42Z | 34,238,688 | 7 | 2015-12-12T10:18:22Z | [
"python",
"iteration"
] | I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria.
```
for tup in somelist:
if determine(tup):
code_to_remove_tup
```
What should I use in place of `code_to_remove_tup`? I can't figure out how to remove the item in this fashion. | **The [official Python 2 tutorial 4.2. "for Statements"](https://docs.python.org/2/tutorial/controlflow.html#for-statements) says**:
> If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over ... |
Convert a Unicode string to a string in Python (containing extra symbols) | 1,207,457 | 258 | 2009-07-30T15:41:11Z | 1,207,479 | 369 | 2009-07-30T15:44:32Z | [
"python",
"string",
"unicode",
"type-conversion"
] | How do you convert a Unicode string (containing extra characters like £ $, etc.) into a Python string? | ```
title = u"Klüft skräms inför pÃ¥ fédéral électoral groÃe"
import unicodedata
unicodedata.normalize('NFKD', title).encode('ascii','ignore')
'Kluft skrams infor pa federal electoral groe'
``` |
Convert a Unicode string to a string in Python (containing extra symbols) | 1,207,457 | 258 | 2009-07-30T15:41:11Z | 1,207,496 | 42 | 2009-07-30T15:46:26Z | [
"python",
"string",
"unicode",
"type-conversion"
] | How do you convert a Unicode string (containing extra characters like £ $, etc.) into a Python string? | Here is an example:
```
>>> u = u'â¬â¬â¬'
>>> s = u.encode('utf8')
>>> s
'\xe2\x82\xac\xe2\x82\xac\xe2\x82\xac'
``` |
Convert a Unicode string to a string in Python (containing extra symbols) | 1,207,457 | 258 | 2009-07-30T15:41:11Z | 1,207,836 | 75 | 2009-07-30T16:44:54Z | [
"python",
"string",
"unicode",
"type-conversion"
] | How do you convert a Unicode string (containing extra characters like £ $, etc.) into a Python string? | If you have a Unicode string, and you want to write this to a file, or other serialised form, you must first *encode* it into a particular representation that can be stored. There are several common Unicode encodings, such as UTF-16 (uses two bytes for most Unicode characters) or UTF-8 (1-4 bytes / codepoint depending ... |
Convert a Unicode string to a string in Python (containing extra symbols) | 1,207,457 | 258 | 2009-07-30T15:41:11Z | 1,211,102 | 178 | 2009-07-31T07:13:09Z | [
"python",
"string",
"unicode",
"type-conversion"
] | How do you convert a Unicode string (containing extra characters like £ $, etc.) into a Python string? | You can use encode to ASCII if you don't need to translate the non-ASCII characters:
```
>>> a=u"aaaà çççñññ"
>>> type(a)
<type 'unicode'>
>>> a.encode('ascii','ignore')
'aaa'
>>> a.encode('ascii','replace')
'aaa???????'
>>>
``` |
Convert a Unicode string to a string in Python (containing extra symbols) | 1,207,457 | 258 | 2009-07-30T15:41:11Z | 13,073,070 | 60 | 2012-10-25T16:27:20Z | [
"python",
"string",
"unicode",
"type-conversion"
] | How do you convert a Unicode string (containing extra characters like £ $, etc.) into a Python string? | ```
>>> text=u'abcd'
>>> str(text)
'abcd'
```
If a simple conversion. |
Check absolute paths in Python | 1,207,954 | 9 | 2009-07-30T17:04:34Z | 1,207,987 | 23 | 2009-07-30T17:10:04Z | [
"python",
"path"
] | How can I check whether two file paths point to the same file in Python? | ```
$ touch foo
$ ln -s foo bar
$ python
Python 2.5.1 (r251:54863, Feb 6 2009, 19:02:12)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> help(os.path.samefile)
Help on function samefile in module posixpath:
samefile(f1, f2)
Te... |
Where's my JSON data in my incoming Django request? | 1,208,067 | 94 | 2009-07-30T17:22:53Z | 3,020,756 | 147 | 2010-06-11T06:56:22Z | [
"python",
"ajax",
"json",
"django",
"content-type"
] | I'm trying to process incoming JSON/Ajax requests with Django/Python.
[`request.is_ajax()`](https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpRequest.is_ajax) is `True` on the request, but I have no idea where the payload is with the JSON data.
`request.POST.dir` contains this:
```
['__c... | If you are posting JSON to Django, I think you want `request.body` (`request.raw_post_data` on Django < 1.4). This will give you the raw JSON data sent via the post. From there you can process it further.
Here is an example using JavaScript, [jQuery](http://en.wikipedia.org/wiki/JQuery), jquery-json and Django.
JavaS... |
Where's my JSON data in my incoming Django request? | 1,208,067 | 94 | 2009-07-30T17:22:53Z | 3,244,765 | 35 | 2010-07-14T09:13:29Z | [
"python",
"ajax",
"json",
"django",
"content-type"
] | I'm trying to process incoming JSON/Ajax requests with Django/Python.
[`request.is_ajax()`](https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpRequest.is_ajax) is `True` on the request, but I have no idea where the payload is with the JSON data.
`request.POST.dir` contains this:
```
['__c... | I had the same problem. I had been posting a complex JSON response, and I couldn't read my data using the request.POST dictionary.
My JSON POST data was:
```
//JavaScript code:
//Requires json2.js and jQuery.
var response = {data:[{"a":1, "b":2},{"a":2, "b":2}]}
json_response = JSON.stringify(response); // proper ser... |
Where's my JSON data in my incoming Django request? | 1,208,067 | 94 | 2009-07-30T17:22:53Z | 10,990,800 | 22 | 2012-06-12T05:06:01Z | [
"python",
"ajax",
"json",
"django",
"content-type"
] | I'm trying to process incoming JSON/Ajax requests with Django/Python.
[`request.is_ajax()`](https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpRequest.is_ajax) is `True` on the request, but I have no idea where the payload is with the JSON data.
`request.POST.dir` contains this:
```
['__c... | `request.raw_response` is now deprecated. Use `request.body` instead to process non-conventional form data such as XML payloads, binary images, etc.
[Django documentation on the issue](https://docs.djangoproject.com/en/dev/ref/request-response/). |
Where's my JSON data in my incoming Django request? | 1,208,067 | 94 | 2009-07-30T17:22:53Z | 23,008,197 | 21 | 2014-04-11T09:07:42Z | [
"python",
"ajax",
"json",
"django",
"content-type"
] | I'm trying to process incoming JSON/Ajax requests with Django/Python.
[`request.is_ajax()`](https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpRequest.is_ajax) is `True` on the request, but I have no idea where the payload is with the JSON data.
`request.POST.dir` contains this:
```
['__c... | **Method 1**
Client : Send as `JSON`
```
$.ajax({
url: 'example.com/ajax/',
type: 'POST',
contentType: 'application/json; charset=utf-8',
processData: false,
data: JSON.stringify({'name':'John', 'age': 42}),
...
});
//Sent as a JSON object {'name':'John', 'age': 42}
```
Server :
```
data = ... |
Using numpy to build an array of all combinations of two arrays | 1,208,118 | 73 | 2009-07-30T17:32:27Z | 1,208,739 | 26 | 2009-07-30T19:19:11Z | [
"python",
"arrays",
"multidimensional-array",
"numpy"
] | I'm trying to run over the parameters space of a 6 parameter function to study it's numerical behavior before trying to do anything complex with it so I'm searching for a efficient way to do this.
My function takes float values given a 6-dim numpy array as input. What I tried to do initially was this:
First I created... | [itertools.combinations](http://docs.python.org/library/itertools.html#itertools.combinations) is in general the fastest way to get combinations from a Python container (if you do in fact want combinations, i.e., arrangements WITHOUT repetitions and independent of order; that's not what your code appears to be doing, b... |
Using numpy to build an array of all combinations of two arrays | 1,208,118 | 73 | 2009-07-30T17:32:27Z | 1,235,363 | 114 | 2009-08-05T19:48:42Z | [
"python",
"arrays",
"multidimensional-array",
"numpy"
] | I'm trying to run over the parameters space of a 6 parameter function to study it's numerical behavior before trying to do anything complex with it so I'm searching for a efficient way to do this.
My function takes float values given a 6-dim numpy array as input. What I tried to do initially was this:
First I created... | Here's a pure-numpy implementation. It's ca. 5Ã faster than using itertools.
```
import numpy as np
def cartesian(arrays, out=None):
"""
Generate a cartesian product of input arrays.
Parameters
----------
arrays : list of array-like
1-D arrays to form the cartesian product of.
out : ... |
Using numpy to build an array of all combinations of two arrays | 1,208,118 | 73 | 2009-07-30T17:32:27Z | 25,655,090 | 8 | 2014-09-03T23:22:41Z | [
"python",
"arrays",
"multidimensional-array",
"numpy"
] | I'm trying to run over the parameters space of a 6 parameter function to study it's numerical behavior before trying to do anything complex with it so I'm searching for a efficient way to do this.
My function takes float values given a 6-dim numpy array as input. What I tried to do initially was this:
First I created... | The following numpy implementation should be approx. 2x the speed of the given answer:
```
def cartesian2(arrays):
arrays = [np.asarray(a) for a in arrays]
shape = (len(x) for x in arrays)
ix = np.indices(shape, dtype=int)
ix = ix.reshape(len(arrays), -1).T
for n, arr in enumerate(arrays):
... |
Using numpy to build an array of all combinations of two arrays | 1,208,118 | 73 | 2009-07-30T17:32:27Z | 35,608,701 | 15 | 2016-02-24T17:14:46Z | [
"python",
"arrays",
"multidimensional-array",
"numpy"
] | I'm trying to run over the parameters space of a 6 parameter function to study it's numerical behavior before trying to do anything complex with it so I'm searching for a efficient way to do this.
My function takes float values given a 6-dim numpy array as input. What I tried to do initially was this:
First I created... | ***In newer version of `numpy` (>1.8.x), `np.meshgrid` provides a much faster implementation:***
@pv's solution
```
In [113]:
%timeit cartesian(([1, 2, 3], [4, 5], [6, 7]))
10000 loops, best of 3: 135 µs per loop
In [114]:
cartesian(([1, 2, 3], [4, 5], [6, 7]))
Out[114]:
array([[1, 4, 6],
[1, 4, 7],
... |
Dictionary with classes? | 1,208,322 | 7 | 2009-07-30T18:10:06Z | 1,208,348 | 22 | 2009-07-30T18:14:57Z | [
"python",
"dictionary",
"class"
] | In Python is it possible to instantiate a class through a dictionary?
```
shapes = {'1':Square(), '2':Circle(), '3':Triangle()}
x = shapes[raw_input()]
```
I want to let the user pick from a menu and not code huge if else statements on the input. For example if the user entered 2, x would then be a new instance of C... | Almost. What you want is
```
shapes = {'1':Square, '2':Circle, '3':Triangle} # just the class names in the dict
x = shapes[raw_input()]() # get class from dict, then call it to create a shape instance.
``` |
how do I use CommaSeparatedIntegerField in django? | 1,208,698 | 31 | 2009-07-30T19:11:21Z | 1,208,832 | 22 | 2009-07-30T19:34:00Z | [
"python",
"django",
"django-models"
] | There is almost no documentation for it here:
<http://docs.djangoproject.com/en/dev/ref/models/fields/#commaseparatedintegerfield>
Maybe someone could, by example, show me how to populate a `CommaSeparatedIntegerField` in Django?
-thanks. | Looking at the source for django...
```
class CommaSeparatedIntegerField(CharField):
def formfield(self, **kwargs):
defaults = {
'form_class': forms.RegexField,
'regex': '^[\d,]+$',
'max_length': self.max_length,
'error_messages': {
'invalid':... |
Django and urls.py: How do I HttpResponseRedirect via a named url? | 1,208,802 | 16 | 2009-07-30T19:29:30Z | 1,208,839 | 27 | 2009-07-30T19:35:34Z | [
"python",
"django",
"redirect",
"django-urls"
] | I'm writing a member-based web application, and I need to be able to redirect the page after login. I want to use the named url from my urls.py script in my views.py file for the login application, but I can't for the life of me figure out what to do. What I have is this:
```
def login(request):
if request.session.ha... | You need to use the [`reverse()`](http://docs.djangoproject.com/en/dev/topics/http/urls/#django.core.urlresolvers.reverse) utils function.
```
from django.core.urlresolvers import reverse
def myview(request):
return HttpResponseRedirect(reverse('arch-summary', args=[1945]))
```
Where `args` satisfies all the arg... |
Django and urls.py: How do I HttpResponseRedirect via a named url? | 1,208,802 | 16 | 2009-07-30T19:29:30Z | 1,211,218 | 7 | 2009-07-31T07:56:54Z | [
"python",
"django",
"redirect",
"django-urls"
] | I'm writing a member-based web application, and I need to be able to redirect the page after login. I want to use the named url from my urls.py script in my views.py file for the login application, but I can't for the life of me figure out what to do. What I have is this:
```
def login(request):
if request.session.ha... | A more concise way to write that if statement would be `if request.session.get('user')`. has\_key is deprecated nowadays, and .get() returns None (by default, changeable by passing a second parameter).
So combining this with Soviut's reply:
```
from django.core.urlresolvers import reverse
def login(request):
if ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.