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 much memory is used by a numpy ndarray?
9,395,758
16
2012-02-22T13:29:32Z
9,395,791
27
2012-02-22T13:31:24Z
[ "python", "arrays", "memory", "numpy", "floating-point" ]
Does anybody know how much memory is used by a numpy ndarray? (with let's say 10,000,000 float elements).
The array is simply stored in one consecutive block in memory. Assuming by "float" you mean standard double precision floating point numbers, then the array will need 8 bytes per element. In general, you can simply query the `nbytes` attribute for the total memory requirement of an array, and `itemsize` for the size o...
replace item in a string if it matches an item in the list
9,396,302
2
2012-02-22T14:01:47Z
9,396,328
10
2012-02-22T14:03:32Z
[ "python", "list", "replace" ]
I am trying to remove words from a string if they match a list. ``` x = "How I Met Your Mother 7x17 (HDTV-LOL) [VTV] - Mon, 20 Feb 2012" tags = ['HDTV', 'LOL', 'VTV', 'x264', 'DIMENSION', 'XviD', '720P', 'IMMERSE'] print x for tag in tags: if tag in x: print x.replace(tag, '') ``` It produces this outp...
You are not keeping the result of `x.replace()`. Try the following instead: ``` for tag in tags: x = x.replace(tag, '') print x ``` Note that your approach matches any substring, and not just full words. For example, it would remove the `LOL` in `RUN LOLA RUN`. One way to address this would be to enclose each ta...
Loading a video in OpenCV in Python
9,396,459
5
2012-02-22T14:11:39Z
9,396,912
10
2012-02-22T14:41:05Z
[ "python", "opencv", "computer-vision" ]
I'm desperately attempting to load a video file in OpenCV in Python (on OSX Lion) using the following code: ``` > import cv > capture = cv.CaptureFromFile("in.avi") ``` However, i only get the following warning: ``` > WARNING: Couldn't read movie file in.avi ``` There is no explanation as to what the problem is (it...
Answer: See my comment - Wrong path.
How can I use a string with the same name of an object in Python to access the object itself?
9,396,706
9
2012-02-22T14:28:49Z
9,396,745
13
2012-02-22T14:31:00Z
[ "python", "object", "reference" ]
For example, in the code below I would like to obtain the list [1,2,3] using x as a reference. ``` In[1]: pasta=[1,2,3] In:[2]: pasta Out[2]: [1, 2, 3] In [3]: x='pas'+'ta' In [4]: x Out[4]: 'pasta' ```
What you are trying to do is a bad practice. What you really need is a [`dict`](http://docs.python.org/py3k/library/stdtypes.html#mapping-types-dict): ``` >>> dct = {'pasta': [1,2,3]} >>> x = 'pas' + 'ta' >>> dct[x] [1, 2, 3] ``` This is the right *data structure* for the actual task you're trying to achieve: using ...
Error when running dropbox.py
9,397,421
4
2012-02-22T15:10:39Z
9,397,661
9
2012-02-22T15:24:26Z
[ "python", "dropbox" ]
``` test@SERVER:~/source/dropbox/.dropbox-dist$ ./dropbox.py Traceback (most recent call last): File "./dropbox.py", line 39, in <module> import urllib File "/usr/lib/python2.6/urllib.py", line 30, in <module> from urlparse import urljoin as basejoin File "/usr/lib/python2.6/urlparse.py", line 84, i...
Looks like there's another module in your Python path named `collections` (probably `collections.py` but could also be a folder named `collections` that has an `__init__.py` in it) that's preventing the Python 2.6 `collections` module from being imported. Could be something in the directory that's current when you invo...
Why is my Django view decorator not getting the request passed to it?
9,397,584
8
2012-02-22T15:20:36Z
9,397,717
20
2012-02-22T15:27:43Z
[ "python", "django", "decorator" ]
I have a setup looking something like this: ``` def foo_decorator(function): @wraps(function) def decorator(*args, **kwargs): print kwargs return function(*args, **kwargs) return decorator @foo_decorator def analytics(request, page_id, promotion_id): pass ``` Outputting: ``` {'promo...
`request` isn't a keyword argument to the view, it's the first positional argument. You can access it as `args[0]`. ``` def foo_decorator(function): @wraps(function) def decorator(*args, **kwargs): print args[0] return function(*args, **kwargs) return decorator ``` I would recommend that ...
How to set the default color cycle for all subplots with matplotlib?
9,397,944
47
2012-02-22T15:39:32Z
9,398,214
59
2012-02-22T15:54:00Z
[ "python", "matplotlib", "colors" ]
How can I set a default set of colors for plots made with matplotlib? I can set a particular color map like this ``` import numpy as np import matplotlib.pyplot as plt fig=plt.figure(i) ax=plt.gca() colormap = plt.get_cmap('jet') ax.set_color_cycle([colormap(k) for k in np.linspace(0, 1, 10)]) ``` but is there some ...
Sure! Either [specify `axes.color_cycle` in your `.matplotlibrc` file](http://matplotlib.sourceforge.net/users/customizing.html) or set it at runtime using `matplotlib.rcParams` or `matplotlib.rc`. As an example of the latter: ``` import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np # Set the ...
How to set the default color cycle for all subplots with matplotlib?
9,397,944
47
2012-02-22T15:39:32Z
37,211,181
13
2016-05-13T13:21:31Z
[ "python", "matplotlib", "colors" ]
How can I set a default set of colors for plots made with matplotlib? I can set a particular color map like this ``` import numpy as np import matplotlib.pyplot as plt fig=plt.figure(i) ax=plt.gca() colormap = plt.get_cmap('jet') ax.set_color_cycle([colormap(k) for k in np.linspace(0, 1, 10)]) ``` but is there some ...
Starting from matplotlib 1.5, mpl.rcParams['axes.color\_cycle'] is deprecated. You should use axes.prop\_cycle: ``` import matplotlib as mpl mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=["r", "#e94cdc", "0.7"]) ```
python argh/argparse: How can I pass a list as a command-line argument?
9,398,065
49
2012-02-22T15:45:46Z
9,398,245
65
2012-02-22T15:55:21Z
[ "python", "command-line-arguments", "argparse", "argh" ]
I'm trying to pass a list of arguments to a python script using the argh library. Something that can take inputs like these: ``` ./my_script.py my-func --argA blah --argB 1 2 3 4 ./my_script.py my-func --argA blah --argB 1 ./my_script.py my-func --argA blah --argB ``` My internal code looks like this: ``` import arg...
With `argparse`, you just use `type=int` ``` import argparse parser = argparse.ArgumentParser() parser.add_argument('-a', '--arg', nargs='+', type=int) print parser.parse_args() ``` Example output: ``` $ python test.py -a 1 2 3 Namespace(arg=[1, 2, 3]) ``` Edit: I'm not familiar with `argh`, but it seems to be jus...
Why am I getting the error: command 'llvm-gcc-4.2' failed with exit status 1
9,398,142
17
2012-02-22T15:50:05Z
10,019,178
34
2012-04-04T21:00:38Z
[ "python", "osx-lion", "llvm", "easy-install" ]
I am setting up os X 10.7. I am using the default install of Python: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ I use a Python based package manager called easy\_install. Easy\_install seems to not be able to find the compiler. EDIT: When I tried to install MySQL-python I got this error: ```...
I had the exact same problem when I upgraded from OSX 10.6 to 10.7. If you upgrade to 10.7 from 10.6, your version of Python may go from 2.6 to 2.7 and a result you may need to re-install most of your python packages. Here's what worked for me: 1. Install the latest version of XCode from the App Store 2. Inside XCode...
How do I run a Python script on my web server?
9,398,560
20
2012-02-22T16:13:52Z
9,398,638
19
2012-02-22T16:17:48Z
[ "python", "webserver", "cgi-bin" ]
I've just started learning Python, and I'm pretty lost right now. I want to run my script on my server that is hosted through hosting24.com. Their FAQ says they support Python, but I have no clue where to put my script for it to run. There is a folder called cgi-bin in my root, I'm guessing that is where I put my scri...
Very simply, you can rename your python script to "pythonscript.cgi". Post that in your cgi-bin directory, add the appropriate permissions and browse to it. [This is a great link](http://docs.python.org/howto/webservers.html) you can start with. [Here's another good one.](https://autofei.wordpress.com/2010/06/13/add-...
Get $_SERVER['HTTP_USER_AGENT'] variable value in Bottle
9,400,166
3
2012-02-22T17:47:52Z
9,400,291
8
2012-02-22T17:55:42Z
[ "python", "bottle" ]
I am new to python bottle framework and need to get $\_SERVER['HTTP\_USER\_AGENT'] variable value specially. Pleas can some one explain how can I achieve this.
Try it: ``` import request, route, run @route('/user-agent') def user_agent(): return request.environ.get('HTTP_USER_AGENT') run() ```
Calculating frequency of values in dictionary
9,401,095
2
2012-02-22T18:50:26Z
9,401,152
7
2012-02-22T18:54:40Z
[ "python", "dictionary" ]
I've dictionary which contains values like this {a:3,b:9,c:88,d:3} I want to calculate how many times particular number appears in above dictionary. For example in above dictionary 3 appears twice in dictionary Please help to write python script
You should use [`collections.Counter`](http://docs.python.org/dev/library/collections.html#collections.Counter): ``` >>> from collections import Counter >>> d = {'a':3, 'b':9, 'c':88, 'd': 3} >>> Counter(d.values()).most_common() [(3, 2), (88, 1), (9, 1)] ```
How To Merge an Arbitrary Number of Tuples in Python?
9,401,209
6
2012-02-22T18:59:05Z
9,401,257
9
2012-02-22T19:02:05Z
[ "python", "tuples", "iterable-unpacking" ]
I have a list of tuples: ``` l=[(1,2,3),(4,5,6)] ``` The list can be of arbitrary length, as can the tuples. I'd like to convert this into a list or tuple of the elements, in the order they appear: ``` f=[1,2,3,4,5,6] # or (1,2,3,4,5,6) ``` If I know the at development time how many tuples I'll get back, I could ju...
``` l = [(1, 2), (3, 4), (5, 6)] print sum(l, ()) # (1, 2, 3, 4, 5, 6) ```
How To Merge an Arbitrary Number of Tuples in Python?
9,401,209
6
2012-02-22T18:59:05Z
9,401,283
15
2012-02-22T19:03:41Z
[ "python", "tuples", "iterable-unpacking" ]
I have a list of tuples: ``` l=[(1,2,3),(4,5,6)] ``` The list can be of arbitrary length, as can the tuples. I'd like to convert this into a list or tuple of the elements, in the order they appear: ``` f=[1,2,3,4,5,6] # or (1,2,3,4,5,6) ``` If I know the at development time how many tuples I'll get back, I could ju...
[Chain](http://docs.python.org/library/itertools.html#itertools.chain) them (only creates a generator instead of reserving extra memory): ``` >>> from itertools import chain >>> l = [(1,2,3),(4,5,6)] >>> list(chain.from_iterable(l)) [1, 2, 3, 4, 5, 6] ```
matplotlib animating a scatter plot
9,401,658
23
2012-02-22T19:32:22Z
9,416,663
40
2012-02-23T16:04:04Z
[ "python", "matplotlib" ]
I just downloaded and installed version 1.1.1 of matplotlib which include newer capabilities for animation. I'm trying to do an animation of a scatter plot where colors and size of the points changes at different stage of the animation. So basically I've a set of data (actually a numpy ndarray) an x value and an y valu...
Here's a quick example using the new animation module. It's slightly more complex than it has to be, but this should give you a framework to do fancier things. If you're on OSX and using the OSX backend, you'll need to change `blit=True` to `blit=False` in the `FuncAnimation` initialization below. The OSX backend doe...
Dynamically create plots in Chaco
9,401,748
14
2012-02-22T19:39:08Z
11,067,046
7
2012-06-16T21:08:22Z
[ "python", "plot", "traits", "enthought", "chaco" ]
The Chaco plotting toolkit for Python includes examples that show how to dynamically *update* existing plots. However, my application requires that I **dynamically create and destroy plots** depending on the data. I am new to programming with Chaco and Traits, so a simple example that illustrates how to do this would b...
This is a bit late, but here's an example that creates and destroys Chaco plots. The main interface is `PlotSelector`, which defines some fake data and radio buttons to switch between two different plot styles (line and bar plots). This example uses a Traits event to signal when to close a plot, and then handles that ...
Python is slow when iterating over a large list
9,402,033
10
2012-02-22T19:59:50Z
9,402,110
15
2012-02-22T20:05:31Z
[ "python", "sql", "database", "pyodbc" ]
I am currently selecting a large list of rows from a database using pyodbc. The result is then copied to a large list, and then i am trying to iterate over the list. Before I abandon python, and try to create this in C#, I wanted to know if there was something I was doing wrong. ``` clientItems.execute("Select ids fro...
This should not be slow with Python native lists - but maybe ODBC's driver is returning a "lazy" object that tries to be smart but just gets slow. Try just doing `allIDRows = list(clientItemsCursor.fetchall())` in your code and post further benchmarks. (Python lists can get slow if you start inserting things in its ...
Installing Python Package from Github Using PIP
9,402,035
8
2012-02-22T20:00:06Z
9,402,466
14
2012-02-22T20:33:08Z
[ "python", "github", "pip" ]
I've seen it documented that you can install a Github hosting Python package using pip via: ``` sudo pip install -e git+git://github.com/myuser/myproject.git#egg=myproject ``` However, this appears to install the package to the current working directory, which is almost never where is should be. How do you instruct ...
The -e flag tells pip to install it as "editable", i.e. keep the source around. Drop the -e flag and it should do about what you expect. ``` sudo pip install git+git://github.com/myuser/myproject.git#egg=myproject ``` If that doesn't work try using https instead of git. ``` sudo pip install git+https://github.com/my...
Drawing a huge graph with networkX and matplotlib
9,402,255
14
2012-02-22T20:15:47Z
9,406,398
21
2012-02-23T02:41:14Z
[ "python", "graph", "matplotlib", "networkx" ]
I am drawing a graph with around 5K nodes in it using networkX and matplotlib. The GTK window by matplotlib has tools to zoom and visualise the graph. Is there any way, I can save a magnified version for proper visualisation later? ``` import matplotlib.pyplot as plt import networkx as nx pos=nx.spring_layout(G) #G...
You have two easy options: ## Up the DPI ``` plt.savefig("graph.png", dpi=1000) ``` (larger image file size) ## Save as a PDF ``` plt.savefig("graph.pdf") ``` This is the best option, as the final graph is not rasterized. In theory, you should be able to zoom in indefinitely.
Using python and PIL how can I grab a block of text in an image?
9,402,765
3
2012-02-22T20:51:55Z
9,406,278
9
2012-02-23T02:25:31Z
[ "python", "image-processing", "python-imaging-library", "python-2.7" ]
I have an image (\*.png) which contains two blocks of text. I am trying to grab each block of text individually using the python imaging library (PIL) in python27. I have tried to blur the image and then find the edges of the blurred block so that I can then recover the boundaries of each block (for use later with "cr...
I would start by making a histogram of the image projected onto one axis. Take your image, [crop to the outer bounding box first](http://stackoverflow.com/questions/9396312/use-python-pil-or-similar-to-shrink-whitespace/9398422#9398422). An example of the projected histogram onto to the y-axis: ``` from PIL import Ima...
Python list syntax explanation
9,403,109
4
2012-02-22T21:13:28Z
9,403,193
8
2012-02-22T21:19:15Z
[ "python", "python-3.x" ]
I've noticed that when I'm using python, I'll occasionally make a typographical error and have a definition that looks something like ``` L = [1,2,3,] ``` My question is, why doesn't this cause an error?
It doesn't cause an error because it is an intentional feature that trailing commas are allowed for lists and tuples. This is especially important for tuples, because otherwise it would be difficult to define a single element tuple: ``` >>> (100,) # this is a tuple because of the trailing comma (100,) >>> (100) ...
Django - Filtering in DetailView
9,403,247
2
2012-02-22T21:23:10Z
9,403,478
10
2012-02-22T21:38:48Z
[ "python", "django", "django-views", "django-class-based-views" ]
I had a function based view that looked like this: ``` def account_details(request, acc_id): account = get_object_or_404(Account, pk=acc_id, person__user=request.user) # ... ``` Which shows you details of your account on success, and 404 if you don't have permissions to access the account or it doesn't exist....
What arguments would you need to pass to `get_queryset` anyways? This should do it: ``` def get_queryset(self): qs = super(MyView, self).get_queryset() return qs.filter(person__user=self.request.user) ```
How do I use Python 3.2 email module to send unicode messages encoded in utf-8 with quoted-printable?
9,403,265
7
2012-02-22T21:24:35Z
9,509,718
7
2012-03-01T02:18:21Z
[ "python", "email", "character-encoding", "python-3.x", "mime" ]
I want to send email messages that have arbitrary unicode bodies in a Python 3.2 program. But, in reality, these messages will consist largely of 7bit ASCII text. So I would like the messages encoded in utf-8 using quoted-printable. So far, I've found this works, but it seems wrong: ``` c = email.charset.Charset('utf-...
That email package isn't confused about which is which (encoded unicode versus content-transfer-encoded binary data), but the documentation does not make it very clear, since much of the documentation dates from an era when "encoding" *meant* content-transfer-encoding. We're working on a better API that will make all t...
Python: How to get multiple elements inside square brackets
9,403,275
6
2012-02-22T21:25:10Z
9,403,300
14
2012-02-22T21:27:05Z
[ "python", "regex", "pattern-matching", "match", "python-2.7" ]
I have a string/pattern like this: ``` [xy][abc] ``` I try to get the values contained inside the square brackets: * xy * abc There are never brackets inside brackets. Invalid: `[[abc][def]]` So far I've got this: ``` import re pattern = "[xy][abc]" x = re.compile("\[(.*?)\]") m = outer.search(pattern) inner_valu...
`re.findall` is your friend here: ``` >>> import re >>> sample = "[xy][abc]" >>> re.findall(r'\[([^]]*)\]',sample) ['xy', 'abc'] ```
What is the best way to setup Django on os X 10.7 Lion?
9,403,453
2
2012-02-22T21:37:18Z
9,403,589
13
2012-02-22T21:46:31Z
[ "python", "django", "osx-lion", "clang" ]
I am setting up Python and Django on os X 10.7 from a virgin install and Xcode 4.3. I tried using the default install of Python: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ I normally use a Python based package manager called easy\_install. Easy\_install seems to not be able to find the compile...
Did you install the command-line tools with Xcode 4.3? They are not installed by default. You can install them by going to the Downloads pane in Xcode 4.3's preferences.
Map of all points below a certain time of travel?
9,403,699
31
2012-02-22T21:54:55Z
9,502,885
30
2012-02-29T16:27:54Z
[ "python", "google-maps" ]
My question is very simple and can be understood in one line: Is there a way, tool, etc. using google maps to get an overlay of all surface which is below a certain time of travel? I hope the question is clear, but I coulnd't find anything related on the web. If you have any information, I'll take it! ***UPDATE:***...
I think you are looking for something like [Mapnificient](http://www.mapnificent.net/): it shows you areas you can reach with public transportation in a given time ([video](http://vimeo.com/16362921)). ![enter image description here](http://i.stack.imgur.com/RzpHe.jpg) A similar site with even more options is [How Fa...
Sum of each element in python list of tuples
9,404,245
3
2012-02-22T22:35:15Z
9,404,356
8
2012-02-22T22:42:08Z
[ "python", "list", "tuples" ]
I want to add each element of list containing tuples. For example, ``` >>> list1 [(0, 1, 2), (3, 4, 5), (6, 7, 8)] >>> list2 [(1, 2, 3), (4, 5, 6), (7, 8, 9)] ``` Answer should be ``` list3 = [(1,3,5),(7,9,11),(13,15,17)] ```
zip is your friend here. ``` result = [] for ta, tb in zip(list1, list2): t =tuple(a+b for a, b in zip(ta, tb)) result.append(t) print result >> [(1,3,5),(7,9,11),(13,15,17)] ``` or more pythonic is: ``` result = [tuple(a+b for a, b in zip(ta, tb)) for ta, tb in zip(list1, list2)] print result >> [(1,3,5)...
Taking the floor of a float
9,404,967
18
2012-02-22T23:36:28Z
9,405,029
20
2012-02-22T23:42:16Z
[ "python", "python-3.x", "math", "floor" ]
I have found two ways of taking floors in Python: ``` 3.1415 // 1 ``` and ``` import math math.floor(3.1415) ``` The problem with the first approach is that it return a float (namely `3.0`). The second approach feels clumsy and too long. Are there alternative solutions for taking floors in Python?
As long as your numbers are positive, you can simply convert to an `int` to round down to the next integer: ``` >>> int(3.1415) 3 ``` For negative integers, this will round up, though.
NLTK Thinks that Imperatives are Nouns
9,406,093
11
2012-02-23T02:00:04Z
9,572,724
8
2012-03-05T19:32:42Z
[ "python", "nltk" ]
I'm using the pos\_tagger on recipes. A problem I'm having is that the pos\_tagger returns that words in the imperative tense are nouns, shouldn't they be verbs? For example: With the input: ``` combine 1 1/2 cups floud, 3/4 cup sugar, salt and baking powder ``` The output is: ``` [('combine', 'NN'), ('1', 'CD'), (...
What you're seeing is a very common problem in traditional statistical natural language processing (NLP). In short, the data you are using the tagger on doesn't look like the data it was trained on. NLTK doesn't document the details, but as far as I know the default tagger is trained on Wall Street Journal articles, th...
Is there a way to uninstall multiple packages with pip?
9,406,123
14
2012-02-23T02:03:06Z
9,406,259
24
2012-02-23T02:22:10Z
[ "python", "pip", "xargs" ]
I am attempting to remove all of the installed "pyobjc-framework"-prefixed packages. I have tried the following: ``` % pip freeze | grep pyobjc-framework | xargs pip uninstall ``` but this barfs because each pip uninstall requires confirmation (perhaps a way to bypass this would be a solution). Please help before I ...
Your command should actually work if you add the `-y | --yes` flag to pip :-) > -y, --yes Don't ask for confirmation of uninstall deletions. Possibly: `% pip freeze | grep pyobjc-framework | xargs pip uninstall -y`
How can I use a pre-made color map for my heat map in matplotlib?
9,406,400
5
2012-02-23T02:41:29Z
9,406,905
9
2012-02-23T03:51:15Z
[ "python", "matplotlib" ]
I want to use a color map from <http://goo.gl/5P4CT> for my matplotlib heat map. I tried doing this: ``` myHeatMap.imshow(heatMap, extent=ext, cmap=get_cmap(cm.datad["Spectral"])) ``` However, the Python interpreter complains ``` in get_cmap if name in cmap_d: TypeError: unhashable type: 'dict' ``` What is the...
It looks like you are simply calling `get_cmap` wrong. Try: ``` from pylab import imshow, show, get_cmap from numpy import random Z = random.random((50,50)) # Test data imshow(Z, cmap=get_cmap("Spectral"), interpolation='nearest') show() ``` ![enter image description here](http://i.stack.imgur.com/Mafjl.png) ## ...
scrapy crawling just 1 level of a web-site
9,406,895
3
2012-02-23T03:50:13Z
9,474,369
9
2012-02-28T00:03:21Z
[ "python", "web-crawler", "scrapy" ]
I am using scrapy to crawl all the web pages under a domain. I have seen [this](http://stackoverflow.com/questions/8381082/scrapy-not-crawling-all-the-pages) question. But there is no solution. My problem seems to be similar one. My output of crawl command looks like this: ``` scrapy crawl sjsu2012-02-22 19:41:35-080...
I think the best way to do this is by using a Crawlspider. So you have to modify your code to this below to be able to find all links from the first page and visit them: ``` class SjsuSpider(CrawlSpider): name = 'sjsu' allowed_domains = ['sjsu.edu'] start_urls = ['http://cs.sjsu.edu/'] # allow=() is u...
Python: eval() that coerces values to floating point?
9,407,640
6
2012-02-23T05:23:12Z
9,407,667
11
2012-02-23T05:26:26Z
[ "python", "eval" ]
Is there a way to execute an `eval`-like function that coerces its values to floating point? I am hoping to ``` eval('1/3') ``` and have it return the floating point value .333333 rather than the integer value 0.
Grab the compiler flag for `__future__.division`, pass it and your code to `compile()`, then run `eval()` on the returned code object. **(note by mh)** This has the added advantage of not changing the division operation globally, which might have unexpected side effects. **(end note)** ``` >>> import __future__ >>> e...
Python Sort() method
9,408,050
2
2012-02-23T06:10:41Z
9,408,064
10
2012-02-23T06:12:24Z
[ "python" ]
I am starting to learn Python. Can someone explain why sort() returns None? ``` alist.sort() ## correct alist = blist.sort() ## NO incorrect, sort() returns None ``` Why shouldn't ``` alist = blist.sort() ``` return the sorted list and give it back to alist? This does not make sense to me. Thanks.
`alist.sort()` sorts `alist` in-place, modifying `alist` itself. If you want a new list to assign somewhere, use `blist = sorted(alist)` * `list.sort()`: <http://docs.python.org/library/stdtypes.html#mutable-sequence-types> * `sorted()`: <http://docs.python.org/library/functions.html#sorted>
lxml - difficulty parsing stackexchange rss feed
9,409,095
5
2012-02-23T07:56:59Z
9,409,562
9
2012-02-23T08:38:44Z
[ "python", "rss", "xml-parsing", "lxml" ]
Hia I am having problems parsing an rss feed from stackexchange in python. When I try to get the summary nodes, an empty list is return I have been trying to solve this, but can't get my head around. Can anyone help out? thanks a `In [3o]: import lxml.etree, urllib2` ``` In [31]: url_cooking = 'http://cooking.stac...
Take a look at these two versions ``` import lxml.html, lxml.etree url_cooking = 'http://cooking.stackexchange.com/feeds' #lxml.etree version data = lxml.etree.parse(url_cooking) summary_nodes = data.xpath('.//feed/entry/summary') print('Found ' + str(len(summary_nodes)) + ' summary nodes') #lxml.html version data ...
run python command line interpreter with imports loaded automatically
9,409,762
6
2012-02-23T08:55:32Z
9,409,833
11
2012-02-23T09:01:18Z
[ "python" ]
I would like to play around in the python interpreter but with a bunch of imports and object setup completed. Right now I'm launching the interpreter on the command line and doing the setup work every time. Is there any way to launch the command line interpreter with all the initialization work done? Ex: ``` # Done a...
You can create a script with the code you wish to run automatically, then use [`python -i`](http://docs.python.org/using/cmdline.html#cmdoption-i) to run it. For example, create a script (let's call it script.py) with this: ``` import foo import baz l = [1,2,3,4] ``` Then run the script ``` $ python -i script.py >>>...
how to install python-devel for 2.6 version?
9,410,021
11
2012-02-23T09:14:31Z
11,684,053
12
2012-07-27T08:20:04Z
[ "python", "centos", "yum", "centos5" ]
i use centos 5.4 ,the default python version is python2.4,so i use the python2.6.2.tar.gz compile a python 2.6 version and now i want to intstall board review project it need install python-devel package,if i use yum install python-devel,it will install the python2.4 relevent version python-devel, how could i get a p...
If you enable the [EPEL](http://fedoraproject.org/wiki/EPEL) repo, you can install python 2.6 and the devel headers using yum: ``` # yum install python26 # yum install python26-devel ``` These packages won't then conflict with the python 2.4 ones.
How to filter model results for multiple values for a many to many field in django
9,410,647
13
2012-02-23T09:52:57Z
9,411,482
16
2012-02-23T10:46:57Z
[ "python", "django" ]
I have the following Model: ``` class Group(models.Model): member = models.ManyToManyField(Player, through='GroupMember') name = models.CharField(max_length=20, unique=True) join_password = models.CharField(max_length=20) date_created = datetime.datetime.now() def __unicode__(self): return...
If your `Player` model looks like this: ``` class Player(models.Model): name = models.CharField(max_length=200) ``` Then, you can execute this query: ``` Group.objects.filter(player__name__in=['Player1','Player2']) ``` Which roughly translates to *"find all groups that have players whose names match 'Player1' a...
How to filter model results for multiple values for a many to many field in django
9,410,647
13
2012-02-23T09:52:57Z
16,003,998
13
2013-04-14T20:29:49Z
[ "python", "django" ]
I have the following Model: ``` class Group(models.Model): member = models.ManyToManyField(Player, through='GroupMember') name = models.CharField(max_length=20, unique=True) join_password = models.CharField(max_length=20) date_created = datetime.datetime.now() def __unicode__(self): return...
The easiest solution for you will be: ``` p1 = Player.objects.get(id=1) p2 = Player.objects.get(id=2) groups = Group.objects.filter(member=p1).filter(member=p2) ``` Note that you can't use the \_\_in filter like this because this will result in an OR and return groups that don't contain both players: ``` Group.objec...
How do I create a pip installable project?
9,411,494
12
2012-02-23T10:47:41Z
9,412,269
8
2012-02-23T11:37:02Z
[ "python", "pip" ]
How do I create a pip installable project? How do you register with pip? What meta data config should all projects have in order to allow integration and easy import.
You need to 1. Write a setup.py file 2. Run python setup.py sdist tar gzipped file. 3. Run register or submit the project using the web form. You can register using: ``` >> python setup.py register ``` An exmaple setup.py file is: ``` #!/usr/bin/env python from distutils.core import setup setup(name='Distutils'...
Is Multithreading (in python) the same as calling the script multiple times?
9,411,992
2
2012-02-23T11:19:25Z
9,412,038
8
2012-02-23T11:21:35Z
[ "python", "multithreading" ]
Let's assume we have some task, that could be divided into independent subtasks and we want to process these tasks in parallel on the same machine. I read about multithreading and ran into [this post](http://stackoverflow.com/a/5441992/641514), which describes GlobalInterpreterLocks. Since I do not understand fully ho...
> Is Multithreading (in my case in python) effectivle the same as calling a script multiple times? In a word, no. Due to the [GIL](http://en.wikipedia.org/wiki/Global_Interpreter_Lock), in Python it is far easier to achieve true parallelism by using multiple processes than it is by using multiple threads. Calling the...
Python: Parse ISO 8601 date and time from a string (using the standard modules)
9,412,345
4
2012-02-23T11:41:59Z
9,412,482
7
2012-02-23T11:50:06Z
[ "python", "python-2.7" ]
I want to parse the date for entries given by SVN: ``` svn list --xml https://subversion:8765/svn/Foo/tags/ ``` If I am not mistaken it is given using the [ISO 8601](http://en.wikipedia.org/wiki/ISO_8601) standard. An example is: ``` dateString = "2012-02-14T11:22:34.593750Z" ``` I am using Python 2.7 and am lookin...
No need for a regexp, use `datetime.datetime.strptime()` instead.
Simple Digit Recognition OCR in OpenCV-Python
9,413,216
229
2012-02-23T12:37:22Z
9,620,295
327
2012-03-08T15:35:49Z
[ "python", "opencv", "numpy", "computer-vision", "ocr" ]
I am trying to implement a "Digit Recognition OCR" in OpenCV-Python (cv2). It is just for learning purposes. I would like to learn both KNearest and SVM features in OpenCV. I have 100 samples (i.e. images) of each digit. I would like to train with them. There is a sample `letter_recog.py` that comes with OpenCV sampl...
Well, I decided to workout myself on my question to solve above problem. What i wanted is to implement a simpl OCR using KNearest or SVM features in OpenCV. And below is what i did and how. ( it is just for learning how to use KNearest for simple OCR purposes). **1)** My first question was about letter\_recognition.da...
Simple Digit Recognition OCR in OpenCV-Python
9,413,216
229
2012-02-23T12:37:22Z
20,902,310
24
2014-01-03T11:13:20Z
[ "python", "opencv", "numpy", "computer-vision", "ocr" ]
I am trying to implement a "Digit Recognition OCR" in OpenCV-Python (cv2). It is just for learning purposes. I would like to learn both KNearest and SVM features in OpenCV. I have 100 samples (i.e. images) of each digit. I would like to train with them. There is a sample `letter_recog.py` that comes with OpenCV sampl...
For those who interested in C++ code can refer below code. Thanks **Abid Rahman** for the nice explanation. --- The procedure is same as above but, the contour finding uses only first hierarchy level contour, so that the algorithm uses only outer contour for each digit. ## Code for creating sample and Label data ``...
most efficent way of finding the minimum float in a python list
9,413,367
5
2012-02-23T12:47:13Z
9,413,477
9
2012-02-23T12:53:35Z
[ "python", "list" ]
Quick question, which is more efficient for finding the smallest number (float) in a long list (10000+ elements) is it ``` min(mylist) ``` or ``` mylist.sort() ``` and then returning ``` mylist[0] ``` or something else... thanks!
If the list is already populated, `min()` is the most efficient way. There are some tricks you might use in special scenarios: * If you build the list from scratch, simply keep the smallest item yet in an external variable, so that the answer will be given in `O(1)`. * If there are only Floats in the list, use an [Ar...
most efficent way of finding the minimum float in a python list
9,413,367
5
2012-02-23T12:47:13Z
9,413,698
11
2012-02-23T13:07:27Z
[ "python", "list" ]
Quick question, which is more efficient for finding the smallest number (float) in a long list (10000+ elements) is it ``` min(mylist) ``` or ``` mylist.sort() ``` and then returning ``` mylist[0] ``` or something else... thanks!
Frst, if you care about performance in Python (which isn't always a sensible thing to care about, but that's another conversation), you should be using the [timeit module](http://docs.python.org/library/timeit.html). Even in C it's hard to predict how certain functions will behave after compilation, and it's harder in ...
flask-cache memoize URL query string parameters as well
9,413,566
10
2012-02-23T12:59:19Z
14,264,116
18
2013-01-10T17:49:14Z
[ "python", "flask" ]
The flask-cache extension has a `@cache.memoize` decorator to cache a view including the view's `*args` and `**kwargs`. Some of my views however take a URL query string as well, for example `/foo/image?width=640`. The decorator adds a `make_cache_key` method to the decorated view function that can be used to customise ...
I had the same problem today and didn't find any example on the internet so I played around a little. This is my make\_cache\_key: ``` def make_cache_key(*args, **kwargs): path = request.path args = str(hash(frozenset(request.args.items()))) lang = get_locale() return (path + args + lang).encode('utf-...
Python variable handling, I don't understand it
9,414,034
6
2012-02-23T13:29:37Z
9,414,126
8
2012-02-23T13:36:14Z
[ "python", "variables" ]
I can't find concise information about what is going on in this very simple program: ``` print 'case 1' # a and b stay different a = [1,2,3] b = a b = [4,5,6] print 'a =',a print 'b =',b print print 'case 2' # a and b becomes equal a = [1,2,3] b = a b[0] = 4 b[1] = 5 b[2] = 6 print 'a =',a print 'b =',b print p...
This is [a fantastic visualization tool for python code](http://people.csail.mit.edu/pgbovine/python/tutor.html#mode=edit). Run your code in it and everything should become clear in a minute.
merging "several" python dictionaries
9,415,785
14
2012-02-23T15:18:37Z
9,415,875
10
2012-02-23T15:22:55Z
[ "python", "dictionary" ]
I have to merge list of python dictionary. For eg: ``` dicts[0] = {'a':1, 'b':2, 'c':3} dicts[1] = {'a':1, 'd':2, 'c':'foo'} dicts[2] = {'e':57,'c':3} super_dict = {'a':[1], 'b':[2], 'c':[3,'foo'], 'd':[2], 'e':[57]} ``` I wrote the following code: ``` super_dict = {} for d in dicts: for k, v in d.items(): ...
Merge the keys of all dicts, and for each key assemble the list of values: ``` super_dict = {} for k in set(k for d in dicts for k in d): super_dict[k] = [d[k] for d in dicts if k in d] ``` The expression `set(k for d in dicts for k in d)` builds a set of all unique keys of all dictionaries. For each of these uni...
merging "several" python dictionaries
9,415,785
14
2012-02-23T15:18:37Z
9,416,020
15
2012-02-23T15:29:42Z
[ "python", "dictionary" ]
I have to merge list of python dictionary. For eg: ``` dicts[0] = {'a':1, 'b':2, 'c':3} dicts[1] = {'a':1, 'd':2, 'c':'foo'} dicts[2] = {'e':57,'c':3} super_dict = {'a':[1], 'b':[2], 'c':[3,'foo'], 'd':[2], 'e':[57]} ``` I wrote the following code: ``` super_dict = {} for d in dicts: for k, v in d.items(): ...
You can iterate over the dictionaries directly -- no need to use `range`. The `setdefault` method of dict looks up a key, and returns the value if found. If not found, it returns a default, and also assigns that default to the key. ``` super_dict = {} for d in dicts: for k, v in d.iteritems(): # d.items() in Pyth...
merging "several" python dictionaries
9,415,785
14
2012-02-23T15:18:37Z
9,416,117
14
2012-02-23T15:33:53Z
[ "python", "dictionary" ]
I have to merge list of python dictionary. For eg: ``` dicts[0] = {'a':1, 'b':2, 'c':3} dicts[1] = {'a':1, 'd':2, 'c':'foo'} dicts[2] = {'e':57,'c':3} super_dict = {'a':[1], 'b':[2], 'c':[3,'foo'], 'd':[2], 'e':[57]} ``` I wrote the following code: ``` super_dict = {} for d in dicts: for k, v in d.items(): ...
``` from collections import defaultdict dicts = [{'a':1, 'b':2, 'c':3}, {'a':1, 'd':2, 'c':'foo'}, {'e':57, 'c':3} ] super_dict = defaultdict(set) # uses set to avoid duplicates for d in dicts: for k, v in d.iteritems(): super_dict[k].add(v) ```
How can I print many significant figures in Python?
9,415,939
6
2012-02-23T15:26:06Z
9,415,970
10
2012-02-23T15:27:06Z
[ "python" ]
For a scientific application I need to output very precise numbers, so I have to print 15 significant figures. There are already questions on this topic here, but they all concern with *truncating* the digits, not *printing more*. I realized that the `print` function converts the input `float` to a 10 character `strin...
You could use the string formatting operator `%`: ``` In [3]: val = 1./3 In [4]: print('%.15f' % val) 0.333333333333333 ``` or `str.format()`: ``` In [8]: print(str.format('{0:.15f}', val)) Out[8]: '0.333333333333333' ``` In new code, the latter is the preferred style, although the former is still widely used. Fo...
How can I print many significant figures in Python?
9,415,939
6
2012-02-23T15:26:06Z
19,614,000
7
2013-10-27T02:25:49Z
[ "python" ]
For a scientific application I need to output very precise numbers, so I have to print 15 significant figures. There are already questions on this topic here, but they all concern with *truncating* the digits, not *printing more*. I realized that the `print` function converts the input `float` to a 10 character `strin...
Thought the original question wanted to format n significant figures, not n decimal points. So a custom function might be required until some more native built-in types are on offer? So you'll want something like: ``` def float_nsf(q,n): """ Truncate a float to n significant figures. May produce overflow in ...
Python Class Based Decorator with parameters that can decorate a method or a function
9,416,947
29
2012-02-23T16:22:02Z
9,417,088
26
2012-02-23T16:30:42Z
[ "python", "function", "methods", "arguments", "decorator" ]
I've seen many examples of Python decorators that are: * function style decorators (wrapping a function) * class style decorators (implementing `__init__`, `__get__`, and `__call__`) * decorators which do not take arguments * decorators which take arguments * decorators which are "method friendly" (ie can decorate a m...
You don't need to mess around with descriptors. It's enough to create a wrapper function inside the `__call__()` method and return it. Standard Python functions can always act as either a method or a function, depending on context: ``` class MyDecorator(object): def __init__(self, argument): self.arg = arg...
Python Class Based Decorator with parameters that can decorate a method or a function
9,416,947
29
2012-02-23T16:22:02Z
9,417,114
8
2012-02-23T16:32:23Z
[ "python", "function", "methods", "arguments", "decorator" ]
I've seen many examples of Python decorators that are: * function style decorators (wrapping a function) * class style decorators (implementing `__init__`, `__get__`, and `__call__`) * decorators which do not take arguments * decorators which take arguments * decorators which are "method friendly" (ie can decorate a m...
You're missing a level. Consider the code ``` class Foo(object): @MyDecorator("foo baby!") def bar(self): print "in bar!" ``` It is identical to this code ``` class Foo(object): def bar(self): print "in bar!" bar = MyDecorator("foo baby!")(bar) ``` So `MyDecorator.__init__` gets cal...
Conditionally installing importlib on python2.6
9,418,064
5
2012-02-23T17:29:39Z
9,418,401
10
2012-02-23T17:50:26Z
[ "python", "dependencies", "dependency-management", "import" ]
I have a python library that has a dependency on `importlib`. `importlib` is in the standard library in Python 2.7, but is a third-party package for older pythons. I typically keep my dependencies in a pip-style requirements.txt. Of course, if I put `importlib` in here, it will fail if installed on 2.7. How can I condi...
I don't think this is possible with pip and a single requirements file. I can think of two options I'd choose from: ## Multiple requirements files Create a base.txt file that contains most of your packages: ``` # base.txt somelib1 somelib2 ``` And create a requirements file for python 2.6: ``` # py26.txt -r base.t...
Python: Download Returned Zip file from URL
9,419,162
9
2012-02-23T18:42:35Z
14,260,592
28
2013-01-10T14:50:55Z
[ "python", "url", "download", "zip", "urllib" ]
If I have a URL that, when submitted in a web browser, pops up a dialog box to save a zip file...how would I go about catching and downloading this zip file in Python? Thanks!
As far as I can tell, the proper way to do this is: ``` import requests, zipfile, StringIO r = requests.get(zip_file_url, stream=True) z = zipfile.ZipFile(StringIO.StringIO(r.content)) z.extractall() ``` of course you'd want to check that the GET was successful with `r.ok`. For python 3+, sub the StringIO module wit...
3D Contour plot from data using Mayavi / Python
9,419,451
8
2012-02-23T19:02:23Z
9,424,035
8
2012-02-24T01:18:14Z
[ "python", "numpy", "plot", "contour", "mayavi" ]
I would like to do a 3D contour plot using Mayavi in exactly the same way as the third figure on this page (a hydrogen electron cloud model) : <http://www.sethanil.com/python-for-reseach/5> I have a set of data points which I created using my own model which I would like to use. The data points are stored in a multi-...
The trick is to interpolate over a grid before you plot - I'd use `scipy` for this. Below `R` is a (500,3) array of XYZ values and `V` is the "magnitude" at each XYZ point. ``` from scipy.interpolate import griddata import numpy as np # Create some test data, 3D gaussian, 200 points dx, pts = 2, 100j N = 500 R = np....
Is there a version of list.sort() that returns the sorted list?
9,419,689
4
2012-02-23T19:16:53Z
9,419,709
13
2012-02-23T19:18:53Z
[ "python", "list", "sorting", "random", "shuffle" ]
I'm trying to perform an inline operation where I need to sort a list as part of the process. The `sort` function of `list` type objects operates on the list it was called on instead of returning the result. The [Python docs](http://docs.python.org/tutorial/datastructures.html#more-on-lists) confirms this: > **list.s...
There's the built-in [`sorted()`](http://docs.python.org/library/functions.html#sorted): ``` >>> a = sorted(list('hello')) >>> a ['e', 'h', 'l', 'l', 'o'] ``` Also notice that you don't need `list()` anymore: ``` >>> sorted('hello') ['e', 'h', 'l', 'l', 'o'] ``` Since `basesalts` seems to be a list of strings, you ...
Python parser for Python-like language
9,420,400
13
2012-02-23T20:05:48Z
9,420,600
8
2012-02-23T20:19:53Z
[ "python", "parsing", "code-generation" ]
I'm looking to write a Python import filter or preprocessor for source files that are essentially Python with extra language elements. The goal is to read the source file, parse it to an abstract syntax tree, apply some transforms in order to implement the new parts of the language, and write valid Python source which ...
The first thing that comes to mind is [`lib2to3`](http://docs.python.org/library/2to3.html#module-lib2to3). It is a complete pure-Python implementation of a Python parser. It reads a Python grammar file and parses Python source files according to this grammar. It offers a great infrastructure for performing AST manipul...
Is it possible to compile c code using python?
9,420,673
3
2012-02-23T20:24:26Z
9,420,715
8
2012-02-23T20:27:30Z
[ "python", "c", "compiler-construction", "compilation", "compiler-errors" ]
I want to build a python program that get as input a path to .c file and then it compile its. The program will output OK to the screen if the compilation is sucessful , and BAD otherwise. I'm been trying to google it , but couldnot find anything. I've been also trying to run cmd within python with an argument of the ...
Sure, why not? Of course, you'd need GCC installed (or llvm) so you have something to compile with. You can just use os.system, or any of the other ways for calling an external program. Of course, you're probably better off looking at something like [SCons](http://www.scons.org/), which already exists to solve this pr...
Retrieve browser headers in Python
9,420,886
10
2012-02-23T20:39:07Z
9,422,555
20
2012-02-23T22:39:56Z
[ "python", "tornado" ]
I'm currently drawing a blank as how to get the current browser header information for a user in Python Tornado? For example, in PHP you'd simple view the $\_SERVER data. What is Tornado's alternative? Note: [How do I get the client IP of a Tornado request?](http://stackoverflow.com/questions/3110919/how-do-i-get-the-...
Here's a snippet based off of a server I have where we retrieve some header data from the request: ``` class api(tornado.web.RequestHandler): def initialize(self, *args, **kwargs): self.remote_ip = self.request.headers.get('X-Forwarded-For', self.request.headers.get('X-Real-Ip', self.request.remote_ip)) ...
deploying python applications
9,421,373
7
2012-02-23T21:11:44Z
9,421,511
12
2012-02-23T21:21:17Z
[ "python", "deployment" ]
Is it possible to deploy python applications such that you don't release the source code and you don't have to be sure the customer has python installed? I'm thinking maybe there is some installation process that can run a python app from just the .pyc files and a shared library containing the interpreter or something...
1. You protect your source code *legally*, not *technologically*. Distributing py files really isn't a big deal. The only technological solution here is *not* to ship your program (which is really becoming more popular these days, as software is provided over the internet rather than fully installed locally more often....
Django FileField (or ImageField) open() method returns None for valid file?
9,421,797
16
2012-02-23T21:41:54Z
9,422,028
7
2012-02-23T21:57:50Z
[ "python", "django" ]
let me put it like this: model.py: ``` class Task(models.Model): ... seq_file = models.FileField(upload_to='files/', blank=True, null=True) ... ``` ajax.py (I'm using dajaxice but it doesn't matter): ``` ... def startTask(request, name): task = Task.objects.get(task_name=name) data = task.seq_fi...
A [`FileField`](https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField) will give you a file-like object and there is no need to call open() on it. In your example, just call `task.seq_file.file`. Why is that? There are many storage backends for `FileField`, and many of them are not backed...
Django FileField (or ImageField) open() method returns None for valid file?
9,421,797
16
2012-02-23T21:41:54Z
9,422,160
21
2012-02-23T22:09:15Z
[ "python", "django" ]
let me put it like this: model.py: ``` class Task(models.Model): ... seq_file = models.FileField(upload_to='files/', blank=True, null=True) ... ``` ajax.py (I'm using dajaxice but it doesn't matter): ``` ... def startTask(request, name): task = Task.objects.get(task_name=name) data = task.seq_fi...
because open method of models.FileField doesn't return anything you can just use: ``` task.seq_file.read() ``` and you don't need calculate path of file for checking if file exist. you can use task.seq\_file.path: ``` if not os.path.isfile(task.seq_file.path): .... ```
Another Simple Random Walk Simulation Using Python(Two-Dimensional)
9,421,928
6
2012-02-23T21:50:36Z
9,422,166
8
2012-02-23T22:09:56Z
[ "python" ]
I'm trying to solve a two-dimensional random walk problem from the book, exploring python. But, I couldn't figure out how can I solve this problem.I made some research but those were too complicated to understand what is it about. I'm a beginner learner. So, I can't understand the code by looking it. Please explain me ...
I can at least give you a few hints. So you have four possible moves. Each move can be represented by a tuple which is the displacement in the x and y directions: ``` moves = [(0, 1), (1, 0), (0, -1), (-1, 0)] ``` To set the start position in the center: ``` grid_size = 11 x = grid_size // 2 y = grid_size // 2 ``` ...
why does urllib.urlopen(url) fail while urllib2.urlopen(url) works. What specifically about the server response is causing this?
9,422,231
7
2012-02-23T22:15:56Z
9,422,552
7
2012-02-23T22:39:48Z
[ "python", "http", "urllib2", "urllib" ]
I just want a better idea of what's going on here, I can of course "work around" the problem by using urllib2. ``` import urllib import urllib2 url = "http://www.crutchfield.com/S-pqvJFyfA8KG/p_15410415/Dynamat-10415-Xtreme-Speaker-Kit.html" # urllib2 works fine (foo.headers / foo.read() also behave) foo = urllib2.u...
This server is both non-deterministic and sensitive to HTTP version. `urllib2` is HTTP/1.1, `urllib` is HTTP/1.0. You can reproduce this by running `curl --http1.0 -I "http://www.crutchfield.com/S-pqvJFyfA8KG/p_15410415/Dynamat-10415-Xtreme-Speaker-Kit.html"` a few times in a row. You should see the output `curl: (52) ...
Why does tempfile.NamedTemporaryFile() truncate my data?
9,422,478
2
2012-02-23T22:33:46Z
9,422,590
7
2012-02-23T22:42:04Z
[ "python" ]
Here is a test I created to recreate a problem I was having when I used tempfile.NamedTemporaryFile(). The problem is that when I use tempfile the data in my CSV is truncated off the end of the file. When you run this test script, temp2.csv will get truncated and temp1.csv will be the same size as the original CSV. I...
Add temp.flush() after temp.write(data).
Overlapping y-axis tick label and x-axis tick label in matplotlib
9,422,587
33
2012-02-23T22:42:00Z
9,422,835
31
2012-02-23T23:02:58Z
[ "python", "matplotlib" ]
If I create a plot with matplotlib using the following code: ``` import numpy as np from matplotlib import pyplot as plt xx = np.arange(0,5, .5) yy = np.random.random( len(xx) ) plt.plot(xx,yy) plt.imshow() ``` I get a result that looks like the attached image. The problem is the bottom-most y-tick label overlaps the...
In the ticker module there is a class called [MaxNLocator](http://matplotlib.sourceforge.net/api/ticker_api.html#matplotlib.ticker.MaxNLocator) that can take a `prune` kwarg. Using that you can remove the first tick: ``` import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator import numpy as np xx ...
Overlapping y-axis tick label and x-axis tick label in matplotlib
9,422,587
33
2012-02-23T22:42:00Z
20,599,129
13
2013-12-15T20:02:59Z
[ "python", "matplotlib" ]
If I create a plot with matplotlib using the following code: ``` import numpy as np from matplotlib import pyplot as plt xx = np.arange(0,5, .5) yy = np.random.random( len(xx) ) plt.plot(xx,yy) plt.imshow() ``` I get a result that looks like the attached image. The problem is the bottom-most y-tick label overlaps the...
You can pad the ticks on the x-axis: ``` ax.tick_params(axis='x', pad=15) ``` Replace `ax` with `plt.gca()` if you haven't stored the variable `ax` for the current figure. You can also pad both the axes removing the `axis` parameter.
Accessing parent model instance from modelform of admin inline
9,422,735
9
2012-02-23T22:53:47Z
12,053,145
12
2012-08-21T10:39:43Z
[ "python", "django", "django-models", "django-forms" ]
I'm using a TabularInline in Django's admin, configured to show one extra blank form. ``` class MyChildInline(admin.TabularInline): model = MyChildModel form = MyChildInlineForm extra = 1 ``` The model looks like MyParentModel->MyChildModel->MyInlineForm. I'm using a custom form so I can dynamically look...
To pass a value of a formset to the individual forms, you'd have to see how they are constructed. An editor/IDE with "jump to definition" really helps here to dive into the `ModelAdmin` code, and learn about the `inlineformset_factory` and it's `BaseInlineFormSet` class. From there you'll find that the form is constru...
What is the best way to run a django project on aws?
9,423,620
5
2012-02-24T00:27:48Z
9,424,119
11
2012-02-24T01:28:06Z
[ "python", "django", "deployment", "amazon-web-services" ]
How should the project be deployed and run. There are loads of tools in this space. Which should be used and why? * Supervisor * Gunocorn * Ngnix * Fabric * Boto * Pip * Virtualenv * Load balancers
It depends on your configuration. We are using the following stack for our environment on Rackspace, but you can setup the same thing on AWS with EC2 instances. * Ubuntu 11.04 * Varnish (in memory cache) to avoid disk seeks * NginX to server static content * Apache to server dynamic content (MOD-WSGI) * Python 2.7.2 w...
Console windows closes right after I hit ctrl+F5 in visual studio tools for python
9,424,873
7
2012-02-24T03:15:16Z
9,834,430
7
2012-03-23T05:09:06Z
[ "python", "visual-studio-2010", "ptvs" ]
I have installed Python Tools for Visual Studio and I cannot see the output in the console window like I see output when I run a C# console application within visual studio upon hitting the following Shortcut keys. **F5 --** Starts debugging the program and closes the console window in c# and in Python **Ctrl+F5 --*...
There's an option in Tools->Options->Python Tools->Advanced under the Debugging section for "Wait for input when process exits abnormally" and "Wait for input when the process exits normally". I thought they were supposed to be on by default but enabling them should cause it to wait.
Difference between exit(0) and exit(1) in Python
9,426,045
52
2012-02-24T05:49:34Z
9,426,054
90
2012-02-24T05:50:48Z
[ "python", "exit-code" ]
What's the difference between `exit(0)` and `exit(1)` in Python? I tried looking around but didn't find a specific question on these lines. If it's already been answered, a link would be sufficient.
0 and 1 are the exit codes. `exit(0)` means a clean exit without any errors / problems `exit(1)` means there was some issue / error / problem and that is why the program is exiting. This is not Python specific and is pretty common. A non-zero exit code is treated as an abnormal exit, and at times, the error code ind...
Difference between exit(0) and exit(1) in Python
9,426,045
52
2012-02-24T05:49:34Z
9,426,067
9
2012-02-24T05:51:51Z
[ "python", "exit-code" ]
What's the difference between `exit(0)` and `exit(1)` in Python? I tried looking around but didn't find a specific question on these lines. If it's already been answered, a link would be sufficient.
This determines the [exit status](http://en.wikipedia.org/wiki/Exit_status) of the program when it finishes running (generally, 0 for success and 1 for error). It is not unique to Python, and the exact effect depends on your operating system and how the program is called (though 99% of the time, if you're just running...
Ordered tally of the cumulative number of unique words seen by a given position
9,426,805
4
2012-02-24T07:10:27Z
15,064,516
8
2013-02-25T10:10:53Z
[ "python", "list" ]
I have a list of words given below (example): ``` ['the', 'counter', 'starts', 'the', 'starts', 'for'] ``` I want to process this list in order and generate a `pair (x,y)` where x is incremented with each word and y is incremented only when it sees a unique word. So for the given example, my output should be like: ...
try this: ``` >>>from collections import Counter >>>data = ['the', 'counter', 'starts', 'the', 'starts', 'for'] >>>tally=Counter() >>>for elem in data: >>> tally[elem] += 1 >>>tally Counter({'starts': 2, 'the': 2, 'counter': 1, 'for': 1}) ``` from here: <http://docs.python.org/2/library/collections.html> Of cours...
relative path not working even with __init__.py
9,427,037
4
2012-02-24T07:35:27Z
9,427,195
9
2012-02-24T07:49:51Z
[ "python", "import", "package", "importerror" ]
I know that there are plenty of similar questions on stack overflow. But the common answer doesn't seem to be working for me. I have a file structure like this ``` proj/ lib/ __init__.py aa.py bb.py test/ __init__.py aa_test.py ``` I figu...
You need to update your [`sys.path`](http://docs.python.org/library/sys.html#sys.path), which is where python looks for modules, as opposed to your system's path in the current environment, which is what [`os.environ["PATH"]`](http://docs.python.org/library/os.html#os.environ) is referring to. Example: ``` import os,...
Remove duplicate dict in list in Python
9,427,163
32
2012-02-24T07:46:41Z
9,427,216
66
2012-02-24T07:51:31Z
[ "python", "list", "dictionary" ]
I have a list of dicts, and I'd like to remove the dicts with identical key and value pairs. For this list: `[{'a': 123}, {'b': 123}, {'a': 123}]` I'd like to return this: `[{'a': 123}, {'b': 123}]` Another example: For this list: `[{'a': 123, 'b': 1234}, {'a': 3222, 'b': 1234}, {'a': 123, 'b': 1234}]` I'd like to...
Try this: ``` [dict(t) for t in set([tuple(d.items()) for d in l])] ``` The strategy is to convert the list of dictionaries to a list of tuples where the tuples contain the items of the dictionary. Since the tuples can be hashed, you can remove duplicates using `set` and, after that, re-create the dictionaries from t...
Why does calling ffmpeg from python block?
9,428,154
4
2012-02-24T09:16:14Z
9,428,273
7
2012-02-24T09:24:23Z
[ "python", "ffmpeg" ]
I tried 3 methods to call ffmpeg from python, but it always blocks and doesn't return any result. However, if I execute it from shell, it works. For eg: ``` /usr/bin/ffmpeg -y -i /tmp/uploadedfiles/movie8_15_10s.mpg -ar 1600 -ac 1 /tmp/uploadedfiles/movie8_15_10s.mpg.wav ``` this works. However, ``` ffmpeg_com...
You should use [`subprocess.Popen`](http://docs.python.org/library/subprocess.html#subprocess.Popen) instead of `os.popen`. In particular, to get same behaviour, you can run the process through a shell with `shell=True` and gather the output from `stdout` and `stderr` as follows: ``` p = subprocess.Popen(command, she...
Redeclaration of the method "in" within a class
9,428,419
4
2012-02-24T09:35:11Z
9,428,475
11
2012-02-24T09:39:24Z
[ "python", "python-3.x", "adt" ]
I am creating an Abstract Data Type, which create a doubly linked list (not sure it's the correct translation). In it I have create a method \_\_len\_\_ to calcucate the length of it in the correct way, a method \_\_repr\_\_ to represent it correctly, but I wan't now to create a method which, when the user will make so...
Are you looking for [`__contains__`](http://docs.python.org/py3k/reference/datamodel.html#object.__contains__)? > `object.__contains__(self, item)` > > > Called to implement membership test operators. Should return true if *item* is in *self,* false otherwise. For mapping objects, this should consider the keys of the ...
How to make some filters mandatory in tastypie?
9,428,962
9
2012-02-24T10:15:16Z
9,429,687
13
2012-02-24T11:07:23Z
[ "python", "django", "rest", "filtering", "tastypie" ]
``` class LinguistResource(ModelResource): class Meta: model = Linguist queryset = Linguist.objects.all() resource_name = 'linguists_by_language' filtering = { "language": ('exact', ), } ``` Is it possible to make "language" filter mandatory? My goal is raise e...
You can catch this by overriding [build\_filters](http://readthedocs.org/docs/django-tastypie/en/v0.9.10/resources.html#build-filters): ``` from tastypie.exceptions import BadRequest def build_filters(self, filters=None): if 'language' not in filters: raise BadRequest("missing language param") # or mayb...
Networkx - Shortest path length
9,430,027
6
2012-02-24T11:31:55Z
9,431,420
9
2012-02-24T13:16:57Z
[ "python", "networkx" ]
I'm using `networkx` to manage large network graph which consists of 50k nodes. I want to calculate the shortest path length between a specific set of nodes, say N. For that i'm using the `nx.shortest_path_length` function. In some of the nodes from N there might not be a path so networkx is raising and stopping my...
``` import networkx as nx G=nx.Graph() G.add_nodes_from([1,2,3,4]) G.add_edge(1,2) G.add_edge(3,4) try: n=nx.shortest_path_length(G,1,4) print n except nx.NetworkXNoPath: print 'No path' ```
Extracting zip file contents to specific directory in Python 2.7
9,431,918
44
2012-02-24T13:56:11Z
9,432,315
84
2012-02-24T14:25:38Z
[ "python", "windows", "compression" ]
This is the code I am currently using to extract a zip file that lives in the same current working directory as the script. How can I specify a different directory to extract to? The code I tried is not extracting it where I want. ``` import zipfile fh = open('test.zip', 'rb') z = zipfile.ZipFile(fh) for name in z.n...
I think you've just got a mixup here. Should probably be something like the following: ``` import zipfile fh = open('test.zip', 'rb') z = zipfile.ZipFile(fh) for name in z.namelist(): outpath = "C:\\" z.extract(name, outpath) fh.close() ``` and if you just want to extract all the files: ``` import zipfile ...
Extracting zip file contents to specific directory in Python 2.7
9,431,918
44
2012-02-24T13:56:11Z
28,322,611
8
2015-02-04T13:26:10Z
[ "python", "windows", "compression" ]
This is the code I am currently using to extract a zip file that lives in the same current working directory as the script. How can I specify a different directory to extract to? The code I tried is not extracting it where I want. ``` import zipfile fh = open('test.zip', 'rb') z = zipfile.ZipFile(fh) for name in z.n...
I tried the other answers in this thread, but the final solution for me was simply: ``` zfile = zipfile.ZipFile('filename.zip') zfile.extractall(optional_target_folder) ``` Look at [extractall](https://docs.python.org/2/library/zipfile.html#zipfile.ZipFile.extractall), but use it only with trustworthy zip files.
Python: How can I inherit from the built-in list type?
9,432,719
9
2012-02-24T14:50:44Z
9,432,844
14
2012-02-24T14:58:08Z
[ "python", "list", "inheritance", "new-operator" ]
I want to add some attributes to the built-in `list` type, so I wrote this: ``` class MyList(list): def __new__(cls, *args, **kwargs): obj = super(MyList, cls).__new__(cls, *args, **kwargs) obj.append('FirstMen') return obj def __init__(self, *args, **kwargs): self.name = 'West...
The `list` type usually does the actual initialisation of the list inside its `__init__()` method, as it is the convention for mutable types. You only need to overwrite `__new__()` when subtyping immutable types. While you *can* overwrite `__new__()` when subclassing list, there is not much point in doing so for your u...
How to pass members of a dict to a function
9,433,356
4
2012-02-24T15:30:58Z
9,433,369
11
2012-02-24T15:32:08Z
[ "python" ]
Suppose I have a function that I do not control that looks something like the following: ``` def some_func(foo, bar, bas, baz): do_something() return some_val ``` Now I want to call this function passing elements from a dict that contains keys that are identical to the arguments of this function. I could do s...
That's what `**` argument unpacking is for: ``` some_func(**mydict) ``` See also [Unpacking argument lists](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists) in the Python tutorial.
Converting utc time string to datetime object
9,433,851
8
2012-02-24T15:58:13Z
9,434,404
13
2012-02-24T16:31:15Z
[ "python", "python-2.7" ]
I'm using the Paypal API and I get back a timestamp in the following format. It try to parse this to a datetime object using strptime, but I get the following error: ``` (Pdb) datetime.strptime('2012-03-01T10:00:00Z','%Y-%M-%dT%H:%M:%SZ') *** error: redefinition of group name 'M' as group 5; was group 2 ``` Also, as ...
The parser from dateutil is your friend. You'll have to pip install dateutil but you've save bags and bags of date conversion code: ``` pip install python-dateutil ``` You can use it like this. ``` from dateutil import parser ds = '2012-03-01T10:00:00Z' # or any date sting of differing formats. date = parser.parse(...
How does multiprocessing.Manager() work in python?
9,436,757
24
2012-02-24T19:23:24Z
9,436,866
31
2012-02-24T19:30:58Z
[ "python", "multiprocessing" ]
I have a concern about multiprocessing.Manager() in python, here is the example, ``` import multiprocessing def f(ns): ns.x *=10 ns.y *= 10 if __name__ == '__main__': manager = multiprocessing.Manager() ns = manager.Namespace() ns.x = 1 ns.y = 2 print 'before', ns p = multiprocessi...
Manager proxy objects are unable to propagate changes made to mutable objects inside a container. So in other words, if you have a `manager.list()` object, any changes to the managed list itself are propagated to all the other processes. But if you have a list *inside* that list, any changes to the inner list are not p...
How does multiprocessing.Manager() work in python?
9,436,757
24
2012-02-24T19:23:24Z
9,436,927
10
2012-02-24T19:35:52Z
[ "python", "multiprocessing" ]
I have a concern about multiprocessing.Manager() in python, here is the example, ``` import multiprocessing def f(ns): ns.x *=10 ns.y *= 10 if __name__ == '__main__': manager = multiprocessing.Manager() ns = manager.Namespace() ns.x = 1 ns.y = 2 print 'before', ns p = multiprocessi...
`ns` is a NamespaceProxy instance. These objects have special `__getattr__`, `__setattr__`, and `__delattr__` methods that allow values to be shared across processes. In order to take advantage of this mechanism when changing a value, you must trigger `__setattr__`. ``` ns.x.append(10) ``` causes `ns.__getattr__` to ...
Excluding primary key in Django dumpdata with natural keys
9,436,954
4
2012-02-24T19:38:47Z
9,714,117
8
2012-03-15T04:45:58Z
[ "python", "django", "django-models" ]
How do you exclude the primary key from the JSON produced by Django's dumpdata when natural keys are enabled? I've constructed a record that I'd like to "export" so others can use it as a template, by loading it into a separate databases with the same schema without conflicting with other records in the same model. A...
The problem with `json` is that you can't omit the `pk` field since it will be required upon loading of the fixture data again. If not existing, json will fail with ``` $ python manage.py loaddata some_data.json [...] File ".../django/core/serializers/python.py", line 85, in Deserializer data = {Model._meta.pk.attname...
Set of all subsets
9,438,936
10
2012-02-24T22:25:10Z
9,449,081
9
2012-02-25T23:32:08Z
[ "python" ]
In Python2 I could use ``` def subsets(mySet): return reduce(lambda z, x: z + [y + [x] for y in z], mySet, [[]]) ``` to find all subsets of `mySet`. Python 3 has removed `reduce`. What would be an equally concise rewrite of this for Python3?
Here's a [list](http://rosettacode.org/wiki/Power_set#Python) of several possible implementations of the power set (the set of all subsets) algorithm in Python. Some are recursive, some are iterative, some of them don't use `reduce`. Plenty of options to choose from!
comparing python with c/fortran
9,439,869
10
2012-02-25T00:12:03Z
9,443,809
13
2012-02-25T12:04:01Z
[ "python", "c", "performance", "fortran" ]
I wrote the following programs to compare the speed of python with c/fortran. To get the time used by the programs I used the "time" command. All the programs compute the square root of x*x+y*y+z\*z where x,y,z are floats. I used the root square because it is one of the most time consuming parts in scientific computing...
I have recently done [a similar test](http://ilnumerics.net/blog/fast-faster-performance-comparison-c-ilnumerics-fortran-matlab-and-numpy-part-i/) with a more realistic real-world algorithm. It involves numpy, Matlab, FORTRAN and C# (via [ILNumerics](http://ilnumerics.net)). Without specific optimizations, numpy appear...
Django dynamic urls
9,439,899
8
2012-02-25T00:18:24Z
9,439,973
10
2012-02-25T00:27:36Z
[ "python", "django", "django-urls" ]
I am developing a website using Django as the backend, and I want to allow the customer to add new pages using the admin interface - so he enters a page title, an page alias that is used for nicer urls, and chooses whether he wants static content or an article based structure. My approach is the following: I have crea...
You can use [named groups](https://docs.djangoproject.com/en/dev/topics/http/urls/#named-groups) in the urls to pass data to views and it won't require any dynamic updating in the urls. The named part containing `page.alias` will be simply passed as a keyword argument to your view function. You can use it to get the ac...
Solving Systems of Equations with SymPy
9,440,337
6
2012-02-25T01:37:19Z
9,440,633
10
2012-02-25T02:27:14Z
[ "python", "sympy" ]
I'm trying to solve a set of equations with SymPy 0.7.1: ``` from sympy import * equations = [ Eq(S('vf'), S('vi + a*t')), Eq(S('d'), S('vi*t + 1/2*a*t**2')), Eq(S('a'), S('10')), Eq(S('d'), S('60')), Eq(S('vi'), S('5')) ] print solve(equations) ``` produces the correct result, but in a strange or...
I can't figure out the outputs either. Originally I thought the problem was because you were creating new var objects rather than reusing the original ones, but that turned out not to be it. If possible, I'd simply upgrade to 0.7.1-git, where things are much better behaved: ``` >>> import sympy >>> sympy.__version__ '...
Identify contiguous regions in 2D numpy array
9,440,921
7
2012-02-25T03:28:33Z
9,441,457
12
2012-02-25T05:11:59Z
[ "python", "algorithm", "numpy" ]
I have a large `numpy` array that I've applied a filter over. I'd like to identify the contiguous regions in this masked array. Here I'm defining a region to be contiguous if, for any index `(x1,y1)` to any other index `(x2,y2)`, they belong to the same region if there is a path of `True` values along equal integer ste...
You're looking for scipy.ndimage.label more info [here](http://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.measurements.label.html). label returns an array the same shape as the input where each "unique feature has a unique value", so if you want the indices of the features you can do something like: ``...
Flask static_folder hosted on S3
9,441,390
13
2012-02-25T04:58:45Z
13,108,837
7
2012-10-28T12:36:52Z
[ "python", "amazon-s3", "flask", "jinja" ]
I am trying to reroute all of my /static content to host on Amazon S3. My first thought was to use global config['path'] throughout my jinja templates, but this won't work for external css and js files, plus it is kind of messy. I found the static\_folder and static\_url\_path released in 0.7 and this seems like what I...
I recently developed a Flask extension to deal with just this situation. It's called [Flask-S3](https://github.com/e-dard/flask-s3), and you can read the documentation for it [here](http://flask-s3.readthedocs.org/en/latest/). As an example, here is how you would integrate it into your Flask application: ``` from fla...
Python: a better way to write a if-then block with join?
9,441,663
3
2012-02-25T05:49:24Z
9,441,775
9
2012-02-25T06:09:00Z
[ "python" ]
Is there a better way to write this code? I know it's very simple, but the way I wrote it seems so repetitive. I'm not necessary looking for a one-line genius code, just some other readable, useful alternative. Thanks in advance! ``` def __unicode__( self ): location = [] if self.room != None: locat...
*This first part was an answer to the original question if choosing the first non-None element to append. See updates below that address the revised question* Without trying to do a crazy one-line or something too fancy, I think this is a pretty easy solution. Just loop over them and append the first one that is not N...
PyQt mouse events for QTabWidget
9,442,165
4
2012-02-25T07:24:09Z
9,445,581
7
2012-02-25T16:01:20Z
[ "python", "pyqt", "qtabwidget" ]
I want to detect middle mouse clicks on a QTabWidget. I was expecting there to be a mouse event related signal on QWidget, but all I am seeing are methods. Do I need to subclass the QTabWidget and then override said methods in order to do what I want, or am I missing something?
You can either install an event filter on the `QTabBar` (returned by `QTabWidget.tabBar()`) to receive and handle press and release events, or subclass `QTabBar` to redefine `mousePressEvent` and `mouseReleaseEvent` and replace the `QTabBar` of the `QTabWidget` with `QTabWidget.setTabBar()`. 1. Example using the event...
Can sys.argv handle optional arguments?
9,442,313
6
2012-02-25T07:49:28Z
9,442,384
9
2012-02-25T08:01:01Z
[ "python" ]
``` from sys import argv script, lira_cbt, [eur_hedge] = argv if eur_hedge == None: #Do x else: #Do y ``` I want it to be able to run with just lira\_cbt as an argument (doing x), or with both lira\_cbt and eur\_hedge (doing y). Can this be achieved with sys.argv?
Just use the length of `sys.argv` ``` if len(sys.argv) == 2: # do X else: # do Y ```