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
Python lists of lists order of operations
8,585,614
2
2011-12-21T05:53:23Z
8,585,666
8
2011-12-21T05:59:03Z
[ "python", "list", "matrix" ]
Here's a list of lists: ``` a = [[1,2,3],[4,5,6],[7,8,9]] ``` To get the number 4 from the variable 'a', I would call `a[1][0]` but if instead of numbers what if they were lists: ``` a = [[[1],[2],[3]], [[4],[5],[6]], [[7],[8],[9]]] ``` To get the number 4 now, would it be `a[0][1][0]` or `a[1][0][0]`? I know I ca...
Python evaluates expressions like `a[1][0][0]` from left to right. The parts of this expression are: 1. `a` which is the list `[[[1],[2],[3]],[[4],[5],[6]],[[7],[8],[9]]]` 2. `a[1]` which is the list `[[4],[5],[6]]` 3. `a[1][0]` which is the list `[4]` 4. `a[1][0][0]` which is the integer `4`.
Linear X Logarithmic scale
8,586,216
7
2011-12-21T07:12:26Z
8,587,609
13
2011-12-21T09:30:22Z
[ "python", "math" ]
Given a line `X` pixels long like: > ``` > 0-------|---V---|-------|-------|-------max > ``` If `0 <= V <= max`, in linear scale `V` position would be `X/max*V` pixels. How can I calculate the pixel position for a logarithmic scale, and starting from the pixel position how can I get back the value of V? 1. It is no...
So you've got some arbitrary value `V`, and you know that 0 <= `V` <= `Vmax`. You want to calculate the x-coordinate of a pixel, call it `X`, where your "screen" has x-coordinates from 0 to `Xmax`. As you say, to do this the "normal" way, you'd do ``` X = Xmax * V / Vmax V = Vmax * X / Xmax ``` I like to think of it ...
Python regex for integer?
8,586,346
7
2011-12-21T07:27:00Z
8,586,432
40
2011-12-21T07:35:07Z
[ "python", "regex", "django", "forms" ]
I'm learning reg ex and I would like to use a regular expression in Python to define only integers - whole numbers not decimals. I could make one that only allows numbers by using `d`, but it also allows decimal numbers which I don't want: ``` price = TextField(_('Price'),[validators.Regexp('\d', message=_('This is no...
Regexp work on the character base, and `\d` means a single digit `0`...`9` and not a decimal number. A regular expression that matches only integers could be for example ``` ^-?[0-9]+$ ``` meaning 1. `^` start of string 2. `-?` an optional (this is what `?` means) minus sign 3. `[0-9]+` one or more digits (the plus...
Get required fields from Document in mongoengine?
8,586,738
6
2011-12-21T08:13:01Z
8,587,151
10
2011-12-21T08:52:05Z
[ "python", "mongodb", "mongoengine" ]
I want to be able to get a list or some sort of set of fields that are required by the document i've created. For instance, here is my document: ``` nickName = StringField(required=True) password = StringField(required=True) firstName = StringField() lastName = StringField() joinDate ...
You can loop through the Class.\_fields property. If your class was called User you could do this: ``` >>> [k for k,v in User._fields.iteritems() if v.required] ['joinDate', 'password', 'nickName', 'lastVisited'] ``` To get a sorted list based on creation you can use the creation counter like so: ``` >>> from opera...
Writing complex custom metadata on images through python
8,586,940
5
2011-12-21T08:32:34Z
8,590,271
9
2011-12-21T13:06:39Z
[ "python", "image", "metadata", "python-imaging-library" ]
I'm looking to write custom metadata on to images(mostly jpegs, but could be others too). So far I haven't been able to do that through PIL preferably (I'm on centos 5 & I couldn't get pyexiv installed) I understand that I can update some pre-defined tags, but I need to create custom fields/tags! Can that be done? Thi...
The python [pyexiv2 module](http://tilloy.net/dev/pyexiv2/api.html) can read/write metadata. I think there is a limited set of valid EXIF tags. I don't know how, or if it is possible to create your own custom tags. However, you could use the Exif.Photo.UserComment tag, and fill it with JSON: ``` import pyexiv2 import...
How does variable swapping work internally?
8,587,236
13
2011-12-21T08:59:31Z
8,587,264
25
2011-12-21T09:02:24Z
[ "python" ]
Simple and short question. Swapping two variables in Python is very easy: `a, b = b, a`. That's ok, I have no objections :) But I'm interested how it works internally? Does it create some temporary variable by itself or it is something more interesting (I bet so)?
Python source code is converted to [bytecode](http://docs.python.org/glossary.html#term-bytecode) before it is executed. You can see how the swap works internally by using the disassembler `dis` to see what the bytecode looks like: ``` import dis >>> def f(a,b): a, b = b, a >>> dis.dis(f) 1 0 LOAD_FAST ...
SQLAlchemy or psycopg2?
8,588,126
8
2011-12-21T10:08:50Z
8,588,766
23
2011-12-21T11:01:04Z
[ "python", "postgresql", "sqlalchemy", "psycopg2" ]
I am writing a quick and dirty script which requires interaction with a database (PG). The script is a pragmatic, tactical solution to an existing problem. however, I envisage that the script will evolve over time into a more "refined" system. Given the fact that it is currently being put together very quickly (i.e. I...
SQLAlchemy is a ORM, psycopg2 is a database driver. These are completely different things: SQLAlchemy **generates** SQL statements and psycopg2 sends SQL statements to the database. SQLAlchemy depends on psycopg2 or other database drivers to communicate with the database! As a rather complex software layer SQLAlchemy ...
Django reverse url with parameters to a class based view
8,588,522
8
2011-12-21T10:41:14Z
8,588,614
17
2011-12-21T10:48:38Z
[ "python", "django", "hyperlink", "django-class-based-views" ]
I just started learning python and django and I have a question. I got the assignment to turn function views into class based views. But my links wont work now. these are from urls.py: ``` url(r'^$', ContactIndex.as_view()), url(r'^add$', ContactAdd.as_view()), url(r'^([0-9]+)/update$', ContactUpdate.as_view()), url(...
To make url reversing easy, I recommend that you always [name your url patterns](https://docs.djangoproject.com/en/dev/topics/http/urls/#naming-url-patterns). ``` url(r'^$', ContactIndex.as_view(), name="contact_index"), url(r'^add$', ContactAdd.as_view(), name="contact_add"), url(r'^([0-9]+)/update$', ContactUpdate.a...
Does a Python object which doesn't override comparison operators equals itself?
8,588,890
5
2011-12-21T11:12:27Z
8,588,993
8
2011-12-21T11:21:17Z
[ "python", "equality" ]
``` class A(object): def __init__(self, value): self.value = value x = A(1) y = A(2) q = [x, y] q.remove(y) ``` I want to remove from the list a specific object which was added before to it and to which I still have a reference. I do not want an equality test. I want an identity test. This code seems to...
Yes, in your case `q.remove(y)` would remove the first occurrence of an object which compares equal with `y`. However, the way you have defined your `class A`, you wouldn't ever have another object compare equal to `y`, except another reference to `y` itself. This is because no other object could have a memory address...
Logging in Python?
8,589,064
10
2011-12-21T11:26:44Z
8,589,252
11
2011-12-21T11:43:07Z
[ "python", "logging" ]
I have used log4J and log4N on previous not-pythonic projects. I like heirachy of warnings,errors and escalations. The ability to log the error and if it is serious email the support team. Also automatic log file cycling is important as the it will be running on a small LINUX device. Can I do this with the standard Py...
Yes, the [logging module](http://docs.python.org/library/logging.html#module-logging) has log levels DEBUG, INFO, WARNING, ERROR and CRITICAL. You can setup a [SMTPHandler](http://docs.python.org/library/logging.handlers.html#smtphandler) to send mail when the logging level is, say, CRITICAL, and you can setup a [Rotat...
Logging in Python?
8,589,064
10
2011-12-21T11:26:44Z
8,589,256
7
2011-12-21T11:43:26Z
[ "python", "logging" ]
I have used log4J and log4N on previous not-pythonic projects. I like heirachy of warnings,errors and escalations. The ability to log the error and if it is serious email the support team. Also automatic log file cycling is important as the it will be running on a small LINUX device. Can I do this with the standard Py...
The standard Python `logging` module is explicitly inspired by log4J, so you will almost certainly find it suitable. It has the same hierarchy, and you can define handlers that listen to one or more levels and do something appropriate, whether it's log to a file or to an email address via SMTP. See the [Python logging ...
Using array to generate random text
8,589,297
10
2011-12-21T11:47:24Z
8,589,340
17
2011-12-21T11:50:17Z
[ "python", "arrays" ]
I am trying to generate random text using letter frequencies that I have obtained. First, I succeeded with the following code: ``` for i in range(450): outcome=random.random() if 0<outcome<0.06775: sys.stdout.write('a') if 0.06775<outcome<0.07920: sys.stdout.write('b') if 0.07920<outcom...
``` import random import sys import bisect f_list = [0, 0.06775, 0.08242, 0.10199, 0.13522, 0.23703, 0.25514, 0.27324, 0.32793, 0.38483, 0.38577, 0.39278, 0.42999, 0.45023, 0.50728, 0.56756, 0.58256, 0.58391, 0.62924, 0.68509, 0.7616, 0.78481, 0.79229, 0.81161, 0.81251, 0.82718, 0.82773, 0.99998] alphabet = 'abcdefghi...
SqlAlchemy: getting the id of the last record inserted
8,589,674
10
2011-12-21T12:14:50Z
8,590,301
9
2011-12-21T13:08:55Z
[ "python", "postgresql", "sqlalchemy", "psycopg2" ]
I am using SQLAlchemy without the ORM, i.e. using hand crafted SQL statememts to directly interact with the backend db. I am using PG as my backend db (psycopg2 as DB driver) in this instance - I don't know if that affects the answer. I have statements like this (for brevity, assume that conn is a valid connection to ...
User [`lastrowid`](http://www.sqlalchemy.org/docs/core/connections.html?highlight=lastrowid#sqlalchemy.engine.base.ResultProxy.lastrowid) ``` result = conn.execute("INSERT INTO user (name, country_id) VALUES ('Homer', 123)") result.lastrowid ```
SqlAlchemy: getting the id of the last record inserted
8,589,674
10
2011-12-21T12:14:50Z
8,590,931
10
2011-12-21T13:58:03Z
[ "python", "postgresql", "sqlalchemy", "psycopg2" ]
I am using SQLAlchemy without the ORM, i.e. using hand crafted SQL statememts to directly interact with the backend db. I am using PG as my backend db (psycopg2 as DB driver) in this instance - I don't know if that affects the answer. I have statements like this (for brevity, assume that conn is a valid connection to ...
You might be able to use the `RETURNING` clause of the [`INSERT` statement](http://www.postgresql.org/docs/current/interactive/sql-insert.html) like this: ``` result = conn.execute("INSERT INTO user (name, country_id) VALUES ('Homer', 123) RETURNING *") ``` If you only want the resulting `id`: ...
Python iterate over a dictionary
8,589,812
3
2011-12-21T12:26:40Z
8,589,839
13
2011-12-21T12:28:21Z
[ "python" ]
``` In [26]: test = {} In [27]: test["apple"] = "green" In [28]: test["banana"] = "yellow" In [29]: test["orange"] = "orange" In [32]: for fruit, colour in test: ....: print fruit ....: --------------------------------------------------------------------------- ValueError ...
``` for fruit, color in test.iteritems(): # do stuff ``` This is covered in [the tutorial](http://docs.python.org/tutorial/datastructures.html#dictionaries).
Python iterate over a dictionary
8,589,812
3
2011-12-21T12:26:40Z
8,589,860
11
2011-12-21T12:30:05Z
[ "python" ]
``` In [26]: test = {} In [27]: test["apple"] = "green" In [28]: test["banana"] = "yellow" In [29]: test["orange"] = "orange" In [32]: for fruit, colour in test: ....: print fruit ....: --------------------------------------------------------------------------- ValueError ...
Change ``` for fruit, colour in test: print "The fruit %s is the colour %s" % (fruit, colour) ``` to ``` for fruit, colour in test.items(): print "The fruit %s is the colour %s" % (fruit, colour) ``` or ``` for fruit, colour in test.iteritems(): print "The fruit %s is the colour %s" % (fruit, colour) `...
Capturing x,y Coordinates with Python PIL
8,590,234
5
2011-12-21T13:03:21Z
8,590,577
8
2011-12-21T13:29:26Z
[ "python", "python-imaging-library" ]
I want to display an image to the user with PIL and when the user clicks anywhere on this image, I want a def onmousedown(x,y) to be called. I will do some extra stuff in this function. How can I do this in PIL? Thanks,
PIL won't do it alone -- PIL is an image manipulation library with no User Interfaces - it does have a `show`method, which does open an external program which displays the image, but does not communicate back with the Python process. Therefore, in order to be able to get a user to interact with an image, one does have...
How to do POS tagging using the NLTK POS tagger in Python?
8,590,370
19
2011-12-21T13:14:02Z
8,599,513
24
2011-12-22T04:43:48Z
[ "python", "nlp", "nltk", "pos-tagger" ]
I just started using a part-of-speech tagger, and I am facing many problems. I started POS tagging with the following: ``` import nltk text=nltk.word_tokenize("We are going out.Just you and me.") ``` When I want to print `'text'`, the following happens: ``` print nltk.pos_tag(text) Traceback (most recent call last)...
When you type `nltk.download()` in Python, an NLTK Downloader interface gets displayed automatically. Click on Models and choose maxent\_treebank\_pos\_. It gets installed automatically. ``` import nltk text=nltk.word_tokenize("We are going out.Just you and me.") print nltk.pos_tag(text) [('We', 'PRP'), ('are', 'VB...
How to do POS tagging using the NLTK POS tagger in Python?
8,590,370
19
2011-12-21T13:14:02Z
37,651,321
8
2016-06-06T07:01:47Z
[ "python", "nlp", "nltk", "pos-tagger" ]
I just started using a part-of-speech tagger, and I am facing many problems. I started POS tagging with the following: ``` import nltk text=nltk.word_tokenize("We are going out.Just you and me.") ``` When I want to print `'text'`, the following happens: ``` print nltk.pos_tag(text) Traceback (most recent call last)...
From `NLTK` versions higher than v3.2, please use: ``` >>> import nltk >>> nltk.__version__ '3.2.1' >>> nltk.download('averaged_perceptron_tagger') [nltk_data] Downloading package averaged_perceptron_tagger to [nltk_data] /home/alvas/nltk_data... [nltk_data] Package averaged_perceptron_tagger is already up-to-da...
django: Fat models and skinny controllers?
8,590,468
13
2011-12-21T13:21:48Z
8,590,943
23
2011-12-21T13:59:00Z
[ "python", "django", "model-view-controller" ]
This is a general architecture question. I read in many places that in an MVC framework, (1) models ought to be fat, and controllers ought to be skinny. But I also read that (2) the details depend on the framework you're developing in. So, what if you're developing in django? My experience with django is that a lot of...
MVC is not a universal solution and most of the time it's done wrong and can't keep its promises: in practice modifying a model will require modifications in the controller as well, because it's done wrong. If you really want loose coupling between Model and Controller then - and people usually ignore that - you *have ...
Python: Does an iteration through 'list[a:b]' first copy that part of the list (which could be expensive)?
8,590,781
5
2011-12-21T13:46:36Z
8,590,836
8
2011-12-21T13:50:16Z
[ "python" ]
When I iterate through the values of `list1` from `start` to `stop`, as in: ``` for value in list1[start:stop]: .... ``` Does python first copy that part of the list (as is done when doing `list2 = list1[:]`)? This could get very expensive for large lists! If it doesn't copy it in the above example, does that al...
`list1[start:stop]` creates a new list, period. This is always the case, regardless of whether you're iterating over the result directly or have a function in between or use it in any other context (you'd need a moderately static language, or sophisticated type inference, to optimize even for simple instances of the fi...
Iteration count in python?
8,590,810
12
2011-12-21T13:48:45Z
8,590,841
15
2011-12-21T13:50:30Z
[ "python" ]
Let's say I have a list of tuples l, and I do something like this: ``` for (a,b) in l: do something with a,b, and the index of (a,b) in l ``` Is there an easy way to get the index of (a,b)? I can use the index method of list, but what if (a,b) is not unique? I can also iterate on the indexes in the first place, ...
Use [`enumerate()`](http://docs.python.org/library/functions.html#enumerate): ``` for i,(a,b) in enumerate(l): ... # `i` contains the index ```
Iteration count in python?
8,590,810
12
2011-12-21T13:48:45Z
8,590,856
15
2011-12-21T13:51:35Z
[ "python" ]
Let's say I have a list of tuples l, and I do something like this: ``` for (a,b) in l: do something with a,b, and the index of (a,b) in l ``` Is there an easy way to get the index of (a,b)? I can use the index method of list, but what if (a,b) is not unique? I can also iterate on the indexes in the first place, ...
Use [enumerate](http://docs.python.org/library/functions.html#enumerate). ``` for i, (a, b) in enumerate(l): # i will be the index of (a, b) in l ```
Python throws UnicodeEncodeError although I am doing str.decode(). Why?
8,590,912
4
2011-12-21T13:55:57Z
8,592,536
9
2011-12-21T15:51:30Z
[ "python", "string", "encoding", "escaping" ]
Consider this function: ``` def escape(text): print repr(text) escaped_chars = [] for c in text: try: c = c.decode('ascii') except UnicodeDecodeError: c = '&{};'.format(htmlentitydefs.codepoint2name[ord(c)]) escaped_chars.append(c) return ''.join(escaped_...
It's a misleading error-report which comes from the way python handles the de/encoding process. You tried to decode an already decoded String a second time and that confuses the Python function which retaliates by confusing you in turn! ;-) The encoding/decoding process takes place as far as i know, by the codecs-modul...
python xlxml xpath expression to match substring in attribute
8,592,885
4
2011-12-21T16:14:05Z
8,592,964
7
2011-12-21T16:20:49Z
[ "python", "xpath", "lxml" ]
Let's say I have the below XML ``` <root> <element class="Page" style="background: url(/images/RlEguQY3_ghsdr.png?1324483033) repeat left top;" /> <element class="User" /> <element class="Image" src="/images/bg.png" /> </root> ``` I am looking for a xpath expression which 1) matches all elements that have **...
``` //element[contains(@style, '/images') or (@class='Image' and contains(@src, '/images'))] ``` (or something similar) should do it.
Robust Hand Detection via Computer Vision
8,593,091
19
2011-12-21T16:30:57Z
8,598,434
21
2011-12-22T01:25:10Z
[ "python", "image-processing", "opencv", "computer-vision", "skin" ]
I am currently working on a system for robust hand detection. The first step is to take a photo of the hand (in HSV color space) with the hand placed in a small rectangle to determine the skin color. I then apply a thresholding filter to set all non-skin pixels to black and all skin pixels white. So far it works quit...
Have you taken a look at the camshift paper by Gary Bradski? You can download it from [here](http://www.google.com.sg/url?sa=t&rct=j&q=real%20time%20face%20and%20object%20tracking%20as%20a%20component%20of%20a%20perceptual%20user%20interface&source=web&cd=2&ved=0CCgQFjAB&url=http://www.cvmt.dk/education/teaching/CVG9Ex...
Doctests that contain string literals
8,593,315
2
2011-12-21T16:47:25Z
8,594,009
8
2011-12-21T17:42:05Z
[ "python", "comments", "doctest", "python-2.4" ]
I have a unit test that I'd like to write for a function that takes XML as a string. It's a doctest and I'd like the XML in-line with the tests. Since the XML is multi-line, I tried a string literal within the doctest, but no success. Here's simplified test code: ``` def test(): """ >>> config = \"\"\"\ <?xml ve...
This code works: ``` def test(): """ >>> config = '''<?xml version="1.0"?> ... <test> ... <data>d1</data> ... <data>d2</data> ... </test>''' >>> print config <?xml version="1.0"?> <test> <data>d1</data> <data>d2</data> </test> """ if __name__ == "__main__": import doctest doct...
In Python, how do I count the trailing zeros in a string or integer?
8,593,355
3
2011-12-21T16:50:12Z
8,593,399
16
2011-12-21T16:53:34Z
[ "python", "string" ]
I am trying to write a function that returns the number of trailing 0s in a string or integer. Here is what I am trying and it is not returning the correct values. ``` def trailing_zeros(longint): manipulandum = str(longint) x = 0 i = 1 for ch in manipulandum: if manipulandum[-i] == '0': ...
For strings, it is probably the easiest to use [`rstrip()`](http://docs.python.org/library/stdtypes.html#str.rstrip): ``` In [2]: s = '23989800000' In [3]: len(s) - len(s.rstrip('0')) Out[3]: 5 ```
JSON load/dump in Python
8,594,158
7
2011-12-21T17:53:38Z
8,594,204
10
2011-12-21T17:56:59Z
[ "python", "json" ]
From the docs: <http://docs.python.org/library/json.html> ``` >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') [u'foo', {u'bar': [u'baz', None, 1.0, 2]}] ``` I modified it like this: ``` >>> the_dump=json.dumps("['foo', {'bar':['baz', null, 1.0, 2]}]") >>> the_load = json.loads(the_dump) u"['foo', {'bar':['b...
``` >>> the_dump=json.dumps("['foo', {'bar':['baz', null, 1.0, 2]}]") ``` You're asking it to json encode a string, so it's not surprising that you get a string back when you decode. Try instead: ``` >>> the_dump=json.dumps(['foo', {'bar':['baz', None, 1.0, 2]}]) ```
A better pattern for ajax loading with pyramid?
8,594,437
4
2011-12-21T18:17:24Z
8,595,651
8
2011-12-21T20:06:48Z
[ "python", "pyramid" ]
I've read up on [using different renderers](http://stackoverflow.com/questions/6553569/in-pyramid-how-can-i-use-a-different-renderer-based-on-contents-of-context/6557728#6557728) or [overriding renderer](http://stackoverflow.com/questions/8573149/easy-way-to-switch-between-renderers-within-the-same-view-method/8573355#...
I would suggest using 2 views which properly allow you to apply a different "look-and-feel" (responses) to the same data. ``` def get_items(request): return {} # values that you can pick and choose from in each view @view_config(route_name='name', permission='perm', xhr=True, renderer='json') def r_ajax(request):...
Python multiprocessing pipe recv() doc unclear or did I miss anything?
8,594,909
5
2011-12-21T18:59:07Z
8,595,331
8
2011-12-21T19:37:44Z
[ "python", "documentation", "multiprocessing", "pipe" ]
I have been learning how to use the Python multiprocessing module recently, and reading the official doc. In [**16.6.1.2. Exchanging objects between processes**](http://docs.python.org/library/multiprocessing.html#exchanging-objects-between-processes) there is a simple example about using pipe to exchange data. And, i...
When you start a new process with `mp.Process`, the child process inherits the pipes of the parent. When the child closes `conn`, the parent process still has `child_conn` open, so the reference count for the pipe file descriptor is still greater than 0, and so EOFError is not raised. To get the EOFError, close the en...
Nested for loop (list comprehension) in python; outer loop not looping
8,595,803
3
2011-12-21T20:18:08Z
8,595,897
9
2011-12-21T20:24:48Z
[ "python", "nested", "list-comprehension" ]
I am trying to compare data from columns from two different files. I've attempted to use a `for`, and now a `list comprehension`. The issue is that the outer for loop is not being iterated through, but the inner one is. I've checked individually and iteration is just fine; but once I nest I get this issue. Is there so...
Note that in your solution the for loops are nested, so that's why one loop seems to iterate while the other one doesn't seem to. What you need to use to get one element of both iterators at a time is `itertools.izip`: ``` [ oldrow[5] + " " + newrow[3] for oldrow, newrow in itertools.izip(origInv, newInv)] ```
truncate to 3 decimals in python
8,595,973
8
2011-12-21T20:31:09Z
8,595,991
18
2011-12-21T20:32:53Z
[ "python" ]
Self explanatory, I want to get 1324343032.324 As you can see below, the following do not work: ``` >>1324343032.324325235 * 1000 / 1000 1324343032.3243253 >>int(1324343032.324325235 * 1000) / 1000.0 1324343032.3239999 >>round(int(1324343032.324325235 * 1000) / 1000.0,3) 1324343032.3239999 >>str(1324343032.3239999) '...
`'%.3f'%(1324343032.324325235)` Use an additional `float()` around it if you want to preserve it as a float.
python: Accessing an instance variable using a name containing a variable
8,598,095
4
2011-12-22T00:28:40Z
8,598,170
8
2011-12-22T00:42:27Z
[ "python", "variables", "instance" ]
in python I'm trying to access a instance variable where I need to use the value of another variable to determine the name: Example Instance Variable: user.remote.directory where it point to the value of 'servername:/mnt/.....' and user portion contains the userid of the user, such as joe.remote.directory from another...
Unsure quite what you want, but I think `getattr(obj, 'name')` might help. See <http://docs.python.org/library/functions.html#getattr>
f.write vs print >> f
8,598,228
20
2011-12-22T00:50:25Z
8,598,283
18
2011-12-22T01:00:20Z
[ "python" ]
There are at least two ways to write to a file in python: ``` f = open(file, 'w') f.write(string) ``` or ``` f = open(file, 'w') print >> f, string ``` Is there a difference between the two? Or is any one more Pythonic? I'm trying to write a bunch of HTML to file so I need a bunch of write/print statements through ...
`print` does things `file.write` doesn't, allowing you to skip string formatting for some basic things. It inserts spaces between arguments and appends the line terminator. ``` print "a", "b" # prints something like "a b\n" ``` It calls the `__str__` or `__repr__` special methods of an object to convert it to a stri...
f.write vs print >> f
8,598,228
20
2011-12-22T00:50:25Z
8,598,884
11
2011-12-22T02:42:20Z
[ "python" ]
There are at least two ways to write to a file in python: ``` f = open(file, 'w') f.write(string) ``` or ``` f = open(file, 'w') print >> f, string ``` Is there a difference between the two? Or is any one more Pythonic? I'm trying to write a bunch of HTML to file so I need a bunch of write/print statements through ...
I disagree somewhat with several of the opinions expressed here, that `print >> f` is redundant and should be avoided in favour of `f.write`. `print` and `file.write` are quite different operations. `file.write` just directly writes a string to a file. `print` is more like "render values to stdout as text". Naturally,...
How to append error message to form.non_field_errors in django?
8,598,247
8
2011-12-22T00:52:52Z
8,598,842
17
2011-12-22T02:32:40Z
[ "python", "django", "django-forms" ]
I have a form with several fields. I have separate validation checks for each field, done via the forms validation. I however also need to check if few fields are filled in before redirecting the user to a different view. I was hoping I could somehow append the error to forms.non\_field\_errors as it is not for a parti...
1. **Call full\_clean()**, this should initialize `form._errors`. This step is critical, if you don't do it, it won't work. 2. **Make the error list**, it takes a list of messages, instanciate it as such: `error_list = form.error_class(['your error messages'])` 3. **Assign the error list to NON\_FIELD\_ERRORS**, you ha...
how to save a pylab figure into in-memory file which can be read into PIL image?
8,598,673
15
2011-12-22T02:02:24Z
8,598,881
21
2011-12-22T02:41:53Z
[ "python", "python-imaging-library", "matplotlib" ]
new to PIL, but want to get a quick solution out of it. The following is my first shot which never works: ``` import cStringIO import pylab from PIL import Image pylab.figure() pylab.plot([1,2]) pylab.title("test") buffer = cStringIO.StringIO() pylab.savefig(buffer, format='png') im = Image.open(buffer.read()) buffer....
Remember to call `buf.seek(0)` so `Image.open(buf)` starts reading from the beginning of the `buf`: ``` import io from PIL import Image import matplotlib.pyplot as plt plt.figure() plt.plot([1, 2]) plt.title("test") buf = io.BytesIO() plt.savefig(buf, format='png') buf.seek(0) im = Image.open(buf) im.show() buf.close...
Python loops: Precise way to handle mapping matching lists
8,600,516
4
2011-12-22T07:12:58Z
8,600,534
13
2011-12-22T07:14:33Z
[ "python" ]
A function returns two lists which are logically mapped **one-to-one**. Suppose ``` name = ["facebook", "twitter", "myspace"] hits = [4000, 2500, 1800] ``` Therefore, hits for facebook are 4000, twitter 2500, and myspace 2500. **I want to convert these two separate lists into a list of dictionaries** like ``` [ {...
You could do: ``` [{"name": n, "data": [h]} for n, h in zip(name, hits)] ``` While this does what you asked for, there's probably more data structure here than you really need. Consider: ``` >>> dict(zip(name, hits)) {'twitter': 2500, 'myspace': 1800, 'facebook': 4000} ``` This provides the same data set in an easi...
Serving large files ( with high loads ) in Django
8,600,843
15
2011-12-22T07:52:19Z
8,600,924
9
2011-12-22T08:00:58Z
[ "python", "django", "permissions", "download" ]
I've been using a method for serving downloads but since it was not secure i decided to change that . ( the method was a link to the original file in storage , but the risk was that everyone with the link could have downloaded the file ! ) so i now serve the file via my views , that way only users with permission can d...
You can use the 'sendfile' method as described in this [answer](http://stackoverflow.com/questions/1156246/having-django-serve-downloadable-files/1158750#1158750). Practically you need this (c&p): ``` response = HttpResponse(mimetype='application/force-download') response['Content-Disposition'] = 'attachment; filenam...
Serving large files ( with high loads ) in Django
8,600,843
15
2011-12-22T07:52:19Z
8,601,118
38
2011-12-22T08:23:24Z
[ "python", "django", "permissions", "download" ]
I've been using a method for serving downloads but since it was not secure i decided to change that . ( the method was a link to the original file in storage , but the risk was that everyone with the link could have downloaded the file ! ) so i now serve the file via my views , that way only users with permission can d...
Your opening of the image loads it in memory and this is what causes the increase in load under heavy use. As posted by Martin the real solution is to serve the file directly. Here is another approach, which will stream your file in chunks without loading it in memory. ``` import os import mimetypes from django.http ...
python class that acts as mapping for **unpacking
8,601,268
35
2011-12-22T08:39:49Z
8,601,389
46
2011-12-22T08:52:13Z
[ "python", "class", "mapping", "argument-unpacking" ]
Without subclassing dict, what would a class need to be considered a mapping so that it can be passed to a method with \*\* ``` from abc import ABCMeta class uobj: __metaclass__ = ABCMeta uobj.register(dict) def f(**k): return k o = uobj() f(**o) # outputs: f() argument after ** must be a mapping, not uobj ``...
The `__getitem__()` and `keys()` methods will suffice: ``` >>> class D: def keys(self): return ['a', 'b'] def __getitem__(self, key): return key.upper() >>> def f(**kwds): print kwds >>> f(**D()) {'a': 'A', 'b': 'B'} ```
python class that acts as mapping for **unpacking
8,601,268
35
2011-12-22T08:39:49Z
8,613,822
16
2011-12-23T08:37:12Z
[ "python", "class", "mapping", "argument-unpacking" ]
Without subclassing dict, what would a class need to be considered a mapping so that it can be passed to a method with \*\* ``` from abc import ABCMeta class uobj: __metaclass__ = ABCMeta uobj.register(dict) def f(**k): return k o = uobj() f(**o) # outputs: f() argument after ** must be a mapping, not uobj ``...
If you're trying to create a Mapping — not just satisfy the requirements for passing to a function — then you really should inherit from `collections.Mapping`. As described in the [documentation](http://docs.python.org/library/collections.html), you need to implement just: ``` __getitem__ __len__ __iter__ ``` The...
Timing out a multiprocessing function
8,601,856
5
2011-12-22T09:32:03Z
8,601,961
11
2011-12-22T09:39:17Z
[ "python", "timeout" ]
I need to set a time limit on a python function which use some multiprocessing stuff (I don't know if it matters). Something like this: ``` function(a_list): p1 = Process(a_list[0:len(a_list/2)]) p2 = Process(a_list[len(a_list)/2: len(a_list)]) //start and join p1, p2 ``` I look around the net and I ...
You should be able to do that with this code: ``` process.join(timeout) if process.is_alive(): process.terminate() ``` So instead of setting a timeout in the function, you can join with a timeout the process and if the process hasn't finished after that timeout, then terminate it.
weird behaviour with list of dictionaries in python
8,602,963
2
2011-12-22T11:06:15Z
8,602,981
9
2011-12-22T11:08:05Z
[ "python", "list", "dictionary" ]
Here is a simple code that performs operations on lists: ``` >>> a = [0] * 5 >>> a [0, 0, 0, 0, 0] >>> a[0] = 5 >>> a [5, 0, 0, 0, 0] >>> ``` For now, nothing abnormal. Now, I try to do the same with a list of dictionaries instead of a list of integers: ``` >>> a = [{}] * 5 >>> a [{}, {}, {}, {}, {}] >>> a[0]['b'] ...
This is not weird. --- Workaround: ``` a = [{} for i in xrange(5)] ``` --- `[…] * 5` creates one `…` and a list of five pointers to this `…`. `0` is an immutable integer. You cannot modify it, you can just replace it with another integer (such as `a[0] = 5`). Then it is a different integer. `{}` is a mutab...
How TDD can be applied to Django Class based Generic Views?
8,603,035
21
2011-12-22T11:12:23Z
8,603,940
16
2011-12-22T12:36:09Z
[ "python", "django", "testing", "tdd" ]
Since Class based Generic Views in Django involve some work by the framework I find very hard to work with them in a TDD style. Now I use the TestClient to access the view from the http mocked stack, but I would prefer to properly unittest specific methods (es. overrides of get\_object and get\_queryset ) before 'funct...
Generally, that would include creating a request via the [`RequestFactory`](https://docs.djangoproject.com/en/dev/topics/testing/advanced/#django.test.client.RequestFactory) and instantiating the view class with keyword arguments. Afterwards, you can call any of the view methods and evaluate the result, passing any req...
Sqlalchemy in clause
8,603,088
91
2011-12-22T11:16:59Z
8,603,129
119
2011-12-22T11:20:50Z
[ "python", "sqlalchemy" ]
I'm trying to do this query in sqlalchemy ``` SELECT id, name FROM user WHERE id in (123,456) ``` I would like to bind the list [123,456] at execution time.
How about `session.query(MyUserClass).filter(MyUserClass.id.in_((123,456))).all()` ? **edit**: Without the ORM, it would be ``` session.execute( select( [MyUserTable.c.id, MyUserTable.c.name], MyUserTable.c.id.in_((123, 456)) ) ).fetchall() ``` [`select()`](http://docs.sqlalchemy.org/en/rel_...
Sqlalchemy in clause
8,603,088
91
2011-12-22T11:16:59Z
8,603,171
58
2011-12-22T11:23:34Z
[ "python", "sqlalchemy" ]
I'm trying to do this query in sqlalchemy ``` SELECT id, name FROM user WHERE id in (123,456) ``` I would like to bind the list [123,456] at execution time.
Assuming you use the declarative style (i.e. ORM classes), it is pretty easy: ``` query = db_session.query(User.id, User.name).filter(User.id.in_([123,456])) results = query.all() ``` `db_session` is your database session here, while `User` is the ORM class with `__tablename__` equal to `"users"`.
Sqlalchemy in clause
8,603,088
91
2011-12-22T11:16:59Z
29,505,985
10
2015-04-08T04:33:01Z
[ "python", "sqlalchemy" ]
I'm trying to do this query in sqlalchemy ``` SELECT id, name FROM user WHERE id in (123,456) ``` I would like to bind the list [123,456] at execution time.
An alternative way is using raw SQL mode with SQLAlchemy, I use SQLAlchemy 0.9.8, python 2.7, MySQL 5.X, and MySQL-Python as connector, in this case, a tuple is needed. My code listed below: ``` id_list = [1, 2, 3, 4, 5] # in most case we have an integer list or set s = text('SELECT id, content FROM myTable WHERE id I...
Is there a difference between `%`-format operator and `str.format()` in python regarding unicode and utf-8 encoding?
8,603,333
7
2011-12-22T11:37:08Z
8,603,385
10
2011-12-22T11:41:22Z
[ "python", "string", "encoding", "string-formatting" ]
Assume that ``` n = u"Tübingen" repr(n) # `T\xfcbingen` # Unicode i = 1 # integer ``` The first of the following files throws ``` UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 82: ordinal not in range(128) ``` When I do `n.encode('utf8')` it works. The second works flawless in both ...
You're using `string.format` while you don't have a string but an `unicode` object. ``` print u'{id}, {name}'.format(id=i, name=n) ``` will work, since it uses `unicode.format` instead.
How to use django-notification to inform a user when somebody comments on their post
8,603,469
7
2011-12-22T11:49:08Z
8,603,735
11
2011-12-22T12:15:06Z
[ "python", "django", "django-signals", "django-apps", "django-notification" ]
I have been developing in django for sometime now, and have developed a neat website having functionality such as writing blogs, posting questions, sharing content etc. However there is still one thing that is missing and i.e. creating notification for users. What I want to do is to inform users in their profiles, whe...
Yes django-notifications is only designed for email notifications. Here is a signal slot that you can add to your models.py and tweak to your own needs: ``` from django.db import models from django.contrib.sites.models import Site from django.db.models import signals from notification import models as notification d...
ImportError: No module named
8,605,036
2
2011-12-22T14:07:37Z
8,607,578
7
2011-12-22T17:21:25Z
[ "python", "import", "python-3.x", "migrate", "visa" ]
I'm migrating PyVisa from Python 2.6 to Python 3.2. I'm able to install the module. It's listed in `C:\Python32\Lib\site-packages\pyvisa` The `__init__.py` file imports a module (`vpp43.py`) from this folder. At this line I get following error: > ``` > Traceback (most recent call last): > File "D:\Documents and Setti...
In Python 3.x implicit relative imports have gone away. Instead of ``` import configparser, os, sys, vpp43 ``` `pyvisa\__init__.py` needs to say: ``` import configparser, os, sys from . import vpp43 ```
How to translate this Math Formula in Haskell or Python? (Was translated in PHP)
8,605,183
17
2011-12-22T14:20:52Z
8,663,431
14
2011-12-29T02:32:57Z
[ "php", "python", "math", "haskell", "matrix" ]
I'm trying to convert a Math Formula into PHP code. You can see the formula in the accepted answer here: [Applying a Math Formula in a more elegant way (maybe a recursive call would do the trick)](http://math.stackexchange.com/questions/92942/applying-a-math-formula-in-a-more-elegant-way-maybe-a-recursive-call-would-d...
Here you go. I place this code into the public domain. ``` # Function to make an array of 'width' zeros function makerow($width){ $row=array(); for($x=0;$x<$width;$x++){ $row[$x]=0; } return $row; } # Function to make a width*height matrix function makematrix($width,$height){ $matrix=array(); for($y=0;$y<$h...
How to install matplotlib with Python3.2
8,605,847
27
2011-12-22T15:13:40Z
8,606,026
37
2011-12-22T15:29:54Z
[ "python", "numpy", "matplotlib", "python-3.2" ]
I installed python3.2 in ubuntu (the default edition is not deleted), and I follow the steps in [here](http://matplotlib.sourceforge.net/faq/installing_faq.html#how-to-install) However when i use ``` python3.2 setup.py install ``` I got: ``` "error: command 'gcc' failed with exit status 1", "src/ft2font.cpp:2224:2...
Matplotlib supports python 3.x as of version 1.2, released in January, 2013. To install it, have a look at the [installation instructions](http://matplotlib.org/users/installing.html). In general, call `pip install matplotlib` or use your preferred mechanism (`conda`, `homebrew`, windows installer, system package mana...
Finding the source code for built-in Python functions?
8,608,587
43
2011-12-22T19:02:08Z
8,608,609
51
2011-12-22T19:06:01Z
[ "python", "python-internals" ]
> **Possible Duplicate:** > [About python's built in sort() method](http://stackoverflow.com/questions/1517347/about-pythons-built-in-sort-method) Is there a way to see how built in functions work in python? I don't mean just how to use them, but also how were they built, what is the code behind ***sorted*** or ***e...
Since Python is open source you can read the [source code](https://hg.python.org/cpython/file/c6880edaf6f3). To find out what file a particular module or function is implemented in you can usually print the `__file__` attribute. Alternatively, you may use the `inspect` module, see the section [Retrieving Source Code](...
Finding the source code for built-in Python functions?
8,608,587
43
2011-12-22T19:02:08Z
8,608,643
11
2011-12-22T19:10:35Z
[ "python", "python-internals" ]
> **Possible Duplicate:** > [About python's built in sort() method](http://stackoverflow.com/questions/1517347/about-pythons-built-in-sort-method) Is there a way to see how built in functions work in python? I don't mean just how to use them, but also how were they built, what is the code behind ***sorted*** or ***e...
The [iPython](http://ipython.org/) shell makes this easy: `function?` will give you the documentation. `function??` shows also the code. BUT this only works for pure python functions. Then you can always [download](http://python.org/download/source/) the source code for the (c)Python. If you're interested in pythonic...
Finding the source code for built-in Python functions?
8,608,587
43
2011-12-22T19:02:08Z
26,947,116
10
2014-11-15T14:56:36Z
[ "python", "python-internals" ]
> **Possible Duplicate:** > [About python's built in sort() method](http://stackoverflow.com/questions/1517347/about-pythons-built-in-sort-method) Is there a way to see how built in functions work in python? I don't mean just how to use them, but also how were they built, what is the code behind ***sorted*** or ***e...
Here is a cookbook answer to supplement @Chris' answer: 1. Install Mecurial as necessary. 2. `hg clone https://hg.python.org/cpython` 3. Code will checkout to a subdirectory called `cpython` -> `cd cpython` 4. Let's say we are looking for the definition of `print()`... 5. `egrep --color=always -R 'print' | less -R` 6....
Python GTK+ Canvas
8,608,686
3
2011-12-22T19:15:35Z
8,610,359
9
2011-12-22T22:20:06Z
[ "python", "user-interface", "canvas", "gtk", "pygobject" ]
I'm currently learning GTK+ via PyGobject and need something like a canvas. I already searched the docs and found two widgets that seem likely to do the job: GtkDrawingArea and GtkLayout. I need a few basic functions like fillrect or drawline ... In fact these functions are available from c but I couldn't find directio...
In order to illustrate my points made in the comments, let me post a quick'n'dirty PyGtk example that uses a `GtkDrawingArea` to create a canvas and paints into it using cairo **CORRECTION**: you said PyGObject, that is Gtk+3, so the example is as follows (the main difference is that there is no `expose` event, instea...
Why do we use __init__ in python classes?
8,609,153
38
2011-12-22T20:06:39Z
8,609,238
113
2011-12-22T20:15:05Z
[ "python", "class" ]
Sorry if this question is a bit general but its been bugging me because I don't fully understand it. I'm a python newbie and all my programming so far has been functions and I'm starting to look at using classes(since I'm incorporating some other people's code into my programs). I understand the idea behind classes(cr...
By what you wrote, you are missing a critical piece of understanding: the difference between a class and an object. `__init__` doesn't initialize a class, it initializes an instance of a class or an object. Each dog has colour, but dogs as a class don't. Each dog has four or fewer feet, but the class of dogs doesn't. T...
Why do we use __init__ in python classes?
8,609,153
38
2011-12-22T20:06:39Z
8,609,687
9
2011-12-22T21:03:00Z
[ "python", "class" ]
Sorry if this question is a bit general but its been bugging me because I don't fully understand it. I'm a python newbie and all my programming so far has been functions and I'm starting to look at using classes(since I'm incorporating some other people's code into my programs). I understand the idea behind classes(cr...
To contribute my 5 cents to the thorough explanation from Amadan. Where classes are a description "of a type" in an abstract way. Objects are their realizations: the living breathing thing. In the object-orientated world there are principal ideas you can almost call the essence of everything. They are: 1. encapsulati...
differentiate null=True, blank=True in django
8,609,192
362
2011-12-22T20:11:03Z
8,609,425
438
2011-12-22T20:35:26Z
[ "python", "django", "django-models" ]
When we add a database field in django we generally write `models.CharField(max_length=100, null=True, blank=True)`. The same is done with `ForeignKey`, `DecimalField` etc. What is the basic difference in having 1. `null=True` only 2. `blank=True` only 3. `null=True`, `blank=True` in respect to different (`CharField`...
`null=True` sets `NULL` (versus `NOT NULL`) on the column in your DB. Blank values for Django field types such as `DateTimeField` or `ForeignKey` will be stored as `NULL` in the DB. `blank=True` determines whether the field will be required in forms. This includes the admin and your own custom forms. If `blank=True` t...
differentiate null=True, blank=True in django
8,609,192
362
2011-12-22T20:11:03Z
21,812,150
45
2014-02-16T14:00:00Z
[ "python", "django", "django-models" ]
When we add a database field in django we generally write `models.CharField(max_length=100, null=True, blank=True)`. The same is done with `ForeignKey`, `DecimalField` etc. What is the basic difference in having 1. `null=True` only 2. `blank=True` only 3. `null=True`, `blank=True` in respect to different (`CharField`...
This is how the ORM maps `blank` & `null` fields for Django 1.8 ``` class Test(models.Model): charNull = models.CharField(max_length=10, null=True) charBlank = models.CharField(max_length=10, blank=True) charNullBlank = models.CharField(max_length=10, null=True, blank=True) intNull ...
differentiate null=True, blank=True in django
8,609,192
362
2011-12-22T20:11:03Z
23,117,850
8
2014-04-16T18:54:26Z
[ "python", "django", "django-models" ]
When we add a database field in django we generally write `models.CharField(max_length=100, null=True, blank=True)`. The same is done with `ForeignKey`, `DecimalField` etc. What is the basic difference in having 1. `null=True` only 2. `blank=True` only 3. `null=True`, `blank=True` in respect to different (`CharField`...
As said in Django Model Field reference: [Link](https://docs.djangoproject.com/en/dev/ref/models/fields/) ## Field options *The following arguments are available to all field types. All are optional.* ### `null` `Field.null` If `True`, Django will store empty values as `NULL` in the database. Default is `Fals...
Python regular expressions OR
8,609,597
14
2011-12-22T20:53:21Z
8,609,621
25
2011-12-22T20:55:56Z
[ "python", "regex" ]
Suppose I want a regular expression that matches both "Sent from my iPhone" and "Sent from my iPod". How do I write such an expression? I tried things like: ``` re.compile("Sent from my [iPhone]|[iPod]") ``` but doesn't seem to work.
``` re.compile("Sent from my (iPhone|iPod)") ```
Python regular expressions OR
8,609,597
14
2011-12-22T20:53:21Z
8,609,636
9
2011-12-22T20:57:37Z
[ "python", "regex" ]
Suppose I want a regular expression that matches both "Sent from my iPhone" and "Sent from my iPod". How do I write such an expression? I tried things like: ``` re.compile("Sent from my [iPhone]|[iPod]") ``` but doesn't seem to work.
``` re.compile("Sent from my (?:iPhone|iPod)") ``` If you need to capture matches, remove the `?:`. Fyi, your regex didn't work because you are testing for one character out of i,P,h,o,n,e or one character out of i,P,o,d..
Python ImportError: No module named wx
8,609,666
17
2011-12-22T21:00:44Z
29,254,923
9
2015-03-25T11:53:48Z
[ "python", "importerror", "wx" ]
Im sorry to ask this question again. I have searched and found endles repeats of it both on stackoverflow and also on general google search. Unfortunatly I just cant get my system sorted. I have the following: ``` C:\Python27\Lib\site-packages\wx-2.8-msw-unicode ``` this folder contains the wx folder and also wx & w...
Ubuntu: ``` sudo apt-get install python-wxtools ```
Generate in-memory image for Django testing
8,611,651
7
2011-12-23T02:24:13Z
8,611,844
12
2011-12-23T03:01:34Z
[ "python", "django", "django-testing" ]
Is it possible to generate an in-memory image for testing purposes? Here is my current code: ``` def test_issue_add_post(self): url = reverse('issues_issue_add') image = 'cover.jpg' data = { 'title': 'Flying Cars', 'cover': image, } response = self.cli...
To generate a 200x200 test image of solid red: ``` import Image size = (200,200) color = (255,0,0,0) img = Image.new("RGBA",size,color) ``` To convert it to a file-like object, then: ``` import StringIO f = StringIO.StringIO(img.tostring()) ``` <http://effbot.org/imagingbook/image.htm>
Python3 porting: TypeError: unorderable types: dict() < int()
8,613,515
2
2011-12-23T07:50:55Z
8,613,573
10
2011-12-23T07:57:30Z
[ "python", "python-3.x", "porting" ]
I have this piece of code that is working fine in python 2.7. "dist" is a dictionary of number and "min\_dist" is just a number. ``` for v in vertices: if dist[v.node_id] < min_dist: min_dist = dist[v.node_id] cur_min = v ``` Now I am trying to run it under python 3.2 and it gives me this error: ...
Your code is "wrong" in Python 2 as well. It makes no sense to compare a dictionary to an integer. It's like asking if a color is bigger than a number, it simply makes no sense. Python 2 allows comparisons of different types like this, and will always say that a dictionary is larger than a number, which is arbitrary. ...
Jquery and Django CSRF Token
8,614,947
12
2011-12-23T10:29:54Z
8,615,071
22
2011-12-23T10:43:09Z
[ "jquery", "python", "django", "csrf" ]
I have 2 html Pages. A Parent Page and a Child Page. The Child Page Contains a Submit Button that runs code on the Parent Page to submit an Ajax message. I load the child page using $.load() method and then when the button is clicked it runs a $.ajax .POST Method. This post method only passes a JSON String to the Pyt...
You are not passing the csrf token with **POST**. Try doing what I have done in *data*. That is to fetch the csrf token (or your own method) and pass it in your arguments. ``` $.ajax({ url : url, type: "POST", data : {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value}, dat...
Django: Calculate the Sum of the column values through query
8,616,343
20
2011-12-23T12:55:22Z
8,616,400
55
2011-12-23T12:59:08Z
[ "python", "django" ]
I have a model ``` class ItemPrice( models.Model ): price = models.DecimalField ( max_digits = 8, decimal_places=2 ) .... ``` I tried this to calculate the sum of `price` in this queryset: ``` items = ItemPrice.objects.all().annotate(Sum('price')) ``` what's wrong in this query? or is there any other way ...
You're probably looking for [`aggregate`](https://docs.djangoproject.com/en/dev/topics/db/aggregation/) ``` from django.db.models import Sum ItemPrice.objects.aggregate(Sum('price')) ```
How to make SMTPHandler not block
8,616,617
4
2011-12-23T13:25:15Z
8,644,081
10
2011-12-27T11:22:08Z
[ "python", "logging", "smtp", "handler" ]
I installed a local [SMTP server](http://www.hmailserver.com/) and used [`logging.handlers.SMTPHandler`](http://docs.python.org/library/logging.handlers.html#smtphandler) to log an exception using this code: ``` import logging import logging.handlers import time gm = logging.handlers.SMTPHandler(("localhost", 25), 'in...
Here's the implementation I'm using, which I based on [this Gmail adapted SMTPHandler](http://mynthon.net/howto/-/python/python%20-%20logging.SMTPHandler-how-to-use-gmail-smtp-server.txt). I took the part that sends to SMTP and placed it in a different thread. ``` import logging.handlers import smtplib from threadin...
Time out decorator on a multprocessing function
8,616,630
5
2011-12-23T13:26:59Z
8,620,034
8
2011-12-23T19:48:49Z
[ "python", "timeout", "multiprocessing", "signals" ]
I have this decorator taken directly from an example I found on the net: ``` class TimedOutExc(Exception): pass def timeout(timeout): def decorate(f): def handler(signum, frame): raise TimedOutExc() def new_f(*args, **kwargs): old = signal.signal(signal.SIGALRM, hand...
While I agree with the main point of Aaron's answer, I would like to elaborate a bit. The processes launched by `multiprocessing` must be stopped *in the function to be decorated*; I don't think that this can be done generally and simply from the decorator itself (the decorated function is the only entity that knows w...
Python - Getting all links from a div having a class
8,616,928
5
2011-12-23T14:00:31Z
8,617,025
18
2011-12-23T14:11:05Z
[ "python" ]
I am using BeautifulSoup to get all links of mobile phones from this url <http://www.gsmarena.com/samsung-phones-f-9-0-p2.php> My code for the following is : ``` import urllib2 from BeautifulSoup import BeautifulSoup url = "http://www.gsmarena.com/samsung-phones-f-9-0-p2.php" text = urllib2.urlopen(url).read(); soup...
There are only three `<div>` elements in that page with a class of 'makers', this will print the first link from each div, so three in all. This is likely closer to what you desire: ``` import urllib2 from BeautifulSoup import BeautifulSoup url = "http://www.gsmarena.com/samsung-phones-f-9-0-p2.php" text = urllib2.u...
How to properly handle and retain system shutdown (and SIGTERM) in order to finish its job in Python?
8,617,363
6
2011-12-23T14:51:57Z
11,858,588
9
2012-08-08T06:08:35Z
[ "python", "unix" ]
**Basic need :** I've a Python daemon that's calling another program through os.system. My wish is to be able to properly to handle system shutdown or SIGTERM in order to let the called program return and then exiting. **What I've already tried:** I've tried an approach using signal : ``` import signal, time def han...
Your code does almost work, except you forgot to exit after cleaning up. We often need to catch various other signals such as INT, HUP and QUIT, but not so much with daemons. ``` import sys, signal, time def handler(signum = None, frame = None): print 'Signal handler called with signal', signum time.sleep(1)...
A nice way to find all combinations that give a sum of N?
8,617,455
5
2011-12-23T15:01:32Z
8,617,488
12
2011-12-23T15:05:06Z
[ "python" ]
Is there a nice way for generating a list of digits (0-9), with repetitions and a length of 6, such that the sum is N, say, 20. For example: ``` 004673 -> 4+6+7+3=20 121673 -> 1+2+1+6+7+3=20 ... ``` Thanks
``` ['{0:06}'.format(i) for i in xrange(1000000) if sum(map(int,str(i))) == 20] ``` does the trick and needs about 5 seconds to return all 35127 numbers. **UPDATE** - as a bonus, here comes the ugly-but-much-faster (~40 times faster) version: ``` result = [] for a in xrange(10): for b in xrange(10): for ...
Creating C structs in Cython
8,617,890
7
2011-12-23T15:45:47Z
8,647,997
9
2011-12-27T18:33:23Z
[ "python", "c", "struct", "cython" ]
I'd like to create my very own list container using Cython. I'm a very new begginer to it, and following the documentation I could get to creating such a structure : ``` cdef struct s_intList: int value void* next ctypedef s_intList intList ``` but when comes the time to acces the struct members, I can't ...
You have to allocate the memory for the intList. Either with a local variable or using malloc. ``` cdef struct s_intList: int value void* next ctypedef s_intList intList cpdef object foo(): cdef intList li li.value = 10 ```
Django filter queryset __in for *every* item in list
8,618,068
38
2011-12-23T16:01:46Z
8,637,972
45
2011-12-26T17:54:51Z
[ "python", "django", "filter", "django-queryset" ]
Let's say I have the following models ``` class Photo(models.Model): tags = models.ManyToManyField(Tag) class Tag(models.Model): name = models.CharField(max_length=50) ``` In a view I have a list with active filters called *categories*. I want to filter Photo objects which have all tags present in *categorie...
**Summary:** One option is, as suggested by jpic and sgallen in the comments, to add `.filter()` for each category. Each additional `filter` adds more joins, which should not be a problem for small set of categories. There is the [aggregation](https://docs.djangoproject.com/en/dev/topics/db/aggregation/) [approach](h...
Django method to change User email not working
8,619,025
3
2011-12-23T17:39:17Z
8,619,080
10
2011-12-23T17:45:39Z
[ "python", "django", "forms" ]
I am attempting to create a page where a user can see what their current email is and change it if they would like. I am just testing with a very simple form and a very simple HttpResponseRedirect if the form is not valid. However neither my email is changing for the user nor is my failure response if the form is not v...
`ChangeEmail` is a normal form. These don't have `save` methods - only ModelForms do. You're correctly setting the user email from the form's cleaned\_data - but you should be saving the `user1` object, not the form. Also, it's best not to redirect away on validation failure. Leave out that first `else` clause, and mo...
(SWIG C++ to Python) warning 301: class keyword used, but not in C++ mode
8,619,112
2
2011-12-23T17:49:53Z
8,621,385
8
2011-12-23T23:01:51Z
[ "c++", "python", "swig" ]
I am attempting to compile a C++ extension for python. I have created an interface file foo.i which looks like this: ``` %module foo %include "typemaps.i" // For pointers to primitive types %include "std_string.i" // std::string mapping %apply const std::string& {std...
You need to [call SWIG](http://www.swig.org/Doc2.0/SWIGPlus.html#SWIGPlus_nn5) with `-c++` when you call it if you're using C++.
Inconsistency between %time and %timeit in IPython
8,619,167
21
2011-12-23T17:55:07Z
8,731,619
29
2012-01-04T17:59:27Z
[ "python", "ipython", "timeit" ]
I am confronted to a weird situation that I can't explain. Here is my test timing the generation of a large list of tuples: ``` In [1]: def get_list_of_tuples(): ...: return [(i,) for i in range(10**6)] ...: In [2]: %time res = get_list_of_tuples() CPU times: user 0.93 s, sys: 0.08 s, total: 1.01 s Wall tim...
The main difference is because "[by default, timeit() temporarily turns off garbage collection during the timing](http://docs.python.org/library/timeit.html#timeit.Timer.timeit)". Turning the garbage collection returns results similar to the one shown in the question, i.e. the time of execution with garbage collection...
How to avoid the "This message may not have been sent by" warning when sending email using Google App Engine?
8,620,252
6
2011-12-23T20:16:04Z
8,621,440
8
2011-12-23T23:11:38Z
[ "python", "google-app-engine", "email" ]
I have a python GAE app that sends emails like in the [example](http://code.google.com/appengine/docs/python/mail/sendingmail.html) using the address of a registered administrator for the application as the "sender" address. When an email arrives from such an API call, here's a pic of [the attached warning](http://i.im...
Assuming you're seeing this in production, it's probably because you're claiming to be from a gmail address, but sending via App Engine. Use one of your app's email addresses as the sender (foo@yourapp.appspotmail.com) and it should work fine.
numpy: ndenumerate for masked arrays?
8,620,798
5
2011-12-23T21:30:46Z
8,621,173
7
2011-12-23T22:28:04Z
[ "python", "numpy" ]
Is there a way to enumerate over the non-masked locations of a masked `numpy ndarray` (e.g. in the way that `ndenumerate` does it for regular `ndarrays`, but omitting all the masked entries)? EDIT: to be more precise: the enumeration should not only skip over the masked entries, but also show the indices of the non-ma...
You can access only valid entries using **inverse of a mask** as an index: ``` >>> import numpy as np >>> import numpy.ma as ma >>> x = np.array([11, 22, -1, 44]) >>> m_arr = ma.masked_array(x, mask=[0, 0, 1, 0]) >>> for index, i in np.ndenumerate(m_arr[~m_arr.mask]): print index, i (0,) 11 (1,) 22 (2,) 44 ``...
Admin interface for SQLAlchemy?
8,621,669
7
2011-12-23T23:56:08Z
14,519,811
12
2013-01-25T10:24:39Z
[ "python", "django", "sqlalchemy", "django-orm", "formalchemy" ]
I've been developing a [Django](https://www.djangoproject.com/) app, however I've recently changed the overall architecture plan. I no longer need a web-framework, just a simple Python script, so I'm changing from using the Django ORM to using [SQLAlchemy](http://www.sqlalchemy.org/) to create and manage the database. ...
Use [Flask-Admin](http://flask-admin.readthedocs.org/). Right now it has about 70% of Django features, some really great features, that Django doesn't support and it extremely flexible as Flask
Is there a way to access hardware directly in Python?
8,622,667
11
2011-12-24T00:32:39Z
8,622,706
7
2011-12-24T04:35:41Z
[ "python", "hardware", "graphics" ]
I want to learn about graphical libraries by myself and toy with them a bit. I built a small program that defines lines and shapes as lists of pixels, but I cannot find a way to access the screen directly so that I can display the points on the screen without any intermediate. What I mean is that I do not want to use ...
No, Python isn't the best choice for this type of raw hardware access to the video card. I would recommend writing C in DOS. Well, actually, I don't recommend it. It's a horrible thing to do. But, it's how I learned to do it, and it's probably about as friendly as you are going to get for accessing hardware directly wi...
Passing a pointer to a list in Python
8,622,769
4
2011-12-24T04:51:32Z
8,622,804
9
2011-12-24T04:58:47Z
[ "python", "list", "pointers" ]
Is there any way to pass a pointer to a list, so I could have `update_list(list, data)` Instead of having to do `list = update_list(list, data)` Independent of whether this is possible, what is advisable and Pythonic in this situation?
I recommend reading [Semantics of Python variable names from a C++ perspective](http://rg03.wordpress.com/2007/04/21/semantics-of-python-variable-names-from-a-c-perspective/): > **All variables are references** This is oversimplification of the entire article, but this (and the understanding that a `list` is a **muta...
Group by max or min in a numpy array
8,623,047
6
2011-12-24T06:09:57Z
8,623,168
7
2011-12-24T06:42:10Z
[ "python", "numpy" ]
I have two equal-length 1D numpy arrays, `id` and `data`, where `id` is a sequence of repeating, ordered integers that define sub-windows on `data`. For example, ``` id data 1 2 1 7 1 3 2 8 2 9 2 10 3 1 3 -10 ``` I would like to aggregate `data` by grouping on `id` and taking either the ...
I've been seeing some very similar questions on stack overflow the last few days. The following code is very similar to the implementation of numpy.unique and because it takes advantage of the underlying numpy machinery, it is most likely going to be faster than anything you can do in a python loop. ``` import numpy a...
What is a python thread
8,623,573
24
2011-12-24T08:37:47Z
8,623,651
22
2011-12-24T08:57:53Z
[ "python", "multithreading" ]
I have several questions regarding Python threads. 1. Is a Python thread a Python or OS implementation? 2. When I use htop a multi-threaded script has multiple entries - the same memory consumption, the same command but a different PID. Does this mean that a [Python] thread is actually a special kind of process? (I kn...
1. Python thread are implemented using OS threads in all implementation I know (C Python, PyPy and Jython). For each Python thread, there is an underlying OS thread. 2. Some operating systems (Linux being one of them) give all different thread launched by the same executable in the list of all running processes. This i...
What is a python thread
8,623,573
24
2011-12-24T08:37:47Z
8,623,686
10
2011-12-24T09:10:03Z
[ "python", "multithreading" ]
I have several questions regarding Python threads. 1. Is a Python thread a Python or OS implementation? 2. When I use htop a multi-threaded script has multiple entries - the same memory consumption, the same command but a different PID. Does this mean that a [Python] thread is actually a special kind of process? (I kn...
I'm not familiar with the implementation, so let's make an experiment: ``` import threading import time def target(): while True: print 'Thread working...' time.sleep(5) NUM_THREADS = 5 for i in range(NUM_THREADS): thread = threading.Thread(target=target) thread.start() ``` 1. The numbe...
Python argparse type and choice restrictions with nargs > 1
8,624,034
11
2011-12-24T10:46:44Z
8,624,107
14
2011-12-24T11:01:19Z
[ "python", "argparse" ]
The title pretty much says it all. If I have nargs greater than 1, is there any way I can set restrictions (such as choice/type) on the individual args parsed? This is some example code: ``` parser = argparse.ArgumentParser() parser.add_argument('-c', '--credits', nargs=2, help='number of credits required for a s...
You can validate it with a [custom action:](http://docs.python.org/library/argparse.html#action) ``` import argparse import collections class ValidateCredits(argparse.Action): def __call__(self, parser, args, values, option_string=None): # print '{n} {v} {o}'.format(n=args, v=values, o=option_string) ...
__unicode__() doesn't return a string
8,624,264
7
2011-12-24T11:33:01Z
8,624,298
13
2011-12-24T11:39:29Z
[ "python" ]
I have the following class in python ``` class myTest: def __init__(self, str): self.str = str def __unicode__(self): return self.str ``` and in some other file a instantiate myTest to try out the unicode() method ``` import myClass c = myClass.myTest("hello world") print c ``` as print ...
Generally it is done like this: ``` class myTest: def __init__(self, str): self.str = str def __unicode__(self): return self.str def __str__(self): return unicode(self).encode('utf-8') ``` This is because `__unicode__` is not called implicitly in they way that `__str__` an...
Django Paginate by Year
8,624,507
3
2011-12-24T12:26:33Z
8,624,624
7
2011-12-24T12:50:30Z
[ "python", "django", "pagination", "django-class-based-views" ]
I was able to preview the 100 most recent items in my news clipping database on my website's index page with a generic view: [DPRM](http://www.drugpolicyreformmovement.com) Now I need to paginate my database in a separate logical section of my website. I need to paginate by year. I don't care how many entries are in ...
With the new [Class Based Views](https://docs.djangoproject.com/en/dev/topics/class-based-views/) the easies would be to use the [YearArchiveView](https://docs.djangoproject.com/en/dev/ref/class-based-views/#yeararchiveview) ``` class ArticleYearArchiveView(YearArchiveView): model = Article paginate_by = 100 ...
passing a variable into a jinja import or include from a parent html file
8,624,520
9
2011-12-24T12:29:14Z
8,624,601
10
2011-12-24T12:46:49Z
[ "python", "templates", "flask", "jinja" ]
The scenario would be: "you have a variable called person which contains a number of fields like name, address, etc which you want to pass to a partial piece of html" - this solution could be results from a search for customers for example snippet.html ``` <div id="item"> <ul> <li> <span>{{name}}</sp...
When you include a template into another one, it gains access to its context, so if you pass your `person` variable to `mypage.html`'s context, you'll be able to access it from your imported template like this: `snippet.html:` ``` <div id="item"> <ul> <li> <span>{{ person.name }}</span> ...
Check if two items are in a list, in a particular order?
8,625,351
4
2011-12-24T15:28:25Z
8,625,376
8
2011-12-24T15:34:22Z
[ "python", "list", "order" ]
Say I have a list `v = [1, 2, 3, 4, 3, 1, 2]`. I want to write a function, `find_pair` which will check if two numbers are in the list and adjacent to each other. So, `find_pair(v, 2, 3)` should return `True`, but `find_pair(v, 1, 4)` should return `False`. Is it possible to implement `find_pair` without a loop?
``` v = [1,2,3,4,3,1,2] any([2,3] == v[i:i+2] for i in xrange(len(v) - 1)) ``` While @PaoloCapriotti's version does the trick, this one is faster, because it stops parsing the `v` as soon as a match is found.
python: multiprocessing Event
8,626,157
13
2011-12-24T18:20:58Z
8,687,095
10
2011-12-31T08:04:51Z
[ "python", "multiprocessing" ]
What is difference between `multiprocessing.Event` and `multiprocessing.managers.SyncManager.Event`. When do I use each? Why two different objects exist? Same question for other similar objects existing in `multiprocessing` directly and also in `Manager` (`Lock`, etc.)
Unfortunately, the only given answer is not very correct and others wasn't given. I looked it up my own, and found that `multiprocessing.Event` can be used to synch between processes, it's completely alright. `Event` and other objects from `multiprocessing.Manager` exist to be able to synchronize things between proce...
join 4 strings to the one if they are not empty in python
8,626,694
27
2011-12-24T20:23:14Z
8,626,704
59
2011-12-24T20:25:31Z
[ "python", "string", "join" ]
I have 4 string fields. Any of them can be empty. What I need is to join them as one string with space between them. If I use: ``` new_string = string1 + ' ' + string2 + ' ' + string3 + ' ' + string4 ``` result is blank space on the beginning of the new string if string1 is empty. Also I have 3 blank spaces if string...
``` >>> strings = ['foo','','bar','moo'] >>> ' '.join(filter(None, strings)) 'foo bar moo' ``` By using `None` in the [`filter()`](http://docs.python.org/library/functions.html#filter) call, it removes all falsy elements.
join 4 strings to the one if they are not empty in python
8,626,694
27
2011-12-24T20:23:14Z
8,626,817
7
2011-12-24T20:51:30Z
[ "python", "string", "join" ]
I have 4 string fields. Any of them can be empty. What I need is to join them as one string with space between them. If I use: ``` new_string = string1 + ' ' + string2 + ' ' + string3 + ' ' + string4 ``` result is blank space on the beginning of the new string if string1 is empty. Also I have 3 blank spaces if string...
If you KNOW that the strings have no leading/trailing whitespace: ``` >>> strings = ['foo','','bar','moo'] >>> ' '.join(x for x in strings if x) 'foo bar moo' ``` otherwise: ``` >>> strings = ['foo ','',' bar', ' ', 'moo'] >>> ' '.join(x.strip() for x in strings if x.strip()) 'foo bar moo' ``` and if any of the str...
What would you use the heapq Python module for in real life?
8,627,109
12
2011-12-24T22:02:43Z
8,627,323
16
2011-12-24T22:57:39Z
[ "python", "heap" ]
After reading Guido's [Sorting a million 32-bit integers in 2MB of RAM using Python](http://neopythonic.blogspot.com/2008/10/sorting-million-32-bit-integers-in-2mb.html), I discovered the `heapq` module, but the concept is pretty abstract to me. One reason is that I don't understand the concept of a heap completely, b...
The [heapq module](http://docs.python.org/library/heapq.html#module-heapq) is commonly use to implement [priority queues](http://en.wikipedia.org/wiki/Priority_queue). You see priority queues in event schedulers that are constantly adding new events and need to use a heap to efficiently locate the next scheduled event...
why is my text not aligning properly in wxPython?
8,627,730
6
2011-12-25T01:01:30Z
8,628,948
11
2011-12-25T09:09:59Z
[ "python", "wxpython", "alignment", "wx" ]
I'm using wxPython to build a GUI and I'm trying to align some text but it's not working at all. I'm trying align three different static text items in three places (right aligned, center aligned, and left aligned) in three seperate panels. The result that I'm getting though is that all three static text controls are al...
**Edit:** Although everything commented below works on windows, the first option would not work on, for example, Ubuntu due to maybe a bug. A previous post given in the comments indicate that the same problem is found in OSX. In any case, the second option using vertical sizers works both in Ubuntu and windows so you...
Generate .pyc from Python AST?
8,627,835
10
2011-12-25T01:49:27Z
8,628,185
11
2011-12-25T04:20:03Z
[ "python", "bytecode", "abstract-syntax-tree" ]
How would I generate a .pyc file from a Python AST such that I could import the file from Python? I've used `compile` to create a code object, then written the `co_code` attribute to a file, but when I try to import the file from Python, I get an `ImportError: Bad magic number in output.pyc`.
The solution can be adapted from the `py_compile` module: ``` import marshal import py_compile import time import ast codeobject = compile(ast.parse('print "Hello World"'), '<string>', 'exec') with open('output.pyc', 'wb') as fc: fc.write('\0\0\0\0') py_compile.wr_long(fc, long(time.time())) marshal.dump...
How to keep a socket open until client closes it?
8,627,986
9
2011-12-25T02:52:07Z
8,628,089
14
2011-12-25T03:40:39Z
[ "python", "networking" ]
I have simple python server and client. Server: ``` import SocketServer import threading class MyTCPHandler(SocketServer.BaseRequestHandler): def handle(self): self.data = self.request.recv(1024).strip() print str(self.client_address[0]) + " wrote: " print self.data self.request....
A `MyTcpHandler` object is created for each connection, and `handle` is called to deal with the client. The connection is closed when `handle` returns, so you have to handle the complete communication from the client within the `handle` method: ``` class MyTCPHandler(SocketServer.BaseRequestHandler): def handle(se...