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
Numpy- weight and sum rows of a matrix
5,069,385
4
2011-02-21T17:52:17Z
5,069,435
8
2011-02-21T17:57:40Z
[ "python", "vector", "matrix", "numpy" ]
Using Python & Numpy, I would like to: * Consider each row of an (n columns x m rows) matrix as a vector * Weight each row (scalar multiplication on each component of the vector) * Add each row to create a final vector (vector addition). The weights are given in a regular numpy array, n x 1, so that each vect...
It will be more convenient to use a two-dimensional `numpy.array` than a `numpy.matrix` in this case. ``` start_matrix = numpy.array([[1,2,3],[4,5,6]]) weights = numpy.array([0.5,-1]) final_vector = (start_matrix.T * weights).sum(axis=1) # array([-3.5, -4. , -4.5]) ``` The multiplication operator `*` does the right t...
Numpy- weight and sum rows of a matrix
5,069,385
4
2011-02-21T17:52:17Z
5,071,162
7
2011-02-21T20:54:33Z
[ "python", "vector", "matrix", "numpy" ]
Using Python & Numpy, I would like to: * Consider each row of an (n columns x m rows) matrix as a vector * Weight each row (scalar multiplication on each component of the vector) * Add each row to create a final vector (vector addition). The weights are given in a regular numpy array, n x 1, so that each vect...
Even a 'technically' correct answer has been all ready given, I'll give my straightforward answer: ``` from numpy import array, dot dot(array([0.5, -1]), array([[1, 2, 3], [4, 5, 6]])) # array([-3.5 -4. -4.5]) ``` This one is much more on with the spirit of linear algebra (and as well those three dotted requirements ...
Scraping data without having to explicitly define each field to be scraped
5,069,416
9
2011-02-21T17:55:19Z
5,077,350
16
2011-02-22T11:13:46Z
[ "python", "scrapy" ]
I want to scrape a page of data (using the Python Scrapy library) without having to define each individual field on the page. Instead I want to dynamically generate fields using the `id` of the element as the field name. At first I was thinking the best way to do this would be to have a pipeline that collects all the ...
## **Update:** The old method didn't work with [item loaders](http://doc.scrapy.org/en/latest/topics/loaders.html) and was complicating things unnecessarily. Here's a better way of achieving a flexible item: ``` from scrapy.item import BaseItem from scrapy.contrib.loader import ItemLoader class FlexibleItem(dict, Ba...
Connecting to EC2 using keypair (.pem file) via Fabric
5,069,895
22
2011-02-21T18:43:33Z
5,071,823
29
2011-02-21T22:09:45Z
[ "python", "fabric" ]
Anyone has any Fabric recipe that shows how to connect to EC2 using the pem file? I tried writing it with this manner: [Python Fabric run command returns "binascii.Error: Incorrect padding"](http://stackoverflow.com/questions/5063796/python-fabric-run-command-returns-binascii-error-incorrect-padding) But I'm faced wi...
Without addressing your encoding issue, you might put your EC2 stuff into an ssh config file: * ~/.ssh/config or, if global: * /etc/ssh\_config There you can specify your host, ip address, user, identify file, etc., so it's a simple matter of: ``` ssh myhost ``` Example: ``` Host myhost User ubuntu HostName ...
Connecting to EC2 using keypair (.pem file) via Fabric
5,069,895
22
2011-02-21T18:43:33Z
5,072,396
30
2011-02-21T23:17:28Z
[ "python", "fabric" ]
Anyone has any Fabric recipe that shows how to connect to EC2 using the pem file? I tried writing it with this manner: [Python Fabric run command returns "binascii.Error: Incorrect padding"](http://stackoverflow.com/questions/5063796/python-fabric-run-command-returns-binascii-error-incorrect-padding) But I'm faced wi...
To use the pem file I generally add the pem to the ssh agent, then simply refer to the username and host: ``` ssh-add ~/.ssh/ec2key.pem fab -H ubuntu@ec2-host deploy ``` or specify the env information (without the key) like the example you linked to: ``` env.user = 'ubuntu' env.hosts = [ 'ec2-host' ] ``` and ru...
Connecting to EC2 using keypair (.pem file) via Fabric
5,069,895
22
2011-02-21T18:43:33Z
12,786,533
9
2012-10-08T17:26:02Z
[ "python", "fabric" ]
Anyone has any Fabric recipe that shows how to connect to EC2 using the pem file? I tried writing it with this manner: [Python Fabric run command returns "binascii.Error: Incorrect padding"](http://stackoverflow.com/questions/5063796/python-fabric-run-command-returns-binascii-error-incorrect-padding) But I'm faced wi...
Another thing you can do is set the key\_filename in the env variable: <http://stackoverflow.com/a/5327496/1729558>
Python code objects - what are they used for?
5,071,117
4
2011-02-21T20:50:05Z
5,071,899
8
2011-02-21T22:18:02Z
[ "python", "types", "internals" ]
What are the uses of [Python code objects](http://docs.python.org/reference/datamodel.html#types)? Besides being used by the interpreter or debugger what other useful usages do they have? Have you interacted directly with code objects? If yes, in what situation?
The primary use of code objects is to separate the static parts of functions (code) from the dynamic parts (functions). Code objects are the things that are stashed in .pyc files, and are created when code is compiled; function objects are created from them at runtime when functions are declared. They're exposed for de...
RAII in Python - automatic destruction when leaving a scope
5,071,121
17
2011-02-21T20:50:22Z
5,071,214
11
2011-02-21T21:00:24Z
[ "python", "scope", "raii", "with-statement" ]
I've been trying to find RAII in Python. Resource Allocation Is Initialization is a pattern in C++ whereby an object is initialized as it is created. If it fails, then it throws an exception. In this way, the programmer knows that the object will never be left in a half-constructed state. Python can do this much. But ...
1. You are right about `with` -- it is completely unrelated to variable scoping. 2. Avoid global variables if you think they are a problem. This includes module level variables. 3. The main tool to hide state in Python are classes. 4. Generator expressions (and in Python 3 also list comprehensions) have their own scope...
RAII in Python - automatic destruction when leaving a scope
5,071,121
17
2011-02-21T20:50:22Z
5,071,376
22
2011-02-21T21:17:07Z
[ "python", "scope", "raii", "with-statement" ]
I've been trying to find RAII in Python. Resource Allocation Is Initialization is a pattern in C++ whereby an object is initialized as it is created. If it fails, then it throws an exception. In this way, the programmer knows that the object will never be left in a half-constructed state. Python can do this much. But ...
**tl;dr** RAII is not possible, you mix it up with scoping in general and when you miss those extra scopes you're probably writing bad code. Perhaps I don't get your question(s), or you don't get some very essential things about Python... First off, deterministic object destruction tied to scope is *impossible* in a g...
python ubuntu virtualenv -> error
5,071,385
8
2011-02-21T21:17:50Z
7,635,915
7
2011-10-03T13:50:18Z
[ "python", "ubuntu", "virtualenv" ]
Newbie here, be kind. The other day I am all: ``` sudo apt-get install python-virtualenv ``` And then I am (following instructions): ``` virtualenv env ``` And Ubuntu 10.10 is like: ``` Traceback (most recent call last): File "/usr/local/bin/virtualenv", line 5, in <module> from pkg_resources import load_en...
Had the same issue after upgrading to Ubuntu 11.04.. Turns out it was only because apt installed python-virtualenv 1.4, which was too old. I removed the deb package and used `pip install` instead and it worked fine. ``` pip install virtualenv ```
Django/Python version of Premailer?
5,071,654
4
2011-02-21T21:48:06Z
5,078,961
8
2011-02-22T13:49:29Z
[ "python", "django", "email" ]
I'm looking to automate the sending of multi-part emails. Now I need to format the text accordingly for both HTML and plaintext versions. [Premailer](http://premailer.dialect.ca/) seems pretty awesome. I especially like how it handles the plaintext version. Anyone know of anything comparable written for Django/Python?
<https://pypi.python.org/pypi/premailer> There is also a barely-supported [Django Premailer](https://github.com/alexhayes/django-premailer) app, for ideas.
How do I deploy a Flask application in IIS?
5,072,166
14
2011-02-21T22:46:28Z
22,107,980
27
2014-02-28T23:48:30Z
[ "python", "iis-6", "wsgi", "flask", "isapi-wsgi" ]
Can anyone help me get a Flask application running on IIS 6? I have tried to use isapi-wsgi, but when I visit the Virtual Directory address I get a page that says "The specified module could not be found." Are there other options for this? Below is the Python script I wrote for isapi-wsgi. The Virtual Directory was ma...
# High Level Overview HTTP -> IIS -> ISAPI -> FastCGI -> WSGI (Flask application) --- # Setup Steps ## Step 1: Install Required Binaries 1. Install Python (2.7 or 3.x -- I used 3.3) 2. Install pip-Win (I used version 1.6) 3. Install pywin32 (I used version 218) 4. Install the IIS FastCGI extension with [fcgisetup ...
django admin: how to make a readonly url field clickable in change_form.html?
5,072,189
9
2011-02-21T22:49:59Z
15,683,721
8
2013-03-28T13:54:52Z
[ "python", "django", "django-admin" ]
I want to make a readonly URL field clickable in the admin on a change\_form page. I tried a widget, but soon realized widgets are for form fields only. So, before I try to solve this problem with jQuery (find and replace or something), I would like to know if there is a more elegant solution for this in python. Any id...
Old question, but still deserves an answer. [Ref the doc](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.readonly_fields), `readonly_fields` also supports those customization ways now, works just as [the link](http://stackoverflow.com/questions/1949248/how-to-add-clickable-lin...
How do you directly overlay a scatter plot on top of a jpg image in matplotlib / Python?
5,073,386
13
2011-02-22T02:21:20Z
5,073,509
21
2011-02-22T02:47:43Z
[ "python", "image", "matplotlib", "overlay", "plot" ]
I need to rapidly plot jpg frames that result as the output of a tracking algorithm. Companion with the jpg frames are text files containing simple (x,y) data locating the image targets that are being tracked. I would like to use matplotlib to plot the jpg images, then overlay a scatter plot of the (x,y) data which get...
The `pyplot.scatter()` function was tailor made for this reason: ``` import matplotlib.pyplot as plt im = plt.imread(image_name) implot = plt.imshow(im) # put a blue dot at (10, 20) plt.scatter([10], [20]) # put a red dot, size 40, at 2 locations: plt.scatter(x=[30, 40], y=[50, 60], c='r', s=40) plt.show() ``` See...
in python, how do I check to see if keys in a dictionary all have the same value x?
5,073,624
5
2011-02-22T03:12:13Z
5,073,649
16
2011-02-22T03:17:19Z
[ "python", "list", "dictionary", "unique" ]
I have a dictionary list in my python code and I'm trying to check for the rare occurance of all keys having the same numerical value say 1. How would I go about doing this in an efficient manner?
I will assume you meant the same **value**: ``` d = {'a':1, 'b':1, 'c':1} len(set(d.values()))==1 # -> True ``` If you want to check for a specific value, how about ``` testval = 1 all(val==testval for val in d.values()) # -> True ``` this code will most often fail early (quickly)
How can I efficiently process a numpy array in blocks similar to Matlab's blkproc (blockproc) function
5,073,767
19
2011-02-22T03:42:35Z
5,073,886
9
2011-02-22T04:10:05Z
[ "python", "matlab", "image-processing", "numpy", "scipy" ]
I'm looking for a good approach for efficiently dividing an image into small regions, processing each region separately, and then re-assembling the results from each process into a single processed image. Matlab had a tool for this called [blkproc](http://nf.nci.org.au/facilities/software/Matlab/toolbox/images/blkproc....
Process by slices/views. Concatenation is very expensive. ``` for x in xrange(0, 160, 16): for y in xrange(0, 160, 16): view = A[x:x+16, y:y+16] view[:,:] = fun(view) ```
How can I efficiently process a numpy array in blocks similar to Matlab's blkproc (blockproc) function
5,073,767
19
2011-02-22T03:42:35Z
5,078,155
16
2011-02-22T12:34:29Z
[ "python", "matlab", "image-processing", "numpy", "scipy" ]
I'm looking for a good approach for efficiently dividing an image into small regions, processing each region separately, and then re-assembling the results from each process into a single processed image. Matlab had a tool for this called [blkproc](http://nf.nci.org.au/facilities/software/Matlab/toolbox/images/blkproc....
Here are some examples of a different (loop free) way to work with blocks: ``` import numpy as np from numpy.lib.stride_tricks import as_strided as ast A= np.arange(36).reshape(6, 6) print A #[[ 0 1 2 3 4 5] # [ 6 7 8 9 10 11] # ... # [30 31 32 33 34 35]] # 2x2 block view B= ast(A, shape= (3, 3, 2, 2), strid...
What is __return__?
5,073,911
12
2011-02-22T04:14:23Z
18,674,516
8
2013-09-07T14:51:26Z
[ "python" ]
I am debugging a script in Python 3.1 and discovered this: > (Pdb) p locals() > {'count': 264, 'self': , 'depth': 1, 'offset': 0, **'\_\_return\_\_': None,** 'blkno': 4, 'size': 264} I found [deferred PEP](http://www.python.org/dev/peps/pep-0316/) that mentions it, and little else. **What is `__return__`?** When was...
It is a **return value** of a function call when the **pdb debugger** stops after evaluating the return command. Is is very important for a return expressions with any side effect (that can't be reproduced like e.g. reading a line from pipe). ``` (Pdb) ... some breakpoint ... > test.py(3)f() -> return x + 1 (Pdb) l 1 ...
Convert zero-padded bytes to UTF-8 string
5,074,043
9
2011-02-22T04:36:17Z
5,074,089
8
2011-02-22T04:43:34Z
[ "python", "unicode", "utf-8", "byte", "strncpy" ]
I'm [unpacking](http://docs.python.org/dev/library/struct.html#struct.unpack) several structs that contain [`'s'`](http://docs.python.org/dev/library/struct.html#format-characters) type fields from C. The fields contain zero-padded UTF-8 strings handled by [`strncpy`](http://linux.die.net/man/3/strncpy) in the C code (...
Use [`str.rstrip()`](http://docs.python.org/library/stdtypes.html#str.rstrip) to remove the trailing NULs: ``` >>> 'hiya\0\0\0'.rstrip('\0') 'hiya' ```
Convert zero-padded bytes to UTF-8 string
5,074,043
9
2011-02-22T04:36:17Z
5,076,070
11
2011-02-22T09:02:52Z
[ "python", "unicode", "utf-8", "byte", "strncpy" ]
I'm [unpacking](http://docs.python.org/dev/library/struct.html#struct.unpack) several structs that contain [`'s'`](http://docs.python.org/dev/library/struct.html#format-characters) type fields from C. The fields contain zero-padded UTF-8 strings handled by [`strncpy`](http://linux.die.net/man/3/strncpy) in the C code (...
Either `rstrip` or `replace` will only work if the string is padded out to the end of the buffer with nulls. In practice the buffer may not have been initialised to null to begin with so you might get something like `b'hiya\0x\0'`. If you know categorically 100% that the C code starts with a null initialised buffer an...
Python unexpected EOF while parsing
5,074,225
34
2011-02-22T05:04:33Z
5,074,243
10
2011-02-22T05:06:47Z
[ "python", "eof", "python-2.x" ]
Here's my python code. Could someone show me what's wrong with it. ``` while 1: date=input("Example: March 21 | What is the date? ") if date=="June 21": sd="23.5° North Latitude" if date=="March 21" | date=="September 21": sd="0° Latitude" if date=="December 21": sd="23.5° South Latitude" if sd: pri...
**Indent it!** first. That would take care of your `SyntaxError`. Apart from that there are couple of other problems in your program. * Use `raw_input` when you want accept string as an input. `input` takes only Python expressions and it does an `eval` on them. * You are using certain 8bit characters in your script l...
Python unexpected EOF while parsing
5,074,225
34
2011-02-22T05:04:33Z
5,074,256
51
2011-02-22T05:08:34Z
[ "python", "eof", "python-2.x" ]
Here's my python code. Could someone show me what's wrong with it. ``` while 1: date=input("Example: March 21 | What is the date? ") if date=="June 21": sd="23.5° North Latitude" if date=="March 21" | date=="September 21": sd="0° Latitude" if date=="December 21": sd="23.5° South Latitude" if sd: pri...
use `raw_input` instead of `input` :) > If you use `input`, then the data you > type is is interpreted as a **Python > Expression** which means that you > end up with gawd knows what type of > object in your target variable, and a > heck of a wide range of exceptions > that can be generated. So you should > **NOT** us...
Django, JQuery, and autocomplete
5,074,329
16
2011-02-22T05:21:45Z
5,074,873
9
2011-02-22T06:36:55Z
[ "jquery", "python", "django", "autocomplete" ]
After some extensive research (googling), I cannot find a current tutorial on how to set up autocomplete using Django and JQuery. There appears to be a variety of plugins and there appears to be no consistency or standard about which to use or when. I'm not a pro at either Django or JQuery, but need an autocomplete so...
If you're looking to search from within your django models then something like: ``` from django.utils import simplejson def autocompleteModel(request): search_qs = ModelName.objects.filter(name__startswith=request.REQUEST['search']) results = [] for r in search_qs: results.append(r.name) re...
Match first instance of Python regex search
5,074,331
17
2011-02-22T05:21:50Z
5,074,346
40
2011-02-22T05:23:55Z
[ "python", "regex" ]
I'm looking to the first instance of a match two square brackets using regular expressions. Currently, I am doing ``` regex = re.compile("(?<=(\[\[)).*(?=\]\])") r = regex.search(line) ``` which works for lines like ``` [[string]] ``` returns `string` but when I try it on a separate line: ``` [[string]] ([[string...
**Python regular expressions are greedy** Python regular expressions will match as much as they can by default. In your case, this means the first set of brackets and the last. In python, you can make it non-greedy by adding a '?' after the greedy part of the expression. In your case, this would translate to `.*?` in ...
Retrieving parameters from a URL
5,074,803
60
2011-02-22T06:27:16Z
5,075,477
86
2011-02-22T07:54:22Z
[ "python", "django", "parsing", "url" ]
Given a URL like the following, how can I parse the value of the query parameters? For example, in this case I want the value of `def`. ``` /abc?def='ghi' ``` I am using Django in my environment; is there a method on the `request` object that could help me? I tried using `self.request.get('def')` but it is not retur...
Try with something like this: ``` import urlparse url = 'http://foo.appspot.com/abc?def=ghi' parsed = urlparse.urlparse(url) print urlparse.parse_qs(parsed.query)['def'] ```
Retrieving parameters from a URL
5,074,803
60
2011-02-22T06:27:16Z
14,633,704
31
2013-01-31T19:33:48Z
[ "python", "django", "parsing", "url" ]
Given a URL like the following, how can I parse the value of the query parameters? For example, in this case I want the value of `def`. ``` /abc?def='ghi' ``` I am using Django in my environment; is there a method on the `request` object that could help me? I tried using `self.request.get('def')` but it is not retur...
``` import urlparse url = 'http://example.com/?q=abc&p=123' par = urlparse.parse_qs(urlparse.urlparse(url).query) print par['q'], par['p'] ```
Retrieving parameters from a URL
5,074,803
60
2011-02-22T06:27:16Z
22,109,957
10
2014-03-01T04:06:16Z
[ "python", "django", "parsing", "url" ]
Given a URL like the following, how can I parse the value of the query parameters? For example, in this case I want the value of `def`. ``` /abc?def='ghi' ``` I am using Django in my environment; is there a method on the `request` object that could help me? I tried using `self.request.get('def')` but it is not retur...
I know this is a bit late but since I found myself on here today, I thought that this might be a useful answer for others. ``` import urlparse url = 'http://example.com/?q=abc&p=123' parsed = urlparse.urlparse(url) params = urlparse.parse_qsl(parsed.query) for x,y in params: print "Parameter = "+x,"Value = "+y ```...
Regular expression to remove line breaks
5,075,247
7
2011-02-22T07:25:04Z
5,075,283
16
2011-02-22T07:28:45Z
[ "python", "regex", "python-2.7" ]
I am a complete newbie to Python, and I'm stuck with a regex problem. I'm trying to remove the line break character at the end of each line in a text file, but only if it follows a lowercase letter, i.e. `[a-z]`. If the end of the line ends in a lower case letter, I want to replace the line break/newline character with...
Try ``` re.sub(r"(?<=[a-z])\r?\n"," ", textblock) ``` `\Z` only matches at the end of the string, after the last linebreak, so it's definitely not what you need here. `\z` is not recognized by the Python regex engine. `(?<=[a-z])` is a [positive lookbehind assertion](http://www.regular-expressions.info/lookaround.ht...
Installing PIL to use with Django on Mac OS X
5,075,620
16
2011-02-22T08:14:50Z
5,079,482
12
2011-02-22T14:37:46Z
[ "python", "django", "osx", "python-imaging-library" ]
I'm really annoyed by installation of PIL (Python Imaging Library) on Mac OS X 10.6. Does anyone have it installed and could post the recipe here? I've tried a lot of them posted here on this site and a lot from google, but always anding with missing some part and can't work normally with PIL... Thanks in advance. Ign...
**EDIT:** This answer has been getting voted up recently, and I want to modify it to reflect what I'm doing now. Firstly, I've switched from MacPorts to [Homebrew](http://mxcl.github.com/homebrew/) for package management on Mac OS X. Secondly, I've switched from using my package manager to using [pip](http://www.pip-i...
Installing PIL to use with Django on Mac OS X
5,075,620
16
2011-02-22T08:14:50Z
6,898,937
14
2011-08-01T13:16:24Z
[ "python", "django", "osx", "python-imaging-library" ]
I'm really annoyed by installation of PIL (Python Imaging Library) on Mac OS X 10.6. Does anyone have it installed and could post the recipe here? I've tried a lot of them posted here on this site and a lot from google, but always anding with missing some part and can't work normally with PIL... Thanks in advance. Ign...
Following steps worked for me: ``` $ brew install pip $ export ARCHFLAGS="-arch i386 -arch x86_64" $ pip install pil ```
In Python, is read() , or readlines() faster?
5,076,024
15
2011-02-22T08:59:49Z
5,076,078
12
2011-02-22T09:03:54Z
[ "python", "io" ]
I want to read a huge file in my code. Is read() or readline() faster for this. How about the loop: ``` for line in fileHandle ```
If file is huge, read() is definitevely bad idea, as it loads (without size parameter), whole file into memory. Readline reads only one line at time, so I would say that is better choice for huge files. And just iterating over file object should be as effective as using readline. See <http://docs.python.org/tutorial...
In Python, is read() , or readlines() faster?
5,076,024
15
2011-02-22T08:59:49Z
5,076,086
19
2011-02-22T09:04:41Z
[ "python", "io" ]
I want to read a huge file in my code. Is read() or readline() faster for this. How about the loop: ``` for line in fileHandle ```
For a text file just iterating over it with a `for` loop is almost always the way to go. Never mind about speed, it is the cleanest. In some versions of python `readline()` really does just read a single line while the `for` loop reads large chunks and splits them up into lines so it may be faster. I think that more r...
In Python, is read() , or readlines() faster?
5,076,024
15
2011-02-22T08:59:49Z
5,077,872
7
2011-02-22T12:03:24Z
[ "python", "io" ]
I want to read a huge file in my code. Is read() or readline() faster for this. How about the loop: ``` for line in fileHandle ```
The docs for [readlines](http://docs.python.org/library/stdtypes.html#file.readlines) indicate there is an optional sizehint. Because it is so vague, it's easy to overlook, but I found this to often be the fastest way to read files. Use readlines(1), which hints one line, but in fact reads in about 4k or 8k worth of li...
Reading e-mails from Outlook with Python through MAPI
5,077,625
17
2011-02-22T11:42:27Z
15,904,604
25
2013-04-09T14:24:26Z
[ "python", "outlook", "exchange-server", "mapi", "cdo.message" ]
I'm trying to write a short program that will read in the contents of e-mails within a folder on my exchange/Outlook profile so I can manipulate the data. However I'm having a problem finding much information about python and exchange/Outlook integration. A lot of stuff is either very old/has no docs/not explained. I'v...
I had the same problem you did - didn't find much that worked. The following code, however, works like a charm. ``` import win32com.client outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case, ...
Which is the best approach of this data structure in python?
5,077,941
2
2011-02-22T12:11:58Z
5,078,147
8
2011-02-22T12:34:05Z
[ "python", "data-structures" ]
I have the following situation in python: I am parsing an ontology and i want to keep track of some properties of the ontology and build a data structure with the below characteristics: -there will be a single key to access each value -the value would be another key-value data structure with the following 3 enties: ...
"Lines of code" is probably not the best metric to optimize. This looks like a classic example of outgrowing a "dictionaries and lists" solution. I've been there many times. Use a class, it will let you write understandable maintainable code, with named methods for manipulating your data structure. This will give you ...
Using python to return a list of squared integers
5,079,094
3
2011-02-22T14:00:50Z
5,079,152
15
2011-02-22T14:06:16Z
[ "python", "list" ]
I'm looking to write a function that takes the integers within a list, such as [1, 2, 3], and returns a new list with the squared integers; [1, 4, 9] How would I go about this? PS - just before I was about to hit submit I noticed Chapter 14 of O'Reilly's 'Learning Python' seems to provide the explanation I'm looking ...
You can (and should) use [**list comprehension**](http://docs.python.org/tutorial/datastructures.html#list-comprehensions): ``` squared = [x**2 for x in lst] ``` `map` makes one function call per element and while `lambda` expressions are quite handy, using `map` + `lambda` is mostly slower than list comprehension. ...
Using python to return a list of squared integers
5,079,094
3
2011-02-22T14:00:50Z
5,079,239
9
2011-02-22T14:15:08Z
[ "python", "list" ]
I'm looking to write a function that takes the integers within a list, such as [1, 2, 3], and returns a new list with the squared integers; [1, 4, 9] How would I go about this? PS - just before I was about to hit submit I noticed Chapter 14 of O'Reilly's 'Learning Python' seems to provide the explanation I'm looking ...
Besides lambda and list comprehensions, you can also use generators. List comprehension calculates all the squares when it's called, generators calculate each square as you iterate through the list. Generators are better when input size is large or when you're only using some initial part of the results. ``` def gener...
Best approach to use jira programatically
5,079,541
5
2011-02-22T14:43:29Z
14,101,218
10
2012-12-31T11:51:00Z
[ "c#", "python", "jira" ]
I would like to be able to create/assign/and close jira tickets or entries programatically.. I was able to google and found that jira has command line tools available as well as a soap API. Suggestions on what approach would be the best? thanks
In c# I have been using the following dot net lib: <https://bitbucket.org/farmas/atlassian.net-sdk>
Methods with the same name in one class in python?
5,079,609
11
2011-02-22T14:48:36Z
5,079,643
9
2011-02-22T14:51:24Z
[ "python", "overloading" ]
How to declare few methods with the same name ,but with different numbers of parameters or different types in one class? What I must to change in this class: ``` class MyClass: """""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" ...
You can't. There are not overloads or multimethods or similar things. One name refers to one thing. As far as the language is concerned anyway, you can always emulate them yourself... You *could* check types with `isinstance` (but please do it properly - e.g. in Python 2, use `basestring` to detect both strings and uni...
Methods with the same name in one class in python?
5,079,609
11
2011-02-22T14:48:36Z
5,079,766
22
2011-02-22T14:59:19Z
[ "python", "overloading" ]
How to declare few methods with the same name ,but with different numbers of parameters or different types in one class? What I must to change in this class: ``` class MyClass: """""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" ...
You can have a function that takes in variable number of arguments. ``` def my_method(*args, **kwds): # do something # when you call the method my_method(a1, a2, k1=a3, k2=a4) # you get: args = (a1, a2) kwds = {'k1':a3, 'k2':a4} ``` So you can modify your function as follows: ``` def my_method(*args): if ...
Python/Matplotlib - Adjusting the spacing between the edge of the plot and the x-axis
5,080,058
10
2011-02-22T15:23:15Z
5,081,329
9
2011-02-22T17:04:05Z
[ "python", "matplotlib" ]
How can I adjust the amount of space between the x-axis and the edge of the plot window? My x-axis labels are oriented vertically and they are running off of the edge of the window that Matplotlib draws. Here's some example code: ``` import matplotlib.pyplot as plt x=[1,2,3,4,5] y=[1,2,3,4,5] plt.plot(x,y) plt.xticks...
As Paul said, you are using figures. You can get a reference to the current figure with gcf() and then set the spacing as per the [FAQ](http://matplotlib.sourceforge.net/faq/howto_faq.html#move-the-edge-of-an-axes-to-make-room-for-tick-labels). I've added two lines to your code: ``` import matplotlib.pyplot as plt x=[...
How to group the choices in a Django Select widget?
5,080,828
16
2011-02-22T16:22:37Z
5,081,418
10
2011-02-22T17:12:00Z
[ "python", "django", "widget" ]
Is it possible to created *named choice groups* in a Django select (dropdown) widget, when that widget is on a form that is *auto-generated* from a data Model? Can I create the widget on the left-side picture below? ![Two widgets with one grouped](http://i.stack.imgur.com/o54cq.png) My first experiment in creating a ...
After a quick look at the ModelChoiceField code in django.forms.models, I'd say try extending that class and override its choice property. Set up the property to return a custom iterator, based on the orignial ModelChoiceIterator in the same module (which returns the tuple you're having trouble with) - a new GroupedMo...
Modifying DYLD_LIBRARY_PATH for mysql, python, and django
5,081,574
9
2011-02-22T17:25:27Z
5,347,328
7
2011-03-18T02:15:16Z
[ "python" ]
I've seen two dozen posts concerning this issue, but I'm so NOOB I'm not sure how to modify everything correctly. I'm attempting to finish the installation, but when I go to Python and "import MySQLdb" I end up getting: ``` ImportError: dlopen(/Users/pccampbell/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.5-fat3.e...
add the export command to /etc/profile as follows: ``` export DYLD_LIBRARY_PATH=/usr/local/mysql/lib ``` Note:There is no "/" after lib above. If you add / after lib, and try installing MySQL-python, the errors will keep occuring when running ">>import MySQLdb" I hope this solves the problem for you! :-)
Modifying DYLD_LIBRARY_PATH for mysql, python, and django
5,081,574
9
2011-02-22T17:25:27Z
8,609,135
14
2011-12-22T20:04:25Z
[ "python" ]
I've seen two dozen posts concerning this issue, but I'm so NOOB I'm not sure how to modify everything correctly. I'm attempting to finish the installation, but when I go to Python and "import MySQLdb" I end up getting: ``` ImportError: dlopen(/Users/pccampbell/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.5-fat3.e...
According to Matt's idea, in mac os x Lion, you should add the following sentence like this to your /etc/profile: ``` export DYLD_LIBRARY_PATH=/usr/local/mysql/lib:$DYLD_LIBRARY_PATH ```
How do I prevent a C shared library to print on stdout in python?
5,081,657
28
2011-02-22T17:32:35Z
5,103,455
15
2011-02-24T10:37:23Z
[ "python", "ctypes" ]
I work with a python lib that imports a C shared library that prints on stdout. I want a clean output in order to use it with pipes or to redirect in files. The prints are done outside of python, in the shared library. At the beginning, my approach was: ``` # file: test.py import os from ctypes import * from tempfile...
Yeah, you really want to use `os.dup2` instead of `os.dup`, like your second idea. Your code looks somewhat roundabout. Don't muck about with `/dev` entries except for `/dev/null`, it's unnecessary. It's also unnecessary to write anything in C here. The trick is to save the `stdout` fdes using `dup`, then pass it to `...
How do I prevent a C shared library to print on stdout in python?
5,081,657
28
2011-02-22T17:32:35Z
14,797,594
8
2013-02-10T12:13:57Z
[ "python", "ctypes" ]
I work with a python lib that imports a C shared library that prints on stdout. I want a clean output in order to use it with pipes or to redirect in files. The prints are done outside of python, in the shared library. At the beginning, my approach was: ``` # file: test.py import os from ctypes import * from tempfile...
Combining both answers - <http://stackoverflow.com/a/5103455/1820106> & <http://stackoverflow.com/a/4178672/1820106> to context manager that blocks print to stdout only for its scope (the code in the first answer blocked any external output, the latter answer missed the sys.stdout.flush() at end): ``` class HideOutput...
How do I prevent a C shared library to print on stdout in python?
5,081,657
28
2011-02-22T17:32:35Z
17,954,769
13
2013-07-30T18:34:46Z
[ "python", "ctypes" ]
I work with a python lib that imports a C shared library that prints on stdout. I want a clean output in order to use it with pipes or to redirect in files. The prints are done outside of python, in the shared library. At the beginning, my approach was: ``` # file: test.py import os from ctypes import * from tempfile...
Based on [@Yinon Ehrlich's answer](http://stackoverflow.com/a/14797594/4279). This variant tries to avoid leaking file descriptors: ``` import os import sys from contextlib import contextmanager @contextmanager def stdout_redirected(to=os.devnull): ''' import os with stdout_redirected(to=filename): ...
How to create a stock quote fetching app in python
5,081,710
11
2011-02-22T17:37:47Z
5,081,774
12
2011-02-22T17:45:03Z
[ "python", "google-finance" ]
I'm quite new to programming in **Python**. I want to make an application which will **fetch stock prices** from [google finance](http://www.google.com/finance). One example is CSCO *(Cisco Sytems)*. I would then use that data to **warn the user when the stock reaches a certain value**. It also needs to **refresh ever...
This module comes courtesy of [Corey Goldberg](http://www.goldb.org/goldblog/2007/09/14/PythonStockQuoteModule.aspx). Program: ``` import urllib import re def get_quote(symbol): base_url = 'http://finance.google.com/finance?q=' content = urllib.urlopen(base_url + symbol).read() m = re.search('id="ref_694...
How to create a stock quote fetching app in python
5,081,710
11
2011-02-22T17:37:47Z
28,834,238
10
2015-03-03T14:25:20Z
[ "python", "google-finance" ]
I'm quite new to programming in **Python**. I want to make an application which will **fetch stock prices** from [google finance](http://www.google.com/finance). One example is CSCO *(Cisco Sytems)*. I would then use that data to **warn the user when the stock reaches a certain value**. It also needs to **refresh ever...
As for now (2015), the google finance api is deprecated. But you may use the pypi module [googlefinance](https://pypi.python.org/pypi/googlefinance/0.4). Install googlefinance ``` $pip install googlefinance ``` It is easy to get current stock price: ``` >>> from googlefinance import getQuotes >>> import json >>> pr...
ctypes - Beginner
5,081,875
41
2011-02-22T17:54:25Z
5,082,294
120
2011-02-22T18:33:48Z
[ "python", "python-3.x", "ctypes" ]
I have the task of "wrapping" a c library into a python class. The docs are incredibly vague on this matter. It seems they expect only advanced python users would implement ctypes. Well i'm a beginner in python and need help. Some step by step help would be wonderful. So I have my c library. What do I do? What files ...
Here's a quick and dirty ctypes tutorial. First, write your C library. Here's a simple Hello world example: ### testlib.c ``` #include <stdio.h> void myprint(void); void myprint() { printf("hello world\n"); } ``` Now compile it as a shared library ([mac fix found here](http://stackoverflow.com/questions/45807...
ctypes - Beginner
5,081,875
41
2011-02-22T17:54:25Z
5,082,460
8
2011-02-22T18:47:44Z
[ "python", "python-3.x", "ctypes" ]
I have the task of "wrapping" a c library into a python class. The docs are incredibly vague on this matter. It seems they expect only advanced python users would implement ctypes. Well i'm a beginner in python and need help. Some step by step help would be wonderful. So I have my c library. What do I do? What files ...
Firstly: The `>>>` code you see in python examples is a way to indicate that it is Python code. It's used to separate Python code from output. Like this: ``` >>> 4+5 9 ``` Here we see that the line that starts with `>>>` is the Python code, and 9 is what it results in. This is exactly how it looks if you start a Pyth...
Help with __add__
5,082,190
27
2011-02-22T18:25:01Z
5,082,229
67
2011-02-22T18:28:59Z
[ "python" ]
I am trying to understand how `__add__` works: ``` class MyNum: def __init__(self,num): self.num=num def __add__(self,other): return MyNum(self.num+other.num) def __str__(self): return str(self.num) ``` If I put them in a list ``` d=[MyNum(i) for i in range(10)] ``` this works `...
You need to define `__radd__` as well to get this to work. `__radd__` is *reverse add*. When Python tries to evaluate `x + y` it first attempts to call `x.__add__(y)`. If this fails then it falls back to `y.__radd__(x)`. This allows you to override addition by only touching one class. Consider for example how Python ...
Help with __add__
5,082,190
27
2011-02-22T18:25:01Z
5,082,240
13
2011-02-22T18:30:10Z
[ "python" ]
I am trying to understand how `__add__` works: ``` class MyNum: def __init__(self,num): self.num=num def __add__(self,other): return MyNum(self.num+other.num) def __str__(self): return str(self.num) ``` If I put them in a list ``` d=[MyNum(i) for i in range(10)] ``` this works `...
``` >>> help(sum) Help on built-in function sum in module __builtin__: sum(...) sum(sequence[, start]) -> value Returns the sum of a sequence of numbers (NOT strings) plus the value of parameter 'start' (which defaults to 0). When the sequence is empty, returns start. ``` In other words, provide a s...
How can I make a large python data structure more efficient to unpickle?
5,082,451
2
2011-02-22T18:46:40Z
5,082,556
10
2011-02-22T18:55:36Z
[ "python", "performance", "serialization", "pickle" ]
I have a list of ~1.7 million "token" objects, along with a list of ~130,000 "structure" objects which reference the token objects and group them into, well, structures. It's an ~800MB memory footprint, on a good day. I'm using `__slots__` to keep my memory footprint down, so my `__getstate__` returns a tuple of seria...
Pickle is not the best method for storing large amounts of similar data. It can be slow for large data sets, and more importantly, it is very fragile: changing around your source can easily break all existing datasets. (I would recommend reading what pickle at its heart actually is: a bunch of bytecode expressions. It ...
Python string formatting: % vs. .format
5,082,452
849
2011-02-22T18:46:42Z
5,082,482
624
2011-02-22T18:49:21Z
[ "python", "performance", "logging", "string-formatting" ]
Python 2.6 introduced the [`str.format()`](https://docs.python.org/2/library/stdtypes.html#str.format) method with a slightly different syntax from the existing `%` operator. Which is better and for what situations? 1. The following uses each method and has the same outcome, so what is the difference? ``` #!/us...
To answer your first question... `.format` just seems more sophisticated in many ways. An annoying thing about `%` is also how it can either take a variable or a tuple. You'd think the following would always work: ``` "hi there %s" % name ``` yet, if `name` happens to be `(1, 2, 3)`, it will throw a `TypeError`. To g...
Python string formatting: % vs. .format
5,082,452
849
2011-02-22T18:46:42Z
5,082,809
97
2011-02-22T19:21:07Z
[ "python", "performance", "logging", "string-formatting" ]
Python 2.6 introduced the [`str.format()`](https://docs.python.org/2/library/stdtypes.html#str.format) method with a slightly different syntax from the existing `%` operator. Which is better and for what situations? 1. The following uses each method and has the same outcome, so what is the difference? ``` #!/us...
Assuming you're using Python's `logging` module, you can pass the string formatting arguments as arguments to the `.debug()` method rather than doing the formatting yourself: ``` log.debug("some debug info: %s", some_info) ``` which avoids doing the formatting unless the logger actually logs something.
Python string formatting: % vs. .format
5,082,452
849
2011-02-22T18:46:42Z
6,334,743
11
2011-06-13T18:43:10Z
[ "python", "performance", "logging", "string-formatting" ]
Python 2.6 introduced the [`str.format()`](https://docs.python.org/2/library/stdtypes.html#str.format) method with a slightly different syntax from the existing `%` operator. Which is better and for what situations? 1. The following uses each method and has the same outcome, so what is the difference? ``` #!/us...
`%` gives much better performance than `format` from my test. `format` runs twice slower than `%`
Python string formatting: % vs. .format
5,082,452
849
2011-02-22T18:46:42Z
6,335,836
210
2011-06-13T20:20:32Z
[ "python", "performance", "logging", "string-formatting" ]
Python 2.6 introduced the [`str.format()`](https://docs.python.org/2/library/stdtypes.html#str.format) method with a slightly different syntax from the existing `%` operator. Which is better and for what situations? 1. The following uses each method and has the same outcome, so what is the difference? ``` #!/us...
Something that the modulo operator ( % ) can't do, afaik: ``` tu = (12,45,22222,103,6) print '{0} {2} {1} {2} {3} {2} {4} {2}'.format(*tu) ``` result ``` 12 22222 45 22222 103 22222 6 22222 ``` Very useful. Another point: `format()`, being a function, can be used as an argument in other functions: ``` li = [12,45...
Python string formatting: % vs. .format
5,082,452
849
2011-02-22T18:46:42Z
6,893,888
47
2011-08-01T03:01:34Z
[ "python", "performance", "logging", "string-formatting" ]
Python 2.6 introduced the [`str.format()`](https://docs.python.org/2/library/stdtypes.html#str.format) method with a slightly different syntax from the existing `%` operator. Which is better and for what situations? 1. The following uses each method and has the same outcome, so what is the difference? ``` #!/us...
Also, [PEP 3101](http://www.python.org/dev/peps/pep-3101/) proposes the replacement of the `%` operator with the new, advanced string formatting in Python 3, where it would be the default.
Python string formatting: % vs. .format
5,082,452
849
2011-02-22T18:46:42Z
12,252,460
42
2012-09-03T18:15:42Z
[ "python", "performance", "logging", "string-formatting" ]
Python 2.6 introduced the [`str.format()`](https://docs.python.org/2/library/stdtypes.html#str.format) method with a slightly different syntax from the existing `%` operator. Which is better and for what situations? 1. The following uses each method and has the same outcome, so what is the difference? ``` #!/us...
But please be careful, just now I've discovered one issue when trying to replace all `%` with `.format` in existing code: **`'{}'.format(unicode_string)` will try to encode unicode\_string and will probably fail.** Just look at this Python interactive session log: ``` Python 2.7.2 (default, Aug 27 2012, 19:52:55) [G...
Python string formatting: % vs. .format
5,082,452
849
2011-02-22T18:46:42Z
23,637,584
21
2014-05-13T17:10:00Z
[ "python", "performance", "logging", "string-formatting" ]
Python 2.6 introduced the [`str.format()`](https://docs.python.org/2/library/stdtypes.html#str.format) method with a slightly different syntax from the existing `%` operator. Which is better and for what situations? 1. The following uses each method and has the same outcome, so what is the difference? ``` #!/us...
As I discovered today, the old way of formatting strings via `%` doesn't support `Decimal`, Python's module for decimal fixed point and floating point arithmetic, out of the box. Example (using Python 3.3.5): ``` #!/usr/bin/env python3 from decimal import * getcontext().prec = 50 d = Decimal('3.12375239e-24') # no ...
Python string formatting: % vs. .format
5,082,452
849
2011-02-22T18:46:42Z
25,433,007
11
2014-08-21T18:00:48Z
[ "python", "performance", "logging", "string-formatting" ]
Python 2.6 introduced the [`str.format()`](https://docs.python.org/2/library/stdtypes.html#str.format) method with a slightly different syntax from the existing `%` operator. Which is better and for what situations? 1. The following uses each method and has the same outcome, so what is the difference? ``` #!/us...
As a side note, you don't have to take a performance hit to use new style formatting with logging. You can pass any object to `logging.debug`, `logging.info`, etc. that implements the `__str__` magic method. When the logging module has decided that it must emit your message object (whatever it is), it calls `str(messag...
Python string formatting: % vs. .format
5,082,452
849
2011-02-22T18:46:42Z
27,301,386
21
2014-12-04T18:33:46Z
[ "python", "performance", "logging", "string-formatting" ]
Python 2.6 introduced the [`str.format()`](https://docs.python.org/2/library/stdtypes.html#str.format) method with a slightly different syntax from the existing `%` operator. Which is better and for what situations? 1. The following uses each method and has the same outcome, so what is the difference? ``` #!/us...
Yet another advantage of `.format` (which I don't see in the answers): it can take object properties. ``` In [12]: class A(object): ....: def __init__(self, x, y): ....: self.x = x ....: self.y = y ....: In [13]: a = A(2,3) In [14]: 'x is {0.x}, y is {0.y}'.format(a) Out[14]:...
Python string formatting: % vs. .format
5,082,452
849
2011-02-22T18:46:42Z
36,645,589
19
2016-04-15T11:12:07Z
[ "python", "performance", "logging", "string-formatting" ]
Python 2.6 introduced the [`str.format()`](https://docs.python.org/2/library/stdtypes.html#str.format) method with a slightly different syntax from the existing `%` operator. Which is better and for what situations? 1. The following uses each method and has the same outcome, so what is the difference? ``` #!/us...
Update 2016: As of [Python 3.6](https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew-fstrings) you can substitute variables into strings by name: ``` >>> origin = "London" >>> destination = "Paris" >>> f"from {origin} to {destination}" 'from London to Paris' ``` Note the `f"` prefix. If you try this in Python 3.5 o...
Google App Engine json post request body
5,082,832
4
2011-02-22T19:22:57Z
5,083,542
11
2011-02-22T20:26:27Z
[ "python", "json", "google-app-engine", "post" ]
I can't read body from POST request on Google app engine application whenever I send string which contains colon ":" This is my request handler class: ``` class MessageSync(webapp.RequestHandler): def post(self): print self.request.body ``` Ad this is my testing script: ``` import httplib2 json_works = '{"work...
In the case of `json_doesnt_work`, the `print` function is setting the `self.request.body` as a `Response header` because it's in a form of a `{key:value}` parameter. ``` {'status': '200', 'content-length': '0', 'expires': 'Fri, 01 Jan 1990 00:00:00 GMT', 'server': 'Development/1.0', 'cache-control': 'no-cache', '...
python: convert "5,4,2,4,1,0" into [[5, 4], [2, 4], [1, 0]]
5,083,194
8
2011-02-22T19:56:34Z
5,083,261
14
2011-02-22T20:01:58Z
[ "python" ]
Is there a "straightforward" way to convert a str containing numbers into a list of [x,y] ints? ``` # from: '5,4,2,4,1,0,3,0,5,1,3,3,14,32,3,5' # to: [[5, 4], [2, 4], [1, 0], [3, 0], [5, 1], [3, 3], [14, 32], [3, 5]] ``` By the way, the following works, but wouldn't call it straightforward... Also, it can be assumed ...
One option: ``` >>> num_str = '5,4,2,4,1,0,3,0,5,1,3,3,4,3,3,5' >>> l = num_str.split(',') >>> zip(l[::2], l[1::2]) [('5', '4'), ('2', '4'), ('1', '0'), ('3', '0'), ('5', '1'), ('3', '3'), ('4', '3'), ('3', '5')] ``` **Reference**: [`str.split()`](http://docs.python.org/library/stdtypes.html#str.split), [`zip()`](htt...
python: convert "5,4,2,4,1,0" into [[5, 4], [2, 4], [1, 0]]
5,083,194
8
2011-02-22T19:56:34Z
5,083,312
10
2011-02-22T20:06:36Z
[ "python" ]
Is there a "straightforward" way to convert a str containing numbers into a list of [x,y] ints? ``` # from: '5,4,2,4,1,0,3,0,5,1,3,3,14,32,3,5' # to: [[5, 4], [2, 4], [1, 0], [3, 0], [5, 1], [3, 3], [14, 32], [3, 5]] ``` By the way, the following works, but wouldn't call it straightforward... Also, it can be assumed ...
``` #!/usr/bin/env python from itertools import izip def pairwise(iterable): "s -> (s0,s1), (s2,s3), (s4, s5), ..." a = iter(iterable) return izip(a, a) s = '5,4,2,4,1,0,3,0,5,1,3,3,4,3,3,5' fields = s.split(',') print [[int(x), int(y)] for x,y in pairwise(fields)] ``` Taken from [@martineau's answer](h...
python: convert "5,4,2,4,1,0" into [[5, 4], [2, 4], [1, 0]]
5,083,194
8
2011-02-22T19:56:34Z
5,084,126
21
2011-02-22T21:23:26Z
[ "python" ]
Is there a "straightforward" way to convert a str containing numbers into a list of [x,y] ints? ``` # from: '5,4,2,4,1,0,3,0,5,1,3,3,14,32,3,5' # to: [[5, 4], [2, 4], [1, 0], [3, 0], [5, 1], [3, 3], [14, 32], [3, 5]] ``` By the way, the following works, but wouldn't call it straightforward... Also, it can be assumed ...
There are two important one line idioms in Python that help make this "straightforward". The first idiom, use [zip()](http://docs.python.org/library/functions.html#zip). From the Python documents: > The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data s...
Find minimum element in a dictionary of dictionaries
5,083,340
2
2011-02-22T20:09:08Z
5,083,453
11
2011-02-22T20:19:35Z
[ "python", "multidimensional-array", "python-2.4" ]
I need to find what element of `apple` has the minimum `size`. Tnx for all answers. But there is one problem: I use Python 2.4.2 (I can't change it) and function `min` haven't `key` arg. Yes, I need key of `apple` ``` apple = {1:{'size':12,'color':'red'},2:{'size':10,'color':'green'}} ```
``` import operator min(apple.values(), key=operator.itemgetter('size')) ``` will return you ``` {'color': 'green', 'size': 10} ``` UPDATE: to get the index: ``` min(apple, key=lambda k: apple[k]['size']) ```
Find minimum element in a dictionary of dictionaries
5,083,340
2
2011-02-22T20:09:08Z
5,083,497
7
2011-02-22T20:23:09Z
[ "python", "multidimensional-array", "python-2.4" ]
I need to find what element of `apple` has the minimum `size`. Tnx for all answers. But there is one problem: I use Python 2.4.2 (I can't change it) and function `min` haven't `key` arg. Yes, I need key of `apple` ``` apple = {1:{'size':12,'color':'red'},2:{'size':10,'color':'green'}} ```
Python has a very nice parameter for the `min` function that allows using an arbitrary function to be minified instead of just using comparison on the elements: ``` result = min(apple.values(), key=lambda x:x['size']) ``` The `key` parameter replaced in most cases the older idiom of decorate-process-undecorate that c...
Google Static Maps API: Generating a static map with paths
5,083,549
5
2011-02-22T20:26:53Z
5,157,975
9
2011-03-01T17:21:33Z
[ "python", "google-maps", "google-static-maps" ]
I'm trying to generate a static google map with some points on it, and some lines connecting these points (I'm soon going to make the lines correspond with the driving directions, but that comes later). Right now I've got code like this to generate the URL: ``` def getStaticMapAddress(self, route): url = "http://m...
There is something wrong with the color parameter of the paths. The following URI works for me: [`http://maps.google.com/maps/api/staticmap?center=50.8202008,-0.1324898&zoom=6&size=400x400&markers=50.8202008,-0.1324898|51.447341,-0.0761212|51.4608947,-2.5884312&path=weight:5|50.8202008,-0.1324898|51.447341,-0.0761212|...
Python/Matplotlib - Change the relative size of a subplot
5,083,763
21
2011-02-22T20:46:15Z
5,084,061
32
2011-02-22T21:17:03Z
[ "python", "matplotlib" ]
I have two plots ``` import matplotlib.pyplot as plt plt.subplot(121) plt.subplot(122) ``` I want `plt.subplot(122)` to be half as wide as `plt.subplot(121)`. Is there a straightforward way to set the height and width parameters for a subplot?
See the grid-spec tutorial: <http://matplotlib.sourceforge.net/users/gridspec.html> Example code: ``` import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec f = plt.figure() gs = gridspec.GridSpec(1, 2,width_ratios=[2,1]) ax1 = plt.subplot(gs[0]) ax2 = plt.subplot(gs[1]) plt.show() ``` You can a...
Python/Matplotlib - Change the relative size of a subplot
5,083,763
21
2011-02-22T20:46:15Z
5,084,192
8
2011-02-22T21:29:24Z
[ "python", "matplotlib" ]
I have two plots ``` import matplotlib.pyplot as plt plt.subplot(121) plt.subplot(122) ``` I want `plt.subplot(122)` to be half as wide as `plt.subplot(121)`. Is there a straightforward way to set the height and width parameters for a subplot?
By simply specifying the geometry with “`122`”, you're implicitly getting the automatic, equal-sized columns-and-rows layout. To customise the layout grid, you need to get a little more specific. See “[Customizing Location of Subplot Using GridSpec](http://matplotlib.org/users/gridspec.html)” in the Matplotlib...
How to Print "Pretty" String Output in Python
5,084,743
18
2011-02-22T22:25:14Z
5,085,137
43
2011-02-22T23:06:40Z
[ "python", "string", "terminal", "pretty-print" ]
I have a list of dicts with the fields classid, dept, coursenum, area, and title from a sql query. I would like to output the values in a human readable format. I was thinking a Column header at the top of each and then in each column the approrpiate output ie: ``` CLASSID DEPT COURSE NUMBER AREA TI...
[Standard Python string formatting](http://docs.python.org/library/string.html#formatstrings) may suffice. ``` # assume that your data rows are tuples template = "{0:8}|{1:10}|{2:15}|{3:7}|{4:10}" # column widths: 8, 10, 15, 7, 10 print template.format("CLASSID", "DEPT", "COURSE NUMBER", "AREA", "TITLE") # header for ...
How to Print "Pretty" String Output in Python
5,084,743
18
2011-02-22T22:25:14Z
5,087,336
9
2011-02-23T05:25:44Z
[ "python", "string", "terminal", "pretty-print" ]
I have a list of dicts with the fields classid, dept, coursenum, area, and title from a sql query. I would like to output the values in a human readable format. I was thinking a Column header at the top of each and then in each column the approrpiate output ie: ``` CLASSID DEPT COURSE NUMBER AREA TI...
``` class TablePrinter(object): "Print a list of dicts as a table" def __init__(self, fmt, sep=' ', ul=None): """ @param fmt: list of tuple(heading, key, width) heading: str, column label key: dictionary key to value to print ...
Python - package installed with easy_install is not being detected (PIL 1.1.7)
5,085,229
7
2011-02-22T23:18:58Z
6,010,398
7
2011-05-15T18:40:09Z
[ "python", "python-imaging-library", "setuptools", "easy-install" ]
I installed PIL with easy\_install but for some reason when I run a file that uses it, I get: ``` ImportError: No module named PIL ``` Does anyone know why this could be? I think it's also worth mentioning that I installed web.py through easy\_install and it's working fine.
I have the same problem. To me, it looks like a bug in PIL easy\_install process. The library is installed, but you have to leave out PIL from imports (aka `import Image` works), which is obviously wrong. To solve, don't use easy\_install to perform the install. Download the tar package and `python setup.py install` i...
Python + nose: make assertions about logged text?
5,085,257
5
2011-02-22T23:23:32Z
5,086,594
11
2011-02-23T03:07:03Z
[ "python", "testing", "logging", "nose" ]
Is there some simple way of capturing and making assertions about logged messages with `nose`? For example, I'd like to be able to do something like: ``` cook_eggs() assert_logged("eggs are ready!") ```
You can create a custom handler which can check for the message being sent through logging. The [BufferingHandler](http://docs.python.org/library/logging.html#memoryhandler) is a perfect match for this job. You might also want to attach in your test the handler to any logger you are using in your code, such as `loggin...
How to get the current port number in Flask?
5,085,656
7
2011-02-23T00:14:43Z
5,089,963
20
2011-02-23T10:59:30Z
[ "python", "networking", "web-frameworks", "flask" ]
Using [Flask](http://flask.pocoo.org/), how can I get the current port number that flask is connected to? I want to start a server on a random port using port 0 but I also need to know which port I am on. **Edit** I think I've found a work around for my issue, although it isn't an answer to the question. I can iterat...
You can't easily get at the server socket used by Flask, as it's hidden in the internals of the standard library (Flask uses Werkzeug, whose development server is based on the stdlib's `BaseHTTPServer`). However, you can create an ephemeral port yourself and then close the socket that creates it, then use that port yo...
How to check if array is not empty?
5,086,178
19
2011-02-23T01:48:56Z
5,086,185
13
2011-02-23T01:51:31Z
[ "python" ]
How to check if the array is not empty? I did this: ``` if not self.table[5] is None: ``` Is this the right way?
If by array you mean [list](http://www.diveintopython.net/native_data_types/lists.html), then if you treat a list as a boolean it will yield True if it has items and False if it's empty. ``` l = [] if l: print "list has items" if not l: print "list is empty" ```
How to check if array is not empty?
5,086,178
19
2011-02-23T01:48:56Z
6,768,542
26
2011-07-20T21:03:21Z
[ "python" ]
How to check if the array is not empty? I did this: ``` if not self.table[5] is None: ``` Is this the right way?
with `a` as a **[numpy array](http://numpy.scipy.org/)**, use: ``` if a.size: print('array is not empty') ``` (in Python, objects like `[1,2,3]` are called lists, not arrays.)
python incorrect timezone conversion using pytz
5,086,419
2
2011-02-23T02:34:34Z
5,092,978
8
2011-02-23T15:27:19Z
[ "python", "timezone", "pytz" ]
I wrote the following script in python to convert datetime from any given timezone to EST. ``` from datetime import datetime, timedelta from pytz import timezone import pytz utc = pytz.utc # Converts char representation of int to numeric representation '121'->121, '-1729'->-1729 def toInt(ch): ret = 0 ...
Firstly slightly less insane implementation: ``` import datetime import pytz EST = pytz.timezone('US/Eastern') def convert2EST(date, time, tzone): dt = datetime.datetime.strptime(date+time, '%Y%m%d%H:%M:%S') tz = pytz.timezone(tzone) dt = tz.localize(dt) return dt.astimezone(EST) ``` Now, we try to ...
how to pass parameters of a function when using timeit.Timer()
5,086,430
12
2011-02-23T02:36:15Z
5,086,496
7
2011-02-23T02:48:00Z
[ "python", "timer" ]
This is the outline of a simple program ``` # some pre-defined constants A = 1 B = 2 # function that does something critical def foo(num1, num2): # do something # main program.... do something to A and B for i in range(20): # do something to A and B # and update A and B during each iteration import time...
Your function needs to be define in the setup string. A good way to do this is by setting up your code in a module, so you simple have to do ``` t = timeit.Timer("foo(num1, num2)", "from myfile import foo") t.timeit(5) ``` Otherwise, you'll have to define all of the setup as a string inside the setup statement. ``` ...
how to pass parameters of a function when using timeit.Timer()
5,086,430
12
2011-02-23T02:36:15Z
5,086,538
9
2011-02-23T02:56:14Z
[ "python", "timer" ]
This is the outline of a simple program ``` # some pre-defined constants A = 1 B = 2 # function that does something critical def foo(num1, num2): # do something # main program.... do something to A and B for i in range(20): # do something to A and B # and update A and B during each iteration import time...
Supposing that your module filename is test.py ``` # some pre-defined constants A = 1 B = 2 # function that does something critical def foo(n, m): pass # main program.... do something to A and B for i in range(20): pass import timeit t = timeit.Timer(stmt="test.foo(test.A, test.B)", setup="import test") p...
how to pass parameters of a function when using timeit.Timer()
5,086,430
12
2011-02-23T02:36:15Z
18,434,710
7
2013-08-25T23:20:08Z
[ "python", "timer" ]
This is the outline of a simple program ``` # some pre-defined constants A = 1 B = 2 # function that does something critical def foo(num1, num2): # do something # main program.... do something to A and B for i in range(20): # do something to A and B # and update A and B during each iteration import time...
I usually create an extra function: ``` def f(x,y): return x*y v1 = 10 v2 = 20 def f_test(): f(v1,v2) print(timeit.timeit("f_test()", setup="from __main__ import f_test")) ```
how to pass parameters of a function when using timeit.Timer()
5,086,430
12
2011-02-23T02:36:15Z
32,556,672
7
2015-09-14T02:55:47Z
[ "python", "timer" ]
This is the outline of a simple program ``` # some pre-defined constants A = 1 B = 2 # function that does something critical def foo(num1, num2): # do something # main program.... do something to A and B for i in range(20): # do something to A and B # and update A and B during each iteration import time...
The functions can use arguments in `timeit` if these are created using closures, we can add this behaviours by wrapping them in another function. ``` def foo(num1, num2): def _foo(): # do something to num1 and num2 pass return _foo A = 1 B = 2 import timeit t = timeit.Timer(foo(A,B)) print ...
Python: Is there an inverse for ndarray.flatten('F')?
5,086,789
7
2011-02-23T03:46:06Z
5,086,804
11
2011-02-23T03:48:58Z
[ "python", "arrays", "numpy" ]
For example: ``` from numpy import * x = array([[1,2], [3, 4], [5, 6]]) print x.flatten('F') >>>[1 3 5 2 4 6] ``` Is it possible to get `[[1,2], [3, 4], [5, 6]]` from `[1 3 5 2 4 6]`?
``` >>> a = numpy.array((1, 3, 5, 2 ,4, 6)) >>> a.reshape(2, -1).T array([[1, 2], [3, 4], [5, 6]]) >>> ```
Python pretty XML printer with lxml
5,086,922
6
2011-02-23T04:14:18Z
9,612,463
24
2012-03-08T03:24:01Z
[ "python", "lxml", "pretty-print" ]
After reading from an existing file with 'ugly' XML and doing some modifications, pretty printing doesn't work. I've tried `etree.write(FILE_NAME, pretty_print=True)`. I have the following XML: ``` <testsuites tests="14" failures="0" disabled="0" errors="0" time="0.306" name="AllTests"> <testsuite name="AIR" test...
For me, this issue was not solved until I noticed this little tidbit here: <http://lxml.de/FAQ.html#why-doesn-t-the-pretty-print-option-reformat-my-xml-output> Short version: Read in the file with this command: ``` >>> parser = etree.XMLParser(remove_blank_text=True) >>> tree = etree.parse(filename, parser) ``` Th...
To find the number of syllables in a word
5,087,493
5
2011-02-23T05:55:54Z
5,087,502
12
2011-02-23T05:57:07Z
[ "python", "nltk" ]
I need to find out the number of syllables in a word from the English language using NLTK. This is the code I have so far: ``` import curses from curses.ascii import isdigit import nltk from nltk.corpus import cmudict d = cmudict.dict() def nsyl(word): return [len(list(y for y in x if isdigit(y[-1]))) for x in...
you need to put quotes around the word 'arithmetic'
how should I set default python version
5,087,831
6
2011-02-23T06:47:11Z
5,088,548
19
2011-02-23T08:31:58Z
[ "python" ]
I installed python2.6 and python3 on windows 7,and set environment var:path=d:\python2.6,and when I run ">>>python" in cmd window,it display the python version is 2.6,it is right!but when I wrote a script in a bat file,and run the bat file,it display the python version is 3.1,what is wrong here? the script code in bat...
The last Python you install that registers itself in the environment is the default (I can't remember the exact wording in the installer, but it is the first option). There are a number of settings so to make sure they are all registered consistently just reinstall the version you want to be the default. If you want t...
Python Tuple to JSON output
5,087,903
6
2011-02-23T07:00:36Z
5,087,977
23
2011-02-23T07:11:53Z
[ "python", "json" ]
How do I turn this: ``` data = ((1, '2011-01-01'), (2, '2011-01-02'), (1, '2011-01-15'), (3, '2011-02-01')) ``` into this: ``` { "item": [ "1", "2", "1", "3", ], "settings": { "axisx": [ "2011-01-01", "2011-01-02", "2011-01-15", "2011-02-01" ], "...
Use the [json library](http://docs.python.org/library/json.html). Then convert your data using something like this: ``` somedict = { "item" : [ x[0] for x in data ], "settings" : { "axisx" : [ x[1] for x in data ], "axisy" : [ 0, 100], "colour" ...
`python -m unittest discover` does not discover tests
5,088,960
16
2011-02-23T09:20:53Z
5,089,954
20
2011-02-23T10:58:08Z
[ "python", "unit-testing", "nose", "unittest2" ]
Python's unittest discover does not find my tests! I have been using nose to discover my unit tests and it is working fine. From the top level of my project, if I run `nosetests` I get: ``` Ran 31 tests in 0.390s ``` Now that python 2.7 [unittest has discovery](http://docs.python.org/library/unittest.html#unittest-t...
The behaviour is intentional, but the documentation could make this clearer. If you look at the first paragraph in the test discovery section, it says `For a project’s tests to be compatible with test discovery they must all be importable from the top level directory of the project (in other words, they must all be i...
AppEngine - Writes are limited to 1 per second
5,089,485
2
2011-02-23T10:14:50Z
5,089,698
7
2011-02-23T10:34:14Z
[ "python", "google-app-engine" ]
I'm looking into using the AppEngine DataStore for a database system, but I'm confused by this quote in the documentation: "**This allows queries on a single guestbook to be strongly consistent, but also limits changes to the guestbook to 1 write per second (the supported limit for entity groups).**" Source: <http://...
Hey, nope, having a reference to another entity and belonging to the same entity group as another entity are two independent things. Entities belong to the same entity group only if you explicitly supply a `parent` argument when you [instantiate](http://code.google.com/appengine/docs/python/datastore/entities.html#Ent...
Is there a way to efficiently yield every file in a directory containing millions of files?
5,090,418
11
2011-02-23T11:44:30Z
5,090,519
8
2011-02-23T11:53:53Z
[ "python", "list", "file", "yield" ]
I'm aware of `os.listdir`, but as far as I can gather, that gets all the filenames in a directory into memory, and then returns the list. What I want, is a way to yield a filename, work on it, and then yield the next one, without reading them all into memory. Is there any way to do this? I worry about the case where f...
The glob module Python from 2.5 onwards has an iglob method which returns an iterator. An iterator is exactly for the purposes of not storing huge values in memory. ``` glob.iglob(pathname) Return an iterator which yields the same values as glob() without actually storing them all simultaneously. ``` For example: ``...
Is there a way to efficiently yield every file in a directory containing millions of files?
5,090,418
11
2011-02-23T11:44:30Z
5,091,076
13
2011-02-23T12:45:18Z
[ "python", "list", "file", "yield" ]
I'm aware of `os.listdir`, but as far as I can gather, that gets all the filenames in a directory into memory, and then returns the list. What I want, is a way to yield a filename, work on it, and then yield the next one, without reading them all into memory. Is there any way to do this? I worry about the case where f...
**tl;dr <update>:** As of Python 3.5 (currently in beta) just use `os.scandir` </update> As I've written earlier, since "iglob" is just a facade for a real iterator, you will have to call low level system functions in order to get one at a time like you want. Fortyuantelly, that is doable from Python. If have not told...
Is there a way to efficiently yield every file in a directory containing millions of files?
5,090,418
11
2011-02-23T11:44:30Z
5,091,568
8
2011-02-23T13:31:05Z
[ "python", "list", "file", "yield" ]
I'm aware of `os.listdir`, but as far as I can gather, that gets all the filenames in a directory into memory, and then returns the list. What I want, is a way to yield a filename, work on it, and then yield the next one, without reading them all into memory. Is there any way to do this? I worry about the case where f...
Since you are using Linux, you might want to look at [pyinotify](http://pyinotify.sourceforge.net/). It would allow you to write a Python script which monitors a directory for filesystem changes -- such as the creation, modification or deletion of files. Every time such a filesystem event occurs, you can arrange for t...
In Python, partial function application (currying) versus explicit function definition
5,091,528
16
2011-02-23T13:27:01Z
5,091,736
13
2011-02-23T13:48:57Z
[ "python", "functional-programming", "currying", "partial-functions" ]
In Python, is it considered better style to: * explicitly define useful functions in terms of more general, possibly internal use, functions; or, * use partial function application to explicitly describe function currying? I will explain my question by way of a contrived example. Suppose one writes a function, \_sor...
If you want to have the curried functions as part of a public interface, use explicit function definitions. This has the following additional advantages: 1. It is easier to assign a docstring to an explicit function definition. For `partial()` functions, you would have to assign to the `__doc__` attribute, which is so...
How do I register custom filter in Google App Engine template system?
5,091,596
5
2011-02-23T13:33:43Z
5,093,230
12
2011-02-23T15:47:47Z
[ "python", "django", "google-app-engine", "django-templates" ]
According to Django documentation I've registered my filter: ``` from google.appengine.ext.webapp import template # ... register = template.create_template_register() @register.filter(name='wld') def wld(result): if result == 1 : return "win" if result == 0 : return "loss" if result == 0.5 : return "draw" ...
Once you have created your custom tag library, you need to register it with the Django template engine: ``` from google.appengine.ext.webapp import template template.register_template_library('path.to.lib') ``` Note that the call `template.register_template_library` is a wrapper that is provided as part of the AppEng...
List of all available matplotlib backends
5,091,993
38
2011-02-23T14:10:25Z
5,092,255
24
2011-02-23T14:32:58Z
[ "python", "matplotlib" ]
The current backend name is accessible via ``` >>> import matplotlib.pyplot as plt >>> plt.get_backend() 'GTKAgg' ``` Is there a way to get a list of all backends that can be used on a particular machine? Thanks in advance.
You can access the lists ``` matplotlib.rcsetup.interactive_bk matplotlib.rcsetup.non_interactive_bk matplotlib.rcsetup.all_backends ``` the third being the concatenation of the former two. If I read the source code correctly, those lists are hard-coded though, and don't tell you what backends are actually usable. Th...
List of all available matplotlib backends
5,091,993
38
2011-02-23T14:10:25Z
13,731,150
31
2012-12-05T19:44:35Z
[ "python", "matplotlib" ]
The current backend name is accessible via ``` >>> import matplotlib.pyplot as plt >>> plt.get_backend() 'GTKAgg' ``` Is there a way to get a list of all backends that can be used on a particular machine? Thanks in advance.
Here is a modification of the script posted previously. It finds all supported backends, validates them and measures their fps. On OSX it crashes python when it comes to tkAgg, so use at your own risk ;) ``` from pylab import * import time import matplotlib.backends import matplotlib.pyplot as p import os.path def ...
A better way than eval() when translating keyword arguments in QuerySets (Python/Django)
5,092,336
4
2011-02-23T14:41:10Z
5,092,385
11
2011-02-23T14:45:41Z
[ "python", "django", "eval" ]
I'm using django-transmeta (couldn't get anything else working better with django 1.2.5) which creates several columns in a table like: content\_en, content\_es, content\_it Before implementing i18n I had: ``` items = Items.objects.filter(categories__slug=slug) ``` now category.slug is internationalized therefore I ...
Try ``` q = Q(**{"categories__slug_" + current_lang + "__contains": slug}) items = Items.objects.filter(q) ```