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 |
|---|---|---|---|---|---|---|---|---|---|
Nonalphanumeric list order from os.listdir() in Python | 4,813,061 | 19 | 2011-01-27T05:30:29Z | 4,813,738 | 9 | 2011-01-27T07:26:22Z | [
"python",
"list",
"directory-listing",
"listdir"
] | I often use python to process directories of data. Recently, I have noticed that the default order of the lists has changed to something almost nonsensical. For example, if I am in a current directory containing the following subdirectories: run01, run02, ... run19, run20, and then I generate a list from the following ... | Per the [documentation](http://docs.python.org/library/os.html?highlight=listdir#os.listdir):
> os.listdir(path)
>
> > Return a list
> > containing the names of the entries in
> > the directory given by path. **The list
> > is in arbitrary order**. It does not
> > include the special entries '.' and
> > '..' even if t... |
Nonalphanumeric list order from os.listdir() in Python | 4,813,061 | 19 | 2011-01-27T05:30:29Z | 15,003,650 | 36 | 2013-02-21T13:35:36Z | [
"python",
"list",
"directory-listing",
"listdir"
] | I often use python to process directories of data. Recently, I have noticed that the default order of the lists has changed to something almost nonsensical. For example, if I am in a current directory containing the following subdirectories: run01, run02, ... run19, run20, and then I generate a list from the following ... | You can use the builtin `sorted` function to sort the strings however you want. Based on what you describe,
```
sorted(os.listdir(whatever_directory))
```
Alternatively, you can use the `.sort` method of a list:
```
lst = os.listdir(whatever_directory)
lst.sort()
```
I think should do the trick.
Note that the orde... |
Difference between subprocess.Popen and os.system | 4,813,238 | 44 | 2011-01-27T06:04:09Z | 4,813,266 | 13 | 2011-01-27T06:09:21Z | [
"python",
"subprocess"
] | What is the difference between subprocess.Popen() and os.system() ? | Subprocess is based on popen2, and as such has a number of advantages - there's a full list in the [PEP here](http://www.python.org/dev/peps/pep-0324/), but some are:
* using pipe in the shell
* better newline support
* better handling of exceptions |
Difference between subprocess.Popen and os.system | 4,813,238 | 44 | 2011-01-27T06:04:09Z | 4,813,317 | 12 | 2011-01-27T06:17:36Z | [
"python",
"subprocess"
] | What is the difference between subprocess.Popen() and os.system() ? | subprocess.Popen() is strict superset of os.system(). |
Difference between subprocess.Popen and os.system | 4,813,238 | 44 | 2011-01-27T06:04:09Z | 4,813,571 | 35 | 2011-01-27T06:56:12Z | [
"python",
"subprocess"
] | What is the difference between subprocess.Popen() and os.system() ? | If you check out the [subprocess section of the Python docs](http://docs.python.org/library/subprocess.html#replacing-os-system), you'll notice there is an example of how to replace `os.system()` with `subprocess.Popen()`:
```
sts = os.system("mycmd" + " myarg")
```
...does the same thing as...
```
sts = Popen("mycm... |
Difference between subprocess.Popen and os.system | 4,813,238 | 44 | 2011-01-27T06:04:09Z | 4,813,638 | 9 | 2011-01-27T07:07:56Z | [
"python",
"subprocess"
] | What is the difference between subprocess.Popen() and os.system() ? | os.system is equivalent to Unix [system](http://linux.die.net/man/3/system) command, while subprocess was a helper module created to provide many of the facilities provided by the Popen commands with an easier and controllable interface. Those were designed similar to the [Unix Popen](http://linux.die.net/man/3/popen) ... |
Django/Python Circular model reference | 4,813,293 | 14 | 2011-01-27T06:14:15Z | 4,813,461 | 33 | 2011-01-27T06:38:08Z | [
"python",
"django",
"django-models"
] | Ok So I'm TRYING to write nice organized code and actually making seperate django apps instead of lumping everything together into 1. My problem is that I have 3 apps that each reference 1 other model from the next app. So basically I have an endless loop, App A needs to know about B.models.something1 , App B needs to ... | From the [docs](http://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey):
> To refer to models defined in another
> application, you can explicitly
> specify a model with the full
> application label. For example, if the
> Manufacturer model above is defined in
> another application called production,
> you... |
Fetch only the last 128 bytes of an mp3 file over a http connection | 4,814,137 | 5 | 2011-01-27T08:28:10Z | 4,814,210 | 9 | 2011-01-27T08:37:46Z | [
"python",
"http",
"tags",
"mp3"
] | I have been looking for an example of how python could fetch only the last 128 bytes of an mp3 file over a http connection. Is it possible to do range specific file access over HTTP in python? | Yes, it is possible to do it via HTTP using urllib2.
```
class HTTPRangeHandler(urllib2.BaseHandler):
def http_error_206(self, req, fp, code, msg, hdrs):
# Range header supported
r = urllib.addinfourl(fp, hdrs, req.get_full_url())
r.code = code
r.msg = msg
return r
def... |
abstractmethod is not defined | 4,814,523 | 4 | 2011-01-27T09:19:34Z | 4,814,533 | 13 | 2011-01-27T09:20:56Z | [
"python",
"abstract-class"
] | I cannot run this code, because I get the exception:
```
NameError: name 'abstractmethod' is not defined
File "C:\Tests\trunk\PythonTests\AbstractClasses.py", line 12, in <module>
class MyIterable:
File "C:\Tests\trunk\PythonTests\AbstractClasses.py", line 15, in MyIterable
@abstractmethod
from abc import ABCMeta... | You only imported `ABCMeta`
```
from abc import ABCMeta
```
Also import `abstractmethod`
```
from abc import ABCMeta, abstractmethod
```
and everything should be fine. |
Avoid Redundancy in Python | 4,814,655 | 5 | 2011-01-27T09:33:30Z | 4,814,692 | 7 | 2011-01-27T09:37:17Z | [
"python",
"import",
"init",
"redundancy"
] | I recently started using Python 2.6 for Ubuntu Server admin and have two minor issues concerning redundancy:
First thing are imports: They all look something like
import Class from Class
```
from class import Class
```
And the second thing are `__init__` methods:
```
__init__(self,arg1,...,argn):
self.arg1 = a... | The second thing is not redundancy - it is setting instance attributes. You can do it also like this:
```
class Foo:
def __init__(self, **kwargs):
for name, value in kwargs.items():
setattr(self, name, value)
```
But then you need to call Foo like this:
```
Foo(arg1=1, arg2=2, arg3=3)
```
Al... |
subprocess.check_output() doesn't seem to exist (Python 2.6.5) | 4,814,970 | 64 | 2011-01-27T10:05:43Z | 4,814,985 | 102 | 2011-01-27T10:07:19Z | [
"python"
] | I've been reading the Python documentation about the subprocess module (see [here](http://docs.python.org/library/subprocess.html#subprocess-replacements)) and it talks about a `subprocess.check_output()` command which seems to be exactly what I need.
However, when I try and use it I get an error that it doesn't exist... | It was introduced in 2.7 See the [docs](http://docs.python.org/library/subprocess.html#subprocess.check_output).
Use [subprocess.Popen](http://docs.python.org/library/subprocess.html#subprocess.Popen) if you want the output:
```
>>> import subprocess
>>> output = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE)... |
subprocess.check_output() doesn't seem to exist (Python 2.6.5) | 4,814,970 | 64 | 2011-01-27T10:05:43Z | 13,160,748 | 50 | 2012-10-31T14:53:44Z | [
"python"
] | I've been reading the Python documentation about the subprocess module (see [here](http://docs.python.org/library/subprocess.html#subprocess-replacements)) and it talks about a `subprocess.check_output()` command which seems to be exactly what I need.
However, when I try and use it I get an error that it doesn't exist... | **IF** it's used heavily in the code you want to run but that code doesn't have to be maintained long-term (or you need a quick fix irrespective of potential maintenance headaches in the future) then you could duck punch (aka monkey patch) it in wherever subprocess is imported...
Just lift the code from 2.7 and insert... |
How do I get a website's IP address using Python 3.x? | 4,815,065 | 8 | 2011-01-27T10:14:45Z | 4,815,095 | 8 | 2011-01-27T10:18:07Z | [
"python",
"dns",
"ip"
] | I have a string representing a domain name. How can I get the corresponding IP address using Python 3.x? Something like this:
```
>>> get_ip('http://www.stackoverflow.com')
'64.34.119.12'
``` | ```
Python 3.1.3 (r313:86834, Nov 27 2010, 18:30:53) [MSC v.1500 32 bit (Intel)] on win32
>>> import socket
>>> socket.gethostbyname('cool-rr.com')
'174.120.139.162'
```
Note that:
* gethostbyname() doesn't work with [IPv6](http://en.wikipedia.org/wiki/IPv6).
* gethostbyname() uses the C call gethostbanme(), which is... |
Index confusion in numpy arrays | 4,815,297 | 13 | 2011-01-27T10:41:05Z | 4,815,332 | 7 | 2011-01-27T10:46:46Z | [
"python",
"arrays",
"numpy"
] | I'm really confused by the index logic of numpy arrays with several dimensions. Here is an example:
```
import numpy as np
A = np.arange(18).reshape(3,2,3)
[[[ 0, 1, 2],
[ 3, 4, 5]],
[[ 6, 7, 8],
[ 9, 10, 11]],
[[12, 13, 14],
[15, 16, 17]]])
```
this gives me an array of shape (3,2,3), call them (x,y,... | I recommend the following advanced tutorial, which explains the various indexing methods: [NumPy MedKit](http://mentat.za.net/numpy/numpy_advanced_slides/)
Once you understand the powerful ways to index arrays (and how they can be combined) it will make sense. If your first try was valid then this would collide with s... |
Index confusion in numpy arrays | 4,815,297 | 13 | 2011-01-27T10:41:05Z | 4,817,229 | 16 | 2011-01-27T13:59:36Z | [
"python",
"arrays",
"numpy"
] | I'm really confused by the index logic of numpy arrays with several dimensions. Here is an example:
```
import numpy as np
A = np.arange(18).reshape(3,2,3)
[[[ 0, 1, 2],
[ 3, 4, 5]],
[[ 6, 7, 8],
[ 9, 10, 11]],
[[12, 13, 14],
[15, 16, 17]]])
```
this gives me an array of shape (3,2,3), call them (x,y,... | There are two types of indexing in NumPy [basic](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#basic-slicing) and [advanced](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing). Basic indexing uses tuples of slices for indexing, and does not copy the array, but rather [cre... |
How to access (and edit) variables from a callback function? | 4,815,329 | 4 | 2011-01-27T10:46:16Z | 4,815,796 | 7 | 2011-01-27T11:35:13Z | [
"python",
"variables",
"namespaces",
"callback",
"closures"
] | I use Boto to access Amazon S3. And for file uploading I can assign a callback function. The problem is that I cannot access the needed variables from that callback function until I make them global. In another hand, if I make them global, they are global for all other Celery tasks, too (until I restart Celery), as the... | In Python 2.x closures are read-only. You can however use a closure over a mutable value... i.e.
```
def myfunc():
stuff = [17] # <<---- this is a mutable object
def lfun(arg):
print "got arg", arg, "and stuff[0] is", stuff[0]
stuff[0] += 1
return lfun
my_function = myfunc()
my_function("h... |
loop over 2 lists, repeating the shortest until end of longest | 4,815,792 | 9 | 2011-01-27T11:34:51Z | 4,815,808 | 8 | 2011-01-27T11:36:24Z | [
"python",
"list",
"loops"
] | I am sure there is an easy and obvious way to do this, but I have been googling and reading the docs and I just cannot find anything.
This is what I want to achieve:
```
la = ['a1','a2','a3','a4']
lb = ['b1','b2']
result = ['a1_b1','a2_b2','a3_b1','a4_b2']
```
I have a list of dates and some of them has something ma... | Try
```
result = ["_".join((i, j)) for i, j in itertools.izip(la, itertools.cycle(lb))]
``` |
loop over 2 lists, repeating the shortest until end of longest | 4,815,792 | 9 | 2011-01-27T11:34:51Z | 4,816,039 | 11 | 2011-01-27T12:00:19Z | [
"python",
"list",
"loops"
] | I am sure there is an easy and obvious way to do this, but I have been googling and reading the docs and I just cannot find anything.
This is what I want to achieve:
```
la = ['a1','a2','a3','a4']
lb = ['b1','b2']
result = ['a1_b1','a2_b2','a3_b1','a4_b2']
```
I have a list of dates and some of them has something ma... | Assuming `la` is longer than `lb`:
```
>>> import itertools
>>> [x+'_'+y for x,y in zip(la, itertools.cycle(lb))]
['a1_b1', 'a2_b2', 'a3_b1', 'a4_b2']
```
* `itertools.cycle(lb)` returns a cyclic iterator for the elements in `lb`.
* `zip(...)` returns a list of tuples in which each element corresponds to an element i... |
Right click contextMenu on QPushButton | 4,815,925 | 7 | 2011-01-27T11:48:40Z | 4,839,906 | 12 | 2011-01-29T22:43:10Z | [
"python",
"qt",
"pyqt",
"contextmenu",
"pyqt4"
] | For my app I have created a GUI in Qt Designer and converted it into python(2.6) code.
On some of the `QPushButton` (created with the designer) I want to add a right click context menu. The menu options depend on the application status.
How to implement such a context menu ? | Check if an example below would work for you. The key thing is to [set context menu policy](http://doc.qt.io/qt-4.8/qwidget.html#contextMenuPolicy-prop) for your widget to CustomContextMenu and connect to the widget's [customContextMenuRequested](http://doc.qt.io/qt-4.8/qwidget.html#customContextMenuRequested) signal:
... |
Caching a Django queryset for the calendar date | 4,817,503 | 2 | 2011-01-27T14:23:23Z | 4,843,714 | 8 | 2011-01-30T15:33:47Z | [
"python",
"django",
"memcached",
"django-queryset",
"django-cache"
] | I have a query which results only change once a day. Seems like a waste to be performing that query every request I get for that page. I am investigating using memcached for this.
How would I begin? Anyone have any suggestions or pitfalls I should avoid in using Django's caching? Should I cache at the template or at t... | Normally before I decide where to do the caching I ask myself a few questions.
1. How often does this data change
2. Do I use this data in more then one place
3. How much data is it going to be
Since I don't know all of the details for your application, I'm going to make some assumptions.
1. you have a view that eit... |
SQL IN operator using pyodbc and SQL Server | 4,819,356 | 6 | 2011-01-27T16:57:16Z | 4,824,615 | 11 | 2011-01-28T03:37:29Z | [
"python",
"sql",
"pyodbc"
] | I'm using pyodbc to query to an SQL Server database
```
import datetime
import pyodbc
conn = pyodbc.connect("Driver={SQL Server};Server='dbserver',Database='db',
TrustedConnection=Yes")
cursor = conn.cursor()
ratings = ("PG-13", "PG", "G")
st_dt = datetime(2010, 1, 1)
end_dt = datetime(2010,... | You cannot parameterize multiple values in an `IN ()` clause using a single string parameter. The only way to accomplish that is:
1. String substitution (as you did).
2. Build a parameterized query in the form `IN (?, ?, . . ., ?)` and then pass in a *separate* parameter for each place holder. I'm not an expert at Pyt... |
SQL IN operator using pyodbc and SQL Server | 4,819,356 | 6 | 2011-01-27T16:57:16Z | 16,732,494 | 9 | 2013-05-24T10:07:16Z | [
"python",
"sql",
"pyodbc"
] | I'm using pyodbc to query to an SQL Server database
```
import datetime
import pyodbc
conn = pyodbc.connect("Driver={SQL Server};Server='dbserver',Database='db',
TrustedConnection=Yes")
cursor = conn.cursor()
ratings = ("PG-13", "PG", "G")
st_dt = datetime(2010, 1, 1)
end_dt = datetime(2010,... | To expand on Larry's second option - dynamically creating a parameterized string, I used the following successfully:
```
placeholders = ",".join("?" * len(code_list))
sql = "delete from dbo.Results where RESULT_ID = ? AND CODE IN (%s)" % placeholders
params = [result_id]
params.extend(code_list)
cursor.execute(sql, pa... |
Multiple Tries in Try/Except Block | 4,819,402 | 5 | 2011-01-27T17:00:15Z | 4,819,434 | 18 | 2011-01-27T17:02:55Z | [
"python",
"exception"
] | I have some python code where I can accept two different file names, so I would like to do something like try the first file name, if there is an exception then try the second filename, if the second try fails, then raise the exception and handle the error.
So the basic logic is:
```
first try this:
f = file(name1... | You could simply use a `for` loop:
```
for name in filenames:
try:
f = open(name)
break
except IOError:
pass
else:
# error
``` |
Java's Mahout equivalent in Python | 4,819,437 | 23 | 2011-01-27T17:03:16Z | 4,819,493 | 19 | 2011-01-27T17:07:40Z | [
"java",
"python",
"scalability",
"machine-learning",
"mahout"
] | **[Java based Mahout's](http://mahout.apache.org/)** goal is to build scalable machine learning libraries. Are there any equivalent libraries in Python ? | scikits learn is highly recommended <http://scikit-learn.sourceforge.net/> |
Passing Python list to C++ vector using Boost.python | 4,819,707 | 7 | 2011-01-27T17:27:40Z | 4,837,782 | 10 | 2011-01-29T15:55:43Z | [
"python",
"vector",
"boost-python"
] | How do I pass a Python list of my object type `ClassName` to a C++ function that accepts a `vector<ClassName>`?
The best I found is something like this: [example](http://mail.python.org/pipermail/cplusplus-sig/2003-September/005367.html). Unfortunately, the code crashes and I can't seem to figure out why. Here's what ... | Assuming you have function that takes a `std::vector<Foo>`
```
void bar (std::vector<Foo> arg)
```
The easiest way to handle this is to expose the `vector` to python.
```
BOOST_PYTHON_MODULE(awesome_module)
{
class_<Foo>("Foo")
//methods and attrs here
;
class_<std::vector<Foo> >("VectorOfFoo")
... |
basics of python encryption w/ hashlib sha1 | 4,820,043 | 12 | 2011-01-27T18:02:04Z | 4,820,227 | 13 | 2011-01-27T18:21:12Z | [
"python",
"encryption",
"sha1",
"hmac",
"hashlib"
] | I'm struggling to fully understand how encryption works and is coded, particularly with python. I'm just trying to get the basics down and create code in the simplest form.
I'm going to be passing a userID between two different sites, but obviously I need this to be encrypted with a private key so Website2 knows it ca... | The `hashlib` module provides hashing functions. While there is some relation to encryption, once you hash some data you can not go back to get the original data from the hash result.
Instead of encripting the data you can take a different approach: creating a unique signature using a hash of the data and some secret.... |
basics of python encryption w/ hashlib sha1 | 4,820,043 | 12 | 2011-01-27T18:02:04Z | 4,820,263 | 15 | 2011-01-27T18:24:55Z | [
"python",
"encryption",
"sha1",
"hmac",
"hashlib"
] | I'm struggling to fully understand how encryption works and is coded, particularly with python. I'm just trying to get the basics down and create code in the simplest form.
I'm going to be passing a userID between two different sites, but obviously I need this to be encrypted with a private key so Website2 knows it ca... | What you want is an encryption library not one that just provides hash algorithms. With python's `hashlib` library:
```
import hashlib
m = hashlib.sha1()
m.update("The quick brown fox jumps over the lazy dog")
print(m.hexdigest())
```
Returns: `2fd4e1c67a2d28fced849ee1bb76e7391b93eb12`
Given this hash, it is extreme... |
Trouble installing psycopg2 on CentOS | 4,821,094 | 12 | 2011-01-27T19:49:15Z | 4,821,175 | 12 | 2011-01-27T19:58:08Z | [
"python",
"postgresql",
"installation",
"centos",
"psycopg2"
] | I'm trying to install psycopg2 on CentOS, I followed everything on this [tutorial](http://thebuild.com/blog/2009/10/17/wordpress-to-djangopostgresql-part-3-installing-apache-python-2-6-psycopg2-and-mod_wsgi/) from "On with it: Installing Python 2.6" all the way to when it imports psycopg2, but when I try to import I ge... | psycopg2 is a python wrapper around the PostgreSQL libraries, so you need those installed on your system too.
Since you're using CentOS, try this from the command line to install the postgre libs.
`yum install postgresql-libs` |
Trouble installing psycopg2 on CentOS | 4,821,094 | 12 | 2011-01-27T19:49:15Z | 4,821,248 | 17 | 2011-01-27T20:04:59Z | [
"python",
"postgresql",
"installation",
"centos",
"psycopg2"
] | I'm trying to install psycopg2 on CentOS, I followed everything on this [tutorial](http://thebuild.com/blog/2009/10/17/wordpress-to-djangopostgresql-part-3-installing-apache-python-2-6-psycopg2-and-mod_wsgi/) from "On with it: Installing Python 2.6" all the way to when it imports psycopg2, but when I try to import I ge... | 1. Forget your tutorial.
2. [Install EPEL](http://fedoraproject.org/wiki/EPEL/FAQ#howtouse)
3. yum install python-psycopg2
Django [supports Python 2.4](http://docs.djangoproject.com/en/dev/intro/install/) just fine. If you really need Python 2.6 you can also use EPEL (`yum install python26`) - but there's no psycopg2 ... |
Python dynamic instantiation from string name of a class in dynamically imported module | 4,821,104 | 65 | 2011-01-27T19:49:57Z | 4,821,120 | 104 | 2011-01-27T19:51:58Z | [
"python"
] | In python, I have to instantiate certain class, knowing its name in a string, but this class 'lives' in a dynamically imported module. An example follows:
loader-class script:
```
import sys
class loader:
def __init__(self, module_name, class_name): # both args are strings
try:
__import__(module_name)
... | You can use [getattr](http://docs.python.org/2/library/functions.html#getattr)
```
getattr(module, class_name)
```
to access the class. More complete code:
```
module = __import__(module_name)
class_ = getattr(module, class_name)
instance = class_()
``` |
Python dynamic instantiation from string name of a class in dynamically imported module | 4,821,104 | 65 | 2011-01-27T19:49:57Z | 4,821,140 | 9 | 2011-01-27T19:53:37Z | [
"python"
] | In python, I have to instantiate certain class, knowing its name in a string, but this class 'lives' in a dynamically imported module. An example follows:
loader-class script:
```
import sys
class loader:
def __init__(self, module_name, class_name): # both args are strings
try:
__import__(module_name)
... | Use `getattr` to get an attribute from a name in a string. In other words, get the instance as
```
instance = getattr(modul, class_name)()
``` |
Python dynamic instantiation from string name of a class in dynamically imported module | 4,821,104 | 65 | 2011-01-27T19:49:57Z | 24,674,853 | 7 | 2014-07-10T11:02:13Z | [
"python"
] | In python, I have to instantiate certain class, knowing its name in a string, but this class 'lives' in a dynamically imported module. An example follows:
loader-class script:
```
import sys
class loader:
def __init__(self, module_name, class_name): # both args are strings
try:
__import__(module_name)
... | Copy-paste snippet:
```
def str_to_class(module_name, class_name)
try:
module_ = importlib.import_module(module_name)
try:
class_ = getattr(module_, class_name)()
except AttributeError:
logging.error('Class does not exist')
except ImportError:
logging.err... |
Python dynamic instantiation from string name of a class in dynamically imported module | 4,821,104 | 65 | 2011-01-27T19:49:57Z | 30,941,292 | 38 | 2015-06-19T14:56:35Z | [
"python"
] | In python, I have to instantiate certain class, knowing its name in a string, but this class 'lives' in a dynamically imported module. An example follows:
loader-class script:
```
import sys
class loader:
def __init__(self, module_name, class_name): # both args are strings
try:
__import__(module_name)
... | # tl;dr
Use a combination of `getattr` and `importlib.import_module`:
```
import importlib
MyClass = getattr(importlib.import_module("module.submodule"), "Klass")
instance = MyClass()
```
# explanations
Please don't use `__import__` to dynamically import a module by name, as it does not allow you to import submodul... |
How to make simplejson serializable class | 4,821,940 | 7 | 2011-01-27T21:13:26Z | 4,822,098 | 10 | 2011-01-27T21:29:24Z | [
"python",
"serialization",
"simplejson"
] | I have a class defined like this
```
class A:
def __init__(self):
self.item1 = None
def __repr__(self):
return str(self.__dict__)
```
when I do:
```
>>> import simplejson
>>> myA = A()
>>> simplejson.dumps(myA)
TypeError: {'item1': None} is not JSON serializable
```
I can't find the reason w... | You can't serialize arbitrary objects with `simplejson`. You need to pass a `default` and `object_hook` to `dump` and `load`. Here's an example:
```
class SerializerRegistry(object):
def __init__(self):
self._classes = {}
def add(self, cls):
self._classes[cls.__module__, cls.__name__] = cls
... |
Reading least significant bits in Python | 4,822,130 | 2 | 2011-01-27T21:33:49Z | 4,822,184 | 7 | 2011-01-27T21:38:17Z | [
"python",
"bit-manipulation",
"syslog"
] | I am having to parse the Facility and Severity of syslog messages in Python. These values come with each message as a single integer. The severity of the event is 0-7, specified in the 3 least significant bits in the integer. What is the easiest/fastest way to evaluate these 3 bits from the number?
The code I have rig... | ```
SEV = PRI & 7
FAC = PRI >> 3
```
Like that. |
check_password() from a user again | 4,822,724 | 9 | 2011-01-27T22:34:22Z | 4,822,892 | 8 | 2011-01-27T22:51:42Z | [
"python",
"django",
"website",
"authentication"
] | I do have the following form. How can I check the password from the user again, before the user can change his emailadsress finally. Even he is logged in, I just want to be sure that it is really the user. Just a securtiy thing.
How do I do it with check\_password()
Thanks!
Craphunter
```
'EmailChangeForm' obje... | I feel like you answered your own question : )
The docs on the `check_password` method are here:
<http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.User.check_password>
```
success = user.check_password(request.POST['submitted_password'])
if success:
# do your email changing magic
else:... |
check_password() from a user again | 4,822,724 | 9 | 2011-01-27T22:34:22Z | 4,823,128 | 14 | 2011-01-27T23:19:53Z | [
"python",
"django",
"website",
"authentication"
] | I do have the following form. How can I check the password from the user again, before the user can change his emailadsress finally. Even he is logged in, I just want to be sure that it is really the user. Just a securtiy thing.
How do I do it with check\_password()
Thanks!
Craphunter
```
'EmailChangeForm' obje... | I would refactor your code to look something like this:
View:
```
@login_required
def view(request, extra_context=None, ...):
form = EmailChangeForm(user=request.user, data=request.POST or None)
if request.POST and form.is_valid():
send_email_change_request(request.user,
... |
Sending Meeting Invitations With Python | 4,823,574 | 6 | 2011-01-28T00:35:11Z | 14,648,531 | 8 | 2013-02-01T14:30:34Z | [
"python",
"icalendar"
] | I'm pretty new to Python and i'm trying to create a script which gathers data from our database and converts the data into sets. It then takes those sets of data and generates ICS (icalendar) objects (by using icalendar <http://codespeak.net/icalendar/>).
The problem I'm running into is the email part, I am able to se... | below is what worked for me sending invites via python over gmail (worked with google calendar, outlook and outlook.com (live/hotmail):
```
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate... |
Get all related many-to-many objects from a Django QuerySet | 4,823,601 | 12 | 2011-01-28T00:38:52Z | 4,823,685 | 16 | 2011-01-28T00:51:54Z | [
"python",
"django",
"many-to-many",
"django-queryset"
] | I have a twisty maze of interrelated Django models, with many-to-many fields describing the relationships.
What's the cleanest way to get a list of unique members of a related model from a QuerySet?
If I have a Item model with a groups ManyToMany pointing to the Groups model.
If I have a queryset of Items, of 'items... | One solution is to use 2 queries.
You can use the reverse relationships to query all `Group`s that an `Item` in your `items` points to.
```
groups = groups.objects.filter(item__in=items).distinct().values_list('name', flat=True)
``` |
Is there a module for python that does facial recognition? | 4,824,190 | 9 | 2011-01-28T02:13:59Z | 4,824,205 | 11 | 2011-01-28T02:17:36Z | [
"python",
"image-recognition"
] | Is there a module for python that does facial recognition? It should take in an image and compare it to a different image. | You should check out [OpenCV](http://opencv.org/) :) it is a useful toolkit for this sort of thing and is implemented in Python, C, and C++.
It also has some pretty thorough documentation from what I remember. |
Parse Multi-Part Email with Sub-parts using Python | 4,824,376 | 2 | 2011-01-28T02:49:40Z | 4,825,114 | 8 | 2011-01-28T05:22:02Z | [
"python"
] | I am using this function to parse an email. I am able to parse "simple" multi-part emails, but it produces an error (UnboundLocalError: local variable 'html' referenced before assignment) when the email defines multiple boundaries (sub-parts). I would like the script to separate the text and html portions and return on... | Like the comment said you always check html but only declare it in one of the specific cases. Thats what the error is telling you, you reference html before assigning it. In python it is not valid to check if something is None if it hasn't been assigned to anything. For example open the python interactive prompt:
```
... |
Regex to match digits of specific length | 4,824,942 | 12 | 2011-01-28T04:48:54Z | 4,824,952 | 17 | 2011-01-28T04:50:49Z | [
"python",
"regex"
] | I am looking to match a 15 digit number (as part of a larger regex string). Right now, I have
```
\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d
```
but I feel like there must be a cleaner way to do this. | If your regex language is Perl-compatible: `\d{15}`.
It is difficult to say how handle the edges (so you don't accidentally grab extra digits) without knowing the outer context in which this snippet will be used. The definitive context-independent solution is this:
```
(?:(?<!\d)\d{15}(?!\d))
```
You can put this in... |
Regex to match digits of specific length | 4,824,942 | 12 | 2011-01-28T04:48:54Z | 4,824,967 | 22 | 2011-01-28T04:53:33Z | [
"python",
"regex"
] | I am looking to match a 15 digit number (as part of a larger regex string). Right now, I have
```
\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d
```
but I feel like there must be a cleaner way to do this. | You can generally do ranges as follows:
```
\d{4,7}
```
which means a minimum of 4 and maximum of 7 digits. For your particular case, you can use the one-argument variant, `\d{15}`.
Both of these forms are supported in [Python's regular expressions](http://docs.python.org/library/re.html) - look for the text `{m,n}`... |
Exception traceback is hidden if not re-raised immediately | 4,825,234 | 38 | 2011-01-28T05:42:44Z | 4,825,279 | 74 | 2011-01-28T05:51:40Z | [
"python",
"exception",
"exception-handling",
"try-catch",
"traceback"
] | I've got a piece of code similar to this:
```
import sys
def func1():
func2()
def func2():
raise Exception('test error')
def main():
err = None
try:
func1()
except:
err = sys.exc_info()[1]
pass
# some extra processing, involving checking err details (if err is not N... | A blank `raise` raises the last exception.
```
# need to re-raise err so caller can do its own handling
if err:
raise
```
If you use `raise something` Python has no way of knowing if `something` was an exception just caught before, or a new exception with a new stack trace. That's why there is the blank `raise` t... |
Exception traceback is hidden if not re-raised immediately | 4,825,234 | 38 | 2011-01-28T05:42:44Z | 14,162,421 | 32 | 2013-01-04T18:03:42Z | [
"python",
"exception",
"exception-handling",
"try-catch",
"traceback"
] | I've got a piece of code similar to this:
```
import sys
def func1():
func2()
def func2():
raise Exception('test error')
def main():
err = None
try:
func1()
except:
err = sys.exc_info()[1]
pass
# some extra processing, involving checking err details (if err is not N... | It is possible to [modify and rethrow](http://docs.python.org/2/reference/simple_stmts.html#grammar-token-raise_stmt) an exception:
> If no expressions are present, `raise` re-raises the last exception that
> was active in the current scope. If no exception is active in the
> current scope, a `TypeError` exception is ... |
cannot dump data by using python ./manage.py dumpdata app | 4,825,311 | 6 | 2011-01-28T05:55:33Z | 4,825,435 | 7 | 2011-01-28T06:17:07Z | [
"python",
"django",
"fixture"
] | I created an app in a Django project. For testing purpose, I would like to create fixture files. I found that I can dump my database in order to create fixture automatically if it already has data. I want to use a fixture, so I used the command `python ./manage.py dumpdata app`, but it returned a list of a ton of `\x02... | I'm not sure I understand your question completely. When you dump the data you need to store it in a fixture. Check out this blog post:
<http://solutions.treypiepmeier.com/2008/09/28/use-django-fixtures-to-automatically-load-data-when-you-install-an-app/>
Basically do something like this (replace [app\_name] with the ... |
Django i18n setlang not changing session data django_language | 4,825,442 | 9 | 2011-01-28T06:17:29Z | 24,299,615 | 13 | 2014-06-19T05:51:21Z | [
"python",
"django",
"internationalization"
] | I don't know what I'm doing wrong, but my session data won't change even if I submit a new language to /i18n/setlang. I am to translate to Filipino language using the code 'tl' but somehow, it just doesn't seem to work. Please help. Here are some code:
```
# Django settings for ppdjango project.
import os
DEBUG = Tru... | ```
MIDDLEWARE_CLASSES = (
'django.middleware.cache.UpdateCacheMiddleware',
+ 'django.middleware.locale.LocaleMiddleware', # you need this to activate language (code)
'django.middleware.common.CommonMiddleware',
...
)
``` |
Prevent delete in Django model | 4,825,815 | 11 | 2011-01-28T07:20:20Z | 19,007,641 | 10 | 2013-09-25T14:25:31Z | [
"python",
"django",
"django-models",
"django-signals"
] | I have a setup like this (simplified for this question):
```
class Employee(models.Model):
name = models.CharField(name, unique=True)
class Project(models.Model):
name = models.CharField(name, unique=True)
employees = models.ManyToManyField(Employee)
```
When an Employee is about to get deleted, I want t... | I was looking for an answer to this problem, was not able to find a good one, which would work for both models.Model.delete() and QuerySet.delete(). I went along and, sort of, implementing Steve K's solution. I used this solution to make sure an object (Employee in this example) can't be deleted from the database, in e... |
How do I Filter the PyQt QCombobox Items based on the text input? | 4,827,207 | 2 | 2011-01-28T10:32:48Z | 4,829,759 | 9 | 2011-01-28T15:14:53Z | [
"python",
"qt",
"pyqt",
"qcombobox"
] | I need a QCombox which Items are filtered based on the text input. If I set the QCombobox editable, the user can insert text and the QCompleter is automatically created. But the items are not filtered and I donât want the user to add new Items.
Is there any possibility to add this functionality to the QCombobox? | Try this code, is something i used in a project of mine
```
import sys
from PyQt4.QtGui import QComboBox, QApplication, QCompleter, QSortFilterProxyModel, QStandardItemModel, QStandardItem
from PyQt4.QtCore import Qt
class ExtendedCombo( QComboBox ):
def __init__( self, parent = None):
super( ExtendedCom... |
How do I Filter the PyQt QCombobox Items based on the text input? | 4,827,207 | 2 | 2011-01-28T10:32:48Z | 7,693,234 | 7 | 2011-10-07T21:55:17Z | [
"python",
"qt",
"pyqt",
"qcombobox"
] | I need a QCombox which Items are filtered based on the text input. If I set the QCombobox editable, the user can insert text and the QCompleter is automatically created. But the items are not filtered and I donât want the user to add new Items.
Is there any possibility to add this functionality to the QCombobox? | Thanks for the nice answer, I had the same problem.
It works nicely, but forces you to supply an external model, which is unnecessary.
I extended the code to also work with the internal standard model already supplied by the combobox.
Also some cleanup and documentation has been done...
```
#!/usr/bin/env python
# -*-... |
problem subclassing builtin type | 4,827,303 | 6 | 2011-01-28T10:44:40Z | 4,827,380 | 9 | 2011-01-28T10:51:42Z | [
"python",
"python-3.x",
"subclassing",
"built-in-types"
] | ```
# Python 3
class Point(tuple):
def __init__(self, x, y):
super().__init__((x, y))
Point(2, 3)
```
would result in
> TypeError: tuple() takes at most 1
> argument (2 given)
Why? What should I do instead? | `tuple` is an immutable type. It's already created and immutable before `__init__` is even called. That is why this doesn't work.
If you really want to subclass a tuple, use [`__new__`](http://docs.python.org/reference/datamodel.html#object.__new__).
```
>>> class MyTuple(tuple):
... def __new__(typ, itr):
... ... |
How to let Pool.map take a lambda function | 4,827,432 | 21 | 2011-01-28T10:57:13Z | 4,827,520 | 31 | 2011-01-28T11:06:32Z | [
"python",
"multiprocessing",
"pool"
] | I the following function
```
def copy_file(source_file, target_dir):
pass
```
Now I would like to use multiprocessing to execute this function at once
```
p = new Pool(12)
p.map(lambda x: copy_file(x,target_dir), file_list)
```
The problem is, lambda's can't be pickled, so this fails. What is the most neat (pyt... | Use a function object:
```
class Copier(object):
def __init__(self, tgtdir):
self.target_dir = tgtdir
def __call__(self, src):
copy_file(src, self.target_dir)
```
To run your `Pool.map`:
```
p.map(Copier(target_dir), file_list)
``` |
How to let Pool.map take a lambda function | 4,827,432 | 21 | 2011-01-28T10:57:13Z | 4,828,728 | 9 | 2011-01-28T13:26:55Z | [
"python",
"multiprocessing",
"pool"
] | I the following function
```
def copy_file(source_file, target_dir):
pass
```
Now I would like to use multiprocessing to execute this function at once
```
p = new Pool(12)
p.map(lambda x: copy_file(x,target_dir), file_list)
```
The problem is, lambda's can't be pickled, so this fails. What is the most neat (pyt... | The answer below was stricken because this [does not actually work](http://bugs.python.org/issue5228) in Python2 since `functools.partial` objects (in Python2) are not picklable.
`functools.partial` objects were made picklable in Python3, however, so this solution does work there.
---
You could use [functools.partia... |
Are there any uses of the empty tuple in Python? | 4,828,041 | 14 | 2011-01-28T12:09:43Z | 4,828,285 | 15 | 2011-01-28T12:37:03Z | [
"python"
] | Is there any other purpose (besides being there because it needs to be) the empty tuple may have? Or: what would you use the empty tuple for? If anything. I just can't find an answer (well, a positive answer as in: "yes, there is"), please help me out with getting this question out of my head. "for testing if another t... | Here's when.
```
def tuple_of_primes_less_than( n ):
if n <= 2: return ()
else:
x, p = set( range(2,n) ), 2
while p <= max(x):
for k in range(2,int(2+math.sqrt(p))):
x.discard(k*p)
p += 1
return tuple( sorted( x ) )
``` |
How to make an immutable object in Python? | 4,828,080 | 104 | 2011-01-28T12:14:06Z | 4,828,108 | 47 | 2011-01-28T12:17:02Z | [
"python",
"python-3.x",
"immutability"
] | Although I have never needed this, it just struck me that making an immutable object in Python could be slightly tricky. You can't just override [`__setattr__`](https://docs.python.org/3/reference/datamodel.html#object.__setattr__), because then you can't even set attributes in the [`__init__`](https://docs.python.org/... | The easiest way to do this is using `__slots__`:
```
class A(object):
__slots__ = []
```
Instances of `A` are immutable now, since you can't set any attributes on them.
If you want the class instances to contain data, you can combine this with deriving from `tuple`:
```
from operator import itemgetter
class Poi... |
How to make an immutable object in Python? | 4,828,080 | 104 | 2011-01-28T12:14:06Z | 4,828,137 | 14 | 2011-01-28T12:20:16Z | [
"python",
"python-3.x",
"immutability"
] | Although I have never needed this, it just struck me that making an immutable object in Python could be slightly tricky. You can't just override [`__setattr__`](https://docs.python.org/3/reference/datamodel.html#object.__setattr__), because then you can't even set attributes in the [`__init__`](https://docs.python.org/... | You could create a `@immutable` decorator that either overrides the `__setattr__` *and* change the `__slots__` to an empty list, then decorate the `__init__` method with it.
Edit: As the OP noted, changing the `__slots__` attribute only prevents the *creation of new attributes*, not the modification.
Edit2: Here's an... |
How to make an immutable object in Python? | 4,828,080 | 104 | 2011-01-28T12:14:06Z | 4,828,492 | 23 | 2011-01-28T13:01:35Z | [
"python",
"python-3.x",
"immutability"
] | Although I have never needed this, it just struck me that making an immutable object in Python could be slightly tricky. You can't just override [`__setattr__`](https://docs.python.org/3/reference/datamodel.html#object.__setattr__), because then you can't even set attributes in the [`__init__`](https://docs.python.org/... | Another idea would be to completely disallow `__setattr__` and use `object.__setattr__` in the constructor:
```
class Point(object):
def __init__(self, x, y):
object.__setattr__(self, "x", x)
object.__setattr__(self, "y", y)
def __setattr__(self, *args):
raise TypeError
def __delatt... |
How to make an immutable object in Python? | 4,828,080 | 104 | 2011-01-28T12:14:06Z | 4,828,831 | 67 | 2011-01-28T13:39:08Z | [
"python",
"python-3.x",
"immutability"
] | Although I have never needed this, it just struck me that making an immutable object in Python could be slightly tricky. You can't just override [`__setattr__`](https://docs.python.org/3/reference/datamodel.html#object.__setattr__), because then you can't even set attributes in the [`__init__`](https://docs.python.org/... | Yet another solution I just thought of: The simplest way to get the same behaviour as your original code is
```
Immutable = collections.namedtuple("Immutable", ["a", "b"])
```
It does not solve the problem that attributes can be accessed via `[0]` etc., but at least it's considerably shorter and provides the addition... |
How to make an immutable object in Python? | 4,828,080 | 104 | 2011-01-28T12:14:06Z | 4,829,374 | 7 | 2011-01-28T14:36:19Z | [
"python",
"python-3.x",
"immutability"
] | Although I have never needed this, it just struck me that making an immutable object in Python could be slightly tricky. You can't just override [`__setattr__`](https://docs.python.org/3/reference/datamodel.html#object.__setattr__), because then you can't even set attributes in the [`__init__`](https://docs.python.org/... | I don't think it is entirely possible except by using either a tuple or a namedtuple. No matter what you if you override `__setattr__()` the user can always bypass it by calling `object.__setattr__()` directly, so any solution that depends on `__setattr__` is guaranteed not to work.
This is about the nearest you can g... |
How to make an immutable object in Python? | 4,828,080 | 104 | 2011-01-28T12:14:06Z | 4,854,045 | 33 | 2011-01-31T17:34:25Z | [
"python",
"python-3.x",
"immutability"
] | Although I have never needed this, it just struck me that making an immutable object in Python could be slightly tricky. You can't just override [`__setattr__`](https://docs.python.org/3/reference/datamodel.html#object.__setattr__), because then you can't even set attributes in the [`__init__`](https://docs.python.org/... | > ..howto do it "properly" in C..
You could use [Cython](http://docs.cython.org/index.html) to create an extension type for Python:
```
cdef class Immutable:
cdef readonly object a, b
cdef object __weakref__ # enable weak referencing support
def __init__(self, a, b):
self.a, self.b = a, b
```
It... |
Import a Python module into a Jinja template? | 4,828,406 | 25 | 2011-01-28T12:51:30Z | 4,829,057 | 36 | 2011-01-28T14:04:02Z | [
"python",
"jinja2",
"python-import"
] | Is it possible to import a Python module into a Jinja template so I can use its functions?
For example, I have a **format.py** file that contains methods for formatting dates and times. In a Jinja macro, can I do something *like* the following?
```
{% from 'dates/format.py' import timesince %}
{% macro time(mytime) ... | Within the template, no, you cannot import python code.
The way to do this is to register the function as a jinja2 [custom filter](http://jinja.pocoo.org/docs/api/#custom-filters), like this:
In your python file:
```
from dates.format import timesince
environment = jinja2.Environment(whatever)
environment.filters['... |
Import a Python module into a Jinja template? | 4,828,406 | 25 | 2011-01-28T12:51:30Z | 11,856,935 | 11 | 2012-08-08T02:43:00Z | [
"python",
"jinja2",
"python-import"
] | Is it possible to import a Python module into a Jinja template so I can use its functions?
For example, I have a **format.py** file that contains methods for formatting dates and times. In a Jinja macro, can I do something *like* the following?
```
{% from 'dates/format.py' import timesince %}
{% macro time(mytime) ... | Just pass the function into the template, like so
```
from dates.format import timesince
your_template.render(timesince)
```
and in the template, just call it like any other function,
```
{% macro time(mytime) %}
<a title="{{ mytime }}">{{ timesince(mytime) }}</a>
{% endmacro %}
```
Functions are first-class ci... |
how to direct output into a txt file in python in windows | 4,828,885 | 6 | 2011-01-28T13:46:28Z | 4,829,070 | 15 | 2011-01-28T14:05:01Z | [
"python"
] | ```
import itertools
variations = itertools.product('abc', repeat=3)
for variations in variations:
variation_string = ""
for letter in variations:
variation_string += letter
print (variation_string)
```
How can I redirect output into a txt file (on windows platform)? | From the console you would write:
```
python script.py > out.txt
```
If you want to do it in Python then you would write:
```
with open('out.txt', 'w') as f:
f.write(something)
```
Obviously this is just a trivial example. You'd clearly do more inside the with block. |
How to remove read-only attrib directory with Python in Windows? | 4,829,043 | 22 | 2011-01-28T14:02:39Z | 4,829,092 | 8 | 2011-01-28T14:07:59Z | [
"python",
"windows",
"attributes"
] | I have a read only directory copied from version controlled directory which is locked.

When I tried to remove this directory with `shutil.rmtree(TEST_OBJECTS_DIR)` command, I got the following error message.
```
WindowsError: [Error 5] Access is deni... | Not tested but It would be, something like to enable write access.
```
import os, stat
os.chmod(ur"file_path_name", stat.S_IWRITE)
```
You may need to combine with os.walk to make everything write enable. something like
```
for root, dirs, files in os.walk(ur'root_dir'):
for fname in files:
full_path = ... |
How to remove read-only attrib directory with Python in Windows? | 4,829,043 | 22 | 2011-01-28T14:02:39Z | 4,829,285 | 29 | 2011-01-28T14:26:39Z | [
"python",
"windows",
"attributes"
] | I have a read only directory copied from version controlled directory which is locked.

When I tried to remove this directory with `shutil.rmtree(TEST_OBJECTS_DIR)` command, I got the following error message.
```
WindowsError: [Error 5] Access is deni... | If you are using shutil.rmtree, you can use the onerror member of that function to provide a function that takes three params: function, path, and exception info. You can use this method to mark read only files as writable while you are deleting your tree.
```
import os, shutil, stat
def on_rm_error( func, path, exc_... |
Efficiently solving a letter/number problem in Python | 4,829,950 | 8 | 2011-01-28T15:31:11Z | 4,830,141 | 10 | 2011-01-28T15:47:34Z | [
"python",
"math"
] | If `a = 15` and `152` is represented as `a2` while `215` is represented as `2a` then a number x has to be found such that
`8x = 8*x8`
I tried this naive Python code
```
>>> i = 0
>>> while(i<=100000000000000000):
... if(int("8"+str(i))==8*int(str(i)+"8")):
... break
... i = i+1
... print i
```
but it is tak... | A bit of math helps here: Let *x* be a natural number with *n* digits. Then 8x = 8 \* 10^n + x, and x8 = 10\*x + 8. So the equation to be solved is 8 \* 10^n + x = 8 \* (10\*x + 8) = 80\*x + 64, where *x* and *n* must be natural numbers. It immediately follows that x = (8 \* 10^n - 64) / 79. Now we only have to check w... |
Python: How do I format a date in Jinja2? | 4,830,535 | 114 | 2011-01-28T16:19:35Z | 4,830,613 | 12 | 2011-01-28T16:29:11Z | [
"python",
"jinja2"
] | Using Jinja2, how do I format a date field? I know in Python I can simply do this:
```
print car.date_of_manufacture.strftime('%Y-%m-%d')
```
But how do I format the date in Jinja2? Thanks. | I think you have to write your own filter for that. It's actually the example for custom filters in the documentation: <http://jinja.pocoo.org/docs/api/#custom-filters> |
Python: How do I format a date in Jinja2? | 4,830,535 | 114 | 2011-01-28T16:19:35Z | 4,830,620 | 193 | 2011-01-28T16:29:46Z | [
"python",
"jinja2"
] | Using Jinja2, how do I format a date field? I know in Python I can simply do this:
```
print car.date_of_manufacture.strftime('%Y-%m-%d')
```
But how do I format the date in Jinja2? Thanks. | There are two ways to do it. The direct approach would be to simply call (and print) the strftime() method in your template, for example
```
{{ car.date_of_manufacture.strftime('%Y-%m-%d') }}
```
Another, sightly better approach would be to define your own filter, e.g.:
```
def format_datetime(value, format='medium'... |
Python: How do I format a date in Jinja2? | 4,830,535 | 114 | 2011-01-28T16:19:35Z | 17,382,079 | 11 | 2013-06-29T16:03:44Z | [
"python",
"jinja2"
] | Using Jinja2, how do I format a date field? I know in Python I can simply do this:
```
print car.date_of_manufacture.strftime('%Y-%m-%d')
```
But how do I format the date in Jinja2? Thanks. | Here's the filter that I ended up using for strftime in Jinja2 and Flask
```
@app.template_filter('strftime')
def _jinja2_filter_datetime(date, fmt=None):
date = dateutil.parser.parse(date)
native = date.replace(tzinfo=None)
format='%b %d, %Y'
return native.strftime(format)
```
And then you use the fi... |
Python: How do I format a date in Jinja2? | 4,830,535 | 114 | 2011-01-28T16:19:35Z | 28,204,762 | 7 | 2015-01-29T00:01:39Z | [
"python",
"jinja2"
] | Using Jinja2, how do I format a date field? I know in Python I can simply do this:
```
print car.date_of_manufacture.strftime('%Y-%m-%d')
```
But how do I format the date in Jinja2? Thanks. | If you are dealing with a lower level time object (I often just use integers), and don't want to write a custom filter for whatever reason, an approach I use is to pass the strftime function into the template as a variable, where it can be called where you need it.
For example:
```
import time
context={
'now':int... |
Is it possible to use pip to install a package from a private github repository? | 4,830,856 | 138 | 2011-01-28T16:52:32Z | 4,837,571 | 139 | 2011-01-29T15:08:11Z | [
"python",
"git",
"github",
"pip"
] | As the title suggests I am trying to install a python package from a private github repo. For a public repository I can issue the following command which works fine:
```
pip install git+git://github.com/django/django.git
```
However if I try this for a private repository:
```
pip install git+git://github.com/echweb/... | You can use `git+ssh` URI scheme, but you MUST set username:
```
pip install git+ssh://git@github.com/echweb/echweb-utils.git
```
See **`git@`** part into URI?
PS: Also read about [deploy keys](http://help.github.com/deploy-keys/).
PPS: In my installation the "git+ssh" URI scheme works only with "editable" requirem... |
Is it possible to use pip to install a package from a private github repository? | 4,830,856 | 138 | 2011-01-28T16:52:32Z | 12,523,376 | 18 | 2012-09-21T02:09:58Z | [
"python",
"git",
"github",
"pip"
] | As the title suggests I am trying to install a python package from a private github repo. For a public repository I can issue the following command which works fine:
```
pip install git+git://github.com/django/django.git
```
However if I try this for a private repository:
```
pip install git+git://github.com/echweb/... | Also works with Bitbucket:
```
pip install git+ssh://git@bitbucket.org/username/projectname.git
```
Pip will use your SSH keys in this case. |
Is it possible to use pip to install a package from a private github repository? | 4,830,856 | 138 | 2011-01-28T16:52:32Z | 12,581,878 | 8 | 2012-09-25T11:20:23Z | [
"python",
"git",
"github",
"pip"
] | As the title suggests I am trying to install a python package from a private github repo. For a public repository I can issue the following command which works fine:
```
pip install git+git://github.com/django/django.git
```
However if I try this for a private repository:
```
pip install git+git://github.com/echweb/... | The syntax for the requirements file is given here:
<https://pip.pypa.io/en/latest/reference/pip_install.html#requirements-file-format>
So for example:
```
-e git+http://github.com/rwillmer/django-behave#egg=django-behave
```
if you want the source to stick around after installation
or just
```
git+http://github.... |
Is it possible to use pip to install a package from a private github repository? | 4,830,856 | 138 | 2011-01-28T16:52:32Z | 14,431,634 | 42 | 2013-01-21T02:17:50Z | [
"python",
"git",
"github",
"pip"
] | As the title suggests I am trying to install a python package from a private github repo. For a public repository I can issue the following command which works fine:
```
pip install git+git://github.com/django/django.git
```
However if I try this for a private repository:
```
pip install git+git://github.com/echweb/... | As an additional technique, if you have the private repository cloned locally, you can do:
```
pip install git+file://c:/repo/directory
``` |
Is it possible to use pip to install a package from a private github repository? | 4,830,856 | 138 | 2011-01-28T16:52:32Z | 15,597,781 | 26 | 2013-03-24T11:19:28Z | [
"python",
"git",
"github",
"pip"
] | As the title suggests I am trying to install a python package from a private github repo. For a public repository I can issue the following command which works fine:
```
pip install git+git://github.com/django/django.git
```
However if I try this for a private repository:
```
pip install git+git://github.com/echweb/... | You can do it directly with the HTTPS URL like this:
```
pip install git+https://github.com/username/repo.git
```
This also works just appending that line in the requirements.txt in a django project, for instance. |
Making shlex.split respect UNC paths | 4,830,874 | 4 | 2011-01-28T16:54:06Z | 4,831,026 | 7 | 2011-01-28T17:10:31Z | [
"python",
"shlex"
] | I'm using `shlex.split` to tokenize arguments for a `subprocess.Popen` call. However, when one of those args is a UNC path, things get hairy:
```
import shlex
raw_args = '-path "\\\\server\\folder\\file.txt" -arg SomeValue'
args = shlex.split(raw_args)
print raw_args
print args
```
produces
```
-path "\\server\fol... | I don't know if this helps you:
```
>>> shlex.split(raw_args, posix=False)
['-path', '"\\\\server\\folder\\file.txt"', '-arg', 'SomeValue']
``` |
Matplotlib not displaying figures | 4,831,220 | 8 | 2011-01-28T17:29:03Z | 4,831,249 | 14 | 2011-01-28T17:31:52Z | [
"python",
"numpy",
"matplotlib",
"scipy"
] | This must be a really basic question: I am trying to use Matplotlib. Here's the basic example from the [documentation](http://matplotlib.sourceforge.net/api/pyplot_api.html).
```
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,5,0.1)
y = np.sin(x)
plt.plot(x,y)
```
I have tried this in `ipython`, `... | You're missing `plt.show()` to order matplotlib to show a window with the graph. |
function inside function | 4,831,680 | 72 | 2011-01-28T18:23:10Z | 4,831,750 | 96 | 2011-01-28T18:29:58Z | [
"python",
"coding-style"
] | Simple example. Two methods, one called from another:
```
def method_a(arg):
some_data = method_b(arg)
def method_b(arg):
return some_data
```
In Python we can declare `def` inside another `def`. So, if `method_b` is required for and called only from `method_a`, should I declare `method_b` inside `method_a`?... | ```
>>> def sum(x, y):
... def do_it():
... return x + y
... return do_it
...
>>> a = sum(1, 3)
>>> a
<function do_it at 0xb772b304>
>>> a()
4
```
Is this what you were looking for? It's called a [closure](http://en.wikipedia.org/wiki/Closure_%28computer_programming%29). |
function inside function | 4,831,680 | 72 | 2011-01-28T18:23:10Z | 4,831,762 | 11 | 2011-01-28T18:31:19Z | [
"python",
"coding-style"
] | Simple example. Two methods, one called from another:
```
def method_a(arg):
some_data = method_b(arg)
def method_b(arg):
return some_data
```
In Python we can declare `def` inside another `def`. So, if `method_b` is required for and called only from `method_a`, should I declare `method_b` inside `method_a`?... | It's actually fine to declare one function inside another one. This is specially useful creating decorators.
However, as a rule of thumb, if the function is complex (more than 10 lines) it might be a better idea to declare it on the module level. |
function inside function | 4,831,680 | 72 | 2011-01-28T18:23:10Z | 4,832,497 | 29 | 2011-01-28T20:01:28Z | [
"python",
"coding-style"
] | Simple example. Two methods, one called from another:
```
def method_a(arg):
some_data = method_b(arg)
def method_b(arg):
return some_data
```
In Python we can declare `def` inside another `def`. So, if `method_b` is required for and called only from `method_a`, should I declare `method_b` inside `method_a`?... | You don't really gain much by doing this, in fact it slows `method_a` down because it'll define and recompile the other function every time it's called. Given that, it would probably be better to just prefix the function name with underscore to indicate it's a private method -- i.e. `_method_b`.
I suppose you *might* ... |
function inside function | 4,831,680 | 72 | 2011-01-28T18:23:10Z | 24,090,940 | 10 | 2014-06-06T21:32:14Z | [
"python",
"coding-style"
] | Simple example. Two methods, one called from another:
```
def method_a(arg):
some_data = method_b(arg)
def method_b(arg):
return some_data
```
In Python we can declare `def` inside another `def`. So, if `method_b` is required for and called only from `method_a`, should I declare `method_b` inside `method_a`?... | A function inside of a function is commonly used for [closures](http://en.wikipedia.org/wiki/Closure_%28computer_programming%29).
(There is a [lot of contention](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) over [what exactly](http://stackoverflow.com/questions/36636/what-is-a-closure) ma... |
Is there something like a "symbolic link" (in *nixes terms) but for objects in ZODB in Plone? | 4,832,664 | 4 | 2011-01-28T20:18:25Z | 5,051,291 | 7 | 2011-02-19T14:27:01Z | [
"python",
"symlink",
"plone",
"zope",
"zodb"
] | Suppose I have an object in `/school1/document-rules`.
Suppose in another context, `/school2`, I need to have the same `document-rules` that is available in `/school1/document-rules`.
In ZODB, having `/school1/document-rules` and `/school2/document-rules` means I have two different objects.
I would like to know if i... | [SimpleAlias](http://plone.org/products/simplealias/) does what you want. I've used it and it works well. You could also look at [collective.alias](http://pypi.python.org/pypi/collective.alias) |
Read in tuple of lists from text file as tuple, not string - Python | 4,832,789 | 5 | 2011-01-28T20:32:59Z | 4,832,832 | 10 | 2011-01-28T20:36:47Z | [
"python",
"file",
"list",
"text",
"tuples"
] | I have a text file I would like to read in that contains rows of tuples. Each tuple/row in text is in the form of ('description string', [list of integers 1], [list of integers 2]). Where the text file might look something like:
('item 1', [1,2,3,4] , [4,3,2,1])
('item 2', [ ] , [4,3,2,1])
('item 3, [1,2] , [ ])
... | What about using `eval`?
**EDIT** See @Ignacio's answer using `ast.literal_eval`.
```
>>> c = eval("('item 1', [1,2,3,4] , [4,3,2,1])")
>>> c
('item 1', [1, 2, 3, 4], [4, 3, 2, 1])
```
I would only recommend doing this if you are 100% sure of the contents of the file.
```
>>> def myFunc(myString, myList1, myList2):... |
Read in tuple of lists from text file as tuple, not string - Python | 4,832,789 | 5 | 2011-01-28T20:32:59Z | 4,832,854 | 19 | 2011-01-28T20:39:10Z | [
"python",
"file",
"list",
"text",
"tuples"
] | I have a text file I would like to read in that contains rows of tuples. Each tuple/row in text is in the form of ('description string', [list of integers 1], [list of integers 2]). Where the text file might look something like:
('item 1', [1,2,3,4] , [4,3,2,1])
('item 2', [ ] , [4,3,2,1])
('item 3, [1,2] , [ ])
... | You're looking for [`ast.literal_eval()`](http://docs.python.org/library/ast.html#ast.literal_eval).
```
>>> ast.literal_eval("('item 1', [1,2,3,4] , [4,3,2,1])")
('item 1', [1, 2, 3, 4], [4, 3, 2, 1])
``` |
the order in which result of a set is printed in Python | 4,833,297 | 4 | 2011-01-28T21:38:10Z | 4,833,307 | 8 | 2011-01-28T21:39:09Z | [
"python"
] | I'm new to Python. I've a question. Some one could help me.
I do the following in the command prompt:
```
>>> a=set()
>>> for i in range(0,8):
... a.add((i,j))
...
```
the answer that I get when I print it is like this:
```
>>> a
set([(2, 7), (4, 7), (6, 7), (5, 7), (7, 7), (0, 7), (1, 7), (3, 7)])
```
I under... | You are right that a set doesn't store its elements in sorted order. If you want to get a list of the elements in the set in sorted order you can use the built-in function [`sorted`](http://docs.python.org/library/functions.html#sorted):
```
>>> a
set([(2, 7), (4, 7), (6, 7), (5, 7), (7, 7), (0, 7), (1, 7), (3, 7)])
>... |
% confuses python raw sql query | 4,833,966 | 4 | 2011-01-28T23:18:10Z | 4,833,979 | 8 | 2011-01-28T23:21:54Z | [
"python",
"rawsql",
"sql-like"
] | Following [this SO question](http://stackoverflow.com/questions/4451726/empty-a-relational-database-schema), I'm trying to "truncate" all tables related to a certain django application using the following raw sql commands in python:
```
cursor.execute("set foreign_key_checks = 0")
cursor.execute("select concat('trunca... | Have you tried %%? That quotes a % in Python string-formatting. |
Ruby Equivalent of Python "_" | 4,834,125 | 3 | 2011-01-28T23:48:51Z | 4,834,137 | 11 | 2011-01-28T23:50:28Z | [
"python",
"ruby",
"irb",
"python-idle"
] | In Python, you can use the `_` field to grab the last computed value. That's really useful in IDLE. Does Ruby have an equivalent for IRB?
An example from Python:
```
>>> 2 + 2
4
>>> _
4
>>> "Me " + "You"
'Me You'
>>> _
'Me You'
``` | \_ isn't working?
```
host:~ user$ irb
irb(main):001:0> s = "test"
=> "test"
irb(main):002:0> puts _
test
=> nil
``` |
Is this the right way to run a shell script inside Python? | 4,834,483 | 28 | 2011-01-29T01:20:28Z | 4,834,864 | 31 | 2011-01-29T03:00:18Z | [
"python",
"linux",
"bash",
"shell",
"unix"
] | ```
import subprocess
retcode = subprocess.call(["/home/myuser/go.sh", "abc.txt", "xyz.txt"])
```
When I run these 2 lines, will I be doing exactly this?:
```
/home/myuser/go.sh abc.txt xyz.txt
```
Why do I get this error? But when I run go.sh normally, I don't get that error.
```
File "/usr/lib/python2.6/subproces... | > OSError: [Errno 8] Exec format error
This is an error reported by the operating system when trying to run `/home/myuser/go.sh`.
It looks to me like the shebang (`#!`) line of `go.sh` is not valid.
Here's a sample script that runs from the shell but not from `Popen`:
```
#\!/bin/sh
echo "You've just called $0 $@."... |
Is this the right way to run a shell script inside Python? | 4,834,483 | 28 | 2011-01-29T01:20:28Z | 5,010,951 | 9 | 2011-02-15T23:58:19Z | [
"python",
"linux",
"bash",
"shell",
"unix"
] | ```
import subprocess
retcode = subprocess.call(["/home/myuser/go.sh", "abc.txt", "xyz.txt"])
```
When I run these 2 lines, will I be doing exactly this?:
```
/home/myuser/go.sh abc.txt xyz.txt
```
Why do I get this error? But when I run go.sh normally, I don't get that error.
```
File "/usr/lib/python2.6/subproces... | Change the code to following:
```
retcode = subprocess.call(["/home/myuser/go.sh", "abc.txt", "xyz.txt"], shell=True,)
```
Notice "shell=True"
From: <http://docs.python.org/library/subprocess.html#module-subprocess>
> On Unix, with shell=True: If args is a
> string, it specifies the command
> string to execute thro... |
How do I run a bash script inside Python, but act as if it's running from another directory? | 4,834,807 | 5 | 2011-01-29T02:47:21Z | 4,834,818 | 11 | 2011-01-29T02:50:08Z | [
"python",
"linux",
"bash",
"shell",
"unix"
] | ```
subprocess.call(["/home/blah/trunk/blah/run.sh", "/tmp/ad_xml", "/tmp/video_xml"])
```
I do this. However, inside my run.sh, I have "relative" paths.
So, I have to "cd" into that directory, and then run the shell script. How do I do that? | Use the `cwd` argument to `subprocess.call()`
From the docs here: <http://docs.python.org/library/subprocess.html>
> If `cwd` is not None, the childâs
> current directory will be changed to
> `cwd` before it is executed. Note that
> this directory is not considered when
> searching the executable, so you canât
> ... |
first order differences along a given axis in NumPy array | 4,835,075 | 9 | 2011-01-29T04:04:26Z | 4,835,121 | 7 | 2011-01-29T04:15:46Z | [
"python",
"arrays",
"numpy"
] | ```
#compute first differences of 1d array
from numpy import *
x = arange(10)
y = zeros(len(x))
for i in range(1,len(x)):
y[i] = x[i] - x[i-1]
print y
```
The above code works but there must be at least one easy, pythonesque way to do this without having to use a for loop. Any suggestions? | What about:
```
diff(x)
# array([1, 1, 1, 1, 1, 1, 1, 1, 1])
``` |
python's `with` statement target is unexpectedly None | 4,835,611 | 11 | 2011-01-29T06:58:46Z | 4,835,626 | 16 | 2011-01-29T07:03:25Z | [
"python",
"with-statement",
"contextmanager",
"as-keyword"
] | seems like I do not understand something with---the python `with` statement.
Consider this class:
```
class test(object):
def __enter__(self): pass
def __exit__(self, *ignored): pass
```
now, when using it with `with`, like in
```
with test() as michael:
print repr(michael)
```
I would expect some outp... | From the [`with`](http://docs.python.org/reference/compound_stmts.html#the-with-statement) documentation:
> If a target was included in the `with` statement, the return value from `__enter__()` is assigned to it.
If you `def __enter__(self): return self`, then your expected output is produced. |
Incrementing sub-sets of matrices in Python | 4,836,048 | 2 | 2011-01-29T09:14:07Z | 4,836,064 | 7 | 2011-01-29T09:19:24Z | [
"python",
"matrix",
"numpy"
] | I want to increment a small subsection (variable) of an matrix [illustrative code below] - but running over them by loops seems sloppy and inelegant -- and I suspect is the slowest way to do this calc.
One of the ideas I had was to create another array of ones, of the dimensions that i want to increment (2x3 in example... | You can do the same simply by:
```
a[3:5,4:7] += 1
``` |
Do I need to add a db_index to this Django model? | 4,836,327 | 20 | 2011-01-29T10:25:21Z | 4,836,354 | 35 | 2011-01-29T10:32:14Z | [
"python",
"mysql",
"database",
"django",
"indexing"
] | ```
class Comments(models.Model):
content = models.ForeignKey(Content)
```
Do I need to add a db\_index to "content"? Or would that automatically be indexed because it's a foreign key? | Unless specified otherwise, an index will be created for a `ForeignKey`. Relevant source code:
```
class ForeignKey(RelatedField, Field):
# snip
def __init__(self, to, to_field=None, rel_class=ManyToOneRel, **kwargs):
# snip
if 'db_index' not in kwargs:
kwargs['db_index'] = True
``` |
End of support for python 2.7? | 4,836,375 | 64 | 2011-01-29T10:37:00Z | 4,836,440 | 8 | 2011-01-29T10:47:15Z | [
"python",
"python-3.x",
"python-2.7",
"python-2.x"
] | Is there a known date/timeframe when python 2.7 will not be supported any more in favor of python 3? | [This article](http://www.computerworlduk.com/news/applications/18331/python-2-nears-end-of-life/) says: âWhen 2.7 is released, the 2.x line will move into five years of a bug fix-only mode.â
So, as far as I see, Python 2.7 was the last 2.x feature-adding release, and though found bugs are going to be fixed (for s... |
End of support for python 2.7? | 4,836,375 | 64 | 2011-01-29T10:37:00Z | 4,836,447 | 23 | 2011-01-29T10:47:57Z | [
"python",
"python-3.x",
"python-2.7",
"python-2.x"
] | Is there a known date/timeframe when python 2.7 will not be supported any more in favor of python 3? | In May 2010, [Word of God](http://tvtropes.org/pmwiki/pmwiki.php/Main/WordOfGod) was that [patchlevel releases for Python 2.7 will probably be made for at least 6 years](http://mail.python.org/pipermail/python-dev/2010-May/099971.html).
So, maybe 2016, probably later.
Edit: Pushed back to 2020. See the revision to PE... |
End of support for python 2.7? | 4,836,375 | 64 | 2011-01-29T10:37:00Z | 23,062,904 | 51 | 2014-04-14T14:34:03Z | [
"python",
"python-3.x",
"python-2.7",
"python-2.x"
] | Is there a known date/timeframe when python 2.7 will not be supported any more in favor of python 3? | As of 13 Apr 2014, from <http://hg.python.org/peps/rev/76d43e52d978> (PEP 373, Python 2.7 Release Schedule):
> The End Of Life date (EOL, sunset date) for Python 2.7 has been moved
> five years into the future, to 2020. This decision was made to
> clarify the status of Python 2.7 and relieve worries for those users
> ... |
Does Python have a built in function for string natural sort? | 4,836,710 | 113 | 2011-01-29T11:55:53Z | 4,836,734 | 102 | 2011-01-29T12:01:31Z | [
"python",
"sorting",
"python-3.x"
] | Using Python 3.x, I have a list of strings for which I would like to perform a natural alphabetical sort.
**Natural sort:** The order by which files in Windows are sorted.
For instance, the following list is naturally sorted (what I want):
```
['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
```
... | Try this:
```
import re
def natural_sort(l):
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
return sorted(l, key = alphanum_key)
```
Output:
```
['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12... |
Does Python have a built in function for string natural sort? | 4,836,710 | 113 | 2011-01-29T11:55:53Z | 8,940,266 | 16 | 2012-01-20T10:53:53Z | [
"python",
"sorting",
"python-3.x"
] | Using Python 3.x, I have a list of strings for which I would like to perform a natural alphabetical sort.
**Natural sort:** The order by which files in Windows are sorted.
For instance, the following list is naturally sorted (what I want):
```
['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
```
... | I wrote a function based on <http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html> which adds the ability to still pass in your own 'key' parameter. I need this in order to perform a natural sort of lists that contain more complex objects (not just strings).
```
import re
def natural_so... |
Does Python have a built in function for string natural sort? | 4,836,710 | 113 | 2011-01-29T11:55:53Z | 16,090,640 | 54 | 2013-04-18T18:37:05Z | [
"python",
"sorting",
"python-3.x"
] | Using Python 3.x, I have a list of strings for which I would like to perform a natural alphabetical sort.
**Natural sort:** The order by which files in Windows are sorted.
For instance, the following list is naturally sorted (what I want):
```
['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
```
... | Here's a much more pythonic version of Mark Byer's answer:
```
import re
def natural_sort_key(s, _nsre=re.compile('([0-9]+)')):
return [int(text) if text.isdigit() else text.lower()
for text in re.split(_nsre, s)]
```
Now this function can be used as a key in any function that uses it, like `list.sor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.