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
Configuring Python to use additional locations for site-packages
7,901,373
14
2011-10-26T10:22:22Z
7,901,603
21
2011-10-26T10:47:19Z
[ "python", "packages" ]
Is there a way to tell Python about additional `site-packages` locations without modifying existing scripts? On my CentOS 5.5 server I have a Python 2.7 installation that is installed in `/opt/python2.7.2` and there is a `site-packages` folder at `/opt/python2.7.2/lib/python2.7/site-packages`. The reason for this is ...
You can use the [Site-specific configuration hook](http://docs.python.org/library/site.html). > "A path configuration file is a file whose name has the form `name.pth` and exists in one of the four directories mentioned above; its contents are additional items (one per line) to be added to `sys.path`." In your case, ...
Django: nested custom template tags
7,901,598
3
2011-10-26T10:46:25Z
7,901,638
9
2011-10-26T10:50:55Z
[ "python", "django", "templates" ]
I have written 2 custom template tags in Django. The goal is to use one custom tag inside of another. Is it permitted? The template for custom "outer" tag looks like this: ``` <ul> {% for type in types %} {% custom_internal_tag param1 %} {% endfor %} </ul> ``` Which after rendering results in > Inva...
They are definitely allowed, but that error can come up because your custom tag is not properly defined, located or loaded. Make sure all your custom tags are located in your `app/templatetags` directory and are loaded properly, usually using the `@register` decorator. *Reference:* <https://docs.djangoproject.com/en/...
NumPy arrays with SQLite
7,901,853
4
2011-10-26T11:15:42Z
7,928,151
7
2011-10-28T10:38:46Z
[ "python", "arrays", "sqlite", "numpy", "scipy" ]
The most common SQLite interface I've seen in Python is `sqlite3`, but is there anything that works well with NumPy arrays or recarrays? By that I mean one that recognizes data types and does not require inserting row by row, and extracts into a NumPy (rec)array...? Kind of like R's SQL functions in the `RDB` or `sqldf...
why not give ***[redis](http://redis.io)*** a try? Drivers for your two platforms of interest are available--python (*redis*, via package index][2](http://pypi.python.org/pypi)), and R (*rredis*, [CRAN](http://cran.r-project.org/)). The genius of redis is *not* that it will magically recognize the NumPy data type and...
Python Workflow Design Pattern
7,902,647
17
2011-10-26T12:36:51Z
7,934,994
14
2011-10-28T21:13:51Z
[ "python", "workflow" ]
Im working on a piece of software design, and im stuck between not having any idea what im doing, and feeling like im reinventing the wheel. My situation is the following: I am designing a scientific utility with an interactive UI. User input should trigger visual feedback (duh), some of it directly, i.e. editing a do...
I believe that you are both, right and wrong, in doubt of re-inventing the wheel. Maybe different *levels* of thinking gives you a hint here. How to eat an elephant? # Level A: software design At that level, you would want to stick to the best practice that **no long operations are done in the UI** (and UI thread). ...
python count items in list and keep their order of occurrance
7,902,924
3
2011-10-26T12:58:53Z
7,902,958
8
2011-10-26T13:02:16Z
[ "python" ]
Given: a list, such as l=[4,4,4,4,5,5,5,6,7,7,7] Todo: get the count of an element and keep their occurrence order, e.g.: [(4,4),(5,3),(6,1),(7,3)] I could do it with: ``` tmpL = [(i,l.count(i)) for i in l] tmpS = set() cntList = [x for x in tmpL if x not in tmpS and not tmpS.add(x)] ``` But is there a better ...
Use `groupby`: ``` >>> l = [4,4,4,4,5,5,5,6,7,7,7,2,2] >>> from itertools import groupby >>> [(i, l.count(i)) for i,_ in groupby(l)] [(4, 4), (5, 3), (6, 1), (7, 3), (2, 2)] ```
Pretty print in lxml is failing when I add tags to a parsed tree
7,903,759
13
2011-10-26T14:02:22Z
7,904,066
19
2011-10-26T14:22:51Z
[ "python", "xml", "parsing", "lxml", "pretty-print" ]
I have an xml file that I'm using etree from lxml to work with, but when I add tags to it, pretty printing doesn't seem to work. ``` >>> from lxml import etree >>> root = etree.parse('file.xml').getroot() >>> print etree.tostring(root, pretty_print = True) <root> <x> <y>test1</y> </x> </root> ``` So far so g...
It has to do with how `lxml` treats whitespace -- see the [lxml FAQ](http://lxml.de/FAQ.html#why-doesn-t-the-pretty-print-option-reformat-my-xml-output) for details. To fix this, change the loading part of the file to the following: ``` parser = etree.XMLParser(remove_blank_text=True) root = etree.parse('file.xml', p...
New instance of Python class with a non-None class attribute
7,903,845
4
2011-10-26T14:08:19Z
7,903,892
7
2011-10-26T14:10:41Z
[ "python", "python-2.7", "class-instance-variables" ]
I have a Python class that has a class attribute set to something other than `None`. When creating a new instance, the changes made to that attribute perpetuates through all instances. Here's some code to make sense of this: ``` class Foo(object): a = [] b = 2 foo = Foo() foo.a.append('item') foo.b = 5 ```...
Yes, this is how it is supposed to work. If `a` and `b` belong to the *instance* of `Foo`, then the correct way to do this is: ``` class Foo(object): def __init__(self): self.a = [] self.b = 2 ``` The following makes `a` and `b` belong to the *class itself*, so all instances share the same variables: `...
Implementing a Kolmogorov Smirnov test in python scipy
7,903,977
17
2011-10-26T14:16:15Z
7,904,652
18
2011-10-26T15:04:11Z
[ "python", "statistics", "scipy" ]
I have a data set on N numbers that I want to test for normality. I know scipy.stats has a [kstest function](http://docs.scipy.org/doc/scipy-0.7.x/reference/generated/scipy.stats.kstest.html) but there are no examples on how to use it and how to interpret the results. Is anyone here familiar with it that can give me so...
Your data was generated with mu=0.07 and sigma=0.89. You are testing this data against a normal distribution with mean 0 and standard deviation of 1. The null hypothesis (`H0`) is that the distribution of which your data is a sample is equal to the standard normal distribution with mean 0, std deviation 1. The small ...
Integer divsion in Python
7,904,445
6
2011-10-26T14:49:53Z
7,904,481
13
2011-10-26T14:52:36Z
[ "python", "math", "integer", "integer-division" ]
I'm confused about the following integer math in python: `-7/3 = -3` since `(-3)*3 = -9 < -7`. I understand. `7/-3 = -3` I don't get how this is defined. `(-3)*(-3) = 9 > 7`. In my opinion, it should be -2, because `(-3)*(-2) = 6 < 7`. How does this work?
From the [documentation](http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex): > For (plain or long) integer division, the result is an integer. **The result is always rounded towards minus infinity**: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. The rounding towards `-inf` ...
Adding a Log entry for an action by a user in a Django App
7,905,106
7
2011-10-26T15:35:59Z
7,905,253
8
2011-10-26T15:47:58Z
[ "python", "django", "django-admin" ]
I need to create a log entry for changes made by a user to the database via the views in my django application. I have enabled the django-admin module and I can retrieve the logs of the changes made using the admin interface like this: ``` from django.contrib.admin.models import LogEntry from django.contrib.contentty...
You're very close. You just need to create new `LogEntry` objects and save them. `LogEntry` has a shortcut function on `objects` to do this. ``` from django.contrib.admin.models import LogEntry, ADDITION, CHANGE LogEntry.objects.log_action( user_id=request.user.id, content_type_id=ContentType....
Testing Equivalence of xml.etree.ElementTree
7,905,380
13
2011-10-26T15:57:07Z
12,591,017
7
2012-09-25T21:03:25Z
[ "python", "python-3.x", "elementtree" ]
I'm interested in equivalence of two xml elements; and I've found that testing the tostring of the elements works; however, that seems hacky. Is there a better way to test equivalence of two etree Elements? Example: ``` import xml.etree.ElementTree as etree h1 = etree.Element('hat',{'color':'red'}) h2 = etree.Element(...
Comparing strings doesn't always work. The order of the attributes should not matter for considering two nodes equivalent. However, if you do string comparison, the order obviously matters. I'm not sure if it is a problem or a feature, but my version of lxml.etree preserves the order of the attributes if they are pars...
How do I list all the attributes of an object in python pdb?
7,905,904
14
2011-10-26T16:39:47Z
7,905,945
20
2011-10-26T16:41:50Z
[ "python", "debugging", "pdb" ]
I try to list all the attributes of an object in Python pdb. Let's say I want to list all the attributes and all methods of `sys.stderr`. How can I do that?
For pdb, you should be able to do `p dir(a)`.
Spline representation with scipy.interpolate: Poor interpolation for low-amplitude, rapidly oscillating functions
7,906,126
4
2011-10-26T16:57:20Z
7,907,395
8
2011-10-26T18:46:10Z
[ "python", "math", "scipy", "interpolation" ]
I need to (numerically) calculate the first and second derivative of a function for which I've attempted to use both `splrep` and `UnivariateSpline` to create splines for the purpose of interpolation the function to take the derivatives. However, it seems that there's an inherent problem in the spline representation i...
I'm guessing that your problem is due to aliasing. What is `x` in your example? If the `x` values that you're interpolating at are less closely spaced than your original points, you'll inherently lose frequency information. This is completely independent from any type of interpolation. It's inherent in downsampling. ...
matplotlib savefig() plots different from show()
7,906,365
22
2011-10-26T17:17:58Z
7,906,795
21
2011-10-26T17:57:46Z
[ "python", "graph", "plot", "matplotlib" ]
When I use `show()` to plot the graphs in `X`, the graphs looks very good. However when I start to use `savefig()` to generate large amount of graphs, the `savefig()` generated graphs ' font, lines, polygons all look smaller than the `show()` generated graph. My environment is Ubuntu and the backend for `show()` is `Qt...
`savefig` specifies the DPI for the saved figure (The default is 100 if it's not specified in your .matplotlibrc, have a look at the [`dpi` kwarg to `savefig`](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.savefig)). It doesn't inheret it from the DPI of the original figure. The DPI affects t...
matplotlib savefig() plots different from show()
7,906,365
22
2011-10-26T17:17:58Z
7,912,007
19
2011-10-27T05:25:08Z
[ "python", "graph", "plot", "matplotlib" ]
When I use `show()` to plot the graphs in `X`, the graphs looks very good. However when I start to use `savefig()` to generate large amount of graphs, the `savefig()` generated graphs ' font, lines, polygons all look smaller than the `show()` generated graph. My environment is Ubuntu and the backend for `show()` is `Qt...
You render your *matplotlib* plots to different devices (e.g., on-screen via Quartz versus to to-file via pdf using different functions (***plot*** versus ***savefig***) whose parameters are nearly the same, yet the *default values* for those parameters are not the same for both functions. Put another way, the ***save...
Delete some dots on the beggining of a string in python
7,906,854
2
2011-10-26T18:03:00Z
7,906,907
10
2011-10-26T18:06:57Z
[ "python", "regex", "string" ]
I have some strings which starts with dots, and I want to delete it. Which is the best way. And if the next caracter isn't a "/" add it. I'm new in python and I've been trying to do something like this to erase dots but there is a syntax error. ``` while (re.match(r'\.*', url[0]).end()) = 0: url = url[1:] ``` * .....
To get rid of the dots: ``` mystr = '...../your_string' mystr = '/' + mystr.lstrip('./') ``` and the result should be: > /your\_string regardless of whether it begins with dots or slashes (they all will be replaced with single slash).
json.dumps vs flask.jsonify
7,907,596
109
2011-10-26T19:06:29Z
7,907,657
70
2011-10-26T19:13:33Z
[ "python", "json", "flask" ]
I am not sure I understand the purpose of `flask.jsonify` method. I try to make json string from this: ``` data = {"id": str(album.id), "title": album.title} ``` but what I get with `json.dumps` differs from what I get with `flask.jsonify`. ``` json.dumps(data): [{"id": "4ea856fd6506ae0db42702dd", "title": "Business...
You can do: ``` flask.jsonify(**data) ``` or ``` flask.jsonify(id=str(album.id), title=album.title) ```
json.dumps vs flask.jsonify
7,907,596
109
2011-10-26T19:06:29Z
13,172,658
130
2012-11-01T07:20:13Z
[ "python", "json", "flask" ]
I am not sure I understand the purpose of `flask.jsonify` method. I try to make json string from this: ``` data = {"id": str(album.id), "title": album.title} ``` but what I get with `json.dumps` differs from what I get with `flask.jsonify`. ``` json.dumps(data): [{"id": "4ea856fd6506ae0db42702dd", "title": "Business...
The `jsonify()` function in flask returns `flask.Response()` object that already has the appropriate content-type header 'application/json' for use with json responses, whereas the `json.dumps()` will just return an encoded string, which would require manually adding the mime type header. See more about the `jsonify()...
json.dumps vs flask.jsonify
7,907,596
109
2011-10-26T19:06:29Z
16,003,910
33
2013-04-14T20:21:11Z
[ "python", "json", "flask" ]
I am not sure I understand the purpose of `flask.jsonify` method. I try to make json string from this: ``` data = {"id": str(album.id), "title": album.title} ``` but what I get with `json.dumps` differs from what I get with `flask.jsonify`. ``` json.dumps(data): [{"id": "4ea856fd6506ae0db42702dd", "title": "Business...
This is `flask.jsonify()` ``` def jsonify(*args, **kwargs): if __debug__: _assert_have_json() return current_app.response_class(json.dumps(dict(*args, **kwargs), indent=None if request.is_xhr else 2), mimetype='application/json') ``` The `json` module used is either `simplejson` or `json` in t...
json.dumps vs flask.jsonify
7,907,596
109
2011-10-26T19:06:29Z
22,464,865
14
2014-03-17T20:38:34Z
[ "python", "json", "flask" ]
I am not sure I understand the purpose of `flask.jsonify` method. I try to make json string from this: ``` data = {"id": str(album.id), "title": album.title} ``` but what I get with `json.dumps` differs from what I get with `flask.jsonify`. ``` json.dumps(data): [{"id": "4ea856fd6506ae0db42702dd", "title": "Business...
The choice of one or another depends on what you intend to do. From what I do understand: * **jsonify** would be useful when you are building an API someone would query and expect json in return. E.g: The REST github API could use this method to answer your request. * **dumps**, is more about formating data/python obj...
openpyxl check for empty cell
7,907,928
5
2011-10-26T19:40:12Z
8,407,990
9
2011-12-06T22:46:03Z
[ "python", "object", "comparison", "openpyxl" ]
openpyxl seems to be a great method for using Python to read Excel files, but I've run into a constant problem. I need to detect whether a cell is empty or not, but can't seem to compare any of the cell properties. I tried casting as a string and using "" but that didn't work. The type of cell when it is empty is None,...
To do something when cell is not empty add: ``` if cell.value: ``` which in python is the same as if cell value is not None (i.e.: if not cell.value == None:) Note to avoid checking empty cells you can use ``` worksheet.get_highest_row() ``` and ``` worksheet.get_highest_column() ``` Also I found it useful (alth...
Possible to make labels appear when hovering over a point in matplotlib?
7,908,636
32
2011-10-26T20:38:14Z
7,909,589
23
2011-10-26T22:15:00Z
[ "python", "matplotlib" ]
I am using matplotlib to make scatter plots. Each point on the scatter plot is associated with a named object. I would like to be able to see the name of an object when I hover my cursor over the point on the scatter plot associated with that object. In particular, it would be nice to be able to quickly see the names o...
From <http://matplotlib.sourceforge.net/examples/event_handling/pick_event_demo.html> : ``` from matplotlib.pyplot import figure, show import numpy as npy from numpy.random import rand if 1: # picking on a scatter plot (matplotlib.collections.RegularPolyCollection) x, y, c, s = rand(4, 100) def onpick3(even...
List "quirk" in python
7,909,794
4
2011-10-26T22:42:05Z
7,909,800
7
2011-10-26T22:43:24Z
[ "python", "list" ]
I was trying out some things with lists in the interactive interpreter and I noticed this: ``` >>> list = range(1, 11) >>> for i in list: ... list.remove(i) ... >>> list [2, 4, 6, 8, 10] ``` Can anyone explain why it left even numbers? This is confusing me right now... Thanks a lot.
It isn't safe to [modify a list](http://docs.python.org/tutorial/controlflow.html#for-statements) that you are iterating over.
Impossible to set an attribute to a string?
7,910,768
8
2011-10-27T01:25:23Z
7,910,791
9
2011-10-27T01:30:45Z
[ "python" ]
Usually, you can set an arbitrary attribute to a custom object, for instance ``` ---------- >>> a=A() >>> a.foo=42 >>> a.__dict__ {'foo': 42} >>> ---------- ``` On the other hand, you can't do the same binding with a string object : ``` ---------- >>> a=str("bar") >>> a.foo=42 Traceback (most recent call last): F...
Because the `str` type is a type wich does not has an attribute dict. From [the docs](http://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy), "Classes" section: > A class has a namespace implemented by a dictionary object. > Class attribute references are translated to lookups in this > dictionar...
Can't install via pip with Virtualenv
7,911,003
33
2011-10-27T02:08:48Z
7,911,058
65
2011-10-27T02:19:03Z
[ "python", "pip" ]
Below is the error I get when I run `pip`: ``` serkan$ rm -r mysite serkan$ pwd /Users/serkan/Desktop/Python Folder serkan$ virtualenv mysite New python executable in mysite/bin/python Installing setuptools............done. Installing pip...............done. serkan$ source mysite/bin/activate (mysite)serkan$ pip inst...
Create your virtualenv environment within a path without spaces. This is why it is happening: When you create an environment, it sets up a `bin` directory. In that `bin` directory are all the executables relating to the environment. Some are scripts. As you may know, hashbangs are used to tell the system what interpre...
Can't install via pip with Virtualenv
7,911,003
33
2011-10-27T02:08:48Z
20,369,673
7
2013-12-04T07:38:20Z
[ "python", "pip" ]
Below is the error I get when I run `pip`: ``` serkan$ rm -r mysite serkan$ pwd /Users/serkan/Desktop/Python Folder serkan$ virtualenv mysite New python executable in mysite/bin/python Installing setuptools............done. Installing pip...............done. serkan$ source mysite/bin/activate (mysite)serkan$ pip inst...
icktoofay is correct about the cause. To use pip with virtualenv in a directory with spaces, edit `/path/to/env/bin/pip`, replacing the shebang at the top with `#!/usr/bin/env python` (or `#!/usr/bin/env pypy` if you're using pypy). Note that virtualenv changes your environment such that `/usr/bin/env python` refers ...
PIL Convert PNG or GIF with Transparency to JPG without
7,911,451
13
2011-10-27T03:34:15Z
7,911,663
22
2011-10-27T04:15:17Z
[ "python", "image-processing", "python-imaging-library" ]
I'm prototyping an image processor in Python 2.7 using PIL1.1.7 and I would like all images to end up in JPG. Input file types will include tiff,gif,png both with transparency and without. I've been trying to combine two scripts that I found that 1. convert other file types to JPG and 2. removing transparency by creati...
Make your background RGB, not RGBA. And remove the later conversion of the background to RGB, of course, since it's already in that mode. This worked for me with a test image I created: ``` from PIL import Image im = Image.open(r"C:\jk.png") bg = Image.new("RGB", im.size, (255,255,255)) bg.paste(im,im) bg.save(r"C:\jk...
Load/reload a portion of code in Python without restarting main script
7,912,250
5
2011-10-27T06:06:19Z
7,925,946
8
2011-10-28T06:39:25Z
[ "python", "twisted", "irc" ]
# Intro I've been tinkering with Twisted for the past few days, having picked up python less than a month ago. My first inclination was to play with something I know and use every day, IRC. I've gotten a basic IRC connection up and running thanks to the [ircLogBot.py](http://twistedmatrix.com/documents/current/words/e...
Twisted has some built-in functionality in [`twisted.python.rebuild`](http://twistedmatrix.com/documents/current/api/twisted.python.rebuild.html#rebuild) which provides a more comprehensive implementation of Python's built-in [`reload`](http://docs.python.org/library/functions.html#reload) function. There are still som...
How do I change a value while debugging python with pdb?
7,912,820
10
2011-10-27T07:23:16Z
7,912,888
8
2011-10-27T07:32:37Z
[ "python", "debugging", "pdb" ]
I want to run pdb, step through the code, and at some point change the value pointed at by some name. So I might want to change the value pointed at by the name 'stationLat'. But it seems I can't. Here's the example: ``` >>> import extractPercentiles >>> import pdb >>> pdb.run( "extractPercentiles.extractOneStation()"...
This appears to be a [bug in Python 2.6](http://bugs.python.org/issue5215). You should be able to do this in Python 2.7.
Can't install python module "pycrypto" on Debian lenny
7,913,140
15
2011-10-27T08:02:15Z
7,913,198
23
2011-10-27T08:07:21Z
[ "python", "debian", "python-2.6", "pycrypto", "lenny" ]
I tried to install pycrypto module by downloading the source code and executing the following command `python setup.py install`, then an error came ``` running install running build running build_py running build_ext warning: GMP library not found; Not building Crypto.PublicKey._fastmath. building 'Crypto.Hash.MD2' ex...
Don't install it from source. Install the Debian package instead: ``` aptitude install python-crypto ``` And to install the python dev files (which you won't need anyway if you follow my above advice): ``` aptitude install python-dev ```
python bottle persistent cookie not working
7,913,169
3
2011-10-27T08:04:28Z
7,914,272
8
2011-10-27T09:52:19Z
[ "python", "cookies", "bottle" ]
I have a site im working on, i want to store a value in a cookie this is an number, when the user comes to the website, i want to know what the number was on their last visit, so I'm thinking of having a persistant cookie that stores the current value, when the user comes to the site, if there is no session cookie, th...
Bottle uses <http://docs.python.org/library/cookie.html> to implement cookie support. This implementation requires the `expires` parameter to be a string in the `Wdy, DD-Mon-YY HH:MM:SS GMT` format. Passing datetime or date objects fails silently. I'll fix that in future versions of Bottle (hi, I'm the author) but for...
make list python have key pair
7,913,248
3
2011-10-27T08:12:50Z
7,913,297
9
2011-10-27T08:17:32Z
[ "python" ]
I have ``` list('327VUQ56156TX374'); ['3', '2', '7', 'V', 'U', 'Q', '5', '6', '1', '5', '6', 'T', 'X', '3', '7', '4'] ``` I want to get the array associative like this , its index.`[ 1=>'3',... 16=>'4' ]` anyone can tell me please thanks
``` dict(enumerate('327VUQ56156TX374')) ``` If you want starting count from 1 (and have a good reason for this :-)), you can use this (but it's only for >= 2.6) ``` dict(enumerate('327VUQ56156TX374', start=1)) ```
Can I overwrite the string form of a namedtuple?
7,914,152
13
2011-10-27T09:41:46Z
7,914,193
7
2011-10-27T09:45:56Z
[ "python" ]
For example: ``` >>> Spoken = namedtuple("Spoken", ["loudness", "pitch"]) >>> s = Spoken(loudness=90, pitch='high') >>> str(s) "Spoken(loudness=90, pitch='high')" ``` What I want is: ``` >>> str(s) 90 ``` That is I want the string representation to display the loudness attribute. Is this possible ?
You can define a function for it: ``` def print_loudness(self): return str(self.loudness) ``` and assign it to `__str__`: ``` Spoken.__str__ = print_loudness ```
Can I overwrite the string form of a namedtuple?
7,914,152
13
2011-10-27T09:41:46Z
7,914,212
26
2011-10-27T09:47:31Z
[ "python" ]
For example: ``` >>> Spoken = namedtuple("Spoken", ["loudness", "pitch"]) >>> s = Spoken(loudness=90, pitch='high') >>> str(s) "Spoken(loudness=90, pitch='high')" ``` What I want is: ``` >>> str(s) 90 ``` That is I want the string representation to display the loudness attribute. Is this possible ?
Yes, it is not hard to do and there is an example for it in the [namedtuple docs](http://docs.python.org/library/collections.html#collections.namedtuple). The technique is to make a subclass that adds its own str method: ``` >>> from collections import namedtuple >>> class Spoken(namedtuple("Spoken", ["loudness", "pi...
Python: all possible combinations of "dynamic" list
7,914,613
5
2011-10-27T10:27:21Z
7,914,717
7
2011-10-27T10:36:44Z
[ "python", "list", "iteration", "permutation", "combinations" ]
I really can't find this out. I tried to use itertools, tried all kind of looping, but still i can't achieve what I want. Here is what i need: I have list such as: ``` list = [("car", 2), ("plane", 3), ("bike", 1)] ``` This list is each time different, there can be 5 different items in it each time and what I need i...
You could use [`itertools.product()`](http://docs.python.org/library/itertools.html#itertools.product): ``` my_list = [("car", 2), ("plane", 3), ("bike", 1)] a = itertools.product(*([name + str(i + 1) for i in range(length)] for name, length in my_list)) for x in a: print x ``` prints ``...
Does uninstalling a package with "pip" also removes the dependent packages?
7,915,998
21
2011-10-27T12:45:57Z
10,284,948
16
2012-04-23T17:04:08Z
[ "python", "packages", "pip" ]
When you use `pip` to install a package , all the necessary required packages will also be installed with it(dependencies). Does uninstalling that packages also remove the dependent packages?
Not, it doesn't uninstall the dependencies packages: ``` $ pip install specloud $ pip freeze ``` > figleaf==0.6.1 > nose==1.1.2 > pinocchio==0.3 > specloud==0.4.5 ``` $ pip uninstall specloud $ pip freeze ``` > figleaf==0.6.1 > nose==1.1.2 > pinocchio==0.3 As you can see all the packages are still there ...
Does uninstalling a package with "pip" also removes the dependent packages?
7,915,998
21
2011-10-27T12:45:57Z
27,713,702
32
2014-12-30T22:49:20Z
[ "python", "packages", "pip" ]
When you use `pip` to install a package , all the necessary required packages will also be installed with it(dependencies). Does uninstalling that packages also remove the dependent packages?
You can install and use the [pip-autoremove](https://github.com/invl/pip-autoremove) utility to remove a package plus unused dependencies. ``` # install pip-autoremove pip install pip-autoremove # remove "somepackage" plus its dependencies: pip-autoremove somepackage -y ```
How to purge all tasks of a specific queue with celery in python?
7,918,270
13
2011-10-27T15:23:28Z
20,410,181
31
2013-12-05T20:38:01Z
[ "python", "django", "celery" ]
How to purge all scheduled and running tasks of a specific que with celery in python? The questions seems pretty straigtforward, but to add I am not looking for the command line code I have the following line, which defines the que and would like to purge that que to manage tasks: ``` CELERY_ROUTES = {"socialreport.t...
just to update @Sam Stoelinga answer for celery 3.1, now it can be done like this on a terminal: ``` celery amqp queue.purge <QUEUE_NAME> ``` For Django be sure to start it from the manage.py file: ``` ./manage.py celery amqp queue.purge <QUEUE_NAME> ``` If not, be sure celery is able to point correctly to the brok...
PDF scraping using R
7,918,718
10
2011-10-27T15:54:26Z
7,918,885
10
2011-10-27T16:05:11Z
[ "python", "pdf", "screen-scraping" ]
I have been using the XML package successfully for extracting HTML tables but want to extend to PDF's. From previous questions it does not appear that there is a simple R solution but wondered if there had been any recent developments Failing that, is there some way in Python (in which I am a complete Novice) to obtai...
Extracting text from PDFs is hard, and nearly always requires lots of care. I'd start with the command line tools such as pdftotext and see what they spit out. The problem is that PDFs can store the text in any order, can use awkward font encodings, and can do things like use ligature characters (the joined up 'ff' an...
Python 2.5.2- what was instead of 'with' statement
7,918,745
6
2011-10-27T15:56:03Z
7,918,772
18
2011-10-27T15:58:04Z
[ "python", "gzip", "with-statement" ]
I wrote my code for python 2.7 but the server has 2.5. How do i rewrite the next code so it will run in python 2.5.2: ``` gzipHandler = gzip.open(gzipFile) try: with open(txtFile, 'w') as out: for line in gzipHandler: out.write(line) except: pass ``` Right now, when i try to run my scrip...
In Python 2.5, you actually *can* use the `with` statement -- just import it from `__future__`: ``` from __future__ import with_statement ```
Deciding to WSGI or Django for new web app
7,919,968
4
2011-10-27T17:34:33Z
7,920,144
7
2011-10-27T17:50:43Z
[ "python", "django", "wsgi", "django-wsgi" ]
I'm in the process of setting up a new web app and deciding whether to just do it with WSGI or go the full framework route with Django. The app's foremost requirements: 1) The app has no UI what so ever and all of the data is exposed to clients via a REST api with JSON. 2) It will have data to persist so MongoDB & p...
I suggest you consider something between those two extremes. [Flask](http://flask.pocoo.org/) is lightweight, very easy to use, and connects to your web server via wsgi. You can use regular python database connectors with it, and a few databases even have Flask-specific [extension](http://flask.pocoo.org/docs/extension...
Difference between Django Form 'initial' and 'bound data'?
7,920,128
17
2011-10-27T17:49:06Z
7,920,343
31
2011-10-27T18:10:38Z
[ "python", "django", "django-forms" ]
Given an example like this: ``` class MyForm(forms.Form): name = forms.CharField() ``` I'm trying to grasp what the difference between the following two snippets is: "Bound Data" style: ``` my_form = MyForm({'name': request.user.first_name}) ``` "Initial data" style: ``` my_form = MyForm(initial={'name': req...
Here's the key part from the django docs on [bound and unbound forms](https://docs.djangoproject.com/en/dev/ref/forms/api/#bound-and-unbound-forms). > A Form instance is either **bound** to a set of data, or **unbound**: > > * If it’s **bound** to a set of data, it’s capable of validating that data and rendering t...
How can printing an object result in different output than both str() and repr()?
7,920,284
16
2011-10-27T18:05:28Z
7,920,986
11
2011-10-27T19:04:44Z
[ "python", "sqlite3" ]
I was testing some code on the interpreter and I noticed some unexpected behavior for the [`sqlite3.Row`](http://docs.python.org/library/sqlite3.html#sqlite3.Row) class. My understanding was that `print obj` will always get the same result as `print str(obj)`, and typing `obj` into the interpreter will get the same re...
PySqlite provides the special native hook for `print`, but it doesn't implement `__repr__` or `__str__`. I'd say that's a bit of a missed chance, but at least it explains the behavior you're observing. See pysqlite source: <http://code.google.com/p/pysqlite/source/browse/src/row.c#215> And python docs: <http://docs.py...
python multiprocessing pickle protocol
7,920,601
13
2011-10-27T18:32:33Z
7,922,877
9
2011-10-27T21:51:08Z
[ "python", "multiprocessing" ]
I am using the Python multiprocessing module to place objects onto a queue and have them processed by several workers. My first issue was getting bound instance methods to pickle, which I have working, but now I'm running into a separate issue caused by the fact that the objects are using `__slots__`. When the mp modu...
If it's not possible to change the pickle protocol the multiprocessing package uses, then define `__getstate__` and `__setstate__` for your objects: ``` import pickle class Foo(object): __slots__ = ['this', 'that', 'other'] def __init__(self): self.this = 1 self.that = 2 self.other = ...
Using exec in a for loop in python
7,920,858
3
2011-10-27T18:52:59Z
7,920,882
7
2011-10-27T18:55:53Z
[ "python", "exec" ]
I am trying to run a for loop that goes through each line of the output of a command. For ex: ``` for line in exec 'lspci | grep VGA': count = count + 1 ``` To try and get the amount of video cards installed in a system. But it doesn't seem to line the syntax on the for loop line. Do I have to import a library f...
`exec` executes Python code, not an external command. You're looking for [`subprocess.Popen()`](http://docs.python.org/library/subprocess.html#popen-constuctor): ``` import subprocess p = subprocess.Popen('lspci', stdout=subprocess.PIPE) for line in p.stdout: if 'VGA' in line: print line.strip() p.wait() ``` On...
How to transform numpy.matrix or array to scipy sparse matrix
7,922,487
24
2011-10-27T21:14:08Z
7,922,642
34
2011-10-27T21:29:02Z
[ "python", "numpy", "scipy", "sparse-matrix" ]
For SciPy sparse matrix, one can use `todense()` or `toarray()` to transform to NumPy matrix or array. What are the functions to do the inverse? I searched, but got no idea what keywords should be the right hit.
You can pass a numpy array or matrix as an argument when initializing a sparse matrix. For a CSR matrix, for example, you can do the following. ``` >>> import numpy as np >>> from scipy import sparse >>> A = np.array([[1,2,0],[0,0,3],[1,0,4]]) >>> B = np.matrix([[1,2,0],[0,0,3],[1,0,4]]) >>> A array([[1, 2, 0], ...
How to transform numpy.matrix or array to scipy sparse matrix
7,922,487
24
2011-10-27T21:14:08Z
7,923,729
12
2011-10-27T23:45:16Z
[ "python", "numpy", "scipy", "sparse-matrix" ]
For SciPy sparse matrix, one can use `todense()` or `toarray()` to transform to NumPy matrix or array. What are the functions to do the inverse? I searched, but got no idea what keywords should be the right hit.
There are several sparse matrix classes in scipy. > bsr\_matrix(arg1[, shape, dtype, copy, blocksize]) Block Sparse Row matrix > coo\_matrix(arg1[, shape, dtype, copy]) A sparse matrix in COOrdinate format. > csc\_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Column matrix > csr\_matrix(arg1[, shape, dtyp...
Python 2.4.3: ConfigParser.NoSectionError: No section: 'formatters'
7,922,602
10
2011-10-27T21:25:28Z
7,923,152
41
2011-10-27T22:21:51Z
[ "python", "logging", "config" ]
Trying to use a logging configuration file to implement `TimedRotatinigFileHandler`. Just won't take the config file for some reason. Any suggestions appreciated. --- x.py: ``` import logging import logging.config import logging.handlers logging.config.fileConfig("x.ini") MyLog = logging.getLogger('x') MyLog.de...
The error message is strictly accurate but misleading. The reason the "formatters" section is missing, is because the logging module can't find the file you passed to `logging.config.fileConfig`. Try using an absolute file path.
Django request QueryDict Errors on pop()
7,923,315
3
2011-10-27T22:46:11Z
7,923,525
8
2011-10-27T23:13:43Z
[ "python", "django", "django-views" ]
Looking at dir(request.GET), I notice that pop is listed as a method. I also believe i've popped off attributes from request in the past. Is that accurate? If so, why would this fail? ``` request.GET.pop('key') ```
`request.GET` and `request.POST` are immutable [`QueryDict`](https://docs.djangoproject.com/en/dev/ref/request-response/#querydict-objects) instances. This means you cannot change their attributes directly. Copying a `QueryDict`, returns a mutable `QueryDict`. You can then call the pop method of the copy without raisi...
How to include docs directory in python distribution
7,923,509
9
2011-10-27T23:12:11Z
7,923,595
10
2011-10-27T23:23:30Z
[ "python", "setup.py" ]
I have a python project with the following structure: ``` Clustering (project name) clustering (package) clustering.py and other modules tests (sub-package) test_clustering.py and other such files docs/ bin/ ``` I would like to include the docs directory in my distribution, but I can not seem t...
You'll need to create a MANIFEST.in file and include some simple instructions on what extra files you want to include (See [MANIFEST.in Template](http://docs.python.org/distutils/sourcedist.html#the-manifest-in-template)) Example (to include docs dir and all files directly underneath): ``` include docs/* ``` or, to ...
Python: Read huge number of lines from stdin
7,923,748
7
2011-10-27T23:47:15Z
7,924,778
11
2011-10-28T03:19:05Z
[ "python", "stdin", "readline" ]
I'm trying to read a huge amount of lines from standard input with python. ``` more hugefile.txt | python readstdin.py ``` The problem is that the program freezes as soon as i've read just a single line. ``` print sys.stdin.read(8) exit(1) ``` This prints the first 8 bytes but then i expect it to terminate but it n...
This should work efficiently in a modern Python: ``` import sys for line in sys.stdin: # do something... print line, ``` You can then run the script like this: ``` python readstdin.py < hugefile.txt ```
Python: list of distinct, empty sets
7,924,709
2
2011-10-28T03:05:56Z
7,924,719
9
2011-10-28T03:07:45Z
[ "python" ]
I am a python newbie and am attempting to write code for sieve of Eratosthenes. For this I have to initialize a list of empty sets. I tried doing this `factors=[set()]*1001`, but this produces a shallow copy. I want a deep copy, so that `factors[i]` and `factors[j]` point to different sets. Is there a simple syntax for...
``` factors = [set() for index in xrange(1001)] ```
Ruby Packaging Ecosystem As Python Terminolgies
7,925,028
8
2011-10-28T04:03:52Z
7,925,097
10
2011-10-28T04:15:21Z
[ "python", "ruby", "rubygems", "comparison", "packaging" ]
I have some experience with Ruby, but it’s less than my Python experience. I've packaged and published several Python packages, but there’s only one Ruby package I've published. I want to learn rapidly about Ruby packaging ecosystem by comparing to Python. * I believe that there’s the tool equivalent to virtuale...
RVM is similar to virtualenv also checkout rbenv (perhaps more like virtualenv) Bundler is for packaging dependencies for development and deployment, it works like `setup.py` and pip (I haven't used pip, it seems to have some features of rubygems and Bundler) Bundler's `Gemfile` is similar to pip's requirement file ...
Vim :colorscheme on Python
7,925,623
6
2011-10-28T05:49:24Z
7,925,721
7
2011-10-28T06:05:35Z
[ "python", "osx", "vim", "syntax-highlighting", "osx-lion" ]
I'm using Mac OSX Lion 10.7.2, Terminal.app supports 256 (output of :echo &t\_Co). In my vimrc I have (PATH/TO/vim/vimrc) ``` syntax on filetype plugin indent on set nobackup ``` When I "vim blah.py" and `:colorscheme torte`, syntax colors are not loading. For example python keyword doesn't have a proper colors (They...
if it works in c but not on py, the filetype file and/or syntax file is not at the right location for python. [vim manual](http://vimdoc.sourceforge.net/htmldoc/usr_43.html) should help you, but I also would try `:scr` command. This lists all the vim script loaded. So you start vim in two different way `vim your.c` ...
Vim :colorscheme on Python
7,925,623
6
2011-10-28T05:49:24Z
8,054,976
7
2011-11-08T17:58:53Z
[ "python", "osx", "vim", "syntax-highlighting", "osx-lion" ]
I'm using Mac OSX Lion 10.7.2, Terminal.app supports 256 (output of :echo &t\_Co). In my vimrc I have (PATH/TO/vim/vimrc) ``` syntax on filetype plugin indent on set nobackup ``` When I "vim blah.py" and `:colorscheme torte`, syntax colors are not loading. For example python keyword doesn't have a proper colors (They...
The way that I made it to work (I'm using Terminal) is to have `let python_highlight_all = 1` in my ~/.vimrc file and now everything works fine and all objects such as list, tuple, ... are colored. For more information please look at the syntax/python.vim.
Can Mustache Templates do template extension?
7,925,931
41
2011-10-28T06:37:33Z
8,002,498
53
2011-11-03T22:05:48Z
[ "javascript", "python", "ruby", "templates", "mustache" ]
I'm new to Mustache. Many templating languages (e.g., **Django** / **Jinja**) will let you extend a "parent" template like so... ### base.html ``` <html><head></head> <body> {% block content %}{% endblock %} </body> </html> ``` ### frontpage.html ``` {% extends "base.html" %} {% block content %}<h1>Foo...
I recently found myself in the same boat, except I came from a mako background. Mustache does not allow for template extension/inheritance but there are a few options available to you that I know of. 1. You could use partials: ``` {{>header}} Hello {{name}} {{>footer}} ``` 2. You could inject temp...
Can Mustache Templates do template extension?
7,925,931
41
2011-10-28T06:37:33Z
11,637,661
9
2012-07-24T19:07:19Z
[ "javascript", "python", "ruby", "templates", "mustache" ]
I'm new to Mustache. Many templating languages (e.g., **Django** / **Jinja**) will let you extend a "parent" template like so... ### base.html ``` <html><head></head> <body> {% block content %}{% endblock %} </body> </html> ``` ### frontpage.html ``` {% extends "base.html" %} {% block content %}<h1>Foo...
I've proposed this to the specification for Mustache here: <https://github.com/mustache/spec/issues/38> Currently mustache.java, hogan.js and phly\_mustache support template inheritance.
Can Mustache Templates do template extension?
7,925,931
41
2011-10-28T06:37:33Z
12,944,439
8
2012-10-17T22:33:58Z
[ "javascript", "python", "ruby", "templates", "mustache" ]
I'm new to Mustache. Many templating languages (e.g., **Django** / **Jinja**) will let you extend a "parent" template like so... ### base.html ``` <html><head></head> <body> {% block content %}{% endblock %} </body> </html> ``` ### frontpage.html ``` {% extends "base.html" %} {% block content %}<h1>Foo...
Mustache can't. You want [Nunjucks](http://nunjucks.jlongster.com/)! [Author's introduction](http://jlongster.com/Introducing-Nunjucks,-a-Better-Javascript-Templating-System) explains why. All other solutions for inheritance are Bad. It is basically Django (really jinja2) template style, with beautiful inheritanc...
Python best practice and securest to connect to MySQL and execute queries
7,929,364
23
2011-10-28T12:38:48Z
7,929,438
35
2011-10-28T12:45:52Z
[ "python", "mysql", "sql-injection" ]
What is the safest way to run queries on mysql, I am aware of the dangers involved with MySQL and SQL injection. However I do not know how I should run my queries to prevent injection on the variables to which other users (webclients) can manipulate. I used to write my own escape function, but apparently this is "not-...
To avoid injections, use `execute` with `%s` in place of each variable, then pass the value via a list or tuple as the second parameter of `execute`. Here is an [example from the documentation](http://mysql-python.sourceforge.net/MySQLdb.html#some-examples): ``` c=db.cursor() max_price=5 c.execute("""SELECT spam, eggs...
Python best practice and securest to connect to MySQL and execute queries
7,929,364
23
2011-10-28T12:38:48Z
7,929,842
38
2011-10-28T13:22:33Z
[ "python", "mysql", "sql-injection" ]
What is the safest way to run queries on mysql, I am aware of the dangers involved with MySQL and SQL injection. However I do not know how I should run my queries to prevent injection on the variables to which other users (webclients) can manipulate. I used to write my own escape function, but apparently this is "not-...
As an expansion of Bruno's answer, your MySQL client library may support any of several different formats for specifying named parameters. From [PEP 249 (DB-API)](http://www.python.org/dev/peps/pep-0249/), you could write your queries like: ### 'qmark' ``` >>> cursor.execute("SELECT spam FROM eggs WHERE lumberjack = ...
python map object methods
7,929,789
3
2011-10-28T13:18:10Z
7,929,896
9
2011-10-28T13:27:25Z
[ "python" ]
I am looping through an array of objects, calling a method on each like so: ``` for cell in cells: cell.update_type(next_cells[cell.index]) ``` Is there a way to do the equivalent with map()?
It appears `update_type` returns `None`, so you could use: ``` any(cell.update_type(next_cells[cell.index]) for cell in cells) ``` but unless there is a *problem* with a normal loop, just stick with that. It's the most readable and you shouldn't optimize prematurely. You *shouldn't* use `map` here because there is n...
Getting `django-registration` to send you to the page you were originally trying to visit
7,930,526
8
2011-10-28T14:23:57Z
7,952,013
11
2011-10-31T09:45:00Z
[ "python", "django", "django-authentication", "django-registration" ]
`django.contrib.auth` has an awesome feature: When you try to access a page that's decorated by `login_required`, you get redirected to the login page with a `next` argument, so after you login you get redirected back to the page you were originally trying to access. That's good for the user flow. **But,** apparently ...
If you look at the view responsible for the activation of an account via email ([registration.views.activate](https://bitbucket.org/ubernostrum/django-registration/src/fad7080fe769/registration/backends/default/__init__.py)) you'll see that it accepts a **success\_url** parameter which is "The name of a URL pattern to ...
Django ManyToMany FIeld: 'tuple' object has no attribute 'user'
7,931,025
3
2011-10-28T15:00:22Z
7,931,064
9
2011-10-28T15:03:35Z
[ "python", "django", "django-models" ]
Having a little django problem i'm stuck with... My Model: ``` class Mymodel(models.Model): [...] user = models.ManyToManyField(User) ``` My attempt to create a new user on it ``` mymodel = Mymodel.objects.get_or_create(date=date, day=day, time=time) # This one gives a solid Mymodel object i can play with my...
`get_or_create` returns a tuple consisting of (object, created). To get just the model, use: ``` mymodel, _ = Mymodel.objects.get_or_create(date=date, day=day, time=time) ``` or ``` mymodel = Mymodel.objects.get_or_create(date=date, day=day, time=time)[0] ```
Shuffle in Python
7,931,309
8
2011-10-28T15:21:52Z
7,931,355
9
2011-10-28T15:25:15Z
[ "python", "random", "shuffle" ]
Is there a straightforward way to RETURN a shuffled array in Python rather than shuffling it in place? e.g., instead of ``` x = [array] random.shuffle(x) ``` I'm looking for something like ``` y = shuffle(x) ``` which maintains x. Note, I am not looking for a function, not something like: ``` x=[array] y=x rando...
Just write your own. ``` import random def shuffle(x): x = list(x) random.shuffle(x) return x x = range(10) y = shuffle(x) print x # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print y # [2, 5, 0, 4, 9, 3, 6, 1, 7, 8] ```
Shuffle in Python
7,931,309
8
2011-10-28T15:21:52Z
7,931,395
10
2011-10-28T15:28:10Z
[ "python", "random", "shuffle" ]
Is there a straightforward way to RETURN a shuffled array in Python rather than shuffling it in place? e.g., instead of ``` x = [array] random.shuffle(x) ``` I'm looking for something like ``` y = shuffle(x) ``` which maintains x. Note, I am not looking for a function, not something like: ``` x=[array] y=x rando...
It would be pretty simple to implement your own using `random`. I would write it as follows: ``` def shuffle(l): l2 = l[:] #copy l into l2 random.shuffle(l2) #shuffle l2 return l2 #return shuffled l2 ```
Shuffle in Python
7,931,309
8
2011-10-28T15:21:52Z
7,933,993
13
2011-10-28T19:36:23Z
[ "python", "random", "shuffle" ]
Is there a straightforward way to RETURN a shuffled array in Python rather than shuffling it in place? e.g., instead of ``` x = [array] random.shuffle(x) ``` I'm looking for something like ``` y = shuffle(x) ``` which maintains x. Note, I am not looking for a function, not something like: ``` x=[array] y=x rando...
`sorted` with a `key` function that returns a random value: ``` import random sorted(l, key=lambda *args: random.random()) ``` Or ``` import os sorted(l, key=os.urandom) ```
Are datagrams always received completely?
7,931,726
13
2011-10-28T15:57:22Z
7,931,768
12
2011-10-28T16:00:35Z
[ "java", "python", "c", "udp", "datagram" ]
Most datagram receiving functions such as c's recv or read, javas DatagramPacket class or pythons SocketServer, include the possibility to find out the amount of received data. c: ``` int amount = recv(sock, buf, n, MSG_WAITALL); ``` java: ``` int amount = datagramSocket.getLength(); ``` python: ``` class MyUDPHa...
UDP datagrams cannot be partially delivered¹; they are delivered as-is or not at all. So yes, you can be sure that the received datagram was sent exactly as you see it on the receiver's end. *Edit to incorporate Will's comment which is the best kind of correct (i.e., technically):* ¹They can be fragmented at the IP...
Convert Python to R
7,933,400
8
2011-10-28T18:37:57Z
7,933,538
10
2011-10-28T18:52:55Z
[ "python" ]
I know there exists a module (rpy and rpy2) to convert R code to Python. Is there any easy way to do the reverse?
rpy(2) does not convert code. It only allows you an interface to communicate with R from python and issue R commands from within python. Given that R is very dependent upon statistical libraries that aren't available in python the conversion would generally be a tremendous amount of work. To convert a single line like...
How do I set headers using python's urllib?
7,933,417
27
2011-10-28T18:39:49Z
7,933,464
8
2011-10-28T18:44:50Z
[ "python", "http", "header", "urllib" ]
I am pretty new to python's urllib. What I need to do is set a custom header for the request being sent to the server. Specifically, I need to set the Content-type and Authorizations headers. I have looked into the python documentation, but I haven't been able to find it.
Use urllib2 and create a Request object which you then hand to urlopen. <http://docs.python.org/library/urllib2.html> I dont really use the "old" urllib anymore. ``` req = urllib2.Request("http://google.com", None, {'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'...
How do I set headers using python's urllib?
7,933,417
27
2011-10-28T18:39:49Z
7,933,546
40
2011-10-28T18:53:39Z
[ "python", "http", "header", "urllib" ]
I am pretty new to python's urllib. What I need to do is set a custom header for the request being sent to the server. Specifically, I need to set the Content-type and Authorizations headers. I have looked into the python documentation, but I haven't been able to find it.
adding HTTP headers using [urllib2](http://docs.python.org/library/urllib2.html): from the docs: ``` import urllib2 req = urllib2.Request('http://www.example.com/') req.add_header('Referer', 'http://www.python.org/') resp = urllib2.urlopen(req) content = resp.read() ```
How do I set headers using python's urllib?
7,933,417
27
2011-10-28T18:39:49Z
24,870,196
10
2014-07-21T16:37:22Z
[ "python", "http", "header", "urllib" ]
I am pretty new to python's urllib. What I need to do is set a custom header for the request being sent to the server. Specifically, I need to set the Content-type and Authorizations headers. I have looked into the python documentation, but I haven't been able to find it.
For both Python 3 and Python 2, this works: ``` try: from urllib.request import Request, urlopen # Python 3 except: from urllib2 import Request, urlopen # Python 2 q = Request('http://api.company.com/items/details?country=US&language=en') q.add_header('apikey', 'xxx') a = urlopen(q).read() print(a) ```
Python - Write To Beginning and End of Every Line in TXT
7,933,472
2
2011-10-28T18:45:22Z
7,933,542
7
2011-10-28T18:53:04Z
[ "python", "text", "text-files", "readlines" ]
I'm currently looking for a way to write to beginning and end of every line of a TXT file in Python. For example, **Current TXT document:** ``` Jimmy Was Here ``` **Write the 1st VALUE to the beginning of every line** ``` 111Jimmy 111Was 111Here ``` **Write the 2nd VALUE to the end of every line** ``` 111Jimmy222...
``` prefix = '111' suffix = '222' with open('source.txt', 'r') as src: with open('dest.txt', 'w') as dest: for line in src: dest.write('%s%s%s\n' % (prefix, line.rstrip('\n'), suffix)) ```
Django dynamic model fields
7,933,596
103
2011-10-28T18:58:20Z
7,934,577
195
2011-10-28T20:32:06Z
[ "python", "django", "dynamic", "django-models", "django-custom-manager" ]
I'm working on a **multi-tenanted** application in which some users can define their own data fields (via the admin) to collect additional data in forms and report on the data. The latter bit makes JSONField not a great option, so instead I have the following solution: ``` class CustomDataField(models.Model): """ ...
***As of today, there are four available approaches, two of them requiring a certain storage backend:*** 1. **[Django-eav](https://github.com/mvpdev/django-eav)** (the original package is no longer mantained but has some **[thriving forks](https://github.com/mvpdev/django-eav/network)**) This solution is based on ...
Django dynamic model fields
7,933,596
103
2011-10-28T18:58:20Z
9,055,271
10
2012-01-29T17:44:34Z
[ "python", "django", "dynamic", "django-models", "django-custom-manager" ]
I'm working on a **multi-tenanted** application in which some users can define their own data fields (via the admin) to collect additional data in forms and report on the data. The latter bit makes JSONField not a great option, so instead I have the following solution: ``` class CustomDataField(models.Model): """ ...
I've been working on pushing the django-dynamo idea further. The project is still undocumented but you can read the code at <https://github.com/charettes/django-mutant>. Actually FK and M2M fields (see contrib.related) also work and it's even possible to define wrapper for your own custom fields. There's also support...
Python: find closest key in a dictionary from the given input key
7,934,547
7
2011-10-28T20:28:52Z
7,934,624
13
2011-10-28T20:35:28Z
[ "python", "algorithm", "dictionary" ]
I have a data in form a dictionary.. NOw I take the input from the user and it can be anything.. And I am trying to do the following. If the key exists then cool.. fetch the value from the dictionary. if not, then fetch the nearest (in numeric sense). For example..if the input key is 200 and the keys are like :.... ``...
here's your function on one line: ``` data.get(num, data[min(data.keys(), key=lambda k: abs(k-num))]) ``` edit: to not evaluate the min when the key is in the dict use: ``` data[num] if num in data else data[min(data.keys(), key=lambda k: abs(k-num))] ``` or if all values in `data` evaluate to `True` you can use: ...
Python: find closest key in a dictionary from the given input key
7,934,547
7
2011-10-28T20:28:52Z
7,935,325
17
2011-10-28T21:57:00Z
[ "python", "algorithm", "dictionary" ]
I have a data in form a dictionary.. NOw I take the input from the user and it can be anything.. And I am trying to do the following. If the key exists then cool.. fetch the value from the dictionary. if not, then fetch the nearest (in numeric sense). For example..if the input key is 200 and the keys are like :.... ``...
This issue is made a lot harder by dict keys being in no particular order. If you can play with how you make the dict so they are in order (like your example) and use python >= 2.7 you can use [OrderedDict](http://docs.python.org/library/collections.html#collections.OrderedDict) and [bisect](http://docs.python.org/libr...
Python: find closest key in a dictionary from the given input key
7,934,547
7
2011-10-28T20:28:52Z
22,997,000
7
2014-04-10T19:13:13Z
[ "python", "algorithm", "dictionary" ]
I have a data in form a dictionary.. NOw I take the input from the user and it can be anything.. And I am trying to do the following. If the key exists then cool.. fetch the value from the dictionary. if not, then fetch the nearest (in numeric sense). For example..if the input key is 200 and the keys are like :.... ``...
Rather than using OrderedDict and bisect, consider the [SortedDict](http://www.grantjenks.com/docs/sortedcontainers/sorteddict.html) type in the [sortedcontainers](http://www.grantjenks.com/docs/sortedcontainers/) module. It's a pure-Python and [fast-as-C implementation](http://www.grantjenks.com/docs/sortedcontainers/...
Python overwriting variables in nested functions
7,935,966
29
2011-10-28T23:43:45Z
7,935,984
27
2011-10-28T23:46:14Z
[ "python", "scope" ]
Suppose I have the following python code: ``` def outer(): string = "" def inner(): string = "String was changed by a nested function!" inner() return string ``` I want a call to outer() to return "String was changed by a nested function!", but I get "". I conclude that Python thinks that the ...
In Python 3.x, you can use the [`nonlocal`](http://docs.python.org/release/3.1.3/reference/simple_stmts.html#nonlocal) keyword: ``` def outer(): string = "" def inner(): nonlocal string string = "String was changed by a nested function!" inner() return string ``` In Python 2.x, you cou...
Python overwriting variables in nested functions
7,935,966
29
2011-10-28T23:43:45Z
27,910,553
11
2015-01-12T20:52:15Z
[ "python", "scope" ]
Suppose I have the following python code: ``` def outer(): string = "" def inner(): string = "String was changed by a nested function!" inner() return string ``` I want a call to outer() to return "String was changed by a nested function!", but I get "". I conclude that Python thinks that the ...
You can also get around this by using function attributes: ``` def outer(): def inner(): inner.string = "String was changed by a nested function!" inner.string = "" inner() return inner.string ``` Clarification: this works in both python 2.x and 3.x.
Writing to a new directory in Python without changing directory
7,935,972
8
2011-10-28T23:44:31Z
7,936,073
9
2011-10-29T00:10:22Z
[ "python", "file", "rss", "io", "folders" ]
Currently, I have the following code... ``` file_name = content.split('=')[1].replace('"', '') #file, gotten previously fileName = "/" + self.feed + "/" + self.address + "/" + file_name #add folders output = open(file_name, 'wb') output.write(url.read()) output.close() ``` My goal is to have python write the file (u...
First, I'm not 100% confident I understand the question, so let me state my assumption: 1) You want to write to a file in a directory that doesn't exist yet. 2) The path is relative (to the current directory). 3) You don't want to change the current directory. So, given that: Check out these two functions: os.makedirs...
Text alignment in a Matplotlib legend
7,936,034
10
2011-10-29T00:00:46Z
8,078,114
11
2011-11-10T10:30:28Z
[ "python", "matplotlib", "legend" ]
I am trying to right-align the entries in a matplotlib axes legend (by default they are left-aligned), but can't seem to find any way of doing this. The setup I have is below: (I have added data and labels to my\_fig axes using the ax.plot() command) ``` ax = my_fig.get_axes()[0] legend_font = FontProperties(size=10)...
The backdoor you're looking for is the following: ``` # get the width of your widest label, since every label will need # to shift by this amount after we align to the right shift = max([t.get_window_extent().width for t in legend.get_texts()]) for t in legend.get_texts(): t.set_ha('right') # ha is alias for hori...
Any good implementation of greedy set cover for large datasets?
7,936,037
5
2011-10-29T00:01:14Z
7,936,220
7
2011-10-29T00:41:28Z
[ "python", "algorithm", "numpy", "scipy", "linear-programming" ]
This question follows from a related question of mine posted [here](http://stackoverflow.com/questions/7927787/finding-an-optimal-solution-that-minimizes-a-constraint). @mhum suggested that my problem falls into the *covering problem* domain. I tried encoding my question into a minimum set cover problem and currently I...
There is a well-known greedy approximation algorithm for set cover that is also easy to implement in whatever language of your choice. The algorithm itself is described here: <http://en.wikipedia.org/wiki/Set_cover_problem#Greedy_algorithm> It is so simple that the easiest thing is just to write it from scratch. Not...
Python: "Self" is not not defined?
7,936,426
3
2011-10-29T01:35:25Z
7,936,436
10
2011-10-29T01:38:11Z
[ "python", "python-3.x", "self", "defined" ]
Back with the same confusing script.. there was A LOT of spacing issues that I fixed... but seem to be missing more? Whats wrong with this -- its saying line 332 `self` is not defined... Here are a few lines above and below that script in case it matters: ``` #-Whats being decompiled start #map(None,*list) = zip(*lis...
If the code excerpt accurately reflects what's in your program the problem is that you have only a single line in your `__init__` constructor. You need to fix your indentation. `Self` is only defined in member functions. Your non-indented code is not part of the constructor, but is actually getting run when you `impor...
How to remove the row that has special characters in it
7,937,042
3
2011-10-29T04:38:11Z
7,937,051
8
2011-10-29T04:42:37Z
[ "python", "linux", "bash" ]
I have a large text file that has a lot of special characters in it like "$!@%#$/" plus many more and I would like to remove the line in the text file if it has any special characters in that line. The only characters I want to keep is a-z and A-Z. If this was the file... ``` !Somejunk)(^% )%(&_ this my_file is *(%%$...
``` $ grep '^[[:alpha:]]\+$' << EOF > !Somejunk)(^% > )%(&_ > this > my_file > is > *(%%$ > the > they're > file > EOF this is the file ```
Django-mptt order
7,937,130
7
2011-10-29T05:11:05Z
9,128,479
8
2012-02-03T12:11:48Z
[ "python", "django", "django-mptt" ]
In my project I am using django-mptt for categories. My model: ``` class Category(models.model): name = models.CharField() parent = models.ForeignKey("self", blank=True, null=True, related_name="sub_category") nav_order = models.IntegerField(null=False, blank=False, default=0) ...
When defining the model you can specify the ordering with "order\_insertion\_by". So something like this: ``` class Category(MPTTModel): name = models.CharField() parent = models.ForeignKey("self", blank=True, null=True, related_name="sub_category") class MPTTMeta: order_insertion_b...
Default method implementations in python(__str__,__eq__,__repr__,ect.)
7,937,994
4
2011-10-29T09:18:49Z
7,938,051
8
2011-10-29T09:30:32Z
[ "python", "oop", "metaprogramming" ]
Are there any ways to add a simple implementations for `__str__`,`__eq__`,`__repr__` to a class? Basically I want an `__eq__` to be just be whether all non prefixed instance variables are equal. And a `__str__`/`__repr__` that just names each variable and calls str/repr on each variable. Is there a mechanism for t...
You could define a `Default` mixin: ``` class Default(object): def __repr__(self): return '-'.join( str(getattr(self,key)) for key in self.__dict__ if not key.startswith('_')) def __eq__(self,other): try: return all(getattr(self,key)==getattr(other,key) ...
How to get value from selected item in treeview in PyGTK?
7,938,007
10
2011-10-29T09:22:06Z
7,938,561
20
2011-10-29T11:19:15Z
[ "python", "gtk", "pygtk", "gtktreeview" ]
I'm learning PyGtk. I have a simple treeview with 1 column, I get items for that treeview from list. How to get value of selected item in treeview?
You may use the [gtk.TreeView.get\_selection()](http://www.pygtk.org/docs/pygtk/class-gtktreeview.html#method-gtktreeview--get-selection) method to get the `gtk.TreeSelection`. Next, you should use the [gtk.TreeSelection.get\_selected\_rows()](http://www.pygtk.org/docs/pygtk/class-gtktreeselection.html#method-gtktrees...
Terminal in broken state (invisible text / no echo) after exit() during input() / raw_input()
7,938,402
11
2011-10-29T10:49:05Z
7,938,912
12
2011-10-29T12:31:31Z
[ "python", "terminal", "python-3.x", "pyqt", "pyqt4" ]
I've been writing a small utility application using Python 3 (the below testcase also works in Python 2, however) and PyQt 4 that uses the `code` module to spawn a REPL prompt allowing interaction with a Qt window. Unfortunately I've hit a problem I've been unable to solve: When I `exit()` the app while `code` is insi...
This is no real solution to the problem, but if you type "reset" in the terminal after you've closed the app, it goes back to normal. I had similar issues once when developing a c application that didn't close a pipe correctly. Maybe something similar is happening here aswell.
Terminal in broken state (invisible text / no echo) after exit() during input() / raw_input()
7,938,402
11
2011-10-29T10:49:05Z
24,780,259
7
2014-07-16T11:59:37Z
[ "python", "terminal", "python-3.x", "pyqt", "pyqt4" ]
I've been writing a small utility application using Python 3 (the below testcase also works in Python 2, however) and PyQt 4 that uses the `code` module to spawn a REPL prompt allowing interaction with a Qt window. Unfortunately I've hit a problem I've been unable to solve: When I `exit()` the app while `code` is insi...
Try `os.system('stty sane')`. The `stty sane` is supposed to reset echo, and some other things apparently.
Using python multiprocessing pipes
7,938,457
12
2011-10-29T10:58:57Z
7,942,344
7
2011-10-29T23:30:06Z
[ "python", "multiprocessing", "pipe", "python-2.6" ]
I am trying to write a class that will calculate checksums using multiple processes, thereby taking advantage of multiple cores. I have a quite simple class for this, and it works great when executing a simple case. But whenever I create two or more instances of the class, the worker never exits. It seems like it never...
Yep, that is surprising behaviour indeed. However, if you look at the output of `lsof` for the two parallel child processes it is easy to notice that the second child process has more file descriptors open. What happens is that when two parallel child processes get started the second child inherits the pipes of the p...
ab is erroring out with apr_socket_recv: Connection refused (61)
7,938,869
60
2011-10-29T12:21:55Z
8,114,719
129
2011-11-13T21:02:55Z
[ "python", "apachebench", "eventlet" ]
I am testing eventlet out, and I am getting this error: ``` ~>ab -n 10 -c 1 http://localhost:8090/ This is ApacheBench, Version 2.3 <$Revision: 655654 $> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking localhost (...
I found using 127.0.0.1 rather than localhost worked: `ab -n 10 -c 1 http://127.0.0.1:8090/` Update: May have been a bug in ab: <https://groups.google.com/forum/#!msg/nodejs/TZU5H7MdoII/yivu0d4LMaAJ>
ab is erroring out with apr_socket_recv: Connection refused (61)
7,938,869
60
2011-10-29T12:21:55Z
8,825,278
12
2012-01-11T19:17:07Z
[ "python", "apachebench", "eventlet" ]
I am testing eventlet out, and I am getting this error: ``` ~>ab -n 10 -c 1 http://localhost:8090/ This is ApacheBench, Version 2.3 <$Revision: 655654 $> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking localhost (...
New version's apache have fix the issue. Only have to rebuild ab. Try to download latest package from <http://archive.apache.org/dist/> Have to patch apache and build a new ab. ``` $ wget http://archive.apache.org/dist/httpd/httpd-2.3.16-beta.tar.bz2 $ tar jxvf httpd-2.3.16-beta.tar.bz2 $ cd httpd-2.3.16-beta $ ./c...
Zeromq with python hangs if connecting to invalid socket
7,939,977
2
2011-10-29T16:03:06Z
8,132,499
7
2011-11-15T06:48:29Z
[ "python", "zeromq" ]
If I connect to an inexistent socket with pyzmq I need to hit CTRL\_C to stop the program. Could someone explay why this happens? ``` import zmq INVALID_ADDR = 'ipc:///tmp/idontexist.socket' context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect(INVALID_ADDR) socket.send('hello') poller = zmq.Poll...
This question was also [posted](https://github.com/zeromq/pyzmq/issues/153) as a pyzmq Issue on GitHub. I will paraphrase my explanation here (I hope that is appropriate, I am fairly new to SO): A general rule: When in doubt, hangs at the end of your zeromq program are due to LINGER. The hang here is caused by the LI...
Getting the array as GET query parameters in Python
7,940,085
27
2011-10-29T16:22:35Z
7,940,290
25
2011-10-29T16:57:51Z
[ "python", "list", "flask", "request", "werkzeug" ]
I know in php I could just use `$_GET['key1']['key2']` to retrieve GET data that is sent in the form of an array but is that something possible in Python as I just receive a string and it's not recognized as an array/list. I use flask/werkzeug if that matters.
The deep parsing of argument names is unique for PHP AFAIK. If you need just a simple list, just pass several parameters with the same name and use `request.args.getlist(<paramname>)` ([documentation](http://werkzeug.pocoo.org/docs/wrappers/#werkzeug.wrappers.BaseRequest.args)). Otherwise you have to parse the query ...
Getting the array as GET query parameters in Python
7,940,085
27
2011-10-29T16:22:35Z
7,940,355
38
2011-10-29T17:07:51Z
[ "python", "list", "flask", "request", "werkzeug" ]
I know in php I could just use `$_GET['key1']['key2']` to retrieve GET data that is sent in the form of an array but is that something possible in Python as I just receive a string and it's not recognized as an array/list. I use flask/werkzeug if that matters.
`request.args` is a MultiDict instance ([MultiDict](http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.MultiDict), [Flask request api](http://flask.pocoo.org/docs/api/#flask.Request)). ``` request.args[key] ## returns a single value, the first if there are multiple request.args.getlist(key) ## retu...
Write to File open in Second Function (Python)
7,940,321
4
2011-10-29T17:02:39Z
7,940,395
7
2011-10-29T17:12:45Z
[ "python", "function" ]
I currently have the below function within my code:- ``` def openFiles(): file1 = open('file1.txt', 'w') file2 = open('file2.txt', 'w') ``` What I'm hoping to do is now, in a second method is to write to the open file. However, whenever I try to write to the files using for example "file1.write("hello")", an ...
You can use python global keyword as shown below. ``` def openFiles(): global file1 global file2 file1 = open('file1.txt', 'w') file2 = open('file2.txt', 'w') def writeFiles(): file1.write("hello") openFiles() writeFiles() ``` However I would recommend you use a class for this instead. For examp...
is it possible to overwrite "self" to point to another object inside self.method in python?
7,940,470
5
2011-10-29T17:26:03Z
7,940,581
8
2011-10-29T17:42:14Z
[ "python", "python-c-api" ]
``` class Wrapper(object): def __init__(self, o): # get wrapped object and do something with it self.o = o def fun(self, *args, **kwargs): self = self.o # here want to swap # or some low level C api like # some_assign(self, self.o) # so that it swaps id() mem addr...
Assigning to `self` inside a method simply rebinds the local variable `self` to the new object. Generally, an assignment to a bare name never changes any objects, it just rebinds the name on the left-hand side to point to the object on the right-hand side. So what you would need to do is modify the object `self` point...
Parsing HTML with XPath, Python and Scrapy
7,941,060
2
2011-10-29T19:09:20Z
8,926,962
9
2012-01-19T13:37:57Z
[ "python", "xpath", "scrapy" ]
I am writing a Scrapy program to extract the data. [This is the url](http://deepstylekorea.com/shop/step1.php?number=1345), and I want to scrape `20111028013117` (code) information. I have taken XPath from FireFox add-on [XPather](https://addons.mozilla.org/en-US/firefox/addon/xpather/). This is the path: ``` /html/b...
The reason of why your xpath doesn't work is becuase of `tbody`. You have to remove it and check if you get that result that you want. You can read this in scrapy documentation: <http://doc.scrapy.org/en/0.14/topics/firefox.html> > Firefox, in particular, is known for adding `<tbody>` elements to > tables. Scrapy, on...
Is there a function to make scatterplot matrices in matplotlib?
7,941,207
18
2011-10-29T19:36:41Z
7,941,594
10
2011-10-29T20:48:07Z
[ "python", "matplotlib", "scatter-plot" ]
Example of scatterplot matrix ![enter image description here](http://i.stack.imgur.com/Sz6SK.jpg) Is there such a function in matplotlib.pyplot?
Generally speaking, matplotlib doesn't usually contain plotting functions that operate on more than one axes object (subplot, in this case). The expectation is that you'd write a simple function to string things together however you'd like. I'm not quite sure what your data looks like, but it's quite simple to just bu...
Is there a function to make scatterplot matrices in matplotlib?
7,941,207
18
2011-10-29T19:36:41Z
20,027,942
43
2013-11-17T06:36:52Z
[ "python", "matplotlib", "scatter-plot" ]
Example of scatterplot matrix ![enter image description here](http://i.stack.imgur.com/Sz6SK.jpg) Is there such a function in matplotlib.pyplot?
For those who don't want to define own functions, there's a great Data Analysis libarary in Python, called [Pandas](http://pandas.pydata.org), where you can find [scatter\_matrix()](http://pandas.pydata.org/pandas-docs/stable/visualization.html#scatter-plot-matrix) method: ``` from pandas.tools.plotting import scatter...