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 |
|---|---|---|---|---|---|---|---|---|---|
Nicest way to pad zeroes to string | 339,007 | 647 | 2008-12-03T22:39:51Z | 14,269,071 | 28 | 2013-01-10T23:19:37Z | [
"python",
"string"
] | What is the nicest/shortest way to pad a string with zeroes to the left, so the string length has a specific length? | ```
>>> '99'.zfill(5)
'00099'
>>> '99'.rjust(5,'0')
'00099'
```
if you want the opposite:
```
>>> '99'.ljust(5,'0')
'99000'
``` |
Nicest way to pad zeroes to string | 339,007 | 647 | 2008-12-03T22:39:51Z | 24,386,708 | 24 | 2014-06-24T12:31:08Z | [
"python",
"string"
] | What is the nicest/shortest way to pad a string with zeroes to the left, so the string length has a specific length? | Works in both Python 2 and Python 3:
```
>>> "{:0>2}".format("1") # Works for both numbers and strings.
'01'
>>> "{:02}".format(1) # Only works for numbers.
'01'
``` |
How do you unzip very large files in python? | 339,053 | 15 | 2008-12-03T23:00:54Z | 339,506 | 16 | 2008-12-04T03:08:28Z | [
"python",
"compression",
"zip",
"unzip"
] | Using python 2.4 and the built-in `ZipFile` library, I cannot read very large zip files (greater than 1 or 2 GB) because it wants to store the entire contents of the uncompressed file in memory. Is there another way to do this (either with a third-party library or some other hack), or must I "shell out" and unzip it th... | Here's an outline of decompression of large files.
```
import zipfile
import zlib
import os
src = open( doc, "rb" )
zf = zipfile.ZipFile( src )
for m in zf.infolist():
# Examine the header
print m.filename, m.header_offset, m.compress_size, repr(m.extra), repr(m.comment)
src.seek( m.header_offset )
... |
Writing a compiler for a DSL in python | 339,217 | 5 | 2008-12-04T00:17:14Z | 339,235 | 7 | 2008-12-04T00:24:14Z | [
"python",
"dsl",
"dsl-tools"
] | I am writing a game in python and have decided to create a DSL for the map data files. I know I could write my own parser with regex, but I am wondering if there are existing python tools which can do this more easily, like re2c which is used in the PHP engine.
Some extra info:
* Yes, I *do* need a DSL, and even if I... | There are plenty of Python parsing tools: <http://nedbatchelder.com/text/python-parsers.html> |
Writing a compiler for a DSL in python | 339,217 | 5 | 2008-12-04T00:17:14Z | 339,308 | 11 | 2008-12-04T01:02:53Z | [
"python",
"dsl",
"dsl-tools"
] | I am writing a game in python and have decided to create a DSL for the map data files. I know I could write my own parser with regex, but I am wondering if there are existing python tools which can do this more easily, like re2c which is used in the PHP engine.
Some extra info:
* Yes, I *do* need a DSL, and even if I... | I've always been impressed by [pyparsing](http://pyparsing.wikispaces.com/). The author, Paul McGuire, is active on the [python list](http://mail.python.org/mailman/listinfo/python-list)/[comp.lang.python](http://groups.google.com/group/comp.lang.python) and has always been very helpful with any queries concerning it. |
End-line characters from lines read from text file, using Python | 339,537 | 26 | 2008-12-04T03:39:07Z | 339,579 | 17 | 2008-12-04T04:13:21Z | [
"python"
] | When reading lines from a text file using python, the end-line character often needs to be truncated before processing the text, as in the following example:
```
f = open("myFile.txt", "r")
for line in f:
line = line[:-1]
# do something with line
```
Is there an elegant way or idiom for retrie... | Simple. Use **splitlines()**
```
L = open("myFile.txt", "r").read().splitlines();
for line in L:
process(line) # this 'line' will not have '\n' character at the end
``` |
End-line characters from lines read from text file, using Python | 339,537 | 26 | 2008-12-04T03:39:07Z | 339,842 | 43 | 2008-12-04T08:04:19Z | [
"python"
] | When reading lines from a text file using python, the end-line character often needs to be truncated before processing the text, as in the following example:
```
f = open("myFile.txt", "r")
for line in f:
line = line[:-1]
# do something with line
```
Is there an elegant way or idiom for retrie... | The *idiomatic* way to do this in Python is to use **rstrip('\n')**:
```
for line in open('myfile.txt'): # opened in text-mode; all EOLs are converted to '\n'
line = line.rstrip('\n')
process(line)
```
Each of the other alternatives has a gotcha:
* **file('...').read().splitlines()** has to load the whole f... |
Is rewriting a PHP app into Python a productive step? | 340,318 | 6 | 2008-12-04T11:48:19Z | 340,338 | 14 | 2008-12-04T11:54:58Z | [
"php",
"python"
] | I have some old apps written in PHP that I'm thinking of converting to Python - both are websites that started as simple static html, then progressed to PHP and now include blogs with admin areas, rss etc. I'm thinking of rewriting them in Python to improve maintainability as well as to take advantage of my increase in... | You need to take some parts into mind here,
1. What will you gain from re-writing
2. Is it an economically wise decision
3. Will the code be easier to handle for new programmers
4. Performance-wise, will this be a good option?
These four points is something that is important, will the work be more efficient after you... |
Suppressing Output of Paramiko SSHClient Class | 340,341 | 4 | 2008-12-04T11:56:59Z | 340,896 | 7 | 2008-12-04T15:08:27Z | [
"python",
"paramiko"
] | When I call the connect function of the Paramiko `SSHClient` class, it outputs some log data about establishing the connection, which I would like to suppress.
Is there a way to do this either through Paramiko itself, or Python in general? | Paramiko doesn't output anything by default. You probably have a call to the logging module, setting a loglevel that's inherited when paramiko sets up it's own logging.
If you want to get at the paramiko logger to override the settings:
```
logger = paramiko.util.logging.getLogger()
```
There's also a convenience fu... |
Can I install Python 3.x and 2.x on the same computer? | 341,184 | 69 | 2008-12-04T16:18:57Z | 341,218 | 28 | 2008-12-04T16:29:38Z | [
"python",
"windows",
"python-3.x",
"compatibility"
] | I'm running Windows and the shell/OS automatically runs Python based on the registry settings when you run a program on the command line. Will this break if I install a 2.x and 3.x version of Python on the same machine?
I want to play with Python 3 while still being able to run 2.x scripts on the same machine. | You can have both installed.
You should write in front of your script :
```
#!/bin/env python2.6
```
or eventually..
```
#!/bin/env python3.0
```
## Update
My solution work perfectly with Unix, after a quick search on [Google](http://news.softpedia.com/news/Your-First-Python-Script-on-Windows-81974.shtml), here i... |
Can I install Python 3.x and 2.x on the same computer? | 341,184 | 69 | 2008-12-04T16:18:57Z | 436,455 | 9 | 2009-01-12T18:26:55Z | [
"python",
"windows",
"python-3.x",
"compatibility"
] | I'm running Windows and the shell/OS automatically runs Python based on the registry settings when you run a program on the command line. Will this break if I install a 2.x and 3.x version of Python on the same machine?
I want to play with Python 3 while still being able to run 2.x scripts on the same machine. | I'm using 2.5, 2.6, and 3.0 from the shell with one line batch scripts of the form:
```
:: The @ symbol at the start turns off the prompt from displaying the command.
:: The % represents an argument, while the * means all of them.
@c:\programs\pythonX.Y\python.exe %*
```
Name them `pythonX.Y.bat` and put them somewhe... |
Can I install Python 3.x and 2.x on the same computer? | 341,184 | 69 | 2008-12-04T16:18:57Z | 762,725 | 7 | 2009-04-18T01:45:53Z | [
"python",
"windows",
"python-3.x",
"compatibility"
] | I'm running Windows and the shell/OS automatically runs Python based on the registry settings when you run a program on the command line. Will this break if I install a 2.x and 3.x version of Python on the same machine?
I want to play with Python 3 while still being able to run 2.x scripts on the same machine. | Here you go...
**winpylaunch.py**
```
#
# Looks for a directive in the form: #! C:\Python30\python.exe
# The directive must start with #! and contain ".exe".
# This will be assumed to be the correct python interpreter to
# use to run the script ON WINDOWS. If no interpreter is
# found then the script will be run with... |
Can I install Python 3.x and 2.x on the same computer? | 341,184 | 69 | 2008-12-04T16:18:57Z | 13,297,878 | 35 | 2012-11-08T21:11:48Z | [
"python",
"windows",
"python-3.x",
"compatibility"
] | I'm running Windows and the shell/OS automatically runs Python based on the registry settings when you run a program on the command line. Will this break if I install a 2.x and 3.x version of Python on the same machine?
I want to play with Python 3 while still being able to run 2.x scripts on the same machine. | The official solution for coexistence seems to be the [Python Launcher for Windows](http://blog.python.org/2011/07/python-launcher-for-windows_11.html), PEP 397 which was included in [Python 3.3.0](http://www.python.org/download/releases/3.3.0/). Installing the release dumps `py.exe` and `pyw.exe` launchers into `%SYST... |
Can I install Python 3.x and 2.x on the same computer? | 341,184 | 69 | 2008-12-04T16:18:57Z | 32,195,996 | 7 | 2015-08-25T05:15:42Z | [
"python",
"windows",
"python-3.x",
"compatibility"
] | I'm running Windows and the shell/OS automatically runs Python based on the registry settings when you run a program on the command line. Will this break if I install a 2.x and 3.x version of Python on the same machine?
I want to play with Python 3 while still being able to run 2.x scripts on the same machine. | Here's my setup:
1. Install both Python 2.7 and 3.4 with the [windows installers](https://www.python.org/downloads/).
2. Go to `C:\Python34` (the default install path) and change python.exe to python3.exe
3. **Edit** [your environment variables](https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs... |
Python Decorators run before function it is decorating is called? | 341,379 | 4 | 2008-12-04T17:13:32Z | 341,389 | 19 | 2008-12-04T17:17:27Z | [
"python",
"django",
"decorator"
] | As an example,
```
def get_booking(f=None):
print "Calling get_booking Decorator"
def wrapper(request, **kwargs):
booking = _get_booking_from_session(request)
if booking == None:
# we don't have a booking in our session.
return HttpRedirect('/')
else:
... | I believe python decorators are just syntactic sugar.
```
@foo
def bar ():
pass
```
is the same thing as
```
def bar ():
pass
bar = foo(bar)
```
As you can see, *foo* is being called even though *bar* has not been called. This is why you see the output from your decorator function. Your output should contai... |
Python logging in Django | 342,434 | 39 | 2008-12-04T23:24:26Z | 343,575 | 13 | 2008-12-05T11:35:08Z | [
"python",
"django",
"logging"
] | I'm developing a Django app, and I'm trying to use Python's logging module for error/trace logging. Ideally I'd like to have different loggers configured for different areas of the site. So far I've got all of this working, but one thing has me scratching my head.
I have the root logger going to sys.stderr, and I have... | Difficult to comment on your specific case. If settings.py is executed twice, then it's normal that you get two lines for every log sent.
The way we set it up in our projects is to have one module dedicated to logging. That modules has a "module singleton" pattern, so that we only execute the interesting code once.
I... |
Python logging in Django | 342,434 | 39 | 2008-12-04T23:24:26Z | 345,669 | 28 | 2008-12-06T01:06:01Z | [
"python",
"django",
"logging"
] | I'm developing a Django app, and I'm trying to use Python's logging module for error/trace logging. Ideally I'd like to have different loggers configured for different areas of the site. So far I've got all of this working, but one thing has me scratching my head.
I have the root logger going to sys.stderr, and I have... | Allow me to answer my own question. The underlying problem here is that settings.py gets imported twice, or maybe even more (See [here](http://www.mail-archive.com/django-users@googlegroups.com/msg39059.html)). (I still don't understand why this is. Maybe some Django expert could explain that to me.) This seems to be t... |
Python logging in Django | 342,434 | 39 | 2008-12-04T23:24:26Z | 3,983,086 | 23 | 2010-10-20T23:23:54Z | [
"python",
"django",
"logging"
] | I'm developing a Django app, and I'm trying to use Python's logging module for error/trace logging. Ideally I'd like to have different loggers configured for different areas of the site. So far I've got all of this working, but one thing has me scratching my head.
I have the root logger going to sys.stderr, and I have... | As of version 1.3, Django uses standard python logging, configured with the `LOGGING` setting (documented here: [1.3](http://docs.djangoproject.com/en/1.3/ref/settings/#std%3asetting-LOGGING), [dev](http://docs.djangoproject.com/en/dev/ref/settings/#std%3asetting-LOGGING)).
Django logging reference: [1.3](http://docs.... |
Python logging in Django | 342,434 | 39 | 2008-12-04T23:24:26Z | 5,889,904 | 9 | 2011-05-04T21:09:10Z | [
"python",
"django",
"logging"
] | I'm developing a Django app, and I'm trying to use Python's logging module for error/trace logging. Ideally I'd like to have different loggers configured for different areas of the site. So far I've got all of this working, but one thing has me scratching my head.
I have the root logger going to sys.stderr, and I have... | Reviving an old thread, but I was experiencing duplicate messages while using Django 1.3 Python logging with the [dictConfig format](http://docs.python.org/library/logging.config.html#configuration-dictionary-schema).
The `disable_existing_loggers` gets rid of the duplicate handler/logging problem with multiple settin... |
Best way to import version-specific python modules | 342,437 | 13 | 2008-12-04T23:28:10Z | 342,484 | 27 | 2008-12-04T23:57:33Z | [
"python",
"migration",
"module",
"code-migration"
] | Which method makes the most sense for importing a module in python that is version specific? My use case is that I'm writing code that will be deployed into a python 2.3 environment and in a few months be upgraded to python 2.5. This:
```
if sys.version_info[:2] >= (2, 5):
from string import Template
else:
fro... | Always the second way - you never know what different Python installations will have installed. `Template` is a specific case where it matters less, but when you test for the capability instead of the versioning you're always more robust.
That's how I make [Testoob](http://www.testoob.org) support Python 2.2 - 2.6: I ... |
How should I learn to use the Windows API with Python? | 342,729 | 17 | 2008-12-05T02:20:30Z | 342,740 | 28 | 2008-12-05T02:26:44Z | [
"python",
"winapi"
] | I have very little experience building software for Windows, and zero experience using the Windows API, but I'm reasonably familiar with Python. So, how should I go about learning to use the Windows API with Python? | Honestly, no. The Windows API is an 800 pound monster covered with hair. [Charlie Petzold's 15 pound book](http://www.charlespetzold.com/faq.html) was the canonical reference once upon a time.
That said, the [Python for Windows](http://python.net/crew/mhammond/win32/) folks have some good material. Microsoft has the [... |
How should I learn to use the Windows API with Python? | 342,729 | 17 | 2008-12-05T02:20:30Z | 343,804 | 7 | 2008-12-05T13:19:43Z | [
"python",
"winapi"
] | I have very little experience building software for Windows, and zero experience using the Windows API, but I'm reasonably familiar with Python. So, how should I go about learning to use the Windows API with Python? | Avoid tutorials (written by kids, for kids, newbie level)
Read the Petzold, Richter, Pietrek, Russinovich and Adv. Win32 api newsgroup
news://comp.os.ms-windows.programmer.win32 |
How should I learn to use the Windows API with Python? | 342,729 | 17 | 2008-12-05T02:20:30Z | 350,143 | 18 | 2008-12-08T16:53:44Z | [
"python",
"winapi"
] | I have very little experience building software for Windows, and zero experience using the Windows API, but I'm reasonably familiar with Python. So, how should I go about learning to use the Windows API with Python? | About 4 years ago I set out to truly understand the Windows API. I was coding in C# at the time, but I felt like the framework was abstracting me too much from the API (which it was). So I switched to Delphi (C++ or C would have also been good choices).
In my opinion, it is important that you start working in a langua... |
What happened to the python bindings for CGAL? | 343,210 | 7 | 2008-12-05T08:36:49Z | 13,081,921 | 10 | 2012-10-26T06:32:58Z | [
"python",
"geometry",
"polygon",
"computational-geometry",
"cgal"
] | I found the [Computational Geometry Algorithms Library](http://www.cgal.org/) in my search for an algorithm to decompose a concave polygon into the minimum number of convex components. Links off the site and numerous google results indicate there are python bindings for it, which would be really handy, but all the link... | A rewrite of the CGAL-Python bindings has been done as part of the cgal-bindings project. Check it out : <http://code.google.com/p/cgal-bindings/> |
What can Pygame do in terms of graphics that wxPython can't? | 343,505 | 16 | 2008-12-05T11:03:36Z | 344,002 | 19 | 2008-12-05T14:35:58Z | [
"python",
"graphics",
"wxpython",
"pygame"
] | I want to develop a very simple 2D game in Python. Pygame is the most popular library for game development in Python, but I'm already quite familiar with wxPython and feel comfortable using it. I've even written a [Tetris clone](http://eli.thegreenplace.net/2008/05/31/a-tetris-clone-in-python-wxpython/) in it, and it w... | Well, in theory there is nothing you can do with Pygame that you can't with wxPython. The point is not what but how. In my opinion, it's easier to write a game with PyGame becasue:
* It's faster. Pygame is based on SDL which is a C library specifically designed for games, it has been developed with speed in mind. When... |
What can Pygame do in terms of graphics that wxPython can't? | 343,505 | 16 | 2008-12-05T11:03:36Z | 344,045 | 13 | 2008-12-05T14:53:07Z | [
"python",
"graphics",
"wxpython",
"pygame"
] | I want to develop a very simple 2D game in Python. Pygame is the most popular library for game development in Python, but I'm already quite familiar with wxPython and feel comfortable using it. I've even written a [Tetris clone](http://eli.thegreenplace.net/2008/05/31/a-tetris-clone-in-python-wxpython/) in it, and it w... | wxPython is based on [wxWidgets](http://wxwidgets.org/) which is a GUI-oriented toolkit. It has the advantage of using the styles and decorations provided by the system it runs on and thus it is very easy to write portable applications that integrate nicely into the look and feel of whatever you're running. You want a ... |
How to convert from UTM to LatLng in python or Javascript | 343,865 | 23 | 2008-12-05T13:42:34Z | 343,961 | 10 | 2008-12-05T14:21:28Z | [
"javascript",
"python",
"gis",
"arcgis-js-api",
"proj4js"
] | I have a bunch of files with coordinates in UTM form. For each coordinate I have easting, northing and zone. I need to convert this to LatLng for use with Google Map API to show the information in a map.
I have found some online calculators that does this, but no actual code or libraries. <http://trac.osgeo.org/proj4j... | What I found is the following site: <http://home.hiwaay.net/~taylorc/toolbox/geography/geoutm.html>
It has a javascript converter, you should check the algorithm there. From the page:
> Programmers: The JavaScript source code in this document may be copied and reused without restriction. |
How to convert from UTM to LatLng in python or Javascript | 343,865 | 23 | 2008-12-05T13:42:34Z | 344,060 | 8 | 2008-12-05T14:58:52Z | [
"javascript",
"python",
"gis",
"arcgis-js-api",
"proj4js"
] | I have a bunch of files with coordinates in UTM form. For each coordinate I have easting, northing and zone. I need to convert this to LatLng for use with Google Map API to show the information in a map.
I have found some online calculators that does this, but no actual code or libraries. <http://trac.osgeo.org/proj4j... | According to this page, UTM is supported by proj4js.
<http://trac.osgeo.org/proj4js/wiki/UserGuide#Supportedprojectionclasses>
You may also want to take a look at [GDAL](http://gdal.org). The gdal library has excellent python support, though it may be a bit overkill if you're only doing projection conversion. |
How to convert from UTM to LatLng in python or Javascript | 343,865 | 23 | 2008-12-05T13:42:34Z | 344,083 | 31 | 2008-12-05T15:04:59Z | [
"javascript",
"python",
"gis",
"arcgis-js-api",
"proj4js"
] | I have a bunch of files with coordinates in UTM form. For each coordinate I have easting, northing and zone. I need to convert this to LatLng for use with Google Map API to show the information in a map.
I have found some online calculators that does this, but no actual code or libraries. <http://trac.osgeo.org/proj4j... | I ended up finding java code from IBM that solved it: <http://www.ibm.com/developerworks/java/library/j-coordconvert/index.html>
Just for reference, here is my python implementation of the method I needed:
```
import math
def utmToLatLng(zone, easting, northing, northernHemisphere=True):
if not northernHemispher... |
Django Admin's "view on site" points to example.com instead of my domain | 344,851 | 22 | 2008-12-05T19:23:11Z | 344,909 | 21 | 2008-12-05T19:46:26Z | [
"python",
"django",
"django-admin"
] | I added a `get_absolute_url` function to one of my models.
```
def get_absolute_url(self):
return '/foo/bar'
```
The admin site picks it up and adds a "view on site" link to the detail page for that object (when I put a real URL there instead of "/foo/bar").
The problem is instead of going to `http://localhost:8... | You have to change [default site](http://docs.djangoproject.com/en/dev/ref/contrib/sites/#ref-contrib-sites) domain value. |
Is this idiom pythonic? (someBool and "True Result" or "False Result") | 345,745 | 7 | 2008-12-06T01:57:04Z | 345,773 | 17 | 2008-12-06T02:14:46Z | [
"coding-style",
"python"
] | I just came across this idiom in some open-source Python, and I choked on my drink.
Rather than:
```
if isUp:
return "Up"
else:
return "Down"
```
or even:
```
return "Up" if isUp else "Down"
```
the code read:
```
return isUp and "Up" or "Down"
```
I can see this is the same result, but is this a typical... | The "a and b or c" idiom was the canonical way to express the ternary arithmetic if in Python, before [PEP 308](http://www.python.org/dev/peps/pep-0308/) was written and implemented. This idiom fails the "b" answer is false itself; to support the general case, you could write
```
return (a and [b] or [c])[0]
```
An ... |
Is this idiom pythonic? (someBool and "True Result" or "False Result") | 345,745 | 7 | 2008-12-06T01:57:04Z | 345,775 | 9 | 2008-12-06T02:20:46Z | [
"coding-style",
"python"
] | I just came across this idiom in some open-source Python, and I choked on my drink.
Rather than:
```
if isUp:
return "Up"
else:
return "Down"
```
or even:
```
return "Up" if isUp else "Down"
```
the code read:
```
return isUp and "Up" or "Down"
```
I can see this is the same result, but is this a typical... | You should read [Using the and-or trick](http://www.diveintopython.net/power_of_introspection/and_or.html) (section 4.6.1) of *Dive Into Python* by Mark Pilgrim. It turns out that the and-or trick has major pitfalls you should be aware of. |
Python - No handlers could be found for logger "OpenGL.error" | 345,991 | 64 | 2008-12-06T05:59:43Z | 346,501 | 156 | 2008-12-06T17:18:34Z | [
"python",
"logging",
"opengl",
"wxpython",
"pyopengl"
] | Okay, what is it, and why does it occur on Win2003 server, but not on WinXP.
It doesn't seem to affect my application at all, but I get this error message when I close the application. And it's annoying (as errors messages should be).
I am using pyOpenGl and wxPython to do the graphics stuff. Unfortunately, I'm a C# ... | Looks like OpenGL is trying to report some error on Win2003, however you've not configured your system where to output logging info.
You can add the following to the beginning of your program and you'll see details of the error in stderr.
```
import logging
logging.basicConfig()
```
Checkout documentation on [loggin... |
Postgres - how to return rows with 0 count for missing data? | 346,132 | 9 | 2008-12-06T09:32:04Z | 346,195 | 16 | 2008-12-06T11:30:40Z | [
"python",
"database",
"postgresql"
] | I have unevenly distributed data(wrt date) for a few years (2003-2008). I want to query data for a given set of start and end date, grouping the data by any of the supported intervals (day, week, month, quarter, year) in PostgreSQL 8.3 (<http://www.postgresql.org/docs/8.3/static/functions-datetime.html#FUNCTIONS-DATETI... | You can create the list of all first days of the last year (say) with
```
select distinct date_trunc('month', (current_date - offs)) as date
from generate_series(0,365,28) as offs;
date
------------------------
2007-12-01 00:00:00+01
2008-01-01 00:00:00+01
2008-02-01 00:00:00+01
2008-03-01 00:00:00+01
... |
Postgres - how to return rows with 0 count for missing data? | 346,132 | 9 | 2008-12-06T09:32:04Z | 15,733,103 | 9 | 2013-03-31T18:44:22Z | [
"python",
"database",
"postgresql"
] | I have unevenly distributed data(wrt date) for a few years (2003-2008). I want to query data for a given set of start and end date, grouping the data by any of the supported intervals (day, week, month, quarter, year) in PostgreSQL 8.3 (<http://www.postgresql.org/docs/8.3/static/functions-datetime.html#FUNCTIONS-DATETI... | This question is old. But since fellow users picked it as master for a new duplicate I am adding a proper answer.
### Proper solution
```
SELECT *
FROM (
SELECT day::date
FROM generate_series(timestamp '2007-12-01'
, timestamp '2008-12-01'
, interval '1 month'... |
Read file object as string in python | 346,230 | 26 | 2008-12-06T12:41:36Z | 346,237 | 73 | 2008-12-06T12:47:18Z | [
"python",
"file",
"urllib2"
] | I'm using `urllib2` to read in a page. I need to do a quick regex on the source and pull out a few variables but `urllib2` presents as a file object rather than a string.
I'm new to python so I'm struggling to see how I use a file object to do this. Is there a quick way to convert this into a string? | You can use Python in interactive mode to search for solutions.
if `f` is your object, you can enter `dir(f)` to see all methods and attributes. There's one called `read`. Enter `help(f.read)` and it tells you that `f.read()` is the way to retrieve a string from an file object. |
Read file object as string in python | 346,230 | 26 | 2008-12-06T12:41:36Z | 346,255 | 12 | 2008-12-06T13:07:39Z | [
"python",
"file",
"urllib2"
] | I'm using `urllib2` to read in a page. I need to do a quick regex on the source and pull out a few variables but `urllib2` presents as a file object rather than a string.
I'm new to python so I'm struggling to see how I use a file object to do this. Is there a quick way to convert this into a string? | From the doc [file.read()](http://docs.python.org/library/stdtypes.html#file.read) (my emphasis):
> file.read([size])
>
> Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. **The bytes are retur... |
Format numbers in django templates | 346,467 | 83 | 2008-12-06T16:46:49Z | 346,633 | 11 | 2008-12-06T19:21:33Z | [
"python",
"django"
] | I'm trying to format numbers. Examples:
```
1 => 1
12 => 12
123 => 123
1234 => 1,234
12345 => 12,345
```
It strikes as a fairly common thing to do but I can't figure out which filter I'm supposed to use.
Edit: If you've a generic Python way to do this, I'm happy adding a formatted field in my model. | If you don't want to get involved with locales here is a function that formats numbers:
```
def int_format(value, decimal_points=3, seperator=u'.'):
value = str(value)
if len(value) <= decimal_points:
return value
# say here we have value = '12345' and the default params above
parts = []
wh... |
Format numbers in django templates | 346,467 | 83 | 2008-12-06T16:46:49Z | 347,560 | 162 | 2008-12-07T13:10:22Z | [
"python",
"django"
] | I'm trying to format numbers. Examples:
```
1 => 1
12 => 12
123 => 123
1234 => 1,234
12345 => 12,345
```
It strikes as a fairly common thing to do but I can't figure out which filter I'm supposed to use.
Edit: If you've a generic Python way to do this, I'm happy adding a formatted field in my model. | Django's contributed [humanize](http://docs.djangoproject.com/en/dev/ref/contrib/humanize/#ref-contrib-humanize) application does this:
```
{% load humanize %}
{{ my_num|intcomma }}
```
Be sure to add `'django.contrib.humanize'` to your `INSTALLED_APPS` list in the `settings.py` file. |
Format numbers in django templates | 346,467 | 83 | 2008-12-06T16:46:49Z | 2,180,209 | 47 | 2010-02-01T21:26:44Z | [
"python",
"django"
] | I'm trying to format numbers. Examples:
```
1 => 1
12 => 12
123 => 123
1234 => 1,234
12345 => 12,345
```
It strikes as a fairly common thing to do but I can't figure out which filter I'm supposed to use.
Edit: If you've a generic Python way to do this, I'm happy adding a formatted field in my model. | Regarding Ned Batchelder's solution, here it is with 2 decimal points and a dollar sign.
```
from django.contrib.humanize.templatetags.humanize import intcomma
def currency(dollars):
dollars = round(float(dollars), 2)
return "$%s%s" % (intcomma(int(dollars)), ("%0.2f" % dollars)[-3:])
```
Then you can
```
{... |
Format numbers in django templates | 346,467 | 83 | 2008-12-06T16:46:49Z | 10,859,264 | 54 | 2012-06-02T02:02:31Z | [
"python",
"django"
] | I'm trying to format numbers. Examples:
```
1 => 1
12 => 12
123 => 123
1234 => 1,234
12345 => 12,345
```
It strikes as a fairly common thing to do but I can't figure out which filter I'm supposed to use.
Edit: If you've a generic Python way to do this, I'm happy adding a formatted field in my model. | Building on other answers, to extend this to floats, you can do:
```
{% load humanize %}
{{ floatvalue|floatformat:2|intcomma }}
``` |
Is it more efficient to use "import <module>" or "from <module> import <func>"? | 346,723 | 3 | 2008-12-06T20:25:05Z | 346,753 | 10 | 2008-12-06T20:45:37Z | [
"python",
"import"
] | Say I only needed to use findall() from the re module, is it more efficient to do:
```
from re import findall
```
or
```
import re
```
Is there actually any difference in speed/memory usage etc? | There is no difference on the import, however there is a small difference on access.
When you access the function as
```
re.findall()
```
python will need to first find the module in the global scope and then find findall in modules dict. May make a difference if you are calling it inside a loop thousands of times. |
Is it more efficient to use "import <module>" or "from <module> import <func>"? | 346,723 | 3 | 2008-12-06T20:25:05Z | 346,967 | 8 | 2008-12-06T23:20:18Z | [
"python",
"import"
] | Say I only needed to use findall() from the re module, is it more efficient to do:
```
from re import findall
```
or
```
import re
```
Is there actually any difference in speed/memory usage etc? | When in doubt, time it:
```
from timeit import Timer
print Timer("""re.findall(r"\d+", "fg12f 1414 21af 144")""", "import re").timeit()
print Timer("""findall(r"\d+", "fg12f 1414 21af 144")""", "from re import findall").timeit()
```
I get the following results, using the minimum of 5 repetitions of 10,000,000 calls:... |
Django.contrib.flatpages without models | 346,840 | 6 | 2008-12-06T21:48:55Z | 346,877 | 9 | 2008-12-06T22:08:59Z | [
"python",
"django",
"templates",
"django-flatpages"
] | I have some flatpages with empty `content` field and their content inside the template (given with `template_name` field).
### Why I am using `django.contrib.flatpages`
* It allows me to serve (mostly) static pages with minimal URL configuration.
* I don't have to write views for each of them.
### Why I don't need t... | Using the [`direct_to_template`](https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-simple-direct-to-template) generic view would be a lot simpler. You could use the passed in parameters on one view to specify the actual template in urls.py, if you don't want to add an entry for each page:
`... |
Where do I go from here -- regarding programming? | 347,054 | 3 | 2008-12-07T00:49:52Z | 347,065 | 7 | 2008-12-07T00:58:04Z | [
"php",
"asp.net",
"python",
"linux"
] | I seem to be in a never ending tail spin of Linux, or not, Windows or not. Web programming or system programming. Python or PHP.
I'am self teaching myself programming. But it seems I keep being torn about which way to go. Unfortunately it is always seemingly good reasons to get side tracked. You know the whole open so... | You will only have a first language for a little while. Pick any direction that interests you, and follow it. There is no way around the introduction "Drink from the Firehose" experience.
Keep early project simple, and tangible. Build useful things and the motivation will be there.
Web / desktop / mobile / etc, its a... |
How do I concisely implement multiple similar unit tests in the Python unittest framework? | 347,109 | 14 | 2008-12-07T01:59:49Z | 347,607 | 11 | 2008-12-07T14:07:12Z | [
"python",
"unit-testing"
] | I'm implementing unit tests for a family of functions that all share a number of invariants. For example, calling the function with two matrices produce a matrix of known shape.
I would like to write unit tests to test the entire family of functions for this property, without having to write an individual test case fo... | Here's my favorite approach to the "family of related tests". I like explicit subclasses of a TestCase that expresses the common features.
```
class MyTestF1( unittest.TestCase ):
theFunction= staticmethod( f1 )
def setUp(self):
self.matrix1 = numpy.ones((5,10))
self.matrix2 = numpy.identity(5)... |
Rounding float to the nearest factor? | 347,538 | 6 | 2008-12-07T12:45:15Z | 347,549 | 11 | 2008-12-07T13:00:28Z | [
"python",
"algorithm",
"math"
] | I have a small math problem I am trying to solve
Given a number x and resolution y, I need to find the next x' with the required resolution.
e.g.
```
x = 1.002 y = 0.1 x'= 1.1
x = 0.348 y = 0.1 x'= 0.4
x = 0.50 y = 1 x'= 1
x = 0.32 y = 0.05 x'= 0.35
```
Is there any smart way of doi... | ```
import math
def next_multiple(x, y):
return math.ceil(x/y)*y
def try_it(x, y):
print x, y, next_multiple(x, y)
for x, y in [
(1.002, 0.1),
(0.348, 0.1),
(0.50, 1),
(0.32, 0.05)
]:
try_it(x, y)
```
produces:
```
1.002 0.1 1.1
0.348 0.1 0.4
0.5 1 1.0
0.32 0.05 0.35
```
I think yo... |
How do I get nose to discover dynamically-generated testcases? | 347,574 | 6 | 2008-12-07T13:30:45Z | 676,420 | 7 | 2009-03-24T07:19:15Z | [
"python",
"unit-testing",
"nose"
] | This is a follow-up to a [previous question](http://stackoverflow.com/questions/347109/how-do-i-concisely-implement-multiple-similar-unit-tests-in-the-python-unittest) of mine.
In the previous question, methods were explored to implement what was essentially the same test over an entire family of functions, ensuring t... | Nose has a "test generator" feature for stuff like this. You write a generator function that yields each "test case" function you want it to run, along with its args. Following your previous example, this could check each of the functions in a separate test:
```
import unittest
import numpy
from somewhere import the_... |
Gauss-Legendre Algorithm in python | 347,734 | 12 | 2008-12-07T16:15:40Z | 347,749 | 24 | 2008-12-07T16:29:55Z | [
"python",
"algorithm",
"pi"
] | I need some help calculating Pi. I am trying to write a python program that will calculate Pi to X digits. I have tried several from the python mailing list, and it is to slow for my use.
I have read about the [Gauss-Legendre Algorithm](http://en.wikipedia.org/wiki/Gauss-Legendre_algorithm), and I have tried porting it... | 1. You forgot parentheses around `4*t`:
```
pi = (a+b)**2 / (4*t)
```
2. You can use `decimal` to perform calculation with higher precision.
```
#!/usr/bin/env python
from __future__ import with_statement
import decimal
def pi_gauss_legendre():
D = decimal.Decimal
with decimal.... |
AKS Primes algorithm in Python | 347,811 | 23 | 2008-12-07T17:41:10Z | 347,840 | 42 | 2008-12-07T18:02:27Z | [
"python",
"algorithm",
"primes"
] | A few years ago, it was proven that [PRIMES is in P](http://www.cse.iitk.ac.in/~manindra/algebra/primality_v6.pdf). Are there any algorithms implementing [their primality test](http://en.wikipedia.org/wiki/AKS_primality_test) in Python? I wanted to run some benchmarks with a naive generator and see for myself how fast ... | Quick answer: no, the AKS test is not the fastest way to test primality. There are much *much* faster primality tests that either assume the (generalized) Riemann hypothesis and/or are randomized. (E.g. [Miller-Rabin](http://en.wikipedia.org/wiki/Miller-Rabin_primality_test) is fast and simple to implement.) The real b... |
How to test django caching? | 347,812 | 14 | 2008-12-07T17:41:34Z | 348,079 | 7 | 2008-12-07T21:06:49Z | [
"python",
"django",
"caching",
"django-cache"
] | Is there a way to be **sure** that a page is coming from cache on a production server and on the development server as well?
The solution **shouldn't** involve caching middleware because not every project uses them. Though the solution itself might **be** a middleware.
Just checking if the data is stale is not a very... | Mock the view, hit the page, and see if the mock was called. if it was not, the cache was used instead. |
How to test django caching? | 347,812 | 14 | 2008-12-07T17:41:34Z | 348,546 | 18 | 2008-12-08T02:33:16Z | [
"python",
"django",
"caching",
"django-cache"
] | Is there a way to be **sure** that a page is coming from cache on a production server and on the development server as well?
The solution **shouldn't** involve caching middleware because not every project uses them. Though the solution itself might **be** a middleware.
Just checking if the data is stale is not a very... | We do a lot of component caching and not all of them are updated at the same time. So we set host and timestamp values in a universally included context processor. At the top of each template fragment we stick in:
```
<!-- component_name {{host}} {{timestamp}} -->
```
The component\_name just makes it easy to do a Vi... |
How to test django caching? | 347,812 | 14 | 2008-12-07T17:41:34Z | 5,563,503 | 12 | 2011-04-06T08:32:14Z | [
"python",
"django",
"caching",
"django-cache"
] | Is there a way to be **sure** that a page is coming from cache on a production server and on the development server as well?
The solution **shouldn't** involve caching middleware because not every project uses them. Though the solution itself might **be** a middleware.
Just checking if the data is stale is not a very... | Peter Rowells suggestion works well, but you don't need a custom template context processor
for timestamps. You can simply use the template tag:
```
<!-- {% now "jS F Y H:i" %} -->
``` |
What could justify the complexity of Plone? | 348,044 | 12 | 2008-12-07T20:41:40Z | 348,317 | 7 | 2008-12-07T23:30:53Z | [
"python",
"content-management-system",
"plone",
"zope"
] | Plone is very complex. [Zope](http://en.wikipedia.org/wiki/Zope)2, [Zope3](http://en.wikipedia.org/wiki/Zope_3), [Five](http://codespeak.net/z3/five/), [ZCML](http://wiki.zope.org/zope3/ZCML), [ZODB](http://en.wikipedia.org/wiki/Zope_Object_Database), [ZEO](http://en.wikipedia.org/wiki/Zope_Object_Database#ZEO), a whol... | I see four things that can justify an investment of time in using Plone:
* Plone has a large and helpful community. Most of the things you need, somebody else
already did at some time in the past. He probably asked some questions and got helpful
answers, or he wrote a tutorial. Usually that leaves traces easy to... |
What could justify the complexity of Plone? | 348,044 | 12 | 2008-12-07T20:41:40Z | 348,508 | 29 | 2008-12-08T01:59:39Z | [
"python",
"content-management-system",
"plone",
"zope"
] | Plone is very complex. [Zope](http://en.wikipedia.org/wiki/Zope)2, [Zope3](http://en.wikipedia.org/wiki/Zope_3), [Five](http://codespeak.net/z3/five/), [ZCML](http://wiki.zope.org/zope3/ZCML), [ZODB](http://en.wikipedia.org/wiki/Zope_Object_Database), [ZEO](http://en.wikipedia.org/wiki/Zope_Object_Database#ZEO), a whol... | It's hard to answer your question without any background information. Is the complexity justified if you just want a blog? No. Is the complexity justified if you're building a company intranet for 400+ people? Yes. Is it a good investment if you're looking to be a consultant? Absolutely! There's a lot of Plone work out... |
What could justify the complexity of Plone? | 348,044 | 12 | 2008-12-07T20:41:40Z | 351,692 | 23 | 2008-12-09T03:29:19Z | [
"python",
"content-management-system",
"plone",
"zope"
] | Plone is very complex. [Zope](http://en.wikipedia.org/wiki/Zope)2, [Zope3](http://en.wikipedia.org/wiki/Zope_3), [Five](http://codespeak.net/z3/five/), [ZCML](http://wiki.zope.org/zope3/ZCML), [ZODB](http://en.wikipedia.org/wiki/Zope_Object_Database), [ZEO](http://en.wikipedia.org/wiki/Zope_Object_Database#ZEO), a whol... | If you want to see the complexity of Plone, you have to ask for it. For most people, it's just not there. It installs in a couple of minutes through a one-click installer. Then it's one click to log in, one click to create a page, use a WYSYWIG editor, and one click to save. Everything is through an intuitive web GUI. ... |
What could justify the complexity of Plone? | 348,044 | 12 | 2008-12-07T20:41:40Z | 446,659 | 9 | 2009-01-15T13:08:53Z | [
"python",
"content-management-system",
"plone",
"zope"
] | Plone is very complex. [Zope](http://en.wikipedia.org/wiki/Zope)2, [Zope3](http://en.wikipedia.org/wiki/Zope_3), [Five](http://codespeak.net/z3/five/), [ZCML](http://wiki.zope.org/zope3/ZCML), [ZODB](http://en.wikipedia.org/wiki/Zope_Object_Database), [ZEO](http://en.wikipedia.org/wiki/Zope_Object_Database#ZEO), a whol... | I found an anonymous comment [here](http://bitubique.com/content/im-done-plone#comment-10) which is much better than that post itself, so I'm reposting it here in full, with a couple of typos corrected.
---
This summer my chess club asked me to make a new website, where the members of the board should be able to add ... |
Creating a list of objects in Python | 348,196 | 42 | 2008-12-07T22:15:46Z | 348,215 | 39 | 2008-12-07T22:22:39Z | [
"python",
"list",
"object",
"loops"
] | I'm trying to create a Python script that opens several databases and compares their contents. In the process of creating that script, I've run into a problem in creating a list whose contents are objects that I've created.
I've simplified the program to its bare bones for this posting. First I create a new class, cre... | You demonstrate a fundamental misunderstanding.
You never created an instance of SimpleClass at all, because you didn't call it.
```
for count in xrange(4):
x = SimpleClass()
x.attr = count
simplelist.append(x)
```
Or, if you let the class take parameters, instead, you can use a list comprehension.
```
... |
Creating a list of objects in Python | 348,196 | 42 | 2008-12-07T22:15:46Z | 348,284 | 7 | 2008-12-07T23:06:58Z | [
"python",
"list",
"object",
"loops"
] | I'm trying to create a Python script that opens several databases and compares their contents. In the process of creating that script, I've run into a problem in creating a list whose contents are objects that I've created.
I've simplified the program to its bare bones for this posting. First I create a new class, cre... | It shouldn't be necessary to recreate the SimpleClass object each time, as some are suggesting, if you're simply using it to output data based on its attributes. However, you're not actually creating an instance of the class; you're simply creating a reference to the class object itself. Therefore, you're adding a refe... |
Creating a list of objects in Python | 348,196 | 42 | 2008-12-07T22:15:46Z | 352,505 | 31 | 2008-12-09T11:50:39Z | [
"python",
"list",
"object",
"loops"
] | I'm trying to create a Python script that opens several databases and compares their contents. In the process of creating that script, I've run into a problem in creating a list whose contents are objects that I've created.
I've simplified the program to its bare bones for this posting. First I create a new class, cre... | To fill a list with seperate instances of a class, you can use a for loop in the declaration of the list. The \* multiply will link each copy to the same instance.
```
instancelist = [ MyClass() for i in range(29)]
```
and then access the instances through the index of the list.
```
instancelist[5].attr1 = 'whamma'
... |
Receive and send emails in python | 348,392 | 29 | 2008-12-08T00:12:25Z | 348,551 | 21 | 2008-12-08T02:36:49Z | [
"python",
"email"
] | How can i receive and send email in python? A 'mail server' of sorts.
I am looking into making an app that listens to see if it recieves an email addressed to foo@bar.domain.com, and sends an email to the sender.
Now, am i able to do this all in python, would it be best to use 3rd party libraries? | Here is a very simple example:
```
import smtplib
server = 'mail.server.com'
user = ''
password = ''
recipients = ['user@mail.com', 'other@mail.com']
sender = 'you@mail.com'
message = 'Hello World'
session = smtplib.SMTP(server)
# if your SMTP server doesn't need authentications,
# you don't need the following line... |
Receive and send emails in python | 348,392 | 29 | 2008-12-08T00:12:25Z | 349,352 | 10 | 2008-12-08T12:23:21Z | [
"python",
"email"
] | How can i receive and send email in python? A 'mail server' of sorts.
I am looking into making an app that listens to see if it recieves an email addressed to foo@bar.domain.com, and sends an email to the sender.
Now, am i able to do this all in python, would it be best to use 3rd party libraries? | I do not think it would be a good idea to write a real mail server in Python. This is certainly possible (see mcrute's and Manuel Ceron's posts to have details) but it is a lot of work when you think of everything that a real mail server must handle (queuing, retransmission, dealing with spam, etc).
You should explain... |
How can I download all emails with attachments from Gmail? | 348,630 | 80 | 2008-12-08T03:57:49Z | 348,649 | 10 | 2008-12-08T04:17:37Z | [
"java",
"python",
"perl",
"gmail"
] | How do I connect to Gmail and determine which messages have attachments? I then want to download each attachment, printing out the Subject: and From: for each message as I process it. | I'm not an expert on Perl, but what I do know is that GMail supports IMAP and POP3, 2 protocols that are completely standard and allow you to do just that.
Maybe that helps you to get started. |
How can I download all emails with attachments from Gmail? | 348,630 | 80 | 2008-12-08T03:57:49Z | 641,843 | 7 | 2009-03-13T08:40:25Z | [
"java",
"python",
"perl",
"gmail"
] | How do I connect to Gmail and determine which messages have attachments? I then want to download each attachment, printing out the Subject: and From: for each message as I process it. | ```
#!/usr/bin/env python
"""Save all attachments for given gmail account."""
import os, sys
from libgmail import GmailAccount
ga = GmailAccount("your.account@gmail.com", "pA$$w0Rd_")
ga.login()
# folders: inbox, starred, all, drafts, sent, spam
for thread in ga.getMessagesByFolder('all', allPages=True):
for msg ... |
How can I download all emails with attachments from Gmail? | 348,630 | 80 | 2008-12-08T03:57:49Z | 642,988 | 141 | 2009-03-13T14:34:44Z | [
"java",
"python",
"perl",
"gmail"
] | How do I connect to Gmail and determine which messages have attachments? I then want to download each attachment, printing out the Subject: and From: for each message as I process it. | Hard one :-)
```
import email, getpass, imaplib, os
detach_dir = '.' # directory where to save attachments (default: current)
user = raw_input("Enter your GMail username:")
pwd = getpass.getpass("Enter your password: ")
# connecting to the gmail imap server
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user,pwd)
m... |
How can I download all emails with attachments from Gmail? | 348,630 | 80 | 2008-12-08T03:57:49Z | 643,366 | 7 | 2009-03-13T15:52:00Z | [
"java",
"python",
"perl",
"gmail"
] | How do I connect to Gmail and determine which messages have attachments? I then want to download each attachment, printing out the Subject: and From: for each message as I process it. | Take a look at [Mail::Webmail::Gmail](http://search.cpan.org/~mincus/Mail-Webmail-Gmail-1.09/lib/Mail/Webmail/Gmail.pm#GETTING%5FATTACHMENTS):
**GETTING ATTACHMENTS**
There are two ways to get an attachment:
1 -> By sending a reference to a specific attachment returned by `get_indv_email`
```
# Creates an array of ... |
Formatting a data structure into a comma-separated list of arguments | 349,175 | 6 | 2008-12-08T11:00:39Z | 349,182 | 12 | 2008-12-08T11:03:54Z | [
"python",
"refactoring",
"list"
] | I need to convert a list (or a dict) into a comma-separated list for passing to another language.
Is there a nicer way of doing this than:
```
result = ''
args = ['a', 'b', 'c', 'd']
i = 0
for arg in args:
if i != 0: result += arg
else: result += arg + ', '
i += 1
result = 'function (... | `', '.join(args)` will do the trick. |
Formatting a data structure into a comma-separated list of arguments | 349,175 | 6 | 2008-12-08T11:00:39Z | 349,197 | 11 | 2008-12-08T11:09:37Z | [
"python",
"refactoring",
"list"
] | I need to convert a list (or a dict) into a comma-separated list for passing to another language.
Is there a nicer way of doing this than:
```
result = ''
args = ['a', 'b', 'c', 'd']
i = 0
for arg in args:
if i != 0: result += arg
else: result += arg + ', '
i += 1
result = 'function (... | ```
'function(%s)' % ', '.join(args)
```
produces
```
'function(a, b, c, d)'
``` |
How do I find the "concrete class" of a django model baseclass | 349,206 | 10 | 2008-12-08T11:11:45Z | 349,494 | 12 | 2008-12-08T13:05:59Z | [
"python",
"django",
"inheritance",
"django-models"
] | I'm trying to find the actual class of a django-model object, when using model-inheritance.
Some code to describe the problem:
```
class Base(models.model):
def basemethod(self):
...
class Child_1(Base):
pass
class Child_2(Base):
pass
```
If I create various objects of the two Child classes and... | Django implements model inheritance with a OneToOneField between the parent model's table and the child model's table. When you do `Base.object.all()`, Django is querying just the Base table, and so has no way of knowing what the child table is. Therefore, unfortunately, it's not possible to go directly to the child mo... |
How do I pass a python list in the post query? | 349,369 | 7 | 2008-12-08T12:28:28Z | 349,384 | 8 | 2008-12-08T12:35:54Z | [
"python",
"web-services"
] | I want to send some strings in a list in a POST call. eg:
```
www.example.com/?post_data = A list of strings
```
The python code receives the data as a single string (Instead of a list of strings). How do I post it as a list of strings? | There's no such thing as a "list of strings" in a URL (or in practically anything in HTTP - if you specify multiple values for the same header, they come out as a single delimited value in most web app frameworks IME). It's just a single string. I suggest you delimit the strings in some way (e.g. comma-separated) and t... |
Getting the lesser n elements of a list in Python | 350,519 | 8 | 2008-12-08T19:10:10Z | 350,568 | 13 | 2008-12-08T19:27:39Z | [
"python",
"algorithm",
"sorting"
] | I need to get the lesser n numbers of a list in Python. I need this to be really fast because it's in a critical part for performance and it needs to be repeated a lot of times.
n is usually no greater than 10 and the list usually has around 20000 elements. The list is always different each time I call the function. S... | You actually want a sorted sequence of mins.
```
mins = items[:n]
mins.sort()
for i in items[n:]:
if i < mins[-1]:
mins.append(i)
mins.sort()
mins= mins[:n]
```
This runs *much* faster because you aren't even looking at mins unless it's provably got a value larger than the given item. Abo... |
Getting the lesser n elements of a list in Python | 350,519 | 8 | 2008-12-08T19:10:10Z | 350,685 | 10 | 2008-12-08T20:01:12Z | [
"python",
"algorithm",
"sorting"
] | I need to get the lesser n numbers of a list in Python. I need this to be really fast because it's in a critical part for performance and it needs to be repeated a lot of times.
n is usually no greater than 10 and the list usually has around 20000 elements. The list is always different each time I call the function. S... | ```
import heapq
nlesser_items = heapq.nsmallest(n, items)
```
Here's a correct version of [S.Lott's algorithm](http://stackoverflow.com/questions/350519/getting-the-lesser-n-elements-of-a-list-in-python#350568):
```
from bisect import insort
from itertools import islice
def nsmallest_slott_bisect(n, iterable, i... |
Why is my Python C Extension leaking memory? | 350,647 | 5 | 2008-12-08T19:51:04Z | 350,695 | 16 | 2008-12-08T20:04:32Z | [
"python",
"c",
"refcounting"
] | The function below takes a python file handle, reads in packed binary data from the file, creates a Python dictionary and returns it. If I loop it endlessly, it'll continually consume RAM. What's wrong with my RefCounting?
```
static PyObject* __binParse_getDBHeader(PyObject *self, PyObject *args){
PyObject *o; //gen... | `PyDict_New()` returns a new reference, check the [docs](http://docs.python.org/c-api/dict.html) for `PyDict`. So if you increase the refcount immediately after creating it, you have two references to it. One is transferred to the caller when you return it as a result value, but the other one never goes aways.
You als... |
How does Django Know the Order to Render Form Fields? | 350,799 | 70 | 2008-12-08T20:37:44Z | 350,913 | 38 | 2008-12-08T21:12:56Z | [
"python",
"django",
"class",
"django-forms",
"contacts"
] | If I have a Django form such as:
```
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
```
And I call the as\_table() method of an instance of this form, Django will render the fields as the same order as specified above.
My q... | I went ahead and answered my own question. Here's the answer for future reference:
In Django `form.py` does some dark magic using the `__new__` method to load your class variables ultimately into `self.fields` in the order defined in the class. `self.fields` is a Django `SortedDict` instance (defined in `datastructure... |
How does Django Know the Order to Render Form Fields? | 350,799 | 70 | 2008-12-08T20:37:44Z | 1,191,310 | 86 | 2009-07-28T00:12:20Z | [
"python",
"django",
"class",
"django-forms",
"contacts"
] | If I have a Django form such as:
```
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
```
And I call the as\_table() method of an instance of this form, Django will render the fields as the same order as specified above.
My q... | **[NOTE: this answer is now somewhat outdated - please see the discussion below it].**
If f is a form, its fields are f.fields, which is a `django.utils.datastructures.SortedDict` (it presents the items in the order they are added). After form construction f.fields has a keyOrder attribute, which is a list containing ... |
How does Django Know the Order to Render Form Fields? | 350,799 | 70 | 2008-12-08T20:37:44Z | 5,747,259 | 11 | 2011-04-21T16:53:43Z | [
"python",
"django",
"class",
"django-forms",
"contacts"
] | If I have a Django form such as:
```
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
```
And I call the as\_table() method of an instance of this form, Django will render the fields as the same order as specified above.
My q... | Fields are listed in the order they are defined in ModelClass.\_meta.fields. But if you want to change order in Form, you can do by using keyOrder function.
For example :
```
class ContestForm(ModelForm):
class Meta:
model = Contest
exclude=('create_date', 'company')
def __init__(self, *args, **kwargs):
... |
How does Django Know the Order to Render Form Fields? | 350,799 | 70 | 2008-12-08T20:37:44Z | 34,502,078 | 7 | 2015-12-28T23:05:23Z | [
"python",
"django",
"class",
"django-forms",
"contacts"
] | If I have a Django form such as:
```
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
```
And I call the as\_table() method of an instance of this form, Django will render the fields as the same order as specified above.
My q... | New to Django 1.9 is **[Form.field\_order](https://docs.djangoproject.com/en/1.9/ref/forms/api/#django.forms.Form.field_order)** and **[Form.order\_fields()](https://docs.djangoproject.com/en/1.9/ref/forms/api/#django.forms.Form.order_fields)**. |
What does the function set use to check if two objects are different? | 351,271 | 6 | 2008-12-08T23:02:23Z | 351,287 | 13 | 2008-12-08T23:08:24Z | [
"python",
"methods",
"set"
] | Simple code:
```
>>> set([2,2,1,2,2,2,3,3,5,1])
set([1, 2, 3, 5])
```
Ok, in the resulting sets there are no duplicates.
What if the object in the list are not int but are some defined by me?
What method does it check to understand if they are different? I implemented \_\_eq\_\_ and \_\_cmp\_\_ with some objects but ... | According to the [set documentation](http://docs.python.org/library/stdtypes.html#set-types-set-frozenset), the elements must be [hashable](http://docs.python.org/glossary.html#term-hashable).
An object is hashable if it has a hash value which never changes during its lifetime (it needs a `__hash__()` method), and can... |
How do I mock an IMAP server in Python, despite extreme laziness? | 351,656 | 9 | 2008-12-09T02:57:49Z | 351,675 | 8 | 2008-12-09T03:14:39Z | [
"python",
"testing",
"imap",
"mocking"
] | I'm curious to know if there is an easy way to mock an IMAP server (a la the `imaplib` module) in Python, *without* doing a lot of work.
Is there a pre-existing solution? Ideally I could connect to the existing IMAP server, do a dump, and have the mock server run off the real mailbox/email structure.
Some background ... | I found it quite easy to write an IMAP server in twisted last time I tried. It comes with support for writing IMAP servers and you have a huge amount of flexibility. |
Python imaplib Gmail authenticate failure | 351,927 | 7 | 2008-12-09T06:07:50Z | 351,934 | 8 | 2008-12-09T06:10:52Z | [
"python",
"gmail",
"imap"
] | I just ran into an issue with Python's imaplib and Gmail's authentication mechanism:
```
>>> import imaplib
>>> imap = imaplib.IMAP4_SSL('imap.gmail.com', 993)
>>> imap.authenticate('bobdole@gmail.com', 'Bob Dole likes your style!')
Traceback (most recent call last):
...
imaplib.error: AUTHENTICATE command error: BA... | Instead of
```
>>> imap.authenticate('bobdole@gmail.com', 'Bob Dole likes your style!')
```
use
```
>>> imap.login('bobdole@gmail.com', 'Bob Dole likes your style!')
``` |
Capitalize a string | 352,478 | 25 | 2008-12-09T11:42:47Z | 352,494 | 7 | 2008-12-09T11:47:59Z | [
"python",
"string"
] | Does anyone know of a really simple way of capitalizing just the first letter of a string, regardless of the capitalization of the rest of the string?
For example:
```
asimpletest -> Asimpletest
aSimpleTest -> ASimpleTest
```
I would like to be able to do all string lengths as well. | ```
str = str[0].upper() + str[1:]
```
This should work with every string, except for the empty string (`""`). |
Capitalize a string | 352,478 | 25 | 2008-12-09T11:42:47Z | 352,513 | 49 | 2008-12-09T11:52:33Z | [
"python",
"string"
] | Does anyone know of a really simple way of capitalizing just the first letter of a string, regardless of the capitalization of the rest of the string?
For example:
```
asimpletest -> Asimpletest
aSimpleTest -> ASimpleTest
```
I would like to be able to do all string lengths as well. | @[saua](#352494) is right, and
```
str = str[:1].upper() + str[1:]
```
will work for any string |
Capitalize a string | 352,478 | 25 | 2008-12-09T11:42:47Z | 14,162,785 | 9 | 2013-01-04T18:30:46Z | [
"python",
"string"
] | Does anyone know of a really simple way of capitalizing just the first letter of a string, regardless of the capitalization of the rest of the string?
For example:
```
asimpletest -> Asimpletest
aSimpleTest -> ASimpleTest
```
I would like to be able to do all string lengths as well. | What about `your_string.title()`?
e.g. `"banana".title() -> Banana` |
Capitalize a string | 352,478 | 25 | 2008-12-09T11:42:47Z | 16,212,385 | 63 | 2013-04-25T10:29:58Z | [
"python",
"string"
] | Does anyone know of a really simple way of capitalizing just the first letter of a string, regardless of the capitalization of the rest of the string?
For example:
```
asimpletest -> Asimpletest
aSimpleTest -> ASimpleTest
```
I would like to be able to do all string lengths as well. | ```
>>> b = "my name"
>>> b.capitalize()
'My name'
>>> b.title()
'My Name'
``` |
Extending builtin classes in python | 352,537 | 17 | 2008-12-09T12:01:30Z | 352,546 | 19 | 2008-12-09T12:08:35Z | [
"python"
] | How can I extend a builtin class in python?
I would like to add a method to the str class.
I've done some searching but all I'm finding is older posts, I'm hoping someone knows of something newer. | Just subclass the type
```
>>> class X(str):
... def myMethod( self ):
... return int(self)
...
>>> s=X("Hi Mom")
>>> s.lower()
'hi mom'
>>> s.myMethod()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in myMethod
ValueError: invalid literal for int() ... |
Weighted random selection with and without replacement | 352,670 | 43 | 2008-12-09T13:15:00Z | 353,576 | 31 | 2008-12-09T17:27:01Z | [
"python",
"algorithm",
"random",
"random-sample"
] | Recently I needed to do weighted random selection of elements from a list, both with and without replacement. While there are well known and good algorithms for unweighted selection, and some for weighted selection without replacement (such as modifications of the resevoir algorithm), I couldn't find any good algorithm... | One of the fastest ways to make many with replacement samples from an unchanging list is the alias method. The core intuition is that we can create a set of equal-sized bins for the weighted list that can be indexed very efficiently through bit operations, to avoid a binary search. It will turn out that, done correctly... |
How to add file extensions based on file type on Linux/Unix? | 352,837 | 11 | 2008-12-09T14:10:18Z | 352,846 | 12 | 2008-12-09T14:13:59Z | [
"python",
"linux",
"bash",
"unix",
"shell"
] | This is a question regarding Unix shell scripting (any shell), but any other "standard" scripting language solution would also be appreciated:
I have a directory full of files where the filenames are hash values like this:
```
fd73d0cf8ee68073dce270cf7e770b97
fec8047a9186fdcc98fdbfc0ea6075ee
```
These files have dif... | You can use
```
file -i filename
```
to get a MIME-type. You could potentially lookup the type in a list and then append an extension. You can find a [list of MIME-types](http://www.iana.org/assignments/media-types/media-types.xhtml) and [example file extensions](http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs... |
How to add file extensions based on file type on Linux/Unix? | 352,837 | 11 | 2008-12-09T14:10:18Z | 352,919 | 7 | 2008-12-09T14:33:48Z | [
"python",
"linux",
"bash",
"unix",
"shell"
] | This is a question regarding Unix shell scripting (any shell), but any other "standard" scripting language solution would also be appreciated:
I have a directory full of files where the filenames are hash values like this:
```
fd73d0cf8ee68073dce270cf7e770b97
fec8047a9186fdcc98fdbfc0ea6075ee
```
These files have dif... | Following csl's response:
> You can use
>
> ```
> file -i filename
> ```
>
> to get a MIME-type.
> You could potentially lookup the type
> in a list and then append an
> extension. You can find list of
> MIME-types and suggested file
> extensions on the net.
I'd suggest you write a script that takes the output of `fi... |
How to add file extensions based on file type on Linux/Unix? | 352,837 | 11 | 2008-12-09T14:10:18Z | 352,973 | 9 | 2008-12-09T14:47:24Z | [
"python",
"linux",
"bash",
"unix",
"shell"
] | This is a question regarding Unix shell scripting (any shell), but any other "standard" scripting language solution would also be appreciated:
I have a directory full of files where the filenames are hash values like this:
```
fd73d0cf8ee68073dce270cf7e770b97
fec8047a9186fdcc98fdbfc0ea6075ee
```
These files have dif... | Here's mimetypes' version:
```
#!/usr/bin/env python
"""It is a `filename -> filename.ext` filter.
`ext` is mime-based.
"""
import fileinput
import mimetypes
import os
import sys
from subprocess import Popen, PIPE
if len(sys.argv) > 1 and sys.argv[1] == '--rename':
do_rename = True
del sys.argv[1]
else:... |
Beginner: Trying to understand how apps interact in Django | 353,571 | 23 | 2008-12-09T17:25:23Z | 353,667 | 20 | 2008-12-09T18:01:25Z | [
"python",
"django",
"django-models",
"django-apps"
] | I just got done working through the Django tutorials for the second time, and am understanding things much more clearly now. However, I'm still unclear how apps inside a site interact with one another.
For example, lets say I'm writing a blog application (a rather popular activity, apparently). Blog posts and comments... | Take a look at django's built-in [contenttypes framework](http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#ref-contrib-contenttypes):
`django.contrib.contenttypes`
It allows you develop your applications as stand-alone units. This is what the django developers used to allow django's built-in [comment fr... |
How do I check if a string is a number (float) in Python? | 354,038 | 872 | 2008-12-09T20:03:42Z | 354,073 | 1,069 | 2008-12-09T20:15:18Z | [
"python",
"casting",
"floating-point",
"type-conversion"
] | What is the best possible way to check if a string can be represented as a number in Python?
The function I currently have right now is:
```
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
```
Which, not only is ugly and slow, seems clunky. However I haven'... | In case you are looking for parsing (positive, unsigned) integers instead of floats, you can use the [`isdigit()`](https://docs.python.org/2/library/stdtypes.html#str.isdigit) function for string objects.
```
>>> a = "03523"
>>> a.isdigit()
True
>>> b = "963spam"
>>> b.isdigit()
False
```
[String Methods - `isdigit()... |
How do I check if a string is a number (float) in Python? | 354,038 | 872 | 2008-12-09T20:03:42Z | 354,130 | 429 | 2008-12-09T20:30:48Z | [
"python",
"casting",
"floating-point",
"type-conversion"
] | What is the best possible way to check if a string can be represented as a number in Python?
The function I currently have right now is:
```
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
```
Which, not only is ugly and slow, seems clunky. However I haven'... | > Which, not only is ugly and slow
I'd dispute both.
A regex or other string parsing would be uglier and slower.
I'm not sure that anything much could be faster than the above. It calls the function and returns. Try/Catch doesn't introduce much overhead because the most common exception is caught without an extensiv... |
How do I check if a string is a number (float) in Python? | 354,038 | 872 | 2008-12-09T20:03:42Z | 354,134 | 9 | 2008-12-09T20:31:49Z | [
"python",
"casting",
"floating-point",
"type-conversion"
] | What is the best possible way to check if a string can be represented as a number in Python?
The function I currently have right now is:
```
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
```
Which, not only is ugly and slow, seems clunky. However I haven'... | Casting to float and catching ValueError is probably the fastest way, since float() is specifically meant for just that. Anything else that requires string parsing (regex, etc) will likely be slower due to the fact that it's not tuned for this operation. My $0.02. |
How do I check if a string is a number (float) in Python? | 354,038 | 872 | 2008-12-09T20:03:42Z | 358,479 | 33 | 2008-12-11T04:56:26Z | [
"python",
"casting",
"floating-point",
"type-conversion"
] | What is the best possible way to check if a string can be represented as a number in Python?
The function I currently have right now is:
```
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
```
Which, not only is ugly and slow, seems clunky. However I haven'... | > Which, not only is ugly and slow, seems clunky.
It may take some getting used to, but this is the pythonic way of doing it. As has been already pointed out, the alternatives are worse. But there is one other advantage of doing things this way: polymorphism.
The central idea behind duck typing is that "if it walks a... |
How do I check if a string is a number (float) in Python? | 354,038 | 872 | 2008-12-09T20:03:42Z | 3,335,060 | 27 | 2010-07-26T13:10:15Z | [
"python",
"casting",
"floating-point",
"type-conversion"
] | What is the best possible way to check if a string can be represented as a number in Python?
The function I currently have right now is:
```
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
```
Which, not only is ugly and slow, seems clunky. However I haven'... | Updated after Alfe pointed out you don't need to check for float separately as complex handles both:
```
def is_number(s):
try:
complex(s) # for int, long, float and complex
except ValueError:
return False
return True
```
---
Previously said: Is some rare cases you might also need to che... |
How do I check if a string is a number (float) in Python? | 354,038 | 872 | 2008-12-09T20:03:42Z | 3,618,897 | 50 | 2010-09-01T14:06:08Z | [
"python",
"casting",
"floating-point",
"type-conversion"
] | What is the best possible way to check if a string can be represented as a number in Python?
The function I currently have right now is:
```
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
```
Which, not only is ugly and slow, seems clunky. However I haven'... | There is one exception that you may want to take into account: the string 'NaN'
If you want is\_number to return FALSE for 'NaN' this code will not work as Python converts it to its representation of a number that is not a number (talk about identity issues):
```
>>> float('NaN')
nan
```
Otherwise, I should actually... |
How do I check if a string is a number (float) in Python? | 354,038 | 872 | 2008-12-09T20:03:42Z | 9,337,733 | 12 | 2012-02-18T01:35:32Z | [
"python",
"casting",
"floating-point",
"type-conversion"
] | What is the best possible way to check if a string can be represented as a number in Python?
The function I currently have right now is:
```
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
```
Which, not only is ugly and slow, seems clunky. However I haven'... | ## Just Mimic C#
**In C# there are two different functions that handle parsing of scalar values:**
* Float.Parse()
* Float.TryParse()
**float.parse():**
```
def parse(string):
try:
return float(string)
except Exception:
throw TypeError
```
*Note: If you're wondering why I changed the except... |
How do I check if a string is a number (float) in Python? | 354,038 | 872 | 2008-12-09T20:03:42Z | 10,762,002 | 33 | 2012-05-25T22:22:32Z | [
"python",
"casting",
"floating-point",
"type-conversion"
] | What is the best possible way to check if a string can be represented as a number in Python?
The function I currently have right now is:
```
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
```
Which, not only is ugly and slow, seems clunky. However I haven'... | how about this:
```
'3.14'.replace('.','',1).isdigit()
```
which will return true only if there is one or no '.' in the string of digits.
```
'3.14.5'.replace('.','',1).isdigit()
```
will return false
edit: just saw another comment ...
adding a `.replace(badstuff,'',maxnum_badstuff)` for other cases can be done. i... |
How do I check if a string is a number (float) in Python? | 354,038 | 872 | 2008-12-09T20:03:42Z | 15,205,926 | 9 | 2013-03-04T16:12:38Z | [
"python",
"casting",
"floating-point",
"type-conversion"
] | What is the best possible way to check if a string can be represented as a number in Python?
The function I currently have right now is:
```
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
```
Which, not only is ugly and slow, seems clunky. However I haven'... | You can use Unicode strings, they have a method to do just what you want:
```
>>> s = u"345"
>>> s.isnumeric()
True
```
Or:
```
>>> s = "345"
>>> u = unicode(s)
>>> u.isnumeric()
True
```
<http://www.tutorialspoint.com/python/string_isnumeric.htm>
<http://docs.python.org/2/howto/unicode.html> |
How do I check if a string is a number (float) in Python? | 354,038 | 872 | 2008-12-09T20:03:42Z | 25,299,619 | 11 | 2014-08-14T03:34:08Z | [
"python",
"casting",
"floating-point",
"type-conversion"
] | What is the best possible way to check if a string can be represented as a number in Python?
The function I currently have right now is:
```
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
```
Which, not only is ugly and slow, seems clunky. However I haven'... | For strings of non-numbers, `try: except:` is actually slower than regular expressions. For strings of valid numbers, regex is slower. So, the appropriate method depends on your input.
If you find that you are in a performance bind, you can use a new third-party module called [fastnumbers](https://pypi.python.org/pypi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.