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 |
|---|---|---|---|---|---|---|---|---|---|
Processing large amount of data in Python | 12,546,702 | 5 | 2012-09-22T18:45:58Z | 12,815,940 | 7 | 2012-10-10T09:18:46Z | [
"python",
"csv",
"amazon-ec2",
"machine-learning",
"scientific-computing"
] | I have been trying to process a good chunk of data (a few GBs) but my personal computer resists to do it in a reasonable time span, so I was wondering what options do I have? I was using python's [csv.reader](http://docs.python.org/library/csv.html) but it was painfully slow even to fetch 200,000 lines. Then I migrated... | I would try to use [`numpy`](http://numpy.scipy.org/) to work with your large datasets localy. Numpy arrays should use less memory compared `csv.reader` and computation times should be much faster when using vectorised numpy functions.
However there may be a memory problem when reading the file.
[`numpy.loadtxt`](http... |
Flask-framework: MVC pattern | 12,547,206 | 3 | 2012-09-22T19:54:15Z | 12,547,285 | 8 | 2012-09-22T20:05:24Z | [
"python",
"design-patterns",
"model-view-controller",
"flask"
] | Flask-framework is MVC. What part of the application should I consider a model, what a view and what a controller? Both in regular application and in RESTful app.
When I say RESTful I mean something like this:
```
main_dir--|
|
app1--|
| |
| __init__.py
| api.py
... | Flask is actually not an MVC framework. It is a minimalistic framework which gives you a lot of freedom in how you structure your application, but MVC pattern is a very good fit for what Flask provides.
Essentially you write your methods and map them to specific route, e.g.:
```
@app.route("/")
def hello():
retur... |
Python 3: EOF when reading a line (Sublime Text 2 is angry) | 12,547,683 | 22 | 2012-09-22T21:02:53Z | 12,549,001 | 8 | 2012-09-23T01:15:41Z | [
"python",
"python-3.x",
"sublimetext2",
"eof"
] | ```
while True:
reply = input('Enter text')
if reply == 'stop': break
print(reply.upper())
```
The result was:
> ```
> Enter text:Traceback (most recent call last):
> File "C:\PythonProjects\5.py", line 2, in <module>
> reply = input('Enter text:')
> EOFError: EOF when reading a line
> [Finished in ... | EOF is a special out-of-band signal which means the end of input. It's not a character (though in the old DOS days, 0x1B acted like EOF), but rather a signal from the OS that the input has ended.
On Windows, you can "input" an EOF by pressing `Ctrl+Z` at the command prompt. This signals the terminal to close the input... |
Python 3: EOF when reading a line (Sublime Text 2 is angry) | 12,547,683 | 22 | 2012-09-22T21:02:53Z | 12,549,696 | 7 | 2012-09-23T04:19:11Z | [
"python",
"python-3.x",
"sublimetext2",
"eof"
] | ```
while True:
reply = input('Enter text')
if reply == 'stop': break
print(reply.upper())
```
The result was:
> ```
> Enter text:Traceback (most recent call last):
> File "C:\PythonProjects\5.py", line 2, in <module>
> reply = input('Enter text:')
> EOFError: EOF when reading a line
> [Finished in ... | `help(input)` shows what keyboard shortcuts produce EOF, namely, Unix: `Ctrl-D`, Windows: `Ctrl-Z+Return`:
> input([prompt]) -> string
>
> Read a string from standard input. The trailing newline is stripped.
> If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise
> EOFError. On Unix, GNU readline is used if... |
Python 3: EOF when reading a line (Sublime Text 2 is angry) | 12,547,683 | 22 | 2012-09-22T21:02:53Z | 15,417,765 | 26 | 2013-03-14T18:49:33Z | [
"python",
"python-3.x",
"sublimetext2",
"eof"
] | ```
while True:
reply = input('Enter text')
if reply == 'stop': break
print(reply.upper())
```
The result was:
> ```
> Enter text:Traceback (most recent call last):
> File "C:\PythonProjects\5.py", line 2, in <module>
> reply = input('Enter text:')
> EOFError: EOF when reading a line
> [Finished in ... | I had the same problem. The problem with the Sublime Text's default console is that it does not support input.
To solve it, you have to install a package called SublimeREPL. SublimeREPL provides a Python interpreter which accepts input.
There is an [article](http://www.bestpythonide.com/python-input-eoferror-in-subli... |
How to check queue length in Python | 12,548,481 | 13 | 2012-09-22T23:22:59Z | 12,548,492 | 21 | 2012-09-22T23:24:48Z | [
"python",
"data-structures",
"python-3.x",
"python-2.7",
"queue"
] | How to check Queue's length in python?
I dont see they provide Queue.lenght in python....
<http://docs.python.org/tutorial/datastructures.html>
```
from collections import deque
queue = deque(["Eric", "John", "Michael"])
```
how to check the length of this queue?
and can we initialize like
```
queue= deque([]) ... | `len(queue)` should give you the result, 3 in this case.
Specifically, `len(object)` function will call `object.__len__` method [[reference link](http://docs.python.org/reference/datamodel.html#object.__len__)]. And the object in this case is `deque`, which implements `__len__` method (you can see it by `dir(deque)`).... |
Circus, running circusd as a daemon? | 12,549,864 | 5 | 2012-09-23T05:00:07Z | 12,554,332 | 9 | 2012-09-23T17:05:41Z | [
"python",
"daemon"
] | So, I just switched from Supervisor to Circus for controlling Python processes. I'm starting the daemon as circusd from the command line. Obviously, this isn't how I should be doing it, but I can't find any docs on the right way. Enlightenment? | There isn't a built in way to start circus with Upstart. I added a file `circus.conf` to `/etc/init`:
```
start on filesystem and net-device-up IFACE=lo
exec /usr/local/bin/circusd /etc/circus.ini
```
My circus conf is at `/etc/circus.ini`
After this I can use `sudo service circus...` to control the process.
Update... |
How can I have a Django signal call a model method? | 12,549,977 | 11 | 2012-09-23T05:29:14Z | 12,550,857 | 22 | 2012-09-23T08:35:17Z | [
"python",
"django",
"django-models",
"django-signals"
] | Maybe it's just late, but I cannot figure out why this isn't working. When I have a post\_save signal call a generic function, it works, but when I have a post\_save signal call a method from a model, nothing happens. Here is code that works:
```
class Revision(models.Model):
# Model junk...
def send_email(sender... | It seems to me that the problem in the second one is you are using an unbounded method `send_mail`. If you really want to call `send_mail` from within a class, maybe [`@classmethod`](http://docs.python.org/library/functions.html#classmethod) or [`@staticmethod`](http://docs.python.org/library/functions.html#staticmetho... |
Retrieving specific POST data in Flask | 12,551,526 | 29 | 2012-09-23T10:25:09Z | 12,551,565 | 34 | 2012-09-23T10:29:50Z | [
"python",
"json",
"flask"
] | I'm trying to get the post data in flask
```
@app.route('/getpersonbyid', methods = ['POST'])
def getPersonById():
personId = (int)(request.form['personId'])
print personId
```
I'm sending the data "personId" via POST in RESTClient. But i'm not getting the result.
Is there an error in the code... | You want to *return* your `personId` value; printing it to the console won't help in a web application:
```
@app.route('/getpersonbyid', methods = ['POST'])
def getPersonById():
personId = int(request.form['personId'])
return str(personId) # back to a string to produce a proper response
```
The parenthesis a... |
Compile Python 2.7.3 from source on a system with Python 2.7 already | 12,553,057 | 5 | 2012-09-23T14:15:32Z | 12,553,268 | 13 | 2012-09-23T14:44:03Z | [
"python",
"python-2.7",
"shared-libraries"
] | I wish to compile Python 2.7.3 from source. The OS is OpenSUSE 11.4 x86\_64, which already provides Python 2.7. I'd like to use 2.7.3 for the latest security patches, but it's a shared system so I can't tinker with the system Python interpreter.
I compile using `./configure --prefix=/opt/python --enable-shared`. No co... | To avoid having to specify the runtime library path using `LD_LIBRARY_PATH` each time Python is started, you can specify it at build time using the `-rpath` linker option:
```
./configure --enable-shared --prefix=/opt/python \
LDFLAGS=-Wl,-rpath=/opt/python/lib
``` |
how to filter duplicate requests based on url in scrapy | 12,553,117 | 28 | 2012-09-23T14:25:06Z | 13,605,919 | 30 | 2012-11-28T13:15:35Z | [
"python",
"web-crawler",
"scrapy"
] | I am writing a crawler for a website using scrapy with CrawlSpider.
Scrapy provides an in-built duplicate-request filter which filters duplicate requests based on urls. Also, I can filter requests using *rules* member of CrawlSpider.
What I want to do is to filter requests like:
```
http:://www.abc.com/p/xyz.html?id... | You can write custom middleware for duplicate removal and add it in settings
```
import os
from scrapy.dupefilter import RFPDupeFilter
from scrapy.utils.request import request_fingerprint
class CustomFilter(RFPDupeFilter):
"""A dupe filter that considers specific ids in the url"""
def __getid(self, url):
... |
how to filter duplicate requests based on url in scrapy | 12,553,117 | 28 | 2012-09-23T14:25:06Z | 18,809,057 | 8 | 2013-09-15T04:56:43Z | [
"python",
"web-crawler",
"scrapy"
] | I am writing a crawler for a website using scrapy with CrawlSpider.
Scrapy provides an in-built duplicate-request filter which filters duplicate requests based on urls. Also, I can filter requests using *rules* member of CrawlSpider.
What I want to do is to filter requests like:
```
http:://www.abc.com/p/xyz.html?id... | Following ytomar's lead, I wrote this filter that filters based purely on URLs that have already been seen by checking an in-memory set. I'm a Python noob so let me know if I screwed something up, but it seems to work all right:
```
from scrapy.dupefilter import RFPDupeFilter
class SeenURLFilter(RFPDupeFilter):
"... |
Create JSON Reponse in Django with Model | 12,553,599 | 2 | 2012-09-23T15:30:14Z | 12,553,956 | 8 | 2012-09-23T16:16:39Z | [
"python",
"django",
"json",
"django-models",
"django-serializer"
] | I am having some issue here. I am trying to return a JSON response made of a message and a model instance:
```
class MachineModel(models.Model):
name = models.CharField(max_length=64, blank=False)
description = models.CharField(max_length=64, blank=False)
manufacturer = models.ForeignKey(Manufa... | You should use [django serializers](https://docs.djangoproject.com/en/dev/topics/serialization/) instead of `simplejson`:
For example, this returns correctly serialized data:
```
from django.core import serializers
# serialize queryset
serialized_queryset = serializers.serialize('json', some_queryset)
# serialize obj... |
How to test that variable is not equal to multiple things? Python | 12,553,609 | 9 | 2012-09-23T15:30:57Z | 12,553,633 | 18 | 2012-09-23T15:34:16Z | [
"python"
] | This is the piece of code I have:
```
choice = ""
while choice != "1" and choice != "2" and choice != "3":
choice = raw_input("pick 1, 2 or 3")
if choice == "1":
print "1 it is!"
elif choice == "2":
print "2 it is!"
elif choice == "3":
print "3 it is!"
else:
pr... | The while bit could be refactored a little to make it a little bit cleaner by checking if the element is within a list of choices like so
```
while choice not in [1, 2, 3]:
```
This is checking is the value of choice is not an element in that list |
None value in python dictionary | 12,553,938 | 4 | 2012-09-23T16:14:57Z | 12,553,950 | 13 | 2012-09-23T16:16:11Z | [
"python",
"if-statement",
"dictionary",
"nonetype"
] | Is it possible to check none value in dict
```
dict = {'a':'None','b':'12345','c':'None'}
```
My code
```
for k,v in d.items():
if d[k] != None:
print "good"
else:
print "Bad
```
Prints three good after executing above code snippet.
```
good
good
good
```
Required:If value is None than not printing go... | Your none values are actually strings in your dictionary.
You can check for 'None'
or use actual python [None](http://docs.python.org/library/constants.html#None) value.
```
d = {'a':None,'b':'12345','c':None}
for k,v in d.items():
if d[k] is None:
print "good"
else:
print "Bad"
```
prints "good" 2 t... |
Adding new column to existing DataFrame in Python pandas | 12,555,323 | 205 | 2012-09-23T19:00:01Z | 12,555,491 | 20 | 2012-09-23T19:22:27Z | [
"python",
"pandas",
"dataframe"
] | I have a DataFrame with named columns and rows indexed with not- continuous numbers like from the code:
```
df1 = DataFrame(np.random.randn(10, 4), columns=['a', 'b', 'c', 'd'])
mask = df1.applymap(lambda x: x <-0.7)
df1 = df1[-mask.any(axis=1)]
sLength = len(df1['a'])
e = Series(np.random.randn(sLength))
```
I would... | Doing this directly via [NumPy](http://en.wikipedia.org/wiki/NumPy) will be the most efficient:
```
df1['e'] = np.random.randn(sLength)
```
---
Note my original (very old) suggestion was to use `map` (which is much slower):
```
df1['e'] = df1['a'].map(lambda x: np.random.random())
``` |
Adding new column to existing DataFrame in Python pandas | 12,555,323 | 205 | 2012-09-23T19:00:01Z | 12,555,510 | 255 | 2012-09-23T19:24:45Z | [
"python",
"pandas",
"dataframe"
] | I have a DataFrame with named columns and rows indexed with not- continuous numbers like from the code:
```
df1 = DataFrame(np.random.randn(10, 4), columns=['a', 'b', 'c', 'd'])
mask = df1.applymap(lambda x: x <-0.7)
df1 = df1[-mask.any(axis=1)]
sLength = len(df1['a'])
e = Series(np.random.randn(sLength))
```
I would... | Use the original df1 indexes to create the series:
```
df1['e'] = Series(np.random.randn(sLength), index=df1.index)
```
---
---
**Edit 2015**
Some reported to get the `SettingWithCopyWarning` with this code.
However, the code still runs perfect with the current pandas version 0.16.1.
```
>>> sLength = len(df... |
Adding new column to existing DataFrame in Python pandas | 12,555,323 | 205 | 2012-09-23T19:00:01Z | 13,843,741 | 62 | 2012-12-12T16:04:31Z | [
"python",
"pandas",
"dataframe"
] | I have a DataFrame with named columns and rows indexed with not- continuous numbers like from the code:
```
df1 = DataFrame(np.random.randn(10, 4), columns=['a', 'b', 'c', 'd'])
mask = df1.applymap(lambda x: x <-0.7)
df1 = df1[-mask.any(axis=1)]
sLength = len(df1['a'])
e = Series(np.random.randn(sLength))
```
I would... | This is the simple way of adding a new column: `df['e'] = e` |
Adding new column to existing DataFrame in Python pandas | 12,555,323 | 205 | 2012-09-23T19:00:01Z | 30,777,185 | 8 | 2015-06-11T09:45:04Z | [
"python",
"pandas",
"dataframe"
] | I have a DataFrame with named columns and rows indexed with not- continuous numbers like from the code:
```
df1 = DataFrame(np.random.randn(10, 4), columns=['a', 'b', 'c', 'd'])
mask = df1.applymap(lambda x: x <-0.7)
df1 = df1[-mask.any(axis=1)]
sLength = len(df1['a'])
e = Series(np.random.randn(sLength))
```
I would... | I got the dreaded `SettingWithCopyWarning`, and it wasn't fixed by using the iloc syntax. My DataFrame was created by read\_sql from an ODBC source. Using a suggestion by lowtech above, the following worked for me:
```
df.insert(len(rec.columns), 'e', pd.Series(np.random.randn(sLength), index=df.index))
```
This wor... |
Adding new column to existing DataFrame in Python pandas | 12,555,323 | 205 | 2012-09-23T19:00:01Z | 35,387,129 | 10 | 2016-02-14T00:49:58Z | [
"python",
"pandas",
"dataframe"
] | I have a DataFrame with named columns and rows indexed with not- continuous numbers like from the code:
```
df1 = DataFrame(np.random.randn(10, 4), columns=['a', 'b', 'c', 'd'])
mask = df1.applymap(lambda x: x <-0.7)
df1 = df1[-mask.any(axis=1)]
sLength = len(df1['a'])
e = Series(np.random.randn(sLength))
```
I would... | > I would like to add a new column, 'e', to the existing data frame and do not change anything in the data frame. (The series always got the same length as a dataframe.)
I assume that the index values in `e` match those in `df1`.
The easiest way to initiate a new column named `e`, and assign it the values from your s... |
Adding new column to existing DataFrame in Python pandas | 12,555,323 | 205 | 2012-09-23T19:00:01Z | 38,510,820 | 9 | 2016-07-21T17:35:37Z | [
"python",
"pandas",
"dataframe"
] | I have a DataFrame with named columns and rows indexed with not- continuous numbers like from the code:
```
df1 = DataFrame(np.random.randn(10, 4), columns=['a', 'b', 'c', 'd'])
mask = df1.applymap(lambda x: x <-0.7)
df1 = df1[-mask.any(axis=1)]
sLength = len(df1['a'])
e = Series(np.random.randn(sLength))
```
I would... | It seems that in recent Pandas versions the way to go is to use [df.assign](http://pandas.pydata.org/pandas-docs/stable/dsintro.html#assigning-new-columns-in-method-chains):
`df1.assign(e=np.random.randn(sLength))`
It doesn't produce SettingWithCopyWarning. |
Squaring all elements in a list | 12,555,443 | 3 | 2012-09-23T19:17:31Z | 12,555,463 | 14 | 2012-09-23T19:19:42Z | [
"python",
"arrays",
"return",
"square"
] | I am told to
Write a function, square(a), that takes an array, a, of numbers and returns an array containing each of the values of a squared.
At first, I had
```
def square(a):
for i in a: print i**2
```
But this does not work since I'm printing, and not returning like I was asked.
So I tried
```
def squar... | **Use a list comprehension (this is the way to go in pure Python):**
```
>>> l = [1, 2, 3, 4]
>>> [i**2 for i in l]
[1, 4, 9, 16]
```
Or [numpy](http://numpy.scipy.org/) (a well-established module):
```
>>> numpy.array([1, 2, 3, 4])**2
array([ 1, 4, 9, 16])
```
In `numpy`, math operations on arrays are, by defaul... |
Squaring all elements in a list | 12,555,443 | 3 | 2012-09-23T19:17:31Z | 12,555,492 | 13 | 2012-09-23T19:22:35Z | [
"python",
"arrays",
"return",
"square"
] | I am told to
Write a function, square(a), that takes an array, a, of numbers and returns an array containing each of the values of a squared.
At first, I had
```
def square(a):
for i in a: print i**2
```
But this does not work since I'm printing, and not returning like I was asked.
So I tried
```
def squar... | You could use a list comprehension:
```
def square(list):
return [i ** 2 for i in list]
```
Or you could `map` it:
```
def square(list):
return map(lambda x: x ** 2, list)
```
Or you could use a generator. It won't return a list, but you can still iterate through it, and since you don't have to allocate an ... |
Flask Babel - 'translations/de/LC_MESSAGES/messages.po' is marked as fuzzy, skipping | 12,555,692 | 8 | 2012-09-23T19:47:15Z | 12,555,922 | 8 | 2012-09-23T20:19:03Z | [
"python",
"flask",
"babel"
] | I cant get a basic translationto work in Flask Babel.
Here are my steps.
1. I have this in a page `{{_("Hello")}}`
2. I run this command.
```
pybabel extract -F babel.cfg -o messages.pot .
```
3. I then run this command for German.
```
pybabel init -i messages.pot -d translations -l de
```
4. Here... | You can force `pybabel compile` to compile messages marked as fuzzy with the `-f` (or `--use-fuzzy`) command line switch:
```
pybabel compile -f -d translations
```
'Fuzzy' messages are marked with a `#, fuzzy` line above the `msgid` line, and are the result of a merge where a message is deemed slightly changed from ... |
Finding the kth-smallest element in union of sorted arrays | 12,555,793 | 4 | 2012-09-23T20:00:02Z | 12,555,955 | 7 | 2012-09-23T20:24:50Z | [
"python",
"algorithm"
] | I was studying the article on finding the kth-smallest element in the union of two sorted arrays at [leetcode](http://www.leetcode.com/2011/01/find-k-th-smallest-element-in-union-of.html). I don't think that the algorithm is correct. There is this line: **We make an observation that when Ai < Bj, then it must be true t... | You're interpreting these statements in isolation, but they build on one another. Here's the text that (I think) you're referring to:
> Maintaining the invariant
> i + j = k â 1,
> If Bj-1 < Ai < Bj, then Ai must be the k-th smallest,
> or else if Ai-1 < Bj < Ai, then Bj must be the k-th smallest.
> If one of the ab... |
Decoder JPEG not available error when following Django photo app tutorial | 12,555,831 | 14 | 2012-09-23T20:06:28Z | 12,561,906 | 41 | 2012-09-24T09:08:30Z | [
"python",
"django",
"jpeg",
"python-imaging-library"
] | I am following a Django tutorial that involves image uploading, and have run into this problem. I tried installing and reinstalling PIL, libjpeg, and libfreetype6 several times, but nothing so far seems to be working. I have spent several hours trying to find a solution, and am very frustrated at this point. Please hel... | There are several cases with PIL which lead to a similar experience.
If you have installed PIL out of a virtualenv using
```
pip install PIL
```
Then you should have installed the **dev** versions of libjpeg, libz before.
Assuming you're on a Ubuntu box, a
```
pip uninstall PIL
apt-get install libjpeg-dev zlib1g-dev... |
Is the defaultdict in Python's collections module really faster than using setdefault? | 12,555,967 | 12 | 2012-09-23T20:25:48Z | 12,556,053 | 14 | 2012-09-23T20:38:09Z | [
"python",
"collections",
"defaultdict",
"setdefault",
"python-collections"
] | I've seen other Python programmers use defaultdict from the collections module for the following use case:
```
from collections import defaultdict
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
def main():
d = defaultdict(list)
for k, v in s:
d[k].append(v)
```
I've typical... | Yes, there is something "wrong":
You have put the creation of the `(default)dict` into the statement instead of the setup. Constructing a new `defaultdict` is more expensive than a normal `dict`, and usually that's not the bottleneck you should be profiling in a program - after all, you build your data structures once... |
Get browser version using selenium webdriver | 12,556,163 | 18 | 2012-09-23T20:54:12Z | 12,559,477 | 14 | 2012-09-24T05:47:25Z | [
"python",
"selenium",
"selenium-webdriver"
] | How would I get the browser version being used?
```
>>> from selenium import webdriver
>>> driver = webdriver.Firefox()
>>> print version <-- how to do this?
Firefox 12.0
``` | The `capabilities` property is a dictionary containing information about the browser itself, so this should work:
```
print driver.capabilities['version']
``` |
Get browser version using selenium webdriver | 12,556,163 | 18 | 2012-09-23T20:54:12Z | 13,611,978 | 35 | 2012-11-28T18:30:02Z | [
"python",
"selenium",
"selenium-webdriver"
] | How would I get the browser version being used?
```
>>> from selenium import webdriver
>>> driver = webdriver.Firefox()
>>> print version <-- how to do this?
Firefox 12.0
``` | This answer led me down the right path but is specific to python and the topic is more broad. So, I'm adding an answer for Java which was a bit more tricky. At this time I am using selenium 2.25.0.
```
//make sure have correct import statements - I had to add these
import org.openqa.selenium.Capabilities;
import org.o... |
fastest way to create JSON to reflect a tree structure in Python / Django using mptt | 12,556,268 | 12 | 2012-09-23T21:10:07Z | 12,556,693 | 13 | 2012-09-23T22:11:09Z | [
"python",
"django",
"json",
"tree",
"profiling"
] | What's the fastest way in Python (Django) to create a JSON based upon a Django queryset. Note that parsing it in the template as proposed [here](http://stackoverflow.com/questions/5072301/how-can-create-a-json-tree-from-django-mptt) is not an option.
The background is that I created a method which loops over all nodes... | I suspect by far the biggest slowdown is that this will do 1 database query per node. The json rendering is trivial in comparison to the hundreds of round-trips to your database.
You should cache the children on each node so that those queries can be done all at once.
django-mptt has a [cache\_tree\_children()](https:... |
Is there an easy way to make unicode work in python? | 12,556,839 | 12 | 2012-09-23T22:34:31Z | 12,557,291 | 17 | 2012-09-23T23:52:19Z | [
"python",
"unicode",
"utf-8",
"python-2.7"
] | I'm trying to deal with unicode in python 2.7.2. I know there is the `.encode('utf-8')` thing but 1/2 the time when I add it, I get errors, and 1/2 the time when I don't add it I get errors.
Is there any way to tell python - what I thought was an up-to-date & modern language to just use unicode for strings and not mak... | There is no way to make unicode "just work" apart from using unicode strings everywhere and immediately decoding any encoded string you receive. The problem is that you MUST ALWAYS keep straight whether you're dealing with encoded or unencoded data, or use tools that keep track of it for you, or you're going to have a ... |
Is there an easy way to make unicode work in python? | 12,556,839 | 12 | 2012-09-23T22:34:31Z | 19,654,555 | 19 | 2013-10-29T09:40:59Z | [
"python",
"unicode",
"utf-8",
"python-2.7"
] | I'm trying to deal with unicode in python 2.7.2. I know there is the `.encode('utf-8')` thing but 1/2 the time when I add it, I get errors, and 1/2 the time when I don't add it I get errors.
Is there any way to tell python - what I thought was an up-to-date & modern language to just use unicode for strings and not mak... | This is a very old question but just wanted to add one partial suggestion. While I sympathise with the OP's pain - having gone through it a lot myself - here's one (partial) answer to make things "easier". Put this at the top of any Python 2.7 script:
`from __future__ import unicode_literals`
This will at least ensur... |
Calling a parent class constructor from a child class in python | 12,557,612 | 12 | 2012-09-24T00:54:52Z | 12,557,639 | 24 | 2012-09-24T01:00:53Z | [
"python",
"inheritance"
] | So if I have a class:
```
class Person(object):
'''A class with several methods that revolve around a person's Name and Age.'''
def __init__(self, name = 'Jane Doe', year = 2012):
'''The default constructor for the Person class.'''
self.n = name
self.y = year
```
And then this subclass:
... | Python recommends using `super()`.
Python 2:
```
super(Instructor, self).__init__(name, year)
```
Python 3:
```
super().__init__(name, year)
``` |
Strip in Python | 12,557,794 | 2 | 2012-09-24T01:27:47Z | 12,557,819 | 7 | 2012-09-24T01:30:38Z | [
"python",
"strip"
] | I have a question regarding `strip()` in Python. I am trying to strip a semi-colon from a string, I know how to do this when the semi-colon is at the end of the string, but how would I do it if it is not the last element, but say the second to last element.
eg:
```
1;2;3;4;\n
```
I would like to strip that last semi... | Strip the other characters as well.
```
>>> '1;2;3;4;\n'.strip('\n;')
'1;2;3;4'
``` |
Creating a new file, filename contains loop variable, python | 12,560,600 | 3 | 2012-09-24T07:30:34Z | 12,560,624 | 10 | 2012-09-24T07:32:33Z | [
"python",
"file"
] | I want to run a function over a loop and I want to store the outputs in different files, such that the filename contains the loop variable. Here is an example
```
for i in xrange(10):
f = open("file_i.dat",'w')
f.write(str(func(i))
f.close()
```
How can I do it in python? | Simply construct the file name with `+` and `str`. If you want, you can also use [old-style](http://docs.python.org/library/stdtypes.html#string-formatting) or [new-style formatting](http://docs.python.org/library/stdtypes.html#str.format) to do so, so the file name can be constructed as:
```
"file_" + str(i) + ".dat"... |
Python Extract data from file | 12,561,063 | 6 | 2012-09-24T08:05:53Z | 12,561,163 | 14 | 2012-09-24T08:13:20Z | [
"python",
"python-2.7"
] | I have a text file just say
```
text1 text2 text text
text text text text
```
I am looking to firstly count the number of strings in the file (all deliminated by space) and then output the first two texts. (text 1 text 2)
Any ideas?
Thanks in advance for the help
Edit: This is what I have so far:
```
>>> f=open('... | To read a file line by line, just loop over the open file object in a `for` loop:
```
for line in open(filename):
# do something with line
```
To split a line by whitespace into a list of separate words, use `str.split()`:
```
words = line.split()
```
To count the number of items in a python list, use `len(your... |
AES decryption padding with PKCS5 Python | 12,562,021 | 8 | 2012-09-24T09:15:20Z | 13,893,208 | 14 | 2012-12-15T14:49:51Z | [
"python",
"aes",
"pycrypto",
"cbc-mode"
] | I have been trying to implement AES CBC decryption in Python. Since the ciphered text is not a multiple of 16bytes, padding was necessary. Without padding, this error surfaced
"TypeError: Odd-length string"
But I could not find a proper reference for implementing PKCS5 in PyCrypto Python.
Are there any commands to im... | You need to decode your hex encoded value before decryption. If you want to work with hex encoded keys, decode it as well..
Here, this should work.
```
from Crypto.Cipher import AES
from Crypto import Random
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-ord(s[-1])]
... |
calculate the difference between two datetime.date() dates in years and months | 12,564,077 | 6 | 2012-09-24T11:25:21Z | 12,564,160 | 9 | 2012-09-24T11:29:38Z | [
"python",
"date",
"timedelta"
] | I want to calculate the difference between two datetime.date() dates in years and months.
For example;
```
d1 = date(2001,5,1)
d2 = date(2012,1,1)
d3 = date(2001,1,1)
d4 = date(2012,5,1)
diff1 = d2 - d1
diff2 = d4 - d3
```
Desired result:
```
diff1 == 10 years & 8 months.
diff2 == 11 years & 4 month... | In python, subtracting two `datetime.date` objects results in a [`datetime.timedelta` object](http://docs.python.org/library/datetime.html#timedelta-objects), which has a `days` attribute.
Turning the number of days difference into years and months is not clearly defined; if you define a year as 365 days and a month a... |
calculate the difference between two datetime.date() dates in years and months | 12,564,077 | 6 | 2012-09-24T11:25:21Z | 12,564,353 | 15 | 2012-09-24T11:40:43Z | [
"python",
"date",
"timedelta"
] | I want to calculate the difference between two datetime.date() dates in years and months.
For example;
```
d1 = date(2001,5,1)
d2 = date(2012,1,1)
d3 = date(2001,1,1)
d4 = date(2012,5,1)
diff1 = d2 - d1
diff2 = d4 - d3
```
Desired result:
```
diff1 == 10 years & 8 months.
diff2 == 11 years & 4 month... | If you are able to install the excellent [dateutil](http://labix.org/python-dateutil) package, you can do this:
```
>>> from dateutil import relativedelta as rdelta
>>> from datetime import date
>>> d1 = date(2001,5,1)
>>> d2 = date(2012,1,1)
>>> rd = rdelta.relativedelta(d2,d1)
>>> "{0.years} years and {0.months} mon... |
Python: How to check if a string is a valid IRI? | 12,565,098 | 13 | 2012-09-24T12:31:42Z | 12,565,315 | 18 | 2012-09-24T12:46:49Z | [
"python",
"url",
"python-2.7",
"urlparse"
] | Is there a standard function to check an [IRI](http://en.wikipedia.org/wiki/Internationalized_Resource_Identifier), to check an URL apparently I can use:
```
parts = urlparse.urlsplit(url)
if not parts.scheme or not parts.netloc:
'''apparently not an url'''
```
I tried the above with an URL containing... | Using `urlparse` is not sufficient to test for a valid IRI.
Use the [`rfc3987` package](http://pypi.python.org/pypi/rfc3987) instead:
```
from rfc3987 import parse
parse('http://fdasdf.fdsfîÄÈîs.fss/ÄîÄî', rule='IRI')
``` |
Several `with`s in `try`s | 12,565,216 | 16 | 2012-09-24T12:39:54Z | 12,565,265 | 9 | 2012-09-24T12:43:30Z | [
"python",
"exception",
"nested",
"try-except"
] | I have several possible files which could hold my data; they can be compressed in different ways, so to open them I need to use `file()`, `gzip.GzipFile()` and other which also return a file object (supporting the `with` interface).
I want to try each of them until one succeeds in opening, so I could do something like... | Yea, you could put all your variants through a list and try them until one of them works, thus un-nesting your code:
```
def process_gzip(fn):
with gzip.GzipFile(fn + '.gz') as f:
return process(f)
def process_xlib(fn):
with xCompressLib.xCompressFile(fn + '.x') as f:
return process(f)
def pr... |
virtualenv with python2 and python3 via Homebrew | 12,566,064 | 5 | 2012-09-24T13:28:19Z | 12,566,853 | 13 | 2012-09-24T14:15:06Z | [
"python",
"osx",
"python-3.x",
"virtualenv",
"homebrew"
] | I have installed python2 and python3 with Homebrew. I would like to use virtualenv but I am not sure if I need to install it for both python2/python3. I am also wondering if I use virtualenvwrapper can I just set the VIRTUALENVWRAPPER\_PYTHON to be either python2 or python3 depending on my needs?
Any help is greatly a... | According to [this SO question](http://stackoverflow.com/questions/1534210/use-different-python-version-with-virtualenv), you could use a single `virtualenv` for both version, just use the `-p path/to/python/version` or `--python=path/to/version` flag to specify which version to use for the creation of the virtual envi... |
python 'x days ago' to datetime | 12,566,152 | 8 | 2012-09-24T13:33:47Z | 12,566,244 | 7 | 2012-09-24T13:38:35Z | [
"python",
"datetime"
] | I have strings that show a date in the following format:
```
x minutes/hours/days/months/years ago
```
I need to parse that to a datetime using python.
It seems dateutil can't do it.
Is there a way to do it? | Sure you can do it. You just need a [`timedelta`](http://docs.python.org/library/datetime.html#timedelta-objects).
```
s = "3 days ago"
parsed_s = [s.split()[:2]]
time_dict = dict((fmt,float(amount)) for amount,fmt in parsed_s)
dt = datetime.timedelta(**time_dict)
past_time = datetime.datetime.now() - dt
```
As an as... |
How to add column in ManyToMany Table (Django) | 12,567,151 | 11 | 2012-09-24T14:33:02Z | 12,567,204 | 28 | 2012-09-24T14:36:09Z | [
"python",
"django",
"many-to-many"
] | From the example of Django Book, I understand if I create models as following:
```
from xxx import B
class A(models.Model):
b = ManyToManyField(B)
```
The Django would create a new table(A\_B) beyond Table A, which has three columns:
* id
* a\_id
* b\_id
But now I want to add a new column in the Table A\_B, th... | It's very easy using django too! You can use `through` to define your own manytomany intermediary tables
[Documentation](https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships) provides an example addressing your issue:
```
Extra fields on many-to-many relationships
class ... |
Check if multple variables greater than zero in python | 12,567,290 | 4 | 2012-09-24T14:39:52Z | 12,567,333 | 13 | 2012-09-24T14:41:55Z | [
"python"
] | ```
A = 200
B = -140
C = 400
D = -260
if A < 0:
v1 = 0
else:
v1 = A
if B < 0:
v2 = 0
else:
v2 = B
if C < 0:
v3 = 0
else:
v3 = C
if D < 0:
v4 = 0
else:
v4 = C
```
What is the shorthand implementation for the above code structure.?
Is there a better / elegant / convenient way to do this? | ```
A = 200
B = -140
C = 400
D = -260
v1, v2, v3, v4 = [x if x > 0 else 0 for x in (A, B, C, D)]
```
If you prefer to use the `max` function to the python ternary operator, it would look like:
```
v1, v2, v3, v4 = [max(x, 0) for x in (A, B, C, D)]
```
However, if you're planning on having all of these variables tre... |
Assigning values from dictionary to object | 12,569,014 | 3 | 2012-09-24T16:20:29Z | 12,569,061 | 8 | 2012-09-24T16:23:33Z | [
"python"
] | I very often need to do something like this:
```
"Some dictionary with values obtained somehow (e.g. submitted form values)"
my_dict = {
'name': 'John',
'surname': 'Doe',
'age': 27,
'hair_color': 'green',
}
"object person is some instance of class representing person"
person.name = my_dict['name']
per... | ```
for attr, val in my_dict.items():
setattr(person, attr, val)
```
If `my_dict` might contain any keys that you don't want to copy to `person`, create a list of keys you do want to copy and do something like this:
```
key_list = ['name', 'surname', 'age', 'hair_color']
for attr in key_list:
setattr(person, ... |
Why is adding attributes to an already instantiated object allowed in Python? | 12,569,018 | 22 | 2012-09-24T16:20:51Z | 12,569,046 | 10 | 2012-09-24T16:22:31Z | [
"python",
"attributes",
"python-3.x",
"declaration"
] | I am studying python, and although I think I get the whole concept and notion of Python, today I stumbled upon a piece of code that I did not fully understand:
Say I have a class that is supposed to define Circles but lacks a body:
```
class Circle():
pass
```
Since I have not defined any attributes, how can I d... | No, python is flexible like that, it does not enforce what attributes you can store on user-defined classes.
There is a trick however, using the [`__slots__` attribute](http://docs.python.org/reference/datamodel.html#slots) on a class definition will prevent you from creating additional attributes not defined in the `... |
Why is adding attributes to an already instantiated object allowed in Python? | 12,569,018 | 22 | 2012-09-24T16:20:51Z | 12,569,122 | 10 | 2012-09-24T16:27:14Z | [
"python",
"attributes",
"python-3.x",
"declaration"
] | I am studying python, and although I think I get the whole concept and notion of Python, today I stumbled upon a piece of code that I did not fully understand:
Say I have a class that is supposed to define Circles but lacks a body:
```
class Circle():
pass
```
Since I have not defined any attributes, how can I d... | Python lets you store attributes of any name on virtually on any instance. It's possible to block this (either by writing the class in C, like the built-in types, or by using `__slots__` which allows only certain names).
The reason it works is that most instances store their attributes in a dictionary. Yes, a regular ... |
Why is adding attributes to an already instantiated object allowed in Python? | 12,569,018 | 22 | 2012-09-24T16:20:51Z | 12,569,143 | 23 | 2012-09-24T16:28:41Z | [
"python",
"attributes",
"python-3.x",
"declaration"
] | I am studying python, and although I think I get the whole concept and notion of Python, today I stumbled upon a piece of code that I did not fully understand:
Say I have a class that is supposed to define Circles but lacks a body:
```
class Circle():
pass
```
Since I have not defined any attributes, how can I d... | A leading principle is that *there is no such thing as a declaration*. That is, you never declare "this class has a method foo" or "instances of this class have an attribute bar", let alone making a statement about the types of objects to be stored there. You simply define a method, attribute, class, etc. and it's adde... |
Why is adding attributes to an already instantiated object allowed in Python? | 12,569,018 | 22 | 2012-09-24T16:20:51Z | 12,569,614 | 16 | 2012-09-24T17:02:08Z | [
"python",
"attributes",
"python-3.x",
"declaration"
] | I am studying python, and although I think I get the whole concept and notion of Python, today I stumbled upon a piece of code that I did not fully understand:
Say I have a class that is supposed to define Circles but lacks a body:
```
class Circle():
pass
```
Since I have not defined any attributes, how can I d... | Just to clarify some misunderstandings in the discussions here. This code:
```
class Foo(object):
def __init__(self, bar):
self.bar = bar
foo = Foo(5)
```
And this code:
```
class Foo(object):
pass
foo = Foo()
foo.bar = 5
```
is *exactly equivalent*. There really is no difference. It does exactly ... |
How to identify numpy types in python? | 12,569,452 | 32 | 2012-09-24T16:49:46Z | 12,569,453 | 12 | 2012-09-24T16:49:46Z | [
"python",
"numpy",
"duck-typing",
"dynamic-typing"
] | How can one reliably determine if an object has a numpy type?
I realize that this question goes against the philosophy of duck typing, but idea is to make sure a function (which uses scipy and numpy) never returns a numpy type unless it is called with a numpy type. [This comes up in the solution to another question,](... | The solution I've come up with is:
```
isinstance(y, (np.ndarray, np.generic) )
```
However, [it's not 100% clear](http://docs.scipy.org/doc/numpy/reference/generated/numpy.generic.html?highlight=generic#numpy.generic) that all numpy types are guaranteed to be either `np.ndarray` or `np.generic`, and this probably is... |
How to identify numpy types in python? | 12,569,452 | 32 | 2012-09-24T16:49:46Z | 12,570,040 | 32 | 2012-09-24T17:36:59Z | [
"python",
"numpy",
"duck-typing",
"dynamic-typing"
] | How can one reliably determine if an object has a numpy type?
I realize that this question goes against the philosophy of duck typing, but idea is to make sure a function (which uses scipy and numpy) never returns a numpy type unless it is called with a numpy type. [This comes up in the solution to another question,](... | Use the builtin `type` function to get the type, then you can use the `__module__` property to find out where it was defined:
```
>>> import numpy as np
a = np.array([1, 2, 3])
>>> type(a)
<type 'numpy.ndarray'>
>>> type(a).__module__
'numpy'
>>> type(a).__module__ == np.__name__
True
``` |
Choosing between Scons and Waf in Large Projects | 12,569,463 | 13 | 2012-09-24T16:50:43Z | 14,755,228 | 9 | 2013-02-07T15:48:56Z | [
"python",
"caching",
"scons",
"waf",
"build-tools"
] | We are thinking about converting a really large project from using GNU Make to some more modern build tool. My current suggestion is to use SCons or Waf.
Currently:
* Build times are around 15 minutes.
* Around 100 developers.
* About 10 percent of code is C/C++/Fortran rest is Ada (using gnatmake).
Potential hopes/... | I have been developing a tool chain for our company that is built around `waf`. It targets Fedora, Ubuntu, Arch, Windows, Mac OSX and will be rolled out to our embedded devices doing cross-compilation on various hosts.
We have found the way that `waf` allows contained extensibility through the tools, features and othe... |
Sum all columns with a wildcard name search using Python Pandas | 12,569,730 | 30 | 2012-09-24T17:11:53Z | 12,570,410 | 41 | 2012-09-24T18:05:26Z | [
"python",
"wildcard",
"pandas"
] | I have a dataframe in python pandas with several columns taken from a CSV file.
For instance, data =:
```
Day P1S1 P1S2 P1S3 P2S1 P2S2 P2S3
1 1 2 2 3 1 2
2 2 2 3 5 4 2
```
And what I need is to get the sum of all columns which name starts with P1... something like P1\* with a wildca... | I found the answer.
Using the data, dataframe from the question:
```
from pandas import *
P1Channels = data.filter(regex="P1")
P1Sum = P1Channels.sum(axis=1)
``` |
Python large iterations number fail | 12,569,977 | 13 | 2012-09-24T17:32:27Z | 12,570,419 | 14 | 2012-09-24T18:06:02Z | [
"python",
"parallel-processing",
"iteration",
"montecarlo",
"pi"
] | I wrote simple [monte-carlo Ï calculation](http://math.fullerton.edu/mathews/n2003/montecarlopimod.html) program in Python, using multiprocessing module.
It works just fine, but when I pass 1E+10 iterations for each worker, some problem occur, and the result is wrong. I cant understand what is the problem, because eve... | The problem seems to be that multiprocessing has a limit to the largest int it can pass to subprocesses inside an xrange. Here's a quick test:
```
import sys
from multiprocessing import Pool
def doit(n):
print n
if __name__ == "__main__":
procs = int(sys.argv[1])
iters = int(float(sys.argv[2]))
p = Pool(proces... |
How to upload a file to S3 without creating a temporary local file | 12,570,465 | 12 | 2012-09-24T18:09:12Z | 12,570,605 | 7 | 2012-09-24T18:19:53Z | [
"python",
"amazon-s3",
"amazon"
] | Is there any feasible way to upload a file which is generated dynamically to amazon s3 directly without first create a local file and then upload to the s3 server? I use python. Thanks | The [boto](http://docs.pythonboto.org/) library's [Key](http://docs.pythonboto.org/en/latest/ref/s3.html#boto.s3.key.Key) object has several methods you might be interested in:
* [send\_file](http://docs.pythonboto.org/en/latest/ref/s3.html#boto.s3.key.Key.send_file)
* [set\_contents\_from\_file](http://docs.pythonbot... |
How to upload a file to S3 without creating a temporary local file | 12,570,465 | 12 | 2012-09-24T18:09:12Z | 30,787,354 | 7 | 2015-06-11T17:18:00Z | [
"python",
"amazon-s3",
"amazon"
] | Is there any feasible way to upload a file which is generated dynamically to amazon s3 directly without first create a local file and then upload to the s3 server? I use python. Thanks | Here is an example downloading an image (using requests library) and uploading it to s3, without writing to a local file:
```
import boto
from boto.s3.key import Key
import requests
#setup the bucket
c = boto.connect_s3(your_s3_key, your_s3_key_secret)
b = c.get_bucket(bucket, validate=False)
#download the file
url ... |
How to show PIL images on the screen? | 12,570,859 | 17 | 2012-09-24T18:37:24Z | 12,571,366 | 26 | 2012-09-24T19:15:29Z | [
"python",
"image",
"python-imaging-library"
] | I am doing some image editing with the PIL libary. The point is, that I don't want to save the image each time on my HDD to view it in Explorer. Is there a small module that simply enables me to set up a window and display the image? | From the [PIL tutorial](http://effbot.org/imagingbook/introduction.htm):
> Once you have an instance of the Image class, you can use the methods
> defined by this class to process and manipulate the image. For
> example, let's display the image we just loaded:
>
> `>>> im.show()` |
Have Supervisord Periodically restart child processes | 12,571,052 | 18 | 2012-09-24T18:51:49Z | 12,571,741 | 17 | 2012-09-24T19:39:47Z | [
"php",
"python",
"gearman",
"supervisord"
] | I am using Supervisor (3.0a12) on ubuntu 12.04 to manage php gearman workers. Sometimes the workers get caught in a weird state where they use tons of cpu and ram. While I am figuring this issue out I thought it would be nice to have Supervisor automatically kill and refresh workers occasionally. I looked at <http://su... | The [`superlance` package](http://superlance.readthedocs.org/en/latest/index.html) offers a [`memmon` plugin](http://superlance.readthedocs.org/en/latest/memmon.html) for supervisor. `memmon` monitors memory usage for programs under supervisor control.
You configure `memmon` as a supervisor eventlistener:
```
[eventl... |
Have Supervisord Periodically restart child processes | 12,571,052 | 18 | 2012-09-24T18:51:49Z | 17,894,953 | 13 | 2013-07-27T06:28:43Z | [
"php",
"python",
"gearman",
"supervisord"
] | I am using Supervisor (3.0a12) on ubuntu 12.04 to manage php gearman workers. Sometimes the workers get caught in a weird state where they use tons of cpu and ram. While I am figuring this issue out I thought it would be nice to have Supervisor automatically kill and refresh workers occasionally. I looked at <http://su... | You could use crontab to pass commands directly to supervisorctl. For example, the following will restart a process every 20 minutes.
```
0,20,40 * * * * /path/to/supervisorctl restart [supervisor_process]
``` |
Python: Amazon S3 cannot get the bucket: says 403 Forbidden | 12,571,217 | 11 | 2012-09-24T19:05:12Z | 14,490,668 | 28 | 2013-01-23T22:34:52Z | [
"python",
"amazon-s3",
"boto"
] | I have a bucket for my organization in Amazon S3 which looks like `mydev.orgname`
* I have a Java application that can connect to Amazon S3 with the credentials and can connect to S3, create, read files
* I have a requirement where a application reads the data from Python from same bucket. So I am using [boto](https:/... | Giving the user a "stronger role" is not the correct solution. This is simply a problem with `boto` library usage. Clearly, you don't need extra permissions when using Java S3 library.
Correct way to use boto in this case is:
```
b = conn.get_bucket('my-bucket', validate=False)
k = b.get_key('my/cool/object.txt') # w... |
finding on which page a search string is located in a pdf document using python | 12,571,905 | 5 | 2012-09-24T19:50:36Z | 14,388,556 | 7 | 2013-01-17T21:35:40Z | [
"python",
"pdf",
"pypdf"
] | Which python packages can I use to find out out on which page a specific âsearch stringâ is located ?
I looked into several python pdf packages but couldn't figure out which one I should use.
[PyPDF](http://pybrary.net/pyPdf/) does not seem to have this functionality and [PDFMiner](http://www.unixuser.org/~euske/p... | I finally figured out that pyPDF can help. I am posting it in case it can help somebody else.
**(1) a function to locate the string**
```
def fnPDF_FindText(xFile, xString):
# xfile : the PDF file in which to look
# xString : the string to look for
import pyPdf, re
PageFound = -1
pdfDoc = pyPdf.Pd... |
Python unzipping stream of bytes? | 12,571,913 | 12 | 2012-09-24T19:51:02Z | 12,572,031 | 12 | 2012-09-24T20:00:08Z | [
"python",
"compression"
] | Here is the situation:
* I get gzipped xml documents from Amazon S3
```
import boto
from boto.s3.connection import S3Connection
from boto.s3.key import Key
conn = S3Connection('access Id', 'secret access key')
b = conn.get_bucket('mydev.myorg')
k = Key(b)
k.key('documents/document.xml.gz')
```
* I r... | Yes, you can use the [`zlib` module](http://docs.python.org/library/zlib.html) to decompress byte streams:
```
import zlib
def stream_gzip_decompress(stream):
dec = zlib.decompressobj(32 + zlib.MAX_WBITS) # offset 32 to skip the header
for chunk in stream:
rv = dec.decompress(chunk)
if rv:
... |
Python unzipping stream of bytes? | 12,571,913 | 12 | 2012-09-24T19:51:02Z | 12,957,256 | 7 | 2012-10-18T14:41:14Z | [
"python",
"compression"
] | Here is the situation:
* I get gzipped xml documents from Amazon S3
```
import boto
from boto.s3.connection import S3Connection
from boto.s3.key import Key
conn = S3Connection('access Id', 'secret access key')
b = conn.get_bucket('mydev.myorg')
k = Key(b)
k.key('documents/document.xml.gz')
```
* I r... | I had to do the same thing and this is how I did it:
```
import gzip
f = StringIO.StringIO()
k.get_file(f)
f.seek(0) #This is crucial
gzf = gzip.GzipFile(fileobj=f)
file_content = gzf.read()
``` |
Get a string after a specific substring | 12,572,362 | 30 | 2012-09-24T20:24:26Z | 12,572,391 | 66 | 2012-09-24T20:27:07Z | [
"python",
"string"
] | how can i get a string after a specific substring .
For example I want to get the string after `"world"` in `my_string="hello python world , i'm a beginner "` | The easiest way is probably just to split on your target word
```
my_string="hello python world , i'm a beginner "
print my_string.split("world",1)[1]
```
split takes the word(or character) to split on and optionally a limit to the number of splits.
In this example split on "world" and limit it to only one split.
O... |
Get a string after a specific substring | 12,572,362 | 30 | 2012-09-24T20:24:26Z | 12,572,399 | 15 | 2012-09-24T20:27:31Z | [
"python",
"string"
] | how can i get a string after a specific substring .
For example I want to get the string after `"world"` in `my_string="hello python world , i'm a beginner "` | ```
s1 = "hello python world , i'm a beginner "
s2 = "world"
print s1[s1.index(s2) + len(s2):]
```
If you want to deal with the case where `s2` is *not* present in `s1`, then use `s1.find(s2)` as opposed to `index`. If the return value of that call is `-1`, then `s2` is not in `s1`. |
Get a string after a specific substring | 12,572,362 | 30 | 2012-09-24T20:24:26Z | 16,712,886 | 9 | 2013-05-23T11:35:10Z | [
"python",
"string"
] | how can i get a string after a specific substring .
For example I want to get the string after `"world"` in `my_string="hello python world , i'm a beginner "` | I'm surprised nobody mentioned `partition`.
```
def substring_after(s, delim):
return s.partition(delim)[2]
```
IMHO, this solution is more readable than @arshajii's. Other than that, I think @arshajii's is the best for being the fastest -- it does not create any unnecessary copies/substrings. |
How to configure pylint in the python source | 12,572,835 | 4 | 2012-09-24T20:59:26Z | 12,573,200 | 10 | 2012-09-24T21:30:23Z | [
"python",
"suppress-warnings",
"pylint"
] | Is it possible to disable certain pylint errors/warnings in the python source code itself ? | ```
def foo():
print "000000000000000000000000000000000000000000000000000000000000000000000000000"
print "111111111111111111111111111111111111111111111111111111111111111111111111111"
```
pylint output:
```
C: 2: Line too long (87/80)
C: 3: Line too long (83/80)
C: 1: Missing docstring
C: 1:foo: Black listed n... |
How to configure pylint in the python source | 12,572,835 | 4 | 2012-09-24T20:59:26Z | 12,577,765 | 7 | 2012-09-25T07:02:12Z | [
"python",
"suppress-warnings",
"pylint"
] | Is it possible to disable certain pylint errors/warnings in the python source code itself ? | The #pylint: disable syntax mentionned by @kalgasnik is the correct one. You can find more information about this in the [Pylint FAQ](http://docs.pylint.org/message-control) (your question is `meth2`) |
why i failed to build sqlite3 when build python? | 12,573,787 | 5 | 2012-09-24T22:24:38Z | 13,317,378 | 10 | 2012-11-09T23:10:46Z | [
"python",
"sqlite",
"sqlite3",
"python-2.7",
"python-extensions"
] | why i just failed to build sqlite?
does it have something to do with readline or \_tkinter, or something else?
```
pes/libffi/src/prep_cif.o build/temp.linux-i686-2.7/home/mirror/build/tmp/Python-2.7.3/Modules/_ctypes/libffi/src/closures.o build/temp.linux-i686-2.7/home/mirror/build/tmp/Python-2.7.3/Modules/_ctypes/l... | There is a patch that can be found (and is discussed) at the following address:
<http://bugs.python.org/issue14572>
I had the exact same problem as the original poster, and the patch resolved it.
To apply the [patch](https://gist.github.com/msabramo/2727063/), from terminal in your python 2.7.3 directory:
```
curl -... |
Multiple Forms and Formsets in CreateView | 12,573,992 | 7 | 2012-09-24T22:48:11Z | 12,577,047 | 7 | 2012-09-25T06:05:32Z | [
"python",
"django",
"django-forms",
"django-class-based-views"
] | I have 2 models, `Father` and `Son`.
I have a page to register `Father`. On the same page I have a formset to register `Son`.
On page has a button "more" to add another `Father` and their respective `Son` on the same page.
Does anyone have any examples using `CreateView`? | Class based views are still new, so I'll write this out. The process is simple:
First, create the forms for your objects. One of the forms will be repeated. Nothing special to be done here.
```
class SonInline(ModelForm):
model = Son
class FatherForm(ModelForm):
model = Father
```
Then, create your [`formse... |
C++ GDB Python Pretty Printing Tutorial? | 12,574,253 | 22 | 2012-09-24T23:21:15Z | 12,775,126 | 22 | 2012-10-08T03:58:57Z | [
"c++",
"python",
"gdb"
] | I am looking for a solid tutorial on creating a custom printer.
There are a few sparse pages on the GDB page however they are far from complete and leave much to the imagination!
For instance, I'd love to be able to create a PrettyPrinter for our custom shared pointer class. | Check out Tom Tromey's pretty printing tutorials [part 1](http://tromey.com/blog/?p=524) and [part 2](http://tromey.com/blog/?p=546). There is also the [libstdc++-v6 pretty printer implementation](http://gcc.gnu.org/git/?p=gcc.git;a=blob_plain;f=libstdc%2b%2b-v3/python/libstdcxx/v6/printers.py;hb=HEAD) to look at, whic... |
Can Go really be that much faster than python? | 12,574,909 | 25 | 2012-09-25T01:00:20Z | 12,575,001 | 14 | 2012-09-25T01:17:13Z | [
"python",
"performance",
"go"
] | I think I may have implemented this incorrectly because the results do not make sense. I have a go program that counts to 1000000000
```
package main
import (
"fmt"
)
func main() {
for i := 0; i < 1000000000; i++ {}
fmt.Println("Done")
}
```
It finishes in less than a se... | **This scenario will *highly favor* decent natively-compiled statically-typed languages**. Natively compiled statically-typed languages are capable of emitting a very trivial loop of say, 4-6 CPU opcodes that utilizes simple check-condition for termination. This loop has effectively *zero* branch prediction misses and ... |
Can Go really be that much faster than python? | 12,574,909 | 25 | 2012-09-25T01:00:20Z | 12,575,141 | 55 | 2012-09-25T01:35:26Z | [
"python",
"performance",
"go"
] | I think I may have implemented this incorrectly because the results do not make sense. I have a go program that counts to 1000000000
```
package main
import (
"fmt"
)
func main() {
for i := 0; i < 1000000000; i++ {}
fmt.Println("Done")
}
```
It finishes in less than a se... | One billion is not a very big number. Any reasonably modern machine *should* be able to do this in a few seconds at most, *if it's able to do the work with native types*. I verified this by writing an equivalent C program, reading the assembly to make sure that it actually was doing addition, and timing it (it complete... |
Can Go really be that much faster than python? | 12,574,909 | 25 | 2012-09-25T01:00:20Z | 12,576,824 | 41 | 2012-09-25T05:43:46Z | [
"python",
"performance",
"go"
] | I think I may have implemented this incorrectly because the results do not make sense. I have a go program that counts to 1000000000
```
package main
import (
"fmt"
)
func main() {
for i := 0; i < 1000000000; i++ {}
fmt.Println("Done")
}
```
It finishes in less than a se... | pypy actually does an impressive job of speeding up this loop
```
def main():
x = 0
while x < 1000000000:
x+=1
if __name__ == "__main__":
s=time.time()
main()
print time.time() - s
```
---
```
$ python count.py
44.221405983
$ pypy count.py
1.03511095047
```
~97% speedup!
Clarificatio... |
Convert a 1D array to a 2D array in numpy | 12,575,421 | 21 | 2012-09-25T02:23:30Z | 12,575,451 | 33 | 2012-09-25T02:27:24Z | [
"python",
"arrays",
"matrix",
"numpy",
"multidimensional-array"
] | I want to convert a 1-dimensional array into a matrix by specifying the number of columns in the matrix. Something that would work like this:
```
> import numpy as np
> A = np.array([1,2,3,4,5,6])
> B = vec2matrix(A,ncol=2)
> B
array([[1, 2],
[3, 4],
[5, 6],
[7, 8]])
```
Does numpy have a function that works... | You want to [`reshape`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html) the array.
```
B = np.reshape(A, (-1, 2))
``` |
Convert a 1D array to a 2D array in numpy | 12,575,421 | 21 | 2012-09-25T02:23:30Z | 12,578,645 | 10 | 2012-09-25T08:03:46Z | [
"python",
"arrays",
"matrix",
"numpy",
"multidimensional-array"
] | I want to convert a 1-dimensional array into a matrix by specifying the number of columns in the matrix. Something that would work like this:
```
> import numpy as np
> A = np.array([1,2,3,4,5,6])
> B = vec2matrix(A,ncol=2)
> B
array([[1, 2],
[3, 4],
[5, 6],
[7, 8]])
```
Does numpy have a function that works... | You have two options:
* If you no longer want the original shape, the easiest is just to assign a new shape to the array
```
a.shape = (a.size//ncols, ncols)
```
You can switch the `a.size//ncols` by `-1` to compute the proper shape automatically. Make sure that `a.shape[0]*a.shape[1]=a.size`, else you'll ru... |
Python and Matplotlib and Annotations with Mouse Hover | 12,576,454 | 5 | 2012-09-25T05:04:35Z | 12,577,114 | 7 | 2012-09-25T06:12:39Z | [
"python",
"annotations",
"matplotlib",
"wxpython",
"matplotlib-basemap"
] | I am currently employing this code to have pop up annotatations on a map when i click on a point in a Basemap Matplotlib Plot.
```
dcc = DataCursor(self.figure.gca())
self.figure.canvas.mpl_connect('pick_event',dcc)
plot_handle.set_picker(5)
self.figure.canvas.draw()
class DataCursor(object):
import matplotlib.p... | Take a look at [this question](http://stackoverflow.com/questions/7908636/possible-to-make-labels-appear-when-hovering-over-a-point-in-matplotlib) and [demo](http://matplotlib.org/examples/event_handling/pick_event_demo.html) :
```
from matplotlib.pyplot import figure, show
import numpy as npy
from numpy.random import... |
Inheritance error with Python | 12,576,778 | 2 | 2012-09-25T05:39:30Z | 12,576,869 | 7 | 2012-09-25T05:47:45Z | [
"python"
] | I have the following code.py file:
```
class Shape:
def __init__(self, x, y):
self.x = x
self.y = y
def move(self, delta_x, delta_y):
self.x += delta_x
self.y += delta_y
class Square(Shape):
def __init__(self, side=1, x=0, y=0):
super().__init__(x, y)
self.... | `super` requires an argument and this is exactly what the error message is saying. In your case you need to use `super(Circle, self)` and `super(Square, self)`.
For the gory details you can see [this SO question](http://stackoverflow.com/q/576169/320726) or you can just check the official documentation.
Note that unl... |
Log in with Django-social-auth & tastypie on iOS | 12,577,045 | 2 | 2012-09-25T06:05:25Z | 12,587,020 | 7 | 2012-09-25T16:17:32Z | [
"python",
"ios",
"django",
"api",
"django-socialauth"
] | I'm building out an API using tastypie for an iOS app.
I can handle normal authentication / authorization just fine but I'm a bit confused when it comes to using django-social-auth to register / login / link THROUGH Tastypie.
If I'd, for example like to authenticate or register users on an iOS app using django-social... | You cannot use django-social-auth directly.
To do Facebook login, you need to use the Facebook SDK for iOS (https://developers.facebook.com/docs/reference/iossdk/).
It will return you the access token which you would send to your API created using TastyPie.
When you have the access token, you can register a new user... |
OSError geos_c could not be found when Installing Shapely | 12,578,471 | 12 | 2012-09-25T07:50:20Z | 12,683,010 | 9 | 2012-10-02T00:30:50Z | [
"python",
"matplotlib-basemap",
"geos",
"shapely"
] | I'm a newbie to making/plotting on maps with python, been trying to follow this blogpost to generate a world map (http://sciblogs.co.nz/seeing-data/2011/08/12/plotting-geographic-data-on-a-world-map-with-python/). Got stuck with a few things here:
1. Installing Basemap (a Matplotlib extension for plotting data on geog... | For questions 2-4, you have to have GEOS installed on your system.
If you have homebrew you can do the following:
`brew install geos`
Install homebrew here if you don't have it: <http://mxcl.github.com/homebrew/> |
OSError geos_c could not be found when Installing Shapely | 12,578,471 | 12 | 2012-09-25T07:50:20Z | 17,660,587 | 11 | 2013-07-15T17:50:11Z | [
"python",
"matplotlib-basemap",
"geos",
"shapely"
] | I'm a newbie to making/plotting on maps with python, been trying to follow this blogpost to generate a world map (http://sciblogs.co.nz/seeing-data/2011/08/12/plotting-geographic-data-on-a-world-map-with-python/). Got stuck with a few things here:
1. Installing Basemap (a Matplotlib extension for plotting data on geog... | On Ubuntu, to install `GEOS`, this worked for me:
```
$ sudo apt-get install libgeos-dev
``` |
Separation of business logic and data access in django | 12,578,908 | 209 | 2012-09-25T08:23:06Z | 12,579,490 | 68 | 2012-09-25T08:58:21Z | [
"python",
"django",
"model-view-controller",
"data-access-layer",
"business-logic-layer"
] | I am writing a project in Django and I see that 80% of the code is in the file `models.py`. This code is confusing and, after a certain time, I cease to understand what is really happening.
Here is what bothers me:
1. I find it ugly that my model level (which was supposed to be
responsible only for the work with d... | I usually implement a service layer in between views and models. This acts like your project's API and gives you a good helicopter view of what is going on. I inherited this practice from a colleague of mine that uses this layering technique a lot with Java projects (JSF), e.g:
**models.py**
```
class Book:
author... |
Separation of business logic and data access in django | 12,578,908 | 209 | 2012-09-25T08:23:06Z | 12,585,348 | 17 | 2012-09-25T14:40:12Z | [
"python",
"django",
"model-view-controller",
"data-access-layer",
"business-logic-layer"
] | I am writing a project in Django and I see that 80% of the code is in the file `models.py`. This code is confusing and, after a certain time, I cease to understand what is really happening.
Here is what bothers me:
1. I find it ugly that my model level (which was supposed to be
responsible only for the work with d... | Django employs a slightly modified kind of MVC. There's no concept of a "controller" in Django. The closest proxy is a "view", which tends to cause confusion with MVC converts because in MVC a view is more like Django's "template".
In Django, a "model" is not merely a database abstraction. In some respects, it shares ... |
Separation of business logic and data access in django | 12,578,908 | 209 | 2012-09-25T08:23:06Z | 12,854,081 | 37 | 2012-10-12T07:16:31Z | [
"python",
"django",
"model-view-controller",
"data-access-layer",
"business-logic-layer"
] | I am writing a project in Django and I see that 80% of the code is in the file `models.py`. This code is confusing and, after a certain time, I cease to understand what is really happening.
Here is what bothers me:
1. I find it ugly that my model level (which was supposed to be
responsible only for the work with d... | First of all, [Don't repeat yourself](https://docs.djangoproject.com/en/dev/misc/design-philosophies/).
Then, please be careful not to overengineer, sometimes it is just a waste of time, and makes someone lose focus on what is important. Review the [zen of python](http://www.python.org/dev/peps/pep-0020/) from time to... |
Separation of business logic and data access in django | 12,578,908 | 209 | 2012-09-25T08:23:06Z | 12,857,584 | 272 | 2012-10-12T10:59:06Z | [
"python",
"django",
"model-view-controller",
"data-access-layer",
"business-logic-layer"
] | I am writing a project in Django and I see that 80% of the code is in the file `models.py`. This code is confusing and, after a certain time, I cease to understand what is really happening.
Here is what bothers me:
1. I find it ugly that my model level (which was supposed to be
responsible only for the work with d... | It seems like you are asking about the difference between the *data model* and the *domain model* â the latter is where you can find the business logic and entities as perceived by your end user, the former is where you actually store your data.
Furthermore, I've interpreted the 3rd part of your question as: how to... |
Python Selenium: Find object attributes using xpath | 12,579,061 | 13 | 2012-09-25T08:32:55Z | 12,689,543 | 23 | 2012-10-02T11:37:15Z | [
"python",
"xpath",
"selenium"
] | I am new to xpath, trying to get value of the "value" using xpath:
```
<input type="submit" value=" Search " class="long searchButton" style="width:190px !important;">
```
while it is easy to find element by `"type="submit"` like:
```
browser.find_elements_by_xpath("//*[@type='submit']")
```
I haven't been able t... | I finally used `get_attribute("value")` as:
```
for i in browser.find_elements_by_xpath("//*[@type='submit']"):
print i.get_attribute("value")
``` |
Resample hourly TimeSeries with certain starting hour | 12,579,150 | 4 | 2012-09-25T08:38:49Z | 12,580,527 | 8 | 2012-09-25T09:56:24Z | [
"python",
"pandas"
] | I want to resample a TimeSeries in daily (exactly 24 hours) frequence starting at a certain hour.
Like:
```
index = date_range(datetime(2012,1,1,17), freq='H', periods=60)
ts = Series(data=[1]*60, index=index)
ts.resample(rule='D', how='sum', closed='left', label='left')
```
Result i get:
```
2012-01-01 7
2012-0... | [Resample](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.resample.html#pandas.DataFrame.resample) has an `base` argument which covers this case:
```
ts.resample(rule='24H', how='sum', closed='left', label='left', base=17)
```
Output:
```
2012-01-01 17:00:00 24
2012-01-02 17:00:00 24
2012-... |
Pythonic way to import modules from packages | 12,579,181 | 6 | 2012-09-25T08:40:51Z | 12,579,211 | 10 | 2012-09-25T08:42:16Z | [
"python",
"scipy",
"python-import"
] | Is there any difference, subtle or not so subtle, between the effects of the following import statements? I have found both used in example programs and sure enough, they both seem to work. It would go against the grain of Python's "there is only one way to do stuff" if they were totally equivalent in function, so I'm ... | No, there is no difference between the two statements, both put the exact same object into your module namespace (`globals()`), under the exact same name.
They go about it in slightly different ways but the end-result is the same.
Essentially, the first does:
```
from scipy import interpolate
spi = interpolate
del i... |
Accessing a dictionary member within the same dictionary | 12,579,749 | 4 | 2012-09-25T09:13:23Z | 12,579,790 | 13 | 2012-09-25T09:15:33Z | [
"python",
"syntax",
"dictionary"
] | I am trying to do something like this:
```
_dict = {"foo" : 1234,
"bar" : _dict["foo"] + 1}
```
Cant seem to get the syntax correct, is there a way to acomplish this without using multiple dictionaries, or defining them elsewhere? | You cannot access `_dict` *while* defining it. Python first evaluates the `{...}` dict literal before assigning it to `_dict`. In other words, while evaluating the `{...}` dict literal statement, `_dict` is not yet defined and thus cannot be accessed.
Do this instead:
```
_dict = {"foo" : 1234}
_dict["bar"] = _dict["... |
Accessing a dictionary member within the same dictionary | 12,579,749 | 4 | 2012-09-25T09:13:23Z | 12,579,810 | 9 | 2012-09-25T09:16:46Z | [
"python",
"syntax",
"dictionary"
] | I am trying to do something like this:
```
_dict = {"foo" : 1234,
"bar" : _dict["foo"] + 1}
```
Cant seem to get the syntax correct, is there a way to acomplish this without using multiple dictionaries, or defining them elsewhere? | You'll can either assign then from the same var:
```
foo = 1234
_dict = {
"foo" : foo,
"bar" : foo + 1,
}
```
Or do it with two statements (still the same dict):
```
_dict = { "foo": 1234 }
_dict["bar"] = _dict["foo"] + 1
```
---
If you can elaborate on what you're trying to achieve, perhaps there's a more ele... |
Python random.sample with a generator | 12,581,437 | 19 | 2012-09-25T10:50:43Z | 12,581,484 | 14 | 2012-09-25T10:53:34Z | [
"python",
"generator",
"random-sample"
] | Do you know if there is a way to get python's `random.sample` to work with a generator object. I am trying to get a random sample from a very large text corpus. The problem is that `random.sample()` raises the following error.
```
TypeError: object of type 'generator' has no len()
```
I was thinking that maybe there ... | You can't.
You have two options: read the whole generator into a list, then sample from that list, or use a method that reads the generator one by one and picks the sample from that:
```
import random
def iterSample(iterable, samplesize):
results = []
for i, v in enumerate(iterable):
r = random.rand... |
Python random.sample with a generator | 12,581,437 | 19 | 2012-09-25T10:50:43Z | 12,582,911 | 7 | 2012-09-25T12:24:42Z | [
"python",
"generator",
"random-sample"
] | Do you know if there is a way to get python's `random.sample` to work with a generator object. I am trying to get a random sample from a very large text corpus. The problem is that `random.sample()` raises the following error.
```
TypeError: object of type 'generator' has no len()
```
I was thinking that maybe there ... | Just for the heck of it, here's a one-liner that samples *k* elements without replacement from the *n* items generated in O(*n* lg *k*) time:
```
from heapq import nlargest
def sample_from_iterable(it, k):
return (x for _, x in nlargest(k, ((random.random(), x) for x in it)))
``` |
Python random.sample with a generator | 12,581,437 | 19 | 2012-09-25T10:50:43Z | 12,583,436 | 13 | 2012-09-25T12:56:13Z | [
"python",
"generator",
"random-sample"
] | Do you know if there is a way to get python's `random.sample` to work with a generator object. I am trying to get a random sample from a very large text corpus. The problem is that `random.sample()` raises the following error.
```
TypeError: object of type 'generator' has no len()
```
I was thinking that maybe there ... | While the answer of Martijn Pieters is correct, it does slow down when `samplesize` becomes large, because using `list.insert` in a loop may have quadratic complexity.
Here's an alternative that, in my opinion, preserves the uniformity while increasing performance:
```
def iter_sample_fast(iterable, samplesize):
... |
py.test - test discovery failure when tests in different directories are called the same | 12,582,503 | 27 | 2012-09-25T11:58:43Z | 12,600,278 | 18 | 2012-09-26T11:03:54Z | [
"python",
"unit-testing",
"py.test",
"autodiscovery"
] | Using py.test, two tests called the same in different directory causes py.test to fail. Why is that? How can I change this without renaming all the tests?
To duplicate do:
```
; cd /var/tmp/my_test_module
; mkdir -p ook/test
; mkdir -p eek/test
; touch ook/test/test_proxy.py
; touch eek/test/test_proxy.py
... | Putting an `__init__.py` is one way of resolving the conflict. Unlike nose, current pytest does not try to unload test modules in order to import test modules with the same import name. I used to think it's a bit magic to do this auto-unimporting and might mess up people's expectation from what the import mechanism doe... |
How to check in python that a file in a folder has changed? | 12,582,720 | 7 | 2012-09-25T12:12:05Z | 12,582,773 | 8 | 2012-09-25T12:15:56Z | [
"python",
"inotify"
] | I need to know in python whenever a new file was added/removed/modified in a particular directory
Is there a way for that?
I'm looking for an "inofity"-like function (from POSIX).
Thanks | Use the [pyinotify](https://github.com/seb-m/pyinotify) package. Or [inotify-tools](https://github.com/rvoicilas/inotify-tools). |
How can I hide my stack frames in a TestCase subclass? | 12,583,015 | 7 | 2012-09-25T12:31:42Z | 13,069,480 | 11 | 2012-10-25T13:17:44Z | [
"python",
"unit-testing",
"testing",
"subclass",
"stack-trace"
] | I want to add a custom assert method to a `TestCase` subclass. I tried to copy my implementation from the `unittest` module so that it would match the behaviour of the regular `TestCase` as closely as possible. (I would prefer to just delegate to `self.assertEqual()` but this causes even more backtrace noise, see below... | This question was answered [by Peter Otten on comp.lang.python](http://mail.python.org/pipermail/python-list/2012-October/632388.html).
Move MyTestCase in a separate module and define a global variable `__unittest = True`.
```
$ cat mytestcase.py
import unittest
__unittest = True
class MyTestCase(unittest.TestCase... |
Regular Expression for a pattern of 45 hex numbers OR 48 hex numbers - Python | 12,583,702 | 4 | 2012-09-25T13:10:51Z | 12,584,037 | 7 | 2012-09-25T13:31:19Z | [
"python",
"regex"
] | My file contains either 45 hex numbers, separated by whitespaces or 48 hex numbers, separated by whitespaces. I need ALL of those numbers individually and not as a whole. I am currently using a brute force method to get 45 numbers.
```
pattern = re.compile("([0-9a-f]{2})\s([0-9a-f]{2})\s([0-9a-f]{2})\s([0-9a-f]{2})\s(... | When writing long REs, consider using [`re.VERBOSE`](http://docs.python.org/howto/regex.html#using-re-verbose) to make them more readable.
```
pattern = re.compile(r"""
^( [0-9a-fA-F]{2} (?: \s [0-9a-fA-F]{2} ){44}
(?:(?: \s [0-9a-fA-F]{2} ){3} )? )$
""", re.VERBOSE)
```
Read as: two hex digits, fol... |
How do I create a project in kivy running on android? | 12,584,941 | 4 | 2012-09-25T14:18:17Z | 12,626,181 | 8 | 2012-09-27T16:41:54Z | [
"android",
"python",
"kivy"
] | I'm trying to understand [kivy](http://kivy.org/docs/index.html). After installation, launching kivy, I got a message saying I should create a project first in `/mny/sdcard/kivy`. The folder didn't exist so I created it via FTP connection. I then placed a `main.py` file in a subfolder. launching kivy again (After forci... | Be careful. You're using one possible method to run Kivy-based software, using the [Kivy launcher](http://kivy.org/docs/guide/packaging-android.html#packaging-your-application-for-kivy-launcher). This launcher require you to install your application (`main.py`) and a description file (`android.txt`) in a directory `kiv... |
How do I mock the hierarchy of non-existing modules? | 12,585,046 | 7 | 2012-09-25T14:22:54Z | 12,630,424 | 7 | 2012-09-27T21:40:14Z | [
"python",
"mocking",
"python-mock"
] | Let's assume that we have a system of modules that exists only on production stage. At the moment of testing these modules do not exist. But still I would like to write tests for the code that uses those modules. Let's also assume that I know how to mock all the necessary objects from those modules. The question is: ho... | So, no one helped me with my problem and I decided to solve it by myself. [Here](https://github.com/ikostia/surrogate) is a micro-lib called `surrogate` which allows one to create stubs for non-existing modules.
Lib can be used with `mock` like this:
```
from surrogate import surrogate
from mock import patch
@surrog... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.