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 save an image using django imageField? | 8,822,755 | 5 | 2012-01-11T16:20:17Z | 8,824,146 | 15 | 2012-01-11T17:52:22Z | [
"python",
"django",
"imagefield"
] | posting from an app (iOS android etc..) not a web form.
```
class someImage(models.Model):
image = models.ImageField(upload_to= settings.SHARE_IMAGE_UPLOAD_PATH)
@csrf_exempt
def saveImage(request):
```
How to write the view? it receives an image in a post request.
Every thing i find is form related (server newb... | Just because you're not using an actual HTML form to submit the data doesn't mean you can't use a `ModelForm` to process the request:
```
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed
from django.utils import simplejson
def upload_view(request):
if request.method == 'POST':
... |
How to pass arguments to callback functions in PyQt | 8,824,311 | 3 | 2012-01-11T18:03:21Z | 8,824,715 | 25 | 2012-01-11T18:35:15Z | [
"python",
"pyqt",
"signals-slots"
] | I have around 10 QAction (this number will vary in runtime) in a toolbar, which all will do same thing, but using different parameters. I am thinking to add parameter as an attribute to QAction object, and then, QAction's triggered signal will also send object's itself to the callback function, so that I could get requ... | > How to pass arguments to callback functions in PyQt
You can use [`functools.partial`](http://docs.python.org/library/functools.html#functools.partial) from standart Python library. Example with `QAction`:
```
some_action.triggered.connect(functools.partial(some_callback, param1, param2))
``` |
An autoincrementing callable? | 8,824,381 | 5 | 2012-01-11T18:08:05Z | 8,824,407 | 10 | 2012-01-11T18:09:58Z | [
"python",
"auto-increment",
"counter"
] | I have a method within which I need to pass an ever-increasing integer to another function.
I can do this like so:
```
def foo(i):
print i
def bar():
class Incrementer(object):
def __init__(self, start=0):
self.i = start
def __get__(self):
j = self.i
self... | Try [`itertools.count()`](http://docs.python.org/library/itertools.html#itertools.count) -- it does exactly what you need:
```
>>> c = itertools.count()
>>> next(c)
0
>>> next(c)
1
>>> next(c)
2
``` |
How are version control histories stored and calculated? | 8,824,597 | 11 | 2012-01-11T18:26:03Z | 8,826,262 | 8 | 2012-01-11T20:39:10Z | [
"python",
"git",
"svn",
"version-control",
"mercurial"
] | Consider this simple python code, which demonstrates a very simple version control design for a dictonary:
```
def build_current(history):
current = {}
for action, key, value in history:
assert action in ('set', 'del')
if action == 'set':
current[key] = value
elif action == ... | I think subversion made some attempts at backwards build. But I can explain what I know better: Mercurial snapshots.
Mercurial uses a forward build scheme. But in order for each revision to be easily rebuildable, there are resync points: every time the size of all the deltas needed to rebuild a revision is bigger than... |
How are version control histories stored and calculated? | 8,824,597 | 11 | 2012-01-11T18:26:03Z | 8,826,605 | 10 | 2012-01-11T21:05:16Z | [
"python",
"git",
"svn",
"version-control",
"mercurial"
] | Consider this simple python code, which demonstrates a very simple version control design for a dictonary:
```
def build_current(history):
current = {}
for action, key, value in history:
assert action in ('set', 'del')
if action == 'set':
current[key] = value
elif action == ... | You mentioned these 3 methods of storing (file)-history:
1. **patch** : a patch is the (usually textual, but binary patches are also possible) representation of the difference between two files. It is the output of unix command *diff* and can be applied by unix command *patch*. A lot of versioning systems are using pa... |
Is it odd that my SQLAlchemy MySQL connection always ends up sleeping? | 8,824,826 | 13 | 2012-01-11T18:42:50Z | 8,825,024 | 21 | 2012-01-11T18:56:19Z | [
"python",
"mysql",
"sqlalchemy",
"flask"
] | I have a Flask web application using SQLAlchemy with MySQL, and I have set up a scopedsession(). I also have a teardown\_request handler that calls session.remove() after every request is finished. For some odd reason, if no requests are made on the web app for a day or more, the app gets "Operationalerror: MySQL Serve... | SQLAlchemy's default behavior is to pool connections within the Engine:
<http://www.sqlalchemy.org/docs/core/engines.html>
<http://www.sqlalchemy.org/docs/core/pooling.html>
As far as the disconnect overnight thing, this is a known MySQL behavior, SQLAlchemy provides the pool\_recycle flag to work around it. Here ar... |
Integers from excel files become floats? | 8,825,681 | 7 | 2012-01-11T19:48:40Z | 8,826,544 | 7 | 2012-01-11T21:00:27Z | [
"python",
"xlrd"
] | I use `xlrd` to read data from excel files.
For integers stored in the files, let's say `63`, the `xlrd` interprets it as `63.0` of type `number`.
Why can't `xlrd` recognize `63` as an integer?
Assume `sheet.row(1)[0].value` gives us `63.0`. How can I convert it back to `63`. | The answer given by jcollado is alright if you have all the entries in the excel sheet as numbers which are integers.
But suppose you have a number which is a float you can always put a check condition like -
```
if i==int(i): //checking for the integer:
print int(i) // solving your problem and printing... |
Integers from excel files become floats? | 8,825,681 | 7 | 2012-01-11T19:48:40Z | 8,826,770 | 12 | 2012-01-11T21:16:58Z | [
"python",
"xlrd"
] | I use `xlrd` to read data from excel files.
For integers stored in the files, let's say `63`, the `xlrd` interprets it as `63.0` of type `number`.
Why can't `xlrd` recognize `63` as an integer?
Assume `sheet.row(1)[0].value` gives us `63.0`. How can I convert it back to `63`. | Excel treats all numbers as floats. In general, it doesn't care whether `your_number % 1 == 0.0` is true or not.
Example: `A1 = 63.0, B1 = 63, C1 = INT(A1), A2 = TYPE(A1), B2 = TYPE(B1), C2 = TYPE(C1)`
You'l see that `TYPE()` returns 1 in each case.
From the Excel Help:
```
If value is TYPE returns
Number ... |
Python: avoiding if condition for this code? | 8,826,521 | 6 | 2012-01-11T20:58:48Z | 8,826,602 | 8 | 2012-01-11T21:05:09Z | [
"python",
"if-statement",
"flow-control"
] | for the following code
```
a =func()
if a != None:
b.append(a)
```
a can be assigned to None, is there a way to avoid the if statement and only use one line of code?
original problem is the following
```
import xml.etree.ElementTree as etree
r = etree.parse(f).getroot()
b = etree.Element('register',{})
a = r.... | If you can call func() beforehand, and you want to combine the test and assignment statements into a single statement, then you can do this, with an if-else expression:
```
b += [a] if a is not None else []
```
If a is not None, then this will add [a] to b -- essentially the same operation as b.append(a)
If a *is* N... |
converting utf-16 -> utf-8 AND remove BOM | 8,827,419 | 9 | 2012-01-11T22:09:17Z | 8,827,512 | 13 | 2012-01-11T22:17:20Z | [
"python",
"unicode",
"utf-8",
"utf-16"
] | We have a data entry person who encoded in UTF-16 on Windows and would like to have utf-8 and remove the BOM. The utf-8 conversion works but BOM is still there. How would I remove this? This is what I currently have:
```
batch_3={'src':'/Users/jt/src','dest':'/Users/jt/dest/'}
batches=[batch_3]
for b in batches:
s_... | Just use [`str.decode`](http://docs.python.org/library/stdtypes.html#str.decode) and [`str.encode`](http://docs.python.org/library/stdtypes.html#str.encode):
```
with open(ff_name, 'rb') as source_file:
with open(target_file_name, 'w+b') as dest_file:
contents = source_file.read()
dest_file.write(contents.de... |
converting utf-16 -> utf-8 AND remove BOM | 8,827,419 | 9 | 2012-01-11T22:09:17Z | 8,827,604 | 19 | 2012-01-11T22:25:50Z | [
"python",
"unicode",
"utf-8",
"utf-16"
] | We have a data entry person who encoded in UTF-16 on Windows and would like to have utf-8 and remove the BOM. The utf-8 conversion works but BOM is still there. How would I remove this? This is what I currently have:
```
batch_3={'src':'/Users/jt/src','dest':'/Users/jt/dest/'}
batches=[batch_3]
for b in batches:
s_... | This is the difference between `UTF-16LE` and `UTF-16`
* `UTF-16LE` is little endian **without** a BOM
* `UTF-16` is big or little endian **with** a BOM
So when you use `UTF-16LE`, the BOM is just part of the text. Use `UTF-16` instead, so the BOM is automatically removed. The reason `UTF-16LE` and `UTF-16BE` exist i... |
Python follow redirects and then download the page? | 8,827,545 | 11 | 2012-01-11T22:20:14Z | 8,828,336 | 14 | 2012-01-11T23:42:29Z | [
"python",
"html",
"web-scraping"
] | I have the following python script and it works beautifully.
```
import urllib2
url = 'http://abc.com' # write the url here
usock = urllib2.urlopen(url)
data = usock.read()
usock.close()
print data
```
however, some of the URL's I give it may redirect it 2 or more times. How can I have python wait for redirects to... | You might be better off with Requests library which has better APIs for controlling redirect handling:
<http://docs.python-requests.org/en/latest/user/quickstart/#redirection-and-history>
Requests:
<http://pypi.python.org/pypi/requests/> (urllib replacement for humans) |
Append a plus sign before positive numbers? | 8,827,852 | 7 | 2012-01-11T22:46:48Z | 8,827,930 | 10 | 2012-01-11T22:54:21Z | [
"python",
"printf"
] | I'm printing floats trimmed to 3 digits after the zero, and I'd like to know if I can conditionally append a `+` before positive numbers, so I get
```
+0.005
```
for a positive change and
```
-0.005
```
for a negative change. Is this easily possible from within printf? | Yes, just use a '+' in the format specifier.
Ex:
```
>>> "{0:+.03f}".format(1.23456)
'+1.235'
``` |
A multiline(paragraph) footer and header in reportlab | 8,827,871 | 10 | 2012-01-11T22:48:33Z | 11,942,346 | 18 | 2012-08-13T21:08:52Z | [
"python",
"pdf",
"pdf-generation",
"reportlab"
] | What is a best way to have a footer and header in reportlab, that not just a single line, that can be drawed with canvas.drawString in onPage function. Didn`t find a way to put something like Paragraph into header/footer in onPage function. What is the best way to handle this? Is there a way to put a paragraph into foo... | You can use arbitrary drawing commands in the onPage function, so you can just draw a paragraph (see section 5.3 in the [reportlab user guide](http://www.reportlab.com/docs/reportlab-userguide.pdf)) from your function.
Here is a complete example:
```
from reportlab.lib.pagesizes import letter
from reportlab.lib.style... |
Same algorithm implementation has different retults in Python and C++? | 8,828,155 | 3 | 2012-01-11T23:21:21Z | 8,828,184 | 16 | 2012-01-11T23:24:44Z | [
"c++",
"python"
] | This python code works properly and produces proper output:
```
def fib(x):
v = 1
u = 0
for x in xrange(1,x+1):
t = u + v
u = v
v = t
return v
```
But when I write the same code in C++ it gives me a different and impossible result.
```
int fib(int x)
{
int v = 1;
int u... | For what input? Python has integers of unlimited (memory limited) size, C++'s `int` usually is a four byte integer, so you'll likely have overflow.
The largest Fibonacci number representable with a signed 32-bit integer type is `fib(46) = 1836311903`. |
SPOJ The Next Palindrome | 8,829,296 | 3 | 2012-01-12T02:11:01Z | 8,834,909 | 7 | 2012-01-12T12:14:16Z | [
"python",
"algorithm"
] | I am trying to solve SPOJ problem 5: find the next largest integer "palindrome" for a given input; that is, an integer that in decimal notation reads the same from left-to-right and right-to-left.
Please have a look of the question [here](http://www.spoj.pl/problems/PALIN/)
Instead of using brute force search, I try ... | The input can be long. The problem statement says "not more than 1000000 digits". So probably there are a couple of test cases with several hundred thousand digits. Splitting such a string in halves, reversing one half and appending them does take a little time. But as far as I know, Python's string handling is pretty ... |
LXML and XSL document() Function | 8,831,941 | 6 | 2012-01-12T08:23:09Z | 8,832,695 | 7 | 2012-01-12T09:28:58Z | [
"python",
"xslt",
"lxml"
] | Hi i got the following files :
merge.py:
```
from lxml import etree
xml_input = etree.XML(open('a.xml', 'r').read())
xslt_root = etree.XML(open('merge.xsl', 'r').read())
transform = etree.XSLT(xslt_root)
print str(transform(xml_input))
```
merge.xsl:
```
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.or... | You need to register a URI resolver. See [the documentation](http://lxml.de/resolvers.html).
Probably something like this (untested):
```
class FileResolver(etree.Resolver):
def resolve(self, url, pubid, context):
return self.resolve_filename(url, context)
parser = etree.XMLParser()
parser.resolvers.add(... |
How to use multiple wildcards in Python File Dialog | 8,832,714 | 6 | 2012-01-12T09:30:23Z | 8,833,014 | 14 | 2012-01-12T09:52:03Z | [
"python",
"wxpython"
] | how can I use the code below to have the user browse for either png or jpeg files? Did I do it correctly?
```
wildcard = "pictures (*.jpeg/*.png)|*.jpeg/*.png"
dlg = wx.FileDialog(self, message="Select your picture file",defaultDir=os.getcwd(),defaultFile="*.jpeg/*.png", wildcard=wildcard, style=wx.OPEN)
if dlg.ShowM... | Although I am using a reference of a VB6 [website](http://www.vb-helper.com/howto_add_commondialog_filters.html), the value of wildcard should be
```
wildcard = "pictures (*.jpeg,*.png)|*.jpeg;*.png"
``` |
Using Python bindings, Selenium WebDriver click() is not working sometimes. | 8,832,858 | 10 | 2012-01-12T09:40:29Z | 9,678,084 | 7 | 2012-03-13T03:42:48Z | [
"python",
"selenium",
"webdriver",
"selenium-webdriver"
] | I am trying to submit an input(type= button).But I am unable to update the value.
Any help is appreciated.
I have attached the testcase below for your reference.
**search for CLICK FAILS HERE**
```
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Sel... | You could try substituting `.click()` with .`send_keys("\n")`, which is equivalent to "Pressing enter while focusing on an element".
So this:
```
driver.find_element_by_link_text('PurchaseOrder').click()
```
would become this:
```
driver.find_element_by_link_text('PurchaseOrder').send_keys("\n")
``` |
How to make mechanize wait for web-page 'full' load? | 8,833,239 | 8 | 2012-01-12T10:07:27Z | 8,833,297 | 10 | 2012-01-12T10:11:49Z | [
"python",
"mechanize"
] | I want to scrape some web page which loads its components dynamically.
This page has an onload script, and I can see the complete page 3-5 seconds after typing the URL into my browser.
The problem is, when I call `br.open('URL')`, the response is the web page at 0 seconds.
There is a difference 3-5 seconds later betwe... | The problem you're having is that the web page is rendered in your web browser through the javascript engine. However, mechanize doesn't have the ability to execute javascript on its own so, no matter how long you wait, you aren't going to get the HTML you're missing using just mechanize.
For more information about ho... |
Best way to sort a dictionary into groups using Python | 8,833,312 | 7 | 2012-01-12T10:12:31Z | 8,833,355 | 13 | 2012-01-12T10:16:02Z | [
"python",
"list",
"sorting"
] | I have a list of dictionaries eg:
```
[{'person':'guybrush','job':'pirate'},{'person':'leChuck','job':'pirate'}, {'person':'elaine','job':'governor'}]
```
I want to display the people grouped by their jobs. So in the front end, we can select a job and see all of the people that have the selected job.
I have performe... | This is simple using a [`defaultdict`](http://docs.python.org/library/collections.html#collections.defaultdict):
```
persons_by_jobs = defaultdict(list)
for person in persons:
persons_by_jobs[person['job']].append(person['person'])
``` |
How to determine which points are inside of a polygon and which are not (large number of points)? | 8,833,950 | 15 | 2012-01-12T10:59:55Z | 8,834,235 | 22 | 2012-01-12T11:21:47Z | [
"python",
"numpy",
"matplotlib"
] | I've got a large set of data points (100,000+) stored in a 2-dimensional numpy array (1st column: x coordinates, 2nd column: y coordinates). I've also got several 1-dimensional arrays storing additional information for each data point. I'd now like to create plots from subsets of these 1D arrays which include only the ... | Use [matplotlib.nxutils.points\_inside\_poly](http://matplotlib.org/1.2.1/api/nxutils_api.html#matplotlib.nxutils.points_inside_poly), which implements a very efficient test.
Examples and further explanation of this 40-year-old algorithm at the [matplotlib FAQ](http://matplotlib.sourceforge.net/faq/howto_faq.html#test... |
How to determine which points are inside of a polygon and which are not (large number of points)? | 8,833,950 | 15 | 2012-01-12T10:59:55Z | 8,836,123 | 8 | 2012-01-12T13:47:59Z | [
"python",
"numpy",
"matplotlib"
] | I've got a large set of data points (100,000+) stored in a 2-dimensional numpy array (1st column: x coordinates, 2nd column: y coordinates). I've also got several 1-dimensional arrays storing additional information for each data point. I'd now like to create plots from subsets of these 1D arrays which include only the ... | I'm afraid I'm not familiar with the libraries you are using, but I think I have a reasonable idea for the algorithm you could use and I'll just run through how I would implement that with vanilla python and then I'm sure you can improve it and implement it using these libraries. Also, I am not claiming that this is th... |
How do I make a trailing slash optional with webapp2? | 8,834,332 | 16 | 2012-01-12T11:29:23Z | 8,902,547 | 12 | 2012-01-17T22:20:34Z | [
"python",
"google-app-engine",
"webapp2"
] | I'm using the new webapp2 (now the default webapp in 1.6), and I haven't been able to figure out how to make the trailing slash optional in code like this:
```
webapp.Route('/feed', handler = feed)
```
I've tried `/feed/?`, `/feed/*`, `/feed\/*` and `/feed\/?`, all to no avail. | To avoid creating duplicate URL:s to the same page, you should use a RedirectRoute with strict\_slash set to True to automatically redirect /feed/ to /feed, like this:
```
from webapp2_extras.routes import RedirectRoute
route = RedirectRoute('/feed', handler=feed, strict_slash=True)
```
Read more at <http://webapp2.... |
Where can I get the FirefoxDriver for WebDriver? | 8,834,637 | 9 | 2012-01-12T11:51:59Z | 8,834,938 | 10 | 2012-01-12T12:16:15Z | [
"python",
"firefox",
"webdriver"
] | Google Chrome has a `ChromeDriver` available [here](http://code.google.com/p/chromium/downloads/list). I cannot find the equivalent for Firefox. (Which I think is necessary to make `ActionChains` working.) | Firefox Driver comes with Selenium/Webdriver itself. No need to launch an external server (like Chromedriver). It is all built-in.
<http://code.google.com/p/selenium/wiki/FirefoxDriver> |
How can I include special characters (tab, newline) in a python doctest result string? | 8,834,916 | 17 | 2012-01-12T12:14:48Z | 8,849,771 | 12 | 2012-01-13T11:21:16Z | [
"python",
"string",
"special-characters",
"quotes",
"doctest"
] | Given the following python script:
```
# dedupe.py
import re
def dedupe_whitespace(s,spacechars='\t '):
"""Merge repeated whitespace characters.
Example:
>>> dedupe_whitespace(r"Green\t\tGround") # doctest: +REPORT_NDIFF
'Green\tGround'
"""
for w in spacechars:
s = re.sub(r"("+w+"+)",... | I've gotten this to work using literal string notation for the docstring:
```
def join_with_tab(iterable):
r"""
>>> join_with_tab(['1', '2'])
'1\t2'
"""
return '\t'.join(iterable)
if __name__ == "__main__":
import doctest
doctest.testmod()
``` |
How can I include special characters (tab, newline) in a python doctest result string? | 8,834,916 | 17 | 2012-01-12T12:14:48Z | 8,858,536 | 9 | 2012-01-13T23:15:24Z | [
"python",
"string",
"special-characters",
"quotes",
"doctest"
] | Given the following python script:
```
# dedupe.py
import re
def dedupe_whitespace(s,spacechars='\t '):
"""Merge repeated whitespace characters.
Example:
>>> dedupe_whitespace(r"Green\t\tGround") # doctest: +REPORT_NDIFF
'Green\tGround'
"""
for w in spacechars:
s = re.sub(r"("+w+"+)",... | It's the raw heredoc string notation (`r"""`) that did the trick:
```
# filename: dedupe.py
import re,doctest
def dedupe_whitespace(s,spacechars='\t '):
r"""Merge repeated whitespace characters.
Example:
>>> dedupe_whitespace('Black\t\tGround') #doctest: +REPORT_NDIFF
'Black\tGround'
"""
for w... |
Real world examples of partial function | 8,834,962 | 3 | 2012-01-12T12:18:02Z | 8,835,190 | 9 | 2012-01-12T12:36:01Z | [
"python",
"function",
"lambda",
"functional-programming",
"currying"
] | I have been going through Python's [partial](http://docs.python.org/library/functools.html#functools.partial) function. I found it's interesting but it would be helpful if I can understand it with some real-world examples rather than learning it as just another language feature. | One use I often put it to is printing to `stderr` rather than the default `stdout`.
```
from __future__ import print_function
import sys
from functools import partial
print_stderr = partial(print, file=sys.stderr)
print_stderr('Help! Little Timmy is stuck down the well!')
```
You can then use that with any other arg... |
Writing Tiling window manager in Python | 8,835,234 | 4 | 2012-01-12T12:40:32Z | 8,835,400 | 7 | 2012-01-12T12:53:49Z | [
"python",
"window-managers",
"tiling",
"window-management"
] | I have been using Awesome Tiling window manager for over 6 months now, and quite happy with this.
I would like to write my own Tiling window manager as a weekend project and for hackfun. I noticed that Xmonad and dwm are very small. I am aware of [Qtile](http://qtile.org/) a python window manager.
I don't know where ... | You will need some X client library. I suggest having a look at [python-xlib](http://python-xlib.sourceforge.net/), a pure Python implementation of the client side of the X protocol. It includes [plwm](http://plwm.sourceforge.net/), an example implementation of a minimal window manager written in Python. |
How do I turn a tuple into a tuple of tuples? | 8,836,681 | 2 | 2012-01-12T14:27:24Z | 8,836,698 | 16 | 2012-01-12T14:28:33Z | [
"python",
"tuples"
] | How do I convert this:
```
(1, 315.0, 2, 30.399999618530273, 3, 1.1033999919891357, 4, 8.0)
```
into this:
```
((1, 315.0), (2, 30.399999618530273), (3, 1.1033999919891357), (4, 8.0))
```
is there a simple way to do it without looping through? | ```
>>> x = (1, 315.0, 2, 30.399999618530273, 3, 1.1033999919891357, 4, 8.0)
>>> tuple(zip(x[::2], x[1::2]))
((1, 315.0), (2, 30.399999618530273), (3, 1.1033999919891357), (4, 8.0))
``` |
How do I turn a tuple into a tuple of tuples? | 8,836,681 | 2 | 2012-01-12T14:27:24Z | 8,836,704 | 10 | 2012-01-12T14:28:50Z | [
"python",
"tuples"
] | How do I convert this:
```
(1, 315.0, 2, 30.399999618530273, 3, 1.1033999919891357, 4, 8.0)
```
into this:
```
((1, 315.0), (2, 30.399999618530273), (3, 1.1033999919891357), (4, 8.0))
```
is there a simple way to do it without looping through? | ```
t = (1, 315.0, 2, 30.399999618530273, 3, 1.1033999919891357, 4, 8.0)
print tuple(zip(*[iter(t)] * 2))
```
**Edit:** To make this a bit more readable, it should probably encapsulated in a function like the `grouper()` function from the `itertools` [recipes](http://docs.python.org/library/itertools.html#recipes):
`... |
Add new method to a Python Swig Template class | 8,837,135 | 5 | 2012-01-12T14:58:40Z | 8,843,942 | 8 | 2012-01-12T23:36:29Z | [
"python",
"templates",
"swig"
] | I need to add a new method to my swig template class, for example:
I am declaring a template class in myswig.i as follows:
```
%template(DoubleVector) vector<double>;
```
this will generate a class named "DoubleVector" in the generated .py file with some generated methods. lets suppose they are func1(), func2() and ... | Given an interface file like:
```
%module test
%{
#include <vector>
%}
%include "std_vector.i"
%template(DoubleVector) std::vector<double>;
```
The easiest way to add more functionality to `DoubleVector` is to write it in C++, in the SWIG interface file using `%extend`:
```
%extend std::vector<double> {
void bar... |
Number Trouble with Regex in Python | 8,837,299 | 2 | 2012-01-12T15:09:45Z | 8,837,356 | 8 | 2012-01-12T15:13:00Z | [
"python",
"regex"
] | I'm trying to filter a date retrieved from a .csv file, but no combination I try seems to work. The date comes in as "2011-10-01 19:25:01" or "year-month-date hour:min:sec".
I want just the year, month and date but I get can't seem to get ride of the time from the string:
```
date = bug[2] # Column in which the date ... | If your source is a string, you'd probably better use [strptime](http://docs.python.org/library/time.html#time.strftime)
```
import datetime
string = "2011-10-01 19:25:01"
dt = datetime.datetime.strptime(string, "%Y-%m-%d %H:%M:%S")
```
After that, use
```
dt.year
dt.month
dt.day
```
to access the data you want. |
Different levels of logging in python | 8,837,615 | 5 | 2012-01-12T15:29:28Z | 8,839,101 | 9 | 2012-01-12T17:04:07Z | [
"python",
"logging"
] | I want to do something which I thought is simple.
Actually with the python logging module, I am interested logging
everything on the command line at the level given from the command
line arguments, and log to file to a fixed DEBUG level.
Creating two different loggers with different levels doesn't work, but
setting t... | This is something I'm using with all of my Python command-line apps. It's a little verbose, but you should be able to get a logger that accepts an optional argument to create a console logger at any level, irrespective of what's being logged to the file:
```
#!/usr/bin/env python
import logging
from argparse import Ar... |
add text in a file with python (without replacing it) | 8,837,982 | 7 | 2012-01-12T15:51:34Z | 8,838,096 | 9 | 2012-01-12T15:59:19Z | [
"python"
] | I have a file with ids and information, like this:
```
1oMZgkoaz3o 2011-12-29T01:23:00.000Z 9 503 ApolloIsMyCoPilot
nUW1TomCSQg 2011-12-29T01:23:15.000Z 9 348 grea7stuff
tJuLnRrAcs0 2011-12-29T01:26:20.000Z 9 123 AdelGaming
tyi5g0mnPIs 2011-12-29T01:28:07.000Z 9 703 PreferredGaming
```
and I want to add a flag on som... | You can't write to the file and "insert". Best approach would be to read your file and write out the contents with modifications to a new file and then rename as necessary. |
sqlalchemy add child in one-to-many relationship | 8,839,211 | 8 | 2012-01-12T17:11:44Z | 8,842,527 | 13 | 2012-01-12T21:25:29Z | [
"python",
"orm",
"sqlalchemy"
] | This is the first time I've used ORM, so I'm not sure the best way to handle this. I have a one-to-many relationship where each Parent can have many Children:
```
class Parent(Base):
__tablename__ = 'Parent'
name = Column(String(50))
gid = Column(String(16), primary_key = True)
lastUpdate = Column(Dat... | You are right - you should not create the same parent twice. In terms of adding children, ... well, you really need only to add them and you do not care about the existing ones... So your edited code should do the job just fine. You can make it shorter and more readable though:
```
def addChildren(pname, pid, cloc, cs... |
Py3k: What's more pythonic - one import with commas or many imports? | 8,839,495 | 8 | 2012-01-12T17:29:55Z | 8,839,518 | 14 | 2012-01-12T17:32:21Z | [
"python",
"coding-style",
"python-3.x"
] | What is more pythonic ?
```
import os
import sys
import getopt
...
```
or
```
import os,sys,getopt,...
```
? | From [PEP 8](http://www.python.org/dev/peps/pep-0008/):
Imports should usually be on separate lines, e.g.:
Yes:
```
import os
import sys
```
No:
```
import sys, os
```
it's okay to say this though:
```
from subprocess import Popen, PIPE
``` |
urllib2 HTTP Error 400: Bad Request | 8,840,303 | 12 | 2012-01-12T18:27:39Z | 8,840,451 | 48 | 2012-01-12T18:38:37Z | [
"python",
"urllib2",
"http-error"
] | I have a piece of code like this
```
host = 'http://www.bing.com/search?q=%s&go=&qs=n&sk=&sc=8-13&first=%s' % (query, page)
req = urllib2.Request(host)
req.add_header('User-Agent', User_Agent)
response = urllib2.urlopen(req)
```
and when I input a query greater than one word like "the dog" i get the following error.
... | The reason that "the dog" returns a 400 Error is because you aren't escaping the string for a URL.
If you do this:
```
import urllib, urllib2
quoted_query = urllib.quote(query)
host = 'http://www.bing.com/search?q=%s&go=&qs=n&sk=&sc=8-13&first=%s' % (quoted_query, page)
req = urllib2.Request(host)
req.add_header('Us... |
List of variables used in python program | 8,840,651 | 3 | 2012-01-12T18:54:37Z | 8,840,827 | 8 | 2012-01-12T19:06:56Z | [
"python",
"variables"
] | How can we find all the variables in a python program???
for eg.
**Input**
```
def fact(i):
f=2
for j in range(2,i+1):
f = f * i
i = i - 1
print 'The factorial of ',j,' is ',f
```
**Output**
Variables-- f,j,i | You can get this information from functions:
```
>>> fact.func_code.co_varnames
('i', 'f', 'j')
```
Note these variables names will be generated only if the bytecode for them is built.
```
>>> def f():
a = 1
if 0:
b = 2
>>> f.func_code.co_varnames
('a',)
``` |
How to enable python interactive mode in cygwin? | 8,841,110 | 11 | 2012-01-12T19:29:20Z | 8,841,211 | 20 | 2012-01-12T19:37:55Z | [
"python",
"cygwin",
"command-prompt"
] | I like python in interactive mode when on linux. However on cygwin, the interactive mode doesn't start. I don't see the ">>>" prompt and whatever I enter doesn't result in anything.
**Solved**: I figured out the problem from the answers below. I was using a windows installation of python and it needs `-i` option to st... | Try passing the `-i` flag to Python.
I've experienced this very same thing, [as have others](http://mail.python.org/pipermail/python-win32/2005-August/003637.html). There seems to be an issue with cygwin's ability to operate interactively with native-Windows applications (including Python.exe). If you can, install the... |
pysqlite: Placeholder substitution for column or table names? | 8,841,488 | 12 | 2012-01-12T20:01:17Z | 8,841,775 | 14 | 2012-01-12T20:25:04Z | [
"python",
"sql",
"sqlite3",
"pysqlite"
] | Using pysqlite I am making a procedure to do something with some data. The same kind of operation is done on similar fields in multiple tables and columns, so I thought I could parameterize the sql statement as shown below:
```
def foo():
column = 'c'
table = 't'
row = 1
# preferred approach, gives syntax erro... | You simply can not use placeholders for column or table names. I don't have a authoritative citation for this -- I "know" this only from having tried it and from failing. It makes some sense though:
* If the columns and table could be parametrized, there would be little
purpose to preparing (`execute`-ing) the SQL s... |
Is learning Django without initial knowledge of Python possible? | 8,841,705 | 4 | 2012-01-12T20:19:33Z | 8,841,721 | 9 | 2012-01-12T20:21:15Z | [
"python",
"django"
] | I am coming from procedural PHP with fair amount of knowledge on it. I want to learn Django but I don't have initial knowledge of Python. Can I learn Django at the same time also learning Python? Thank you so much! | No. You'll be writing Python code. In Python. You'll have to learn Python.
A little bit of your project will be CSS, JavaScript and HTML with template tags inserted.
Most of your project will be Python. |
3d plotting with python | 8,841,827 | 10 | 2012-01-12T20:28:47Z | 8,842,032 | 19 | 2012-01-12T20:45:23Z | [
"python",
"numpy",
"plot",
"matplotlib"
] | I'm trying to plot a surface in python. I have a table of N by N values. I have created two vectors X and Y each of N elements. When I try to plot this, I get an error:
```
ValueError: total size of new array must be unchanged
```
I have checked the examples and I see there that for N elements of Z there are N elemen... | First off, don't ever do things like this:
```
mat = []
X = []
Y = []
for x in range(0,bignum):
mat.append([])
X.append(x);
for y in range (0,bignum):
mat[x].append(random.random())
Y.append(y)
```
That's equivalent to:
```
mat = np.random.random((bignum, bignum))
X, Y = np.mgrid[:bignum... |
processing continuous output of a command in python | 8,842,391 | 5 | 2012-01-12T21:14:36Z | 8,842,740 | 7 | 2012-01-12T21:39:17Z | [
"python",
"subprocess"
] | I'm brand new to python, having used perl for years. A typical thing I do all the time is perl is open a command as a pipe and assign its output to a local variable for processing. In other words:
```
"open CMD, "$command|";
$output=<CMD>;
```
a piece of cake. I think I can do something similar in python this way:
`... | Using `select.poll`: You need to [pass objects with a `fileno` method or real file descriptors (integers)](http://docs.python.org/library/select.html#select.select):
```
import os, sys, select, subprocess
args = ['sh', '-c', 'while true; do date; sleep 2; done']
p1 = subprocess.Popen(args, stdout=subprocess.PIPE)
p2 ... |
Selecting the most fluent text from a set of possibilities via grammar checking (Python) | 8,842,817 | 29 | 2012-01-12T21:44:44Z | 8,931,167 | 11 | 2012-01-19T18:15:08Z | [
"python",
"nlp",
"grammar",
"nltk",
"linguistics"
] | # Some background
I am a literature student at New College of Florida, currently working on an overly ambitious creative project. **The project is geared towards the algorithmic generation of poetry**. It's written in Python. My Python knowledge and Natural Language Processing knowledge come only from teaching myself ... | # Grammar Checking with [Link Grammar](http://www.link.cs.cmu.edu/link/)
## Intro to Link Grammar
Link Grammar, developed by Davy Temperley, Daniel Sleator, and John Lafferty, is a syntactic parser of English: "Given a sentence, the system assigns to it a syntactic structure, which consists of a set of labeled links ... |
Python: how to store a numpy multidimensional array in PyTables? | 8,843,062 | 15 | 2012-01-12T22:10:27Z | 8,843,489 | 27 | 2012-01-12T22:45:58Z | [
"python",
"arrays",
"multidimensional-array",
"numpy",
"pytables"
] | How can I put a numpy multidimensional array in a HDF5 file using PyTables?
From what I can tell I can't put an array field in a pytables table.
I also need to store some info about this array and be able to do mathematical computations on it.
Any suggestions? | There may be a simpler way, but this is how you'd go about doing it, as far as I know:
```
import numpy as np
import tables
# Generate some data
x = np.random.random((100,100,100))
# Store "x" in a chunked array...
f = tables.openFile('test.hdf', 'w')
atom = tables.Atom.from_dtype(x.dtype)
ds = f.createCArray(f.root... |
repeating a section of a regular expression? | 8,843,410 | 3 | 2012-01-12T22:38:41Z | 8,843,444 | 19 | 2012-01-12T22:41:45Z | [
"python",
"regex"
] | I'm having to parse a text dump of a spreadsheet. I have a regular expression that correctly parses each line of the data, but it's rather long. It's basically just matching a certain pattern 12 or 13 times.
The pattern I want to repeat is
```
\s+(\w*\.*\w*);
```
This is the regular expression (shortened)
```
^\s+(... | `(\s+(\w*\.*\w*);){12}`
The `{n}` is a "repeat n times"
if you want "12 - 13" times,
`(\s+(\w*\.*\w*);){12,13}`
if you want "12+" times,
`(\s+(\w*\.*\w*);){12,}` |
Django unique_together not preventing duplicates | 8,844,283 | 10 | 2012-01-13T00:16:55Z | 8,848,222 | 7 | 2012-01-13T09:16:17Z | [
"python",
"django"
] | I am clearly not understanding how to do this correctly, can someone set me straight. Here is the model:
```
class Team(models.Model):
teamID=models.CharField(max_length=255) #this will be generated on the iPad
name=models.CharField(max_length=255)
slug=models.SlugField(max_length=50)
teamNumber=models.Ch... | Tried the proper nested-tuple syntax `((foo,bar),)` instead of just `(foo, bar)`?
<https://docs.djangoproject.com/en/dev/ref/models/options/#unique-together> |
Django unique_together not preventing duplicates | 8,844,283 | 10 | 2012-01-13T00:16:55Z | 16,159,180 | 15 | 2013-04-23T01:00:54Z | [
"python",
"django"
] | I am clearly not understanding how to do this correctly, can someone set me straight. Here is the model:
```
class Team(models.Model):
teamID=models.CharField(max_length=255) #this will be generated on the iPad
name=models.CharField(max_length=255)
slug=models.SlugField(max_length=50)
teamNumber=models.Ch... | As aganders3 mentions the constraint is enforced at the database level; I assume though that you are using a database like SQLite that doesn't support this kind of constraint.
The reason that it all works as expected through the admin is that it is doing the uniqueness check itself (it doesn't rely strictly on the dat... |
get file list of files contained in a zip file | 8,844,781 | 15 | 2012-01-13T01:26:27Z | 8,844,823 | 10 | 2012-01-13T01:32:27Z | [
"python"
] | I have a zip archive: `my_zip.zip`. **Inside it is one txt file, the name of which I do not know.** I was taking a look at Python's `zipfile` module ( <http://docs.python.org/library/zipfile.html> ), but couldn't make too much sense of what I'm trying to do.
How would I do the equivalent of 'double-clicking' the zip f... | ```
import zipfile
zip=zipfile.ZipFile('my_zip.zip')
f=zip.open('my_txt_file.txt')
contents=f.read()
f.close()
```
You can see the documentation [here](http://docs.python.org/library/zipfile.html). In particular, the `namelist()` method will give you the names of the zip file members. |
get file list of files contained in a zip file | 8,844,781 | 15 | 2012-01-13T01:26:27Z | 8,845,080 | 26 | 2012-01-13T02:13:04Z | [
"python"
] | I have a zip archive: `my_zip.zip`. **Inside it is one txt file, the name of which I do not know.** I was taking a look at Python's `zipfile` module ( <http://docs.python.org/library/zipfile.html> ), but couldn't make too much sense of what I'm trying to do.
How would I do the equivalent of 'double-clicking' the zip f... | What you need is `ZipFile.namelist()` that will give you a list of all the contents of the archive, you can then do a `zip.open('filename_you_discover')` to get the contents of that file. |
High performance mass short string search in Python | 8,845,245 | 11 | 2012-01-13T02:41:41Z | 8,845,344 | 11 | 2012-01-13T02:56:58Z | [
"python",
"string",
"search"
] | The Problem: A large static list of strings is provided as `A`, A long string is provided as `B`, strings in `A` are all very short (a keywords list), I want to check if every string in `A` is a sub-string of `B` and get them.
Now I use a simple loop like:
```
result = []
for word in A:
if word in B:
resu... | Your problem is large enough that you probably need to hit it with the algorithm bat.
Take a look into the [Aho-Corasick](http://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_string_matching_algorithm) Algorithm. Your problem statement is a paraphrase of the problem that this algorithm tackles.
Also, look into the work ... |
Error importing a .pyd file (as a python module) from a .pyo file | 8,846,480 | 5 | 2012-01-13T05:47:51Z | 16,937,483 | 7 | 2013-06-05T10:25:53Z | [
"python",
"windows",
"module",
"python-2.5"
] | I am running pygame (for Python) on Windows. I have some .pyo files and some .pyd files. I have another script for somewhere else that is trying to import one of the .pyd files as a module but I keep getting the error that no such module exists.
Do .pyo files have issues importing .pyd files as modules? What can I do ... | It's typically because of one or more of the following:
* **The .pyd is not in your current path** (you said it was in the same folder so that should not be the problem)
* **A DLL the .pyd depends on is not in your current path.** Locate the missing DLL's using depends.exe and either copy these dll's to the same folde... |
Python in Desktop Application Development | 8,848,285 | 16 | 2012-01-13T09:21:45Z | 8,848,401 | 15 | 2012-01-13T09:33:25Z | [
"java",
"python",
"desktop-application"
] | My company is revamping the IT infrastructure and systems, so we are at the middle of finalizing the technology for developing the new system.
We have come to two candidates; Java & Python.
The main criteria of the choice is the language must be complete; in a sense that it must be able to use for web & desktop appli... | For Python GUI, there are 3 main options:
* [wxPython](http://www.wxpython.org/)
* [PyQt](http://www.riverbankcomputing.co.uk/software/pyqt/intro)
* [PySide](http://www.pyside.org/)
(PySide is a derivation of PyQt).
For building the interface, you can use [wxGlade](http://wxglade.sourceforge.net/) for wx, and the pa... |
How to get char from string by index? | 8,848,294 | 25 | 2012-01-13T09:22:59Z | 8,848,336 | 46 | 2012-01-13T09:26:37Z | [
"python",
"string"
] | Lets say I have a string that consists of x unknown chars. How could I get char nr. 13 or char nr. x-14? | First make sure the required number is **a valid index** for the string from beginning or end , then you can simply use array subscript notation.
use `len(s)` to get string length
```
>>> s = "hello"
>>> s[3]
'l'
>>> s[5]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: string index out of... |
Python digest/hash for string similarity | 8,848,991 | 6 | 2012-01-13T10:22:07Z | 8,849,322 | 8 | 2012-01-13T10:45:52Z | [
"python",
"algorithm",
"similarity"
] | I'm looking for an algorithm which can generate a short (fx 16 chars (not important) hashcode/digest from a longer string.
The main requirement is that strings which is almost identical should result in the same digest.
Fx 2 almost identical mail:
Hi Martin. Here are some ... spam for you. Regards XYZ.
=> AAAA AAAA ... | It looks like you want [locality-sensitive hashing](http://en.wikipedia.org/wiki/Locality_Sensitive_Hashing). Consider using [minhash](http://en.wikipedia.org/wiki/MinHash) or shingling. There's a great explanation of both in Rajaraman & Ullman's book, [*Mining Massive Datasets*](http://infolab.stanford.edu/~ullman/mmd... |
How do I find Wally with Python? | 8,849,869 | 68 | 2012-01-13T11:28:14Z | 13,271,478 | 49 | 2012-11-07T14:11:45Z | [
"python",
"image-processing",
"machine-learning",
"computer-vision"
] | Shamelessly jumping on the bandwagon :-)
Inspired by [How do I find Waldo with Mathematica](http://stackoverflow.com/questions/8479058/how-do-i-find-waldo-with-mathematica) and the followup [How to find Waldo with R](http://stackoverflow.com/questions/8563604/how-to-find-waldo-with-r), as a new python user I'd love to... | Here's an implementation with [mahotas](http://luispedro.org/software/mahotas)
```
from pylab import imshow
import numpy as np
import mahotas
wally = mahotas.imread('DepartmentStore.jpg')
wfloat = wally.astype(float)
r,g,b = wfloat.transpose((2,0,1))
```
Split into red, green, and blue channels. It's better to use f... |
How can i make tabs in pygtk closable? | 8,850,043 | 4 | 2012-01-13T11:43:26Z | 8,850,091 | 10 | 2012-01-13T11:47:24Z | [
"python",
"tabs",
"gtk",
"pygtk"
] | i am using python with gtk, trying to make a simple text editor with tabs, i am still new, so i wonder how can i make the tabs closable and reordable ? it is much easier in qt, but i loved gtk more. this is my code:
```
import gtk
from tab import *
class Dash(gtk.Notebook):
def __init__(self):
super(gtk.... | Instead of using a `gtk.Label` when appending a new page to the `gtk.Notebook`, you need to create a `gtk.HBox` that contains both a `gtk.Label` and a `gtk.Button`. More or less, something like this:
```
class Dash(gtk.Notebook):
...
def defaultTab(self):
self.append_page(tab.child,tab.header)
...
class Ta... |
Matplotlib overlapping annotations | 8,850,142 | 31 | 2012-01-13T11:51:59Z | 8,851,826 | 7 | 2012-01-13T14:09:46Z | [
"python",
"matplotlib"
] | I want to annotate the bars in a graph with some text but if the bars are close together and have comparable height, the annotations are above ea. other and thus hard to read (the coordinates for the annotations were taken from the bar position and height).
Is there a way to shift one of them if there is a collision?
... | One option is to rotate the text/annotation, which is set by the `rotation` keyword/property. In the following example, I rotate the text 90 degrees to guarantee that it wont collide with the neighboring text. I also set the `va` (short for `verticalalignment`) keyword, so that the text is presented above the bar (abov... |
Matplotlib overlapping annotations | 8,850,142 | 31 | 2012-01-13T11:51:59Z | 10,739,207 | 38 | 2012-05-24T14:12:15Z | [
"python",
"matplotlib"
] | I want to annotate the bars in a graph with some text but if the bars are close together and have comparable height, the annotations are above ea. other and thus hard to read (the coordinates for the annotations were taken from the bar position and height).
Is there a way to shift one of them if there is a collision?
... | I've written a quick solution, which checks each annotation position against default bounding boxes for all the other annotations. If there is a collision it changes its position to the next available collision free place. It also puts in nice arrows.
For a fairly extreme example, it will produce this (none of the num... |
Django. Edit model form in popup in admin | 8,850,273 | 2 | 2012-01-13T12:02:21Z | 9,381,961 | 7 | 2012-02-21T17:14:31Z | [
"python",
"django",
"django-admin"
] | Is there any ready apps for django admin, that allows to edit model in popup?
I want next functionallity:
* View edit form for model in popup.
* On model save - update row in list of models.
Motivation: reduce page reloads.
Also, if there any solutions oriented on massive manual data updates for django? I've taken ... | If you want to open a popup, simply create a link to your 'add' view with the following attribute on that link `onclick='return showAddAnotherPopup(this);'` |
Django - FileField check if None | 8,850,415 | 25 | 2012-01-13T12:14:57Z | 8,850,547 | 38 | 2012-01-13T12:24:52Z | [
"python",
"django",
"django-models"
] | I have a model with an optional file field
```
class MyModel(models.Model):
name = models.CharField(max_length=50)
sound = models.FileField(upload_to='audio/', blank=True)
```
---
Let's put a value
```
>>> test = MyModel(name='machin')
>>> test.save()
```
---
Why do I get that ?
```
>>> test.sound
<FieldFile... | ```
if test.sound.name: print "I have a sound file"
else: print "no sound"
```
Also, `FieldFile`'s boolean value will be False when there's no file: `bool(test.sound) == False` when `test.sound.name` is falsy. |
How to get an ImageField URL within a template? | 8,850,535 | 10 | 2012-01-13T12:24:07Z | 8,850,622 | 25 | 2012-01-13T12:30:30Z | [
"python",
"django"
] | I've got the following model in my Django app:
```
class Image(models.Model):
image = models.ImageField(
upload_to='images/',
height_field='height',
width_field='width'
)
credit = models.CharField(max_length=50, blank=True)
caption = models.TextField(blank=True)
article = ... | You need `{{ image.image.url }}` & `{{ image.image.path }}`, while `{{ image }}` - just an Image object |
What is the effect of "list=list" in Python modules? | 8,850,921 | 43 | 2012-01-13T12:57:26Z | 8,850,976 | 30 | 2012-01-13T13:00:15Z | [
"python"
] | I've seen following code in the python standard library `/usr/lib/python2.7/multiprocessing/dummy/__init__.py`:
```
list = list
dict = dict
```
What does this idiom mean? My best guess is: "let's check if `dict` and `list` exist".
Is it just legacy code from the ancient times without `list` and `dict` in the `__built... | Exports. You then can do:
```
from multiprocessing.dummy import list
```
... which happens to be the regular `list`.
Without that line, there would be no `list` in the package `multiprocessing.dummy`.
This is sensible to have a uniform API across packages. Say all packages are supposed to offer a `list` class. Pack... |
list of wx.ICON_ options in wxpython | 8,851,001 | 3 | 2012-01-13T13:02:16Z | 8,851,049 | 7 | 2012-01-13T13:06:07Z | [
"python",
"icons",
"wxpython"
] | I am having difficulty finding a list of all of the inbuilt icons in wxpython.
So far I have found
```
wx.ICON_INFORMATION
wx.ICON_EXCLAMATION
```
If you knew of such a list, it would be much appreciated. Alternatively please leave any that have not been included.
Thank you | How beautiful is python introspection:
```
>>> import wx
>>> mod = dir(wx)
>>> [item for item in mod if item.startswith('ICON_')]
['ICON_ASTERISK', 'ICON_ERROR', 'ICON_EXCLAMATION', 'ICON_HAND',
'ICON_INFORMATION', 'ICON_MASK', 'ICON_QUESTION', 'ICON_STOP', 'ICON_WARNING']
>>>
``` |
Assert/VerifyElementPresent with Python and WebDriver? | 8,851,682 | 12 | 2012-01-13T13:58:57Z | 8,851,880 | 11 | 2012-01-13T14:14:21Z | [
"python",
"unit-testing",
"selenium",
"selenium-webdriver",
"webdriver"
] | I may just be confused by the change from Selenium to WebDriver and their respective documentation. In a section about test design in the documentation there is talk of using [Assert vs Verify](http://seleniumhq.org/docs/06_test_design_considerations.html#validating-results) such as AssertElementPresent. However in goi... | webdriver is a library for driving browsers. what you want to use are the \*find\_element\* methods to locate elements and then assert conditions against them.
for example, this code does an assertion on content of an element:
```
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('http://www.e... |
(Python) Can some explain what this function is doing (use of object attributes) | 8,851,780 | 3 | 2012-01-13T14:06:06Z | 8,851,842 | 8 | 2012-01-13T14:11:12Z | [
"python"
] | I am carrying out code maintenance on an old Python script. I have come accross a piece of the code, which has me flumoxed. Earlier on in the code (not shown in the snippet below), class are defined, with minimal attributes. Further on in the code, assignments are made to non existent fields in the class. For example
... | There are no "non-existent" attributes of an object. There are no declarations.
Attributes are merely assigned to objects in `__init__` or in any code that references the object. That's just standard Python.
```
class Whatever( object ):
pass
w = Whatever()
w.new_attribute= "some value"
```
Perfectly normal. Th... |
Import numpy with python 2.6 | 8,852,165 | 2 | 2012-01-13T14:37:57Z | 8,852,492 | 9 | 2012-01-13T15:00:34Z | [
"python",
"import",
"numpy"
] | This may be a simple question, but I am stuck: I want to use numpy with Python 2.6. I appended the path where the numpy folder is located:
C:\Python26\lib\site-packages\
and also the path for the numpy folder itself
C:\Python26\lib\site-packages\numpy
However, this error message appears
```
x=np.array([[7,8,5][3,5... | You shouldn't have to add those things to the path. Python knows where to look for installed modules as long as you have C:\Python26 in the path.
Sven Marnach was asking if you did it like this:
```
import numpy as np
x=np.array([[7,8,5],[3,5,7]],np.int32)
```
Edit: I just noticed you left out a comma in your array ... |
webapp2 - How to reverse URL in templates? | 8,852,737 | 5 | 2012-01-13T15:15:45Z | 8,893,709 | 8 | 2012-01-17T11:17:13Z | [
"python",
"google-app-engine",
"web-applications",
"webapp2"
] | I'm starting with webapp2. My english is not very good, so i'll use an
example to explain my problem:
Suppose i'm building an application that will handle cars information.
I've these handlers:
* ViewHandler: will display a view for a single car, with all of its
information (engine, year, brand, model, etc..)
* Lis... | webapp2.uri\_for() is your best bet, but you must use it in combination with named routing. You can read more about webapp2 routing in combination with uri\_for here:
<http://webapp-improved.appspot.com/guide/routing.html>
Here's an example from the above article of how it might look:
```
app = webapp2.WSGIApplicatio... |
Entering Directories as Strings in python | 8,852,939 | 5 | 2012-01-13T15:29:09Z | 8,852,961 | 7 | 2012-01-13T15:30:33Z | [
"python",
"string"
] | I have a list of directories hard coded into my program as such:
```
import os
my_dirs = ["C:\a\foo"
,"C:\b\foo"
,"C:\c\foo"
,"C:\t\foo"
]
```
I later want to perform some operation like `os.path.isfile(my_dirs[3])`. But the string my\_dirs[3] is becoming messed up because `"\t... | Use forward slashes or raw strings: `r'C:\a\foo'` or `'C:/a/foo'`
Actually, using forward slashes is the better solutions since as @Wesley mentioned, you cannot have a raw string ending in a single backslash. While functions from `os.path` will use backslashes on windows, mixing them doesn't cause any problems - so i'... |
Entering Directories as Strings in python | 8,852,939 | 5 | 2012-01-13T15:29:09Z | 8,853,157 | 7 | 2012-01-13T15:44:16Z | [
"python",
"string"
] | I have a list of directories hard coded into my program as such:
```
import os
my_dirs = ["C:\a\foo"
,"C:\b\foo"
,"C:\c\foo"
,"C:\t\foo"
]
```
I later want to perform some operation like `os.path.isfile(my_dirs[3])`. But the string my\_dirs[3] is becoming messed up because `"\t... | I would advise to use **forward slashes** or **double backslashes**. A raw string, as sugested by ThiefMaster, can be tricky; it can, for example, not end with a backslash; so r'c:\foo\' is **not** a valid raw string.. See [python docs](http://docs.python.org/reference/lexical_analysis.html#encodings):
> r"\" is not a... |
PEP 8, why no spaces around '=' in keyword argument or a default parameter value? | 8,853,063 | 42 | 2012-01-13T15:37:34Z | 8,853,111 | 28 | 2012-01-13T15:40:43Z | [
"python",
"coding-style",
"pep8"
] | Why does [PEP 8 recommend not having spaces around `=` in a keyword argument or a default parameter value](http://www.python.org/dev/peps/pep-0008/#other-recommendations)?
Is this inconsistent with recommending spaces around every other occurrence of `=` in Python code?
How is:
```
func(1, 2, very_long_variable_name... | I guess that it is because a keyword parameter is essentially different than a variable assignment.
For example, there is plenty of code like this:
```
kw1 = some calculation here
kw2 = some calculation here
kw3 = some calculation here
some_func(1,
2,
kw1=kw1,
kw2=kw2,
kw3=kw3)
```
As you see, it mak... |
Inheritance of attributes in python using _init_ | 8,853,966 | 13 | 2012-01-13T16:37:03Z | 8,854,054 | 17 | 2012-01-13T16:42:13Z | [
"python",
"inheritance",
"attributes",
"polymorphism"
] | My apologies for writing such a junior question. I'm Java person who just started learning Python so a lot of my questions deal with concepts (since I keep thinking in terms of Java rather than Python). Thanks.
```
class Person():
def __init__(self, name, phone):
self.name = name
self.phone = phone... | When writing the `__init__` function for a class in python, you should always call the `__init__` function of its superclass. We can use this to pass the relevant attributes directly to the superclass, so your code would look like this:
```
class Person(object):
def __init__(self, name, phone):
self.name =... |
How to determine if a path is a subdirectory of another? | 8,854,421 | 5 | 2012-01-13T17:08:29Z | 18,115,718 | 8 | 2013-08-07T23:51:21Z | [
"python",
"file"
] | I am given a list of paths that I need to check files within. Of course, if I am given a root, and a subdirectory, there is no need to process the sub-directory. For example
```
c:\test // process this
c:\test\pics // do not process this
c:\test2 // process this
```
How can I tell (cross platform) that a path is not... | ```
def is_subdir(path, directory):
path = os.path.realpath(path)
directory = os.path.realpath(directory)
relative = os.path.relpath(path, directory)
if relative.startswith(os.pardir):
return False
else:
return True
``` |
Convert ndarray from float64 to integer | 8,855,574 | 16 | 2012-01-13T18:46:48Z | 8,855,645 | 28 | 2012-01-13T18:52:11Z | [
"python",
"numpy",
"scipy"
] | I've got a `ndarray` in python with a `dtype` of `float64`. I'd like to convert the array to be an array of integers. How should I do this?
`int()` won't work, as it says it can't convert it to a scalar. Changing the `dtype` field itself obviously doesn't work, as the actual bytes haven't changed. I can't seem to find... | Use `.astype`.
```
>>> a = numpy.array([1, 2, 3, 4], dtype=numpy.float64)
>>> a
array([ 1., 2., 3., 4.])
>>> a.astype(numpy.int64)
array([1, 2, 3, 4])
```
See the [documentation](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.astype.html#numpy.ndarray.astype) for more options. |
Find the name of a Python variable that was passed to a function | 8,855,974 | 7 | 2012-01-13T19:17:32Z | 8,856,387 | 7 | 2012-01-13T19:50:17Z | [
"python",
"variables",
"reflection"
] | In C/C++, I have often found it useful while debugging to define a macro, say `ECHO(x)`, that prints out the variable name and its value (i.e. `ECHO(variable)` might print `variable 7`). You can get the variable name in a macro using the 'stringification' operator `#` as described [here](http://gcc.gnu.org/onlinedocs/c... | Not really solution, but may be handy (anyway you have `echo('foo')` in question):
```
def echo(**kwargs):
for name, value in kwargs.items():
print name, value
foo = 7
echo(foo=foo)
```
**UPDATE:** Solution for `echo(foo)` with `inspect`
```
import inspect
import re
def echo(arg):
frame = inspect.c... |
Using tempfile to create a sub-directory for all of my tempfiles | 8,856,053 | 4 | 2012-01-13T19:23:25Z | 8,856,265 | 10 | 2012-01-13T19:40:33Z | [
"python",
"temporary-files"
] | I've been using `tempfile.mkdtemp` with a prefix to create my temp files. This results in a lot of different directory in my tmp folder with '`tmp/myprefix{uniq-string}/`'.
I would like to change this and have a subdirectory so that my the temp folders I create are all under one main directory so that the prefix is ac... | To use the dir argument you have to ensure the dir folder exists. Something like this should work:
```
import os
import tempfile
#define the location of 'mytemp' parent folder relative to the system temp
sysTemp = tempfile.gettempdir()
myTemp = os.path.join(sysTemp,'mytemp')
#You must make sure myTemp exists
if not ... |
How to send email to multiple recipients using python smtplib? | 8,856,117 | 76 | 2012-01-13T19:28:49Z | 8,861,795 | 21 | 2012-01-14T11:06:27Z | [
"python",
"email",
"smtp",
"message",
"smtplib"
] | After much searching I couldn't find out how to use smtplib.sendmail to send to multiple recipients. The problem was every time the mail would be sent the mail headers would appear to contain multiple addresses, but in fact only the first recipient would receive the email.
The problem seems to be that the [`email.Mess... | You need to understand the difference between the *visible* address of an email, and the *delivery*.
`msg["To"]` is essentially what is printed on the letter. It doesn't actually have any effect. Except that your email client, just like the regular post officer, will assume that this is who you want to send the email ... |
How to send email to multiple recipients using python smtplib? | 8,856,117 | 76 | 2012-01-13T19:28:49Z | 12,422,921 | 131 | 2012-09-14T10:44:00Z | [
"python",
"email",
"smtp",
"message",
"smtplib"
] | After much searching I couldn't find out how to use smtplib.sendmail to send to multiple recipients. The problem was every time the mail would be sent the mail headers would appear to contain multiple addresses, but in fact only the first recipient would receive the email.
The problem seems to be that the [`email.Mess... | This **really works**, I spent a lot of time trying multiple variants.
```
import smtplib
from email.mime.text import MIMEText
s = smtplib.SMTP('smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = 'me@example.com'
recipients = ['john.doe@example.com', 'john.smith@example.co.uk']
msg['Subje... |
How to send email to multiple recipients using python smtplib? | 8,856,117 | 76 | 2012-01-13T19:28:49Z | 28,203,862 | 51 | 2015-01-28T22:43:53Z | [
"python",
"email",
"smtp",
"message",
"smtplib"
] | After much searching I couldn't find out how to use smtplib.sendmail to send to multiple recipients. The problem was every time the mail would be sent the mail headers would appear to contain multiple addresses, but in fact only the first recipient would receive the email.
The problem seems to be that the [`email.Mess... | The `msg['To']` needs to be a string:
```
msg['To'] = "a@b.com, b@b.com, c@b.com"
```
While the `recipients` in `sendmail(sender, recipients, message)` needs to be a list:
```
sendmail("a@a.com", ["a@b.com", "b@b.com", "c@b.com"], "Howdy")
``` |
Access a previously returned value - Python3.2 | 8,856,240 | 2 | 2012-01-13T19:38:29Z | 8,856,310 | 8 | 2012-01-13T19:43:44Z | [
"python",
"while-loop",
"call",
"return-value"
] | I have been trying for a while to be able to access my recently returned value and use it in if statements without having to recall the value.
Basically I have a while loop that calls a function that allows the user to input and then returns the input back into the loop.
```
while selection() != 0: ## Calls the "WHAT... | That's why you would store the result in a variable, so you can reference it in the future. Something like:
```
sel = selection()
while sel != 0:
input()
if sel==1:
...
sel = selection()
``` |
ValueError: unsupported format character while forming strings | 8,856,523 | 14 | 2012-01-13T20:00:39Z | 8,856,556 | 8 | 2012-01-13T20:03:53Z | [
"python"
] | This works:
```
print "Hello World%s" %"!"
```
But this doesn't
```
print "Hello%20World%s" %"!"
```
the error is `ValueError: unsupported format character 'W' (0x57) at index 8`
I am using Python 2.7.
Why would I do this? Well `%20` is used in place of spaces in urls, and if use it, I can't form strings with the... | You could escape the % with another % so `%%20`
This is a similar relevant question [Python string formatting when string contains "%s" without escaping](http://stackoverflow.com/questions/2847272/python-string-formatting-when-string-contains-s-without-escaping) |
ValueError: unsupported format character while forming strings | 8,856,523 | 14 | 2012-01-13T20:00:39Z | 8,856,631 | 29 | 2012-01-13T20:09:49Z | [
"python"
] | This works:
```
print "Hello World%s" %"!"
```
But this doesn't
```
print "Hello%20World%s" %"!"
```
the error is `ValueError: unsupported format character 'W' (0x57) at index 8`
I am using Python 2.7.
Why would I do this? Well `%20` is used in place of spaces in urls, and if use it, I can't form strings with the... | You could escape the % in %20 like so:
```
print "Hello%%20World%s" %"!"
```
or you could try using the string formatting routines instead, like:
```
print "Hello%20World{0}".format("!")
```
<http://docs.python.org/library/string.html#formatstrings> |
How to move a file in Python | 8,858,008 | 261 | 2012-01-13T22:17:58Z | 8,858,026 | 357 | 2012-01-13T22:19:58Z | [
"python",
"file"
] | I looked into the Python [`os`](http://docs.python.org/library/os.html) interface, but was unable to locate a method to move a file. How would I do the equivalent of `$ mv ...` in Python?
```
>>> source_files = '/PATH/TO/FOLDER/*'
>>> destination_folder = 'PATH/TO/FOLDER'
>>> # equivalent of $ mv source_files destinat... | [`os.rename()`](http://docs.python.org/library/os.html#os.rename) or [`shutil.move()`](http://docs.python.org/library/shutil.html#shutil.move)
Both employ the same syntax:
```
os.rename("path/to/current/file.foo", "path/to/new/desination/for/file.foo")
shutil.move("path/to/current/file.foo", "path/to/new/destination/... |
How to move a file in Python | 8,858,008 | 261 | 2012-01-13T22:17:58Z | 15,015,882 | 30 | 2013-02-22T02:30:13Z | [
"python",
"file"
] | I looked into the Python [`os`](http://docs.python.org/library/os.html) interface, but was unable to locate a method to move a file. How would I do the equivalent of `$ mv ...` in Python?
```
>>> source_files = '/PATH/TO/FOLDER/*'
>>> destination_folder = 'PATH/TO/FOLDER'
>>> # equivalent of $ mv source_files destinat... | For either the os.rename or shutil.move you will need to import the module.
No \* character is necessary to get all the files moved.
We have a folder at /opt/awesome called source with one file named awesome.txt.
```
in /opt/awesome
â â ls
source
â â ls source
awesome.txt
python
>>> source = '/opt/awesome/s... |
How to move a file in Python | 8,858,008 | 261 | 2012-01-13T22:17:58Z | 16,845,955 | 140 | 2013-05-30T21:12:13Z | [
"python",
"file"
] | I looked into the Python [`os`](http://docs.python.org/library/os.html) interface, but was unable to locate a method to move a file. How would I do the equivalent of `$ mv ...` in Python?
```
>>> source_files = '/PATH/TO/FOLDER/*'
>>> destination_folder = 'PATH/TO/FOLDER'
>>> # equivalent of $ mv source_files destinat... | Although `os.rename()` and `shutil.move()` will both rename files, the command that is closest to the Unix mv command is `shutil.move()`. The difference is that `os.rename()` doesn't work if the source and destination are on different disks, while `shutil.move()` doesn't care what disk the files are on. |
Using Python, how do you untar purely in memory? | 8,858,414 | 18 | 2012-01-13T22:58:07Z | 8,858,582 | 12 | 2012-01-13T23:21:11Z | [
"python",
"tar",
"python-requests",
"stringio"
] | I'm working in an environment where I can't save anything to disk. I need to be able to pull tar files and unzip them without saving to disk. This seems to fail:
I've tried this but it tosses errors:
```
# fetch.py
from cStringIO import StringIO
import requests
url = "http://example.com/data.tar.gz"
response = reques... | I suspect that the error is telling you that the file format of the tarfile is wrong. Try fetching the file with `wget` and untarring it on the command line.
The other question, about how to stop Python writing the file contents to disk requires a closer look at the `tarfile` API. Instead of calling `TarFile.extract()... |
Using Python, how do you untar purely in memory? | 8,858,414 | 18 | 2012-01-13T22:58:07Z | 8,858,735 | 11 | 2012-01-13T23:40:56Z | [
"python",
"tar",
"python-requests",
"stringio"
] | I'm working in an environment where I can't save anything to disk. I need to be able to pull tar files and unzip them without saving to disk. This seems to fail:
I've tried this but it tosses errors:
```
# fetch.py
from cStringIO import StringIO
import requests
url = "http://example.com/data.tar.gz"
response = reques... | Turns out the problem was that the file "**data.tar.gz** was not a tar archive. Just a gzip compressed file. So I solved it with:
```
# fetch.py
from cStringIO import StringIO
import gzip
import requests
# Called a 'tar' file but actually a gzip file. @#$%!!!
url = "http://example.com/data.tar.gz"
response = requests.... |
Need help calculating geographical distance | 8,858,838 | 8 | 2012-01-13T23:53:57Z | 8,859,667 | 8 | 2012-01-14T02:25:06Z | [
"python"
] | I'm setting up a small program to take 2 geographical coordinates from a user and then calculate the distance between them(taking into account the curvature of the earth). So I looked up wikipedia on what the formula is [here](http://en.wikipedia.org/wiki/Great-circle_distance).
I basically set up my python function b... | You've got 4 or 5 or 6 problems:
(1) `end_lat = math.radians(end_long)` should be `end_lat = math.radians(end_lat)`
(2) you are missing some stuff as somebody already mentioned, most probably because
(3) your code is illegible (line far too long, redundant parentheses, 17 pointless instances of "math.")
(4) you did... |
django form dropdown list of numbers | 8,859,504 | 12 | 2012-01-14T01:51:42Z | 8,859,564 | 27 | 2012-01-14T02:03:28Z | [
"python",
"django",
"linux"
] | i am new to django and i want to make a simple form, according to the doc i can make a form using forms module from django
```
from django import forms
class CronForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField(required=False, label='Your e-mail address')
message = forms.C... | You're looking for a `ChoiceField` which renders as a `select` html element by default.
<https://docs.djangoproject.com/en/dev/ref/forms/fields/#choicefield>
```
class CronForm(forms.Form):
days = forms.ChoiceField(choices=[(x, x) for x in range(1, 32)])
``` |
How can I use the mongolab add-on to Heroku from python? | 8,859,532 | 2 | 2012-01-14T01:57:18Z | 8,859,656 | 10 | 2012-01-14T02:21:25Z | [
"python",
"mongodb",
"heroku",
"mongolab"
] | The documentation only talks about how to do it from ruby. | This is Will from MongoLab. We have a generic example of how to connect in Python using the official python driver (pymongo). This example is not for connecting from Heroku per say but it should be similar. The difference is that you will need to pluck your driver config from your Heroku ENV environment to supply to th... |
Why does Python seem to treat instance variables as shared between objects? | 8,860,447 | 6 | 2012-01-14T05:52:16Z | 8,860,527 | 7 | 2012-01-14T06:08:01Z | [
"python",
"oop",
"object"
] | I was working on a simple script today when I noticed a strange quirk in the way Python treats instance variables.
Say we have a simple object:
```
class Spam(object):
eggs = {}
def __init__(self, bacon_type):
self.eggs["bacon"] = bacon_type
def __str__(self):
return "My favorite type of ... | As Ignacio has posted, variables which are assigned to at class scope in Python are class variables. Basically, in Python, a class is just a list of statements under a `class` statement. Once that list of statements finishes executing, Python scoops up any variables that were created during the course of that execution... |
pip freeze > requirements.txt error | 8,860,731 | 21 | 2012-01-14T07:04:03Z | 8,861,176 | 21 | 2012-01-14T08:54:11Z | [
"python",
"django",
"pip"
] | I am getting the following error with that command:
```
$pip freeze > requirements.txt
Warning: cannot find svn location for distribute==0.6.16dev-r0
```
This is my requirements.txt file beforehand:
```
Django==1.3
django-registration==0.7
``` | First, I'd note that is not an error, but rather a *warning* (though it is a serious one).
This appears to be an open issue in pip, judging by this [issue page](https://github.com/pypa/pip/issues/287) on the github repository. The problem arises when pip is installing something a development version that is held on a ... |
pip freeze > requirements.txt error | 8,860,731 | 21 | 2012-01-14T07:04:03Z | 18,080,652 | 18 | 2013-08-06T12:48:42Z | [
"python",
"django",
"pip"
] | I am getting the following error with that command:
```
$pip freeze > requirements.txt
Warning: cannot find svn location for distribute==0.6.16dev-r0
```
This is my requirements.txt file beforehand:
```
Django==1.3
django-registration==0.7
``` | ```
sudo pip install --upgrade distribute
``` |
Running Python script from Cocoa application using GCD | 8,862,085 | 10 | 2012-01-14T12:03:23Z | 8,874,124 | 8 | 2012-01-15T23:00:25Z | [
"python",
"objective-c",
"grand-central-dispatch"
] | I'm trying to run a Python script from a Cocoa app. It's working just fine on the main thread, but I'd like to have it running in the background, on a concurrent GCD queue.
I'm using the following method to setup a manager class that runs the Python script:
```
- (BOOL)setupPythonEnvironment {
if (Py_IsInitialize... | From [this page](http://docs.python.org/c-api/init.html), it looks like there are some some pretty complex threading concerns specific to embedding python. Is there a reason you couldn't just run these scripts in a separate process? For instance, the following `-runBunchOfScripts` method would run the script ten times ... |
Network sniffing with python | 8,862,196 | 3 | 2012-01-14T12:28:05Z | 8,862,286 | 11 | 2012-01-14T12:42:06Z | [
"python",
"networking",
"network-programming",
"sniffing"
] | I'm going to build an sniffing software for the university. I have some ideas but want to hear some more. The idea is to use a passive tap on front on the firewall and so get all data...
I know C is faster but i want to do it with python any good ideas like libraries etc?
Refs:
* <http://www.flyninja.net/?p=13>
* <h... | Use [`pylibcap`](http://pylibpcap.sourceforge.net/). It provides an interface to libpcap which is the de-facto standard for packet sniffing on linux. To parse packets, you might want to use the [`construct`](http://construct.readthedocs.org/en/latest/) library as it already contains a parser for TCP packets.
Here's a ... |
Python Proxy Error With Requests Library | 8,862,492 | 5 | 2012-01-14T13:25:23Z | 8,862,633 | 13 | 2012-01-14T13:52:26Z | [
"python",
"http",
"proxy",
"python-requests",
"proxies"
] | I am trying to access the web via a proxy server in Python. I am using the requests library and I am having an issue with authenticating my proxy as the proxy I am using requires a password.
```
proxyDict = {
'http' : 'username:mypassword@77.75.105.165',
'https' : 'username:mypassword@77.75.105.... | You should remove the embedded username and password from `proxyDict`, and use the `auth` parameter instead.
```
import requests
from requests.auth import HTTPProxyAuth
proxyDict = {
'http' : '77.75.105.165',
'https' : '77.75.105.165'
}
auth = HTTPProxyAuth('username', 'mypassword')
r ... |
Python - Find similar colors, best way | 8,863,810 | 6 | 2012-01-14T17:06:46Z | 8,863,952 | 15 | 2012-01-14T17:28:47Z | [
"python",
"colors",
"find"
] | I've made a function to find a color within a image, and return x, y. Now I need to add a new function, where I can find a color with a given tolerence. Should be easy?
Code to find color in image, and return x, y:
```
def FindColorIn(r,g,b, xmin, xmax, ymin, ymax):
image = ImageGrab.grab()
for x in range(xmi... | Computing distances between RGB colours, in a way that's meaningful to the eye, isn't as easy a just taking the Euclidian distance between the two RGB vectors.
There is an interesting article about this here: <http://www.compuphase.com/cmetric.htm>
The example implementation in C is this:
```
typedef struct {
uns... |
ImportError: No module named PIL | 8,863,917 | 41 | 2012-01-14T17:24:27Z | 8,864,020 | 41 | 2012-01-14T17:36:52Z | [
"python",
"python-imaging-library",
"easy-install"
] | I use this command in the shell to install PIL:
```
easy_install PIL
```
then I run `python` and type this: `import PIL`. But I get this error:
```
Traceback (most recent call last):
File "<console>", line 1, in <module>
ImportError: No module named PIL
```
I've never had such problem, what do you think? | You must do
```
import Image
```
instead of `import PIL` (PIL is in fact not imported this way). Since `import Image` works for you, this means that you have in fact installed PIL.
Having a different name for the library and the Python module is unusual, but this is what was chosen for PIL.
You can get more informa... |
ImportError: No module named PIL | 8,863,917 | 41 | 2012-01-14T17:24:27Z | 15,069,918 | 13 | 2013-02-25T15:01:02Z | [
"python",
"python-imaging-library",
"easy-install"
] | I use this command in the shell to install PIL:
```
easy_install PIL
```
then I run `python` and type this: `import PIL`. But I get this error:
```
Traceback (most recent call last):
File "<console>", line 1, in <module>
ImportError: No module named PIL
```
I've never had such problem, what do you think? | Sometimes I get this type of error running a Unitest in python. The solution is to uninstall and install the same package on your virtual environment.
Using this commands:
```
pip uninstall PIL
```
and
```
pip install PIL
```
If for any reason you get an error, add sudo at the beginning of the command and after h... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.