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 |
|---|---|---|---|---|---|---|---|---|---|
How do I deal with multiple common user interfaces? | 2,022,448 | 7 | 2010-01-07T18:00:15Z | 2,022,503 | 10 | 2010-01-07T18:09:02Z | [
"python",
"user-interface",
"pygtk",
"code-reuse",
"maemo"
] | I'm working on a python application that runs on 2 different platforms, namely regular desktop linux and Maemo 4. We use PyGTK on both platforms but on Maemo there are a bunch of little tweaks to make it look nice which are implemented as follows:
```
if util.platform.MAEMO:
# do something fancy for maemo
else:
... | You could wind up much of this in a factory:
```
def createSpec():
if util.platform.MAEMO: return Maemo4Spec()
elif util.platform.MAEMO5: return Maemo5Spec()
return StandardPyGTKSpec()
```
Then, somewhere early in your code, you just call that factory:
```
spec = createSpec()
```
Now, everywhere else you had... |
How to diff file and output stream "on-the-fly"? | 2,022,492 | 25 | 2010-01-07T18:07:32Z | 2,022,512 | 35 | 2010-01-07T18:10:25Z | [
"python",
"diff",
"subprocess",
"pipe"
] | I need to create a diff file using standard UNIX **diff** command with python **subprocess** module. The problem is that I must compare file and stream without creating tempopary file. I thought about using named pipes via **os.mkfifo** method, but didn't reach any good result. Please, can you write a simple example on... | You can use "-" as an argument to `diff` to mean `stdin`. |
How to diff file and output stream "on-the-fly"? | 2,022,492 | 25 | 2010-01-07T18:07:32Z | 2,022,556 | 8 | 2010-01-07T18:16:04Z | [
"python",
"diff",
"subprocess",
"pipe"
] | I need to create a diff file using standard UNIX **diff** command with python **subprocess** module. The problem is that I must compare file and stream without creating tempopary file. I thought about using named pipes via **os.mkfifo** method, but didn't reach any good result. Please, can you write a simple example on... | You could perhaps consider using the [difflib](http://docs.python.org/library/difflib.html#difflib-interface) python module (I've linked to an example here) and create something that generates and prints the diff directly rather than relying on `diff`. The various function methods inside difflib can receive character b... |
Choosing a web application framework in python | 2,023,111 | 10 | 2010-01-07T19:40:46Z | 2,023,133 | 8 | 2010-01-07T19:43:41Z | [
"python",
"web-applications",
"frameworks"
] | I am python newbie from the [asp.net MVC](http://www.asp.net/%28S%28d35rmemuuono1wvm1gsp2n45%29%29/mvc/) world, looking to start a new web application project in python.
How do I go about **choosing a web application framework** in python? [Python website](http://wiki.python.org/moin/WebFrameworks) points to a lot of ... | I would recommend [Pylons](http://www.pylonsproject.org/), it's more customizable and intuitive personally than Django, and instead of proprietary components for say, an ORM, the ideal setup is using best of breed components, so you can use say, Mako for templating.. SQLAlchemy for ORM, you can have your own routing co... |
Choosing a web application framework in python | 2,023,111 | 10 | 2010-01-07T19:40:46Z | 2,023,241 | 11 | 2010-01-07T19:59:43Z | [
"python",
"web-applications",
"frameworks"
] | I am python newbie from the [asp.net MVC](http://www.asp.net/%28S%28d35rmemuuono1wvm1gsp2n45%29%29/mvc/) world, looking to start a new web application project in python.
How do I go about **choosing a web application framework** in python? [Python website](http://wiki.python.org/moin/WebFrameworks) points to a lot of ... | If you're just getting started with Python and want to get a working site with the minimum LOC, I would highly recommend Django.
One of the biggest advantages of Django for someone new to python is the excellent documentation. The [Django Book](http://djangobook.com/en/2.0/) is a great way to dive in and get familiar ... |
C#, Pass Array As Function Parameters | 2,023,528 | 5 | 2010-01-07T20:48:00Z | 2,023,540 | 12 | 2010-01-07T20:49:26Z | [
"c#",
"python"
] | In python the \* allows me to pass a list as function parameters:
```
def add(a,b): return a+b
x = [1,2]
add(*x)
```
Can I replicate this behavior in C# with an array?
Thanks. | The [params](http://msdn.microsoft.com/en-us/library/w5zay9db.aspx) keyword allows something similar
```
public int Add(params int[] numbers) {
int result = 0;
foreach (int i in numbers) {
result += i;
}
return result;
}
// to call:
int result = Add(1, 2, 3, 4);
// you can also use an array ... |
C#, Pass Array As Function Parameters | 2,023,528 | 5 | 2010-01-07T20:48:00Z | 2,023,565 | 9 | 2010-01-07T20:51:38Z | [
"c#",
"python"
] | In python the \* allows me to pass a list as function parameters:
```
def add(a,b): return a+b
x = [1,2]
add(*x)
```
Can I replicate this behavior in C# with an array?
Thanks. | Except for:
1. Changing the method signature to accept an array
2. Adding an overload that accepts an array, extracts the values and calls the original overload
3. Using reflection to call the method
then unfortunately, no, you cannot do that.
Keyword-based and positional-based parameter passing like in Python is no... |
check what files are open in Python | 2,023,608 | 24 | 2010-01-07T20:57:44Z | 2,023,691 | 8 | 2010-01-07T21:08:48Z | [
"python",
"debugging",
"exception",
"file"
] | I'm getting an error in a program that is supposed to run for a long time that too many files are open. Is there any way I can keep track of which files are open so I can print that list out occasionally and see where the problem is? | On Linux, you can use `lsof` to show all files opened by a process. |
check what files are open in Python | 2,023,608 | 24 | 2010-01-07T20:57:44Z | 2,023,709 | 26 | 2010-01-07T21:11:56Z | [
"python",
"debugging",
"exception",
"file"
] | I'm getting an error in a program that is supposed to run for a long time that too many files are open. Is there any way I can keep track of which files are open so I can print that list out occasionally and see where the problem is? | I ended up wrapping the built-in file object at the entry point of my program. I found out that I wasn't closing my loggers.
```
import __builtin__
openfiles = set()
oldfile = __builtin__.file
class newfile(oldfile):
def __init__(self, *args):
self.x = args[0]
print "### OPENING %s ###" % str(self.... |
check what files are open in Python | 2,023,608 | 24 | 2010-01-07T20:57:44Z | 2,023,791 | 17 | 2010-01-07T21:25:59Z | [
"python",
"debugging",
"exception",
"file"
] | I'm getting an error in a program that is supposed to run for a long time that too many files are open. Is there any way I can keep track of which files are open so I can print that list out occasionally and see where the problem is? | On Linux, you can look at the contents of `/proc/self/fd`:
```
$ ls -l /proc/self/fd/
total 0
lrwx------ 1 foo users 64 Jan 7 15:15 0 -> /dev/pts/3
lrwx------ 1 foo users 64 Jan 7 15:15 1 -> /dev/pts/3
lrwx------ 1 foo users 64 Jan 7 15:15 2 -> /dev/pts/3
lr-x------ 1 foo users 64 Jan 7 15:15 3 -> /proc/9527/fd
``... |
check what files are open in Python | 2,023,608 | 24 | 2010-01-07T20:57:44Z | 7,142,094 | 10 | 2011-08-22T00:23:57Z | [
"python",
"debugging",
"exception",
"file"
] | I'm getting an error in a program that is supposed to run for a long time that too many files are open. Is there any way I can keep track of which files are open so I can print that list out occasionally and see where the problem is? | Although the solutions above that wrap opens are useful for one's own code, I was debugging my client to a third party library including some c extension code, so I needed a more direct way. The following routine works under darwin, and (I hope) other unix-like environments:
```
def get_open_fds():
'''
return ... |
check what files are open in Python | 2,023,608 | 24 | 2010-01-07T20:57:44Z | 25,069,136 | 14 | 2014-07-31T21:21:50Z | [
"python",
"debugging",
"exception",
"file"
] | I'm getting an error in a program that is supposed to run for a long time that too many files are open. Is there any way I can keep track of which files are open so I can print that list out occasionally and see where the problem is? | To list all open files in a cross-platform manner, I would recommend [psutil](https://pypi.python.org/pypi/psutil).
```
#!/usr/bin/env python
import psutil
for proc in psutil.process_iter():
print proc.open_files()
```
The original question implicitly restricts the operation to the currently running process, whi... |
Postgis - How do i check the geometry type before i do an insert | 2,023,821 | 9 | 2010-01-07T21:30:47Z | 2,024,599 | 7 | 2010-01-07T23:58:06Z | [
"python",
"postgresql",
"postgis"
] | i have a postgres database with millions of rows in it it has a column called geom which contains the boundary of a property.
using a python script i am extracting the information from this table and re-inserting it into a new table.
when i insert in the new table the script bugs out with the following:
```
Tracebac... | This astonishingly useful bit of PostGIS SQL should help you figure it out... there are many geometry type tests in here:
```
-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
--
-- $Id: cleanGeometry.sql 2008-04-24 10:30Z Dr. Horst Duester $
--
-- cleanGeometry - remove self- and ring-selfinte... |
Python 3 Get HTTP page | 2,023,893 | 17 | 2010-01-07T21:43:04Z | 2,023,920 | 28 | 2010-01-07T21:48:08Z | [
"python",
"http",
"python-3.x"
] | How can I get python to get the contents of an HTTP page? So far all I have is the request and I have imported http.client. | Using [`urllib.request`](http://docs.python.org/3.1/library/urllib.request.html) is probably the easiest way to do this:
```
import urllib.request
f = urllib.request.urlopen("http://stackoverflow.com")
print(f.read())
``` |
Lambda, calling itself into the lambda definition | 2,023,992 | 3 | 2010-01-07T22:01:41Z | 2,024,390 | 8 | 2010-01-07T23:11:14Z | [
"python",
"functional-programming",
"lambda"
] | I'm doing a complicated hack in Python, it's a problem when you mix for+lambda+\*args (don't do this at home kids), the boring details can be omited, the unique solution I found to resolve the problem is to pass the lambda object into the self lambda in this way:
```
for ...
lambda x=x, *y: foo(x, y, <selflambda>)... | You are looking for a [fixed-point combinator](http://en.wikipedia.org/wiki/Fixed_point_combinator), like the Z combinator, for which Wikipedia gives this Python implementation:
```
Z = lambda f: (lambda x: f(lambda *args: x(x)(*args)))(lambda x: f(lambda *args: x(x)(*args)))
```
Z takes one argument, a function desc... |
Access outer class from inner class in python | 2,024,566 | 38 | 2010-01-07T23:49:05Z | 2,024,583 | 27 | 2010-01-07T23:54:24Z | [
"python"
] | I have a situation like so...
```
class Outer(object):
def some_method(self):
# do something
class Inner(object):
def __init__(self):
self.Outer.some_method() # <-- this is the line in question
```
How can I access the `Outer` class's method from the `Inner` class?
**Edit** -... | The methods of a nested class cannot directly access the instance attributes of the outer class.
Note that it is not necessarily the case that an instance of the outer class exists even when you have created an instance of the inner class.
In fact, it is often recommended against using nested classes, since the nesti... |
Access outer class from inner class in python | 2,024,566 | 38 | 2010-01-07T23:49:05Z | 7,034,206 | 22 | 2011-08-11T23:44:28Z | [
"python"
] | I have a situation like so...
```
class Outer(object):
def some_method(self):
# do something
class Inner(object):
def __init__(self):
self.Outer.some_method() # <-- this is the line in question
```
How can I access the `Outer` class's method from the `Inner` class?
**Edit** -... | You're trying to access Outer's class instance, from inner class instance. So just use factory-method to build Inner instance and pass Outer instance to it.
```
class Outer(object):
def createInner(self):
return Outer.Inner(self)
class Inner(object):
def __init__(self, outer_instance):
... |
Access outer class from inner class in python | 2,024,566 | 38 | 2010-01-07T23:49:05Z | 7,152,649 | 11 | 2011-08-22T19:38:17Z | [
"python"
] | I have a situation like so...
```
class Outer(object):
def some_method(self):
# do something
class Inner(object):
def __init__(self):
self.Outer.some_method() # <-- this is the line in question
```
How can I access the `Outer` class's method from the `Inner` class?
**Edit** -... | maybe I'm mad but this seems very easy indeed - the thing is to make your inner class inside a method of the outer class...
```
def do_sthg( self ):
...
def messAround( self ):
outerClassSelf = self
class mooble():
def do_sthg_different( self ):
...
outerClassSelf.do_sthg... |
Django | sort dict in template | 2,024,660 | 7 | 2010-01-08T00:13:50Z | 8,048,313 | 18 | 2011-11-08T09:31:12Z | [
"python",
"django"
] | I want to print out a dictionary, sorted by the key. Sorting the keys is easy in the view, by just putting the keys in a list and then sorting the list. How can I loop through the keys in the template and then get the value from the dictionary.
```
{% for company in companies %}
{% for employee, dependents in comp... | create a custom filter, which is like this:
```
from django import template
from django.utils.datastructures import SortedDict
register = template.Library()
@register.filter(name='sort')
def listsort(value):
if isinstance(value, dict):
new_dict = SortedDict()
key_list = sorted(value.keys())
... |
Is Python a weakly typed language as variables can switch types? | 2,025,353 | 10 | 2010-01-08T03:43:07Z | 2,025,361 | 38 | 2010-01-08T03:45:20Z | [
"python",
"strong-typing",
"weak-typing"
] | The way I understand it, the following is allowed in PHP because it's a weakly-typed language.
```
$var = 'Hello';
$var = 5;
```
I just installed a Windows version of Python 2.6 and I was expecting it NOT to let me change type just like that, but the Python equivalent of the above code works just like in PHP yikes!
... | Your example demonstrates *dynamic* typing, not weak typing. Dynamic typing generally means that the type of data an object can store is mutable; any target may hold a binding to any kind of object. Contrast that with, say, C#, which is statically typed [\*].
```
int i = 5; // Okay.
i = "5"; // Illegal! i can only h... |
Inherit docstrings in Python class inheritance | 2,025,562 | 53 | 2010-01-08T04:45:11Z | 2,025,581 | 26 | 2010-01-08T04:51:35Z | [
"python",
"inheritance",
"documentation"
] | I'm trying to do some class inheritance in Python. I'd like each class and inherited class to have good docstrings. So I think for the inherited class, I'd like it to:
* inherit the base class docstring
* also append relevant extra documentation to the docstring
Is there some "best practice" for doing this sort of do... | You're not the only one! There was a discussion on `comp.lang.python` about this a while ago, and a recipe was created. Check it out **[here](http://code.activestate.com/recipes/576862/)**.
```
"""
doc_inherit decorator
Usage:
class Foo(object):
def foo(self):
"Frobber"
pass
class Bar(Foo):
... |
Inherit docstrings in Python class inheritance | 2,025,562 | 53 | 2010-01-08T04:45:11Z | 2,025,599 | 17 | 2010-01-08T04:55:23Z | [
"python",
"inheritance",
"documentation"
] | I'm trying to do some class inheritance in Python. I'd like each class and inherited class to have good docstrings. So I think for the inherited class, I'd like it to:
* inherit the base class docstring
* also append relevant extra documentation to the docstring
Is there some "best practice" for doing this sort of do... | You can concatenate the docstrings easily:
```
class Foo(object):
"""
Foo Class.
This class foos around.
"""
pass
class Bar(Foo):
"""
Bar class, children of Foo
Use this when you want to Bar around.
parent:
"""
__doc__ += Foo.__doc__
pass
```
However, that is useless.... |
MasterPage like concept in python | 2,025,565 | 7 | 2010-01-08T04:46:00Z | 2,025,647 | 11 | 2010-01-08T05:11:24Z | [
"python",
"google-app-engine",
"master-pages"
] | We are developing a web based application in python on google app engine platform. I have different pages in web site. What I want is to have a master page like functionality like we have in asp.net where I have just on template and all other pages will use that. How can I do this? I am a beginner in python | If you're using Django (or at least Django templates), [Django template inheritance](http://docs.djangoproject.com/en/dev/topics/templates/#template-inheritance) may be what you're looking for. |
Relationship between string module and str | 2,026,038 | 10 | 2010-01-08T07:12:57Z | 2,026,050 | 14 | 2010-01-08T07:16:31Z | [
"python"
] | What is the difference or relationship between *str* and *string*?
```
import string
print str
print string
``` | [`str`](http://docs.python.org/3.1/library/functions.html#str) is a [built-in function](http://docs.python.org/3.1/library/functions.html) (actually a [class](http://docs.python.org/tutorial/classes.html)) which converts its argument to a string. [`string`](http://docs.python.org/3.1/library/string.html) is a [module](... |
How to create Python egg file | 2,026,395 | 71 | 2010-01-08T08:46:51Z | 2,027,033 | 62 | 2010-01-08T10:54:42Z | [
"python",
"packaging",
"egg"
] | I have questions about egg files in Python.
I have much Python code organized by package and I'm trying to create egg files.
I'm following [instructions](http://peak.telecommunity.com/DevCenter/PythonEggs#building-eggs), but they are very common.
According to that, it seems I need to have a setup.py file.
1. Would y... | You are reading the wrong documentation. You want this: <http://peak.telecommunity.com/DevCenter/setuptools>
1. Creating setup.py is covered in the distutils documentation in Python's standard library documentation [here](http://docs.python.org/distutils/setupscript.html). The main difference (for python eggs) is you ... |
How to create Python egg file | 2,026,395 | 71 | 2010-01-08T08:46:51Z | 7,930,975 | 26 | 2011-10-28T14:55:58Z | [
"python",
"packaging",
"egg"
] | I have questions about egg files in Python.
I have much Python code organized by package and I'm trying to create egg files.
I'm following [instructions](http://peak.telecommunity.com/DevCenter/PythonEggs#building-eggs), but they are very common.
According to that, it seems I need to have a setup.py file.
1. Would y... | For #4, the closest thing to starting java with a jar file for your app is a new feature in Python 2.6, [executable zip files and directories](http://docs.python.org/whatsnew/2.6.html#other-language-changes).
```
python myapp.zip
```
Where myapp.zip is a zip containing a `__main__.py` file which is executed as the sc... |
Python Cherrypy 404 Error Handling | 2,026,414 | 5 | 2010-01-08T08:50:55Z | 2,029,218 | 9 | 2010-01-08T17:01:06Z | [
"python",
"cherrypy"
] | I have a web server that has all of the configurations set in the code, but I want to be able to handle all page 404 errors. How would I go about doing this in Python? | See also <http://www.cherrypy.org/wiki/ErrorsAndExceptions#AnticipatedHTTPresponses> if you want more traditional replacement of 4xx and 5xx output. |
Is it possible to tell a python script to stop at some point and give you the hand interactively, for example with ipython? | 2,026,447 | 5 | 2010-01-08T08:57:20Z | 2,026,554 | 15 | 2010-01-08T09:22:41Z | [
"python"
] | Suppose I have a script that does a lot of stuff, and doesn't work well somewhere near the end. I'd love to be able to add a `start_ipython()` function at that point, which would stop the script at this point, and let me inspect variables and so on with ipython. How can I do this? | Note that this has changed in IPython-0.11. Instead of what is described below, simply use the following import:
```
from IPython import embed as shell
```
The answer below works for IPython versions prior to 0.11.
---
In the region where you want to drop into ipython, define this
```
def start_ipython():
from ... |
Packaging Python applications with configuration files | 2,026,876 | 9 | 2010-01-08T10:24:51Z | 2,026,916 | 7 | 2010-01-08T10:33:17Z | [
"python",
"configuration-files",
"packaging"
] | I'm using ConfigParser for configuring my application, and now I want to make it easily distributable, and at the same time preserve the configurability.
I'm thinking I need a directory with configuration file templates, and some way of generating the configuration to actually use from these. Then I need a place to st... | you can use [`data_files`](http://docs.python.org/distutils/setupscript.html#installing-additional-files) option of `distutils` to install files wherever you want.
`data_files` specifies a sequence of `(directory, files)` pairs in the following way:
```
setup(...,
data_files=[('/etc', ['cfg/config1.ini', 'cfg/c... |
Pygame programs hanging on exit | 2,027,105 | 8 | 2010-01-08T11:06:06Z | 2,027,127 | 10 | 2010-01-08T11:09:00Z | [
"python",
"pygame"
] | I'm tinkering around with pygame right now, and it seems like all the little programs that I make with it hang when I try to close them.
Take the following code, for example:
```
from pygame.locals import *
pygame.init()
# YEEAAH!
tile_file = "blue_tile.bmp"
SCREEN_SIZE = (640, 480)
SCREEN_DEPTH = 32
if __name__ == ... | If you are running it from IDLE, then you are missing **pygame.quit()**.
> This is caused by the IDLE python interpreter, which seems to keep the references around somehow. Make sure, you invoke pygame.quit() on exiting your application or game.
See: [In IDLE why does the Pygame window not close correctly?](http://ww... |
Pygame programs hanging on exit | 2,027,105 | 8 | 2010-01-08T11:06:06Z | 2,027,185 | 12 | 2010-01-08T11:22:04Z | [
"python",
"pygame"
] | I'm tinkering around with pygame right now, and it seems like all the little programs that I make with it hang when I try to close them.
Take the following code, for example:
```
from pygame.locals import *
pygame.init()
# YEEAAH!
tile_file = "blue_tile.bmp"
SCREEN_SIZE = (640, 480)
SCREEN_DEPTH = 32
if __name__ == ... | Where do you exit the outer loop?
```
while True: # outer loop
for event in pygame.event.get(): # inner loop
if event.type == QUIT:
break # <- break inner loop
``` |
invoking pylint programmatically | 2,028,268 | 18 | 2010-01-08T14:44:58Z | 2,062,665 | 15 | 2010-01-14T07:03:31Z | [
"python",
"coding-style",
"automated-tests",
"pylint"
] | I'd like to invoke the pylint checker, limited to the Error signalling part, as part of my unit testing. so I checked the pylint executable script, got to the `pylint.lint.Run` helper class and there I got lost in a quite long `__init__` function, ending with a call to `sys.exit()`.
anybody ever tried and managed to d... | Take a look at the `pylint/epylint.py` which contains *two* different ways to start pylint programatically.
You can also simply call :
```
from pylint.lint import Run
Run(['--errors-only', 'myfile.py'])
```
for instance. |
invoking pylint programmatically | 2,028,268 | 18 | 2010-01-08T14:44:58Z | 7,919,648 | 8 | 2011-10-27T17:06:39Z | [
"python",
"coding-style",
"automated-tests",
"pylint"
] | I'd like to invoke the pylint checker, limited to the Error signalling part, as part of my unit testing. so I checked the pylint executable script, got to the `pylint.lint.Run` helper class and there I got lost in a quite long `__init__` function, ending with a call to `sys.exit()`.
anybody ever tried and managed to d... | I got the same problem recently.
syt is right, `pylint.epylint` got several methods in there. However they all call a subprocess in which python is launched again. In my case, this was getting quite slow.
Building from mcarans answer, and finding that there is a flag exit, I did the following
```
class WritableObject... |
Sorting a tuple of dicts | 2,028,375 | 3 | 2010-01-08T15:02:34Z | 2,028,441 | 7 | 2010-01-08T15:11:09Z | [
"python",
"sorting"
] | I am new to Python and am curious if I am doing this correctly. I have a tuple of dicts (from a database call):
```
companies = ( { 'companyid': 1, 'companyname': 'Company C' },
{ 'companyid': 2, 'companyname': 'Company A' },
{ 'companyid': 3, 'companyname': 'Company B' } )
```
I want to s... | You could do something like:
```
import operator
...
sortcompanies.sort(key=operator.itemgetter("companyname"))
```
I think that's a matter of taste.
**EDIT**
I got `companyid` in stead of `companyname`. Corrected that error. |
Django - Allow duplicate usernames | 2,028,515 | 8 | 2010-01-08T15:22:39Z | 2,028,567 | 7 | 2010-01-08T15:29:43Z | [
"python",
"django",
"authentication"
] | I'm working on a project in django which calls for having separate groups of users in their own `username` namespace.
So for example, I might have multiple "organizations", and `username` should only have to be unique within that organization.
I know I can do this by using another model that contains a username/organ... | I'm not sure if this is exactly what you're looking for, but I think you could use a hack similar to what is in [this answer](http://stackoverflow.com/questions/927729/how-to-override-the-verbose-name-of-a-superclass-model-field-in-django).
The following code works, as long as it is in a place that gets executed when ... |
Python urllib2 Progress Hook | 2,028,517 | 26 | 2010-01-08T15:22:50Z | 2,028,704 | 12 | 2010-01-08T15:48:04Z | [
"python",
"http",
"progress-bar",
"urllib2",
"httpclient"
] | I am trying to create a download progress bar in python using the urllib2 http client. I've looked through the API (and on google) and it seems that urllib2 does not allow you to register progress hooks. However the older deprecated urllib does have this functionality.
Does anyone know how to create a progress bar or ... | Why not just read data in chunks and do whatever you want to do in between, e.g. run in a thread, hook into a UI, etc etc
```
import urllib2
urlfile = urllib2.urlopen("http://www.google.com")
data_list = []
chunk = 4096
while 1:
data = urlfile.read(chunk)
if not data:
print "done."
break
... |
Python urllib2 Progress Hook | 2,028,517 | 26 | 2010-01-08T15:22:50Z | 2,030,027 | 37 | 2010-01-08T19:11:23Z | [
"python",
"http",
"progress-bar",
"urllib2",
"httpclient"
] | I am trying to create a download progress bar in python using the urllib2 http client. I've looked through the API (and on google) and it seems that urllib2 does not allow you to register progress hooks. However the older deprecated urllib does have this functionality.
Does anyone know how to create a progress bar or ... | Here's a fully working example that builds on Anurag's approach of chunking in a response. My version allows you to set the the chunk size, and attach an arbitrary reporting function:
```
import urllib2, sys
def chunk_report(bytes_so_far, chunk_size, total_size):
percent = float(bytes_so_far) / total_size
perce... |
Django DateField default options | 2,029,295 | 47 | 2010-01-08T17:18:42Z | 2,029,339 | 25 | 2010-01-08T17:23:53Z | [
"python",
"django",
"django-models"
] | I have a model which has a date time field:
```
date = models.DateField(_("Date"), default=datetime.now())
```
When I check the app in the built in django admin, the DateField also has the time appended to it, so that if you try to save it it returns an error. How do I make the default just the date? (datetime.today(... | You mistake is using the datetime module instead of the date module. You meant to do this:
```
from datetime import date
date = models.DateField(_("Date"), default=date.today)
```
If you only want to capture the current date the proper way to handle this is to use the auto\_now\_add parameter:
```
date = models.Date... |
Django DateField default options | 2,029,295 | 47 | 2010-01-08T17:18:42Z | 2,030,142 | 82 | 2010-01-08T19:29:22Z | [
"python",
"django",
"django-models"
] | I have a model which has a date time field:
```
date = models.DateField(_("Date"), default=datetime.now())
```
When I check the app in the built in django admin, the DateField also has the time appended to it, so that if you try to save it it returns an error. How do I make the default just the date? (datetime.today(... | This is why you should always import the base `datetime` module: `import datetime`, rather than the `datetime` class within that module: `from datetime import datetime`.
The other mistake you have made is to actually call the function in the default, with the `()`. This means that all models will get the date *at the ... |
How to prevent a module from being imported twice? | 2,029,523 | 16 | 2010-01-08T17:49:45Z | 2,029,528 | 9 | 2010-01-08T17:50:41Z | [
"python",
"import",
"module"
] | When writing python modules, is there a way to prevent it being imported twice by the client codes? Just like the c/c++ header files do:
```
#ifndef XXX
#define XXX
...
#endif
```
Thanks very much! | Imports are cached, and only run once. Additional imports only cost the lookup time in `sys.modules`. |
How to prevent a module from being imported twice? | 2,029,523 | 16 | 2010-01-08T17:49:45Z | 2,029,546 | 24 | 2010-01-08T17:53:34Z | [
"python",
"import",
"module"
] | When writing python modules, is there a way to prevent it being imported twice by the client codes? Just like the c/c++ header files do:
```
#ifndef XXX
#define XXX
...
#endif
```
Thanks very much! | Python modules aren't imported multiple times. Just running import two times will not reload the module. If you want it to be reloaded, you have to use the `reload` statement. Here's a demo
`foo.py` is a module with the single line
```
print "I am being imported"
```
And here is a screen transcript of multiple impor... |
Comparing Python nested lists | 2,029,795 | 2 | 2010-01-08T18:34:01Z | 2,029,816 | 8 | 2010-01-08T18:38:13Z | [
"python",
"list",
"nested",
"intersection"
] | I have two nested lists, each nested list containing two strings e.g.:
```
list 1 [('EFG', '[3,4,5]'), ('DEF', '[2,3,4]')] and list 2 [('DEF', '[2,3,4]'), ('FGH', '[4,5,6]')]
```
I would like to compare the two lists and recover those nested lists which are identical with each other. In this case only `('DEF','[2,3,4... | If the lists only contain string tuples, then the easiest way to do it is using sets intersection (&):
```
>>> set([('EFG', '[3,4,5]'), ('DEF', '[2,3,4]')]) & set([('DEF', '[2,3,4]'), ('FGH', '[4,5,6]')])
set([('DEF', '[2,3,4]')])
``` |
Random strings in Python | 2,030,053 | 43 | 2010-01-08T19:15:47Z | 2,030,081 | 109 | 2010-01-08T19:19:40Z | [
"python"
] | How do you create a random string in Python?
I needed it to be number then character repeat till you're done this is what I created
```
def random_id(length):
number = '0123456789'
alpha = 'abcdefghijklmnopqrstuvwxyz'
id = ''
for i in range(0,length,2):
id += random.choice(number)
id +... | Generating strings from (for example) lowercase characters:
```
import random, string
def randomword(length):
return ''.join(random.choice(string.lowercase) for i in range(length))
```
Results:
```
>>> randomword(10)
'vxnxikmhdc'
>>> randomword(10)
'ytqhdohksy'
``` |
Random strings in Python | 2,030,053 | 43 | 2010-01-08T19:15:47Z | 2,030,156 | 25 | 2010-01-08T19:32:04Z | [
"python"
] | How do you create a random string in Python?
I needed it to be number then character repeat till you're done this is what I created
```
def random_id(length):
number = '0123456789'
alpha = 'abcdefghijklmnopqrstuvwxyz'
id = ''
for i in range(0,length,2):
id += random.choice(number)
id +... | Since this question is fairly, uh, random, this may work for you:
```
>>> import uuid
>>> print uuid.uuid4()
58fe9784-f60a-42bc-aa94-eb8f1a7e5c17
``` |
Random strings in Python | 2,030,053 | 43 | 2010-01-08T19:15:47Z | 2,030,293 | 20 | 2010-01-08T19:53:22Z | [
"python"
] | How do you create a random string in Python?
I needed it to be number then character repeat till you're done this is what I created
```
def random_id(length):
number = '0123456789'
alpha = 'abcdefghijklmnopqrstuvwxyz'
id = ''
for i in range(0,length,2):
id += random.choice(number)
id +... | ```
>>> import random
>>> import string
>>> s=string.lowercase+string.digits
>>> ''.join(random.sample(s,10))
'jw72qidagk
``` |
Random strings in Python | 2,030,053 | 43 | 2010-01-08T19:15:47Z | 18,172,468 | 8 | 2013-08-11T13:34:56Z | [
"python"
] | How do you create a random string in Python?
I needed it to be number then character repeat till you're done this is what I created
```
def random_id(length):
number = '0123456789'
alpha = 'abcdefghijklmnopqrstuvwxyz'
id = ''
for i in range(0,length,2):
id += random.choice(number)
id +... | Answer to the original question:
```
os.urandom(n)
```
Quote from: <http://docs.python.org/2/library/os.html>
> Return a string of n random bytes suitable for cryptographic use.
>
> This function returns random bytes from an OS-specific randomness
> source. The returned data should be unpredictable enough for
> cryp... |
How to get current_app for using with reverse in multi-deployable reusable Django application? | 2,030,225 | 8 | 2010-01-08T19:44:14Z | 13,249,060 | 10 | 2012-11-06T10:28:52Z | [
"python",
"django",
"django-urls"
] | I'm writing reusable app. And I want to deploy it several times.
Here is urls.py:
```
urlpatterns = patterns('',
(r'^carphotos/', include('webui.photos.urls', app_name='car-photos') ),
(r'^userphotos/', include('webui.photos.urls', app_name='profile-photos') ),)
```
and photos/urls.py:
```
urlpatterns = patterns('... | I know this is a pretty old question... but I think I found a solution:
As Will Hardy suggested you'll have to keep `app_name` the same for both instances (or not define it at all, it will default to the app the included urls reside in). Define a separate namespace for each app instance though:
```
urlpatterns = patt... |
Logging into facebook with python | 2,030,652 | 4 | 2010-01-08T20:52:38Z | 11,026,989 | 15 | 2012-06-14T05:11:01Z | [
"python"
] | If I run the following code 10 times in a row, it will work about half the time and fail the rest. Anyone know why?
```
import urllib2, cookielib, re, os, sys
class Facebook():
def __init__(self, email, password):
self.email = email
self.password = password
cj = cookielib.CookieJar()
... | So I tried your code, and got it to log in once, then like you I had trouble logging in again. On a line before the 'if' statement, I added
print usock.read()
and ended up getting a bunch of html code. I then dropped that code into a notepad, saved it as an html file, and pulled it up.
This is what's happening: Faceboo... |
Python Image Library produces a crappy quality jpeg when I resize a picture | 2,030,871 | 4 | 2010-01-08T21:27:44Z | 2,030,905 | 13 | 2010-01-08T21:32:20Z | [
"python",
"image",
"file",
"encoding",
"python-imaging-library"
] | I use the Python Image Library (PIL) to resize an image and create a thumbnail.
Why is it that my code produces an image that is so crappy and low-quality? Can someone tell me how to modify the code so that it's the highest quality JPEG?
```
def create_thumbnail(buffer, width=100, height=100):
im = Image.open(Stri... | [Documentation sayyyyys](http://www.pythonware.com/library/pil/handbook/format-jpeg.htm):
```
im.save(thumbnail_file, 'JPEG', quality=90)
``` |
Python Matplotlib rectangular binning | 2,030,970 | 17 | 2010-01-08T21:44:26Z | 2,072,868 | 12 | 2010-01-15T15:57:15Z | [
"python",
"matplotlib",
"histogram"
] | I've got a series of (x,y) values that I want to plot a 2d histogram of using python's matplotlib. Using hexbin, I get something like this:

But I'm looking for something like this:

Example Cod... | Numpy has a function called [histogram2d](http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram2d.html), whose docstring also shows you how to visualize it using Matplotlib. Add `interpolation=nearest` to the imshow call to disable the interpolation. |
In Python, how can I put a thread to sleep until a specific time? | 2,031,111 | 21 | 2010-01-08T22:10:52Z | 2,031,297 | 19 | 2010-01-08T22:42:03Z | [
"python"
] | I know that I can cause a thread to sleep for a specific amount of time with:
```
time.sleep(NUM)
```
How can I make a thread sleep until 2AM? Do I have to do math to determine the number of seconds until 2AM? Or is there some library function?
( Yes, I know about cron and equivalent systems in Windows, but I want t... | Here's a half-ass solution that doesn't account for clock jitter or adjustment of the clock. See comments for ways to get rid of that.
```
import time
import datetime
# if for some reason this script is still running
# after a year, we'll stop after 365 days
for i in xrange(0,365):
# sleep until 2AM
t = datet... |
Python logging over multiple files | 2,031,394 | 5 | 2010-01-08T23:01:32Z | 2,031,557 | 12 | 2010-01-08T23:41:58Z | [
"python",
"logging",
"error-logging"
] | I've read through the logging module documentation and whilst I may have missed something obvious, the code I've got doesn't appear to be working as intended. I'm using Python 2.6.4.
My program consists of several different python files, from which I want to send logging messages to a text file and, potentially, the s... | Are you sure no other logging setup is being done in anything you import.
The incorrect output in your console logs look like the default configuration for a logger, so something else may be setting that up.
Running this quick test script:
```
import logging
from logging.handlers import RotatingFileHandler
import os... |
Python: Very confused about decorators | 2,031,559 | 2 | 2010-01-08T23:42:07Z | 2,031,605 | 11 | 2010-01-08T23:51:58Z | [
"python",
"decorator"
] | I thought I understood decorators but not anymore. Do decorators only work when the function is created?
I wanted to create a series of functions that all have a required argument called 'ticket\_params' that is a dictionary. and then decorate them with something like `@param_checker(['req_param_1', 'req_param_2'])` a... | A decorator is applied immediately after the `def` statement; the equivalence is:
```
@param_checker(['req_param_1', 'req_param_2'])
def my_decorated_function(params):
# do stuff
```
is **exactly** the same thing as:
```
def my_decorated_function(params):
# do stuff
my_decorated_function = param_checker(['re... |
Python find list lengths in a sublist | 2,031,846 | 5 | 2010-01-09T00:55:04Z | 2,031,855 | 13 | 2010-01-09T00:57:25Z | [
"python",
"list"
] | I am trying to find out how to get the length of every list that is held within a particular list. For example:
```
a = []
a.append([])
a[0].append([1,2,3,4,5])
a[0].append([1,2,3,4])
a[0].append([1,2,3])
```
I'd like to run a command like:
```
len(a[0][:])
```
which would output the answer I want which is a list o... | `[len(x) for x in a[0]]` ?
```
>>> a = []
>>> a.append([])
>>> a[0].append([1,2,3,4,5])
>>> a[0].append([1,2,3,4])
>>> a[0].append([1,2,3])
>>> [len(x) for x in a[0]]
[5, 4, 3]
``` |
Python find list lengths in a sublist | 2,031,846 | 5 | 2010-01-09T00:55:04Z | 2,031,877 | 7 | 2010-01-09T01:02:05Z | [
"python",
"list"
] | I am trying to find out how to get the length of every list that is held within a particular list. For example:
```
a = []
a.append([])
a[0].append([1,2,3,4,5])
a[0].append([1,2,3,4])
a[0].append([1,2,3])
```
I'd like to run a command like:
```
len(a[0][:])
```
which would output the answer I want which is a list o... | `map(len, a[0])` |
How can i grab CData out of BeautifulSoup | 2,032,172 | 5 | 2010-01-09T02:53:22Z | 2,032,252 | 11 | 2010-01-09T03:31:41Z | [
"python",
"screen-scraping",
"beautifulsoup",
"cdata"
] | I have a website that I'm scraping that has a similar structure the following. I'd like to be able to grab the info out of the CData block.
I'm using BeautifulSoup to pull other info off the page, so if the solution can work with that, it would help keep my learning curve down as I'm a python novice.
Specifically, I w... | BeautifulSoup sees CData as a special case (subclass) of "navigable strings". So for example:
```
import BeautifulSoup
txt = '''<foobar>We have
<![CDATA[some data here]]>
and more.
</foobar>'''
soup = BeautifulSoup.BeautifulSoup(txt)
for cd in soup.findAll(text=True):
if isinstance(cd, Beautif... |
ValueError in Django | 2,032,360 | 9 | 2010-01-09T04:37:52Z | 2,032,378 | 16 | 2010-01-09T04:47:32Z | [
"python",
"django"
] | I'm getting a strange error and can't figure out why. I'd appreciate any input. I've been stuck on this for a few days. Here is my code:
models.py
```
class Employee(models.Model):
lastname = models.CharField(max_length=75)
firstname = models.CharField(max_length=75)
position = models.ForeignKey(Positi... | ```
urlpatterns = patterns('',
(r'^salaries/employee/$', list_detail.object_list, 'employee_info'),
)
```
The third item in the tuple needs to be a dictionary, not a string. Try removing the single quotes around employee\_info:
```
urlpatterns = patterns('',
(r'^salaries/employee/$', list_detail.obj... |
How to create full compressed tar file using Python? | 2,032,403 | 44 | 2010-01-09T04:59:37Z | 2,032,433 | 63 | 2010-01-09T05:17:44Z | [
"python",
"compression",
"zip",
"tarfile"
] | how can I create a .tar.gz file which compresses the data as much as tar files are compressed... | ```
import tarfile
tar = tarfile.open("sample.tar.gz", "w:gz")
for name in ["file1", "file2", "file3"]:
tar.add(name)
tar.close()
```
If you want to create a tar.bz2 compressed file, just replace file extension name with ".tar.bz2" and "w:gz" with "w:bz2". |
How to create full compressed tar file using Python? | 2,032,403 | 44 | 2010-01-09T04:59:37Z | 2,032,439 | 27 | 2010-01-09T05:19:07Z | [
"python",
"compression",
"zip",
"tarfile"
] | how can I create a .tar.gz file which compresses the data as much as tar files are compressed... | You call [tarfile.open](http://docs.python.org/library/tarfile.html#tarfile.open) with `mode='w:gz'`, meaning "Open for gzip compressed writing."
You'll probably want to end the filename (the `name` argument to `open`) with `.tar.gz`, but that doesn't affect compression abilities.
BTW, you usually get better compress... |
How to create full compressed tar file using Python? | 2,032,403 | 44 | 2010-01-09T04:59:37Z | 17,081,026 | 71 | 2013-06-13T06:58:45Z | [
"python",
"compression",
"zip",
"tarfile"
] | how can I create a .tar.gz file which compresses the data as much as tar files are compressed... | To build a `.tar.gz` for an entire directory tree:
```
def make_tarfile(output_filename, source_dir):
with tarfile.open(output_filename, "w:gz") as tar:
tar.add(source_dir, arcname=os.path.basename(source_dir))
``` |
Subclassing dict: should dict.__init__() be called? | 2,033,150 | 25 | 2010-01-09T11:16:00Z | 2,033,416 | 12 | 2010-01-09T12:55:56Z | [
"python",
"subclass",
"dictionary",
"init"
] | Here is a twofold question, with a theoretical part, and a practical one:
When subclassing dict:
```
class ImageDB(dict):
def __init__(self, directory):
dict.__init__(self) # Necessary??
...
```
should `dict.__init__(self)` be called, just as a "safety" measure (e.g., in case there are some non... | You should probably call `dict.__init__(self)` when subclassing; in fact, you don't know what's happening precisely in dict (since it's a builtin), and that might vary across versions and implementations. Not calling it may result in improper behaviour, since you can't know where dict is holding its internal data struc... |
Subclassing dict: should dict.__init__() be called? | 2,033,150 | 25 | 2010-01-09T11:16:00Z | 2,033,554 | 9 | 2010-01-09T13:56:43Z | [
"python",
"subclass",
"dictionary",
"init"
] | Here is a twofold question, with a theoretical part, and a practical one:
When subclassing dict:
```
class ImageDB(dict):
def __init__(self, directory):
dict.__init__(self) # Necessary??
...
```
should `dict.__init__(self)` be called, just as a "safety" measure (e.g., in case there are some non... | You should generally call base class' `__init__` so why make an exception here?
Either do not override `__init__` or if you need to override `__init__` call base class `__init__`, If you worry about arguments just pass \*args, \*\*kwargs or nothing if you want empty dict e.g.
```
class MyDict(dict):
def __init__(... |
Concatenation Operator + or , | 2,033,242 | 7 | 2010-01-09T11:57:34Z | 2,033,272 | 15 | 2010-01-09T12:07:46Z | [
"python",
"python-3.x",
"concatenation"
] | ```
var1 = 'abc'
var2 = 'xyz'
print('literal' + var1 + var2) # literalabcxyz
print('literal', var1, var2) # literal abc xyz
```
... except for automatic spaces with ',' whats the difference between the two? Which to use normally, also which is the fastest?
Thanks | (You're using Python 3.x, where print is a function—in 2.x, print is a statement. It's a good idea to mention the major Python version—2.x or 3.x—especially when asking for help, because currently most people reasonably assume 2.x unless it's stated.)
The first, `print('literal' + var1 + var2)`, evaluates an expressio... |
how to use IPython | 2,033,575 | 4 | 2010-01-09T14:04:09Z | 2,033,592 | 11 | 2010-01-09T14:10:11Z | [
"python",
"ipython"
] | I could not understand the ipython library. This url provide the common feature but I could not core-relate it. <http://ipython.org/ipython-doc/stable/interactive/tutorial.html>
How to I use IPython to improve my day to day python application experience? | ipython is an improved interactive prompt, not a library. It has features like tab completion and profiles which are not present in the vanilla interactive prompt (which is running python without an input file). All features are listed on the page you cited.
So, it doesn't really improve your day to day python applica... |
Image embossing in Python with PIL -- adding depth, azimuth, etc | 2,034,037 | 6 | 2010-01-09T16:39:51Z | 2,034,258 | 8 | 2010-01-09T17:40:49Z | [
"python",
"image-processing",
"python-imaging-library"
] | I am trying to emboss an image using [PIL](http://en.wikipedia.org/wiki/Python_Imaging_Library).
PIL provides a basic way to emboss an image ( using `ImageFilter.EMBOSS`).
In image editing packages like GIMP, you can vary parameters like Azimuth, depth and elevation in this embossed image.
How to do this with PIL? A... | If you cannot achieve your goal by using or combination of operations (like rotating, then applying the EMBOSS filter, the re-rotating), (or enhancing the contrast then embossing) then you may resort to changing (or creating your own) filter matrix.
Within ImageFilter.py you will find this class:
```
##
# Embossing f... |
Python's interpretation of tabs and spaces to indent | 2,034,517 | 15 | 2010-01-09T18:57:25Z | 2,034,527 | 19 | 2010-01-09T18:59:33Z | [
"python",
"tabs",
"indentation",
"spaces"
] | I decided, that I learn a bit of Python. The first introduction says that it uses indentation to group statements. While the best habit is clearly to use just one of these what happens if I interchange them? How many spaces will be considered equal to one tab? Or will it fail to work at all if tabs and spaces are mixed... | Spaces are not treated as equivalent to tab. A line indented with a tab is at a different indentation from a line indented with 1, 2, 4 ~~or 8~~ spaces.
Proof by counter-example (*erroneous, or, at best, limited - tab != 4 spaces*):
```
x = 1
if x == 1:
^Iprint "fff\n"
print "yyy\n"
```
The '`^I`' shows a `TAB`.... |
Python's interpretation of tabs and spaces to indent | 2,034,517 | 15 | 2010-01-09T18:57:25Z | 2,034,538 | 15 | 2010-01-09T19:02:22Z | [
"python",
"tabs",
"indentation",
"spaces"
] | I decided, that I learn a bit of Python. The first introduction says that it uses indentation to group statements. While the best habit is clearly to use just one of these what happens if I interchange them? How many spaces will be considered equal to one tab? Or will it fail to work at all if tabs and spaces are mixed... | Follow [PEP 8](http://www.python.org/dev/peps/pep-0008/) for Python style. PEP 8 says:
Indentation
> Use 4 spaces per indentation level.
>
> For really old code that you don't want to mess up, you can continue
> to use 8-space tabs.
Tabs or Spaces?
> Never mix tabs and spaces.
>
> The most popular way of indenting P... |
ttk.Button returns None | 2,034,576 | 2 | 2010-01-09T19:11:08Z | 2,034,596 | 10 | 2010-01-09T19:15:24Z | [
"python",
"tkinter",
"ttk"
] | I am trying to use the invoke method of a ttk.Button, as shown at [TkDocs](http://www.tkdocs.com/tutorial/widgets.html#button) (look at *"The Command Callback"*), but I keep getting this error:
> AttributeError: 'NoneType' object has no attribute 'invoke'
So, I tried this in the Interactive Shell:
```
ActivePython 3... | No, you're entirely wrong: your code does **not** show that `ttk.Button` returns `None` -- it shows that the `grid` method on the button object returns `None`! Don't you see that you're calling `.grid` on whatever it is that `ttk.Button` returns (the button object), and it's the result of that **grid** call that you're... |
What are some good projects to make for a newbie Python (but not new to programming) developer? | 2,034,932 | 4 | 2010-01-09T21:00:02Z | 2,035,016 | 8 | 2010-01-09T21:24:31Z | [
"python"
] | I'm downloading Python 3.1.1 and that comes with the IDLE correct?
I'm also downloading QT for Windows which I'm told is a good GUI framework to work with Python.
What projects should I try to make in order to grasp some of the goodies Python brings to the table?
Thanks a bunch SO. | I highly recommend
> <http://www.diveintopython3.net>
It assumes you already understand programming, and walks you through examples that demonstrate the unique abilities of Python. |
If I use QT For Windows, will my application run great on Linux/Mac/Windows? | 2,035,249 | 5 | 2010-01-09T22:40:26Z | 2,035,272 | 8 | 2010-01-09T22:49:27Z | [
"python",
"qt",
"cross-platform"
] | I'm under the impressions that Python runs in the Triforce smoothly. A program that runs in Windows will run in Linux. Is this sentiment correct?
Having said that, if I create my application in QT For Windows, will it run flawlessly in Linux/Mac as well?
Thanks. | Yes. No. Maybe. See also: Java and "write once, run anywhere".
Filesystem layout, external utilities, anything you might do with things like dock icons, character encoding behaviors, these and more are areas you might run into some trouble.
Using Qt and Python, and strenuously avoiding anything that seems tied to Win... |
Getting a list of errors in a Django form | 2,035,288 | 19 | 2010-01-09T22:53:27Z | 2,035,314 | 38 | 2010-01-09T23:05:03Z | [
"python",
"django",
"django-templates",
"django-forms"
] | I'm trying to create a form in Django. That works and all, but I want all the errors to be at the top of the form, not next to each field that has the error. I tried looping over form.errors, but it only showed the name of the field that had an error, not an error message such as "Name is required."
This is pretty muc... | form.errors is a dictionary. When you do `{% for error in form.errors %}` error corresponds to the key.
Instead try
```
{% for field, errors in form.errors.items %}
{% for error in errors %}
...
```
Etc. |
Python: Why does this doc test fail? | 2,035,406 | 3 | 2010-01-09T23:38:37Z | 2,035,422 | 7 | 2010-01-09T23:43:50Z | [
"python",
"doctest",
"docstring"
] | This code that's in the doctest works when run by itself, but in this doctest it fails in 10 places. I can't figure out why it does though. The following is the entire module:
```
class requireparams(object):
"""
>>> @requireparams(['name', 'pass', 'code'])
>>> def complex_function(params):
>>> pri... | doctest requires that you use `...` for continuation lines:
```
>>> @requireparams(['name', 'pass', 'code'])
... def complex_function(params):
... print(params['name'])
... print(params['pass'])
... print(params['code'])
...
>>> params = {
... 'name': 'John Doe',
... 'pass': 'OpenSesame',
... #... |
python: how to refer to the class from within it ( like the recursive function) | 2,035,423 | 8 | 2010-01-09T23:44:12Z | 2,035,992 | 10 | 2010-01-10T03:45:25Z | [
"python",
"class"
] | For a recursive function we can do:
```
def f(i):
if i<0: return
print i
f(i-1)
f(10)
```
However is there a way to do the following thing?
```
class A:
# do something
some_func(A)
# ...
``` | In Python you cannot reference the class in the class body, although in languages like Ruby you can do it.
In Python instead you can use a class decorator but that will be called once the class has initialized. Another way could be to use metaclass but it depends on what you are trying to achieve. |
What is my current desktop environment? | 2,035,657 | 4 | 2010-01-10T01:06:41Z | 21,213,358 | 8 | 2014-01-19T04:53:06Z | [
"python",
"linux",
"environment"
] | How can I get to know what my desktop environment is using Python? I like the result to be *gnome* or *KDE* or else. | I use this in one of my projects:
```
def get_desktop_environment(self):
#From http://stackoverflow.com/questions/2035657/what-is-my-current-desktop-environment
# and http://ubuntuforums.org/showthread.php?t=652320
# and http://ubuntuforums.org/showthread.php?t=652320
# and http://u... |
How to mock users and requests in django | 2,036,202 | 39 | 2010-01-10T05:20:46Z | 2,036,644 | 36 | 2010-01-10T09:59:04Z | [
"python",
"django",
"unit-testing",
"mocking"
] | I have django code that interacts with request objects or user objects. For instance something like:
```
foo_model_instance = models.get_or_create_foo_from_user(request.user)
```
If you were going to test with the django python shell or in a unittest, what would you pass in there? Here simply a User object will do, b... | > How do you mock users?
Initialise a `django.contrib.auth.models.User` object. [`User.objects.create_user`](http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/models.py#L105) makes this easy.
> How do you mock requests?
Initialise a [`django.http.HttpRequest`](http://code.djangoproject.com/brows... |
How to mock users and requests in django | 2,036,202 | 39 | 2010-01-10T05:20:46Z | 25,835,403 | 27 | 2014-09-14T16:24:02Z | [
"python",
"django",
"unit-testing",
"mocking"
] | I have django code that interacts with request objects or user objects. For instance something like:
```
foo_model_instance = models.get_or_create_foo_from_user(request.user)
```
If you were going to test with the django python shell or in a unittest, what would you pass in there? Here simply a User object will do, b... | For request, I would use [RequestFactory](https://docs.djangoproject.com/en/stable/topics/testing/advanced/#the-request-factory) included with Django.
```
from django.test.client import RequestFactory
rf = RequestFactory()
get_request = rf.get('/hello/')
post_request = rf.post('/submit/', {'foo': 'bar'})
```
for user... |
Tips on how to parse custom file format | 2,036,236 | 2 | 2010-01-10T05:39:37Z | 2,036,276 | 8 | 2010-01-10T05:58:27Z | [
"python",
"parsing",
"file-format"
] | Sorry about the vague title, but I really don't know how to describe this problem concisely.
I've created a (more or less) simple [domain-specific language](http://en.wikipedia.org/wiki/Domain-specific_language) that I will to use to specify what validation rules to apply to different entities (generally forms submitt... | First off, if you want to learn about parsing, then write your own recursive descent parser. The language you've defined only requires a handful of productions. I suggest using Python's `tokenize` library to spare yourself the boring task of converting a stream of bytes into a stream of tokens.
For practical parsing o... |
How to keep count in a recursive function? [python] | 2,036,772 | 11 | 2010-01-10T10:57:12Z | 2,036,783 | 11 | 2010-01-10T11:01:02Z | [
"python",
"recursion"
] | I wrote a recursive function to find the no. of instances of a substring in the parent string.
The way I am keeping count is by declaring/initialising count as a global variable outside the function's scope. Problem is, it'll give me correct results only the first time the function is run, because after that count != 0... | One way to modify your code would be to use a local function as follows:
```
def countSubStringMatchRecursive(target,key):
def countit(target,key,count):
index=find(target,key)
if index>=0:
target=target[index+len(key):]
count += countit(target,key,count) + 1
return ... |
How to keep count in a recursive function? [python] | 2,036,772 | 11 | 2010-01-10T10:57:12Z | 2,036,833 | 8 | 2010-01-10T11:33:40Z | [
"python",
"recursion"
] | I wrote a recursive function to find the no. of instances of a substring in the parent string.
The way I am keeping count is by declaring/initialising count as a global variable outside the function's scope. Problem is, it'll give me correct results only the first time the function is run, because after that count != 0... | Your recursive function has O(n^2) performance because it copies the remaining contents of the string each time it finds a match. This is slower than the iterative solution O(n) and unnecessarily so.
You can easily rewrite it to be faster, and at the same time simplify the code and extend its functionality by passing ... |
Listing buildout configuration variables | 2,037,290 | 6 | 2010-01-10T14:35:11Z | 2,038,773 | 14 | 2010-01-10T21:47:50Z | [
"python",
"buildout"
] | I'd like to find out, exactly what variables are available when using zc.buildout. I can always look at the source, but ideally I'd find a list somewhere, or be able to query buildout to find out what **it** thinks are the variables available at any one time. Is this possible? | I found from the [buildout docs](http://pypi.python.org/pypi/zc.buildout#annotated-sections) that
`bin/buildout annotate`
was what I was looking for. |
Django test runner not finding tests | 2,037,364 | 23 | 2010-01-10T14:57:35Z | 2,039,219 | 9 | 2010-01-11T00:10:50Z | [
"python",
"django",
"unit-testing"
] | I am new to both Python and Django and I'm learning by creating a diet management site but I've been completely defeated by getting my unit tests to run. All the docs and blogs I've found say that as long as it's discoverable from tests.py, tests.py is in the same folder as models.py and your test class subclasses Test... | Worked it out.
It turns out I had done `django-admin.py startproject pyDietTracker` but not `python manage.py startapp myApp`. After going back and doing this, it did work as documented. It would appear I have a lot to learn about reading and the difference between a site and an app in Django.
Thank you for your help... |
Django test runner not finding tests | 2,037,364 | 23 | 2010-01-10T14:57:35Z | 4,747,444 | 61 | 2011-01-20T13:03:25Z | [
"python",
"django",
"unit-testing"
] | I am new to both Python and Django and I'm learning by creating a diet management site but I've been completely defeated by getting my unit tests to run. All the docs and blogs I've found say that as long as it's discoverable from tests.py, tests.py is in the same folder as models.py and your test class subclasses Test... | I had the same issue but my problem was different.
I was getting 0 tests Ran as OP.
But it turns out the test methods inside your test class must start with keyword 'test' to run.
Example:
```
from django.test import TestCase
class FooTest(TestCase):
def setUp(self):
pass
def tearDown(self):
... |
Django test runner not finding tests | 2,037,364 | 23 | 2010-01-10T14:57:35Z | 25,820,203 | 12 | 2014-09-13T05:43:59Z | [
"python",
"django",
"unit-testing"
] | I am new to both Python and Django and I'm learning by creating a diet management site but I've been completely defeated by getting my unit tests to run. All the docs and blogs I've found say that as long as it's discoverable from tests.py, tests.py is in the same folder as models.py and your test class subclasses Test... | if you're using a `yourapp/tests` package/style for unittests, make sure theres a `__init__.py` in there (since thats what makes it a python module!) |
How to use Python and Google's Protocol Buffers to deserialize data sent over TCP | 2,038,083 | 16 | 2010-01-10T18:45:29Z | 2,038,176 | 36 | 2010-01-10T19:06:16Z | [
"python",
"tcp",
"protocol-buffers"
] | I'm trying to write an application which uses Google's protocol buffers to deserialize data (sent from another application using protocol buffers) over a TCP connection. The problem is that it looks as if protocol buffers in Python can only deserialize data from a string. Since TCP doesn't have well-defined message bou... | Don't just write the serialized data to the socket. First send a fixed-size field containing the length of the serialized object.
The sending side is roughly:
```
socket.write(struct.pack("H", len(data)) #send a two-byte size field
socket.write(data)
```
And the recv'ing side becomes something like:
```
dataToRe... |
Integration of Python console into a GUI C++ application | 2,038,247 | 24 | 2010-01-10T19:26:09Z | 2,038,319 | 11 | 2010-01-10T19:45:22Z | [
"c++",
"python",
"multithreading",
"user-interface",
"integration"
] | I'm going to add a python console widget (into a C++ GUI) below some other controls:

Many classes are going to be exposed to the python code, including some access to GUI (maybe I'll consider PyQt).
> Should I run the P... | Since you're apparently wanting to embed a Python interpreter to use Python as a scripting language in a what seems to be a Qt application, I suggest you have a look at [PythonQt](http://pythonqt.sourceforge.net/).
With the PythonQt module, Python scripts will be able to interact with the GUI of your host application.... |
What optimizations does Python do without the -O flags? | 2,038,481 | 4 | 2010-01-10T20:26:27Z | 2,038,502 | 9 | 2010-01-10T20:31:52Z | [
"python",
"optimization",
"bytecode"
] | I had always assumed that the Python interpreter did no optimizations without a `-O` flag, but the following is a bit strange:
```
>>> def foo():
... print '%s' % 'Hello world'
...
>>> from dis import dis
>>> dis(foo)
2 0 LOAD_CONST 3 ('Hello world')
3 PRINT_ITEM
... | Yep, it does do constant folding, here's a simpler example:
```
>>> def f(): return 23+100
...
>>> dis.dis(f)
1 0 LOAD_CONST 3 (123)
3 RETURN_VALUE
>>>
```
No way to block this (except by changing sources) AFAIK.
**Edit**: for all the optimization flow, see [peephole.... |
Python's subprocess.Popen() and source | 2,038,575 | 4 | 2010-01-10T20:55:03Z | 2,038,603 | 7 | 2010-01-10T21:03:19Z | [
"python",
"bash"
] | A third-party Python 2.5 script I'm trying to debug has got me stymied. The relevant part of the script is:
```
proc = subprocess.Popen(
"ls && source houdini_setup",
shell = True,
executable = "/bin/bash",
)
```
There is a daemon that listens to port... | `source` uses `$PATH` to find what you pass to it, if you don't specify a directory. Try `source ./houdini_setup`. |
scipy linregress function erroneous standard error return? | 2,038,667 | 5 | 2010-01-10T21:19:07Z | 2,038,870 | 8 | 2010-01-10T22:15:07Z | [
"python",
"scipy",
"regression"
] | I have a weird situation with scipy.stats.linregress seems to be returning an incorrect standard error:
```
from scipy import stats
x = [5.05, 6.75, 3.21, 2.66]
y = [1.65, 26.5, -5.93, 7.96]
gradient, intercept, r_value, p_value, std_err = stats.linregress(x,y)
>>> gradient
5.3935773611970186
>>> intercept
-16.2811279... | I've just been informed by the SciPy user group that the std\_err here represents the standard error of the gradient line, not the standard error of the predicted y's, as per Excel. Nevertheless users of this function should be careful, because this was not always the behaviour of this library - it used to output exact... |
How should I convert this long and complex PHP style URL query string to a Django url? | 2,039,054 | 2 | 2010-01-10T23:09:43Z | 2,039,079 | 9 | 2010-01-10T23:18:57Z | [
"python",
"django",
"url",
"url-routing"
] | I'm converting a small PHP application to Django.
One section has a long query string, indicating how a widget is to be displayed. There are a few required parameters and several optional ones.
The current urls read like:
```
app.php?id=102030&size=large&auto=0&bw=1&extra=1
```
The id and size are required, but aut... | If you consider that "URL" stands for Uniform *Resource* Locator, the URL should only indicate the resource being displayed, and any 'configuration' options should be passed as parameters. So, I think your first idea is fine. |
python-re: How do I match an alpha character | 2,039,140 | 14 | 2010-01-10T23:43:19Z | 2,039,476 | 36 | 2010-01-11T01:41:48Z | [
"python",
"regex",
"unicode",
"regex-negation"
] | How can I match an alpha character with a regular expression. I want a character that is in `\w` but is not in `\d`. I want it unicode compatible that's why I cannot use `[a-zA-Z]`. | Your first two sentences contradict each other. "in `\w` but is not in `\d`" includes underscore. I'm assuming from your third sentence that you don't want underscore.
Using a Venn diagram on the back of an envelope helps. Let's look at what we DON'T want:
(1) characters that are not matched by `\w` (i.e. don't want ... |
How to trigger Google Analytics events from Python? | 2,039,583 | 21 | 2010-01-11T02:18:17Z | 2,100,975 | 11 | 2010-01-20T11:30:39Z | [
"python",
"events",
"google-analytics",
"tracking"
] | I'm developing a site that has a REST API and I'd like to track the API usage using Google Analytics events. Is there a straightforward way to trigger GA events from Python that doesn't involve loading up an entire `webbrowser` component just to send a javascript request? | There is an open source implementation of Google-Analytics for Mobile in python available here: <http://github.com/b1tr0t/Google-Analytics-for-Mobile--python->
> You can probably integrate this into
> your own setup by importing
> 'track\_page\_view' and providing it
> with the appropriate WSGI request
> environment. |
How to trigger Google Analytics events from Python? | 2,039,583 | 21 | 2010-01-11T02:18:17Z | 12,973,600 | 12 | 2012-10-19T11:47:01Z | [
"python",
"events",
"google-analytics",
"tracking"
] | I'm developing a site that has a REST API and I'd like to track the API usage using Google Analytics events. Is there a straightforward way to trigger GA events from Python that doesn't involve loading up an entire `webbrowser` component just to send a javascript request? | [This project](https://github.com/kra3/py-ga-mob) called PyGA is much better. Unlike "Google-Analytics for Mobile" project on github it is well documentated and has rich API. |
Python "from xxx.yyy import xxx" error | 2,039,823 | 3 | 2010-01-11T03:54:27Z | 2,039,832 | 11 | 2010-01-11T03:57:27Z | [
"python"
] | I'm working with the PyFacebook package in Python, and I've seen a number of times people mention that you can write an import statement as follows:
```
from facebook.djangofb import facebook
```
which will alias the "djangofb" module as "facebook." I'm trying to run this from the Python CLI, and it doesn't work beca... | This is the proper way to alias a module via import:
```
import facebook.djangofb as facebook
``` |
Django not recognizing the MEDIA_URL path? | 2,039,889 | 8 | 2010-01-11T04:18:13Z | 2,039,965 | 13 | 2010-01-11T04:49:51Z | [
"python",
"django",
"tinymce"
] | So I'm trying to get TinyMCE up and running on a simple view function, but the path to the tiny\_mce.js file gets screwed up. The file is located at /Users/home/Django/tinyMCE/media/js/tiny\_mce/tiny\_mce.js. I believe that /media/js/tiny\_mce/tiny\_mce.js is correct, as the development server has no access to files ab... | You can either pass it to the template manually as others have suggested or ensure that you are using a [RequestContext](http://docs.djangoproject.com/en/dev/ref/templates/api/#id1) instead of plain Context. RequestContext will automatically populate the context with certain variables including MEDIA\_URL and other med... |
Django not recognizing the MEDIA_URL path? | 2,039,889 | 8 | 2010-01-11T04:18:13Z | 2,040,027 | 7 | 2010-01-11T05:11:02Z | [
"python",
"django",
"tinymce"
] | So I'm trying to get TinyMCE up and running on a simple view function, but the path to the tiny\_mce.js file gets screwed up. The file is located at /Users/home/Django/tinyMCE/media/js/tiny\_mce/tiny\_mce.js. I believe that /media/js/tiny\_mce/tiny\_mce.js is correct, as the development server has no access to files ab... | It looks like ars has answered your *real* question⦠But you'll run into another problem: `MEDIA_URL` must be *different* from `ADMIN_MEDIA_PREFIX`. If they aren't, the `ADMIN_MEDIA_PREFIX` will take precedence. I usually fix this by changing `ADMIN_MEDIA_PREFIX` to `/admin-media/`. |
Django not recognizing the MEDIA_URL path? | 2,039,889 | 8 | 2010-01-11T04:18:13Z | 2,040,098 | 21 | 2010-01-11T05:35:44Z | [
"python",
"django",
"tinymce"
] | So I'm trying to get TinyMCE up and running on a simple view function, but the path to the tiny\_mce.js file gets screwed up. The file is located at /Users/home/Django/tinyMCE/media/js/tiny\_mce/tiny\_mce.js. I believe that /media/js/tiny\_mce/tiny\_mce.js is correct, as the development server has no access to files ab... | It looks like your are using the debug server (your url is <http://127.0.0.1:8000/>...) . Did you install the static serve in your urls.py?
```
if settings.DEBUG:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes':True}),... |
Django One-To-Many Models | 2,039,958 | 11 | 2010-01-11T04:46:32Z | 2,039,971 | 22 | 2010-01-11T04:51:49Z | [
"python",
"django",
"model",
"one-to-many"
] | The following models describe a vulnerability and the URLs out on the internet that reference that vulnerability. Assume that each URL only ever talks about 1 vulnerability, and that many URLs will discuss that vulnerability. Is this the correct way to lay out the model?
```
class Vuln(models.Model):
pub_date = mode... | It should be more like this:
```
class Vuln(models.Model):
pub_date = models.DateTimeField("Publication Date")
short_description = models.CharField("Description", max_length=70)
vendor = models.ForeignKey(Vendor, verbose_name="Vendor")
class Url(models.Model):
url = models.URLField("URL", max_length=200)
... |
Sorting datetime objects while ignoring the year? | 2,040,038 | 7 | 2010-01-11T05:13:53Z | 2,040,058 | 7 | 2010-01-11T05:19:41Z | [
"python",
"datetime",
"sorting"
] | I have a list of birthdays stored in [`datetime`](http://docs.python.org/library/datetime.html#datetime-objects) objects. How would one go about sorting these in Python using only the `month` and `day` arguments?
For example,
```
[
datetime.datetime(1983, 1, 1, 0, 0)
datetime.datetime(1996, 1, 13, 0 ,0)
d... | ```
l.sort(key = lambda x: x.timetuple()[1:3])
``` |
Sorting datetime objects while ignoring the year? | 2,040,038 | 7 | 2010-01-11T05:13:53Z | 2,040,062 | 10 | 2010-01-11T05:22:11Z | [
"python",
"datetime",
"sorting"
] | I have a list of birthdays stored in [`datetime`](http://docs.python.org/library/datetime.html#datetime-objects) objects. How would one go about sorting these in Python using only the `month` and `day` arguments?
For example,
```
[
datetime.datetime(1983, 1, 1, 0, 0)
datetime.datetime(1996, 1, 13, 0 ,0)
d... | You can use `month` and `day` to create a value that can be used for sorting:
```
birthdays.sort(key = lambda d: (d.month, d.day))
``` |
Using object id as a hash for objects in Python | 2,040,101 | 7 | 2010-01-11T05:36:30Z | 2,040,110 | 12 | 2010-01-11T05:39:50Z | [
"python",
"hash"
] | Is it wise to use the object `id` as a hash key (via. the `__hash__`) to be able to hash an otherwise mutable object for a single instance of a program? Using the object attributes would be nicer but they're all mutable and can change.
This occurred to me while looking at <http://stackoverflow.com/questions/2038010/se... | Yes, as long as you also define `__eq__` (and presumably `__ne__`!-) consistently with that. IOW, it's fine, as long as you're fine with `a==b` meaning exactly the same as `a is b`!-) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.