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
Simple cross-tabulation in pandas
9,588,331
20
2012-03-06T17:01:47Z
9,623,878
14
2012-03-08T19:49:23Z
[ "python", "pandas" ]
I stumbled across [pandas](http://pandas.pydata.org/) and it looks ideal for simple calculations that I'd like to do. I have a SAS background and was thinking it'd replace proc freq -- it looks like it'll scale to what I may want to do in the future. However, I just can't seem to get my head around a simple task (I'm n...
Thanks, Jeff. It is possible to do this using `pivot_table` for those interested: ``` In [8]: df Out[8]: category value 0 AB 100 1 AB 200 2 AC 150 3 AD 500 In [9]: df.pivot_table(rows='category', aggfunc=[len, np.sum]) Out[9]: len sum value value cate...
Read input from redirected stdin with python
9,589,092
3
2012-03-06T17:47:36Z
9,589,320
10
2012-03-06T18:02:09Z
[ "python", "shell", "stdin" ]
I have this loop that reads lines from stdin until a newline is entered, however, this only works from typing in the input. How do I get the program to read lines from a redirected stdin via the command line? For instance: ``` $ python graph.py < input.input ``` Here is the loop I have to read lines from input: ```...
As others have mentioned, probably your condition `line == '\n'` never holds true. The proper solution would be to use a loop like: ``` for line in sys.stdin: stripped = line.strip() if not stripped: break lines.append(stripped) ```
Python here document without newlines at top and bottom
9,589,301
22
2012-03-06T18:01:11Z
9,589,361
12
2012-03-06T18:05:24Z
[ "python", "printing", "heredoc" ]
What's the best way to have a here document, without newlines at the top and bottom? For example: ``` print ''' dog cat ''' ``` will have newlines at the top and bottom, and to get rid of them I have to do this: ``` print '''dog cat''' ``` which I find to be much less readable.
use parentheses: ``` print ( '''dog cat''' ) ``` Use `str.strip()` ``` print ''' dog cat '''.strip() ``` use `str.join()` ``` print '\n'.join(( 'dog', 'cat', )) ```
Python here document without newlines at top and bottom
9,589,301
22
2012-03-06T18:01:11Z
9,589,367
33
2012-03-06T18:05:39Z
[ "python", "printing", "heredoc" ]
What's the best way to have a here document, without newlines at the top and bottom? For example: ``` print ''' dog cat ''' ``` will have newlines at the top and bottom, and to get rid of them I have to do this: ``` print '''dog cat''' ``` which I find to be much less readable.
How about this? ``` print ''' dog cat '''[1:-1] ``` Or so long as there's no indentation on the first line or trailing space on the last: ``` print ''' dog cat '''.strip() ``` Or even, if you don't mind a bit more clutter before and after your string in exchange for being able to nicely indent it: ``` from textwra...
Python here document without newlines at top and bottom
9,589,301
22
2012-03-06T18:01:11Z
18,892,482
13
2013-09-19T10:41:44Z
[ "python", "printing", "heredoc" ]
What's the best way to have a here document, without newlines at the top and bottom? For example: ``` print ''' dog cat ''' ``` will have newlines at the top and bottom, and to get rid of them I have to do this: ``` print '''dog cat''' ``` which I find to be much less readable.
Add backslash \ at the end of unwanted lines: ``` text = '''\ cat dog\ ''' ``` It is somewhat more readable.
Return copies of dictionary modified
9,589,466
4
2012-03-06T18:12:38Z
9,589,526
14
2012-03-06T18:16:43Z
[ "python", "lambda" ]
I have a dictionary and for a particular key, I have say 5 possible new values. So I am trying to create 5 copies of the original dictionary by using a simple lambda function that will replace the value of that particular key and return a copy of the master dictionary. ``` # This is the master dictionary. d = {'fn' : ...
You can use a list comprehension: ``` >>> d = {'fn' : 'Joseph', 'ln' : 'Randall', 'phone' : '100' } >>> lst = ['200', '300', '400', '500'] >>> [dict(d, phone=x) for x in lst] [{'ln': 'Randall', 'phone': '200', 'fn': 'Joseph'}, {'ln': 'Randall', 'phone': '300', 'fn': 'Joseph'}, {'ln': 'Randall', 'phone': '400', 'fn': '...
Easy, painless way to test new mercurial hooks (that are works in progress)
9,589,955
16
2012-03-06T18:47:52Z
9,593,414
18
2012-03-06T23:11:58Z
[ "python", "mercurial", "mercurial-hook" ]
I'm in the process of writing a mercurial changegroup hook. I don't have everything figured out yet, but the process of trial and error is made more painful by the fact that I have to keep committing and pushing just to test my work in progress. Is there any way to 'fake' a trigger to execute my changegroup hook with ...
I'm afraid there's no built-in debugging capabilities for this. What I do when writing a hook is to setup two local repositories: ``` $ hg init repo $ hg clone repo clone ``` and then configure the `changegroup` hook in `repo`. Now go into `clone` and do ``` $ echo a > a $ hg add a $ hg commit -m 'a file' ``` to se...
Can I bypass a UnicodeDecodeError in python?
9,590,306
2
2012-03-06T19:16:05Z
9,590,385
7
2012-03-06T19:21:20Z
[ "python", "xml", "django", "parsing", "illegal-characters" ]
I have a python script that parsing an xml file and is returning the following error: `UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 614617: character maps to <undefined>` I'm pretty sure the error is occurring because there are some illegal characters within the xml document I am trying to p...
When you call [`decode()`](http://docs.python.org/library/stdtypes.html#str.decode), you can pass the optional `errors` argument. By default it is set to `strict` (which raises an error if it finds something it can't parse), but you can also set it to `replace` (which replaces the problematic character with `\ufffd`) o...
Forcing Python json module to work with ASCII
9,590,382
8
2012-03-06T19:21:03Z
9,590,743
12
2012-03-06T19:46:18Z
[ "python", "json", "unicode", "ascii" ]
I'm using json.dump() and json.load() to save/read a dictionary of strings to/from disk. The issue is that I can't have any of the strings in unicode. They seem to be in unicode no matter how I set the parameters to dump/load (including ensure\_ascii and encoding).
If you are just dealing with simple JSON objects, you can use the following: ``` def ascii_encode_dict(data): ascii_encode = lambda x: x.encode('ascii') return dict(map(ascii_encode, pair) for pair in data.items()) json.loads(json_data, object_hook=ascii_encode_dict) ``` Here is an example of how it works: ...
Convert an IP string to a number and vice versa
9,590,965
21
2012-03-06T20:01:52Z
9,591,005
55
2012-03-06T20:05:12Z
[ "python", "django" ]
How would I use python to convert an IP address that comes as a `str` to a decimal number and vice versa? For example, for the IP `186.99.109.000 <type'str'>`, I would like to have a decimal or binary form that is easy to store in a database, and then retrieve it.
converting an IP string to long integer: ``` import socket, struct def ip2long(ip): """ Convert an IP string to long """ packedIP = socket.inet_aton(ip) return struct.unpack("!L", packedIP)[0] ``` the other way around: ``` >>> socket.inet_ntoa(struct.pack('!L', 2130706433)) '127.0.0.1' ```
Convert an IP string to a number and vice versa
9,590,965
21
2012-03-06T20:01:52Z
22,272,197
9
2014-03-08T16:51:36Z
[ "python", "django" ]
How would I use python to convert an IP address that comes as a `str` to a decimal number and vice versa? For example, for the IP `186.99.109.000 <type'str'>`, I would like to have a decimal or binary form that is easy to store in a database, and then retrieve it.
A simple solution with **no module imports**: ``` >>> ip = '1.2.3.4' >>> parts = ip.split('.') >>> print (int(parts[0]) << 24) + (int(parts[1]) << 16) + (int(parts[2]) << 8) + int(parts[3]) 16909060 ```
Convert an IP string to a number and vice versa
9,590,965
21
2012-03-06T20:01:52Z
23,691,394
12
2014-05-16T01:46:26Z
[ "python", "django" ]
How would I use python to convert an IP address that comes as a `str` to a decimal number and vice versa? For example, for the IP `186.99.109.000 <type'str'>`, I would like to have a decimal or binary form that is easy to store in a database, and then retrieve it.
Use class `IPAddress` in module `netaddr`. ipv4 `str` -> `int`: ``` print int(netaddr.IPAddress('192.168.4.54')) # OUTPUT: 3232236598 ``` ipv4 `int` -> `str`: ``` print str(netaddr.IPAddress(3232236598)) # OUTPUT: 192.168.4.54 ``` ipv6 `str` -> `int`: ``` print int(netaddr.IPAddress('2001:0db8:0000:0000:0000:ff00...
What is difference between sys.exit(0) and os._exit(0)
9,591,350
18
2012-03-06T20:29:58Z
9,591,397
23
2012-03-06T20:32:55Z
[ "python" ]
Please help me in clarifying the concept of these two python statements in terms of difference in functionality: 1. `sys.exit(0)` 2. `os._exit(0)`
According to the [documentation](http://docs.python.org/library/os.html#os._exit): > ``` > os._exit(): > ``` > > Exit the process with status n, without calling cleanup handlers, flushing stdio buffers, etc. > > **Note** The standard way to exit is `sys.exit(n)`. `_exit()` should normally only be used in the child pro...
What is difference between sys.exit(0) and os._exit(0)
9,591,350
18
2012-03-06T20:29:58Z
9,591,402
11
2012-03-06T20:33:10Z
[ "python" ]
Please help me in clarifying the concept of these two python statements in terms of difference in functionality: 1. `sys.exit(0)` 2. `os._exit(0)`
`os._exit` calls the C function `_exit()` which does an immediate program termination. Note the statement "can never return". `sys.exit()` is identical to `raise SystemExit()`. It raises a Python exception which may be caught by the caller. Original post: <http://bytes.com/topic/python/answers/156121-os-_exit-vs-sys-...
Is it possible to run opencv (python binding) from a virtualenv?
9,592,389
24
2012-03-06T21:42:38Z
12,043,136
25
2012-08-20T18:35:56Z
[ "python", "opencv", "distribution", "virtualenv", "vision" ]
I would like to keep everything contained within the virtualenv. Is this possible with OpenCV? I'm fine with building from scratch, do I just need to setup the virtualenv first then use special compile flags to tell it where to install to?
I found the solution was that I had to copy over cv2.so and cv.py to the directory running the virtualenv, then pip install numpy. To do this on Ubuntu 12.04 I used. ``` virtualenv virtopencv cd virtopencv cp /usr/local/lib/python2.7/dist-packages/cv* ./lib/python2.7/site-packages/ ./bin/pip install numpy source bin/a...
Storing global config variables in a Pyramid project
9,593,586
5
2012-03-06T23:29:28Z
9,594,705
11
2012-03-07T01:49:28Z
[ "python", "pyramid" ]
I'm just getting started with Python's pyramid framework and am unsure where to set application variables and the best way to import them into my project. For example: database username/passwords, paths, thumbnail height/width, etc ... Should I create a dedicated config.py file and import the variables into my functio...
There is a recipe in the cookbook for emulating the Django-style global settings file (for your convenience). However, the recommended way is to store these things in your INI file as deployment settings. Thus you could have one database username/password for development and one for production and it's as simple as hav...
creating a temporary table from a query using sqlalchemy orm
9,593,610
7
2012-03-06T23:33:19Z
9,597,404
11
2012-03-07T07:31:38Z
[ "python", "sql", "sqlalchemy" ]
I can create a temporary table this way: ``` session.execute("CREATE TABLE temptable SELECT existingtable.id, " "existingtable.column2 FROM existingtable WHERE existingtable.id<100000") ``` but the new table is unreadable because it says it has no primary key. `existingtable.id` is the primary key of exisitingtab...
It's not exactly ORM, but to create the table initially, I'd clone the table structure (see `cloneTable` in the example below). For copying the data, I then would use the [InsertFromSelect example](http://docs.sqlalchemy.org/en/latest/core/compiler.html#compiling-sub-elements-of-a-custom-expression-construct). **Edit:...
lxml error "IOError: Error reading file" when parsing facebook mobile in a python scraper script
9,593,990
2
2012-03-07T00:17:22Z
9,594,185
8
2012-03-07T00:43:38Z
[ "python", "linux", "facebook", "web-scraping", "lxml" ]
I use a modified script from [Logging into facebook with python](http://stackoverflow.com/questions/2030652/logging-into-facebook-with-python) post : ``` #!/usr/bin/python2 -u # -*- coding: utf8 -*- facebook_email = "YOUR_MAIL@DOMAIN.TLD" facebook_passwd = "YOUR_PASSWORD" import cookielib, urllib2, urllib, time, sy...
This is your problem: ``` tree = etree.parse(body) ``` The [documentation](http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.parse) says that "`source` is a filename or file object containing XML data." You have provided a string, so lxml is taking the text of your HTTP response body as ...
How to use jQuery UI Datepicker as a Django Widget?
9,594,081
12
2012-03-07T00:27:57Z
9,598,431
11
2012-03-07T09:02:22Z
[ "jquery", "python", "django", "django-widget" ]
Some of my Django 1.3 models have DateField properties. When a form is generated, I'd like to use the jQuery UI Datepicker instead of a plain text field. I understand that I could create new widgets but I don't understand how. In addition, I am not sure if anything like this has already been done for Django (I googled ...
JQueryUI has a very good date UI picker. You can get it here: <http://jqueryui.com> Say for example you have the following form: ``` class DateForm(forms.Form): myDate = forms.DateField() ``` From here you want to bind the JQuery date widget to your field from within your template. I am assuming here you are pas...
Salt and hash a password in python
9,594,125
43
2012-03-07T00:34:03Z
9,595,108
23
2012-03-07T02:44:06Z
[ "python", "authentication", "hash", "passwords", "salt" ]
This code is supposed to hash a password with a salt. The salt and hashed password are being saved in the database. The password itself is not. Given the sensitive nature of the operation, I wanted to make sure everything was kosher. Note: I use the url safe version of b64encode out of habit. ``` import hashlib impo...
**EDIT:** This answer is wrong. Don't use a cryptographic hash to store passwords. Use a password hash. --- Looks fine by me. However, I'm pretty sure you don't actually need base64. You could just do this: ``` import hashlib, uuid salt = uuid.uuid4().hex hashed_password = hashlib.sha512(password + salt).hexdigest()...
Salt and hash a password in python
9,594,125
43
2012-03-07T00:34:03Z
10,948,614
33
2012-06-08T12:11:00Z
[ "python", "authentication", "hash", "passwords", "salt" ]
This code is supposed to hash a password with a salt. The salt and hashed password are being saved in the database. The password itself is not. Given the sensitive nature of the operation, I wanted to make sure everything was kosher. Note: I use the url safe version of b64encode out of habit. ``` import hashlib impo...
The smart thing is not to write the crypto yourself but to use something like passlib: <https://bitbucket.org/ecollins/passlib/wiki/Home> It is easy to mess up writing your crypto code in a secure way. The nasty thing is that with non crypto code you often immediately notice it when it is not working since your progra...
Salt and hash a password in python
9,594,125
43
2012-03-07T00:34:03Z
10,969,833
12
2012-06-10T15:12:48Z
[ "python", "authentication", "hash", "passwords", "salt" ]
This code is supposed to hash a password with a salt. The salt and hashed password are being saved in the database. The password itself is not. Given the sensitive nature of the operation, I wanted to make sure everything was kosher. Note: I use the url safe version of b64encode out of habit. ``` import hashlib impo...
For this to work in Python 3 you'll need to UTF-8 encode for example: ``` hashed_password = hashlib.sha512(password.encode('utf-8') + salt.encode('utf-8')).hexdigest() ``` Otherwise you'll get: > Traceback (most recent call last): > File "", line 1, in > hashed\_password = hashlib.sha512(password + salt).hexdig...
Salt and hash a password in python
9,594,125
43
2012-03-07T00:34:03Z
18,488,878
7
2013-08-28T13:09:11Z
[ "python", "authentication", "hash", "passwords", "salt" ]
This code is supposed to hash a password with a salt. The salt and hashed password are being saved in the database. The password itself is not. Given the sensitive nature of the operation, I wanted to make sure everything was kosher. Note: I use the url safe version of b64encode out of habit. ``` import hashlib impo...
passlib seems to be useful if you need to use hashes stored by an existing system. If you have control of the format, use a modern hash like bcrypt or scrypt. At this time, bcrypt seems to be much easier to use from python. passlib supports bcrypt, and it recommends installing py-bcrypt as a backend: <http://pythonhos...
Salt and hash a password in python
9,594,125
43
2012-03-07T00:34:03Z
23,768,422
21
2014-05-20T19:35:10Z
[ "python", "authentication", "hash", "passwords", "salt" ]
This code is supposed to hash a password with a salt. The salt and hashed password are being saved in the database. The password itself is not. Given the sensitive nature of the operation, I wanted to make sure everything was kosher. Note: I use the url safe version of b64encode out of habit. ``` import hashlib impo...
Based on the other answers to this question, I've implemented a new approach using bcrypt. ### Why use bcrypt If I understand correctly, the argument to use `bcrypt` over `SHA512` is that `bcrypt` is designed to be slow. `bcrypt` also has an option to adjust how slow you want it to be when generating the hashed passw...
How do you add "3 months" to a datetime.date object in python?
9,594,282
12
2012-03-07T00:54:57Z
9,594,654
30
2012-03-07T01:42:23Z
[ "python", "sql", "postgresql" ]
## Python date calculations, where art thou? I have a python app that needs to plot out dates every three months for several years. It's important that the dates occur exactly 4 times a year, and that the dates occur on the same day each year as much as possible, and that the dates occur on the same day of the month a...
If you're looking for exact or "more precise" dates, you're probably better off checking out [dateutil](http://labix.org/python-dateutil). Quick example: ``` >>> from dateutil.relativedelta import relativedelta >>> import datetime >>> TODAY = datetime.date.today() >>> TODAY datetime.date(2012, 3, 6) ``` Now add 3 mo...
Python warnings.warn() vs. logging.warning()
9,595,009
23
2012-03-07T02:30:18Z
9,595,031
8
2012-03-07T02:33:06Z
[ "python", "logging", "warnings" ]
What is the difference between warnings.warn() and logging.warn() in terms of what they do and how they should be used?
One raises an exception which can be caught or ignored as desired, and the other optionally adds an entry to the log based on the current logging level. One should be used when one is warning about various things in code, and the other should be used when logging.
Python warnings.warn() vs. logging.warning()
9,595,009
23
2012-03-07T02:30:18Z
14,762,106
26
2013-02-07T22:18:25Z
[ "python", "logging", "warnings" ]
What is the difference between warnings.warn() and logging.warn() in terms of what they do and how they should be used?
I agree with the other answer -- `logging` is for logging and `warning` is for warning -- but I'd like to add more detail. Here is a tutorial-style HOWTO taking you through the steps in using the `logging` module. <http://docs.python.org/2/howto/logging.html> It directly answers your question: > warnings.warn() in l...
How to calc square root in python?
9,595,135
33
2012-03-07T02:48:51Z
9,595,150
57
2012-03-07T02:50:51Z
[ "python", "math", "sqrt" ]
Why does python give the "wrong" answer? ``` x= 16 sqrt= x**(.5) returns 4 sqrt= x**(1/2) returns 1 ``` Yes, I know `import math` and use `sqrt`. But I'm looking for an answer to the above.
`sqrt=x**(1/2)` is doing integer division. `1/2 == 0`. So you're computing x(1/2) in the first instance, x(0) in the second. So it's not wrong, it's the right answer to a different question.
How to calc square root in python?
9,595,135
33
2012-03-07T02:48:51Z
9,595,161
31
2012-03-07T02:51:57Z
[ "python", "math", "sqrt" ]
Why does python give the "wrong" answer? ``` x= 16 sqrt= x**(.5) returns 4 sqrt= x**(1/2) returns 1 ``` Yes, I know `import math` and use `sqrt`. But I'm looking for an answer to the above.
You have to write: `sqrt = x**(1/2.0)`, otherwise an integer division is performed and the expression `1/2` returns `0`. This behavior is "normal" in Python 2.x, whereas in Python 3.x `1/2` evaluates to `0.5`. If you want your Python 2.x code to behave like 3.x w.r.t. division write `from __future__ import division` -...
How to order django-mptt tree by DateTimeField?
9,596,115
4
2012-03-07T05:03:12Z
9,609,722
8
2012-03-07T21:57:32Z
[ "python", "django", "django-mptt" ]
This is the model I am using: ``` class Comment(MPTTModel): comment = models.CharField(max_length=1023) resource = models.ForeignKey('Resource') created_at = models.DateTimeField(auto_now_add=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children') author = models.Forei...
No, you're not doing something wrong. This is a bug in django-mptt. Basically datetime fields with `auto_add_now=True` don't get a value until after django-mptt tries to figure out where to insert your model in the tree. I've just created an issue on django-mptt to fix this: <https://github.com/django-mptt/django-mpt...
PHP list() equivalent in Python
9,597,803
7
2012-03-07T08:07:29Z
9,597,824
17
2012-03-07T08:09:33Z
[ "php", "python" ]
Is there any equivalent to the PHP list() function in python? For example: PHP: ``` list($first, $second, $third) = $myIndexArray; echo "First: $first, Second: $second"; ```
``` >>> a, b, c = [1, 2, 3] >>> print a, b, c 1 2 3 ``` Or a direct translation of your case: ``` >>> myIndexArray = [1, 2, 3] >>> first, second, third = myIndexArray >>> print "First: %d, Second: %d" % (first, second) First: 1, Second: 2 ``` Python implements this functionality by calling the `__iter__` method on t...
WTForms support for input readonly attribute?
9,599,551
9
2012-03-07T10:17:36Z
9,849,156
11
2012-03-24T04:27:37Z
[ "python", "html", "forms", "wtforms", "readonlyattribute" ]
[Here they say it's not supported out of the box.](https://groups.google.com/group/wtforms/browse_thread/thread/06755a45a13878e9/2c0dd60dc1be2032) Do you know a way to make HTML input form fields use the 'readonly' attribute with WTForms?
I assume you are talking about the `<input readonly>` attribute in HTML/XHTML, which is not what that discussion thread you linked is about. (the linked thread is about a lower-level issue with how to ignore passed form input) The way to set a readonly attribute (and indeed any attribute on a field) is as a keyword-ar...
How to use unittest's self.assertRaises with exceptions in a generator object?
9,599,610
8
2012-03-07T10:21:10Z
9,599,863
23
2012-03-07T10:38:17Z
[ "python", "unit-testing", "generator" ]
I got a generator object that I want to unittest. It goes through a loop and, when at the end of the loop a certain variable is still 0 I raise an exception. I want to unittest this, but I don't know how. Take this example generator: ``` class Example(): def generatorExample(self): count = 0 for in...
[`assertRaises`](http://docs.python.org/library/unittest.html#unittest.TestCase.assertRaises) is a context manager since Python 2.7, so you can do it like this: ``` class testExample(unittest.TestCase): def test_generatorExample(self): with self.assertRaises(RuntimeError): list(Example().gener...
How to parse json in bash or pass curl output to python script
9,600,500
2
2012-03-07T11:21:12Z
9,600,579
7
2012-03-07T11:26:47Z
[ "python", "json", "bash", "pprint" ]
I'm looking to find some way to have pretty print of curl's output in json. I wrote short python script for this purpose, but it won't work with pipe Also I don't want to use subprocesses and run curl from them: So python: ``` #!/usr/bin/python import simplejson from pprint import pprint import sys print pprint(simp...
Using `json.tool` from the shell to validate and pretty-print: ``` $ echo '{"json":"obj"}' | python -mjson.tool { "json": "obj" } ```
python pool apply_async and map_async do not block on full queue
9,601,802
5
2012-03-07T12:47:20Z
9,619,870
7
2012-03-08T15:11:07Z
[ "python", "design-patterns", "queue", "multiprocessing" ]
I am fairly new to python. I am using the multiprocessing module for reading lines of text on stdin, converting them in some way and writing them into a database. Here's a snippet of my code: ``` batch = [] pool = multiprocessing.Pool(20) i = 0 for i, content in enumerate(sys.stdin): batch.append(content) if l...
Just in case some one ends up here, this is how I solved the problem: I stopped using multiprocessing.Pool. Here is how I do it now: ``` #set amount of concurrent processes that insert db data processes = multiprocessing.cpu_count() * 2 #setup batch queue queue = multiprocessing.Queue(processes * 2) #start processes...
python regex split first charchter
9,602,198
2
2012-03-07T13:14:04Z
9,602,241
10
2012-03-07T13:16:55Z
[ "python", "regex", "split" ]
e.g. I have Name : **John Frank Smith** What i want is to seperate by first space so array will be ***[0]=John [1]=Frank Smith*** what i tried , i replace space by ~ and tried to split by regex. ``` import re s="John~Frank~Smith" l=re.compile(r'/~(.+)?/').split(s) ``` output is : ``` ['John~Frank~Smith'] ``` pl...
Use [`str.split()`](http://docs.python.org/library/stdtypes.html#str.split) with the `maxsplit` parameter: ``` >>> s = "John Frank Smith" >>> s.split(None, 1) ['John', 'Frank Smith'] ``` **Note:** This will split on multiple occurrences of whitespace, so a string like ``` John Frank Smith ``` would give the same...
Define an order for ManyToManyField with django
9,602,217
14
2012-03-07T13:15:17Z
9,605,077
12
2012-03-07T16:11:23Z
[ "python", "django" ]
I there a way to define the order of the contents List items? exemple : * ArticleContainer1 contains in this order : article1, article2, article3, article6 * ArticleContainer2 contains in this order : article3, article2, article1, article4 * ArticleContainer3 contains in this order : article5 Here are my...
So this is an example I have, a site that organizes people into departments with per department ordering. Its the same concept as your problem but with different models. This example uses many-to-many through table. ``` class Department(models.Model): slug = models.SlugField( verbose_name = _(u'Slug'), ...
how to tell pylint to ignore certain imports?
9,602,811
6
2012-03-07T13:57:23Z
9,616,857
9
2012-03-08T11:21:25Z
[ "python", "pylint" ]
I'm developing software for Windows with Python. I am developing on Linux, and I am using Pylint to check my code. I can't get rid of the error: ``` F| Unable to import '_winreg' ``` This is obvious - Python on Linux does not have this module. So, what do I have to put in my .pylintrc to ignore this error? Thanks i...
A solution that I have seen employed at my workplace, where there is a special module which Pylint can't possibly get at (Python is embedded and this special module is inside the main executable, while pylint is run in a regular Python installation) is to mock it by creating a .py file and putting it in the python path...
Most efficient way to split strings in Python
9,602,856
12
2012-03-07T14:00:27Z
9,603,035
10
2012-03-07T14:11:31Z
[ "python", "optimization", "split" ]
My current Python Project will require a lot of string splitting to process incoming packages. Since I will be running it on a pretty slow system, I was wondering what the most efficient way to go about this would be. The strings would be formatted something like this: ``` Item 1 | Item 2 | Item 3 <> Item 4 <> Item 5 ...
I'm not sure if it's the most efficient, but certainly the easiest to code seems to be something like this: ``` >>> input = "Item 1 | Item 2 | Item 3 <> Item 4 <> Item 5" >>> re.split( "\||<>", input ) >>> ['Item 1 ', ' Item 2 ', ' Item 3 ', ' Item 4 ', ' Item 5'] ``` I would think there's a fair chance of it being m...
Most efficient way to split strings in Python
9,602,856
12
2012-03-07T14:00:27Z
9,604,407
8
2012-03-07T15:36:30Z
[ "python", "optimization", "split" ]
My current Python Project will require a lot of string splitting to process incoming packages. Since I will be running it on a pretty slow system, I was wondering what the most efficient way to go about this would be. The strings would be formatted something like this: ``` Item 1 | Item 2 | Item 3 <> Item 4 <> Item 5 ...
I was slightly surprised that `split()` performed so badly in your code so I looked at it a bit more closely and noticed that you're calling `list.remove()` in the inner loop. Also you're calling `split()` an extra time on each string. Get rid of those and a solution using `split()` beats the regex hands down on shorte...
How to use matplotlib tight layout with Figure?
9,603,230
16
2012-03-07T14:25:02Z
9,604,442
27
2012-03-07T15:39:05Z
[ "python", "matplotlib", "figure" ]
I found tight\_layout function for pyplot and want to use it. In my application I embed matplotlib plots into Qt GUI and use figure and not pyplot. Is there any way I can apply tight\_layout there? Would it also work if I have several axes in one figure?
Just call `fig.tight_layout()` as you normally would. (`pyplot` is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.) There shouldn't be a difference between the `QtAgg` backend and the default backend (or if there is, it's a bu...
python byte string encode and decode
9,604,747
7
2012-03-07T15:54:15Z
9,605,002
8
2012-03-07T16:07:20Z
[ "python", "json", "unicode", "utf-8", "python-unicode" ]
I am trying to convert an incoming byte string that contains non-ascii characters into a valid utf-8 string such that I can dump is as json. ``` b = '\x80' u8 = b.encode('utf-8') j = json.dumps(u8) ``` I expected j to be '\xc2\x80' but instead I get: ``` UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in po...
You need to examine the documentation for the software API that you are using. BLOB is an acronym: **BINARY** Large Object. If your data is in fact binary, the idea of decoding it to Unicode is of course a nonsense. If it is in fact text, you need to know what encoding to use to decode it to Unicode. Then you use `j...
Can Python Requests library be used on Google App Engine?
9,604,799
18
2012-03-07T15:56:30Z
10,057,030
7
2012-04-07T18:13:06Z
[ "python", "google-app-engine", "python-requests" ]
Can I use [Requests](http://python-requests.org/) on Google App Engine? I think this library is perfect to create a REST client.
Not yet but hopefully very soon. Support for GAE is being worked on - see issue [#498](https://github.com/kennethreitz/requests/issues/498) (App Engine Fixes). Requests uses [urllib3](https://github.com/shazow/urllib3) which in turn uses [httplib](http://docs.python.org/library/httplib.html) which [is](https://develop...
Can Python Requests library be used on Google App Engine?
9,604,799
18
2012-03-07T15:56:30Z
28,544,823
19
2015-02-16T15:29:46Z
[ "python", "google-app-engine", "python-requests" ]
Can I use [Requests](http://python-requests.org/) on Google App Engine? I think this library is perfect to create a REST client.
**Yes. On Google Appengine (version 1.9.18) [requests](https://github.com/kennethreitz/requests) *version 2.3.0* works IN PRODUCTION** (but not on SDK) if you have billing enabled, which enables sockets support. requests on the Appengine SDK fails with all https:// requests: ``` ConnectionError: ('Connection aborte...
Can Python Requests library be used on Google App Engine?
9,604,799
18
2012-03-07T15:56:30Z
37,304,524
8
2016-05-18T15:52:07Z
[ "python", "google-app-engine", "python-requests" ]
Can I use [Requests](http://python-requests.org/) on Google App Engine? I think this library is perfect to create a REST client.
Install the `requests-toolbelt` library: <https://github.com/sigmavirus24/requests-toolbelt> For App Engine it could be something like: `pip install requests-toolbelt -t lib` (See: <https://cloud.google.com/appengine/docs/python/tools/using-libraries-python-27#installing_a_library>) Then add: ``` from requests_tool...
how to add existing files to an python project using pycharm?
9,604,943
21
2012-03-07T16:03:53Z
9,605,018
10
2012-03-07T16:08:21Z
[ "python", "project", "pycharm" ]
I have been using Pycharm IDE in Ubuntu for python development for a few days now. It started out with a basic parser project and now it is evolving into a web server for rest calls. We dont want to ruin the old parser project and we just want to use existing classes, but I could not find any way to import/add any exi...
I'm not sure if I get what you want, but there's way you can add existing source into project: File -> Settings -> Project structure -> Add Content root -> choose folder with existing code
how to add existing files to an python project using pycharm?
9,604,943
21
2012-03-07T16:03:53Z
9,605,030
27
2012-03-07T16:08:55Z
[ "python", "project", "pycharm" ]
I have been using Pycharm IDE in Ubuntu for python development for a few days now. It started out with a basic parser project and now it is evolving into a web server for rest calls. We dont want to ruin the old parser project and we just want to use existing classes, but I could not find any way to import/add any exi...
Copy the files to some directory under the project root using your favorite file manager or add the directory containing your files to the project using `Settings` (`Preferences` on Mac) | `Project Structure` | **Add Content Root**.
Struggling with slice syntax to join list element of a part of a list
9,605,813
5
2012-03-07T16:53:13Z
9,605,845
11
2012-03-07T16:55:16Z
[ "python", "list" ]
Suppose I have a simple Python list like this: ``` >>> l=['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] ``` Now suppose I want to combine `l[2:6]` to a single element like this: ``` >>> l ['0', '1', '2345', '6', '7', '8', '9'] ``` I am able to do it in steps into a new list, like this: ``` >>> l2=l[0:2] >>> l2...
Use a slice assignment: ``` l[2:6] = ["".join(l[2:6])] ```
Python: Gmail Unread Mails Crashes
9,605,862
4
2012-03-07T16:56:11Z
9,758,916
12
2012-03-18T14:02:47Z
[ "python", "email", "gmail", "imap" ]
``` import imaplib, re import os import time import socket imap_host = 'imap.gmail.com' mail = imaplib.IMAP4_SSL(imap_host) mail.login("xxx@example.com", "sddd") while True: try: print 'Connecting to Inbox..' mail.select("inbox") # connect to inbox. result, data = mail.uid('search', None, ...
The reason your script crashes is that call to mail.login() inside "except" block throws an exception that is never caught. Documentation to imaplib states that when you get imaplib.abort exception, you should just retry you command. <http://docs.python.org/library/imaplib> > exception IMAP4.abort IMAP4 server error...
Sqlalchemy: avoiding multiple inheritance and having abstract base class
9,606,551
8
2012-03-07T17:46:33Z
9,619,393
11
2012-03-08T14:42:42Z
[ "python", "sqlalchemy", "multiple-inheritance" ]
So I have a bunch of tables using SQLAlchemy that are modelled as objects which inherit from the result to a call to `declarative_base()`. Ie: ``` Base = declarative_base() class Table1(Base): # __tablename__ & such here class Table2(Base): # __tablename__ & such here ``` Etc. I then wanted to have some com...
It is pretty straigh-forward, you just make `declarative_base()` to return a `Base` class which inherits from your `CommonBase` using `cls=` parameter. Also shown in [Augmenting The Base](http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative.html?highlight=declarative_base#augmenting-the-base) docs. Your code...
Sqlalchemy: avoiding multiple inheritance and having abstract base class
9,606,551
8
2012-03-07T17:46:33Z
18,675,245
20
2013-09-07T16:06:55Z
[ "python", "sqlalchemy", "multiple-inheritance" ]
So I have a bunch of tables using SQLAlchemy that are modelled as objects which inherit from the result to a call to `declarative_base()`. Ie: ``` Base = declarative_base() class Table1(Base): # __tablename__ & such here class Table2(Base): # __tablename__ & such here ``` Etc. I then wanted to have some com...
SQLAlchemy version 0.7.3 introduced the `__abstract__` directive which is used for abstract classes that should not be mapped to a database table, even though they are subclasses of *sqlalchemy.ext.declarative.api.Base*. So now you create a base class like this: ``` Base = declarative_base() class CommonRoutines(Base...
How do I force `setup.py test` to install dependencies into my `virtualenv`?
9,607,565
23
2012-03-07T19:10:17Z
21,003,259
9
2014-01-08T18:06:10Z
[ "python", "virtualenv", "setuptools", "distribute" ]
In a crusade to make my application `pip`-installable, I'm fighting big fights with `setuptools` and `distribute`. I assume my dependencies are correct, i.e. installing with `pip install myapp` should probably fill the virtual environment correctly. However, I'd like to streamline development while I'm at it, so my goa...
By design, you can't make the `tests_requires` or the `setup_requires` entries go into the virtual environment. The idea is to separate what is required for performing tests/setup and what is required to actually use the package being installed. For example, I may require that the "coverage" module be needed for runnin...
How to use '\Q' and '\E' regex symbols in python?
9,608,347
4
2012-03-07T20:10:46Z
9,608,424
9
2012-03-07T20:17:45Z
[ "python", "regex", "escaping" ]
I thought this should work, but it doesn't: ``` import re if re.match("\Qbla\E", "bla"): print "works!" ``` Why it doesn't work? Can I use the '\Q' and '\E' symbols in python? How?
Python's regex engine doesn't support those; see [§7.2.1 "Regular Expression Syntax" in the Python documentation](http://docs.python.org/library/re.html#regular-expression-syntax) for a list of what it *does* support. However, you can get the same effect by writing `re.match(re.escape("bla"), "bla")`; `re.escape` is a ...
Draw axis lines or the origin for Matplotlib contour plot
9,609,372
9
2012-03-07T21:30:56Z
9,609,465
34
2012-03-07T21:37:24Z
[ "python", "matplotlib", "contour" ]
I want to draw `x=0` and `y=0` axis in my contour plot, using a white color. If that is too cumbersome, I would like to have a white dot denoting where the origin is. My contour plot looks as follows and the code to create it is given below. ``` xvec = linspace(-5.,5.,100) X,Y = meshgri...
There are a number of options (E.g. [centered spines](http://matplotlib.sourceforge.net/examples/pylab_examples/spine_placement_demo.html)), but in your case, it's probably simplest to just use [`axhline`](http://matplotlib.sourceforge.net/api/pyplot_api.html?highlight=axvline#matplotlib.pyplot.axvline) and [`axvline`]...
Looping over subset in Jinja
9,610,393
12
2012-03-07T22:55:05Z
9,610,501
18
2012-03-07T23:03:24Z
[ "python", "jinja2" ]
Jinja allows me to do ``` {% for item in all_items %} {{ item }} {% endfor %} ``` but I'd like to be able to only take the first *n* items; in Python that would be ``` for item in all_items[:n]: ``` Is there any elegant way to do this in Jinja, except ``` {% for item in all_items %} {% if loop.index <= n %...
You can use normal python slice syntax. ``` >>> import jinja2 >>> t = jinja2.Template("{% for i in items[:3] %}{{ i }}\n{% endfor %}") >>> items = range(10) >>> print(t.render(items=items)) 0 1 2 ```
Python type() or __class__, == or is
9,610,993
24
2012-03-07T23:52:47Z
9,611,031
8
2012-03-07T23:56:24Z
[ "python", "language-features" ]
I want to test whether an object is an instance of a class, and only this class (no subclasses). I could do it either with: ``` obj.__class__ == Foo obj.__class__ is Foo type(obj) == Foo type(obj) is Foo ``` Are there reasons to choose one over another? (performance differences, pitfalls, etc) In other words: a) is ...
The result of `type()` is equivalent to `obj.__class__` in new style classes, and class objects are not safe for comparison using `is`, use `==` instead. **For new style classes** the preferable way here would be `type(obj) == Foo`. As Michael Hoffman pointed out in his answer, there is a difference here between new ...
Python type() or __class__, == or is
9,610,993
24
2012-03-07T23:52:47Z
9,611,066
8
2012-03-07T23:59:50Z
[ "python", "language-features" ]
I want to test whether an object is an instance of a class, and only this class (no subclasses). I could do it either with: ``` obj.__class__ == Foo obj.__class__ is Foo type(obj) == Foo type(obj) is Foo ``` Are there reasons to choose one over another? (performance differences, pitfalls, etc) In other words: a) is ...
`is` should only be used for identity checks, not type checks (there is an exception to the rule where you can and should use `is` for check against singletons). Note: I would generally not use `type` and `==` for type checks, either. The preferable way for type checks is `isinstance(obj, Foo)`. If you ever have a rea...
Python type() or __class__, == or is
9,610,993
24
2012-03-07T23:52:47Z
9,611,083
11
2012-03-08T00:02:06Z
[ "python", "language-features" ]
I want to test whether an object is an instance of a class, and only this class (no subclasses). I could do it either with: ``` obj.__class__ == Foo obj.__class__ is Foo type(obj) == Foo type(obj) is Foo ``` Are there reasons to choose one over another? (performance differences, pitfalls, etc) In other words: a) is ...
For old-style classes, there is a difference: ``` >>> class X: pass ... >>> type(X) <type 'classobj'> >>> X.__class__ Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: class X has no attribute '__class__' >>> x = X() >>> x.__class__ <class __main__.X at 0x171b5d50> >>> type(x) <...
If string does not contain any of list of strings in python
9,611,524
5
2012-03-08T00:59:32Z
9,611,586
10
2012-03-08T01:07:58Z
[ "python" ]
I have a list of strings, from which I want to locate every line that has 'http://' in it, but does not have 'lulz', 'lmfao', '.png', or any other items in a list of strings in it. How would I go about this? My instincts tell me to use regular expressions, but I have a moral objection to witchcraft.
Here is an option that is fairly extensible if the list of strings to exclude is large: ``` exclude = ['lulz', 'lmfao', '.png'] filter_func = lambda s: 'http://' in s and not any(x in s for x in exclude) matching_lines = filter(filter_func, string_list) ``` List comprehension alternative: ``` matching_lines = [line...
locking global variables under the Threading module of python
9,612,484
3
2012-03-08T03:26:53Z
9,613,674
7
2012-03-08T06:20:28Z
[ "python", "multithreading", "locking" ]
Let us suppose I have 2 threads and a single global variable in a python code with the threading module. In this code, only thread-1 modifies the global variable's value, whereas, thread-2 only reads the value of the global variable and perform its task depending on that value. In this situation, do I need to protect ...
Assigning an object value to a global variable is an atomic operation in Python. Other threads cannot read a variable incorrectly by reading it while it's being assigned. The GIL guarantees this in the C implementation of Python, but other implementations can and do make that same guarantee in different ways. If the g...
Django Template Test Coverage
9,613,759
19
2012-03-08T06:30:21Z
10,969,020
9
2012-06-10T13:18:23Z
[ "python", "django", "unit-testing", "code-coverage" ]
Is there any way to produce a report containing the code coverage in my django test suite for my site's templates? I already have coverage for python, but coverage for templates to identify dead or untested template code would be awesome. To clarify: I want to find lines in my templates that are never executed or emit...
Have a look at Django Template Coverage tool: <https://github.com/traff/dtcov> It does exactly what you need. EDIT: Django Template Coverage was merged to coverage.py as a plugin: <http://nedbatchelder.com/blog/201501/coveragepy_for_django_templates.html> It is recommended to use it instead of original project.
nose plugin for expected-failures
9,613,932
7
2012-03-08T06:52:37Z
9,615,578
10
2012-03-08T09:46:13Z
[ "python", "testing", "nose" ]
Is there an existing plugin which could be used like: ``` @nose.plugins.expectedfailure def not_done_yet(): a = Thingamajig().fancynewthing() assert a == "example" ``` If the test fails, it would appear like a skipped test: ``` $ nosetests ...S.. ``` ..but if it unexpected passes, it would appear similarly ...
I don't know about a nose plugin, but you could easily write your own decorator to do that. Here's a simple implementation: ``` import functools import nose def expected_failure(test): @functools.wraps(test) def inner(*args, **kwargs): try: test(*args, **kwargs) except Exception: ...
import at module level or at function level?
9,614,051
7
2012-03-08T07:08:50Z
9,614,212
12
2012-03-08T07:29:33Z
[ "python", "function", "import", "module", "scope" ]
Which style is preferable? Style A: ``` def foo(): import some_module some_module.something ``` Style B: ``` import some_module def foo(): some_module.something ``` Assume that `some_module` is not used elsewhere in the code, only inside this function.
Indeed, as already noted, it's usually best to follow the PEP 8 recommendation and do your imports at the top. There are some exceptions though. The key to understanding them lies in your embedded question in your second paragraph: "at what stage does the import ... happen?" Import is actually an executable statement....
How to create 0x0 Numpy array?
9,614,516
7
2012-03-08T08:03:55Z
9,614,627
18
2012-03-08T08:18:19Z
[ "python", "numpy" ]
How do I create a 0 x 0 (i.e. `ndim` = 2, `shape` = (0,0)) `numpy.ndarray` of `float`?
``` >>> import numpy as NP >>> a = NP.empty( shape=(0, 0) ) >>> a array([], shape=(0, 0), dtype=float64) >>> a.shape (0, 0) >>> a.size 0 ``` The array above is initialized as a 2D array--i.e., two size parameters passed for shape. Second, the call to *empty* is not strictly necessary--i.e., an array havi...
(Django) Cannot assign "u'1'": "StaffProfile.user" must be a "User" instance
9,616,569
9
2012-03-08T10:59:33Z
9,616,602
11
2012-03-08T11:01:39Z
[ "python", "django" ]
I have a model like below: ``` class StaffProfile(models.Model): user = models.ForeignKey(User) maas = models.FloatField() maas_gunu = models.CharField(max_length=5) ``` When I try to insert data with a code like below: ``` staffprofilesay = StaffProfile.objects.filter(user = user_id).count() if st...
You need to assign a User object e.g. ``` from django.contrib.auth.models import User user = User.objects.get(id=user_id) staffprofile.user = user ```
How to convert special characters into html entities?
9,616,928
4
2012-03-08T11:27:21Z
9,616,960
7
2012-03-08T11:30:15Z
[ "python", "html", "html-entities" ]
I want to convert, in python, special characters like `"%$!&@á é ©"` and not only `'<&">'` as all the documentation and references I've found so far shows. cgi.escape doesn't solve the problem. For example, the string `"á ê ĩ &"` should be converted to `"&aacute; &ecirc; &itilde; &amp;"`. Does anyboy know how t...
You could build your own loop using the dictionaries you can find in <http://docs.python.org/library/htmllib.html#module-htmlentitydefs> The one you're looking for is `htmlentitydefs.codepoint2name`
Python (2.x) multiplication is not happening properly
9,617,295
2
2012-03-08T11:58:34Z
9,617,335
10
2012-03-08T12:01:39Z
[ "python" ]
Here is the code ... ``` a=4 b=8.0 if a and a >0: a=a*int(b) print "Value:",a ``` The desired o/p should be 32. i am also getting the same in python console. But the same code is present in my product where instead of 32 the out put is coming as 44444444 (eight fours) i.e whatever value i'am giving to multipl...
I bet you 100 bob that in your product `a` is not actually the integer 4, but the string '4'. ``` >>> a = '4' >>> b=8.0 >>> if a and a >0: ... a=a*int(b) ... print "Value:",a ... Value: 44444444 ``` This will happen, for example, if you are using something like `a = raw_input('Please enter a number: ')` and ...
reStructuredText not respecting subheadings
9,618,892
4
2012-03-08T14:08:03Z
9,620,095
7
2012-03-08T15:23:31Z
[ "python", "restructuredtext", "docutils" ]
Here's a simple reST snippet: ``` deleting this line causes all subheadings to be rendered as h1 tags I should be an h1 ================= I should be an h2 ----------------- foo I should also be an h2 ---------------------- foo ``` and here's a demonstration of it being rendered: with initial line: <h...
Don't promote the 1st title to document title. Note the **settings\_overrides** param passed to **publish\_parts()** in the example below: ``` rest_content = """ I should be an h1 ================= I should be an h2 ----------------- foo I should also be an h2 ---------------------- foo """ from docutils.core imp...
best way to preserve numpy arrays on disk
9,619,199
43
2012-03-08T14:28:12Z
9,619,713
23
2012-03-08T15:02:40Z
[ "python", "numpy", "pickle", "binary-data", "preserve" ]
I am looking for a fast way to preserve large numpy arrays. I want to save them to the disk in a binary format, then read them back into memory relatively fastly. cPickle is not fast enough, unfortunately. I found [numpy.savez](http://docs.scipy.org/doc/numpy/reference/generated/numpy.savez.html#numpy.savez) and [nump...
I'm a big fan of hdf5 for storing large numpy arrays. There are two options for dealing with hdf5 in python: <http://www.pytables.org/> <http://www.h5py.org/> Both are designed to work with numpy arrays efficiently.
best way to preserve numpy arrays on disk
9,619,199
43
2012-03-08T14:28:12Z
9,630,021
11
2012-03-09T06:45:38Z
[ "python", "numpy", "pickle", "binary-data", "preserve" ]
I am looking for a fast way to preserve large numpy arrays. I want to save them to the disk in a binary format, then read them back into memory relatively fastly. cPickle is not fast enough, unfortunately. I found [numpy.savez](http://docs.scipy.org/doc/numpy/reference/generated/numpy.savez.html#numpy.savez) and [nump...
savez() save data in a zip file, It may take some time to zip & unzip the file. You can use save() & load() function: ``` f = file("tmp.bin","wb") np.save(f,a) np.save(f,b) np.save(f,c) f.close() f = file("tmp.bin","rb") aa = np.load(f) bb = np.load(f) cc = np.load(f) f.close() ``` To save multiple arrays in one fil...
best way to preserve numpy arrays on disk
9,619,199
43
2012-03-08T14:28:12Z
22,198,736
10
2014-03-05T13:10:04Z
[ "python", "numpy", "pickle", "binary-data", "preserve" ]
I am looking for a fast way to preserve large numpy arrays. I want to save them to the disk in a binary format, then read them back into memory relatively fastly. cPickle is not fast enough, unfortunately. I found [numpy.savez](http://docs.scipy.org/doc/numpy/reference/generated/numpy.savez.html#numpy.savez) and [nump...
There is now a HDF5 based clone of `pickle` called `hickle`! <https://github.com/telegraphic/hickle> ``` import numpy as np import hickle as hkl data = {'name' : 'test', 'data_arr' : [1, 2, 3, 4]} # Dump data to file hkl.dump(data, 'new_data_file.hkl') # Load data from file data2 = hkl.load('new_data_file.hkl') ...
Calculate Hitting Time between 2 nodes using NetworkX
9,619,541
4
2012-03-08T14:52:37Z
9,621,864
11
2012-03-08T17:14:45Z
[ "python", "numpy", "graph-theory", "networkx", "pagerank" ]
I would like to know if i can use `NetworkX` to implement hitting time? Basically I want to calculate the hitting time between any 2 nodes in a graph. My graph is unweighted and undirected. If I understand hitting time correctly, it is very similar to the idea of PageRank. Any idea how can I implement hitting time usi...
You don't need `networkX` to solve the problem, `numpy` can do it if you understand the math behind it. A undirected, unweighted graph can always be represented by a [0,1] adjacency matrix. `nth` powers of this matrix represent the number of steps from `(i,j)` after `n` steps. We can work with a Markov matrix, which is...
The most effective way to assign unique integer id to a string?
9,619,619
2
2012-03-08T14:56:51Z
9,619,677
7
2012-03-08T15:00:40Z
[ "python", "hash" ]
The program that I write processes a large number of objects, each with its own unique id, which itself is a string of complicated structure (dozen of unique fields of the object joined by some separator) and big length. Since I have to process a lot of these objects fast and I need to reffer to them by id while proce...
For comparison purposes, you can `intern` the strings and then compare them with `is` instead of `==`, which does a simple pointer comparison and should be as fast as (or faster than) comparing two integers: ``` >>> 'foo' * 100 is 'foo' * 100 False >>> intern('foo' * 100) is intern('foo' * 100) True ``` `intern` guar...
SQLAlchemy proper session handling in multi-thread applications
9,619,789
17
2012-03-08T15:06:36Z
9,621,251
29
2012-03-08T16:35:02Z
[ "python", "multithreading", "session", "sqlalchemy" ]
I have trouble understanding how to properly open and close database sessions efficiently, as I understood by the sqlalchemy documentation, if I use scoped\_session to construct my Session object, and then use the returned Session object to create sessions, it's threadsafe, so basically every thread will get it's own s...
You should only be calling `create_engine` and `scoped_session` once per process (per database). Each will get its own pool of connections or sessions (respectively), so you want to make sure you're only creating *one* pool. Just make it a module level global. if you need to manage your sessions more preciesly than tha...
Python3 CSV module and dictionary
9,620,034
4
2012-03-08T15:20:21Z
9,620,133
10
2012-03-08T15:26:04Z
[ "python", "csv", "python-3.x" ]
Fairly new to python, forgive me if this is a basic question about learning how to use CSV files. ``` import csv theReader = csv.reader(open('filename.csv'), delimiter=',') for line in theReader: print line ``` So I've managed to open the file and can print it sprawling across my screen. But I'm trying to captur...
Python has a built in library that handles reading your lines as dictionaries for you. It is DictReader instead of reader. <http://docs.python.org/release/3.1.3/library/csv.html#csv.DictReader> so using this each line would be a dictionary instead of a list. ``` from csv import DictReader the_reader = DictReader(ope...
Boost.Python custom exception class
9,620,268
8
2012-03-08T15:34:38Z
9,690,436
9
2012-03-13T19:08:05Z
[ "c++", "python", "exception", "boost-python" ]
I'm implementing a Python extension module using Boost.Python. The module should define its own custom exception classes that inherit `Exception`. How do I do that?
The following function creates a new Python exception class and adds it to the current scope. If it is called in a module initialization function, then it is added to the module. The first argument is the name of the new exception class. The second argument is the type object for the base class of the new exception cl...
In Flask, why are all the views shown in a single file?
9,620,575
10
2012-03-08T15:51:58Z
9,621,349
7
2012-03-08T16:41:38Z
[ "python", "flask" ]
Is there a way to split them up (view per file) or is this not recommendable? I'm working on a rather large project and will have a lot of views. Thanks.
You can break down views in various ways. Here are a couple of examples: * <https://github.com/mitsuhiko/flask-website/tree/master/flask_website/views> * <https://bitbucket.org/imwilsonxu/fbone/src/a3f1439f6941/fbone/views> And here's another neat way of organizing your app: [Flask-Classy](https://github.com/apiguy/f...
In Flask, why are all the views shown in a single file?
9,620,575
10
2012-03-08T15:51:58Z
9,621,869
9
2012-03-08T17:15:22Z
[ "python", "flask" ]
Is there a way to split them up (view per file) or is this not recommendable? I'm working on a rather large project and will have a lot of views. Thanks.
* You could put the views into [blueprints](http://flask.pocoo.org/docs/blueprints/#blueprints) which create normally a very nice and clear structure in a flask application. * There is also a nice feature called [Pluggable Views](http://flask.pocoo.org/docs/views/) to create views from classes which is very helpful by ...
Increment of an element in a dictionary of list in Python
9,620,804
2
2012-03-08T16:06:09Z
9,620,865
9
2012-03-08T16:10:42Z
[ "python", "dictionary" ]
I have this trivial code: ``` M = dict.fromkeys([0, 1, 2, 3, 4], [0, 0]) M[0][1] += 2 print(M) ``` Why is this the output? ``` {0: [0, 2], 1: [0, 2], 2: [0, 2], 3: [0, 2], 4: [0, 2]} ``` It increment all elements of the lists in the dictionary! I want to increment just the second element of the list with key 0, som...
all the values in `M` point to the *exact same* list. Proof: ``` >>> map(id, M.values()) [139986331512912, 139986331512912, 139986331512912, 139986331512912, 139986331512912] ``` If you change it, it will affect all keys. Try creating a new list for every key: ``` >>> M = { k:[0,0] for k in [0, 1, 2, 3, 4] } >>> M[0...
Going to Python from R, what's the python equivalent of a data frame?
9,621,185
22
2012-03-08T16:30:48Z
9,621,273
8
2012-03-08T16:36:29Z
[ "python" ]
I'm familiar with the R data holders like vectors, dataframe, etc. but need to do some text analysis and it seems like python has some good setups for doing so. My question is where can I find an explanation of how python holds data. Specifically I have a data set in a tab-separated file where the text is in the 3rd c...
I'm not sure how well this translates to 'R' which I never used, but in Python this is how I would approach it: ``` lines = list() with open('data.txt','r') as f: for line in f: lines.append(line.split()) ``` That will read everything in a python list. Lists are zero-based. To get the text column from the sec...
Going to Python from R, what's the python equivalent of a data frame?
9,621,185
22
2012-03-08T16:30:48Z
9,621,286
29
2012-03-08T16:37:19Z
[ "python" ]
I'm familiar with the R data holders like vectors, dataframe, etc. but need to do some text analysis and it seems like python has some good setups for doing so. My question is where can I find an explanation of how python holds data. Specifically I have a data set in a tab-separated file where the text is in the 3rd c...
Look at the [DataFrame](http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe) object in the [pandas](http://pandas.pydata.org/) library.
Going to Python from R, what's the python equivalent of a data frame?
9,621,185
22
2012-03-08T16:30:48Z
9,621,816
7
2012-03-08T17:11:17Z
[ "python" ]
I'm familiar with the R data holders like vectors, dataframe, etc. but need to do some text analysis and it seems like python has some good setups for doing so. My question is where can I find an explanation of how python holds data. Specifically I have a data set in a tab-separated file where the text is in the 3rd c...
There is no native equivalent to an R dataframe (and it's the main reason why I moved to R). However, you can use the rpy2 library (from <http://thread.gmane.org/gmane.comp.python.rpy/1344>): ``` import array import rpy2.robjects as ro d = dict(x = array.array('i', [1,2]), y = array.array('i', [2,3])) dataf = ro.r['d...
Going to Python from R, what's the python equivalent of a data frame?
9,621,185
22
2012-03-08T16:30:48Z
9,622,265
10
2012-03-08T17:46:08Z
[ "python" ]
I'm familiar with the R data holders like vectors, dataframe, etc. but need to do some text analysis and it seems like python has some good setups for doing so. My question is where can I find an explanation of how python holds data. Specifically I have a data set in a tab-separated file where the text is in the 3rd c...
Mr Ullrich's answer of using the [pandas](http://pandas.pydata.org/) library is the closest approach to the R data frame. However, you can get extremely similar functionality using the [numpy array](http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html), with the data type set to `object` if necessary. N...
(Django) how to get month name?
9,621,388
5
2012-03-08T16:44:12Z
9,621,418
19
2012-03-08T16:46:46Z
[ "python", "django", "datetime" ]
I have a query like below: ``` today = datetime.datetime.now() month = today.month print month ``` and it outputs: ``` 3 ``` I want to display the month name like "March". What should I do?
use the datetime string formatting method, e.g. ``` >>> today.strftime('%B') 'March' ``` for more info, and a full list of formatting codes, see [the python `datetime` docs](http://docs.python.org/library/datetime.html#strftime-strptime-behavior)
Django accessing ForeignKey model objects
9,622,047
10
2012-03-08T17:29:06Z
9,622,120
14
2012-03-08T17:35:14Z
[ "python", "django" ]
Let's say I have the following: ``` class Employee(models.Model): firstName = models.CharField(max_length = 30) lastName = models.CharField(max_length = 30) class License(models.Model): employee = models.ForeignKey(Employee) type = models.CharField(max_length = 30) ``` and in a custom management comm...
``` employee.license_set.all() ``` <https://docs.djangoproject.com/en/dev/topics/db/queries/#backwards-related-objects>
Python: Confused with list.remove
9,622,122
10
2012-03-08T17:35:42Z
9,622,152
11
2012-03-08T17:37:45Z
[ "python", "list" ]
I'm very new to Python, so sorry for the probably simple question. (Although, I spent now 2 hours to find an answer) I simplified my code to illustrate the problem: ``` side=[5] eva=side print(str(side) + " side before") print(str(eva) + " eva before") eva.remove(5) print(str(side) + " side after") print(str(eva) + "...
`eva` and `side` refer to the same list. If you want to have a copy of the list: ``` eva = side[:] ``` You can read more about copying lists in this article: [Python: copying a list the right way](http://henry.precheur.org/python/copy_list) **Edit**: That isn't the only way to copy lists. See the link posted in the...
Python: Confused with list.remove
9,622,122
10
2012-03-08T17:35:42Z
9,622,308
13
2012-03-08T17:49:10Z
[ "python", "list" ]
I'm very new to Python, so sorry for the probably simple question. (Although, I spent now 2 hours to find an answer) I simplified my code to illustrate the problem: ``` side=[5] eva=side print(str(side) + " side before") print(str(eva) + " eva before") eva.remove(5) print(str(side) + " side after") print(str(eva) + "...
Python has "things" and "names for things". When you write ``` side = [5] ``` you make a new thing `[5]`, and give it the name `side`. When you then write ``` eva = side ``` you make a new name for `side`. Assignments are just giving names to things! There's still only one thing `[5]`, with two different names. If...
Save plot to image file instead of displaying it using Matplotlib (so it can be used in batch scripts for example)
9,622,163
384
2012-03-08T17:38:10Z
9,888,817
72
2012-03-27T11:36:31Z
[ "python", "matplotlib" ]
I am writing a quick-and-dirty script to generate plots on the fly. I am using the code below (from [Matplotlib](http://en.wikipedia.org/wiki/Matplotlib) documentation) as a starting point: ``` from pylab import figure, axes, pie, title, show # Make a square figure and axes figure(1, figsize=(6, 6)) ax = axes([0.1, 0...
The solution is: ``` pylab.savefig('foo.png') ```
Save plot to image file instead of displaying it using Matplotlib (so it can be used in batch scripts for example)
9,622,163
384
2012-03-08T17:38:10Z
9,890,599
502
2012-03-27T13:35:44Z
[ "python", "matplotlib" ]
I am writing a quick-and-dirty script to generate plots on the fly. I am using the code below (from [Matplotlib](http://en.wikipedia.org/wiki/Matplotlib) documentation) as a starting point: ``` from pylab import figure, axes, pie, title, show # Make a square figure and axes figure(1, figsize=(6, 6)) ax = axes([0.1, 0...
While the question has been answered, I'd like to add some useful tips when using [savefig](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.savefig). The file format can be specified by the extension: ``` savefig('foo.png') savefig('foo.pdf') ``` Will give a rasterized or vectorized output res...
Save plot to image file instead of displaying it using Matplotlib (so it can be used in batch scripts for example)
9,622,163
384
2012-03-08T17:38:10Z
21,464,691
17
2014-01-30T18:30:37Z
[ "python", "matplotlib" ]
I am writing a quick-and-dirty script to generate plots on the fly. I am using the code below (from [Matplotlib](http://en.wikipedia.org/wiki/Matplotlib) documentation) as a starting point: ``` from pylab import figure, axes, pie, title, show # Make a square figure and axes figure(1, figsize=(6, 6)) ax = axes([0.1, 0...
If you don't like the concept of the "current" figure, do: ``` import matplotlib.image as mpimg img = mpimg.imread("src.png") mpimg.imsave("out.png", img) ```
Save plot to image file instead of displaying it using Matplotlib (so it can be used in batch scripts for example)
9,622,163
384
2012-03-08T17:38:10Z
29,931,148
35
2015-04-28T22:35:11Z
[ "python", "matplotlib" ]
I am writing a quick-and-dirty script to generate plots on the fly. I am using the code below (from [Matplotlib](http://en.wikipedia.org/wiki/Matplotlib) documentation) as a starting point: ``` from pylab import figure, axes, pie, title, show # Make a square figure and axes figure(1, figsize=(6, 6)) ax = axes([0.1, 0...
As others have said, `plt.savefig()` or `fig1.savefig()` is indeed the way to save an image. However I've found that in certain cases (eg. with Spyder having `plt.ion()`: interactive mode = On) the figure is always shown. I work around this by forcing the closing of the figure window in my giant loop, so I don't have ...
Save plot to image file instead of displaying it using Matplotlib (so it can be used in batch scripts for example)
9,622,163
384
2012-03-08T17:38:10Z
31,133,453
7
2015-06-30T08:38:37Z
[ "python", "matplotlib" ]
I am writing a quick-and-dirty script to generate plots on the fly. I am using the code below (from [Matplotlib](http://en.wikipedia.org/wiki/Matplotlib) documentation) as a starting point: ``` from pylab import figure, axes, pie, title, show # Make a square figure and axes figure(1, figsize=(6, 6)) ax = axes([0.1, 0...
``` import datetime import numpy as np from matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot as plt # Create the PdfPages object to which we will save the pages: # The with statement makes sure that the PdfPages object is closed properly at # the end of the block, even if an Exception occurs. w...
Save plot to image file instead of displaying it using Matplotlib (so it can be used in batch scripts for example)
9,622,163
384
2012-03-08T17:38:10Z
34,583,288
16
2016-01-04T00:35:56Z
[ "python", "matplotlib" ]
I am writing a quick-and-dirty script to generate plots on the fly. I am using the code below (from [Matplotlib](http://en.wikipedia.org/wiki/Matplotlib) documentation) as a starting point: ``` from pylab import figure, axes, pie, title, show # Make a square figure and axes figure(1, figsize=(6, 6)) ax = axes([0.1, 0...
Just found this link on the MatPlotLib documentation addressing exactly this issue: <http://matplotlib.org/faq/howto_faq.html#generate-images-without-having-a-window-appear> They say that the easiest way to prevent the figure from popping up is to use a non-interactive backend (eg. Agg), via `matplotib.use(<backend>)`...
python xlrd unsupported format, or corrupt file.
9,623,029
12
2012-03-08T18:43:13Z
9,631,500
12
2012-03-09T09:14:07Z
[ "python", "excel", "xlrd" ]
My code: ``` import xlrd wb = xlrd.open_workbook("Z:\\Data\\Locates\\3.8 locates.xls") sh = wb.sheet_by_index(0) print sh.cell(0,0).value ``` The error: ``` Traceback (most recent call last): File "Z:\Wilson\tradedStockStatus.py", line 18, in <module> wb = xlrd.open_workbook("Z:\\Data\\Locates\\3.8 locates.xls") Fil...
You say: > The file doesn't seem to be corrupted or of a different format. However as the error message says, the first 8 bytes of the file are `'<table r'` ... that is definitely not Excel `.xls` format. Open it with a text editor (e.g. Notepad) that won't take any notice of the (incorrect) `.xls` extension and see ...
Check if two unordered lists are equal
9,623,114
103
2012-03-08T18:49:43Z
9,623,147
178
2012-03-08T18:51:31Z
[ "python" ]
I'm looking for an easy (and quick) way to determine if two **unordered** lists contain the same elements: For example: ``` ['one', 'two', 'three'] == ['one', 'two', 'three'] : true ['one', 'two', 'three'] == ['one', 'three', 'two'] : true ['one', 'two', 'three'] == ['one', 'two', 'three', 'three'] : false ['one',...
Python has a built-in datatype for an unordered collection of (hashable) things, called a `set`. If you convert both lists to sets, the comparison will be unordered. ``` set(x) == set(y) ``` [Documentation on `set`](http://docs.python.org/library/stdtypes.html#set) --- EDIT: @mdwhatcott points out that you want to ...
Check if two unordered lists are equal
9,623,114
103
2012-03-08T18:49:43Z
9,623,607
32
2012-03-08T19:28:42Z
[ "python" ]
I'm looking for an easy (and quick) way to determine if two **unordered** lists contain the same elements: For example: ``` ['one', 'two', 'three'] == ['one', 'two', 'three'] : true ['one', 'two', 'three'] == ['one', 'three', 'two'] : true ['one', 'two', 'three'] == ['one', 'two', 'three', 'three'] : false ['one',...
If elements are always nearly sorted as in your example then builtin `.sort()` ([timsort](http://hg.python.org/cpython/file/2.7/Objects/listsort.txt)) should be fast: ``` >>> a = [1,1,2] >>> b = [1,2,2] >>> a.sort() >>> b.sort() >>> a == b False ``` If you don't want to sort inplace you could use [`sorted()`](http://...
Python format throws KeyError
9,623,134
21
2012-03-08T18:51:00Z
9,623,246
33
2012-03-08T18:57:22Z
[ "python" ]
The following code snippet: ``` template = "\ function routes(app, model){\ app.get('/preNew{className}', function(req, res){\ r...
You have a number of unescaped braces in that code. Python considers all braces to be placeholders and is trying to substitute them all. However, you have only supplied one value. I expect that you don't want all your braces to be placeholders, so you should double the ones that you don't want substituted. Such as: `...
Can you have too many asserts (in Python)?
9,624,509
6
2012-03-08T20:34:21Z
9,624,678
7
2012-03-08T20:46:29Z
[ "python", "validation", "assert" ]
Lately, I've been adding `asserts` to nearly every single function I make to validate every input as sort of a poor-man's replacement for type checking or to prevent myself from accidentally inputting malformed data while developing. For example, ``` def register_symbol(self, symbol, func, keypress=None): assert(i...
I only use `assert`s if they provide far better diagnostics than the error messages that I would get otherwise. Your third assert ``` assert(callable(func)) ``` might be an example for such an assert -- if `func` is not callable, you will get an error message at a completely different line of code than where the actu...
Basic trig: math.atan() issue
9,624,515
4
2012-03-08T20:34:53Z
9,624,606
11
2012-03-08T20:40:47Z
[ "python", "trigonometry" ]
I'm having a little trouble with some basic trig. I'm doing some math homework, and I finally got bored of converting rectangular coordinates to polar coordinates and vice versa, so I decided to whip up a little Python program to help me with the conversions. However, Math.atan() is giving me a little trouble. Here's t...
You should use `atan2` for this. It deals with the quadrants exactly as you need. Like so: ``` def rect_to_polar_input(x, y): hypotenuse = math.hypot(x, y) angle = round(math.degrees(math.atan2(y, x))) if angle<0: angle += 360 return hypotenuse, angle ``` The `if` statement is to deal with the...
matplotlib chart - creating horizontal bar chart
9,626,298
9
2012-03-08T22:51:39Z
9,626,572
16
2012-03-08T23:15:33Z
[ "python", "matplotlib" ]
I have stumbled accross the following snippet, for creating horizontal bar chart using matplotlib: ``` import matplotlib from pylab import * val = 3+10*rand(5) # the bar lengths pos = arange(5)+.5 # the bar centers on the y axis print pos figure(1) barh(pos,val, align='center') yticks(pos, ('Tom', 'Dick', 'Harr...
``` import matplotlib from pylab import * val = 3-6*rand(5) # the bar lengths # changed your data slightly pos = arange(5)+.5 # the bar centers on the y axis print pos figure(1) barh(pos,val, align='center',height=0.1) # notice the 'height' argument yticks(pos, ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')) ...