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-pandas and databases like mysql
10,065,051
65
2012-04-08T18:01:13Z
11,138,275
64
2012-06-21T12:34:29Z
[ "python", "pandas" ]
The documentation for Pandas has numerous examples of best practices for working with data stored in various formats. However, I am unable to find any good examples for working with databases like MySQL for example. Can anyone point me to links or give some code snippets of how to convert query results using mysql-py...
As Wes says, io/sql's read\_sql will do it, once you've gotten a database connection using a DBI compatible library. Here's a short example using the MySQLdb and cx\_Oracle libraries to connect to Oracle and MySQL and query their data dictionaries: ``` import pandas as pd import cx_Oracle ora_conn = cx_Oracle.connect...
python-pandas and databases like mysql
10,065,051
65
2012-04-08T18:01:13Z
12,834,193
8
2012-10-11T07:18:29Z
[ "python", "pandas" ]
The documentation for Pandas has numerous examples of best practices for working with data stored in various formats. However, I am unable to find any good examples for working with databases like MySQL for example. Can anyone point me to links or give some code snippets of how to convert query results using mysql-py...
The same syntax works for Ms SQL server using podbc also. ``` import pyodbc import pandas.io.sql as psql cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=servername;DATABASE=mydb;UID=username;PWD=password') cursor = cnxn.cursor() sql = ("""select * from mytable""") df = psql.frame_query(sql, cnxn) cnxn.close() ```
python-pandas and databases like mysql
10,065,051
65
2012-04-08T18:01:13Z
15,097,125
18
2013-02-26T18:58:37Z
[ "python", "pandas" ]
The documentation for Pandas has numerous examples of best practices for working with data stored in various formats. However, I am unable to find any good examples for working with databases like MySQL for example. Can anyone point me to links or give some code snippets of how to convert query results using mysql-py...
For the record, here is an example using a sqlite database: ``` import pandas as pd import sqlite3 with sqlite3.connect("whatever.sqlite") as con: sql = "SELECT * FROM table_name" df = pd.read_sql_query(sql, con) print df.shape ```
python-pandas and databases like mysql
10,065,051
65
2012-04-08T18:01:13Z
21,260,328
9
2014-01-21T14:03:07Z
[ "python", "pandas" ]
The documentation for Pandas has numerous examples of best practices for working with data stored in various formats. However, I am unable to find any good examples for working with databases like MySQL for example. Can anyone point me to links or give some code snippets of how to convert query results using mysql-py...
MySQL example: ``` import MySQLdb as db from pandas import DataFrame from pandas.io.sql import frame_query database = db.connect('localhost','username','password','database') data = frame_query("SELECT * FROM data", database) ```
python-pandas and databases like mysql
10,065,051
65
2012-04-08T18:01:13Z
23,331,896
12
2014-04-28T03:08:09Z
[ "python", "pandas" ]
The documentation for Pandas has numerous examples of best practices for working with data stored in various formats. However, I am unable to find any good examples for working with databases like MySQL for example. Can anyone point me to links or give some code snippets of how to convert query results using mysql-py...
I prefer to create queries with [**SQLAlchemy**](http://www.sqlalchemy.org/), and then make a DataFrame from it. **SQLAlchemy** makes it easier to combine **SQL** conditions Pythonically if you intend to mix and match things over and over. ``` from sqlalchemy.ext.declarative import declarative_base from sqlalchemy imp...
python-pandas and databases like mysql
10,065,051
65
2012-04-08T18:01:13Z
25,030,617
34
2014-07-30T07:04:38Z
[ "python", "pandas" ]
The documentation for Pandas has numerous examples of best practices for working with data stored in various formats. However, I am unable to find any good examples for working with databases like MySQL for example. Can anyone point me to links or give some code snippets of how to convert query results using mysql-py...
For recent readers of this question: pandas have the following warning in their [docs for version 14.0](http://pandas.pydata.org/pandas-docs/stable/whatsnew.html): > Warning: Some of the existing functions or function aliases have been > deprecated and will be removed in future versions. This includes: > tquery, uquer...
In Python what's some other ways to write a if x==1 or x==5 or x==10...?
10,065,407
9
2012-04-08T18:47:12Z
10,065,445
14
2012-04-08T18:51:10Z
[ "python", "if-statement" ]
I often end up writing code like ``` if x == 1 or x == 5 or x == 10 or x == 22 : pass ``` In English it seems redundant to keep repeating `x`, is there an easier or shorter way to write out an if-statement like that? Maybe checking of existence of `x`'s value in a tuple `( 1, 5, 10, 22, )` or something?
Yes, you are right - either in a tuple or (if this check is made repeatedly) in a set. So either do ``` if x in (1, 5, 10, 22): pass ``` or, if you do this check often and the number of values is large enough, ``` myset = set((1, 5, 10, 22)) [...] if x in myset: pass ``` The `myset` stuff is the more use...
How to update data with a VBO and Pyglet
10,065,631
3
2012-04-08T19:13:59Z
10,092,493
9
2012-04-10T16:17:08Z
[ "python", "opengl", "vbo", "pyglet" ]
I would like to make a mesh with Pyglet that is changing every frame. Therefore I need to update the vertices very often and I thought that a VBO would be the fastest way to go here (correct me if I am wrong). Below an example for Points. Is this the correct way of doing it? I read that the number of glBindBuffer calls...
You don't need to call `glBufferData` every single time in update - create and fill the VBO once (see `setup_initial_points`) and only update it with `glBufferSubData`. In case you are only working with a single VBO, you can also comment out the `glBindBuffer` call in `update()` (see code below). `GL_DYNAMIC_DRAW` vs `...
Difference between map and dict
10,066,374
6
2012-04-08T20:47:35Z
10,066,393
13
2012-04-08T20:50:28Z
[ "python", "map", "hashmap" ]
I might be confused between `hashmap` in Java, and `map`/`dict` in Python. I thought that the `hash` (k/v abstraction) of Java is kind of the same as `dict` in Python But then what does the `map` datatype do? Is it the same abstraction as the hashmap abstraction? If so, then how is it different from dictionary? I...
[Map](http://docs.python.org/library/functions.html#map) is not a datatype in python. It applies a function to a series of values and returns the result. ``` >>> def f(x): ... return x**2 ... >>> map(f, range(5)) [0, 1, 4, 9, 16] ``` Often for a simple case like that to be "pythonic" we use list comprehensions. ...
Post request with multipart/form-data in appengine python not working
10,066,540
4
2012-04-08T21:10:08Z
10,144,903
8
2012-04-13T16:42:54Z
[ "python", "django", "google-app-engine", "post" ]
I'm attempting to send a multipart post request from an appengine app to an external (django) api hosted on dotcloud. The request includes some text and a file (pdf) and is sent using the following code ``` from google.appengine.api import urlfetch from poster.encode import multipart_encode from libs.poster.streamingh...
Here is some code I tested locally that should do the trick (I used a different handler than webapp2 but tried to modify it to webapp2. You'll also need the poster lib found here <http://atlee.ca/software/poster/>): In your POST handler on GAE: ``` from google.appengine.api import urlfetch from poster.encode import m...
How to find common elements in list of lists?
10,066,642
10
2012-04-08T21:23:08Z
10,066,661
23
2012-04-08T21:25:19Z
[ "python", "list", "recursion", "comparison" ]
I'm trying to figure out how to compare an n number of lists to find the common elements. For example: ``` p=[ [1,2,3], [1,9,9], .. .. [1,2,4] >> print common(p) >> [1] ``` Now if I know the number of elements I can do comparions like: ``` for a in b: for c in d: for x in y: ... ``` but t...
You are looking for the set intersection of all the sublists, and the data type you should use for set operations is a set: ``` result = set(p[0]) for s in p[1:]: result.intersection_update(s) print result ```
Python 2.7 : TypeError: 'builtin_function_or_method' object is not subscriptable
10,066,838
2
2012-04-08T21:48:29Z
10,066,846
10
2012-04-08T21:50:07Z
[ "python", "typeerror" ]
I'm trying to make Scrabble in Python. The rack (where the 7 letters are) is a list where I appended 7 times tk.StringVar() Every time the player want to drop a word, I have to get the letters off the rack. Here's my problem. As I can associate the letters of the word dropped and the letters of the rack, I created a pr...
Should be `.index(i)` - parens, not brackets.
Why does Django not find these urls, allthough the regex matches?
10,066,891
3
2012-04-08T21:55:39Z
10,066,932
8
2012-04-08T22:01:43Z
[ "python", "regex", "django" ]
In the python docs for regex there is the description of what the "." does: > (Dot.) In the default mode, this matches any character except a > newline. If the DOTALL flag has been specified, this matches any > character including a newline. For a project i do in Django i set up this regex: ``` url(r'^accounts/confi...
A quick test confirms this should work: ``` >>>import re >>>test = ["accounts/confirm/fb75c6529af9246e4e048d8a4298882909dc03ee0/", "accounts/confirm/fb75c6529af9246e4e-048d8a4298882909dc03ee0/", "accounts/confirm/fb75c6529af9246e4e=048d8a4298882909dc03ee0/", "accounts/confirm/fb75c6529af9246e4e%20048d8a4298882909dc03e...
is it possible to not return anything from a function in python?
10,067,013
6
2012-04-08T22:17:27Z
10,067,021
9
2012-04-08T22:18:52Z
[ "python", "function" ]
with a simple filter that test input against a range 0-100. ``` def foo(foo_input): if 0 <= foo_input <= 100: return f_input ``` This returns none if foo\_input is > 100. But could it actually 'not' return anything? or does a function allways have to return something?
Functions always return something (at least `None`, when no return-statement was reached during execution and the end of the function is reached). Another case is when they are interrupted by exceptions. In this case exception handling will "dominate over the stack" and you will return to the appropriate `except` or g...
is it possible to not return anything from a function in python?
10,067,013
6
2012-04-08T22:17:27Z
10,067,023
9
2012-04-08T22:19:07Z
[ "python", "function" ]
with a simple filter that test input against a range 0-100. ``` def foo(foo_input): if 0 <= foo_input <= 100: return f_input ``` This returns none if foo\_input is > 100. But could it actually 'not' return anything? or does a function allways have to return something?
No. If a `return` statement is not reached before the end of the function then an implicit `None` is returned.
NameError: name 'N_TOKENS' is not defined
10,067,223
4
2012-04-08T22:55:59Z
10,070,672
8
2012-04-09T08:22:58Z
[ "python", "python-2.7", "pycharm" ]
I am new on Python and just got around to install PyCharm for Windows. Downloaded some sample code from Skype for testing their SkypeKit API. But... As soon as I hit the debug button, I get this: (I have Python 2.7 and Django 1.4 installed) ``` Traceback (most recent call last): File "C:\Program Files (x86)\JetBrain...
The tokenize.py module is probably loading the wrong token.py module. See [error importing numpy](http://stackoverflow.com/questions/7414504/error-importing-numpy). Solution 1) rename the new token.py (token2.py) and update references to it in tokenize.py etc. Solution 2) if the new token.py is in a python package you ...
Automatically decorating every instance method in a class
10,067,262
10
2012-04-08T23:01:08Z
10,067,363
14
2012-04-08T23:19:46Z
[ "python", "class", "python-3.x", "decorator" ]
I want to apply the same decorator to every method in a given class, other than those that start and end with `__`. It seems to me it should be doable using a class decorator. Are there any pitfalls to be aware of? Ideally, I'd also like to be able to: 1. disable this mechanism for some methods by marking them with ...
I think this is better done with a metaclass, in order to handle both runtime and subclass method decoration. I don't see an elegant way to handle subclasses automatically with a class decorator. ``` from types import FunctionType # check if an object should be decorated def do_decorate(attr, value): return ('__'...
Is greedy "or" group in regex exists?
10,068,509
6
2012-04-09T03:14:17Z
10,068,524
8
2012-04-09T03:17:06Z
[ "python", "regex" ]
I have an automatically generated regular expression, which basically is one big "or" group like so: ``` (\bthe\b|\bcat\b|\bin\b|\bhat\.\b|\bhat\b) ``` I've noticed that in case of ``` hat. ``` It would match "hat" only, not "hat." as I want. Is there a way to make it more greedy? **UPDATE:** forgot about word bou...
Put `hat\.` before `hat` in the regular expression. The first matching expression in an alternation wins. `hat` matches `hat.` so `hat\.` is never checked. A better way would to just write that part as `hat\.?` rather than `hat\.|hat`. That makes the period optional so you don't need two terms in the alternation. Aft...
How do I insert a space after a certain amount of characters in a string using python?
10,070,434
5
2012-04-09T07:51:55Z
10,070,449
8
2012-04-09T07:54:33Z
[ "python", "string" ]
I need to insert a space after a certain amount of characters in a string. The text is a sentence with no spaces and it needs to be split with spaces after every n characters. so it should be something like this. ``` thisisarandomsentence ``` and i want it to return as : ``` this isar ando msen tenc e ``` the func...
``` def encrypt(string, length): return ' '.join(string[i:i+length] for i in xrange(0,len(string),length)) ``` `encrypt('thisisarandomsentence',4)` gives ``` 'this isar ando msen tenc e' ```
Lambdas inside list comprehensions
10,070,477
7
2012-04-09T07:57:57Z
10,070,557
7
2012-04-09T08:07:38Z
[ "python", "lambda", "functional-programming", "list-comprehension" ]
I wanted to have a list of lambdas that act as sort of a cache to some heavy computation and noticed this: ``` >>> [j() for j in [lambda:i for i in range(10)]] [9, 9, 9, 9, 9, 9, 9, 9, 9, 9] ``` Although ``` >>> list([lambda:i for i in range(10)]) [<function <lambda> at 0xb6f9d1ec>, <function <lambda> at 0xb6f9d22c>...
What you're seeing here is the effect of [closures](http://en.wikipedia.org/wiki/Closure_%28computer_science%29). The lambda is capturing state from the program to be used later. So while each lambda is a unique object, the state isn't necessarily unique. The actual 'gotchya' here, is that the variable `i` is captured...
Lambdas inside list comprehensions
10,070,477
7
2012-04-09T07:57:57Z
10,070,563
13
2012-04-09T08:08:10Z
[ "python", "lambda", "functional-programming", "list-comprehension" ]
I wanted to have a list of lambdas that act as sort of a cache to some heavy computation and noticed this: ``` >>> [j() for j in [lambda:i for i in range(10)]] [9, 9, 9, 9, 9, 9, 9, 9, 9, 9] ``` Although ``` >>> list([lambda:i for i in range(10)]) [<function <lambda> at 0xb6f9d1ec>, <function <lambda> at 0xb6f9d22c>...
The `lambda` returns the value of `i` at the time you call it. Since you call the `lambda` after the loop has finished running, the value of `i` will always be 9. You can create a local `i` variable in the lambda to hold the value at the time the `lambda` was defined: ``` >>> [j() for j in [lambda i=i:i for i in rang...
Non-member vs member functions in Python
10,072,204
12
2012-04-09T10:58:10Z
10,072,274
14
2012-04-09T11:05:03Z
[ "python", "encapsulation", "member-functions", "non-member-functions" ]
I'm relatively new to Python and struggling to reconcile features of the language with habits I've picked up from my background in C++ and Java. The latest issue I'm having has to do with encapsulation, specifically an idea best summed up by Item 23 of Meyer's "*Effective C++*": > [Prefer non-member non-friend functi...
Interesting question. You're starting from a different place than most questions coming from Java programmers, which tend to assume that you need classes when you mostly don't. Generally, in Python there's no point in having classes unless you're specifically doing data encapsulation. Of course, here in your example ...
Why is creating a class in Python so much slower than instantiating a class?
10,072,428
23
2012-04-09T11:18:26Z
10,072,599
27
2012-04-09T11:37:14Z
[ "python", "performance", "class", "memory-management" ]
I found that creation of a class is way slower than instantiation of a class. ``` >>> from timeit import Timer as T >>> def calc(n): ... return T("class Haha(object): pass").timeit(n) <<After several these 'calc' things, at least one of them have a big number, eg. 100000>> >>> calc(9000) 15.947055101394653 >>> c...
This might give you the intuition: ``` >>> class Haha(object): pass ... >>> sys.getsizeof(Haha) 904 >>> sys.getsizeof(Haha()) 64 ``` Class object is **much** more complex and expensive structure than an instance of that class.
Why is creating a class in Python so much slower than instantiating a class?
10,072,428
23
2012-04-09T11:18:26Z
10,072,634
10
2012-04-09T11:40:17Z
[ "python", "performance", "class", "memory-management" ]
I found that creation of a class is way slower than instantiation of a class. ``` >>> from timeit import Timer as T >>> def calc(n): ... return T("class Haha(object): pass").timeit(n) <<After several these 'calc' things, at least one of them have a big number, eg. 100000>> >>> calc(9000) 15.947055101394653 >>> c...
A quick dis of the following functions: ``` def a(): class Haha(object): pass def b(): Haha() ``` gives: ``` 2 0 LOAD_CONST 1 ('Haha') 3 LOAD_GLOBAL 0 (object) 6 BUILD_TUPLE 1 9 LOAD_CONST 2 (<code...
Why is creating a class in Python so much slower than instantiating a class?
10,072,428
23
2012-04-09T11:18:26Z
25,657,995
8
2014-09-04T05:39:39Z
[ "python", "performance", "class", "memory-management" ]
I found that creation of a class is way slower than instantiation of a class. ``` >>> from timeit import Timer as T >>> def calc(n): ... return T("class Haha(object): pass").timeit(n) <<After several these 'calc' things, at least one of them have a big number, eg. 100000>> >>> calc(9000) 15.947055101394653 >>> c...
Ahahaha! Gotcha! Was this perchance done on a Python version without [this patch](https://github.com/python/cpython/commit/ef15a5a230c13d6c69c73141b1c4adf8a676fed9)? (HINT: **IT WAS**) Check the line numbers if you want proof. **Marcin was right**: when the results look screwy you've probably got a screwy benchmark....
Remove repeating characters from words
10,072,744
4
2012-04-09T11:50:00Z
10,072,826
12
2012-04-09T11:56:50Z
[ "python", "nlp", "nltk" ]
I was wondering what is the best way to convert something like "haaaaapppppyyy" to "haappyy". Basically, when parsing slang, people sometimes repeat characters for added emphasis. I was wondering what the best way to do this is? Using `set()` doesn't work because the order of the letters is obviously important. Any ...
It can be done using regular expressions: ``` >>> import re >>> re.sub(r'(.)\1+', r'\1\1', "haaaaapppppyyy") 'haappyy' ``` `(.)\1+` repleaces any character (`.`) followed by one or more of the same character (because of the backref `\1` it must be the same) by twice the character.
How to get first AND last element of tuple at the same time
10,073,137
3
2012-04-09T12:25:26Z
10,073,167
8
2012-04-09T12:28:32Z
[ "python", "indexing", "tuples", "slice" ]
I need to get the first and last dimension of an numpy.ndarray of arbitrary size. If I have `shape(A) = (3,4,4,4,4,4,4,3)` my first Idea would be to do `result = shape(A)[0,-1]` but that doesn't seem to work with tuples, why not ?? Is there a neater way of doing this than ``` s=shape(A) result=(s[0], s[-1]) ``` Tha...
I don't know what's wrong about ``` (s[0], s[-1]) ``` A different option is to use `operator.itemgetter()`: ``` from operator import itemgetter itemgetter(0, -1)(s) ``` I don't think this is any better, though. (It might be slightly faster if you don't count the time needed to instantiate the `itemgetter` instance,...
How can I convert Python dictionary to JavaScript hash table?
10,073,564
2
2012-04-09T12:59:22Z
10,073,713
10
2012-04-09T13:11:10Z
[ "javascript", "python", "django", "django-templates" ]
I have passed to template regular Python dictionary and I need to inside `$(document).ready(function() {.. }` to convert that Python dictionary to JavaScript dictionary. I tried like ``` var js_dict={{parameters}}; ``` but I got errors ( **'** instead of **'** and all strings start with **u'** ). How can I convert ...
Python and javascript both have different ideas about how to represent a dictionary, which means that you need a intermediate representation in order to pass data between them. The most common way to do this is [JSON](http://www.json.org/), which is a simple lightweight data-interchange format. Use the [python json li...
python lookup table
10,074,115
2
2012-04-09T13:42:46Z
10,074,124
10
2012-04-09T13:43:41Z
[ "python" ]
I have a need to create a lookup table where A=10 and Z=35(B=11, C=12 and so on), what's the easiest way to accomplish this in python? I know there must be a very easy way to do it, just can't seem to find it.
For a lookup table you can use a `dict`: ``` d = { 'A' : 10, 'Z' : 35 } # etc.. ``` However in this case it seems there is a simple logical rule for calculating the result so instead of a lookup table you could just use a function with some simple arithmetic: ``` def letterToNumber(c): if not 'A' <= c <= 'Z': ...
python lookup table
10,074,115
2
2012-04-09T13:42:46Z
10,074,127
7
2012-04-09T13:43:55Z
[ "python" ]
I have a need to create a lookup table where A=10 and Z=35(B=11, C=12 and so on), what's the easiest way to accomplish this in python? I know there must be a very easy way to do it, just can't seem to find it.
You don't need a look-up table – the expression ``` chr(c) - 54 ``` (with `c` beinig the upper-case character) will do the trick.
Should memory usage increase when using ElementTree.iterparse() when clear()ing trees?
10,074,200
6
2012-04-09T13:49:55Z
10,078,599
8
2012-04-09T19:26:35Z
[ "python", "memory-leaks", "elementtree" ]
``` import os import xml.etree.ElementTree as et for ev, el in et.iterparse(os.sys.stdin): el.clear() ``` Running the above on the ODP structure [RDF dump](http://rdf.dmoz.org/rdf/structure.rdf.u8.gz) results in always increasing memory. Why is that? I understand ElementTree still builds a parse tree, albeit with...
You are `clear`ing each element but references to them remain in the root document. So the individual elements still cannot be garbage collected. See [this discussion](http://effbot.org/zone/element-iterparse.htm#incremental-parsing) in the ElementTree documentation. The solution is to clear references in the root, li...
Compute hash of only the core image data (excluding metadata) for an image
10,075,065
14
2012-04-09T14:53:33Z
10,075,170
7
2012-04-09T15:01:49Z
[ "python", "exif" ]
I'm writing a script to calculate the MD5 sum of an image excluding the EXIF tag. In order to do this accurately, I need to know where the EXIF tag is located in the file (beginning, middle, end) so that I can exclude it. How can I determine where in the file the tag is located? The images that I am scanning are in ...
One simple way to do it is to hash the core image data. For PNG, you could do this by counting only the "critical chunks" (i.e. the ones starting with capital letters). JPEG has a similar but simpler file structure. The visual hash in ImageMagick decompresses the image as it hashes it. In your case, you could hash the...
Compute hash of only the core image data (excluding metadata) for an image
10,075,065
14
2012-04-09T14:53:33Z
12,175,980
12
2012-08-29T10:33:56Z
[ "python", "exif" ]
I'm writing a script to calculate the MD5 sum of an image excluding the EXIF tag. In order to do this accurately, I need to know where the EXIF tag is located in the file (beginning, middle, end) so that I can exclude it. How can I determine where in the file the tag is located? The images that I am scanning are in ...
It is *much* easier to use the Python Imaging Library to extract the picture data (example in iPython): ``` In [1]: import Image In [2]: import hashlib In [3]: im = Image.open('foo.jpg') In [4]: hashlib.md5(im.tostring()).hexdigest() Out[4]: '171e2774b2549bbe0e18ed6dcafd04d5' ``` This works on any type of image th...
Call exiftool from a python script?
10,075,115
4
2012-04-09T14:58:05Z
10,075,210
14
2012-04-09T15:04:24Z
[ "python", "exiftool" ]
I'm looking to use exiftool to scan the EXIF tags from my photos and videos. It's a perl executable. What's the best way to inferface with this? Are there any Python libraries to do this already? Or should I directly call the executable and parse the output? (The latter seems dirty.) Thanks. The reason I ask is this b...
To avoid launching a new process for each image, you should start `exiftool` using the [`-stay_open`](http://www.sno.phy.queensu.ca/~phil/exiftool/exiftool_pod.html#item__2dstay_open_flag) flag. You can then send commands to the process via stdin, and read the output on stdout. ExifTool supports JSON output, which is p...
How to save dictionaries and arrays in the same archive (with numpy.savez)
10,075,661
8
2012-04-09T15:35:53Z
10,076,319
11
2012-04-09T16:28:23Z
[ "python", "dictionary", "numpy" ]
first question here. I'll try to be concise. I am generating multiple arrays containing feature information for a machine learning application. As the arrays do not have equal dimensions, I store them in a dictionary rather than in an array. There are two different kinds of features, so I am using two different dictio...
As @fraxel has already suggested, using pickle is a much better option in this case. Just save a `dict` with your items in it. However, be sure to use pickle with a binary protocol. By default, it less efficient format, which will result in excessive memory usage and huge files if your arrays are large. ``` saved_dat...
How to save dictionaries and arrays in the same archive (with numpy.savez)
10,075,661
8
2012-04-09T15:35:53Z
10,078,137
7
2012-04-09T18:50:26Z
[ "python", "dictionary", "numpy" ]
first question here. I'll try to be concise. I am generating multiple arrays containing feature information for a machine learning application. As the arrays do not have equal dimensions, I store them in a dictionary rather than in an array. There are two different kinds of features, so I am using two different dictio...
If you need to save your data in a structured way, you should consider using the HDF5 file format (<http://www.hdfgroup.org/HDF5/>). It is very flexible, easy to use, efficient, and other software might already support it (HDFView, Mathematica, Matlab, Origin..). There is a simple python binding called [h5py](http://co...
Python: switching from optparse to argparse
10,076,159
6
2012-04-09T16:16:20Z
10,108,121
12
2012-04-11T14:36:05Z
[ "python", "shell", "command-line-arguments", "argparse", "optparse" ]
After switching from optparse to argparse - I'm experiencing strange errors. Argparse parse args only if leave no space: ``` myScript.py -oOpt ``` or put an equal sign: ``` myScript.py -o=Opt ``` and it doesn't work the normal way: ``` myScript.py -o Opt ``` Here's my argparse initialization: ``` #!/usr/bin/env ...
First, it is necessary to make a small distinction. The `argparse` module does not parse your command-line arguments, the shell does. The shell is responsible for transforming the line you type in the shell into tokens, which are then passed to `sys.argv`, a python array/sequence of command-line arguments. The `argpars...
How to declare a global variable from within a class?
10,076,320
5
2012-04-09T16:28:23Z
10,076,406
9
2012-04-09T16:33:40Z
[ "python", "class" ]
I'm trying to declare a global variable from within a class like so: ``` class myclass: global myvar = 'something' ``` I need it to be accessed outside the class, but I don't want to have to declare it outside the class file. My question is, is this possible? If so, what is the syntax?
In your question, you specify "outside the main file". If you didn't mean "outside the class", then this will work to define a module-level variable: ``` myvar = 'something' class myclass: pass ``` Then you can do, assuming the class and variable definitions are in a module called `mymodule`: ``` import mymodul...
python: sorting a dict of dicts on a key
10,076,568
3
2012-04-09T16:45:54Z
10,076,609
11
2012-04-09T16:48:03Z
[ "python" ]
A data structure like this. ``` { 'ford': {'count': 3}, 'mazda': {'count': 0}, 'toyota': {'count': 1} } ``` What's the best way to sort on the value of `count` within the values of the top-level dict?
``` d = {'ford': {'count': 3}, 'mazda': {'count': 0}, 'toyota': {'count': 1}} >>> sorted(d.items(), key=lambda (k, v): v['count']) [('mazda', {'count': 0}), ('toyota', {'count': 1}), ('ford', {'count': 3})] ``` To keep the result as a dictionary, you can used [`collections.OrderedDict`](http://docs.python.o...
Run Jython and Python in one File
10,077,519
6
2012-04-09T18:01:25Z
10,077,739
9
2012-04-09T18:17:35Z
[ "python", "jython" ]
I developed a project using python. Now i need a gui for that project. So i choose jython for gui(java swing). I also integrate theme in one code (existing project + gui(jython) code). When i run the file with the following command then it shows a syntax error ``` jython project.py ``` Error: ``` File "project.py", ...
Because `with` only just appeared in 2.5, you need a `from __future__` import: ``` from __future__ import with_statement ``` Then you can use your `with` statement. It won't solve your other problems that cropped up in your comments, though...
Python display text w/ font & color?
10,077,644
28
2012-04-09T18:09:49Z
10,077,748
34
2012-04-09T18:18:10Z
[ "python", "pygame" ]
Is there a way I can display text on a pygame window using python? I need to display a bunch of live information that updates and would rather not make an image for each character I need. Can I blit text to the screen?
Yes. It is possible to draw text in pygame: ``` # initialize font; must be called after 'pygame.init()' to avoid 'Font not Initialized' error myfont = pygame.font.SysFont("monospace", 15) # render text label = myfont.render("Some text!", 1, (255,255,0)) screen.blit(label, (100, 100)) ```
Django - DatabaseError: No such table
10,077,721
10
2012-04-09T18:16:09Z
10,080,255
8
2012-04-09T21:41:38Z
[ "python", "database", "django", "django-models" ]
I defined two models: ``` class Server(models.Model): owners = models.ManyToManyField('Person') class Person(models.Model): name = models.CharField(max_length=50) admin.site.register(Server) admin.site.register(Person) ``` After that I even checked the sql, just for fun: ``` BEGIN; CREATE TABLE "servers_se...
As a tip for the future, look into [South](http://south.aeracode.org/), a very useful utility for applying your model changes to the database without having to create a new database each time you've changed the model(s). With it you can easily: `python manage.py migrate app_name` and South will write your model change...
Django - DatabaseError: No such table
10,077,721
10
2012-04-09T18:16:09Z
10,088,249
7
2012-04-10T11:51:53Z
[ "python", "database", "django", "django-models" ]
I defined two models: ``` class Server(models.Model): owners = models.ManyToManyField('Person') class Person(models.Model): name = models.CharField(max_length=50) admin.site.register(Server) admin.site.register(Person) ``` After that I even checked the sql, just for fun: ``` BEGIN; CREATE TABLE "servers_se...
Actually the problem was that the table never got created. Since I am fairly new with django, I did not know that `./manage.py syncdb` does not update existing models, but only creates the ones that do not exist. Because the model 'Server' existed before I added the other model, and it was already in the db, 'syncdb' ...
Copying ManyToMany fields from one model instance to another
10,078,015
5
2012-04-09T18:39:49Z
10,080,118
9
2012-04-09T21:28:02Z
[ "python", "django", "django-models", "django-1.4" ]
I'm new to django, and as a learning app, I'm building an expense logging application. In my models I have three classes that look like this (I simplified them slightly for brevity): ``` class AbstractExpense(models.Model): description = models.CharField(max_length=100) amount = models.IntegerField() ...
You cannot set an m2m field directly like that when creating a model instance. Try the following instead: ``` expense = Expense(description=self.description, amount=self.amount, category=self.category, date=expense_date) expense.save() expense.tags.add(*self.tags.all()) ``` You can check <http...
Copying ManyToMany fields from one model instance to another
10,078,015
5
2012-04-09T18:39:49Z
10,093,557
7
2012-04-10T17:30:56Z
[ "python", "django", "django-models", "django-1.4" ]
I'm new to django, and as a learning app, I'm building an expense logging application. In my models I have three classes that look like this (I simplified them slightly for brevity): ``` class AbstractExpense(models.Model): description = models.CharField(max_length=100) amount = models.IntegerField() ...
The simpliest method I could come up with: ``` e = Expense(description=self.description, amount=self.amount, category=self.category, date=expense_date) e.save() e.tags = self.tags.all() ```
Sort numpy matrix row values in ascending order
10,078,470
4
2012-04-09T19:16:00Z
10,078,608
11
2012-04-09T19:27:12Z
[ "python", "arrays", "matrix", "numpy" ]
I have this following numpy matrix that I want to sort in ascending order **based on the 3rd column values**. ``` [[ 3.05706500e+06 4.98000000e+01 -2.62500070e+01 -9.38135544e+01] [ 3.05706600e+06 4.98000000e+01 -3.00000056e+01 -9.38135544e+01] [ 3.05706700e+06 4.98000000e+01 -3.37500042e+01 -9.381355...
Given your array ``` >>> arr array([[ 3.05706500e+06, 4.98000000e+01, -2.62500070e+01, -9.38135544e+01], [ 3.05706600e+06, 4.98000000e+01, -3.00000056e+01, -9.38135544e+01], [ 3.05706700e+06, 4.98000000e+01, -3.37500042e+01, -9.38135544e+01], [ 3.05706800e+0...
Assert call to method using Mock python
10,078,648
5
2012-04-09T19:30:38Z
10,078,776
7
2012-04-09T19:40:42Z
[ "python", "mocking" ]
I am trying unit testing using the mock library in python. I have the following code. ``` def a(): print 'a' def b(): print 'b' if some condition a() ``` how do i assert that a call for b has been made when a mock call to b has been made. I have tried the following code, but it failed: ``` mymoc...
If you patch `a`, you can ensure it was called like so: ``` with mock.patch('__main__.a') as fake_a: b() fake_a.assert_called_with() ``` If your method is in a different module: ``` import mymodule with mock.patch('mymodule.a') as fake_a: mymodule.b() fake_a.assert_called_with() ```
Django templates: accessing the previous and the following element of the list
10,078,683
3
2012-04-09T19:32:47Z
10,078,830
9
2012-04-09T19:44:44Z
[ "python", "django", "django-templates" ]
I am rather new to django templates and have an impression that I have not understood some basics. I have a list of elements and I need to render an element of the list based on conditions against the the previous and the next elements (in case the following or the previous elements are hidden, I need to mark the curr...
You could [write a custom template filter](https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters) for `next` and `previous`: ``` def next(value, arg): try: return value[int(arg)+1] except: return None ``` and in the template: ``` {% for ... %} {% ...
Django 1.4 and timezones
10,078,822
3
2012-04-09T19:43:50Z
10,078,988
7
2012-04-09T19:57:33Z
[ "python", "django", "timezone" ]
In django docs, it is written that they can always store the datetime objects in TIME\_ZONE provided in settings. I wanted to ask that is it just sufficient to date time aware objects or do we have to convert them to TIME\_ZONE setting? ie if my TIME\_ZONE = "America/Los\_Angeles" and USE\_TZ = True, and I try to save...
I believe that with `USE_TZ = True` django will save everything to the DB in UTC. Every DateTime object must be timezone aware to be saved. When django retrieves a datetime from the database, it will automatically change it from UTC to an aware time in the time zone indicated by `TIME_ZONE` in the settings. So to answ...
How can I improve my code for euler 14?
10,078,987
6
2012-04-09T19:57:29Z
10,079,051
11
2012-04-09T20:02:17Z
[ "python" ]
I solved [Euler problem 14](http://projecteuler.net/problem=14) but the program I used is very slow. I had a look at what the others did and they all came up with elegant solutions. I tried to understand their code without much success. Here is my code (the function to determine the length of the Collatz chain ``` de...
Rather than computing every possible chain from the start to the end, you can keep a cache of chain starts and their resulting length. For example, for the chain ``` 13 40 20 10 5 16 8 4 2 1 ``` you could remember the following: 1. The Collatz chain that starts with 13 has length 10 2. The Collatz chain that...
Training Naive Bayes Classifier on ngrams
10,079,163
9
2012-04-09T20:11:04Z
10,079,310
11
2012-04-09T20:21:11Z
[ "python", "ruby", "nlp", "machine-learning", "classification" ]
I've been using the [Ruby Classifier library](http://classifier.rubyforge.org/) to [classify privacy policies](http://stackoverflow.com/questions/9709293/interesting-nlp-machine-learning-style-project-analyzing-privacy-policies). I've come to the conclusion that the simple bag-of-words approach built into this library ...
If you're ok with python, I'd say [nltk](http://www.nltk.org/data) would be perfect for you. For example: ``` >>> import nltk >>> s = "This is some sample data. Nltk will use the words in this string to make ngrams. I hope that this is useful.".split() >>> model = nltk.NgramModel(2, s) >>> model._ngrams set([('to',...
Skip first entry in for loop in python?
10,079,216
62
2012-04-09T20:14:55Z
10,079,247
121
2012-04-09T20:16:57Z
[ "python" ]
In python, How do I do something like: ``` for car in cars: # Skip first and last, do work for rest ```
To skip the first element in Python you can simply write ``` for car in cars[1:]: # Do What Ever you want ``` or to skip the last elem ``` for car in cars[:-1]: # Do What Ever you want ``` You can use this concept for any sequence.
Skip first entry in for loop in python?
10,079,216
62
2012-04-09T20:14:55Z
10,079,265
103
2012-04-09T20:17:58Z
[ "python" ]
In python, How do I do something like: ``` for car in cars: # Skip first and last, do work for rest ```
The other answers only work for a sequence. For any iterable, to skip the first item: ``` itercars = iter(cars) next(itercars) for car in itercars: # do work ``` If you want to skip the last, you could do: ``` itercars = iter(cars) # add 'next(itercars)' here if you also want to skip the first prev = next(iterc...
Skip first entry in for loop in python?
10,079,216
62
2012-04-09T20:14:55Z
10,079,869
9
2012-04-09T21:06:32Z
[ "python" ]
In python, How do I do something like: ``` for car in cars: # Skip first and last, do work for rest ```
Here is a more general generator function that skips any number of items from the beginning and end of an iterable: ``` def skip(iterable, at_start=0, at_end=0): it = iter(iterable) for x in itertools.islice(it, at_start): pass queue = collections.deque(itertools.islice(it, at_end)) for x in it...
Python: Is it possible to only test specific functions with doctest in a module?
10,080,157
7
2012-04-09T21:31:02Z
10,081,450
9
2012-04-10T00:12:23Z
[ "python", "testing", "flags", "skip", "doctest" ]
I am trying to get into testing in python using the doctest module. At the moment I do 1. Write the tests for the functions. 2. implement the functions code. 3. If Tests pass, write more tests and more code. 4. When the function is done move on to the next function to implement. So after 3 or 4 (independent) function...
[looks like](http://docs.python.org/library/doctest.html#doctest.run_docstring_examples) you could pass the function to `run_docstring_examples`: ``` def f(a, b, c): ''' >>> f(1,2,3) 42 ''' if __name__ == '__main__': import doctest # doctest.testmod() doctest.run_docstring_examples(f, globa...
better way to iterate two , multiple lists at once
10,080,379
21
2012-04-09T21:55:06Z
10,080,389
56
2012-04-09T21:55:56Z
[ "python" ]
Let's say if I have two or more lists of same length: What's a good way to iterate through them like: a, b are lists ``` for i, ele in enumerate(a): print ele, b[i] ``` or ``` for i in range(len(a)): print a[i], b[i] ``` or is there any variant i am missing on? Is there any particular advantages of using ...
The usual way is to use [`zip()`](http://docs.python.org//library/functions.html#zip): ``` for x, y in zip(a, b): # x is from a, y is from b ``` This will stop when the shorter of the two iterables `a` and `b` is exhausted. Also worth noting: [`itertols.izip()`](http://docs.python.org//library/itertools.html#iter...
Python Regular Expressions: Capture lookahead value (capturing text without consuming it)
10,081,060
2
2012-04-09T23:16:19Z
10,081,138
8
2012-04-09T23:26:33Z
[ "python", "regex", "python-3.x", "lookaround" ]
I wish to use regular expressions to split words into groups of `(vowels, not_vowels, more_vowels)`, using a marker to ensure every word begins and ends with a vowel. ``` import re MARKER = "~" VOWELS = {"a", "e", "i", "o", "u", MARKER} word = "dog" if word[0] not in VOWELS: word = MARKER+word if word[-1] not ...
I found it just after posting: ``` re.findall("([%]+)([^%]+)(?=([%]+))".replace("%", "".join(VOWELS)), word) ``` Adding an extra pair of brackets inside the lookahead means that it becomes a capture itself. I found this pretty obscure and hard to find - I'm not sure if it's just everyone else found this obvious, but...
Twisted (Python) - what is the difference between cooperate and coiterate?
10,082,259
8
2012-04-10T02:10:50Z
10,083,618
9
2012-04-10T05:38:29Z
[ "python", "twisted" ]
The docs here <http://twistedmatrix.com/documents/current/api/twisted.internet.task.html#cooperate> suggest that the difference is that cooperate returns a CooperativeTask whereas coiterate returns a Deferred (evidenced by my own tests, not specified in docs). I've invested the weekend learning the basics of Twisted, s...
Almost, but not exactly. `cooperate` is a slightly newer API than `coiterate`. `cooperate` is generally just a slightly better version of `coiterate` and you pretty much always want to use it. Returning a `CooperativeTask` confers two benefits. First, you can [pause](http://twistedmatrix.com/documents/current/api/twist...
Trouble with a very simple regex
10,082,436
4
2012-04-10T02:33:59Z
10,082,459
8
2012-04-10T02:37:00Z
[ "python", "regex" ]
I am using python to try to write some simple code that looks through strings with regular expressions and finds things. In this string: ``` and the next nothing is 44827 ``` I want my regex to return just the numbers. I have set up my python program like this: ``` buf = "and the next nothing is 44827" number = re....
The problem is that `[0-9]*` matches zero or more digits, so it is more than happy to match to a zero-length string. Meanwhile, `[0-9]+` matches one or more digits, so it needs to see at least one number in order to catch. --- you might want to use [`findall`](http://docs.python.org/library/re.html#re.findall) and h...
Struct.Error, Must Be a Bytes Object?
10,082,623
5
2012-04-10T03:05:09Z
10,082,653
15
2012-04-10T03:09:16Z
[ "python", "python-3.x" ]
I am attempting to execute the code: ``` values = (1, 'ab', 2.7) s.struct.Struct('I 2s f') packed = s.pack(*values) ``` But I keep getting the error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> struct.error: argument for 's' must be a bytes object ``` Why...
With Python 3, `'ab'` isn't a `bytes` object, what was called a `str` on Python 2, it's `unicode`. You need to use: ``` values = (1, b'ab', 2.7) ``` which tells Python that `'ab'` is a byte literal. See [PEP 3112](http://www.python.org/dev/peps/pep-3112/) for more info.
Python ordinary dictionary to ordered dictionary conversion
10,083,188
2
2012-04-10T04:41:34Z
10,083,245
7
2012-04-10T04:51:33Z
[ "python", "python-2.7", "dictionary", "ordereddictionary" ]
I have python ordinary dictionary. In this, insertion order is not preserved. I need to keep elements in insertion order. I know that [`OrderedDict`](https://docs.python.org/2/library/collections.html#collections.OrderedDict) can do this job. but, my problem is i need to get an ordered dictionary from an already existi...
Short Answer: This is not possible, once you have created the dictionary it has no order. Items are stored according to their hash and not their insertion order, you need to have the `OrderedDict` created at the start so it can record insertion order as items are inserted.
Python PDF thumbnail preview generation
10,083,355
7
2012-04-10T05:08:10Z
10,781,469
9
2012-05-28T08:21:35Z
[ "python", "linux", "osx", "pdf-generation" ]
I am looking for ways to generate jpeg thumbnail of pdf files. I would like to do that in Python. Is there any library or can anyone guide me how to do it? Thanks I am working on MacOS X Lion. But I would like to run it on Ubuntu or CentOS.
You can use **ImageMagick** {apt-get install imagemagick on Ubuntu} (it also has Python lib **PythonMagick**) to convert pdf to images ``` import subprocess params = ['convert', 'pdf_file', 'thumb.jpg'] subprocess.check_call(params) ``` You can also provide parameters at which the image has to generate out of the pdf...
How do I remove a range (subsection) of a list in Python?
10,084,517
5
2012-04-10T07:08:00Z
10,084,563
7
2012-04-10T07:12:09Z
[ "python", "list" ]
I have a simple, always-consecutive-ordered list like this: ``` all = [ 1, 2, 3, 4, 5, 6 ] # same as range( 1, 7 ) ``` I also have `current = 4`. In the end I want the `all` list to look like this ``` altered = [ 1, 2, 5, 6 ] ``` So what happened was it removed the `current` number and *the one before it* `3`. `cu...
``` all = all[:max(current - 2, 0)] + all[current:] ``` or ``` del all[max(current - 2, 0):current] ```
slices to immutable strings by reference and not copy
10,085,568
8
2012-04-10T08:42:45Z
10,085,630
15
2012-04-10T08:46:54Z
[ "python" ]
If you use [*string*`.split()`](http://docs.python.org/library/stdtypes.html#str.split) on a Python string, it returns a list of strings. These substrings that have been split-out are copies of their part of the parent string. Is it possible to instead get some cheaper slice object that holds only a reference, offset ...
`buffer` will give you a read-only view on a string. ``` >>> s = 'abcdefghijklmnopqrstuvwxyz' >>> b = buffer(s, 2, 10) >>> b <read-only buffer for 0x7f935ee75d70, size 10, offset 2 at 0x7f935ee5a8f0> >>> b[:] 'cdefghijkl' ```
How to stop a python socket.accept() call?
10,090,236
5
2012-04-10T13:59:25Z
10,090,348
8
2012-04-10T14:07:10Z
[ "python", "sockets" ]
I am a newbie in python sockets and am really troubled by the stubbornness of the socket.accept() method. I really need a way of ending a socket.accept() method or any other alternative to socket.accept() which runs one time only. Plzzzz somebody help.
You have several options here: 1. Close the listening socket from another thread - the `accept()` will raise an exception if it fails. 2. Open a local connection to the listening socket - that makes the `accept()` return by design. 3. Use an accept mechanism that can block on more than one synchronization object so th...
Get parent class name in Python
10,091,957
18
2012-04-10T15:44:24Z
10,092,179
28
2012-04-10T15:57:47Z
[ "python", "oop" ]
``` class A(object): def get_class(self): return self.__class__ class B(A): def __init__(self): A.__init__(self) b = B() print b.get_class() ``` This code will print `<class '__main__.B'>`. How can I get the class name where the method has been defined (namely `A`)?
From the documentation: <https://docs.python.org/2/reference/datamodel.html#the-standard-type-hierarchy> Class objects have a `__name__` attribute. It might cleaner to introspect the base class(es) through the `__bases__` attr of the derived class (if the code is to live in the derived class for example). ``` >>> cla...
Get parent class name in Python
10,091,957
18
2012-04-10T15:44:24Z
10,092,497
17
2012-04-10T16:17:24Z
[ "python", "oop" ]
``` class A(object): def get_class(self): return self.__class__ class B(A): def __init__(self): A.__init__(self) b = B() print b.get_class() ``` This code will print `<class '__main__.B'>`. How can I get the class name where the method has been defined (namely `A`)?
> [`inspect.getmro(cls)`](https://docs.python.org/2/library/inspect.html#inspect.getmro) > > *Return a tuple of class cls’s base classes, > including cls, in method resolution order. No class appears more than > once in this tuple. Note that the method resolution order depends on > cls’s type. Unless a very peculia...
Is there a Python equivalent of range(n) for multidimensional ranges?
10,093,293
36
2012-04-10T17:15:34Z
10,093,338
22
2012-04-10T17:17:56Z
[ "python", "numpy", "iteration", "range" ]
On Python, range(3) will return [0,1,2]. Is there an equivalent for multidimensional ranges? ``` range((3,2)) # [(0,0),(0,1),(1,0),(1,1),(2,0),(2,1)] ``` So, for example, looping though the tiles of a rectangular area on a tile-based game could be written as: ``` for x,y in range((3,2)): ``` Note I'm not asking for...
There actually is a simple syntax for this. You just need to have two `for`s: ``` >>> [(x,y) for x in range(3) for y in range(2)] [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)] ```
Is there a Python equivalent of range(n) for multidimensional ranges?
10,093,293
36
2012-04-10T17:15:34Z
10,093,342
33
2012-04-10T17:18:08Z
[ "python", "numpy", "iteration", "range" ]
On Python, range(3) will return [0,1,2]. Is there an equivalent for multidimensional ranges? ``` range((3,2)) # [(0,0),(0,1),(1,0),(1,1),(2,0),(2,1)] ``` So, for example, looping though the tiles of a rectangular area on a tile-based game could be written as: ``` for x,y in range((3,2)): ``` Note I'm not asking for...
You could use `itertools.product()`: ``` >>> import itertools >>> for (i,j,k) in itertools.product(xrange(3),xrange(3),xrange(3)): ... print i,j,k ``` The multiple repeated `xrange()` statements could be expressed like so, if you want to scale this up to a ten-dimensional loop or something similarly ridiculous: ...
Is there a Python equivalent of range(n) for multidimensional ranges?
10,093,293
36
2012-04-10T17:15:34Z
10,098,162
44
2012-04-11T00:03:12Z
[ "python", "numpy", "iteration", "range" ]
On Python, range(3) will return [0,1,2]. Is there an equivalent for multidimensional ranges? ``` range((3,2)) # [(0,0),(0,1),(1,0),(1,1),(2,0),(2,1)] ``` So, for example, looping though the tiles of a rectangular area on a tile-based game could be written as: ``` for x,y in range((3,2)): ``` Note I'm not asking for...
In numpy, it's [`numpy.ndindex`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndindex.html). Also have a look at [`numpy.ndenumerate`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndenumerate.html). E.g. ``` import numpy as np for x, y in np.ndindex((3,2)): print x, y ``` This yields: ...
Eclipse bad indentation warning
10,093,519
8
2012-04-10T17:28:32Z
10,098,212
13
2012-04-11T00:11:48Z
[ "python", "eclipse", "warnings" ]
I am using PyDev perspective. I get a "bad indentation" warning in python files. I am using two spaces for indent and eclipse seems to want me to use 4. How to set the indentation I want so this warning goes away?
You have to change the tab length that PyDev uses at: window > preferences > pydev > editor > tab length
Rounding error in Python with non-odd number?
10,093,783
7
2012-04-10T17:46:51Z
10,093,820
19
2012-04-10T17:50:04Z
[ "python", "python-3.x", "rounding" ]
I'm beginner in Python, and I have one question. Why does rounding a number like 5.5, 7.5, (anything).5 with odd integer part applying `round(num)` work correctly (rule 5/4), but rounding number like (anything).5 with non-odd integer part by the same function returns just an integer part? (But if we add a little numb...
Python 3.x, in contrast to Python 2.x, uses [Banker's rounding](http://en.wikipedia.org/wiki/Banker%27s_rounding) for the `round()` function. This is the [documented](http://docs.python.org/dev/library/functions.html#round) behaviour: > [I]f two multiples are equally close, rounding is done toward the even choice (so...
How to bind a text domain to a local folder for gettext under GTK3
10,094,335
10
2012-04-10T18:27:27Z
10,540,744
9
2012-05-10T19:17:18Z
[ "python", "translation", "gettext", "gtk3", "pygobject" ]
With `gettext` you can either use the default system-wide locale directory, or specify one yourself using `bindtextdomain`. This is useful when running a program directly from source when the compiled .mo translation files are not available in the system's default location. In Python you would do this: ``` import get...
In PyGtk you can use Gtk.Builder too. Accordingly to the PyGtk Gtk.Builder documentation: <http://developer.gnome.org/pygtk/stable/class-gtkbuilder.html#properties-gtkbuilder> > The translation domain used when translating property values that have > been marked as translatable in interface descriptions. If the > tra...
Why use sys.path.append(path) instead of sys.path.insert(1, path)?
10,095,037
50
2012-04-10T19:19:12Z
10,095,099
30
2012-04-10T19:23:47Z
[ "python", "path", "pythonpath" ]
**Edit:** based on a Ulf Rompe's comment, **it is important you use "1" instead of "0"**, otherwise you will break [sys.path](http://docs.python.org/library/sys.html#sys.path). I have been doing python for quite a while now (over a year), and I am always confused as to why people recommend you use `sys.path.append()` ...
If you have multiple versions of a package / module, you need to be using [virtualenv](http://www.virtualenv.org/en/latest/index.html) (emphasis mine): > `virtualenv` is a tool to create isolated Python environments. > > The basic problem being addressed is one of dependencies and versions, and indirectly permissions....
Why use sys.path.append(path) instead of sys.path.insert(1, path)?
10,095,037
50
2012-04-10T19:19:12Z
10,097,543
29
2012-04-10T22:47:18Z
[ "python", "path", "pythonpath" ]
**Edit:** based on a Ulf Rompe's comment, **it is important you use "1" instead of "0"**, otherwise you will break [sys.path](http://docs.python.org/library/sys.html#sys.path). I have been doing python for quite a while now (over a year), and I am always confused as to why people recommend you use `sys.path.append()` ...
If you really need to use sys.path.insert, consider leaving sys.path[0] as it is: ``` sys.path.insert(1, path_to_dev_pyworkbooks) ``` This could be important since 3rd party code may rely on [sys.path documentation](http://docs.python.org/library/sys.html#sys.path%20documentation) conformance: > As initialized upon ...
Why use sys.path.append(path) instead of sys.path.insert(1, path)?
10,095,037
50
2012-04-10T19:19:12Z
11,179,881
8
2012-06-24T18:01:20Z
[ "python", "path", "pythonpath" ]
**Edit:** based on a Ulf Rompe's comment, **it is important you use "1" instead of "0"**, otherwise you will break [sys.path](http://docs.python.org/library/sys.html#sys.path). I have been doing python for quite a while now (over a year), and I am always confused as to why people recommend you use `sys.path.append()` ...
you are confusing the concept of appending and prepending. the following code is prepending: ``` sys.path.insert(1,'/thePathToYourFolder/') ``` it places the new information at the beginning (well, second, to be precise) of the search sequence that your interpreter will go through. `sys.path.append()` puts things at ...
Securing data in the google app engine datastore
10,096,268
17
2012-04-10T20:50:25Z
10,098,781
11
2012-04-11T01:38:22Z
[ "python", "security", "google-app-engine", "rsa", "sha" ]
Our google app engine app stores a fair amount of personally identifying information (email, ssn, etc) to identify users. I'm looking for advice as to how to secure that data. ## My current strategy **Store the sensitive data in two forms:** * Hashed - using SHA-2 and a salt * Encrypted - using public/private key RS...
When deciding on a security architecture, the first thing in your mind should always be threat models. Who are your potential attackers, what are their capabilities, and how can you defend against them? Without a clear idea of your threat model, you've got no way to assess whether or not your proposed security measures...
Call and receive output from Python script in Java?
10,097,491
11
2012-04-10T22:40:51Z
10,097,556
17
2012-04-10T22:48:11Z
[ "java", "python" ]
What's the easiest way to execute a Python script from Java, and receive the output of that script? I've looked for different libraries like Jepp or Jython, but most appear out of date. Another problem with the libraries is that I need to be able to easily include a library with the source code (though I don't need to ...
Not sure if I understand your question correctly, but provided that you can call the Python executable from the console and just want to capture its output in Java, you can use the `exec()` method in the Java `Runtime` class. ``` Process p = Runtime.getRuntime().exec("python yourapp.py"); ``` You can read up on how t...
Call and receive output from Python script in Java?
10,097,491
11
2012-04-10T22:40:51Z
10,097,910
13
2012-04-10T23:29:01Z
[ "java", "python" ]
What's the easiest way to execute a Python script from Java, and receive the output of that script? I've looked for different libraries like Jepp or Jython, but most appear out of date. Another problem with the libraries is that I need to be able to easily include a library with the source code (though I don't need to ...
You can include the [Jython](http://www.jython.org/downloads.html) library in your Java Project. You can [download the source code](http://sourceforge.net/scm/?type=svn&group_id=12867) from the Jython project itself. Jython does offers support for [JSR-223](http://jcp.org/aboutJava/communityprocess/final/jsr223/index....
Unable to install pymssql
10,098,507
9
2012-04-11T00:56:23Z
10,099,357
13
2012-04-11T03:22:05Z
[ "python", "osx" ]
I was trying to install pymssql .For this I use pip and installed it using a virtual environment according to instructions mentioned [here](http://www.pip-installer.org/en/latest/installing.html#using-the-installer) But when I say (my\_new\_env)tmp> pip install pymssql I see the following errors : > Downloading pyms...
You need to install Cython. It is available on PyPi so you may be able to do: ``` pip install cython ``` That may not work on windows (I really don't know), but if it doesn't check out this page: <http://cython.org/#download> On that page you will see a link to windows installers. Pick the right one and you should b...
Implementing Bag-of-Words Naive-Bayes classifier in NLTK
10,098,533
20
2012-04-11T01:00:00Z
10,098,909
29
2012-04-11T02:00:03Z
[ "python", "nlp", "machine-learning", "nltk", "bayesian" ]
I basically have the [same question as this guy](http://stackoverflow.com/questions/2162718/python-nltk-code-snippet-to-train-a-classifier-naive-bayes-using-feature-frequ).. The [example in the NLTK book](http://nltk.googlecode.com/svn/trunk/doc/book/ch06.html#document-classify-all-words) for the Naive Bayes classifier...
[scikit-learn](http://scikit-learn.org) has [an implementation of multinomial naive Bayes](http://scikit-learn.org/stable/modules/naive_bayes.html#multinomial-naive-bayes), which is the right variant of naive Bayes in this situation. A support vector machine (SVM) would probably work better, though. As Ken pointed out...
Django render template within a template
10,098,668
6
2012-04-11T01:21:20Z
10,098,767
11
2012-04-11T01:36:04Z
[ "python", "django" ]
I want to create a template for a component that is used many times on a single page, with very few changes (simply 2 or 3 variables). How can I create this template and render it within another template?
How about [include](https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#include)? Like so: ``` {% include "name_snippet.html" with person="Jane" greeting="Hello" %} ```
Powershell equivalent to Python "in"?
10,098,684
4
2012-04-11T01:22:59Z
10,098,749
8
2012-04-11T01:32:20Z
[ "python", "arrays", "powershell", "syntax" ]
I've been using arrays lately and really missing Python's "in" operator. e.g.: ``` if ("hello" in ["hello", "there", "sup"]): print "this prints :)" ``` I've made up for it a little bit by creating a "ThereExists-Object" function, like so: ``` function ThereExists-Object([System.Management.Automation.ScriptBloc...
``` $arrColors = "blue", "red", "green", "yellow", "white", "pink", "orange", "turquoise" $arrColors -contains "black" False $arrColors -contains "blue" True ``` source: <http://technet.microsoft.com/en-us/library/ee692798.aspx>
ImportError: cannot import name Counter
10,099,013
14
2012-04-11T02:19:07Z
12,588,953
24
2012-09-25T18:26:50Z
[ "python" ]
I have tried using Counter() but everytime I do: ``` from collections import Counter ``` I get an error saying: ``` Traceback (most recent call last): File "<web session>", line 1, in <module> ImportError: cannot import name Counter ``` Do I actually have to make a file that has counter in it and then import it f...
Counter is only supported python2.7 and higher and is not available in earlier versions.
How does Python's unittest module detect test cases?
10,099,491
16
2012-04-11T03:40:36Z
10,099,813
7
2012-04-11T04:29:03Z
[ "python", "unit-testing" ]
I was wondering when we run `unittest.main()`, how does Python know what subclasses `unittest.Testcase` has? For example, if I add a class `FromRomanBadInput(unittest.TestCase)`, how does `unittest` know to run this?
the 'main' function searches for all classes which inherits the unittest.TestCase in imported modules. and current path, then tries to run each method that starts with 'test' from [python's document](http://docs.python.org/library/unittest.html): ``` import random import unittest class TestSequenceFunctions(unittest...
How does Python's unittest module detect test cases?
10,099,491
16
2012-04-11T03:40:36Z
10,100,114
26
2012-04-11T05:07:22Z
[ "python", "unit-testing" ]
I was wondering when we run `unittest.main()`, how does Python know what subclasses `unittest.Testcase` has? For example, if I add a class `FromRomanBadInput(unittest.TestCase)`, how does `unittest` know to run this?
So I looked around in my `Python27/Lib` directory... `unittest.main` is actually an alias for a class, `unittest.TestProgram`. So what happens is you construct an instance of this, and its `__init__` runs, which does a bunch of sanity checks and configuration, including a dynamic import of the module that you called i...
Fabric asks for password even though I can SSH using credential
10,101,127
7
2012-04-11T06:41:53Z
10,101,466
17
2012-04-11T07:10:52Z
[ "python", "django", "ssh", "fabric" ]
I'm having an odd problem while deploying a Django site using Fabric. I've configured two servers to use key files for login. I can SSH into both without a password. I can run fab on one correctly, ``` $ fab live pull [mysite.com] Executing task 'pull' [mysite.com] run: test -d proj [mysite.com] run: test -d proj/.git...
You can add: ``` ssh.util.log_to_file("paramiko.log", 10) ``` To the top of your fabfile, after the imports, to get more detailed information about the authorization process.
Matplotlib legend, add items across columns instead of down
10,101,141
16
2012-04-11T06:43:30Z
10,101,532
16
2012-04-11T07:17:07Z
[ "python", "matplotlib", "legend" ]
For a simple plot below, is there a way to make matplotlib populate the legend so that it fills the rows left to right, instead of first column then second column? ``` >>> from pylab import * >>> x = arange(-2*pi, 2*pi, 0.1) >>> plot(x, sin(x), label='Sine') >>> plot(x, cos(x), label='Cosine') >>> plot(x, arctan(x), l...
I can think of one possible way. You can [order your legend items](http://matplotlib.sourceforge.net/users/legend_guide.html#adjusting-the-order-of-legend-items) as you like. All you need to do is to switch the order so that it will give you the result you want. ``` import matplotlib.pyplot as plt import numpy as np i...
How to know current name of the database in Django?
10,101,602
9
2012-04-11T07:24:50Z
18,343,919
10
2013-08-20T19:54:57Z
[ "python", "django", "unit-testing" ]
I'm writing tests in my django project. For now, I have two database connections: ``` (settings.py) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db_name' ... }, } ``` and custom connection to MongoDB: ``` import sys from pymongo import Connec...
You can check it in `db.settings`: ``` from django import db db.settings.DATABASES['default']['NAME'] ``` To see the database used to fetch a specific object you can do: ``` object._state.db ``` This will give you the database key in config, such as 'default', so if you have multiple databases in config you can che...
Moving matplotlib legend outside of the axis makes it cutoff by the figure box
10,101,700
87
2012-04-11T07:32:08Z
10,136,347
10
2012-04-13T06:42:13Z
[ "python", "matplotlib", "legend" ]
I'm familiar with the following questions: [Matplotlib savefig with a legend outside the plot](http://stackoverflow.com/questions/8971834/matplotlib-savefig-with-a-legend-outside-the-plot) [How to put the legend out of the plot](http://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot) It see...
**Added:** I found something that should do the trick right away, but the rest of the code below also offers an alternative. Use the `subplots_adjust()` function to move the bottom of the subplot up: ``` fig.subplots_adjust(bottom=0.2) # <-- Change the 0.02 to work for your plot. ``` Then play with the offset in the...
Moving matplotlib legend outside of the axis makes it cutoff by the figure box
10,101,700
87
2012-04-11T07:32:08Z
10,154,763
117
2012-04-14T15:26:20Z
[ "python", "matplotlib", "legend" ]
I'm familiar with the following questions: [Matplotlib savefig with a legend outside the plot](http://stackoverflow.com/questions/8971834/matplotlib-savefig-with-a-legend-outside-the-plot) [How to put the legend out of the plot](http://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot) It see...
Sorry EMS, but I actually just got another response from the matplotlib mailling list (Thanks goes out to Benjamin Root). The code I am looking for is adjusting the savefig call to: ``` fig.savefig('samplefigure', bbox_extra_artists=(lgd,), bbox_inches='tight') #Note that the bbox_extra_artists must be an iterable ``...
Moving matplotlib legend outside of the axis makes it cutoff by the figure box
10,101,700
87
2012-04-11T07:32:08Z
15,873,174
10
2013-04-08T07:06:30Z
[ "python", "matplotlib", "legend" ]
I'm familiar with the following questions: [Matplotlib savefig with a legend outside the plot](http://stackoverflow.com/questions/8971834/matplotlib-savefig-with-a-legend-outside-the-plot) [How to put the legend out of the plot](http://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot) It see...
Here is another, very manual solution. You can define the size of the axis and paddings are considered accordingly (including legend and tickmarks). Hope it is of use to somebody. Example (axes size are the same!): ![enter image description here](http://i.stack.imgur.com/P9LNA.png) Code: ``` #======================...
Python - Sum not working in list comprehension syntax if the source is file
10,103,107
2
2012-04-11T09:17:17Z
10,103,182
7
2012-04-11T09:22:42Z
[ "python", "sum", "list-comprehension" ]
I'm a newbie in Python and I'm studying list comprehension. What I'm trying to do is to convert the following code into list comprehension: ``` def words_without_e(): count = 0 words = open('words.txt') for word in words: if word.find('e') == -1: count += 1 words.close() retu...
The simplest solution is this: ``` with open("words.txt") as words: sum(1 for word in words if "e" not in word) ``` As you can see, `sum` does work with any iterator - here I am using a generator expression. Rather than doing `word.find('e') == -1` we can just do `"e" not in word` which is nicer to read and works ...
passing data to subprocess.check_output
10,103,551
19
2012-04-11T09:48:36Z
10,103,704
24
2012-04-11T09:58:08Z
[ "python" ]
I want to invoke a script, piping the contents of a string to its stdin and retrieving its stdout. I don't want to touch the real filesystem so I can't create real temporary files for it. using `subprocess.check_output` I can get whatever the script writes; how can I get the input string into its stdin though? ``` s...
Use `Popen.communicate` instead of `subprocess.check_output`. ``` from subprocess import Popen, PIPE p = Popen([script_name, "-"], stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate("this is some input") ```
passing data to subprocess.check_output
10,103,551
19
2012-04-11T09:48:36Z
25,541,642
11
2014-08-28T05:54:25Z
[ "python" ]
I want to invoke a script, piping the contents of a string to its stdin and retrieving its stdout. I don't want to touch the real filesystem so I can't create real temporary files for it. using `subprocess.check_output` I can get whatever the script writes; how can I get the input string into its stdin though? ``` s...
In Python 3.4 and newer, you can use the *input* keyword parameter to send input via STDIN when using `subprocess.check_output()` Quoting from [the standard library documentation for `subprocess.check_output()`](https://docs.python.org/3.4/library/subprocess.html#subprocess.check_output): > The *input* argument is pa...
Combining an array using Python and NumPy
10,104,245
2
2012-04-11T10:33:06Z
10,104,312
7
2012-04-11T10:37:24Z
[ "python", "arrays", "numpy" ]
I have two arrays of the form: ``` a = np.array([1,2,3]) b = np.array([4,5,6]) ``` Is there a NumPy function which I can apply to these arrays to get the followng output? ``` [[1,4],[2,5][3,6]] ```
``` np.vstack((a,b)).T ``` returns ``` array([[1, 4], [2, 5], [3, 6]]) ``` and ``` np.vstack((a,b)).T.tolist() ``` returns exactly what you need: ``` [[1, 4], [2, 5], [3, 6]] ```
Python 2to3 windows CMD
10,104,805
13
2012-04-11T11:15:02Z
10,104,869
21
2012-04-11T11:19:18Z
[ "python" ]
I have installed python 32 package to the > C:\python32 I have also set the paths: > PYTHONPATH | C:\Python32\Lib;C:\Python32\DLLs;C:\Python32\Lib\lib-tk; > > PATH ;C:\Python32; I would like to use the "2to3" tool, but CMD does not recognize it. ``` CMD: c:\test\python> 2to3 test.py ``` Should i add an extra path...
2to3 is actually a Python script found in the Tools/scripts folder of your Python install. So you should run it like this: ``` python.exe C:\Python32\Tools\scripts\2to3.py your-script-here.py ``` See this for more details: <http://docs.python.org/library/2to3.html>
member or class variables in python
10,106,430
3
2012-04-11T13:02:07Z
10,106,527
12
2012-04-11T13:08:23Z
[ "python", "variables" ]
I come from Java, so I'm getting confused here. ``` class Sample(object): x = 100 # class var? def __init__(self, value): self.y = value # instance var? z = 300 # private var? how do we access this outside Sample? ``` What is the difference between ...
``` class Sample(object): x = 100 _a = 1 __b = 11 def __init__(self, value): self.y = value self._c = 'private' self.__d = 'more private' z = 300 ``` In this example: * `x` is class variable, * `_a` is private class variable (by naming con...
Trouble with map()
10,106,842
5
2012-04-11T13:25:31Z
10,106,900
9
2012-04-11T13:28:25Z
[ "python" ]
I'm trying to convert the values of a list using the `map` function but i am getting a strange result. ``` s = input("input some numbers: ") i = map(int, s.split()) print(i) ``` gives: ``` input some numbers: 4 58 6 <map object at 0x00000000031AE7B8> ``` why does it not return ['4','58','6']?
You are using python 3 which returns generators instead of lists. Call `list(x)` on the variable after you assign it the map generator.
elegant find sub-list in list
10,106,901
14
2012-04-11T13:28:26Z
12,576,755
21
2012-09-25T05:37:35Z
[ "python", "list", "design-patterns" ]
Given a list containing a known pattern surrounded by noise, is there an elegant way to get all items that equal the pattern. See below for my crude code. ``` list_with_noise = [7,2,1,2,3,4,2,1,2,3,4,9,9,1,2,3,4,7,4,3,1,2,3,5] known_pattern = [1,2,3,4] res = [] for i in list_with_noise: for j in known_pattern: ...
I know this question is 5 months old and already "accepted", but googling a very similar problem brought me to this question and all the answers seem to have a couple of rather significant problems, plus I'm bored and want to try my hand at a SO answer, so I'm just going to rattle off what I've found. The first part o...