title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
How to prevent xml.ElementTree fromstring from dropping commentnode | 5,409,161 | 7 | 2011-03-23T17:21:11Z | 5,411,766 | 12 | 2011-03-23T21:19:30Z | [
"python",
"xml",
"elementtree"
] | I have tho following code fragment:
```
from xml.etree.ElementTree import fromstring,tostring
mathml = fromstring(input)
for elem in mathml.getiterator():
elem.tag = 'm:' + elem.tag
return tostring(mathml)
```
When i input the following `input`:
```
<math>
<a> 1 2 3 </a> <b />
<foo>Uitleg<... | You cannot with `xml.etree`, because its parser ignores comments (which is acceptable behaviour for an xml parser by the way). But you can if you use the (compatible) [lxml](http://lxml.de/) library, which allows you to configure [parser options](http://lxml.de/parsing.html#parsers).
```
from lxml import etree
parser... |
Can I combine two decorators into a single one in Python? | 5,409,450 | 15 | 2011-03-23T17:48:14Z | 5,409,491 | 10 | 2011-03-23T17:52:51Z | [
"python",
"decorator"
] | Is there a way to combine two decorators into one new decorator in python?
I realize I can just apply multiple decorators to a function, but I was curious as to whether there's some simple way to combine two into a new one. | Yes. See the definition of a decorator, [here](http://docs.python.org/reference/compound_stmts.html#grammar-token-decorated).
Something like this should work:
```
def multiple_decorators(func):
return decorator1(decorator2(func))
@multiple_decorators
def foo(): pass
``` |
Can I combine two decorators into a single one in Python? | 5,409,450 | 15 | 2011-03-23T17:48:14Z | 5,409,569 | 23 | 2011-03-23T18:00:59Z | [
"python",
"decorator"
] | Is there a way to combine two decorators into one new decorator in python?
I realize I can just apply multiple decorators to a function, but I was curious as to whether there's some simple way to combine two into a new one. | A bit more general:
```
def composed(*decs):
def deco(f):
for dec in reversed(decs):
f = dec(f)
return f
return deco
```
Then
```
@composed(dec1, dec2)
def some(f):
pass
```
is equivalent to
```
@dec1
@dec2
def some(f):
pass
``` |
Sheet music library | 5,411,185 | 13 | 2011-03-23T20:25:08Z | 5,411,214 | 20 | 2011-03-23T20:27:36Z | [
"python",
"music"
] | I'm a python hacker looking to build a sheet music app. I'm comfortable with reading/understanding sheet music (played piano for many years). Here are my complete newbie questions..
Is there a standard for representing notes digitally? I don't want to reinvent any wheels.
Given a sequence of notes and durations, is t... | Take a look at [lilypond](http://lilypond.org/). It uses LaTeX to typeset sheet music. Its input format is simple text, and can be generated pretty easily with Python or whatever.
[Abjad](http://abjad.mbrsi.org/) is a "Python API for Formalized Score Control" and a wrapper around lilypond, but I haven't used it and so... |
How to remove trailing whitespace in code, using another script? | 5,411,603 | 22 | 2011-03-23T21:04:11Z | 5,411,660 | 23 | 2011-03-23T21:09:34Z | [
"python"
] | Something like:
```
import fileinput
for lines in fileinput.FileInput("test.txt", inplace=1):
lines = lines.strip()
if lines == '': continue
print lines
```
But nothing is being printed on stdout.
Assuming some string named `foo`:
```
foo.lstrip() # to remove leading white space
foo.rstrip() # to remov... | `fileinput` seems to be for multiple input streams. This is what I would do:
```
with open("test.txt") as file:
for line in file:
line = line.rstrip()
if line:
print line
``` |
Python Run a daemon sub-process & read stdout | 5,411,780 | 8 | 2011-03-23T21:20:39Z | 5,413,588 | 14 | 2011-03-24T01:10:56Z | [
"python"
] | I need to run a program and gather its output to stdout. This program (socat) needs to run in the background for the duration of the python script. Socat sits in dameon mode once it's run, but first it outputs some lines to stdout that I need for the rest of my script.
Command: `socat -d -d PTY: PTY:`
Output:
```
20... | ```
#!/usr/bin/python
from subprocess import Popen, PIPE, STDOUT
import pty
import os
cmd = 'socat -d -d PTY: PTY:'
master, slave = pty.openpty()
p = Popen(cmd, shell=True, stdin=PIPE, stdout=slave, stderr=slave, close_fds=True)
stdout = os.fdopen(master)
print stdout.readline()
print stdout.readline()
```
There ar... |
Multiplying polynomials in python | 5,413,158 | 4 | 2011-03-24T00:00:41Z | 5,413,198 | 13 | 2011-03-24T00:08:03Z | [
"python"
] | I did the adding and the subtracting but I am having a really hard time multiplying to polynomials in python.
For example, if I have:
```
2X^2 + 5X + 1 [1,5,2]
```
and...
```
3X^3 + 4X^2 + X + 6 [6,1,4,3]
```
We get:
```
6X^5 + 23X^4 + 25X^3 + 21X^2 + 31X + 6 [6,31,21,25,23,6]
```
I am desperate. I have been wor... | ```
s1 = [1,5,2]
s2 = [6,1,4,3]
res = [0]*(len(s1)+len(s2)-1)
for o1,i1 in enumerate(s1):
for o2,i2 in enumerate(s2):
res[o1+o2] += i1*i2
```
**Edit:** In honor of @katrielalex:
```
import collections
import itertools
class Polynomial(object):
def __init__(self, *args):
"""
Create a p... |
Writing/Reading arrays of Data in Open Office using Python. Anyone have any example code? | 5,413,449 | 7 | 2011-03-24T00:46:28Z | 5,414,690 | 8 | 2011-03-24T04:15:24Z | [
"python",
"excel",
"spreadsheet",
"openoffice-calc",
"libreoffice"
] | So I have written a class that makes it extremely easy to interface with either Excel or Gnumeric using Python, and would like to extend the class to include Open Office as well. I could do this in 30 minutes if I just had the ability to do the following:
* Set a single value on an arbitrary
sheet and workbook
* Get... | As a matter of fact, to acess OpenOffice or LibreOffice via Python one has to go through an absolutely opaque amount of boiler plate inherited from the StarOffice times - never properly documented (one feels) or simplified since then.
I had once lectured on this subject, and I took almot 40 minutes, just to retrieve t... |
Python Imaging Library - Text rendering | 5,414,639 | 31 | 2011-03-24T04:07:02Z | 5,414,875 | 10 | 2011-03-24T04:43:54Z | [
"python",
"python-imaging-library",
"imaging"
] | I'm trying to render some text using PIL, but the result that comes out is, frankly, crap.
For example, here's some text I wrote in Photoshop:

and what comes out of PIL:

As you can s... | I've never used PIL, but a quick review of the documentation for the Draw method indicates that PIL provides a way to render **simple** graphics. Photoshop provides a way to render **complex** graphics. To get anywhere close to Photoshop-like results requires, at a minimum, font hinting and anti-aliasing. PIL's documen... |
Python Imaging Library - Text rendering | 5,414,639 | 31 | 2011-03-24T04:07:02Z | 5,414,956 | 16 | 2011-03-24T04:57:34Z | [
"python",
"python-imaging-library",
"imaging"
] | I'm trying to render some text using PIL, but the result that comes out is, frankly, crap.
For example, here's some text I wrote in Photoshop:

and what comes out of PIL:

As you can s... | Try using [pycairo](http://www.cairographics.org/pycairo/) - the python bindings for the Cairo drawing library -- it is usefull for more refined drawing, with antialiased lines,
and such - and you can generate vector based images as well
Correctly handling fonts, and layout is complicated, and requires the use of
the ... |
Python Imaging Library - Text rendering | 5,414,639 | 31 | 2011-03-24T04:07:02Z | 5,430,111 | 42 | 2011-03-25T08:29:07Z | [
"python",
"python-imaging-library",
"imaging"
] | I'm trying to render some text using PIL, but the result that comes out is, frankly, crap.
For example, here's some text I wrote in Photoshop:

and what comes out of PIL:

As you can s... | I came up with my own solution that I find acceptable.
What I did was render the text large, like 3x the size it needs to be then scale it resize it down with antialiasing, it's not 100% perfect, but it's a hell of a lot better than default, and doesn't require cairo or pango.
for example,
```
image = Image.new("RGB... |
How to strip unicode "punctuation" from Python string | 5,414,818 | 6 | 2011-03-24T04:36:10Z | 5,414,883 | 10 | 2011-03-24T04:45:33Z | [
"python",
"unicode",
"punctuation"
] | Here's the problem, I have a unicode string as input to a python sqlite query. The query failed ('like'). It turns out the string, 'FRANCE' doesn't have 6 characters, it has seven. And the seventh is . . . unicode U+FEFF, a zero-width no-break space.
How on earth do I trap a class of such things before the query? | You may use the unicodedata categories as part of the unicode data table in Python:
```
>>> unicodedata.category(u'a')
'Ll'
>>> unicodedata.category(u'.')
'Po'
>>> unicodedata.category(u',')
'Po'
```
The categories for punctation characters start with 'P' as you can see.
So you need to filter you out char by char (us... |
customize select in django admin | 5,414,853 | 3 | 2011-03-24T04:40:59Z | 5,414,924 | 7 | 2011-03-24T04:53:03Z | [
"python",
"django",
"django-admin",
"customization"
] | I have a model, one field of it is a ForeignKey, so i see select in django admin, is it possiable to customize labels of this select?
```
class Model(models.Model):
name = models.CharField()
def __unicode__(self):
return self.name
class Part(models.Model):
name = models.CharField()
parent = ... | If you mean the field label:
using code from:
[Django Admin - Overriding the widget of a custom form field](http://stackoverflow.com/questions/3469979/django-admin-overriding-the-widget-of-a-custom-form-field/4466958#4466958)
```
# forms.py
from django import forms
from django.contrib import admin
class ProductAdmi... |
os.listdir() fails for every directory on UNIX | 5,417,265 | 2 | 2011-03-24T09:47:55Z | 5,448,937 | 7 | 2011-03-27T11:30:29Z | [
"python",
"linux",
"ubuntu"
] | This is the most strangest error ever - Python os.listdir() fails for every directory:
```
Python 2.5.2 (r252:60911, Jan 20 2010, 23:14:04)
[GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.listdir("/")
Tra... | This is caused by a rootkit. I'm just looking at the same problem on a Debian (lenny) server I administer. Look at the top of strace:
```
open("/etc/ld.so.preload", O_RDONLY) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=22, ...}) = 0
mmap(NULL, 22, PROT_READ|PROT_WRITE, MAP_PRIVATE, 3, 0) = 0x7feb24b32000
close(3) ... |
Get date object for the first/last day of the current year | 5,417,727 | 10 | 2011-03-24T10:28:18Z | 5,417,911 | 11 | 2011-03-24T10:42:46Z | [
"python",
"date"
] | I need to get `date` objects for the first and last day in the current year.
Currently I'm using this code which works fine, but I'm curious if there's a nicer way to do it; e.g. without having to specify the month/day manually.
```
from datetime import date
a = date(date.today().year, 1, 1)
b = date(date.today().yea... | The only real improvement that comes to mind is to give your variables more descriptive names than `a` and `b`. |
Computing an md5 hash of a data structure | 5,417,949 | 29 | 2011-03-24T10:46:12Z | 5,419,072 | 16 | 2011-03-24T12:27:28Z | [
"python",
"data-structures",
"md5"
] | I want to compute an md5 hash not of a string, but of an entire data structure. I understand the mechanics of a way to do this (dispatch on the type of the value, canonicalize dictionary key order and other randomness, recurse into sub-values, etc). But it seems like the kind of operation that would be generally useful... | bencode sorts dictionaries so:
```
import hashlib
import bencode
data = ['only', 'lists', [1,2,3],
'dictionaries', {'a':0,'b':1}, 'numbers', 47, 'strings']
data_md5 = hashlib.md5(bencode.bencode(data)).hexdigest()
print data_md5
```
prints:
```
af1b88ca9fd8a3e828b40ed1b9a2cb20
``` |
Computing an md5 hash of a data structure | 5,417,949 | 29 | 2011-03-24T10:46:12Z | 10,288,255 | 35 | 2012-04-23T21:01:47Z | [
"python",
"data-structures",
"md5"
] | I want to compute an md5 hash not of a string, but of an entire data structure. I understand the mechanics of a way to do this (dispatch on the type of the value, canonicalize dictionary key order and other randomness, recurse into sub-values, etc). But it seems like the kind of operation that would be generally useful... | [json.dumps()](http://docs.python.org/library/json.html) can sort dictionaries by key. So you don't need other dependencies:
```
import hashlib
import json
data = ['only', 'lists', [1,2,3], 'dictionaries', {'a':0,'b':1}, 'numbers', 47, 'strings']
data_md5 = hashlib.md5(json.dumps(data, sort_keys=True)).hexdigest()
p... |
How can one replace an element with text in lxml? | 5,418,201 | 6 | 2011-03-24T11:11:49Z | 5,420,500 | 8 | 2011-03-24T14:13:54Z | [
"python",
"xml",
"lxml",
"elementtree"
] | It's easy to completely remove a given element from an XML document with lxml's implementation of the ElementTree API, but I can't see an easy way of consistently replacing an element with some text. For example, given the following input:
```
input = '''<everything>
<m>Some text before <r/></m>
<m><r/> and some text ... | I think that unutbu's XSLT solution is probably the correct way to achieve your goal.
However, here's a somewhat hacky way to achieve it, by modifying the tails of `<r/>` tags and then using `etree.strip_elements`.
```
from lxml import etree
data = '''<everything>
<m>Some text before <r/></m>
<m><r/> and some text a... |
Index of duplicates items in a python list | 5,419,204 | 24 | 2011-03-24T12:37:04Z | 5,419,248 | 9 | 2011-03-24T12:40:24Z | [
"python"
] | Does anyone know how I can get the index position of duplicate items in a python list?
I have tried doing this and it keeps giving me only the index of the 1st occurrence of the of the item in the list.
```
List = ['A', 'B', 'A', 'C', 'E']
```
I want it to give me:
```
index 0: A
index 2: A
``` | ```
>>> def duplicates(lst, item):
... return [i for i, x in enumerate(lst) if x == item]
...
>>> duplicates(List, "A")
[0, 2]
```
To get all duplicates, you can use the below method, but it is not very efficient. If efficiency is important you should consider Ignacio's solution instead.
```
>>> dict((x, duplicate... |
Index of duplicates items in a python list | 5,419,204 | 24 | 2011-03-24T12:37:04Z | 5,419,424 | 10 | 2011-03-24T12:52:04Z | [
"python"
] | Does anyone know how I can get the index position of duplicate items in a python list?
I have tried doing this and it keeps giving me only the index of the 1st occurrence of the of the item in the list.
```
List = ['A', 'B', 'A', 'C', 'E']
```
I want it to give me:
```
index 0: A
index 2: A
``` | ```
dups = collections.defaultdict(list)
for i, e in enumerate(L):
dups[e].append(i)
for k, v in sorted(dups.iteritems()):
if len(v) >= 2:
print '%s: %r' % (k, v)
```
And extrapolate from there. |
Index of duplicates items in a python list | 5,419,204 | 24 | 2011-03-24T12:37:04Z | 5,419,576 | 22 | 2011-03-24T13:02:07Z | [
"python"
] | Does anyone know how I can get the index position of duplicate items in a python list?
I have tried doing this and it keeps giving me only the index of the 1st occurrence of the of the item in the list.
```
List = ['A', 'B', 'A', 'C', 'E']
```
I want it to give me:
```
index 0: A
index 2: A
``` | You want to pass in the optional second parameter to index, the location where you want index to start looking. After you find each match, reset this parameter to the location just after the match that was found.
```
def list_duplicates_of(seq,item):
start_at = -1
locs = []
while True:
try:
... |
How to overwrite the previous print to stdout in python? | 5,419,389 | 53 | 2011-03-24T12:50:06Z | 5,419,443 | 15 | 2011-03-24T12:53:40Z | [
"python"
] | If I had the following code:
```
for x in range(10):
print x
```
I would get the output of
```
1
2
etc..
```
What I would like to do is instead of printing a newline, I want to replace the previous value and overwrite it with the new value on the same line. | Suppress the newline and print `\r`.
```
print 1,
print '\r2'
```
or write to stdout:
```
sys.stdout.write('1')
sys.stdout.write('\r2')
``` |
How to overwrite the previous print to stdout in python? | 5,419,389 | 53 | 2011-03-24T12:50:06Z | 5,419,488 | 61 | 2011-03-24T12:56:11Z | [
"python"
] | If I had the following code:
```
for x in range(10):
print x
```
I would get the output of
```
1
2
etc..
```
What I would like to do is instead of printing a newline, I want to replace the previous value and overwrite it with the new value on the same line. | One way is to use the carriage return (`'\r'`) character to return to the start of the line without advancing to the next line:
```
for x in range(10):
print '{0}\r'.format(x),
print
```
The comma at the end of the print statement tells it not to go to the next line. The last print statement advances to the next ... |
How to overwrite the previous print to stdout in python? | 5,419,389 | 53 | 2011-03-24T12:50:06Z | 21,840,062 | 25 | 2014-02-17T21:56:46Z | [
"python"
] | If I had the following code:
```
for x in range(10):
print x
```
I would get the output of
```
1
2
etc..
```
What I would like to do is instead of printing a newline, I want to replace the previous value and overwrite it with the new value on the same line. | Since I ended up here via Google but am using Python 3, here's how this would work in Python 3:
```
for x in range(10):
print("Progress {:2.1%}".format(x / 10), end="\r")
```
Related answer here: [In Python 3 how can I suppress the newline after a print statement with the comma?](http://stackoverflow.com/question... |
How to overwrite the previous print to stdout in python? | 5,419,389 | 53 | 2011-03-24T12:50:06Z | 25,105,111 | 13 | 2014-08-03T13:27:14Z | [
"python"
] | If I had the following code:
```
for x in range(10):
print x
```
I would get the output of
```
1
2
etc..
```
What I would like to do is instead of printing a newline, I want to replace the previous value and overwrite it with the new value on the same line. | @Mike DeSimone answer will probably work most of the time. But...
```
for x in ['abc', 1]:
print '{}\r'.format(x),
-> 1bc
```
This is because the `'\r'` only goes back to the beginning of the line but doesn't clear the output.
## EDIT: Better solution (than my old proposal below)
If POSIX support is enough for... |
Reading from a frequently updated file | 5,419,888 | 21 | 2011-03-24T13:24:22Z | 5,420,116 | 28 | 2011-03-24T13:42:52Z | [
"python",
"file-io",
"fopen"
] | I'm currently writing a program in python on a Linux system. The objective is to read a log file and execute a bash command upon finding a particular string. The log file is being constantly written to by another program. My question is:
If I open the file using the open() method will my Python file object be updated ... | I would recommend looking at David Beazley's [Generator Tricks for Python](http://www.dabeaz.com/generators/), especially **Part 5: Processing Infinite Data**. It is exactly what you need to handle the Python equivalent of a `tail -f logfile` command in real-time.
```
# follow.py
#
# Follow a file like tail -f.
impor... |
Reading from a frequently updated file | 5,419,888 | 21 | 2011-03-24T13:24:22Z | 5,420,461 | 9 | 2011-03-24T14:11:10Z | [
"python",
"file-io",
"fopen"
] | I'm currently writing a program in python on a Linux system. The objective is to read a log file and execute a bash command upon finding a particular string. The log file is being constantly written to by another program. My question is:
If I open the file using the open() method will my Python file object be updated ... | "An interactive session is worth 1000 words"
```
>>> f1 = open("bla.txt", "wt")
>>> f2 = open("bla.txt", "rt")
>>> f1.write("bleh")
>>> f2.read()
''
>>> f1.flush()
>>> f2.read()
'bleh'
>>> f1.write("blargh")
>>> f1.flush()
>>> f2.read()
'blargh'
```
In other words - yes, a single "open" will do. |
How to install psycopg2 with "pip" on Python? | 5,420,789 | 362 | 2011-03-24T14:33:55Z | 5,421,174 | 58 | 2011-03-24T15:01:46Z | [
"python",
"virtualenv",
"psycopg2",
"pip"
] | I'm using *`virtualenv`* and I need to install "psycopg2".
I have done the following:
```
pip install http://pypi.python.org/packages/source/p/psycopg2/psycopg2-2.4.tar.gz#md5=24f4368e2cfdc1a2b03282ddda814160
```
And I have the following messages:
```
Downloading/unpacking http://pypi.python.org/packages/source/p/p... | I recently configured psycopg2 on a windows machine. The easiest install is using a windows executable binary. You can find it at <http://stickpeople.com/projects/python/win-psycopg/>.
To install the native binary in a virtual envrionment, use easy\_install:
```
C:\virtualenv\Scripts\> activate.bat
(virtualenv) C:\vi... |
How to install psycopg2 with "pip" on Python? | 5,420,789 | 362 | 2011-03-24T14:33:55Z | 5,450,183 | 565 | 2011-03-27T15:25:16Z | [
"python",
"virtualenv",
"psycopg2",
"pip"
] | I'm using *`virtualenv`* and I need to install "psycopg2".
I have done the following:
```
pip install http://pypi.python.org/packages/source/p/psycopg2/psycopg2-2.4.tar.gz#md5=24f4368e2cfdc1a2b03282ddda814160
```
And I have the following messages:
```
Downloading/unpacking http://pypi.python.org/packages/source/p/p... | I found this post searching for a Linux solution to this problem.
This [post by "goshawk"](https://web.archive.org/web/20110305033324/http://goshawknest.wordpress.com/2011/02/16/how-to-install-psycopg2-under-virtualenv/) gave me the solution: run `sudo apt-get install libpq-dev python-dev` if you are on Ubuntu/Debian.... |
How to install psycopg2 with "pip" on Python? | 5,420,789 | 362 | 2011-03-24T14:33:55Z | 9,972,321 | 18 | 2012-04-02T07:22:06Z | [
"python",
"virtualenv",
"psycopg2",
"pip"
] | I'm using *`virtualenv`* and I need to install "psycopg2".
I have done the following:
```
pip install http://pypi.python.org/packages/source/p/psycopg2/psycopg2-2.4.tar.gz#md5=24f4368e2cfdc1a2b03282ddda814160
```
And I have the following messages:
```
Downloading/unpacking http://pypi.python.org/packages/source/p/p... | If you using Mac OS, you should install PostgreSQL from source.
After installation is finished, you need to add this path using:
```
export PATH=/local/pgsql/bin:$PATH
```
or you can append the path like this:
```
export PATH=.../:usr/local/pgsql/bin
```
in your `.profile` file or `.zshrc` file.
This maybe vary by... |
How to install psycopg2 with "pip" on Python? | 5,420,789 | 362 | 2011-03-24T14:33:55Z | 12,714,734 | 27 | 2012-10-03T18:39:02Z | [
"python",
"virtualenv",
"psycopg2",
"pip"
] | I'm using *`virtualenv`* and I need to install "psycopg2".
I have done the following:
```
pip install http://pypi.python.org/packages/source/p/psycopg2/psycopg2-2.4.tar.gz#md5=24f4368e2cfdc1a2b03282ddda814160
```
And I have the following messages:
```
Downloading/unpacking http://pypi.python.org/packages/source/p/p... | For Python 3 you should use `sudo apt-get install libpq-dev python3-dev` under Debian. |
How to install psycopg2 with "pip" on Python? | 5,420,789 | 362 | 2011-03-24T14:33:55Z | 13,158,616 | 93 | 2012-10-31T13:03:24Z | [
"python",
"virtualenv",
"psycopg2",
"pip"
] | I'm using *`virtualenv`* and I need to install "psycopg2".
I have done the following:
```
pip install http://pypi.python.org/packages/source/p/psycopg2/psycopg2-2.4.tar.gz#md5=24f4368e2cfdc1a2b03282ddda814160
```
And I have the following messages:
```
Downloading/unpacking http://pypi.python.org/packages/source/p/p... | On CentOS, you need the postgres dev packages:
```
sudo yum install python-devel postgresql-devel
```
That was the solution on CentOS 6 at least. |
How to install psycopg2 with "pip" on Python? | 5,420,789 | 362 | 2011-03-24T14:33:55Z | 19,711,831 | 51 | 2013-10-31T16:26:26Z | [
"python",
"virtualenv",
"psycopg2",
"pip"
] | I'm using *`virtualenv`* and I need to install "psycopg2".
I have done the following:
```
pip install http://pypi.python.org/packages/source/p/psycopg2/psycopg2-2.4.tar.gz#md5=24f4368e2cfdc1a2b03282ddda814160
```
And I have the following messages:
```
Downloading/unpacking http://pypi.python.org/packages/source/p/p... | if you're on a mac you can use homebrew
```
brew install postgresql
```
And all other options are here: <http://www.postgresql.org/download/macosx/>
Good luck |
How to install psycopg2 with "pip" on Python? | 5,420,789 | 362 | 2011-03-24T14:33:55Z | 20,725,421 | 61 | 2013-12-22T01:51:34Z | [
"python",
"virtualenv",
"psycopg2",
"pip"
] | I'm using *`virtualenv`* and I need to install "psycopg2".
I have done the following:
```
pip install http://pypi.python.org/packages/source/p/psycopg2/psycopg2-2.4.tar.gz#md5=24f4368e2cfdc1a2b03282ddda814160
```
And I have the following messages:
```
Downloading/unpacking http://pypi.python.org/packages/source/p/p... | On Mac Mavericks with Postgres.app version 9.3.2.0 RC2 I needed to use the following code after installing Postgres:
`sudo PATH=$PATH:/Applications/Postgres.app/Contents/Versions/9.3/bin pip install psycopg2` |
How to install psycopg2 with "pip" on Python? | 5,420,789 | 362 | 2011-03-24T14:33:55Z | 27,042,998 | 17 | 2014-11-20T15:14:25Z | [
"python",
"virtualenv",
"psycopg2",
"pip"
] | I'm using *`virtualenv`* and I need to install "psycopg2".
I have done the following:
```
pip install http://pypi.python.org/packages/source/p/psycopg2/psycopg2-2.4.tar.gz#md5=24f4368e2cfdc1a2b03282ddda814160
```
And I have the following messages:
```
Downloading/unpacking http://pypi.python.org/packages/source/p/p... | This is what worked for me (On RHEL, CentOS:
```
sudo yum install postgresql postgresql-devel python-devel
```
And now include the path to your postgresql binary dir with you pip install:
```
sudo PATH=$PATH:/usr/pgsql-9.3/bin/ pip install psycopg2
```
Make sure to include the correct path. Thats all :) |
How to install psycopg2 with "pip" on Python? | 5,420,789 | 362 | 2011-03-24T14:33:55Z | 28,003,482 | 14 | 2015-01-17T19:41:13Z | [
"python",
"virtualenv",
"psycopg2",
"pip"
] | I'm using *`virtualenv`* and I need to install "psycopg2".
I have done the following:
```
pip install http://pypi.python.org/packages/source/p/psycopg2/psycopg2-2.4.tar.gz#md5=24f4368e2cfdc1a2b03282ddda814160
```
And I have the following messages:
```
Downloading/unpacking http://pypi.python.org/packages/source/p/p... | The answers so far are too much like magic recipes. The error that you received tells you that pip cannot find a needed part of the PostgreSQL Query library. Possibly this is because you have it installed in a non-standard place for your OS which is why the message suggests using the --pg-config option.
But a more com... |
How to install psycopg2 with "pip" on Python? | 5,420,789 | 362 | 2011-03-24T14:33:55Z | 32,424,596 | 10 | 2015-09-06T14:27:15Z | [
"python",
"virtualenv",
"psycopg2",
"pip"
] | I'm using *`virtualenv`* and I need to install "psycopg2".
I have done the following:
```
pip install http://pypi.python.org/packages/source/p/psycopg2/psycopg2-2.4.tar.gz#md5=24f4368e2cfdc1a2b03282ddda814160
```
And I have the following messages:
```
Downloading/unpacking http://pypi.python.org/packages/source/p/p... | On `Debian/Ubuntu`:
First install and build dependencies of `psycopg2` package:
```
# apt-get build-dep python-psycopg2
```
Then in your virtual environment, compile and install `psycopg2` module:
```
(env)$ pip install psycopg2
``` |
Python program to traverse directories and read file information | 5,421,599 | 13 | 2011-03-24T15:30:57Z | 5,421,660 | 7 | 2011-03-24T15:36:26Z | [
"python",
"fileinfo",
"directory-traversal"
] | I'm just getting started with Python but already have found it much more productive than Bash shell scripting.
I'm trying to write a Python script that will traverse every directory that branches from the directory I launch the script in, and for each file it encounters, load an instance of this class:
```
class File... | Try
```
info = []
for path, dirs, files in os.walk("."):
info.extend(FileInfo(filename, path) for filename in files)
```
or
```
info = [FileInfo(filename, path)
for path, dirs, files in os.walk(".")
for filename in files]
```
to get a list of one `FileInfo` instance per file. |
Python program to traverse directories and read file information | 5,421,599 | 13 | 2011-03-24T15:30:57Z | 5,421,671 | 17 | 2011-03-24T15:37:13Z | [
"python",
"fileinfo",
"directory-traversal"
] | I'm just getting started with Python but already have found it much more productive than Bash shell scripting.
I'm trying to write a Python script that will traverse every directory that branches from the directory I launch the script in, and for each file it encounters, load an instance of this class:
```
class File... | I'd use `os.walk` doing the following:
```
def getInfos(currentDir):
infos = []
for root, dirs, files in os.walk(currentDir): # Walk directory tree
for f in files:
infos.append(FileInfo(f,root))
return infos
``` |
How to send non-English unicode string using HTTP header? | 5,423,223 | 14 | 2011-03-24T17:39:36Z | 5,426,648 | 21 | 2011-03-24T23:05:50Z | [
"python",
"ios",
"google-app-engine",
"unicode",
"http-headers"
] | I am novice to HTTP related matters.
My question is in iOS development, I would like to send a string using HTTP Header, so I'm using:
```
[httpRequest setValue:@"nonEnglishString" forHTTPHeaderField:@"customHeader"];
```
The receiving server is Python(Google App Engine), saving the string value in the db model as St... | > Is it not POSSIBLE or ALLOWED to send non-English string using HTTP Header?
It's not possible as per HTTP standards to put non-ISO-8859-1 characters directly in an HTTP header. That gives you ASCII ("English"?) characters plus common Western European diacriticals.
However in practice you can't even use the extended... |
Checking if sys.argv[x] is defined | 5,423,381 | 32 | 2011-03-24T17:55:37Z | 5,423,400 | 39 | 2011-03-24T17:57:07Z | [
"python"
] | What would be the best way to check if a variable was passed along for the script:
```
try:
sys.argv[1]
except NameError:
startingpoint = 'blah'
else:
startingpoint = sys.argv[1]
``` | Check the length of `sys.argv`:
```
if len(sys.argv) > 1:
blah = sys.argv[1]
else:
blah = 'blah'
```
Some people prefer the exception-based approach you've suggested (eg, `try: blah = sys.argv[1]; except IndexError: blah = 'blah'`), but I don't like it as much because it doesn't âscaleâ nearly as nicely (... |
Checking if sys.argv[x] is defined | 5,423,381 | 32 | 2011-03-24T17:55:37Z | 5,423,511 | 12 | 2011-03-24T18:07:26Z | [
"python"
] | What would be the best way to check if a variable was passed along for the script:
```
try:
sys.argv[1]
except NameError:
startingpoint = 'blah'
else:
startingpoint = sys.argv[1]
``` | Another way I haven't seen listed yet is to set your sentinel value ahead of time. This method takes advantage of Python's lazy evaluation, in which you don't always have to provide an `else` statement. Example:
```
startingpoint = 'blah'
if len(sys.argv) >= 2:
startingpoint = sys.argv[1]
```
Or if you're going syn... |
Checking if sys.argv[x] is defined | 5,423,381 | 32 | 2011-03-24T17:55:37Z | 5,423,609 | 23 | 2011-03-24T18:17:04Z | [
"python"
] | What would be the best way to check if a variable was passed along for the script:
```
try:
sys.argv[1]
except NameError:
startingpoint = 'blah'
else:
startingpoint = sys.argv[1]
``` | In the end, the difference between `try, except` and testing `len(sys.argv)` isn't all that significant. They're both a bit hackish compared to [`argparse`](http://docs.python.org/library/argparse.html#module-argparse).
---
This occurs to me, though -- what do people think of this, as a sort of low-budget argparse?
... |
Python: how to check if input is a number? | 5,424,716 | 56 | 2011-03-24T19:51:53Z | 5,424,739 | 141 | 2011-03-24T19:53:47Z | [
"python",
"input",
"types"
] | How do I check if a user's input is a number (e.g. `-1`, `0`, `1`, etc.)?
```
user_input = input("Enter something:")
if type(user_input) == int:
print("Is a number")
else:
print("Not a number")
```
The above won't work since `input` always returns a string. | Simply try converting it to an int and then bailing out if it doesn't work.
```
try:
val = int(userInput)
except ValueError:
print("That's not an int!")
``` |
Python: how to check if input is a number? | 5,424,716 | 56 | 2011-03-24T19:51:53Z | 5,424,750 | 26 | 2011-03-24T19:54:34Z | [
"python",
"input",
"types"
] | How do I check if a user's input is a number (e.g. `-1`, `0`, `1`, etc.)?
```
user_input = input("Enter something:")
if type(user_input) == int:
print("Is a number")
else:
print("Not a number")
```
The above won't work since `input` always returns a string. | Apparently this will not work for negative values, but it will for positive. Sorry about that, just learned about this a few hours ago myself as I have just recently gotten into Python.
Use isdigit()
```
if userinput.isdigit():
#do stuff
``` |
Python: how to check if input is a number? | 5,424,716 | 56 | 2011-03-24T19:51:53Z | 8,754,600 | 12 | 2012-01-06T07:14:26Z | [
"python",
"input",
"types"
] | How do I check if a user's input is a number (e.g. `-1`, `0`, `1`, etc.)?
```
user_input = input("Enter something:")
if type(user_input) == int:
print("Is a number")
else:
print("Not a number")
```
The above won't work since `input` always returns a string. | For Python 3 the following will work.
```
userInput = 0
while True:
try:
userInput = int(input("Enter something: "))
except ValueError:
print("Not an integer!")
continue
else:
print("Yes an integer!")
break
``` |
Python: how to check if input is a number? | 5,424,716 | 56 | 2011-03-24T19:51:53Z | 20,457,619 | 7 | 2013-12-08T19:04:44Z | [
"python",
"input",
"types"
] | How do I check if a user's input is a number (e.g. `-1`, `0`, `1`, etc.)?
```
user_input = input("Enter something:")
if type(user_input) == int:
print("Is a number")
else:
print("Not a number")
```
The above won't work since `input` always returns a string. | EDITED:
You could also use this below code to find out if its a number or also a negative
```
import re
num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$")
isnumber = re.match(num_format,givennumber)
if isnumber:
print "given string is number"
```
you could also change your format to your specific requirement.... |
Using PIL to detect a scan of a blank page | 5,426,482 | 4 | 2011-03-24T22:47:25Z | 5,505,754 | 10 | 2011-03-31T20:14:22Z | [
"python",
"computer-vision",
"python-imaging-library",
"imaging",
"image-scanner"
] | So I often run huge double-sided scan jobs on an unintelligent Canon multifunction, which leaves me with a huge folder of JPEGs. Am I insane to consider using PIL to analyze a folder of images to detect scans of blank pages and flag them for deletion?
Leaving the folder-crawling and flagging parts out, I imagine this ... | Here is an alternative solution, using [mahotas](http://luispedro.org/software/mahotas) and [milk](http://luispedro.org/software/milk).
1. Start by creating two directories: `positives/` and `negatives/` where you will manually pick out a few examples.
2. I will assume that the rest of the data is in an `unlabeled/` d... |
In Python, how to change text after it's printed? | 5,426,546 | 8 | 2011-03-24T22:54:21Z | 5,426,562 | 9 | 2011-03-24T22:56:27Z | [
"python"
] | I have a Python program I am writing and I want it to be able to change text after it is printed. For example, let's say I want to print "hello" and erase one letter every second. How would I go about doing that?
Also, I heard about curses but I can't get that to work, and I do not want to simply create new lines unti... | Here's one way to do it.
```
print 'hello',
sys.stdout.flush()
...
print '\rhell ',
sys.stdout.flush()
...
print '\rhel ',
sys.stdout.flush()
```
You can probably also get clever with ANSI escapes. Something like
```
sys.stdout.write('hello')
sys.stdout.flush()
for _ in range(5):
time.sleep(1)
sys.stdout.wri... |
Google python style guide | 5,426,754 | 10 | 2011-03-24T23:17:55Z | 5,426,851 | 19 | 2011-03-24T23:30:57Z | [
"python"
] | Why does the [Google Python Style Guide](http://google-styleguide.googlecode.com/svn/trunk/pyguide.html) prefer list comprehensions and for loops instead of filter, map, and reduce?
Deprecated Language Features:
... "Use list comprehensions and for loops instead of filter, map, and reduce. "
The explanation given : "... | `map` and `filter` are way less powerful than their list comprehension equivalent. LCs can do both filtering and mapping in one step, they don't require explicit function and can be compiled more efficiently because of their special syntax
```
# map and filter
map(lambda x:x+1, filter(lambda x:x%3, range(10)))
# same ... |
Google python style guide | 5,426,754 | 10 | 2011-03-24T23:17:55Z | 16,329,879 | 19 | 2013-05-02T03:29:36Z | [
"python"
] | Why does the [Google Python Style Guide](http://google-styleguide.googlecode.com/svn/trunk/pyguide.html) prefer list comprehensions and for loops instead of filter, map, and reduce?
Deprecated Language Features:
... "Use list comprehensions and for loops instead of filter, map, and reduce. "
The explanation given : "... | The [Google Python Style guide](http://google-styleguide.googlecode.com/svn/trunk/pyguide.html) does not say
> prefer list comprehensions and for loops instead of filter, map, and
> reduce
Rather, the full sentence reads,
> Use list comprehensions and for loops instead of filter and map *when
> the function argument... |
Method for parsing text Cc field of email header? | 5,426,789 | 3 | 2011-03-24T23:22:11Z | 5,426,887 | 11 | 2011-03-24T23:35:01Z | [
"python",
"parsing",
"email",
"email-headers"
] | I have the plain text of a Cc header field that looks like so:
`friend@email.com, John Smith <john.smith@email.com>,"Smith, Jane" <jane.smith@uconn.edu>`
Are there any battle tested modules for parsing this properly?
(bonus if it's in python! the email module just returns the raw text without any methods for splitti... | There are a bunch of function available as a standard python module, but I think you're looking for
[email.utils.parseaddr()](http://docs.python.org/library/email.util.html#email.utils.getaddresses) or [email.utils.getaddresses()](http://docs.python.org/library/email.util.html#email.utils.parseaddr%20email.utils.parsea... |
Loading environment modules within a python script | 5,427,040 | 7 | 2011-03-24T23:54:29Z | 18,324,607 | 8 | 2013-08-19T23:17:11Z | [
"python",
"module",
"environment-variables",
"environment-modules"
] | Is there a way for a python script to load and use [environment modules](http://modules.sourceforge.net/)? `os.system('module load xxx')` doesn't work since it executes them in a subshell (at least, I think that's what's happening). | I know this question's kind of old but it's still relevant enough that I was looking for the answer, so I'm posting what I found that works as well:
At least in the 3.2.9+ sources, you can include the python "init" file to get a python function version of module:
```
>>> execfile('/usr/local/Modules/default/init/pyth... |
Cannot install psycopg2 on OSX 10.6.7 with XCode4 | 5,427,157 | 18 | 2011-03-25T00:12:19Z | 5,427,280 | 8 | 2011-03-25T00:33:54Z | [
"python",
"install",
"xcode4",
"psycopg2",
"pip"
] | Trying to install psycopg2 on OSX results in the following:
```
building 'psycopg2._psycopg' extension
creating build/temp.macosx-10.6-universal-2.6
creating build/temp.macosx-10.6-universal-2.6/psycopg
gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRA... | The problem is that the Python 2.6 included with OS X 10.6 was built for three supported architectures (i386, x86\_64, and ppc for compatibility with earlier releases of OS X) and Python's Distutils tries to ensure that all C extension modules are built with the same `arch`s as the Python interpreter and library. But X... |
Cannot install psycopg2 on OSX 10.6.7 with XCode4 | 5,427,157 | 18 | 2011-03-25T00:12:19Z | 5,431,924 | 49 | 2011-03-25T11:40:26Z | [
"python",
"install",
"xcode4",
"psycopg2",
"pip"
] | Trying to install psycopg2 on OSX results in the following:
```
building 'psycopg2._psycopg' extension
creating build/temp.macosx-10.6-universal-2.6
creating build/temp.macosx-10.6-universal-2.6/psycopg
gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRA... | It seems that there was something wrong with the ARCHFLAGS actually sticking, so finally using:
sudo env ARCHFLAGS="-arch i386 -arch x86\_64" pip install psycopg2
actually worked. |
How to pass a url as a url parameter when there is a question mark in it? | 5,428,296 | 6 | 2011-03-25T03:39:08Z | 5,428,324 | 9 | 2011-03-25T03:45:27Z | [
"python",
"google-app-engine",
"url-parameters"
] | I am using this line to pass the a `url`, `main_id` and `user_tag_list` to the handler:
```
self.response.out.write("""
<a href="/tc?url=%s&main_id=%s&user_tag_list=%s" title="edit tag set">edit tag set</a>
""" %
(item.url, main_id, item.tag_list))
```
this works fine except that when there is already a question ma... | You just want to use `urllib.quote`
```
>>> import urllib
>>> urllib.quote('http://www.google.com?q=Zombie+Apocalypse')
'http%3A//www.google.com%3Fq%3DZombie%2BApocalypse'
```
So:
```
urllib.quote(item.url)
``` |
How to replace all '0xa0' chars with a ' ' in a bunch of text files? | 5,428,844 | 4 | 2011-03-25T05:24:09Z | 5,429,346 | 11 | 2011-03-25T06:41:46Z | [
"python",
"bash",
"shell",
"text",
"utf-8"
] | i've been trying to mass-edit a bunch of text files to utf-8 in python and this error keeps popping out. is there a way to replace them in some python scrips or bash commands?
i used the code:
```
writer = codecs.open(os.path.join(wrd, 'dict.en'), 'wtr', 'utf-8')
for infile in glob.glob(os.path.join(wrd,'*.txt')):
... | OK, first point: your output file is set to automatically encode text written to it as `utf-8`, so don't include an explicit `encode('utf-8')` method call when passing arguments to the `write()` method.
So the first thing to try is to simply use the following in your inner loop:
```
writer.write(line)
```
If that do... |
How to write list of strings to file, adding newlines? | 5,429,064 | 9 | 2011-03-25T05:59:36Z | 5,429,109 | 12 | 2011-03-25T06:04:19Z | [
"python"
] | ```
def generator():
nums = ['09', '98', '87', '76', '65', '54', '43']
s_chars = ['*', '&', '^', '%', '$', '#', '@',]
data = open("list.txt", "w")
for c in s_chars:
for n in nums:
data.write(c + n)
data.close()
```
I would like to add a newline after every "c + n". I know ... | Change
```
data.write(c + n)
```
to
```
data.write("%s%s\n" % (c, n))
``` |
Why is sys.maxint < (sys.maxint - 100 + 0.01) in Python? | 5,429,860 | 7 | 2011-03-25T07:55:13Z | 5,429,890 | 12 | 2011-03-25T07:59:14Z | [
"python",
"floating-point"
] | Why is sys.maxint < (sys.maxint - 100 + 0.01) in Python? | This is probably due to loss of precision for very large floating point values. (the adding of `0.01` converts the right-hand-side to float).
**Edit:** I have tried to come up with an exact explanation of what happens here, but to no avail. So I [posted a question](http://stackoverflow.com/questions/5431517/can-someon... |
python: how to get information about a function? | 5,430,020 | 15 | 2011-03-25T08:18:47Z | 5,430,038 | 22 | 2011-03-25T08:21:08Z | [
"python",
"function",
"methods"
] | When information about a type is needed you can use:
```
my_list = []
dir(my_list)
```
gets:
```
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__... | In python: `help(my_list.append)` for example, will give you the docstring of the function.
```
>>> my_list = []
>>> help(my_list.append)
Help on built-in function append:
append(...)
L.append(object) -- append object to end
``` |
retrieving list items from request.POST in django/python | 5,430,470 | 13 | 2011-03-25T09:10:20Z | 5,430,528 | 35 | 2011-03-25T09:17:57Z | [
"python",
"django"
] | In my `request.POST` i am getting a query dictionary , one of the items in this dictionary is a list with multiple items (`pass_id`)
eg.
I want to retrieve each of the values in `pass_id` and store in a new list. Can you suggest the code for this? | <http://docs.djangoproject.com/en/dev/ref/request-response/#django.http.QueryDict.getlist>
```
request.POST.getlist('pass_id')
``` |
Classes or closures for simple things in Python | 5,430,502 | 18 | 2011-03-25T09:15:29Z | 5,432,287 | 8 | 2011-03-25T12:14:44Z | [
"python",
"performance",
"class",
"memory",
"closures"
] | I would like to know more about the functions "with memory" implemented as classes vs closures.
Consider the (very) simple example:
```
def constant(value):
def _inner():
return value
return _inner
x = constant(5)
print(x())
```
vs.
```
class Constant():
def __init__(self, value):
self._... | In Python 2.6 I get the following:
```
def foo(x):
def bar():
return x
return bar
b = foo(4)
b.__sizeof__()
>>> 44
```
But using a class:
```
class foo(object):
def __init__(self,x):
self.x = x
def __call__(self):
return self.x
c = foo(4)
c.__sizeof__()
>>> 16
```
Which loo... |
Initialization of unit-test in PyDev? | 5,430,707 | 11 | 2011-03-25T09:36:49Z | 5,584,981 | 7 | 2011-04-07T17:18:03Z | [
"python",
"eclipse",
"unit-testing",
"eclipse-plugin",
"pydev"
] | I am unit-testing my python code in eclipse using PyDev unit-testing. I right click on the appropriate file and select *Run As -> Python unit-test*. Concerning this plugin I have a few questions:
1. Is there a way to have a **setUpClass** method that is being executed before any other test within this class? Currently... | It's a PyDev bug, and has been fixed in 2.0.1.
`setUpModule()`, `tearDownModule()`, `setUpClass()`, and `tearDownClass()` are not run in the 'Python unit-test' run configuration due to the bug in PyDev 2.0.0 and earlier. In 2.0.1 they run correctly in the 'Python unit-test' and 'Python Run' configurations. I tested it... |
The Pythonic way of validating a long chain of conditions in Python | 5,431,613 | 6 | 2011-03-25T11:08:21Z | 5,431,922 | 9 | 2011-03-25T11:40:03Z | [
"python"
] | So I have a long chain of conditions that should be validated to be true. Instead of chaining a long `if` condition, I tried to be "innovative" and did it this way, which I reckon is more readable. But my question is, is this the optimal way of doing it?
Or is there a pythonic way of doing it? PS: Please respond with ... | A simpler approach is to build a tuple of the conditions and compare the tuples:
```
def site_info(s):
return s.getId(), s.getName(), s.getCustomer().getId()
if site_info(site) == site_info(site_listing):
return site_listing
else:
continue
```
If you have a lot of conditions, or the conditions are expens... |
Getting index of item while processing a list using map in python | 5,432,762 | 28 | 2011-03-25T13:02:46Z | 5,432,789 | 34 | 2011-03-25T13:04:56Z | [
"python"
] | While processing a list using map(), I want to access index of the item while inside lambda. How can I do that?
For example
```
ranked_users = ['jon','bob','jane','alice','chris']
user_details = map(lambda x: {'name':x, 'rank':?}, ranked_users)
```
How can I get rank of each user in above example? | Use [enumerate](http://docs.python.org/library/functions.html#enumerate):
```
In [3]: user_details = [{'name':x, 'rank':i} for i,x in enumerate(ranked_users)]
In [4]: user_details
Out[4]:
[{'name': 'jon', 'rank': 0},
{'name': 'bob', 'rank': 1},
{'name': 'jane', 'rank': 2},
{'name': 'alice', 'rank': 3},
{'name':... |
Python: Is it possible to make a class iterable using the standard syntax? | 5,434,400 | 27 | 2011-03-25T15:15:31Z | 5,434,478 | 40 | 2011-03-25T15:20:53Z | [
"python",
"syntax",
"attributes",
"static-methods",
"loops"
] | I have inherited a project with many large classes constituent of nothing but class objects (integers, strings, etc). I'd like to be able to check if an attribute is present without needed to define a list of attributes manually.
Is it possible to make a python *class* iterable itself using the standard syntax? That i... | Add the `__iter__` to the metaclass instead of the class itself (assuming Python 2.x):
```
class Foo(object):
bar = "bar"
baz = 1
class __metaclass__(type):
def __iter__(self):
for attr in dir(Foo):
if not attr.startswith("__"):
yield attr
```
For Py... |
Python: Is it possible to make a class iterable using the standard syntax? | 5,434,400 | 27 | 2011-03-25T15:15:31Z | 5,434,488 | 7 | 2011-03-25T15:21:30Z | [
"python",
"syntax",
"attributes",
"static-methods",
"loops"
] | I have inherited a project with many large classes constituent of nothing but class objects (integers, strings, etc). I'd like to be able to check if an attribute is present without needed to define a list of attributes manually.
Is it possible to make a python *class* iterable itself using the standard syntax? That i... | You can iterate over the class's unhidden attributes with `for attr in (elem for elem in dir(Foo) if elem[:2] != '__')`.
A less horrible way to spell that is:
```
def class_iter(Class):
return (elem for elem in dir(Class) if elem[:2] != '__')
```
then
```
for attr in class_iter(Foo):
pass
``` |
learn python the hard way exercise 40 help | 5,434,740 | 2 | 2011-03-25T15:41:23Z | 5,434,777 | 9 | 2011-03-25T15:45:05Z | [
"python"
] | hey guys i am having trouble understanding this, i dont get when themap is referenced to the cities dict really. or the last line, what is the(cities, state) part?
thanks.
```
cities = { 'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'}
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
def find_city(t... | `cities['_find']` is exactly `find_city`. So `cities['_find'](cities, state)` is the same as `find_city(cities, state)`.
The reason for my first statement is this line:
```
cities['_find'] = find_city
```
That doesn't call `find_city`, it sticks the function itself in the dictionary. Python functions are just object... |
Longest Prefix Matches for URLs | 5,434,813 | 10 | 2011-03-25T15:48:00Z | 5,435,784 | 7 | 2011-03-25T17:10:32Z | [
"python",
"url",
"trie",
"longest-prefix"
] | I need information about any standard python package which can be used for "longest prefix match" on URLs. I have gone through the two standard packages <http://packages.python.org/PyTrie/#pytrie.StringTrie> & 'http://pypi.python.org/pypi/trie/0.1.1' but they don't seem to be useful for longest prefix match task on URL... | This example is good for small url lists but does not scale well.
```
def longest_prefix_match(search, urllist):
matches = [url for url in urllist if url.startswith(search)]
if matches:
return max(matches, key=len)
else:
raise Exception("Not found")
```
An implementation using the [trie](h... |
Longest Prefix Matches for URLs | 5,434,813 | 10 | 2011-03-25T15:48:00Z | 5,479,374 | 12 | 2011-03-29T21:51:13Z | [
"python",
"url",
"trie",
"longest-prefix"
] | I need information about any standard python package which can be used for "longest prefix match" on URLs. I have gone through the two standard packages <http://packages.python.org/PyTrie/#pytrie.StringTrie> & 'http://pypi.python.org/pypi/trie/0.1.1' but they don't seem to be useful for longest prefix match task on URL... | ## Performance comparison
### `suffixtree` vs. `pytrie` vs. `trie` vs. `datrie` vs. `startswith` -functions
### Setup
The recorded time is a minimum time among 3 repetitions of 1000 searches. A trie construction time is included and spread among all searches. The search is performed on collections of hostnames from ... |
Iterate a list as pair (current, next) in Python | 5,434,891 | 59 | 2011-03-25T15:54:51Z | 5,434,929 | 13 | 2011-03-25T15:58:08Z | [
"python"
] | I sometimes need to iterate a list in Python looking at the "current" element and the "next" element. I have, till now, done so with code like:
```
for current, next in zip(the_list, the_list[1:]):
# Do something
```
This works and does what I expect, but is there's a more idiomatic or efficient way to do the sam... | Since `the_list[1:]` actually creates a copy of the whole list (excluding its first element), and `zip()` creates a list of tuples immediately when called, in total three copies of your list are created. If your list is very large, you might prefer
```
from itertools import izip, islice
for current_item, next_item in ... |
Iterate a list as pair (current, next) in Python | 5,434,891 | 59 | 2011-03-25T15:54:51Z | 5,434,936 | 63 | 2011-03-25T15:58:52Z | [
"python"
] | I sometimes need to iterate a list in Python looking at the "current" element and the "next" element. I have, till now, done so with code like:
```
for current, next in zip(the_list, the_list[1:]):
# Do something
```
This works and does what I expect, but is there's a more idiomatic or efficient way to do the sam... | Here's a relevant example from the [itertools](http://docs.python.org/library/itertools.html#recipes) module docs:
```
import itertools
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = itertools.tee(iterable)
next(b, None)
return itertools.izip(a, b)
```
How this works:
First, tw... |
Iterate a list as pair (current, next) in Python | 5,434,891 | 59 | 2011-03-25T15:54:51Z | 5,435,009 | 7 | 2011-03-25T16:05:06Z | [
"python"
] | I sometimes need to iterate a list in Python looking at the "current" element and the "next" element. I have, till now, done so with code like:
```
for current, next in zip(the_list, the_list[1:]):
# Do something
```
This works and does what I expect, but is there's a more idiomatic or efficient way to do the sam... | Iterating by index can do the same thing:
```
#!/usr/bin/python
the_list = [1, 2, 3, 4]
for i in xrange(len(the_list) - 1):
current_item, next_item = the_list[i], the_list[i + 1]
print(current_item, next_item)
```
Output:
```
(1, 2)
(2, 3)
(3, 4)
``` |
Python regular expression; why do the search & match appear to find alpha chars in a number string? | 5,436,506 | 2 | 2011-03-25T18:20:28Z | 5,436,561 | 7 | 2011-03-25T18:26:06Z | [
"python",
"regex"
] | I'm running search below Idle, in Python 2.7 in a Windows Bus. 64 bit environment.
According to RegexBuddy, the search pattern ('patternalphaonly') should not produce a match against a string of digits.
I looked at "http://docs.python.org/howto/regex.html", but did not see anything there that would explain why the s... | The star operator (`*`) indicates **zero or more repetitions**. Your string has zero repetitions of an English alphabet letter because it is entirely numbers, which is perfectly valid when using the star (repeat zero times). Instead use the `+` operator, which signifies **one or more** repetitions. Example:
```
>>> n ... |
PyCharm and filters for external tools | 5,436,540 | 15 | 2011-03-25T18:24:33Z | 5,951,079 | 15 | 2011-05-10T13:47:14Z | [
"python",
"regex",
"ide",
"pycharm",
"pep8"
] | I'm trying out PyCharm for Django development and so far am extremely happy. My team strictly follows PEP8 formatting and we use the pep8 command line program to check to make sure our code conforms.
I've configured an external tool command to run pep8 and it works good. I see the capability to create filters that wil... | You're going to kick yourself when you hear this. You've missed a $ off the end of COLUMN. Thank you very much for this by the way, I followed your steps and I have it working perfectly. Your filter should be.
```
$FILE_PATH$:$LINE$:$COLUMN$:.*
```
UPD: To have it work for PyCharm 1.5 use
```
$FILE_PATH$\:$LINE$\:$C... |
Why do Perl's and Python's output of print with "\n" differ? | 5,437,269 | 3 | 2011-03-25T19:35:02Z | 5,437,296 | 15 | 2011-03-25T19:37:01Z | [
"python",
"perl"
] | Why do I need to put "\n" twice after "Content-Type: text/html" with Perl, but only once with Python? For example, the following Python script works:
```
#!/usr/bin/python
print "Content-Type: text/html\n"
print "Hello World!"
```
But the following Perl script doesn't work (it gives a premature end of script headers ... | Because print in Python prints with a newline and print in Perl does not.
`print "Hello world!"` in Python is equivalent to `print "Hello world!\n"` in perl. Perl 6 has a `say` command which does the same thing as Python's print, but sadly, Perl 6 has no stable implementations. In Perl 5.10 or later, you can use `say`... |
Why do Perl's and Python's output of print with "\n" differ? | 5,437,269 | 3 | 2011-03-25T19:35:02Z | 5,437,330 | 10 | 2011-03-25T19:40:11Z | [
"python",
"perl"
] | Why do I need to put "\n" twice after "Content-Type: text/html" with Perl, but only once with Python? For example, the following Python script works:
```
#!/usr/bin/python
print "Content-Type: text/html\n"
print "Hello World!"
```
But the following Perl script doesn't work (it gives a premature end of script headers ... | Perl's [`print`](http://perldoc.perl.org/functions/print.html) doesn't add a newline. Perl's [`say`](http://perldoc.perl.org/functions/say.html) does. These are equivalent:
```
# Python
print "Content-Type: text/html"
print ""
print "Hello World!"
# Perl
print "Content-Type: text/html\n";
print "\n";
print "Hello Wor... |
Python style - line continuation with strings? | 5,437,619 | 86 | 2011-03-25T20:12:37Z | 5,437,652 | 139 | 2011-03-25T20:16:21Z | [
"python",
"coding-style"
] | In trying to obey the python style rules, I've set my editors to a max of 79 cols.
In the PEP, it recommends using python's implied continuation within brackets, parentheses and braces. However, when dealing with strings when I hit the col limit, it gets a little weird.
For instance, trying to use a multiline
```
my... | Since [adjacent string literals are automatically joint into a single string](http://docs.python.org/reference/lexical_analysis.html#string-literal-concatenation), you can just use the implied line continuation inside parentheses as recommended by PEP 8:
```
print("Why, hello there wonderful "
"stackoverflow peo... |
Django Setup Default Logging | 5,438,642 | 70 | 2011-03-25T22:07:00Z | 5,439,502 | 107 | 2011-03-26T00:25:40Z | [
"python",
"django",
"logging"
] | I can't seem to figure out how to setup a "default" logger for my Django installation. I would like to use Django 1.3's new `LOGGING` setting in `settings.py`.
I've looked at the [Django Logging Doc's example](http://docs.djangoproject.com/en/1.3/topics/logging/#an-example), but it looks to me like they only setup han... | Figured it out...
You set the 'catch all' logger by referencing it with the empty string: `''`.
As an example, in the following setup I have the all log events getting saved to `logs/mylog.log`, with the exception of `django.request` log events which will be saved to `logs/django_request.log`. Because `'propagate'` i... |
Django Setup Default Logging | 5,438,642 | 70 | 2011-03-25T22:07:00Z | 24,146,729 | 9 | 2014-06-10T16:54:13Z | [
"python",
"django",
"logging"
] | I can't seem to figure out how to setup a "default" logger for my Django installation. I would like to use Django 1.3's new `LOGGING` setting in `settings.py`.
I've looked at the [Django Logging Doc's example](http://docs.djangoproject.com/en/1.3/topics/logging/#an-example), but it looks to me like they only setup han... | As you said in [your answer](http://stackoverflow.com/a/5439502/4794), Chris, one option to define a default logger is to use the empty string as its key.
However, I think the intended way is to define a special logger under the `root` key of the logging configuration dictionary. I found this in the [Python documentat... |
python nan and inf values | 5,438,745 | 69 | 2011-03-25T22:24:07Z | 5,438,756 | 107 | 2011-03-25T22:25:46Z | [
"python",
"numeric",
null,
"infinite"
] | Is it possible to set an element of an array to `NaN` in Python?
Additionally, is it possible to set a variable to +/- infinity? If so, is there any function to check whether a number is infinity or not? | Cast from string using `float()`:
```
>>> float('NaN')
nan
>>> float('Inf')
inf
>>> -float('Inf')
-inf
>>> float('Inf') == float('Inf')
True
>>> float('Inf') == 1
False
``` |
python nan and inf values | 5,438,745 | 69 | 2011-03-25T22:24:07Z | 5,439,471 | 33 | 2011-03-26T00:19:43Z | [
"python",
"numeric",
null,
"infinite"
] | Is it possible to set an element of an array to `NaN` in Python?
Additionally, is it possible to set a variable to +/- infinity? If so, is there any function to check whether a number is infinity or not? | Yes, you can use [`numpy`](http://numpy.scipy.org/) for that.
```
import numpy as np
a = arange(3,dtype=float)
a[0] = np.nan
a[1] = np.inf
a[2] = -np.inf
a # is now [nan,inf,-inf]
np.isnan(a[0]) # True
np.isinf(a[1]) # True
np.isinf(a[2]) # True
``` |
Flaskr SyntaxError | 5,439,917 | 5 | 2011-03-26T02:08:13Z | 5,439,997 | 11 | 2011-03-26T02:31:24Z | [
"python",
"web-frameworks",
"flask"
] | I'm trying out the Flaskr tutorial(http://flask.pocoo.org/docs/) and I got the following error after I tried to run *flaskr.py* using the terminal:
```
if __name__ == '__main__':
^
SyntaxError: invalid syntax
```
I have absolutely no idea why I got this error. Can someone help me please? | You have forgotten a closing parenthesis in your `return` line, above your `if __name__ == "__main__":` statement, you put
```
return redirect(url_for('show_entries')
```
and it should be
```
return redirect(url_for('show_entries'))
``` |
Find the default application name for a given file | 5,440,050 | 6 | 2011-03-26T02:47:48Z | 5,440,262 | 7 | 2011-03-26T03:52:12Z | [
"python",
"linux"
] | In Linux, is there a way to ask any xdg services, or gtk services, which application is the default application for a given file?
I realize that **xdg-open** will in fact, launch the correct application. However, I want to be able to display the application's name in a context menu. So that when the user clicks on the... | Use the `xdg-mime` command. It allows you to query for a mimetype, and then get the program associated, without executing it.
Note that this returns the name of the associated `.desktop` file. Then you have to locate the actual file and further parse it to get the real name of the program, even localized in any langua... |
Verifying signature on android in-app purchase message in Python on Google App Engine | 5,440,550 | 14 | 2011-03-26T05:38:40Z | 11,197,963 | 14 | 2012-06-25T21:57:57Z | [
"python",
"android",
"google-app-engine",
"in-app-purchase"
] | The sample application on the android developers site validates the purchase json using java code. Has anybody had any luck working out how to validate the purchase in python. In particular in GAE?
The following are the relevant excerpts from the android in-app billing [example program](http://developer.android.com/gu... | Here's how i did it:
```
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from base64 import b64decode
def chunks(s, n):
for start in range(0, len(s), n):
yield s[start:start+n]
def pem_format(key):
return '\n'.join([
'-----BEGIN PUBLIC KEY-... |
Verifying signature on android in-app purchase message in Python on Google App Engine | 5,440,550 | 14 | 2011-03-26T05:38:40Z | 15,263,257 | 7 | 2013-03-07T04:45:09Z | [
"python",
"android",
"google-app-engine",
"in-app-purchase"
] | The sample application on the android developers site validates the purchase json using java code. Has anybody had any luck working out how to validate the purchase in python. In particular in GAE?
The following are the relevant excerpts from the android in-app billing [example program](http://developer.android.com/gu... | I finally figured out that your base64 encoded public key from Google Play is an X.509 subjectPublicKeyInfo DER SEQUENCE, and that the signature scheme is RSASSA-PKCS1-v1\_5 and not RSASSA-PSS. If you have [PyCrypto](https://www.dlitz.net/software/pycrypto/) installed, it's actually quite easy:
```
import base64
from ... |
Counting recursion in a python program! | 5,441,244 | 7 | 2011-03-26T08:41:39Z | 5,441,339 | 13 | 2011-03-26T09:03:51Z | [
"python",
"recursion",
"static"
] | I need to count the number of times recursion in a python program. So basically I need a static variable kind of thing (like in C) which can count the number of times the function is called. | Just pass a counter with the recursion
```
def recur(n, count=0):
if n == 0:
return "Finished count %s" % count
return recur(n-1, count+1)
```
Or im sure there is some fancy decorator, Im gonna investigate that now... |
Python Dicts : Needed a better output | 5,441,555 | 4 | 2011-03-26T09:53:12Z | 5,441,578 | 16 | 2011-03-26T09:58:51Z | [
"python",
"dictionary",
"trie"
] | guys I've written a piece of code which gives the output. Now, this is a trie. Now I want to display in a aesthetic manner. Someone help me out here . My representation should be like this [http://en.wikipedia.org/wiki/File:Trie\_example.svg](http://en.wikipedia.org/wiki/File%3aTrie_example.svg)
But what I want is how... | You should try [Pydot](http://code.google.com/p/pydot/) ! This package allow you to create some graphs line :
```
import pydot
edges = [(1,2), (1,3), (1,4), (3,4)]
g = pydot.graph_from_edges(edges)
g.write_jpeg('graph_from_edges_dot.jpg', prog='dot')
```

To insta... |
Is there a shorter way of writing 'if a > b: a = b' in python? | 5,442,901 | 4 | 2011-03-26T14:20:12Z | 5,442,909 | 20 | 2011-03-26T14:22:40Z | [
"python"
] | Can you shorten the following example?
`if file_size_download > file_size: file_size_download = file_size`
It looks quite clumsy to me. | ```
a = min(a, b)
```
This is short and concise. |
Python multiprocessing pool.map for multiple arguments | 5,442,910 | 134 | 2011-03-26T14:23:10Z | 5,442,981 | 71 | 2011-03-26T14:36:42Z | [
"python",
"multiprocessing"
] | In the Python multiprocessing library, is there a variant of pool.map which support multiple arguments?
```
text = "test"
def harvester(text, case):
X = case[0]
return text+ str(X)
if __name__ == '__main__':
pool = multiprocessing.Pool(processes=6)
case = RAW_DATASET
pool.map(harvester(text,case),... | My initial thought was to use `partial`, and as J.F. Sebastian indicated, `partial` works in this instance in Python >=2.7, so I am posting this, with the caveat that it won't work in 2.6.
Also note that in the above code, you're passing the result of `harvester(text, case)` instead of the function `harvester` itself.... |
Python multiprocessing pool.map for multiple arguments | 5,442,910 | 134 | 2011-03-26T14:23:10Z | 5,443,941 | 157 | 2011-03-26T17:24:28Z | [
"python",
"multiprocessing"
] | In the Python multiprocessing library, is there a variant of pool.map which support multiple arguments?
```
text = "test"
def harvester(text, case):
X = case[0]
return text+ str(X)
if __name__ == '__main__':
pool = multiprocessing.Pool(processes=6)
case = RAW_DATASET
pool.map(harvester(text,case),... | > is there a variant of pool.map which support multiple arguments?
Python 3.3 includes [`pool.starmap()` method](http://docs.python.org/dev/library/multiprocessing.html#multiprocessing.pool.Pool.starmap):
```
#!/usr/bin/env python3
from functools import partial
from itertools import repeat
from multiprocessing import... |
Python multiprocessing pool.map for multiple arguments | 5,442,910 | 134 | 2011-03-26T14:23:10Z | 21,130,146 | 46 | 2014-01-15T06:01:53Z | [
"python",
"multiprocessing"
] | In the Python multiprocessing library, is there a variant of pool.map which support multiple arguments?
```
text = "test"
def harvester(text, case):
X = case[0]
return text+ str(X)
if __name__ == '__main__':
pool = multiprocessing.Pool(processes=6)
case = RAW_DATASET
pool.map(harvester(text,case),... | I think the below will be better
```
def multi_run_wrapper(args):
return add(*args)
def add(x,y):
return x+y
if __name__ == "__main__":
from multiprocessing import Pool
pool = Pool(4)
results = pool.map(multi_run_wrapper,[(1,2),(2,3),(3,4)])
print results
```
output
```
[3, 5, 7]
``` |
Python multiprocessing pool.map for multiple arguments | 5,442,910 | 134 | 2011-03-26T14:23:10Z | 21,292,849 | 15 | 2014-01-22T20:05:19Z | [
"python",
"multiprocessing"
] | In the Python multiprocessing library, is there a variant of pool.map which support multiple arguments?
```
text = "test"
def harvester(text, case):
X = case[0]
return text+ str(X)
if __name__ == '__main__':
pool = multiprocessing.Pool(processes=6)
case = RAW_DATASET
pool.map(harvester(text,case),... | Having learnt about itertools in [J.F. Sebastian](http://stackoverflow.com/a/5443941/446149) answer I decided to take it a step further and write a `parmap` package that takes care about parallelization, offering `map` and `starmap` functions on python-2.7 and python-3.2 (and later also) that can take *any number* of p... |
Python multiprocessing pool.map for multiple arguments | 5,442,910 | 134 | 2011-03-26T14:23:10Z | 28,975,239 | 12 | 2015-03-10T22:24:28Z | [
"python",
"multiprocessing"
] | In the Python multiprocessing library, is there a variant of pool.map which support multiple arguments?
```
text = "test"
def harvester(text, case):
X = case[0]
return text+ str(X)
if __name__ == '__main__':
pool = multiprocessing.Pool(processes=6)
case = RAW_DATASET
pool.map(harvester(text,case),... | Using **Python 3.3+** with `pool.starmap():`
```
from multiprocessing.dummy import Pool as ThreadPool
def write(i, x):
print(i, "---", x)
a = ["1","2","3"]
b = ["4","5","6"]
pool = ThreadPool(2)
pool.starmap(write, zip(a,b))
pool.close()
pool.join()
```
Result:
```
1 --- 4
2 --- 5
3 --- 6
```
You can als... |
Remove empty element but keep zeros as values | 5,442,921 | 2 | 2011-03-26T14:24:56Z | 5,442,945 | 9 | 2011-03-26T14:29:59Z | [
"python",
"list"
] | I have a list as follows:
```
lst = [-1.33, '', -1.33, -1.33 -2.62, 0, -2.66, 1.41, 0, 0, 1.40, '', 1.37, 0]
```
where there are two empty elements `''` in the list with several zeroes and float numbers.
How can I remove the empty elements but keep the zeroes? as follows...
```
lst2 = [-1.33, -1.33, -1.33 -2.62, 0... | Why not simply remove all `''` ?
```
>>> lst2 = [x for x in lst if x != '']
>>> lst2
[-1.33, -1.33, -3.95, 0, -2.66, 1.41, 0, 0, 1.4, 1.37, 0]
>>>
```
or you could keep only floats and ints:
```
>>> [x for x in lst if isinstance(x, (float, int))]
[-1.33, -1.33, -3.95, 0, -2.66, 1.41, 0, 0, 1.4, 1.37, 0]
# or a bit ... |
python pack output in string format | 5,442,984 | 2 | 2011-03-26T14:37:14Z | 5,443,023 | 7 | 2011-03-26T14:42:05Z | [
"python",
"struct",
"pack"
] | I have done the following.
```
from struct import pack, unpack
t = 1234
tt = str(pack("<I", t))
```
printing tt gives `\xf3\xe0\x01\x00`. How do I get original value of `t` back from tt?
I tried using unpacking the `repr(tt)` but that does not work out. How do I go about doing this? | ```
>>> t=1234
>>> tt=pack('<I', t)
>>> tt
'\xd2\x04\x00\x00'
>>> unpack('<I', tt)
(1234,)
>>> ttt, = unpack('<I', tt)
>>> ttt
1234
``` |
how to use forms in django-cms? | 5,443,147 | 13 | 2011-03-26T15:04:57Z | 5,444,105 | 14 | 2011-03-26T17:52:07Z | [
"python",
"django",
"forms",
"content-management-system",
"django-cms"
] | I am an absolute novice to django-cms. I have gone through the tutorial and configured it exactly the same as mentioned in the documentation. Now, I have to build an application which uses a form to upload products.
I dont have a clue as to how to move ahead with it. I want to start it with simple forms as if now, say... | Actually [the solution](http://stackoverflow.com/questions/5443147/how-to-use-forms-in-django-cms/5443598#5443598) proposed by bennylope is not the preferred way to do it, since using request.POST in a plugin can have very bad side effects (eg: what if the same plugin is twice on a page? Or what if there's multiple plu... |
Python - issues with numbers in pathnames | 5,443,200 | 3 | 2011-03-26T15:11:16Z | 5,443,216 | 13 | 2011-03-26T15:14:27Z | [
"python"
] | I need to open all PDFs in a certain directory, so I first generate a list of the file paths using os.path:
```
filenames = [
normpath(join(directoryname, filename))
for filename in listdir(directoryname)
if filename.lower().endswith('.'+extension)
]
```
So an item in that list looks like ... | The backslash is special in C-style strings like Python uses, just like in C++, C#, and Java. Either use a double-backslash to say âyes, I really mean a backslash,â not the character code `\201`, or use an `r''` string that does not interpret backslash sequences:
```
'D:\\Folder\\2010\\file.pdf'
r'D:\Folder\2010\f... |
Dynamic column_property with SQLAlchemy | 5,443,529 | 4 | 2011-03-26T16:10:30Z | 5,457,376 | 7 | 2011-03-28T10:01:22Z | [
"python",
"count",
"sqlalchemy"
] | I've got some SA models and need some trick :
```
class Entry(Base):
__tablename__ = 'entry'
id = Column(Integer, primary_key=True)
title = Column(Unicode(255))
author_id = Column(Integer, ForeignKey('user.id'))
date = Column(DateTime)
content = Column(Text)
author = relationship('User', ba... | Adding property is a good way to get some database state related to the object. But with external criterion parameter the count won't be just a state, but a function. Representing such data as object property won't be good. So query for additional data directly (counting antries newer than `start_date` in all examples ... |
Implementing binary search tree in python | 5,444,394 | 15 | 2011-03-26T18:37:01Z | 5,444,796 | 27 | 2011-03-26T19:35:35Z | [
"python",
"oop",
"class",
"data-structures",
"binary-search-tree"
] | I am extremely sorry for being so naive. I am trying to implement a binary search tree in python (part of learning python in a way). I tried to google it, but I am unable to point out where I have faltered. What I am interested in knowing is not an implementation, but why my code is not working. Any help is really appr... | Here is a quick example of a binary insert:
```
class Node:
def __init__(self, val):
self.l_child = None
self.r_child = None
self.data = val
def binary_insert(root, node):
if root is None:
root = node
else:
if root.data > node.data:
if root.l_child is No... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.