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 protect python class variables from an evil programmer? | 9,179,225 | 5 | 2012-02-07T15:44:20Z | 9,179,309 | 8 | 2012-02-07T15:48:58Z | [
"python",
"class",
"dictionary",
"private",
"protected"
] | How can I protect my variables from this kind of attack:
```
MyClass.__dict__ = {}
MyClass.__dict__.__setitem__('_MyClass__protectedVariable','...but it is not')
```
The above changes the variable dictionary and after that it is childs play to change all the variables. The upper line is crucial for this to work. The ... | In Python, you cannot "protect" attributes this way. Why are you in an antagonistic relationship with your caller? You and he need to agree on some things, this is one of them. Write better docs, become better friends with him. I don't know what your real problem is, but it cannot be solved with code.
Other languages ... |
How to protect python class variables from an evil programmer? | 9,179,225 | 5 | 2012-02-07T15:44:20Z | 9,179,699 | 18 | 2012-02-07T16:14:23Z | [
"python",
"class",
"dictionary",
"private",
"protected"
] | How can I protect my variables from this kind of attack:
```
MyClass.__dict__ = {}
MyClass.__dict__.__setitem__('_MyClass__protectedVariable','...but it is not')
```
The above changes the variable dictionary and after that it is childs play to change all the variables. The upper line is crucial for this to work. The ... | I feel that there is some deep confusion motivating this question. Private variables aren't there to keep the evil "hackers" away. They have nothing to do with security. They're there to promote good programming practices like [maintaining low coupling](http://en.wikipedia.org/wiki/Coupling_%28computer_programming%29).... |
Nested objects and setattr & getattr (yes, it's that time) | 9,180,516 | 6 | 2012-02-07T17:04:00Z | 9,180,838 | 7 | 2012-02-07T17:25:46Z | [
"python"
] | Overview:
```
class Inner(object):
def __init__(self, x):
self.x = x
class Outer(object):
def __init__(self, z):
self.inner = Inner(z)
o = Outer(10)
```
Now, I want the Outer object to behave transparently -- any attributes set on `o` should be set on `o.inner`, same for reading: `o.somethin... | The tricky part is setting the `inner` attribute of the `Outer` class correctly. What you can do is call the `__setattribute__` method of `object` (base class of `Outer`):
```
class Inner(object):
def __init__(self, x):
self.x = x
class Outer(object):
def __init__(self, z):
object.__setatt... |
Python GUI for cardgame | 9,180,803 | 2 | 2012-02-07T17:23:16Z | 9,181,276 | 7 | 2012-02-07T17:55:54Z | [
"python",
"user-interface",
"wxpython",
"tkinter"
] | I am planning to write a card game in python, and now looking for a GUI (I'm new to Python).
I have so far tried out two GUI's :***TK***(inter) and ***wxPython***.
Neither of them seem to be able , **and correct me if I'm wrong**, to do this :
> dragging a panel with an image of a Card in it
And it's not even about ... | As you want to write a game, I would recommend to *not* use a GUI library. Instead, you should look for *Game Libraries* like [PyGame](http://pygame.org/news.html), [PyOpenGl](http://pyopengl.sourceforge.net/) or [Kivy](http://kivy.org/) (aside others). They should all fit up your needs. |
Getting percentage complete of an md5 checksum | 9,181,859 | 2 | 2012-02-07T18:37:07Z | 9,181,881 | 8 | 2012-02-07T18:39:06Z | [
"python",
"cryptography",
"md5"
] | I am currently getting an md5 checksum as follows:
```
>>> import hashlib
>>> f = open(file)
>>> m = hashlib.md5()
>>> m.update(f.read())
>>> checksum = m.hedxigest()
```
I need to return the checksum of a large video file, that will take several minutes to generate. How would I implement a percentage counter, such t... | You can call the `update()` method repeatedly and feed the file in chunks to it. Thus, you can show the progress yourself.
```
import hashlib
import os
def digest_with_progress(filename, chunk_size):
read_size = 0
last_percent_done = 0
digest = hashlib.md5()
total_size = os.path.getsize(filename)
... |
AttributeError: 'module' object has no attribute 'strptime' -- Possible Bug? | 9,182,121 | 8 | 2012-02-07T18:56:13Z | 9,182,195 | 13 | 2012-02-07T19:01:20Z | [
"python",
"google-app-engine",
"import",
"importerror",
"bulkloader"
] | I am a little bit confused as to why I am receiving the error AttributeError: 'module' object has no attribute 'strptime'. When I import datetime in my Python script and call datetime.datetime.strptime(string, format) everything works fine but when I write from datetime import datetime and call datetime.strptime(string... | Perhaps
```
from shared.datastore import *
```
is redefining `datetime` to be the module.
You can check this guess by putting print statements in your code
```
from datetime import datetime
print(datetime)
from shared.datastore import *
print(datetime)
```
and seeing if the value of `datetime` has changed.
If my ... |
Quirk in calculating a percentage with a while loop | 9,182,485 | 2 | 2012-02-07T19:22:59Z | 9,182,517 | 7 | 2012-02-07T19:25:29Z | [
"python"
] | I am trying to do a quick percentage counter, as follow:
```
percentage = 1
while chunk:
chunk = f.read(size/100)
read += len(chunk)
m.update(chunk)
if size > 500000000:
print '%s done for %s.'%(percentage, name)
percentage += 1
```
This returns 102 print statements, [1,102], instead o... | No, it's not a simple off-by-one error.
Let's say the file is 199 bytes long. Each iteration will read `size/100` bytes, i.e. one byte. Consequently, the loop will execute 199 times, and "percentages" would range from 1 to 199.
Given that you only print out the percentages for large files, you won't actually see numb... |
How to get postgresSQL to work on a windows 7 computer with django? | 9,183,447 | 2 | 2012-02-07T20:34:23Z | 9,189,014 | 11 | 2012-02-08T06:58:28Z | [
"python",
"django",
"postgresql",
"install"
] | I'm currently reading the [django book](http://www.djangobook.com/en/2.0/chapter02/) and their instructions aren't working for me. People are talking about editing their paths and needing full paths in the comments and I really just have no idea what they are talking about to be honest. I got django to install correctl... | Before you do anything, make sure that you have `C:\Python27\Scripts` added to your `PATH`, this is where most packages install their scripts (such as django-admin.py).
*Replace `C:\Python27` with wherever Python is installed in your system*
Once you have done that, *open a new command prompt* so the system will read... |
In python, what's the method to ask for a user input based on previous user input? | 9,183,569 | 3 | 2012-02-07T20:42:14Z | 9,183,607 | 7 | 2012-02-07T20:45:15Z | [
"python",
"list",
"input"
] | I have an assignment where I need to ask the user to input the total number of integers that will be in the data set, ask for each of the integers, and then add them into a list, then summarize the list into a dictionary.
For now I'm only worried about the user input part.
Here's what I have so far:
```
data = []
su... | This is a loop whose body is executed total\_ints times:
```
for i in range(total_ints):
data.append(int(raw_input('Enter an integer: ')))
``` |
Boolean argument for script | 9,183,936 | 49 | 2012-02-07T21:08:19Z | 9,183,990 | 13 | 2012-02-07T21:11:14Z | [
"python"
] | In Python, I understand how int and str arguments can be added to scripts.
```
parser=argparse.ArgumentParser(description="""Mydescription""")
parser.add_argument('-l', type=str, default='info', help='String argument')
parser.add_argument('-dt', type=int, default ='', help='int argument')
```
What is it for booleans?... | ```
parser.add_argument('--foo', action='store_true')
``` |
Boolean argument for script | 9,183,936 | 49 | 2012-02-07T21:08:19Z | 9,183,998 | 93 | 2012-02-07T21:11:31Z | [
"python"
] | In Python, I understand how int and str arguments can be added to scripts.
```
parser=argparse.ArgumentParser(description="""Mydescription""")
parser.add_argument('-l', type=str, default='info', help='String argument')
parser.add_argument('-dt', type=int, default ='', help='int argument')
```
What is it for booleans?... | You can either use the `action` with `store_true`|`store_false`, or you can use an int and let implicit casting check a boolean value.
Using the `action`, you wouldn't pass a `--foo=true` and `--foo=false` argument, you would simply include it if it was to be set to true.
```
python myProgram.py --foo
```
In fact I ... |
How can I force Python's file.write() to use the same newline format in Windows as in Linux ("\r\n" vs. "\n")? | 9,184,107 | 48 | 2012-02-07T21:20:00Z | 9,184,137 | 79 | 2012-02-07T21:21:49Z | [
"python",
"newline"
] | I have the simple code:
```
f = open('out.txt','w')
f.write('line1\n')
f.write('line2')
f.close()
```
Code runs on windows and gives file size `12 bytes`, and linux gives `11 bytes`
The reason is new line
In linux it's `\n` and for win it is `\r\n`
But in my code I specify new line as `\n`. The question is how can ... | You need to open the file in *binary mode* i.e. `wb` instead of `w`. If you don't, the end of line characters are auto-converted to OS specific ones.
Here is an excerpt from Python reference about [`open()`](http://docs.python.org/library/functions.html#open).
> The default is to use text mode, which may convert '\n'... |
How to create a bytes or bytearray of given length filled with zeros in Python? | 9,184,489 | 11 | 2012-02-07T21:46:54Z | 9,184,505 | 20 | 2012-02-07T21:48:00Z | [
"python",
"bytearray"
] | All the solutions I found were for lists.
Thanks. | Simple:
```
bytearray(100)
```
will give you 100 zero bytes. |
Function with arguments in two lists | 9,184,497 | 25 | 2012-02-07T21:47:23Z | 9,184,514 | 37 | 2012-02-07T21:49:03Z | [
"python",
"dictionary",
"list-comprehension"
] | I have two lists xscat and yscat. I would like the list comprehension to pick up x and y in xscat and yscat respectively. Resulting list should contain `peaks([x[0], y[0]]), peaks([x[1], y[1]])` , etc
```
xscat=yscat=[-1, -1.5,5]
[peaks([x,y]) for x,y in xscat,yscat]
```
Can you find any solution using comprehensions... | `zip` is what you want:
```
[peaks([x,y]) for x,y in zip(xscat,yscat)]
``` |
Function with arguments in two lists | 9,184,497 | 25 | 2012-02-07T21:47:23Z | 9,184,518 | 10 | 2012-02-07T21:49:14Z | [
"python",
"dictionary",
"list-comprehension"
] | I have two lists xscat and yscat. I would like the list comprehension to pick up x and y in xscat and yscat respectively. Resulting list should contain `peaks([x[0], y[0]]), peaks([x[1], y[1]])` , etc
```
xscat=yscat=[-1, -1.5,5]
[peaks([x,y]) for x,y in xscat,yscat]
```
Can you find any solution using comprehensions... | You need to use `zip`:
```
[peaks([x,y]) for (x,y) in zip(xscat, yscat)]
``` |
Function with arguments in two lists | 9,184,497 | 25 | 2012-02-07T21:47:23Z | 9,185,220 | 7 | 2012-02-07T22:48:19Z | [
"python",
"dictionary",
"list-comprehension"
] | I have two lists xscat and yscat. I would like the list comprehension to pick up x and y in xscat and yscat respectively. Resulting list should contain `peaks([x[0], y[0]]), peaks([x[1], y[1]])` , etc
```
xscat=yscat=[-1, -1.5,5]
[peaks([x,y]) for x,y in xscat,yscat]
```
Can you find any solution using comprehensions... | I assume from your example that you want to use zip() but, just in case what you really want to do is iterate over ALL possible combinations of xscat and yscat then you have more work to do...
So, if you want (xscat[0],yscat[0]), (xscat[0], yscat[1]), (xscat[0], yscat[2]), etc... you can first do a nested comprehensio... |
Pointfree function combination in Python | 9,184,632 | 8 | 2012-02-07T21:58:46Z | 9,184,683 | 8 | 2012-02-07T22:03:25Z | [
"python",
"predicate",
"function-composition",
"pointfree"
] | I have some predicates, e.g.:
```
is_divisible_by_13 = lambda i: i % 13 == 0
is_palindrome = lambda x: str(x) == str(x)[::-1]
```
and want to logically combine them as in:
```
filter(lambda x: is_divisible_by_13(x) and is_palindrome(x), range(1000,10000))
```
The question is now: Can such combination be written in ... | You can override the `&` (bitwise AND) operator in Python by adding an `__and__` method to the `P` class. You could then write something like:
```
P(is_divisible_by_13) & P(is_palindrome)
```
or even
```
P(is_divisible_by_13) & is_palindrome
```
Similarly, you can override the `|` (bitwise OR) operator by adding an... |
pip uninstall broken w/ --environment flag? | 9,184,873 | 3 | 2012-02-07T22:19:33Z | 9,184,903 | 7 | 2012-02-07T22:22:36Z | [
"python",
"virtualenv",
"pip"
] | I can't seem to get pip to uninstall a package when using the environment flag.
I've created a virtual environment:
`virtualenv --no-site-packages /path/to/testenv`
While not in the virtual environment, I issue:
`pip install --environment /path/to/testenv django`
Django is downloaded and installed.
If I do the sa... | Appears to be a bug in pip 1.0. Seems to work if I `pip install --upgrade pip` and then try it. |
setup.py and installing a python project | 9,185,307 | 4 | 2012-02-07T22:56:03Z | 9,185,561 | 7 | 2012-02-07T23:17:34Z | [
"python"
] | I've looked through the setup.py documentation and am still having some difficulties with what I feel should be pretty basic.
I've broken this down to a simple example project that I'm trying to get running, my project's directory layout is as follows:
```
myproject
setup.py
src\
main.py
extern\
_... | The problem is that the module isn't under `sys.path` and that's way it cannot be found by the `import` statement.
In my case, the `extern` module was installed under `~/local/lib/python2.7/site-packages/extern`. However, note that the installation path was arbitrarily set to `~/local` during the installation.
To fix... |
Inverting permutations in Python | 9,185,768 | 3 | 2012-02-07T23:39:33Z | 9,185,908 | 7 | 2012-02-07T23:54:16Z | [
"python",
"permutation"
] | I'm new to programming, and I'm trying to write a Python function to find the inverse of a permutation on {1,2,3,...,n} using the following code:
```
def inv(str):
result = []
i = list(str).index(min(list(str)))
while min(list(str)) < len(list(str)) + 1:
list(str)[i : i + 1] = [len(list(str)) + 1]
... | If you only want the inverse permutation, you can use
```
def inv(perm):
inverse = [0] * len(perm)
for i, p in enumerate(perm):
inverse[p] = i
return inverse
perm = [3, 0, 2, 1]
print(inv(perm))
for i in perm:
print(inv(perm)[i])
[1, 3, 2, 0]
0
1
2
3
``` |
How to multiplex multiple blocking Python generators into one? | 9,186,740 | 7 | 2012-02-08T01:43:23Z | 9,186,832 | 8 | 2012-02-08T01:57:32Z | [
"python",
"generator",
"python-2.7"
] | Consider the following pseudo code:
```
def g_user():
while True:
yield read_user_input()
def g_socket():
while True:
yield read_socket_input()
def g_combined(gu, gs):
# should read user or socket input, whichever is available
while True:
sel = select(gu, gs)
if sel.c... | Look's like someone already implemented this: <http://www.dabeaz.com/generators/genmulti.py>
Mirrored here:
```
import Queue, threading
def gen_multiplex(genlist):
item_q = Queue.Queue()
def run_one(source):
for item in source: item_q.put(item)
def run_all():
thrlist = []
for sour... |
Datetime Python - Next Business Day | 9,187,215 | 7 | 2012-02-08T02:52:40Z | 9,187,358 | 13 | 2012-02-08T03:12:10Z | [
"python",
"datetime"
] | Two related issues: (1) All of the data I work with have weekday dates attached. At various points, I need to know what the next weekday is. I've written something like the code below to make this determination, but I'm sure there's a better way. Anyone? (2) Ideally, I need to know not just the next weekday, but the ne... | I would use [`dateutil.rrule`](http://labix.org/python-dateutil#head-470fa22b2db72000d7abe698a5783a46b0731b57):
```
import datetime
from dateutil import rrule
holidays = [
datetime.date(2012, 5, 1,),
datetime.date(2012, 6, 1,),
# ...
]
# Create a rule to recur every weekday starting today
r = rrule.rrul... |
3d rotation on image | 9,187,387 | 5 | 2012-02-08T03:15:08Z | 9,202,004 | 15 | 2012-02-08T21:47:03Z | [
"python",
"image-processing",
"opencv"
] | I'm trying to get some code that will perform a perspective transformation (in this case a 3d rotation) on an image.
```
import os.path
import numpy as np
import cv
def rotation(angle, axis):
return np.eye(3) + np.sin(angle) * skew(axis) \
+ (1 - np.cos(angle)) * skew(axis).dot(skew(axis))
def ske... | First, build the rotation matrix, of the form
```
[cos(theta) -sin(theta) 0]
R = [sin(theta) cos(theta) 0]
[0 0 1]
```
Applying this coordinate transform gives you a rotation around the origin.
If, instead, you want to rotate around the image center, you have to first shift the imag... |
Possible to prevent init from being called? | 9,187,388 | 3 | 2012-02-08T03:15:09Z | 9,187,568 | 8 | 2012-02-08T03:41:24Z | [
"python",
"initialization"
] | I'm editing the original question because we're all focusing on SHOULD you ever want to do this. My question is simply CAN I do this and HOW (understanding that there may be several solutions). So I'm just going to leave the actual question and cut out the background.
Suppose I have a base class and a child class. Is ... | That's quite doable, but I don't think you should.
Tell the users how to use your class and they should obey. Also, if someone is subclassing he should know how to call the parent's initialization method.
As a proof of concept, here's how it can be done with metaclasses (Python 2.x syntax):
```
>>> class WhoMovedMyIn... |
Using alias() for 'select as' in SQLAlchemy | 9,187,530 | 17 | 2012-02-08T03:35:11Z | 9,187,589 | 46 | 2012-02-08T03:44:38Z | [
"python",
"sqlalchemy",
"pyramid"
] | Let's say I have a table 'shares' with the following columns:
```
company price quantity
Microsoft 100 10
Google 99 5
Google 99 20
Google 101 15
```
I'd like to run the equivalent of a SQL statement like this:
```
select price, sum(quantity) as num from shares where company='... | You actually want the [`label`](http://docs.sqlalchemy.org/en/latest/core/expression_api.html?highlight=label#sqlalchemy.sql.expression.label) method.
```
result = dbsession.query(Shares.price, \
func.sum(Shares.quantity).label("Total sold")) \
.filter(Shares.com... |
Trying to parse json in python. ValueError: Expecting property name | 9,187,885 | 21 | 2012-02-08T04:34:44Z | 9,188,950 | 23 | 2012-02-08T06:52:27Z | [
"python",
"json",
"twitter"
] | I am trying to parse a json object into a python dict. I've never done this before. When I googled this particular error, (what is wrong with the first char?), other posts have said that the string being loaded is not actually a json string. I'm pretty sure this is, though... Thanks for the help. Here is my code.
In t... | That's definitely not JSON - not as printed above anyhow. It's already been parsed into a Python object - JSON would have `false`, not `False`, and wouldn't show strings as `u` for unicode (all JSON strings are unicode). Are you sure you're not getting your json string turned into a Python object for free somewhere in ... |
Trying to parse json in python. ValueError: Expecting property name | 9,187,885 | 21 | 2012-02-08T04:34:44Z | 20,473,835 | 22 | 2013-12-09T15:06:31Z | [
"python",
"json",
"twitter"
] | I am trying to parse a json object into a python dict. I've never done this before. When I googled this particular error, (what is wrong with the first char?), other posts have said that the string being loaded is not actually a json string. I'm pretty sure this is, though... Thanks for the help. Here is my code.
In t... | Sometimes you can have this error because your string values are not well recognized by python. As an example: I've spent quite a lot of time searching for the origin of this kind of error. Here is what I found.
Sometimes a language recognizes a kind of quotes and not another one:
btw, to parse a string in to json in ... |
Why doesn't calling a Python string method do anything unless you assign its output? | 9,189,172 | 101 | 2012-02-08T07:14:15Z | 9,189,193 | 191 | 2012-02-08T07:16:20Z | [
"python",
"string",
"replace"
] | I need help on a simple string replacement, but I don't know what I'm doing wrong.
I have this string:
```
hello world
```
I am looking to change `hello` to `goodbye`, giving me:
```
goodbye world
```
I'm using this code:
```
X = "hello world"
X.replace("hello", "goodbye")
```
Yet the outcome is still like this:... | This is because **strings are immutable in Python**.
Which means that `X.replace("hello","goodbye")` returns **a copy of `X` with replacements made**. Because of that you need replace this line:
```
X.replace("hello", "goodbye")
```
with this line:
```
X = X.replace("hello", "goodbye")
``` |
Using gevent monkey patching with threading makes thread work serially | 9,192,539 | 15 | 2012-02-08T11:36:17Z | 9,192,929 | 18 | 2012-02-08T12:02:48Z | [
"python",
"multithreading",
"gevent"
] | I am using [gevent](http://www.gevent.org/) and I am monkey patching everything.
It seems like the monkey patching causes the threading to work serially.
My code:
```
import threading
from gevent import monkey; monkey.patch_all()
class ExampleThread(threading.Thread):
def run(self):
do_stuff() # takes... | When threads are monkey patched in gevent, they behave as coroutines. This means that you have to explicitly yield control to make it possible for other coroutines to execute.
The way to do this is call a blocking operation that has been patched (this will yield automatically) or [`gevent.sleep`](http://www.gevent.org... |
PySide threading and http downloading | 9,193,323 | 4 | 2012-02-08T12:29:01Z | 9,195,947 | 8 | 2012-02-08T15:08:37Z | [
"python",
"qt",
"pyqt",
"pyside"
] | I've had soooo much trouble getting this code to work properly!!!! It runs fine when I debug it step by step, but when running normally it just crashes. Initially I was using a QThread to update the ImagePreview pixmap, but after a whole day of crashes and pain, I changed course. Now it works, in the above scenario whe... | I think the problem is that you are calling `self.startDownload()` from slot (signal handler). So you are not returning control to Qt main loop (or something like this). Proper way is to call it as deferred event, e.g. by calling it through [`QTimer.singleShot`](http://developer.qt.nokia.com/doc/qt-4.8/qtimer.html#sing... |
Applying a coloured overlay to an image in either PIL or Imagemagik | 9,193,603 | 8 | 2012-02-08T12:48:25Z | 9,204,506 | 12 | 2012-02-09T02:10:52Z | [
"python",
"image-processing",
"python-imaging-library"
] | I am a complete novice to image processing, and I am guessing this is quite easy to do, but I just don't know the terminology.
Basically I have a black and white image, I simply want to appy a coloured overlay to the image, so that I have got the image overlayed with blue green read and yellow like the images shown be... | Here's a code snippet that shows how to use [scikit-image](http://scikit-image.org) to overlay colors on a grey-level image. The idea is to convert both images to the HSV color space, and then to replace the hue and saturation values of the grey-level image with those of the color mask.
```
from skimage import data, c... |
Is there a way to tell if python was configured and compiled with "--with-threads --enable-shared"? | 9,193,773 | 4 | 2012-02-08T12:59:30Z | 9,193,864 | 9 | 2012-02-08T13:05:25Z | [
"python",
"debian"
] | This is for Python 2.6.6 on Debian Squeeez. I'm trying to find out if the binaries shipped with debian were configured with the flags of:
```
--with-threads --enable-shared
```
as if they were not I will need to compile and install from source myself. | `--with-threads` (which is the default) will mean Python supports threading, which will mean `import thread` will work. An easy way to test this is with `python$version -m threading`
`--enable-shared` will mean Python comes with a `libpython$version.so` file, installed in `$prefix/lib` (alongside the `python$version` ... |
Displaying 6.5235375356299998e-07 without exponential notation | 9,193,815 | 3 | 2012-02-08T13:02:04Z | 9,193,882 | 8 | 2012-02-08T13:06:20Z | [
"python",
"floating-point",
"exponential"
] | I have to convert exponential strings, like `6.5235375356299998e-07`,
to a float value, and display the result of my computation like 0.00000065235...
How can I do this in a Python program? | `6.5235375356299998e-07` is a perfectly legal float even if there is an `e` in it. You can do the whole calculation with it:
```
>>> 6.5235375356299998e-07 * 10000000
6.5235375356300001
>>> 6.5235375356299998e-07 + 10000000
10000000.000000652
```
In the second case, many digits will disappear because of the precisio... |
How to document a method with parameter(s)? | 9,195,455 | 43 | 2012-02-08T14:41:52Z | 9,195,565 | 16 | 2012-02-08T14:47:46Z | [
"python",
"documentation",
"documentation-generation"
] | **How to document methods with parameters using Python's documentation strings?**
**EDIT:**
[PEP 257](http://www.python.org/dev/peps/pep-0257/) gives this example:
```
def complex(real=0.0, imag=0.0):
"""Form a complex number.
Keyword arguments:
real -- the real part (default 0.0)
imag -- the imagina... | Conventions:
* [PEP 257 Docstring Conventions](http://www.python.org/dev/peps/pep-0257/)
* [PEP 287 reStructuredText Docstring Format](http://www.python.org/dev/peps/pep-0287/)
Tools:
* [Epydoc: Automatic API Documentation Generation for Python](http://epydoc.sourceforge.net/)
* [sphinx.ext.autodoc â Include docum... |
How to document a method with parameter(s)? | 9,195,455 | 43 | 2012-02-08T14:41:52Z | 10,065,932 | 32 | 2012-04-08T19:49:19Z | [
"python",
"documentation",
"documentation-generation"
] | **How to document methods with parameters using Python's documentation strings?**
**EDIT:**
[PEP 257](http://www.python.org/dev/peps/pep-0257/) gives this example:
```
def complex(real=0.0, imag=0.0):
"""Form a complex number.
Keyword arguments:
real -- the real part (default 0.0)
imag -- the imagina... | Based on my experience, the [numpy docstring conventions](https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt) (PEP257 superset) are the most widely-spread *followed* conventions that are also supported by tools, such as [Sphinx](http://sphinx.pocoo.org/).
One example:
```
Parameters
----------
x : ... |
Saving RSAÂ keys to a file, using pycrypto | 9,197,507 | 8 | 2012-02-08T16:33:45Z | 9,197,929 | 14 | 2012-02-08T16:59:09Z | [
"python",
"pycrypto"
] | Iâm using PyCrypto 2.3 and I would like to save the keys I have generated into a file, so as to distribute them to the client and server. I canât seem to find a way to print the keys correctly, neither can I find examples on the internet.
```
def resetKeys(self):
keys = RSA.generate(1024)
priv... | `keys.exportKey()` for the private key, `keys.publickey().exportKey()` for the public key. You can change the output format with `format` argument, see the [docs at this site](https://www.dlitz.net/software/pycrypto/api/current/Crypto.PublicKey.RSA._RSAobj-class.html#exportKey). |
Problems with Celery & Redis Backend | 9,197,582 | 2 | 2012-02-08T16:38:22Z | 9,204,631 | 7 | 2012-02-09T02:31:50Z | [
"python",
"django",
"redis",
"celery",
"django-celery"
] | I have a system set up currently that is using celery with a redis
backend to do a bunch of asynchronous tasks such as sending emails,
pulling social data, crawling,etc. Everything is working great, but I
am having group figuring out how to monitor the system (aka the number
of queue up messages). I started looking thr... | Your configuration has `CELERY_ALWAYS_EAGER = True`. This means that the tasks run locally and hence you won't see them in Redis. From the docs: <http://celery.readthedocs.org/en/latest/configuration.html#celery-always-eager>
> CELERY\_ALWAYS\_EAGER
>
> If this is True, all tasks will be executed
> locally by blocking... |
Maintain count in python list comprehension | 9,197,844 | 5 | 2012-02-08T16:54:18Z | 9,197,880 | 29 | 2012-02-08T16:56:38Z | [
"python"
] | In Python, is there any `counter` available during the list comprehension as it would be in case of a `for` loop?
It would be more clear why I need a counter, with this example:
I wish to achieve the following:
Initial List: `['p', 'q', 'r', 's']`
Desired List: `[(1, 'P'), (2, 'Q'), (3, 'R'), (4, 'S')]`
In the des... | ### The most basic case
```
[(i, x) for i, x in enumerate(some_list, 1)]
```
### Apply a filter with an if-statements
```
[(i, x) for i, x in enumerate(some_list, 1) if i > 2]
```
or like this
```
[(i, x) for i, x in enumerate(some_list, 1) if x != 'p']
```
### A word of advice
Most often you don't need to do th... |
Pythonic way to check that the lengths of lots of lists are the same | 9,200,576 | 9 | 2012-02-08T20:05:10Z | 9,200,610 | 7 | 2012-02-08T20:07:21Z | [
"python",
"list",
"if-statement"
] | I have a number of lists that I'm going to use in my program, but I need to be sure that they are all the same length, or I'm going to get problems later on in my code.
What's the best way to do this in Python?
For example, if I have three lists:
```
a = [1, 2, 3]
b = ['a', 'b']
c = [5, 6, 7]
```
I could do somethi... | ```
len(set(len(x) for x in l)) <= 1
``` |
Pythonic way to check that the lengths of lots of lists are the same | 9,200,576 | 9 | 2012-02-08T20:05:10Z | 9,200,621 | 20 | 2012-02-08T20:08:00Z | [
"python",
"list",
"if-statement"
] | I have a number of lists that I'm going to use in my program, but I need to be sure that they are all the same length, or I'm going to get problems later on in my code.
What's the best way to do this in Python?
For example, if I have three lists:
```
a = [1, 2, 3]
b = ['a', 'b']
c = [5, 6, 7]
```
I could do somethi... | Assuming you have a non-empty list of lists, e.g.
```
my_list = [[1, 2, 3], ['a', 'b'], [5, 6, 7]]
```
you could use
```
n = len(my_list[0])
if all(len(x) == n for x in my_list):
# whatever
```
This will short-circuit, so it will stop checking when the first list with a wrong length is encountered. |
singular or plural identifier for a dictionary? | 9,200,605 | 12 | 2012-02-08T20:07:09Z | 9,201,009 | 9 | 2012-02-08T20:37:34Z | [
"python",
"coding-style",
"containers",
"identifier"
] | When naming a container , what's a better coding style:
```
source = {}
#...
source[record] = some_file
```
or
```
sources = {}
#...
sources[record] = some_file
```
The plural reads more natural at creation; the singular at assignment.
And it is not an idle question; I did catch myself getting confused in an old c... | I think that there are two very specific use cases with dictionaries that should be identified separately. However, before addressing them, it should be noted that the variable names for dictionaries should almost always be singular, while lists should almost always be plural.
1. **Dictionaries as object-like entities... |
Is there a test suite for numpy / scipy? | 9,200,727 | 27 | 2012-02-08T20:16:57Z | 9,200,923 | 38 | 2012-02-08T20:31:08Z | [
"python",
"numpy",
"scipy"
] | I'm about to reinstall `numpy` and `scipy` on my Ubuntu Lucid. As these things carry quite a few dependencies, I'm wondering if there is a comprehensive test suite to check if the new install really works.
Of course, I can just take a bunch of my scripts and run them one by one to see if they keep working, but that wo... | Yes. Both packages have a `test` method for this.
```
import numpy
numpy.test('full')
import scipy
scipy.test('full')
```
Note that if you do not have [nose](http://readthedocs.org/docs/nose/en/latest/) installed, it will tell you that you need it. |
Getting command-line password input in Python | 9,202,224 | 70 | 2012-02-08T22:03:37Z | 9,202,236 | 117 | 2012-02-08T22:04:59Z | [
"python",
"command-line",
"passwords",
"hidden"
] | You know how in Linux when you try some Sudo stuff it tells you to enter the password and, as you type, nothing is shown in the terminal window (the password is not shown)?
Is there a way to do that in Python? I'm working on a script that requires so sensitive info and would like for it to be hidden when I'm typing it... | Use [`getpass.getpass()`](http://docs.python.org/library/getpass.html#getpass.getpass). |
Getting command-line password input in Python | 9,202,224 | 70 | 2012-02-08T22:03:37Z | 9,202,246 | 11 | 2012-02-08T22:06:06Z | [
"python",
"command-line",
"passwords",
"hidden"
] | You know how in Linux when you try some Sudo stuff it tells you to enter the password and, as you type, nothing is shown in the terminal window (the password is not shown)?
Is there a way to do that in Python? I'm working on a script that requires so sensitive info and would like for it to be hidden when I'm typing it... | Use [getpass](http://docs.python.org/library/getpass.html#getpass.getpass) for this purpose.
> getpass.getpass - Prompt the user for a password without echoing |
Getting command-line password input in Python | 9,202,224 | 70 | 2012-02-08T22:03:37Z | 19,853,787 | 41 | 2013-11-08T07:34:31Z | [
"python",
"command-line",
"passwords",
"hidden"
] | You know how in Linux when you try some Sudo stuff it tells you to enter the password and, as you type, nothing is shown in the terminal window (the password is not shown)?
Is there a way to do that in Python? I'm working on a script that requires so sensitive info and would like for it to be hidden when I'm typing it... | ```
import getpass
pswd = getpass.getpass('Password:')
```
Works on Linux and Windows |
Excluding abstractproperties from coverage reports | 9,202,723 | 11 | 2012-02-08T22:48:07Z | 9,212,387 | 13 | 2012-02-09T14:12:00Z | [
"python",
"code-coverage",
"nosetests",
"abc",
"coverage.py"
] | I have an abstract base class along the lines of:
```
class MyAbstractClass(object):
__metaclass__ = ABCMeta
@abstractproperty
def myproperty(self): pass
```
But when I run nosetests (which coverage) on my project, it complains that the property def line is untested. It can't *actually* be tested (AFAIK)... | There's no way to exclude the abstract properties precisely as you have it, but if you make a slight change, you can. Have your abstract property raise an error:
```
@abstractproperty
def myproperty(self):
raise NotImplementedError
```
Then you can instruct coverage.py to ignore lines that raise NotImplementedEr... |
Excluding abstractproperties from coverage reports | 9,202,723 | 11 | 2012-02-08T22:48:07Z | 19,275,908 | 14 | 2013-10-09T15:11:33Z | [
"python",
"code-coverage",
"nosetests",
"abc",
"coverage.py"
] | I have an abstract base class along the lines of:
```
class MyAbstractClass(object):
__metaclass__ = ABCMeta
@abstractproperty
def myproperty(self): pass
```
But when I run nosetests (which coverage) on my project, it complains that the property def line is untested. It can't *actually* be tested (AFAIK)... | For me the best solution was what @Wesley mentioned in his comment to the accepted answer, specifically replacing 'pass' with a docstring for the abstract property, e.g.:
```
class MyAbstractClass(object):
__metaclass__ = ABCMeta
@abstractproperty
def myproperty(self):
""" this property is too abst... |
Tests succeed, still get traceback | 9,202,772 | 11 | 2012-02-08T22:51:01Z | 9,202,861 | 13 | 2012-02-08T22:58:29Z | [
"python",
"unit-testing"
] | I'm using Python's `unittest` library and all the tests succeed, but I still get a traceback and I can't understand how I can fix the problem.
```
........
----------------------------------------------------------------------
Ran 8 tests in 0.020s
OK
Traceback (most recent call last):
File "C:\Users\Paul\Desktop\... | It appears that you are running in the Python shell, which catches exceptions for you so you can continue debugging. If you had been running from the command line, the line
```
sys.exit(not self.result.wasSuccessful())
```
would have exited your program with an exit code of 0, which indicates success (this might be c... |
Tests succeed, still get traceback | 9,202,772 | 11 | 2012-02-08T22:51:01Z | 11,146,088 | 7 | 2012-06-21T20:19:18Z | [
"python",
"unit-testing"
] | I'm using Python's `unittest` library and all the tests succeed, but I still get a traceback and I can't understand how I can fix the problem.
```
........
----------------------------------------------------------------------
Ran 8 tests in 0.020s
OK
Traceback (most recent call last):
File "C:\Users\Paul\Desktop\... | end your unittest file with:
```
if __name__=='__main__':
try:
unittest.main()
except SystemExit as inst:
if inst.args[0] is True: # raised by sys.exit(True) when tests failed
raise
``` |
Listening to keyboard events without trapping them? | 9,203,067 | 12 | 2012-02-08T23:16:40Z | 9,218,997 | 11 | 2012-02-09T21:22:20Z | [
"python",
"perl",
"keyboard-events",
"xlib",
"keyrelease"
] | I'm writing an command-line application which listens for Control key release events in X Windows and alerts another process when it detects them.
Being new to GNU/Linux, I'd prefer avoiding to fumble with GCC and therefore I'm looking for a scripting-based solution. Since I know a bit of Python, it seemed natural to ... | Thanks to the pykeylogger library mentioned by Croad Langshan, and to the helpful example code provided by Tim Alexander, the author of such library, I've been able to change my program to:
```
#!/usr/bin/env python
from pyxhook import HookManager
watched_keys = ["Control_R", "Control_L"]
def handle... |
Python treat files with uppercase and lowercase names the same | 9,203,879 | 4 | 2012-02-09T00:40:26Z | 9,203,909 | 8 | 2012-02-09T00:43:35Z | [
"python",
"file",
"uppercase",
"lowercase"
] | I just found out this today:
If I have an existing file named a111, and I want to create a new file named A111 in the same directory with Python:
```
f = file('A111', 'w')
f.write('test')
f.close()
```
It will overwrite my file a111 and there's no A111!!
How do I prevent this from happening? | It is not due to python. It is due to the case-insensitivity of your underlying file system (I'm guessing HFS+ in your case?). From [wikipedia](http://en.wikipedia.org/wiki/Filename):
> Not all file systems in Unix-like systems are case-sensitive; by default, HFS+ in Mac OS X is case-insensitive
The solution is to us... |
Pythonic: use of __dict__ in the function self.__init__ of a class | 9,204,671 | 11 | 2012-02-09T02:38:06Z | 9,205,029 | 12 | 2012-02-09T03:31:53Z | [
"class",
"python"
] | While coding a new class with the *spyder* IDE, and using *pylint* to check the final result, I've ran into error messages (but the code work as expected without error).
**Context:** in the constructor function, I want to create new members (quite a lot). Usually, these are few enough so I use this coding:
```
class ... | Yes, it is reasonable to update the instance dictionary directly. Alternatively, you can use *setattr* to update the variables. I've seen both approaches used in production code.
With [*setattr*](http://docs.python.org/library/functions.html#setattr) there is no need to touch the instance dictionary directly:
```
cla... |
python - Is there a way to store a function in a list or dictionary so that when the index (or key) is called it fires off the stored function? | 9,205,081 | 20 | 2012-02-09T03:40:04Z | 9,205,091 | 53 | 2012-02-09T03:41:58Z | [
"python",
"dictionary"
] | For instance, I've tried things like `mydict = {'funcList1': [foo(),bar(),goo()], 'funcList2': [foo(),goo(),bar()]`, which, doesn't work..
Is there some kind of structure with this kind of functionality?
I realize that I could obviously do this just as easily with a bunch of def statements:
```
def func1():
foo(... | Functions are first class objects in Python and so you can dispatch using a dictionary. For example, if `foo` and `bar` are functions, and `dispatcher` is a dictionary like so.
```
dispatcher = {'foo': foo, 'bar': bar}
```
Note that the values are `foo` and `bar` which are the function objects, and NOT `foo()` and `b... |
How do I install wxPython on Mac OS X? | 9,205,317 | 16 | 2012-02-09T04:10:53Z | 12,514,960 | 36 | 2012-09-20T14:35:03Z | [
"python",
"wxpython"
] | I'd like to use wxPython on my Mac OS 10.7 (Lion) computer. (I'm a Tkinter refugee.) I upgraded from Python 2.7.1, then downloaded and installed wxPython2.8-osx-unicode-2.8.12.1-universal-py2.7.dmg. Here's what I get:
```
Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34)
[GCC 4.2.1 (Apple Inc. build 5666) (... | [Homebrew](https://github.com/mxcl/homebrew) provides wxWidgets 2.9 in full 64bit glory including wxWidgets.
`brew install wxmac` |
Getting confused with lambda and list comprehension | 9,205,805 | 14 | 2012-02-09T05:21:12Z | 9,206,062 | 15 | 2012-02-09T05:54:43Z | [
"python",
"lambda",
"closures",
"list-comprehension"
] | Read a question on stack overflow sometime back with the following syntax
```
In [1]: [lambda: x for x in range(5)][0]()
Out[1]: 4
In [2]: [lambda: x for x in range(5)][2]()
Out[2]: 4
```
But i am having a hard time to understand why exactly the output of this comes as 4,
my understanding is it always gives the last ... | This isn't really about either list comprehensions or lambdas. It's about the scoping rules in Python. Let's rewrite the list comprehension into an equivalent loop:
```
funcs = []
for x in range(5):
def f(): return x
funcs.append(f)
funcs[0]() # returns 4
```
Here, we can see that we successively construct fu... |
how to render a Queryset into a table template-django | 9,206,373 | 3 | 2012-02-09T06:27:44Z | 9,247,273 | 12 | 2012-02-12T07:49:41Z | [
"python",
"django",
"templates",
"django-queryset"
] | I have a model which is defined as shown which is acted upon a query and gets a list of objects that have to placed in appropriate cells of a table. Here is the relevant part of the code.
```
class Location(models.Model):
x=models.IntegerField(null=True)
y=models.IntegerField(null=True)
z=models.CharField(... | If you want to make your code simpler, I would like to recommend to use application [django-tables2](https://github.com/bradleyayers/django-tables2). This approach can solve all your issues about generating tables.
As documentation sais:
> django-tables2 simplifies the task of turning sets of data into HTML
> tables.... |
How to split string into words that do not contain whitespaces in python? | 9,206,964 | 4 | 2012-02-09T07:28:02Z | 9,207,026 | 10 | 2012-02-09T07:35:22Z | [
"python",
"string",
"list",
"whitespace"
] | My string is:
```
"This is a string"
```
I want to turn it into a list:
```
["This", "is", "a", "string"]
```
I use the `split(" ")` method, but it adds whitespaces as list elements. Please help,
Best Regards | ```
>>> v="This is a string"
>>> v.split()
['This', 'is', 'a', 'string']
```
just use [`split()`](http://docs.python.org/library/stdtypes.html#str.split). |
Is it possible to run Selenium scripts without having an X server running, too? | 9,207,320 | 6 | 2012-02-09T08:08:32Z | 9,207,749 | 10 | 2012-02-09T08:51:18Z | [
"python",
"selenium",
"selenium-rc",
"selenium-webdriver",
"headless"
] | I have a python script that uses selenium RC; specifically webdriver.
I would love to have the script run as a post-commit hook, ideally through IE, Safari (if possible), Chrome & Firefox.
But I'm not sure what I'd need to do, since every time I run it on my local machine, a browser pops up.
I've heard of "saucelabs... | Yes, you need to have X server running because Selenium requires a running browser and browsers need some kind of X server in order to run.
Fortunately there are many types of X servers and one of them is [Xvfb](http://www.x.org/releases/X11R7.6/doc/man/man1/Xvfb.1.xhtml) aka X virtual framebuffer that does all the op... |
How to Copy/Clone a Virtual Environment from Server to Local Machine | 9,207,430 | 24 | 2012-02-09T08:21:57Z | 9,207,511 | 37 | 2012-02-09T08:28:39Z | [
"python",
"django",
"ubuntu",
"webserver",
"virtualenv"
] | I have an existing Python django Project running in Web Server. Now the client needs to make some changes in the existing code. So I need to set it up in my Local Machine. All the packages needed for this project is installed in a Virtual environment. How can I copy or clone this virtual environment to my Local machine... | 1. Run `pip freeze > requirements.txt` on the remote machine
2. Copy that `requirements.txt` file to your local machine
3. In your local virtual environment, run `pip install -r requirements.txt`
And, so long as all of the requirements are well behaved Python packages, you should be good to go. |
CherryPy with additional threads for custom jobs | 9,207,591 | 12 | 2012-02-09T08:37:46Z | 9,213,886 | 13 | 2012-02-09T15:39:27Z | [
"python",
"multithreading",
"daemon",
"cherrypy"
] | We're designing a system based on CherryPy that in addition to serving web requests needs to do tasks/jobs in parallel. We want it to be a single process running as a daemon and create threads for all the parallel jobs like scheduled tasks or collecting data online.
I've been browsing through the CherryPy documentatio... | Subscribe a [Monitor](https://cherrypy.readthedocs.org/en/3.3.0/refman/process/plugins/index.html#cherrypy.process.plugins.Monitor) instance:
```
from cherrypy.process.plugins import Monitor
def foo():
my.store.collect_data('things', 'stuff')
Monitor(cherrypy.engine, foo, frequency=300).subscribe()
```
This wil... |
monitoring gevent exceptions in jobs | 9,207,802 | 10 | 2012-02-09T08:55:41Z | 9,208,286 | 10 | 2012-02-09T09:32:04Z | [
"python",
"exception-handling",
"gevent"
] | I'm building an application using gevent. My app is getting rather big now,there are a lot of jobs being spawned and destroyed. Many different kind of jobs. Now I've noticed that when one of these jobs crashes my entire application just keeps running (if the exception came from a non main greenlet) which is fine. BUT T... | I think the cleanest way would be to catch the exception you consider fatal and do `sys.exit()` (you'll need gevent [1.0](http://code.google.com/p/gevent/downloads/list) since before that `SystemExit` did not exit the process).
Another way is to use link\_exception, which would be called if the greenlet died with an e... |
Using python multiprocessing with different random seed for each process | 9,209,078 | 7 | 2012-02-09T10:24:12Z | 9,433,953 | 10 | 2012-02-24T16:03:40Z | [
"python",
"multiprocessing"
] | I wish to run several instances of a simulation in parallel, but with each simulation having its own independent data set.
Currently I implement this as follows:
```
P = mp.Pool(ncpus) # Generate pool of workers
for j in range(nrun): # Generate processes
sim = MDF.Simulation(tstep, temp, time, writeout, boundaryx... | Just thought I would add an actual answer to make it clear for others.
Quoting the answer from aix [in this question](http://stackoverflow.com/questions/6914240/multiprocessing-pool-seems-to-work-in-windows-but-not-in-ubuntu):
> What happens is that on Unix every worker process inherits the same
> state of the random... |
how to parse user agent string? python | 9,209,377 | 4 | 2012-02-09T10:44:14Z | 9,209,931 | 9 | 2012-02-09T11:19:35Z | [
"python",
"user-agent"
] | ```
<field name="http.user_agent" showname="User-Agent: CORE/6.506.4.1 OpenCORE/2.02 (Linux;Android 2.2)\r\n" size="62" pos="542" show="CORE/6.506.4.1 OpenCORE/2.02 (Linux;Android 2.2)" value="557365722d4167656e743a20434f52452f362e3530362e342e31204f70656e434f52452f322e303220284c696e75783b416e64726f696420322e32290d0a"/>... | There is a library called [httpagentparser](http://pypi.python.org/pypi/httpagentparser) for that:
```
import httpagentparser
>>> s = "Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/532.9 (KHTML, like Gecko) Chrome/5.0.307.11 Safari/532.9"
>>> print httpagentparser.simple_detect(s)
('Linux', 'Chrome 5.0.307.11')
... |
substring variable name python | 9,209,675 | 3 | 2012-02-09T11:02:40Z | 9,209,703 | 8 | 2012-02-09T11:04:04Z | [
"python",
"variables",
"eval"
] | i have few variables like this:
```
self.lamp_1
self.lamp_2
self.lamp_3
self.lamp_4
```
and now i want to use each of this names is loop to call them automaticly, like this:
```
for i in range(1,5):
self.canvas.itemconfig(self.lamp_/number_i_automaticly/, fill=self.color_blink)
```
I tried using function eval()... | Use a list instead of indexed variable names:
```
self.lamps = [lamp_1, lamp_2, lamp_3, lamp_4]
```
If you insist on using indexed variable names (you shouldn't), you can use `getattr()`:
```
for i in range(1, 5):
self.canvas.itemconfig(getattr(self, "lamp_%i" % i),
fill=self.color_bl... |
Setting up advanced Python logging | 9,210,976 | 4 | 2012-02-09T12:38:39Z | 9,212,488 | 9 | 2012-02-09T14:18:29Z | [
"python",
"logging"
] | I'd like to use logging for my modules, but I'm not sure how to design the following requirements:
* normal logging levels (info, error, warning, debug) but also some additional more verbose debug levels
* logging messages can have different types; some are meant for the developer, some are meant for the user; those t... | ### 1) Adding more verbose debug levels.
Have you thought this through?
Take a look about what the [doc](http://docs.python.org/py3k/howto/logging.html#custom-levels) says:
> Defining your own levels is possible, but **should not be necessary**, as the existing levels have been chosen on the basis of practical exper... |
Overloading standard parantheses ("()") in Python | 9,210,983 | 2 | 2012-02-09T12:39:14Z | 9,210,997 | 12 | 2012-02-09T12:40:17Z | [
"python",
"operator-overloading"
] | This should be very simple but I failed to google it: How (if at all) can I overload the parantheses operator in Python? So that this code will make sense:
```
my_new_object = my_new_class()
x = my_new_object(5)
``` | You need to define [`__call__`](http://docs.python.org/reference/datamodel.html#object.__call__) on your class.
For example
```
>>> class Multiplier(object):
... def __init__(self, num):
... self.num = num
... def __call__(self, other):
... return self.num*other
...
>>> mul5 = Multiplier(5)
>>> mu... |
Overloading standard parantheses ("()") in Python | 9,210,983 | 2 | 2012-02-09T12:39:14Z | 9,211,006 | 8 | 2012-02-09T12:40:50Z | [
"python",
"operator-overloading"
] | This should be very simple but I failed to google it: How (if at all) can I overload the parantheses operator in Python? So that this code will make sense:
```
my_new_object = my_new_class()
x = my_new_object(5)
``` | Define [`__call__()`](http://docs.python.org/reference/datamodel.html#object.__call__) on your class:
```
class MyNewClass(object):
def __call__(self, x):
return x
``` |
Both using cookies and a proxy in Python with urllib2 | 9,211,564 | 6 | 2012-02-09T13:17:19Z | 9,211,752 | 10 | 2012-02-09T13:29:07Z | [
"python",
"cookies",
"proxy",
"urllib2"
] | I'm using urllib2 to interact with a webserver. For the specific problem I need to solve, I need to tunnel the traffic through a proxy. I managed to do that with a urllib2 'ProxyHandler'.
I also need to accept and send cookies. I managed to do that with a urllib2 'cookielib.LWPCookieJar()'.
The problem is that while ... | Combine proxy handler and cookie processor in a single opener:
```
cj = cookielib.CookieJar()
opener = build_opener(ProxyHandler({'http': 'ip:port'}), HTTPCookieProcessor(cj))
``` |
Python PIL, Image. Error after image.load() | 9,211,719 | 2 | 2012-02-09T13:27:52Z | 9,214,768 | 7 | 2012-02-09T16:29:21Z | [
"python",
"python-imaging-library"
] | I'm trying to load my .jpg file and it raises error, but if I try it again, it's ok! Why??
My code and error:
```
>>> import Image
>>> im1 = Image.open('/tmp/test.jpg')
>>> im1.load()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.7/site-packages/PIL/ImageFile.py", lin... | PIL uses lazy loading, which means the image isn't actually read from the file until you try to perform an action on it. The first call to `load` is that first action, so that's when the problem with the file format is detected. The second call to `load` doesn't read the file again, it just returns information that was... |
Python PIL, Image. Error after image.load() | 9,211,719 | 2 | 2012-02-09T13:27:52Z | 23,575,498 | 8 | 2014-05-09T23:33:09Z | [
"python",
"python-imaging-library"
] | I'm trying to load my .jpg file and it raises error, but if I try it again, it's ok! Why??
My code and error:
```
>>> import Image
>>> im1 = Image.open('/tmp/test.jpg')
>>> im1.load()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.7/site-packages/PIL/ImageFile.py", lin... | I had this same issue and came up with a solution which I discuss here: <http://stackoverflow.com/a/23575424/3622198>.
Somewhere before your code block, simply add the following:
```
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
```
... and you should be good to go!
EDIT: It looks like this helps... |
Python hash table design | 9,212,548 | 5 | 2012-02-09T14:22:26Z | 9,212,609 | 21 | 2012-02-09T14:26:36Z | [
"python",
"hash"
] | I want to implement a hash table in python. On the table a class object will be associated with the key value. The problem is I want to use the key value to find the index of the class and update it (which of course is not a problem). But what can I do if I want to sort the table using a particular value of the class.
... | Python's dict is already a hash table.
```
doc_hash = {}
doc_hash[doc.id] = doc
```
To assign rank:
```
docs = sorted(doc_hash.itervalues(), key=operator.attrgetter('score'), reverse=True)
for i, doc in enumerate(docs):
doc.rank = i
``` |
Am I not setting up my Flask 404 handler correctly? | 9,212,824 | 4 | 2012-02-09T14:38:38Z | 9,213,325 | 7 | 2012-02-09T15:07:22Z | [
"python",
"http-status-code-404",
"flask"
] | In my Flask app, I set up a 404 handler like this:
```
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
```
However, when a user goes to an unrecognized url, the system gives an internal server error instead of rendering my 404 template. Am I missing something? | **Internal Server Error** is HTTP error 500 rather than 404 and you haven't added error handler for it. This occurs when the server is unable to fulfill the client request properly. To add a gracious message when such error occurred, you can add a *errorhandler* like 404.
```
@app.errorhandler(500)
def exception_handl... |
Python: __str__, but for a class, not an instance? | 9,213,286 | 7 | 2012-02-09T15:05:05Z | 9,213,324 | 10 | 2012-02-09T15:07:21Z | [
"python",
"string",
"class"
] | I understand the following Python code:
```
>>> class A(object):
... def __str__(self):
... return "An instance of the class A"
...
>>>
>>> a = A()
>>> print a
An instance of the class A
```
Now, I would like to change the output of
```
>>> print A
<class '__main__.A'>
```
Which function do I need to ... | Define `__str__()` on the metaclass:
```
class A(object):
class __metaclass__(type):
def __str__(self):
return "plonk"
```
Now, `print A` will print `plonk`.
**Edit**: As noted by jsbueno in the comments, in Python 3.x you would need to do the following:
```
class Meta(type):
def __str__... |
Function acting as both decorator and context manager in Python? | 9,213,600 | 24 | 2012-02-09T15:22:20Z | 9,213,668 | 26 | 2012-02-09T15:26:51Z | [
"python",
"decorator",
"contextmanager"
] | This might be pushing things a little too far, but mostly out of curiosity..
Would it be possible to have a callable object (function/class) that acts as *both* a Context Manager and a decorator at the same time:
```
def xxx(*args, **kw):
# or as a class
@xxx(foo, bar)
def im_decorated(a, b):
print('do the s... | Starting in Python 3.2, support for this is even included in the standard library. Deriving from the class [`contextlib.ContextDecorator`](http://docs.python.org/py3k/library/contextlib.html#contextlib.ContextDecorator) makes it easy to write classes that can be used as both, a decorator or a context manager. This func... |
Function acting as both decorator and context manager in Python? | 9,213,600 | 24 | 2012-02-09T15:22:20Z | 9,213,866 | 10 | 2012-02-09T15:38:10Z | [
"python",
"decorator",
"contextmanager"
] | This might be pushing things a little too far, but mostly out of curiosity..
Would it be possible to have a callable object (function/class) that acts as *both* a Context Manager and a decorator at the same time:
```
def xxx(*args, **kw):
# or as a class
@xxx(foo, bar)
def im_decorated(a, b):
print('do the s... | ```
class Decontext(object):
"""
makes a context manager also act as decorator
"""
def __init__(self, context_manager):
self._cm = context_manager
def __enter__(self):
return self._cm.__enter__()
def __exit__(self, *args, **kwds):
return self._cm.__exit__(*args, **kwds)
... |
Graphviz - Drawing maximal cliques | 9,213,797 | 7 | 2012-02-09T15:33:24Z | 9,217,887 | 11 | 2012-02-09T20:03:46Z | [
"python",
"graphviz"
] | I want to use graphviz in order to draw for a given graph all the maximal cliques that it has.
Therefore I would like that nodes in the same maximal clique will be visually encapsulated together (meaning that I would like that a big circle will surround them). I know that the cluster option exists - but in all the exam... | Take a tea, it's gonna be long :)
I draw this with [networkx](http://networkx.lanl.gov), but the main steps could be easily transferred into graphviz.
The plan is the following:
**a)** find maximal cliques (just in case, maximal cliques are not necessary the largest cliques);
**b)** draw the graph and remember th... |
Getting serialized json objects from django templates? | 9,214,677 | 4 | 2012-02-09T16:23:11Z | 9,214,791 | 8 | 2012-02-09T16:30:46Z | [
"python",
"django",
"json"
] | I need a clarification. If I for example do a view with a serialized object:
```
def sample(request):
res = [{'name':'man'}]
encoded = json.dumps(res)
return render_to_response('sample/example.html',{'encoded':encoded} )
```
In my templates I pass:
```
{{encoded}}
```
Now from a python script can I do:
... | Try this in your template:
```
{% autoescape off %}
{{ encoded }}
{% endautoescape %}
``` |
cmap.set_bad() not showing any effect with pcolor() | 9,214,971 | 3 | 2012-02-09T16:41:44Z | 9,215,126 | 7 | 2012-02-09T16:52:34Z | [
"python",
"numpy",
"matplotlib"
] | I'm trying to use pcolor on a masked array. I would like masked elements
to show up in a special color. I have written some code, but it does not
seem to work:
```
import matplotlib as mpl
import matplotlib.pyplot as plt
from numpy import linspace
from numpy.random import randn
from numpy.ma import masked_invalid
D ... | The docs for [pcolormesh](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.pcolormesh) say:
> Masked array support is
> implemented via cmap and norm; **in contrast**, pcolor() simply does not
> draw quadrilaterals with masked colors or vertices.
So use pcolormesh instead:
```
import matplotli... |
plot a circle with pyplot | 9,215,658 | 48 | 2012-02-09T17:23:25Z | 9,216,630 | 12 | 2012-02-09T18:31:00Z | [
"python",
"matplotlib"
] | surprisingly I didn't find a straight-forward description on how to draw a circle with matplotlib.pyplot (please no pylab) taking as input center (x,y) and radius r. I tried some variants of this:
```
import matplotlib.pyplot as plt
circle=plt.Circle((0,0),2)
# here must be something like circle.plot() or not?
plt.sho... | ```
#!/usr/bin/python
import matplotlib.pyplot as plt
import numpy as np
def xy(r,phi):
return r*np.cos(phi), r*np.sin(phi)
fig = plt.figure()
ax = fig.add_subplot(111,aspect='equal')
phis=np.arange(0,6.28,0.01)
r =1.
ax.plot( *xy(r,phis), c='r',ls='-' )
plt.show()
```
Or, if you prefer, look at the `path`s, <h... |
plot a circle with pyplot | 9,215,658 | 48 | 2012-02-09T17:23:25Z | 9,216,646 | 63 | 2012-02-09T18:32:25Z | [
"python",
"matplotlib"
] | surprisingly I didn't find a straight-forward description on how to draw a circle with matplotlib.pyplot (please no pylab) taking as input center (x,y) and radius r. I tried some variants of this:
```
import matplotlib.pyplot as plt
circle=plt.Circle((0,0),2)
# here must be something like circle.plot() or not?
plt.sho... | You need to add it to an axes. A `Circle` is a subclass of an `Artist`, and an `axes` has an `add_artist` method.
Here's an example of doing this:
```
import matplotlib.pyplot as plt
circle1 = plt.Circle((0, 0), 0.2, color='r')
circle2 = plt.Circle((0.5, 0.5), 0.2, color='blue')
circle3 = plt.Circle((1, 1), 0.2, col... |
plot a circle with pyplot | 9,215,658 | 48 | 2012-02-09T17:23:25Z | 23,498,706 | 8 | 2014-05-06T15:20:47Z | [
"python",
"matplotlib"
] | surprisingly I didn't find a straight-forward description on how to draw a circle with matplotlib.pyplot (please no pylab) taking as input center (x,y) and radius r. I tried some variants of this:
```
import matplotlib.pyplot as plt
circle=plt.Circle((0,0),2)
# here must be something like circle.plot() or not?
plt.sho... | Use the scatter() method. <http://matplotlib.org/1.3.1/api/pyplot_api.html#matplotlib.pyplot.scatter>
```
import matplotlib.pyplot as plt
x=[1,2,3,4,5]
y=[10,20,30,40,50]
r=[100,80, 60, 40, 20] # in points, not data units
fig, ax = plt.subplots(1,1)
ax.scatter(x, y, s=r)
fig.show()
```
![enter image description here]... |
plot a circle with pyplot | 9,215,658 | 48 | 2012-02-09T17:23:25Z | 24,568,380 | 15 | 2014-07-04T07:00:27Z | [
"python",
"matplotlib"
] | surprisingly I didn't find a straight-forward description on how to draw a circle with matplotlib.pyplot (please no pylab) taking as input center (x,y) and radius r. I tried some variants of this:
```
import matplotlib.pyplot as plt
circle=plt.Circle((0,0),2)
# here must be something like circle.plot() or not?
plt.sho... | If you want to plot a set of circles, you might want to see [this post](http://stackoverflow.com/a/24567352/2144720) or [this gist](https://gist.github.com/syrte/592a062c562cd2a98a83)(a bit newer). The post offered a function named `circles`.
The function `circles` works like `scatter`, but the sizes of plotted circle... |
plot a circle with pyplot | 9,215,658 | 48 | 2012-02-09T17:23:25Z | 29,184,075 | 12 | 2015-03-21T14:51:21Z | [
"python",
"matplotlib"
] | surprisingly I didn't find a straight-forward description on how to draw a circle with matplotlib.pyplot (please no pylab) taking as input center (x,y) and radius r. I tried some variants of this:
```
import matplotlib.pyplot as plt
circle=plt.Circle((0,0),2)
# here must be something like circle.plot() or not?
plt.sho... | ```
import matplotlib.pyplot as plt
circle1=plt.Circle((0,0),.2,color='r')
plt.gcf().gca().add_artist(circle1)
```
A quick condensed version of the accepted answer, that suited my need to quickly plug a circle into an existing plot. Refer to the accepted answer and other answers to understand the details.
By the way:... |
pythonic conversion of list of lists to strings by column | 9,215,879 | 2 | 2012-02-09T17:38:06Z | 9,215,916 | 8 | 2012-02-09T17:40:48Z | [
"python",
"numpy",
"scipy"
] | i have a list of lists corresponding to an array (each list inside the list has the same number of entries):
```
a = [[1,2,3],[4,5,6],[7,8,9]]
```
i'd like to convert this to a single string:
```
"1,4,7\t2,4,8\t3,6,9"
```
ie make each column be a comma separated list of string values from `a`. my solution with nump... | You can transpose a list of lists using [`zip()`](http://docs.python.org/library/functions.html#zip):
```
>>> zip(*a)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
```
Everything else is simple:
```
>>> "\t".join(",".join(map(str, r)) for r in zip(*a))
'1,4,7\t2,5,8\t3,6,9'
``` |
SMTP AUTH extension not supported by server in python 2.4 | 9,216,127 | 12 | 2012-02-09T17:54:25Z | 9,224,314 | 13 | 2012-02-10T07:37:41Z | [
"python",
"linux",
"smtp",
"vps",
"python-2.4"
] | This is my normal code in my VPS hosting which provide python 2.4
```
def mail(receiver,Message):
import smtplib
try:
s=smtplib.SMTP()
s.connect("smtp.gmail.com",465)
s.login("email@gmail.com", "password")
s.sendmail("email@gmail.com", receiver, Message)
except Exception,R:
... | Guys thanks i've found the solution and this is the solution =)
```
def mail(receiver,Message):
import smtplib
try:
s=smtplib.SMTP()
s.connect("smtp.gmail.com",465)
s.ehlo()
s.starttls()
s.ehlo()
s.login("email@gmail.com", "password")
s.sendmail("email@gm... |
Read 32-bit signed value from an "unsigned" bytestream | 9,216,344 | 4 | 2012-02-09T18:09:07Z | 9,216,422 | 8 | 2012-02-09T18:15:54Z | [
"python",
"endianness",
"sign"
] | I want to extract data from a file whoose information is stored in big-endian and *always* unsigned. How does the **"cast"** from *unsigned int* to *int* affect the actual decimal value? Am I correct that the most left bit decides about the whether the value is positive or negative?
I want to parse that file-format wi... | I would use [struct](http://docs.python.org/library/struct.html).
```
import struct
def toU32(bits):
return struct.unpack_from(">I", bits)[0]
def toS32(bits):
return struct.unpack_from(">i", bits)[0]
```
The format string, ">I", means read a big endian, ">", unsigned integer, "I", from the string bits. For ... |
Extend str class to take additional parameters | 9,218,449 | 4 | 2012-02-09T20:42:49Z | 9,218,567 | 7 | 2012-02-09T20:51:16Z | [
"python",
"string",
"class",
"extend"
] | I want to create a new class that is a special type of string. I want it to inherit all the methods of the str class, but I want to be able to pass it an additional parameter that it can use. Something like this:
```
class URIString(str, ns = namespace): # ns defaults to global variable namespace
def getLocalName(... | You would want to do something like this:
```
class URIString(str):
_default_namespace = "default"
def __init__(self, value, namespace=_default_namespace):
self.namespace = namespace
def __new__(cls, value, namespace=_default_namespace):
return super().__new__(cls, value)
@prop... |
Add metadata to image upload to S3 with Python | 9,218,830 | 6 | 2012-02-09T21:11:02Z | 9,218,881 | 13 | 2012-02-09T21:14:28Z | [
"python",
"amazon-s3",
"png",
"content-type",
"boto"
] | I'm successfully adding an image to a bucket on S3, but the problem is I'm not sure how to set the content-type to 'image/png'. Here is my code
```
image = Image.open(self.image)
conn = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
out_im2 = cStringIO.StringIO()
image.save(out_im2, 'PNG... | This is how my image upload code (using boto) works:
```
k.set_metadata('Content-Type', mime)
k.set_contents_from_file(data, policy='public-read')
k.set_acl('public-read')
```
Well at least part of it. |
metaclass error: type.__init__() takes 1 or 3 arguments | 9,219,883 | 4 | 2012-02-09T22:31:43Z | 9,219,895 | 9 | 2012-02-09T22:32:12Z | [
"python",
"metaclass"
] | I have a metaclass:
```
class MyMeta(type):
def __init__(cls, name, bases, dct):
# Do something
...
return super(MyMeta, cls).__init__(cls, name, bases, dct)
```
and a class:
```
class MyClass(object):
__metaclass__ = MyMeta
```
When I use these I get the following error:
```
E ... | The problem is that in the upgrade from python 2.5 to python 2.6 `type.__init__()` was changed so that you are no longer required to pass in `cls`. So simply make the `super` call:
```
return super(MyMeta, cls).__init__(name, bases, dct)
```
Another solution is to avoid the `super` call altogether and do this (althou... |
Python numpy array vs list | 9,220,372 | 9 | 2012-02-09T23:09:15Z | 9,220,452 | 9 | 2012-02-09T23:16:17Z | [
"python",
"arrays",
"list"
] | I need to perform some calculations a large list of numbers.
Do array.array or numpy.array offer significant performance boost over typical arrays?
I don't have to do complicated manipulations on the arrays, I just need to be able to access and modify values,
e.g.
```
import numpy
x = numpy.array([0] * 1000000)
for... | You first need to understand the difference between arrays and lists.
An array is a **contiguous** block of memory consisting of elements of some type (e.g. integers).
You cannot change the size of an array once it is created.
It therefore follows that **each integer element in an array has a *fixed size***, e.g. 4... |
Python numpy array vs list | 9,220,372 | 9 | 2012-02-09T23:09:15Z | 9,220,700 | 7 | 2012-02-09T23:40:27Z | [
"python",
"arrays",
"list"
] | I need to perform some calculations a large list of numbers.
Do array.array or numpy.array offer significant performance boost over typical arrays?
I don't have to do complicated manipulations on the arrays, I just need to be able to access and modify values,
e.g.
```
import numpy
x = numpy.array([0] * 1000000)
for... | Your first example could be speed up. Python loop and access to individual items in a numpy array are slow. Use vectorized operations instead:
```
import numpy as np
x = np.arange(1000000).cumsum()
```
You can put unbounded Python integers to numpy array:
```
a = np.array([0], dtype=object)
a[0] += 12322342342343243... |
How to get siblings when using contains(text(), ) in xpath | 9,221,972 | 3 | 2012-02-10T02:34:59Z | 9,222,121 | 7 | 2012-02-10T02:58:06Z | [
"python",
"xpath"
] | I have been introduced to xpath today and it seems to be very powerful but after quite a bit of searching, I haven't found how to retrieve siblings (via following-sibling and preceding-sibling) when contains is being used:
```
text = """
<html>
<head>
<title>This tag includes 'some_text'</title>
<h2>A h2 tag... | Funny html sample you have.
```
import lxml
text = """
<html>
<body>
<span>This tag includes 'some_text'</span>
<h2>A h2 tag</h2>
</body>
</html>
"""
doc = lxml.etree.fromstring(text, parser=lxml.etree.HTMLParser())
doc.xpath("//*[contains(text(),'so... |
How to extract information between two unique words in a large text file | 9,222,106 | 4 | 2012-02-10T02:55:06Z | 9,222,120 | 12 | 2012-02-10T02:58:00Z | [
"python",
"parsing",
"search",
"text",
"batch-file"
] | I have about 150 text files filled with character information. Each file contains two unique words ()alpha and bravo and i want to extract the text between these unique words and write it to a different file.
Manually i can CTRL+F for the two words and copy the text between, i just want to know how to do this using a ... | You can use [regular expressions](http://docs.python.org/library/re.html) for that.
```
>>> st = "alpha here is my text bravo"
>>> import re
>>> re.findall(r'alpha(.*?)bravo',st)
[' here is my text ']
```
My test.txt file
```
alpha here is my line
yipee
bravo
```
Now using [open](http://docs.python.org/tutorial/inp... |
SQLAlchemy Polymorphic Relationship with Concrete Inheritance | 9,223,630 | 5 | 2012-02-10T06:22:54Z | 9,237,152 | 7 | 2012-02-11T01:54:52Z | [
"python",
"orm",
"sqlalchemy",
"flask-sqlalchemy",
"concrete-inheritance"
] | I am using the concrete table inheritance with SQLAlchemy. In declartive style model class, I have configured it successfully.
My code just like:
```
class Entry(AbstractConcreteBase, db.Model):
"""Base Class of Entry."""
id = db.Column(db.Integer, primary_key=True, nullable=False)
created = db.Column(db... | I have found the reason of the problem and its solution.
According to the document of sqlalchemy offical website, the abstract class could be a mapped class, because the `polymorphic_union` function could create a virtual table.
I am using the declartive style model, not build mapper by hand, so the virtual table `pj... |
How do you verify duck-typed interfaces in python? | 9,223,760 | 8 | 2012-02-10T06:38:24Z | 9,223,841 | 9 | 2012-02-10T06:47:17Z | [
"python"
] | ```
class ITestType(object):
""" Sample interface type """
__metaclass__ = ABCMeta
@abstractmethod
def requiredCall(self):
return
class TestType1(object):
""" Valid type? """
def requiredCall(self):
pass
class TestType2(ITestType):
""" Valid type """
def requiredCall(self):
pass
class T... | Check out the [`ABC` module](http://docs.python.org/library/abc.html). You can define an abstract base class that provides a `__subclasshook__` method that defines whether a particular class "is a subclass" of the abstract base class based on any criteria you like -- such as "it has methods X, Y and Z" or whatever. The... |
Python timestamp from day, month, year | 9,223,905 | 3 | 2012-02-10T06:52:28Z | 9,223,988 | 19 | 2012-02-10T07:00:33Z | [
"python",
"datetime"
] | Is it possible to create a UNIX timestamp in Python (number of seconds) with only day, month and year from a date object? I'm essentially looking for what the timestamp would be at midnight (hour, minute and second would be 0).
Thanks! | ```
>>> import time
>>> import datetime
>>> dt = datetime.datetime.strptime('2012-02-09', '%Y-%m-%d')
>>> time.mktime(dt.timetuple())
1328774400.0
```
**--OR--**
```
>>> dt = datetime.datetime(year=2012, month=2, day=9)
>>> time.mktime(dt.timetuple())
1328774400.0
``` |
In dictionary, converting the value from string to integer | 9,224,385 | 4 | 2012-02-10T07:45:21Z | 9,224,416 | 11 | 2012-02-10T07:48:45Z | [
"python",
"string",
"dictionary",
"integer"
] | Taking this below example :
```
'user_stats': {'Blog': '1',
'Discussions': '2',
'Followers': '21',
'Following': '21',
'Reading': '5'},
```
I want to convert it into:
```
'Blog' : 1 , 'Discussion': 2, 'Followers': 21, 'Following': 21, 'Reading': 5
``` | ```
dict_with_ints = dict((k,int(v)) for k,v in dict_with_strs.iteritems())
``` |
How to install PIL in Ubuntu 11.04? | 9,225,514 | 10 | 2012-02-10T09:28:06Z | 9,225,581 | 12 | 2012-02-10T09:32:29Z | [
"python",
"ubuntu",
"python-imaging-library"
] | I see this question asked all over the internet, and I've tried following them all, but I still can't get PIL to work.
I tried symbolically linking the zlib, jpeg, etc. libraries via:
```
sudo ln -s /usr/lib/x86_64-linux-gnu/libfreetype.so /usr/lib/
sudo ln -s /usr/lib/x86_64-linux-gnu/libz.so /usr/lib/
sudo ln -s /u... | As always, use the package manager:
```
sudo apt-get install python-imaging
```
It'll deal with it all for you. The [packages](http://packages.ubuntu.com/search?keywords=python-imaging) are available.
Manually installing, in any Linux distro, is a wasted endeavour, unless the packages really don't exist. Package mai... |
Why does Python cv2 modules depend on (old) cv | 9,226,258 | 5 | 2012-02-10T10:26:03Z | 9,986,334 | 9 | 2012-04-03T02:27:43Z | [
"python",
"opencv"
] | I'm new to OpenCV and would like to use its Python binding.
When trying out the samples on OSX, I noticed
1.) The windows imshow creates are not resizable
2.) I can fix that with an prior call to cv2.namedWindow, like:
cv2.namedWindow('zoom', cv2.cv.CV\_WINDOW\_NORMAL)
Can we add symbols like CV\_WINDOW\_NORMAL fro... | There are some omisions in the current new cv2 lib. Typically these are constants that did not get migrated to cv2 yet and are still in cv only.
Here is some code to help you find them:
```
import cv2
import cv2.cv as cv
nms = [(n.lower(), n) for n in dir(cv)] # list of everything in the cv module
nms2 = [(n.lower(),... |
Python, windows console and encodings (cp 850 vs cp1252) | 9,226,516 | 11 | 2012-02-10T10:45:48Z | 9,228,117 | 18 | 2012-02-10T12:54:02Z | [
"python",
"windows",
"encoding"
] | I thought I knew everything about encodings and Python, but today I came across a weird problem: although the console is set to code page 850 - and Python reports it correctly - parameters I put on the command line seem to be encoded in code page 1252. If I try to decode them with sys.stdin.encoding, I get the wrong re... | Replying to myself:
On Windows, the encoding used by the console (thus, that of sys.stdin/out) differs from the encoding of various OS-provided strings - obtained through e.g. os.getenv(), sys.argv, and certainly many more.
The encoding provided by sys.getdefaultencoding() is really that - a default, chosen by Python... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.