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
Access environment variables from Python
4,906,977
625
2011-02-05T13:03:35Z
11,447,648
68
2012-07-12T08:14:31Z
[ "python", "environment-variables" ]
I set an environment variable that I want to access in my Python application. How do I get this value?
To check if the key exists (returns True/False) ``` "HOME" in os.environ ``` or (removed from python 3.x) ``` os.environ.has_key("HOME") ``` You can also use get when printing the key, useful if you want to use a default. ( for python 2.7.3 ) ``` print os.environ.get('HOME','/home/username/') ``` where /home/user...
All possible variants of zip in Python
4,907,263
13
2011-02-05T14:09:09Z
4,907,278
23
2011-02-05T14:10:37Z
[ "python", "list" ]
For example, I have a code looks like this: ``` a = [1, 2] b = [4, 5] ``` How can I get something like this: ``` [(1,4), (1,5), (2,4), (2,5)] ``` Like function `zip` does, but with all possible variants. Or can't I?
You want itertools.product: ``` >>> import itertools >>> a = [1,2] >>> b = [4,5] >>> list(itertools.product(a,b)) [(1, 4), (1, 5), (2, 4), (2, 5)] ```
Python - write list list of lists in columns
4,908,987
6
2011-02-05T19:08:21Z
4,909,015
14
2011-02-05T19:11:25Z
[ "python", "list", "csv" ]
I have a list of lists with a various number of elements (int). I want to print/write it, but in columns rather than in rows. Example: ``` l = [[1,2,3],[4,5],[6,7,8,9],[0]] ``` Result: ``` 1 4 6 0 2 5 7 . 3 . 8 . . . 9 . ```
The easiest way to do this is to use `itertools.izip_longest()`: ``` for x in itertools.izip_longest(*l, fillvalue="."): print " ".join(str(i) for i in x) ```
Google App Engine - Use Task Queues or Deferred Jobs
4,909,278
4
2011-02-05T19:51:46Z
4,909,400
9
2011-02-05T20:16:52Z
[ "python", "google-app-engine" ]
Google App Engine has two methods for running jobs at some later point, [Task Queues](http://code.google.com/appengine/docs/python/taskqueue/overview.html) and [Deferred jops](http://code.google.com/appengine/articles/deferred.html) They support all the same features as far as I can tell (e.g. a deferred job can be pl...
I'm not sure if you noticed it, but the documentation for deferreds has this section in the end: > You may be wondering when to use ext.deferred, and when to stick with the built-in task queue API. Here are our suggestions. > > You may want to use the deferred library if: > > * You only use the task queue lightly. > *...
why am i getting a python indent error here in the django sample tutorial
4,909,302
5
2011-02-05T19:56:56Z
4,909,313
12
2011-02-05T19:59:28Z
[ "python", "django", "indentation" ]
i have this code from t[he django sample tutorial](http://docs.djangoproject.com/en/dev/intro/tutorial01/) ``` from django.db import models from datetime import datetime # Create your models here. class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date publ...
My only guess is you have tabs mixed with spaces. It's recommended to use spaces over tabs, with 4 spaces per indentation. <http://www.python.org/dev/peps/pep-0008/> Do you have invisible characters visible on your editor to make sure that isn't the case? *PS: your reputation graph says -6000 and it's really bugging...
python - djangjo: why am i getting this error: AttributeError: 'method_descriptor' object has no attribute 'today'?
4,909,577
13
2011-02-05T20:52:42Z
4,909,596
21
2011-02-05T20:56:31Z
[ "python", "django" ]
I have the following python code: ``` from django.db import models from datetime import datetime class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __unicode__(self): return self.question def was_published_today(self): ...
You probably want "import datetime", not "from datetime import datetime". "date" is a class on the datetime module, but it is also a method on the "datetime.datetime" class.
Interesting 'takes exactly 1 argument (2 given)' Python error
4,909,585
41
2011-02-05T20:54:19Z
4,909,591
61
2011-02-05T20:55:29Z
[ "python" ]
For the error: ``` TypeError: takes exactly 1 argument (2 given) ``` With the following class method: ``` def extractAll(tag): ... ``` and calling it: ``` e.extractAll("th") ``` The error seems very odd when I'm giving it 1 argument, the method should take only 1 argument, but it's saying I'm not giving it 1 a...
The call ``` e.extractAll("th") ``` for a regular method `extractAll()` is indeed equivalent to ``` Extractor.extractAll(e, "th") ``` These two calls are treated the same in all regards, including the error messages you get. If you don't need to pass the instance to a method, you *can* use a `staticmethod`: ``` @...
Interesting 'takes exactly 1 argument (2 given)' Python error
4,909,585
41
2011-02-05T20:54:19Z
4,909,609
8
2011-02-05T20:58:49Z
[ "python" ]
For the error: ``` TypeError: takes exactly 1 argument (2 given) ``` With the following class method: ``` def extractAll(tag): ... ``` and calling it: ``` e.extractAll("th") ``` The error seems very odd when I'm giving it 1 argument, the method should take only 1 argument, but it's saying I'm not giving it 1 a...
> Am I getting it because the act of calling it via e.extractAll("th") also passes in self as an argument? Yes, that's precisely it. If you like, the first parameter is the object name, `e` that you are calling it with. > And if so, by removing the self in the call, would I be making it some kind of class method that...
Interesting 'takes exactly 1 argument (2 given)' Python error
4,909,585
41
2011-02-05T20:54:19Z
7,097,353
16
2011-08-17T18:04:10Z
[ "python" ]
For the error: ``` TypeError: takes exactly 1 argument (2 given) ``` With the following class method: ``` def extractAll(tag): ... ``` and calling it: ``` e.extractAll("th") ``` The error seems very odd when I'm giving it 1 argument, the method should take only 1 argument, but it's saying I'm not giving it 1 a...
If a non-static method is member of a class, you have to define it like that: ``` def Method(self, atributes..) ``` So, I suppose your 'e' is instance of some class with implemented method that tries to execute and has too much arguments.
Why my regex with r'string' matches but not 'string' using Python?
4,909,691
9
2011-02-05T21:14:06Z
4,909,735
14
2011-02-05T21:20:21Z
[ "python", "regex" ]
The way regex works in Python is so intensely puzzling that it makes me more furious with each passing second. Here's my problem: I understand that this gives a result: ``` re.search(r'\bmi\b', 'grand rapids, mi 49505) ``` while this doesn't: ``` re.search('\bmi\b', 'grand rapids, mi 49505) ``` And that's okay. I ...
**The anwser itself** ``` regex = '|'.join([r'\b' + str(state) + r'\b' for state in states]) ``` The reason behind this is that the 'r' prefix tells Python to not analyze the string you pass to it. If you don't put an 'r' before the string, Python will try to turn any char preceding by '\' into a special char, to all...
Django Local Settings
4,909,958
53
2011-02-05T21:58:36Z
4,909,964
91
2011-02-05T22:00:32Z
[ "python", "django", "settings" ]
I'm trying to use local\_setting in *Django 1.2*, but it's not working for me. At the moment I'm just adding **local\_settings.py** to my project. **settings.py** ``` DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'....
You can't just add local\_settings.py, you have to explicity import it. At the *very end* of your settings.py, add this: ``` try: from local_settings import * except ImportError: pass ``` The try/except block is there so that Python just ignores the case when you haven't actually defined a local\_settings fi...
Django Local Settings
4,909,958
53
2011-02-05T21:58:36Z
14,545,196
54
2013-01-27T06:58:49Z
[ "python", "django", "settings" ]
I'm trying to use local\_setting in *Django 1.2*, but it's not working for me. At the moment I'm just adding **local\_settings.py** to my project. **settings.py** ``` DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'....
This is the best practice I think: * `local_settings` imports from `settings` * `local_settings` overrides settings specific to the local environment, especially `DATABASES`, `SECRET_KEY`, `ALLOWED_HOSTS` and `DEBUG` variables * pass to django management commands the flag `--settings=local_settings` You could impleme...
Django Local Settings
4,909,958
53
2011-02-05T21:58:36Z
18,731,139
7
2013-09-11T01:05:57Z
[ "python", "django", "settings" ]
I'm trying to use local\_setting in *Django 1.2*, but it's not working for me. At the moment I'm just adding **local\_settings.py** to my project. **settings.py** ``` DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'....
Since the topic resurfaces routinely let me summarise why you might want to consider this approach: * a dumb settings file is very fast and easy to change; especially in a production environment. No python required: any idiot can jump in and change the database password in a file which just lists names and values; esp...
Matrix multiplication gives unsual result in Python (SciPy/PyLab)
4,910,453
5
2011-02-05T23:38:17Z
4,910,514
8
2011-02-05T23:49:01Z
[ "python", "matrix", "numpy", "scipy", "linear-algebra" ]
I'm new to Python, and a bit rusty with my linear algebra, so perhaps this is a simple question. I'm trying to implement a Taylor Series expansion on a Matrix to compute exp(A), where A is just a simple 3x3 matrix. The formula, BTW for this expansion is sum( A^n / n! ). My routine works alright up to n=9, but at n=10,...
Your matrix is created with elements of type `int32` (32-bit integer). You can see this by printing the value of `A.dtype`. 32-bit integers can only hold values up to about 2 billion, so after that they will wrap around to negative values. If 64-bit integers are large enough, you can use them instead: ``` A = mat('[1...
Comparing/Clustering Trajectories (GPS data of (x,y) points) and Mining the data
4,910,510
6
2011-02-05T23:48:16Z
4,916,634
8
2011-02-06T22:27:24Z
[ "python", "algorithm", "gps", "gis", "data-mining" ]
I've got 2 questions on analyzing a GPS dataset. **1) Extracting trajectories** I have a huge database of recorded GPS coordinates of the form `(latitude, longitude, date-time)`. According to date-time values of consecutive records, I'm trying to extract all trajectories/paths followed by the person. For instance; say...
Have a look at work done at Geography Department of University of Zurich, especially by [Patrick Laube](http://www.geo.unizh.ch/~plaube/#publications) and [Somayeh Dodge](http://www.geo.unizh.ch/~sdodge/). Have a look at the paper > Individual Movements and Geographical Data Mining. Clustering > Algorithms for Highli...
Getting the row index for a 2D numPy array when multiple column values are known
4,910,789
8
2011-02-06T00:54:48Z
4,910,861
8
2011-02-06T01:09:35Z
[ "python", "numpy" ]
Suppose I have a 2D numPy array such as: > a = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] How to I find the index of the row for which I know multiple values? For example, if it is known that the 0th column is 2 and the 1st column is 5, I would like to know the row index where this condition is met (row 1 in this case). In...
``` In [80]: a = np.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]) In [81]: a Out[81]: array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) ``` `a==2` returns a boolean numpy array, showing where the condition is True: ``` In [82]: a==2 Out[82]: array([[False, True, False], [False, False, False], [Fals...
Pyramid of asterisks program in Python
4,911,341
4
2011-02-06T03:24:29Z
4,911,427
19
2011-02-06T03:45:22Z
[ "python" ]
I've written a program in C++ that displays a pyramid of asterisk (see below) and now I'd like to see how it's done in Python but it's not as easy as I'd thought it would be. :) Has anyone tried this and if so could you show me code that would help out? thanks, j ``` * *** ***** ******* *****...
``` def pyramid(rows=8): for i in range(rows): print ' '*(rows-i-1) + '*'*(2*i+1) pyramid(8) * *** ***** ******* ********* *********** ************* *************** pyramid(12) * *** ***** ******* ********* *********** ***...
In Python's sqlite3 module, why can't cursor.rowcount() tell me the number of rows returned by a select statement
4,911,404
2
2011-02-06T03:41:53Z
4,911,430
9
2011-02-06T03:46:47Z
[ "python", "sql", "sqlite", "sqlite3" ]
So I've read [the documentation](http://docs.python.org/library/sqlite3.html#sqlite3.Cursor.rowcount) and it says: > Cursor.rowcount¶ > > Although the Cursor class of the > sqlite3 module implements this > attribute, the database engine’s own > support for the determination of “rows > affected”/”rows selected...
SQLite does not "fetch" all the rows when initially processing the query. It returns a single row each time the prepared query is stepped. From the SQLite3 FAQ [here](http://www.sqlite.org/cvstrac/wiki?p=SqliteWikiFaq) Q) Which func could get the number of rows? A) There is no function to retrieve the number of rows...
Why would os.path.exists("C:\\windows\\system32\\inetsrv\\metaback") return False even when it exists?
4,911,555
9
2011-02-06T04:20:22Z
4,911,624
26
2011-02-06T04:38:04Z
[ "python", "windows", "wow64" ]
I've got a python program which is supposed to clean up a number of directories and one of them is `C:\windows\system32\inetsrv\metaback`; however, `os.path.exists()` returns False on that directory even though it exists (and I have permissions to access it). What's interesting also is that the tool [windirstat](http:...
This is redirection of system folders at work. [When a 32-bit process is running on a 64-bit version of Windows and uses the path `%WINDIR%\System32`, Windows substitutes `%WINDIR%\SysWow64`.](http://msdn.microsoft.com/en-us/library/aa384187.aspx) The function is returning false to tell you that `C:\windows\syswow64\i...
Configuring App Engine path for PyDev on Mac
4,911,823
10
2011-02-06T05:42:00Z
4,911,855
23
2011-02-06T05:49:10Z
[ "python", "eclipse", "google-app-engine", "pydev" ]
I've just installed Eclipse and the Pydev plug-in on my Mac (OS X 10.6.6) and I'm having trouble using the Google App Engine project 'template'. I'm really stuck here so your help would be really appreciated. I can get as far as adding a New Project > Pydev > Pydev Google App Engine Project and setup the project name,...
Put `/usr/local/google_appengine` as the path to ${GOOGLE\_APP\_ENGINE} and Eclipse will resolve that symlink to `/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine`. You should be able to see the /usr folder under Eclipse, which you normally...
Django ManyToManyField
4,912,223
3
2011-02-06T07:47:10Z
4,912,261
10
2011-02-06T08:01:43Z
[ "python", "django" ]
In my model I have: ``` class Poll(models.Model): topic = models.CharField(max_length=200) tags = models.ManyToManyField(Tag) ``` I'm trying to create the Poll object and store tags like so: ``` Tags = [] for splitTag in splitTags: tag = Tag(name = splitTag.lower()) tag.save() Tags.append(tag) ``...
Well, it should be more like this: ``` models.py class Tag(models.Model): name = models.CharField(max_length=200) class Poll(models.Model): topic = models.CharField(max_length=200) tags = models.ManyToManyField(Tag) in views.py: poll = Poll(topic="My topic") poll.save() for splitTag in splitTags: t...
Using Python descriptors with slots
4,912,499
7
2011-02-06T09:15:13Z
4,912,599
9
2011-02-06T09:51:32Z
[ "python", "descriptor", "slots" ]
I want to be able use python descriptors in a class which has the slots optimization: ``` class C(object): __slots__ = ['a'] a = MyDescriptor('a') def __init__(self, val): self.a = val ``` The problem I have is how to implement the descriptor class in order to be able to store values in the cl...
Don't declare the same name as a slot and as an instance method. Use different names, and access the slot as an attribute, not via `__dict__`. ``` class MyDescriptor(object): __slots__ = ['name'] def __init__(self, name_): self.name = name_ def __get__(self, instance, owner): return getattr...
Python - print "x" "y" times when passed in a list of [x,y]
4,912,710
4
2011-02-06T10:21:11Z
4,912,720
12
2011-02-06T10:23:36Z
[ "python", "list" ]
python n00b here doing the pythonchallenge, stuck on middle of a level right now. ex: ([' ', 10], ['#', 20]) How do I print space 10 times with python? I've tried many things, but none worked... Thanks! edit: I'm not looking to learn how to use for-loops, but rather, list-manipulation(is that what they're called?) ...
``` print ' ' * 10 ``` Same as you would for any other character, e.g. ``` print 'a' * 10 ``` So for your list, assuming it's called `l`: ``` for c, n in l: print c * n ```
How do I change the string representation of a Python class?
4,912,852
85
2011-02-06T10:56:31Z
4,912,856
114
2011-02-06T10:57:23Z
[ "python", "string", "python-3.x", "printing" ]
In Java, I can override the `toString()` method of my class. Then Java's print function prints the string representation of the object defined by its `toString()`. Is there a Python equivalent to Java's `toString()`? For example, I have a PlayCard class. I have an instance c of PlayCard. Now: ``` >>> print(c) <__main...
The closest equivalent to Java's `toString` is to implement `__str__` for your class. Put this in your class definition: ``` def __str__(self): return "foo" ``` You may also want to implement `__repr__` to aid in debugging. See here for more information: * [Special Method Names - Basic Customization](http://do...
How do I change the string representation of a Python class?
4,912,852
85
2011-02-06T10:56:31Z
13,489,906
18
2012-11-21T09:19:32Z
[ "python", "string", "python-3.x", "printing" ]
In Java, I can override the `toString()` method of my class. Then Java's print function prints the string representation of the object defined by its `toString()`. Is there a Python equivalent to Java's `toString()`? For example, I have a PlayCard class. I have an instance c of PlayCard. Now: ``` >>> print(c) <__main...
This is not as easy as it seems, some core library functions don't work when only **str** is overwritten (checked with Python 2.7), see this thread for examples [Python: how to make a class JSON serializable](http://stackoverflow.com/questions/3768895/python-how-to-make-a-class-json-serializable) Also, try this ``` im...
How do I check (in runtime) if a given class is a subclass of another given class?
4,912,972
66
2011-02-06T11:26:01Z
4,912,989
16
2011-02-06T11:30:08Z
[ "python", "subclass", "assert" ]
Let's say that I have a class Suit and four subclasses of suit: Heart, Spade, Diamond, Club. ``` class Suit: ... class Heart(Suit): ... class Spade(Suit): ... class Diamond(Suit): ... class Club(Suit): ... ``` I have a method which receives a suit as a parameter, which is a class object, not an instanc...
[`issubclass`](http://docs.python.org/library/functions.html#issubclass)
How do I check (in runtime) if a given class is a subclass of another given class?
4,912,972
66
2011-02-06T11:26:01Z
4,912,999
70
2011-02-06T11:31:09Z
[ "python", "subclass", "assert" ]
Let's say that I have a class Suit and four subclasses of suit: Heart, Spade, Diamond, Club. ``` class Suit: ... class Heart(Suit): ... class Spade(Suit): ... class Diamond(Suit): ... class Club(Suit): ... ``` I have a method which receives a suit as a parameter, which is a class object, not an instanc...
You can use `issubclass()` like this `assert issubclass(suit, Suit)`. But why would you want to do such a thing? Python is not Java.
How do I check (in runtime) if a given class is a subclass of another given class?
4,912,972
66
2011-02-06T11:26:01Z
4,913,013
13
2011-02-06T11:33:52Z
[ "python", "subclass", "assert" ]
Let's say that I have a class Suit and four subclasses of suit: Heart, Spade, Diamond, Club. ``` class Suit: ... class Heart(Suit): ... class Spade(Suit): ... class Diamond(Suit): ... class Club(Suit): ... ``` I have a method which receives a suit as a parameter, which is a class object, not an instanc...
You can use `isinstance` if you have an instance, or `issubclass` if you have a class. Normally thought its a bad idea. Normally in Python you work out if an object is capable of something by attempting to do that thing to it.
Python/matplotlib mplot3d- how do I set a maximum value for the z-axis?
4,913,306
8
2011-02-06T12:34:32Z
18,588,176
7
2013-09-03T09:04:31Z
[ "python", "matplotlib" ]
I am trying to make a 3-dimensional surface plot for the expression: z = y^2/x, for x in the interval [-2,2] and y in the interval [-1.4,1.4]. I also want the z-values to range from -4 to 4. The problem is that when I'm viewing the finished surfaceplot, the z-axis values do not stop at [-4,4]. So my question is how I...
I am having the same issue and still have not found anything better than clipping my data. Unfortunately in my case I am tied to matplotlib 1.2.1. But in case you can upgrade to version 1.3.0 you could have a solution: it seems there is a bunch of new [API](http://matplotlib.org/mpl_toolkits/mplot3d/api.html) related t...
Haversine Formula in Python (Bearing and Distance between two GPS points)
4,913,349
62
2011-02-06T12:41:45Z
4,913,653
139
2011-02-06T13:47:08Z
[ "python", "gps", "distance", "haversine", "bearing" ]
### Problem I would like to know how to get the **distance and bearing between 2 GPS points**. I have researched on the haversine formula. Someone told me that I could also find the bearing using the same data. ### Edit Everything is working fine but the bearing doesn't quite work right yet. The bearing outputs nega...
Here's a Python version: ``` from math import radians, cos, sin, asin, sqrt def haversine(lon1, lat1, lon2, lat2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees) """ # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radi...
how to add value to a tuple?
4,913,397
18
2011-02-06T12:50:35Z
4,913,418
7
2011-02-06T12:55:15Z
[ "python", "tuples" ]
I'm working on a script where I have a list of tuples like `('1','2','3','4')`. e.g.: ``` list = [('1','2','3','4'), ('2','3','4','5'), ('3','4','5','6'), ('4','5','6','7')] ``` Now I need to add `'1234'`, `'2345'`,`'3456'` and `'4567'` respectively at the end of each tuple. e.g: ``` list = [...
In Python, you can't. Tuples are immutable. On the containing list, you could replace tuple `('1', '2', '3', '4')` with a different `('1', '2', '3', '4', '1234')` tuple though.
how to add value to a tuple?
4,913,397
18
2011-02-06T12:50:35Z
4,913,434
8
2011-02-06T12:58:25Z
[ "python", "tuples" ]
I'm working on a script where I have a list of tuples like `('1','2','3','4')`. e.g.: ``` list = [('1','2','3','4'), ('2','3','4','5'), ('3','4','5','6'), ('4','5','6','7')] ``` Now I need to add `'1234'`, `'2345'`,`'3456'` and `'4567'` respectively at the end of each tuple. e.g: ``` list = [...
Based on the syntax, I'm guessing this is Python. The point of a tuple is that it is immutable, so you need to replace each element with a new tuple: ``` list = [l + (''.join(l),) for l in list] # output: [('1', '2', '3', '4', '1234'), ('2', '3', '4', '5', '2345'), ('3', '4', '5', '6', '3456'), ('4', '5', '6', '...
how to add value to a tuple?
4,913,397
18
2011-02-06T12:50:35Z
4,913,789
35
2011-02-06T14:15:06Z
[ "python", "tuples" ]
I'm working on a script where I have a list of tuples like `('1','2','3','4')`. e.g.: ``` list = [('1','2','3','4'), ('2','3','4','5'), ('3','4','5','6'), ('4','5','6','7')] ``` Now I need to add `'1234'`, `'2345'`,`'3456'` and `'4567'` respectively at the end of each tuple. e.g: ``` list = [...
Tuples are immutable and not supposed to be changed - that is what the list type is for. You could replace each tuple by `originalTuple + (newElement,)`, thus creating a new tuple. For example: ``` t = (1,2,3) t = t + (1,) print t (1,2,3,1) ``` But I'd rather suggest to go with lists from the beginning, because they ...
How to efficiently parse fixed width files in Python
4,914,008
50
2011-02-06T14:54:41Z
4,914,089
53
2011-02-06T15:08:12Z
[ "python", "parsing" ]
I am trying to find an efficient way of parsing files that holds fixed width lines. For example, the first 20 characters represent a column, from 21:30 another one and so on. Assuming that the line holds 100 characters, what would be an efficient way to parse a line into several components? I could use string slicing...
I'm not really sure if this is efficient, but it should be readable (as opposed to do the slicing manually). I defined a function `slices` that gets a string and column lengths, and returns the substrings. I made it a generator, so for really long lines, it doesn't build a temporary list of substrings. ``` def slices(...
How to efficiently parse fixed width files in Python
4,914,008
50
2011-02-06T14:54:41Z
4,915,359
37
2011-02-06T18:52:16Z
[ "python", "parsing" ]
I am trying to find an efficient way of parsing files that holds fixed width lines. For example, the first 20 characters represent a column, from 21:30 another one and so on. Assuming that the line holds 100 characters, what would be an efficient way to parse a line into several components? I could use string slicing...
Using the Python standard library's `struct` module would be fairly easy as well as extremely fast since it's written in C. Here's how it could be used to do what you want. It also allows columns of characters to be skipped by specifying negative values for the number of characters in the field. ``` import struct fi...
How to efficiently parse fixed width files in Python
4,914,008
50
2011-02-06T14:54:41Z
4,916,375
9
2011-02-06T21:45:42Z
[ "python", "parsing" ]
I am trying to find an efficient way of parsing files that holds fixed width lines. For example, the first 20 characters represent a column, from 21:30 another one and so on. Assuming that the line holds 100 characters, what would be an efficient way to parse a line into several components? I could use string slicing...
The code below gives a sketch of what you might want to do if you have some serious fixed-column-width file handling to do. "Serious" = multiple record types in each of multiple file types, records up to 1000 bytes, the layout-definer and "opposing" producer/consumer is a government department with attitude, layout ch...
How to empty a file using Python
4,914,277
23
2011-02-06T15:44:09Z
4,914,288
77
2011-02-06T15:45:59Z
[ "python" ]
In the Unix shell I can do this to empty a file: ``` cd /the/file/directory/ :> thefile.ext ``` How would I go about doing this in Python? Is `os.system` the way here, I wouldn't know how since I would have to send 2 actions after each other i.e. the `cd` and then the `:>`.
Opening a file creates it and (unless append ('a') is set) overwrites it with emptyness, such as this: ``` open(filename, 'w').close() ```
How to empty a file using Python
4,914,277
23
2011-02-06T15:44:09Z
30,604,077
7
2015-06-02T18:43:25Z
[ "python" ]
In the Unix shell I can do this to empty a file: ``` cd /the/file/directory/ :> thefile.ext ``` How would I go about doing this in Python? Is `os.system` the way here, I wouldn't know how since I would have to send 2 actions after each other i.e. the `cd` and then the `:>`.
Alternate form of the answer by @rumpel ``` with open(filename, 'w'): pass ```
Google App Engine Task Queues - nasty failure
4,914,793
4
2011-02-06T17:08:21Z
4,915,498
8
2011-02-06T19:17:21Z
[ "python", "google-app-engine", "task-queue" ]
I'm developing an app for GAE and trying to use Task Queues. At present, I just have the thing running on my Windows box through GAE App Launcher but whenever I try to enqueue anything, the development 'server' crashes over and the log is full of nasty output. ``` taskqueue.add(url='/processWork', params={'key', myMod...
``` File "C:\Python27\lib\SocketServer.py" ``` App Engine runs with Python 2.5 and you are using Python 2.7.
What's the difference between raw_input() and input() in python3.x?
4,915,361
185
2011-02-06T18:52:34Z
4,915,366
243
2011-02-06T18:53:25Z
[ "python", "python-3.x" ]
What is the difference between `raw_input()` and `input()` in python3.x ?
The difference is that `raw_input()` does not exist in Python 3.x, while `input()` does. Actually, the old `raw_input()` has been renamed to `input()`, and the old `input()` is gone (but can easily be simulated by using `eval(input())`).
What's the difference between raw_input() and input() in python3.x?
4,915,361
185
2011-02-06T18:52:34Z
4,915,408
134
2011-02-06T19:01:43Z
[ "python", "python-3.x" ]
What is the difference between `raw_input()` and `input()` in python3.x ?
In Python **2**, `raw_input()` returns a string, and `input()` tries to run the input as a Python expression. Since getting a string was almost always what you wanted, Python 3 does that with `input()`. As Sven says, if you ever want the old behaviour, `eval(input())` works.
What's the difference between raw_input() and input() in python3.x?
4,915,361
185
2011-02-06T18:52:34Z
15,129,556
53
2013-02-28T07:07:50Z
[ "python", "python-3.x" ]
What is the difference between `raw_input()` and `input()` in python3.x ?
# Python 2: * `raw_input()` takes exactly what the user typed and passes it back as a string. * `input()` first takes the `raw_input()` and then performs an `eval()` on it as well. The main difference is that `input()` expects a syntactically correct python statement where `raw_input()` does not. # Python 3: * `raw...
What's the difference between raw_input() and input() in python3.x?
4,915,361
185
2011-02-06T18:52:34Z
34,532,864
7
2015-12-30T16:01:45Z
[ "python", "python-3.x" ]
What is the difference between `raw_input()` and `input()` in python3.x ?
In Python 3, `raw_input()` doesn't exist which was already mentioned by Sven. In Python 2, the `input()` function evaluates your input. **Example:** ``` name = input("what is your name ?") what is your name ?harsha Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> name = input("what i...
Django Blob Model Field
4,915,397
19
2011-02-06T18:59:47Z
4,915,465
22
2011-02-06T19:12:34Z
[ "python", "django", "django-models", "django-orm", "django-blob" ]
How do you store a "blob" of binary data using Django's ORM, with a PostgreSQL backend? Yes, I know Django frowns upon that sort of thing, and yes, I know they prefer you use the ImageField or FileField for that, but suffice it to say, that's impractical for my application. I've tried hacking it by using a TextField, ...
This snippet any good: <http://djangosnippets.org/snippets/1597/> > This is possibly the simplest solution for storing binary data in a > TextField. ``` import base64 from django.db import models class Foo(models.Model): _data = models.TextField( db_column='data', blank=True) def ...
Django Blob Model Field
4,915,397
19
2011-02-06T18:59:47Z
7,521,377
9
2011-09-22T20:53:51Z
[ "python", "django", "django-models", "django-orm", "django-blob" ]
How do you store a "blob" of binary data using Django's ORM, with a PostgreSQL backend? Yes, I know Django frowns upon that sort of thing, and yes, I know they prefer you use the ImageField or FileField for that, but suffice it to say, that's impractical for my application. I've tried hacking it by using a TextField, ...
I have been using this simple field for 'mysql' backend, you can modify it for other backends ``` class BlobField(models.Field): description = "Blob" def db_type(self, connection): return 'blob' ```
Django Blob Model Field
4,915,397
19
2011-02-06T18:59:47Z
22,156,987
16
2014-03-03T20:42:35Z
[ "python", "django", "django-models", "django-orm", "django-blob" ]
How do you store a "blob" of binary data using Django's ORM, with a PostgreSQL backend? Yes, I know Django frowns upon that sort of thing, and yes, I know they prefer you use the ImageField or FileField for that, but suffice it to say, that's impractical for my application. I've tried hacking it by using a TextField, ...
If you're using Django >= 1.6, there's a [BinaryField](https://docs.djangoproject.com/en/dev/ref/models/fields/#binaryfield)
How to delete an item in a list if it exists?
4,915,920
117
2011-02-06T20:34:51Z
4,915,950
9
2011-02-06T20:37:51Z
[ "python", "list" ]
I am getting `new_tag` from a form text field with `self.response.get("new_tag")` and `selected_tags` from checkbox fields with ``` self.response.get_all("selected_tags") ``` I combine them like this: ``` tag_string = new_tag new_tag_list = f1.striplist(tag_string.split(",") + selected_tags) ``` (`f1.striplist` is ...
``` try: s.remove("") except ValueError: print "new_tag_list has no empty string" ``` Note that this will only remove one instance of the empty string from your list (as your code would have, too). Can your list contain more than one?
How to delete an item in a list if it exists?
4,915,920
117
2011-02-06T20:34:51Z
4,915,964
390
2011-02-06T20:41:35Z
[ "python", "list" ]
I am getting `new_tag` from a form text field with `self.response.get("new_tag")` and `selected_tags` from checkbox fields with ``` self.response.get_all("selected_tags") ``` I combine them like this: ``` tag_string = new_tag new_tag_list = f1.striplist(tag_string.split(",") + selected_tags) ``` (`f1.striplist` is ...
## 1) Almost-English style: Test for presence using the `in` operator, then apply the `remove` method. ``` if thing in some_list: some_list.remove(thing) ``` The `remove`method will remove only the first occurrence of `thing`, in order to remove all occurrences you can use `while` instead of `if`. ``` while thing i...
Check if a user has a permission in pyramid (pylons 2)?
4,916,127
3
2011-02-06T21:08:35Z
4,918,310
8
2011-02-07T05:27:09Z
[ "python", "pylons", "pyramid" ]
How do i check if a user has a permission in pyramid. For example, I want to show some HTML only if a user has some permission, but have the view available for everybody.
The usual method is: ``` from pyramid.security import has_permission has_permission('view', someresource, request) ``` See also <http://docs.pylonsproject.org/projects/pyramid/1.0/narr/security.html#debugging-imperative-authorization-failures> and <http://docs.pylonsproject.org/projects/pyramid/1.0/api/security.html#...
Extract 2nd level domain from domain? - Python
4,916,890
6
2011-02-06T23:20:02Z
4,916,938
8
2011-02-06T23:30:39Z
[ "javascript", "jquery", "python", "html", "django" ]
**I have a list of domains e.g.** * site.co.uk * site.com * site.me.uk * site.jpn.com * site.org.uk * site.it **also the domain names can contain 3rd and 4th level domains e.g.** * test.example.site.org.uk * test2.site.com **I need to try and extract the 2nd level domain, in all these cases being `site`** --- Any...
no way to reliably get that. Subdomains are arbitrary and there is a monster list of domain extensions that grows every day. Best case is you check against the monster list of domain extensions and maintain the list. list: <http://mxr.mozilla.org/mozilla-central/source/netwerk/dns/effective_tld_names.dat?raw=1>
String to Dictionary in Python
4,917,006
40
2011-02-06T23:44:50Z
4,917,033
10
2011-02-06T23:49:38Z
[ "python", "string", "json", "facebook", "dictionary" ]
So I've spent way to much time on this, and it seems to me like it should be a simple fix. I'm trying to use Facebook's Authentication to register users on my site, and I'm trying to do it server side. I've gotten to the point where I get my access token, and when I go to: <https://graph.facebook.com/me?access_token=M...
Use [ast.literal\_eval](http://docs.python.org/library/ast.html#ast.literal_eval) to evaluate Python literals. However, what you have is JSON (note "true" for example), so use a JSON deserializer. ``` >>> import json >>> s = """{"id":"123456789","name":"John Doe","first_name":"John","last_name":"Doe","link":"http:\/\/...
String to Dictionary in Python
4,917,006
40
2011-02-06T23:44:50Z
4,917,044
81
2011-02-06T23:51:11Z
[ "python", "string", "json", "facebook", "dictionary" ]
So I've spent way to much time on this, and it seems to me like it should be a simple fix. I'm trying to use Facebook's Authentication to register users on my site, and I'm trying to do it server side. I've gotten to the point where I get my access token, and when I go to: <https://graph.facebook.com/me?access_token=M...
This data is [JSON](http://www.json.org/)! You can deserialize it using the built-in [`json` module](http://docs.python.org/library/json.html) if you're on Python 2.6+, otherwise you can use the excellent third-party [`simplejson` module](http://pypi.python.org/pypi/simplejson/). ``` import json # or `import simple...
Where does easy_install install things?
4,917,190
19
2011-02-07T00:22:43Z
11,104,840
8
2012-06-19T15:58:09Z
[ "python", "easy-install" ]
I want to install sphinx, and the website says to use: ``` easy_install -U Sphinx ``` What will happen when I install this command? will I get the source also? Where will it install?
The Standard installation location are: Unix (pure) * /usr/local/lib/pythonX.Y/site- (Default value) Unix (non-pure) * /usr/local/lib/pythonX.Y/site- (Default value) Windows * C:\PythonXY\Lib\site-packages (Default value) Mac OS X * /Library/Python/X.Y/site-packages
Extract files from zip without keeping the structure using python ZipFile?
4,917,284
19
2011-02-07T00:42:52Z
4,917,469
31
2011-02-07T01:30:18Z
[ "python", "extract", "unzip", "zipfile" ]
I try to extract all files from .zip containing subfolders in one folder. I want all the files from subfolders extract in only one folder without keeping the original structure. At the moment, I extract all, move the files to a folder, then remove previous subfolders. The files with same names are overwrited. Is it po...
This opens file handles of members of the zip archive, extracts the filename and copies it to a target file (that's how `ZipFile.extract` works, without taken care of subdirectories). ``` import os import shutil import zipfile my_dir = r"D:\Download" my_zip = r"D:\Download\my_file.zip" with zipfile.ZipFile(my_zip) a...
Subtract a value from every number in a list in Python?
4,918,425
26
2011-02-07T05:50:06Z
4,918,435
42
2011-02-07T05:56:30Z
[ "python", "python-3.x" ]
I'm still reading the Python 3.1.3 tutorial and encountered the following problem: > How do you remove a value from a group of numbers? > > ``` > # A list with a group of values > a = [49, 51, 53, 56] > ``` How do I subtract 13 from each integer value in the list? ``` # Attempting to minus 13 from this list - FAIL! ...
With a list comprehension. ``` a[:] = [x - 13 for x in a] ```
Subtract a value from every number in a list in Python?
4,918,425
26
2011-02-07T05:50:06Z
4,918,586
13
2011-02-07T06:22:05Z
[ "python", "python-3.x" ]
I'm still reading the Python 3.1.3 tutorial and encountered the following problem: > How do you remove a value from a group of numbers? > > ``` > # A list with a group of values > a = [49, 51, 53, 56] > ``` How do I subtract 13 from each integer value in the list? ``` # Attempting to minus 13 from this list - FAIL! ...
If are you working with numbers a lot, you might want to take a look at [NumPy](http://numpy.scipy.org/). It lets you perform all kinds of operation directly on numerical arrays. For example: ``` >>> import numpy >>> array = numpy.array([49, 51, 53, 56]) >>> array - 13 array([36, 38, 40, 43]) ```
How to traverse through the files in a directory?
4,918,458
5
2011-02-07T06:00:43Z
4,918,463
13
2011-02-07T06:01:56Z
[ "python" ]
I have a directory logfiles. I want to process each file inside this directory using a Python script. ``` for file in directory: do..... ``` How do I do this?
With [`os.listdir()`](http://docs.python.org/library/os.html#os.listdir) or [`os.walk()`](http://docs.python.org/library/os.html#os.walk), depending on whether you want to do it recursively.
The Web 2.0 Ecosystem/Stack
4,918,575
8
2011-02-07T06:20:28Z
5,545,820
8
2011-04-05T00:23:15Z
[ "javascript", "python", "ajax", "django", "pyramid" ]
Being new to front-end website development, I can understand some stuff, things like routes, ORM, etc. What I don't understand is how they all play together. My understanding is, there are a bunch of components for a website built with Pyramid/Django etc: 1. A templating engine: Something for you to abstract away your...
> 1) A templating engine: Something for > you to abstract away your HTML from > your code. Makes sense. There's several of these available. Mako tries to utilize many common Python idioms in the templates to avoid having to learn many new concepts. Jinja2 is similar to Django, but with more functionality. Genshi is if...
Regular expression for optionally matching the end of a string (optional $)
4,918,616
5
2011-02-07T06:27:38Z
4,918,619
12
2011-02-07T06:28:24Z
[ "python", "regex" ]
I'm looking to extract, `ID=(?P<group>.+?);` from a string, the 'ID=' is a constant, group can be anything. The match's position will vary in the string. This is fine in most cases, however, occasionally the match will be at the end of the string and the semi-colon will be missing. In this case, how do I optionally ...
You can use `(;|$)` to match it. Or if you don't want a capture, `(?:;|$)`
How to iterate over files and replace text
4,919,681
3
2011-02-07T09:26:40Z
4,919,734
8
2011-02-07T09:33:13Z
[ "python", "python-2.6" ]
I'm python beginner: how can I iterate over csv files in one directory and replace strings e.g. ``` ww into vv .. into -- ``` So, I do not want to replace lines having ww into vv, just those string on this line. I tried something like ``` #!/Python26/ # -*- coding: utf-8 -*- import os, sys for f in os.listdir(path)...
``` import os import csv for filename in os.listdir(path): with open(os.path.join(path, filename), 'r') as f: for row in csv.reader(f): cells = [ cell.replace('www', 'vvv').replace('..', '--') for cell in row ] # now you have a list of cells within one row ...
python threads & sockets
4,920,471
2
2011-02-07T10:58:21Z
4,921,061
7
2011-02-07T12:02:10Z
[ "python", "python-multithreading" ]
i have a "i just want to understand it" question.. first, i'm using python 2.6.5 on ubuntu. so.. threads in python (via thread module) are only "threads", and is just tells the GIL to run code blocks from each "thread" in a certain period of time and so and so.. and there aren't actually real threads here.. so the qu...
Python uses "real" threads, i.e. threads of the underlying platform. On Linux, it will use the pthread library (if you are interested, [here is the implementation](http://svn.python.org/view/python/tags/r271/Python/thread_pthread.h?view=markup)). What is special about Python's threads is the GIL: A thread can only mod...
How can I use break and continue in Django templates?
4,921,027
10
2011-02-07T11:57:34Z
4,921,156
20
2011-02-07T12:15:01Z
[ "python", "django" ]
I want to put break and continue in my code, but it doesn't work in Django template. How can I use continue and break using Django template for loop. Here is an example: ``` {% for i in i_range %} {% for frequency in patient_meds.frequency %} {% ifequal frequency i %} <td class="nopad"><input type="checkbox" name="fre...
For-loops in Django templates are different from plain Python for-loops, so `continue` and `break` will not work in them. See for yourself in the Django [docs](http://docs.djangoproject.com/en/dev/ref/templates/builtins/), there are no `break` or `continue` template tags. Given the overall position of Keep-It-Simple-St...
How can I use break and continue in Django templates?
4,921,027
10
2011-02-07T11:57:34Z
8,298,229
35
2011-11-28T15:36:20Z
[ "python", "django" ]
I want to put break and continue in my code, but it doesn't work in Django template. How can I use continue and break using Django template for loop. Here is an example: ``` {% for i in i_range %} {% for frequency in patient_meds.frequency %} {% ifequal frequency i %} <td class="nopad"><input type="checkbox" name="fre...
Django doesn't support it naturally. You can implement forloop|continue and forloop|break with custom filters. <http://djangosnippets.org/snippets/2093/>
Deleting row with Flask-SQLAlchemy
4,921,038
11
2011-02-07T11:58:42Z
4,921,527
23
2011-02-07T12:53:32Z
[ "python", "sqlalchemy", "flask" ]
I'm trying to make a function to delete a record in my database with flask and the extension for SQLAlchemy. Problem is, instead of deleting just one row, it deletes all of them. Can someone tell me what's wrong with my code? ``` @app.route('/admin/delete/<int:page_id>', methods=['GET','POST']) @requires_auth def dele...
I suspect that this line does not what you think. ``` Page.query.get(page_id).query.delete() ``` You're getting a single instance (which you already did before), and by using `query` you actually issue a new query over all objects without filtering and therefore deleting all of them. Probably what you want to do...
How to obtain a plain text Django error page
4,921,164
9
2011-02-07T12:16:04Z
4,921,329
7
2011-02-07T12:34:37Z
[ "python", "django", "http" ]
During development, I am running Django in Debug mode and I am posting data to my application using a text mode application. Ideally, I need to receive a plain text response when I get an http error code 500 so I don't have to look for the real error inside all that HTML and Javascript. Is it possible to obtain a Djan...
I think to write a middleware, because otherwise the exception isn't available in the 500.html <http://docs.djangoproject.com/en/dev/topics/http/middleware/#process-exception> ``` class ProcessExceptionMiddleware(object): def process_exception(self, request, exception): t = Template("500 Error: {{ excepti...
How to obtain a plain text Django error page
4,921,164
9
2011-02-07T12:16:04Z
4,921,565
9
2011-02-07T12:57:12Z
[ "python", "django", "http" ]
During development, I am running Django in Debug mode and I am posting data to my application using a text mode application. Ideally, I need to receive a plain text response when I get an http error code 500 so I don't have to look for the real error inside all that HTML and Javascript. Is it possible to obtain a Djan...
There's a setting [DEBUG\_PROPAGATE\_EXCEPTIONS](https://docs.djangoproject.com/en/1.9/ref/settings/#debug-propagate-exceptions) which will force Django not to wrap the exceptions, so you can see them, e.g. in devserver logs.
How to obtain a plain text Django error page
4,921,164
9
2011-02-07T12:16:04Z
21,498,065
12
2014-02-01T12:30:34Z
[ "python", "django", "http" ]
During development, I am running Django in Debug mode and I am posting data to my application using a text mode application. Ideally, I need to receive a plain text response when I get an http error code 500 so I don't have to look for the real error inside all that HTML and Javascript. Is it possible to obtain a Djan...
If you are looking for a way to get a plain text error page when using `curl`, you need to add the HTTP header `X-Requested-With` with value `XMLHttpRequest`, e.g. ``` curl -H 'X-Requested-With: XMLHttpRequest' http://example.com/some/url/ ``` Explanation: this is because Django uses the `is_ajax` method to determine...
Automating Selenium tests in Python
4,922,619
5
2011-02-07T14:49:20Z
4,922,757
9
2011-02-07T15:02:45Z
[ "python", "django", "selenium" ]
I have a Django project for which I'm trying to write browser interaction tests with Selenium. My goal is to have the tests automated from Hudson/Jenkins. So far I'm able to get the test hitting the Django server, but from the server logs I see it's hitting the url `/selenium-server/driver` instead of the right path. ...
Never seen the exact error, but I think that Selenium is trying to connect to your app rather than the selenium Server ( a .jar file). Port of the selenium server should be the first argument to selenium() That should default to port 4444, you probably have to start it with ``` $ java -jar selenium-server.jar ``` F...
How to tell BeautifulSoup to extract the content of a specific tag as text? (without touching it)
4,922,969
3
2011-02-07T15:21:09Z
4,923,278
7
2011-02-07T15:47:38Z
[ "python", "syntax-highlighting", "beautifulsoup" ]
I need to parse an html document which contains "code" tags I'm getting the code blocks like this: ``` soup = BeautifulSoup(str(content)) code_blocks = soup.findAll('code') ``` The problem is, if i have a code tag like this: ``` <code class="csharp"> List<Person> persons = new List<Person>(); </code> ``` Beaut...
Add the code tag to the QUOTE\_TAGS dictionary. ``` from BeautifulSoup import BeautifulSoup content = "<code class='csharp'>List<Person> persons = new List<Person>();</code>" BeautifulSoup.QUOTE_TAGS['code'] = None soup = BeautifulSoup(str(content)) code_blocks = soup.findAll('code') ``` Output: ``` [<code class="...
Efficient Numpy 2D array construction from 1D array
4,923,617
28
2011-02-07T16:20:38Z
4,924,179
8
2011-02-07T17:11:05Z
[ "python", "numpy" ]
I have an array like this: ``` A = array([1,2,3,4,5,6,7,8,9,10]) ``` And I am trying to get an array like this: ``` B = array([[1,2,3], [2,3,4], [3,4,5], [4,5,6]]) ``` Where each row (of a fixed arbitrary width) is shifted by one. The array of A is 10k records long and I'm trying to fi...
This solution is not efficiently implemented by a python loop since it comes with all kinds of type-checking best avoided when working with numpy arrays. If your array is exceptionally tall, you will notice a large speed up with this: ``` newshape = (4,3) newstrides = (A.itemsize, A.itemsize) B = numpy.lib.stride_tric...
Efficient Numpy 2D array construction from 1D array
4,923,617
28
2011-02-07T16:20:38Z
4,924,433
37
2011-02-07T17:31:14Z
[ "python", "numpy" ]
I have an array like this: ``` A = array([1,2,3,4,5,6,7,8,9,10]) ``` And I am trying to get an array like this: ``` B = array([[1,2,3], [2,3,4], [3,4,5], [4,5,6]]) ``` Where each row (of a fixed arbitrary width) is shifted by one. The array of A is 10k records long and I'm trying to fi...
Actually, there's an even more efficient way to do this... The downside to using `vstack` etc, is that you're making a copy of the array. Incidentally, this is effectively identical to @Paul's answer, but I'm posting this just to explain things in a bit more detail... There's a way to do this with just views so that ...
generating py.test tests in python
4,923,836
13
2011-02-07T16:40:30Z
4,929,457
9
2011-02-08T04:05:23Z
[ "python", "unit-testing", "py.test" ]
Question first, then an explanation if you're interested. In the context of py.test, how do I generate a large set of test functions from a small set of test-function templates? Something like: ``` models = [model1,model2,model3] data_sets = [data1,data2,data3] def generate_test_learn_parameter_function(model,data)...
Good instincts. `py.test` supports exactly what you're talking about with its `pytest_generate_tests()` hook. They explain it [here](https://pytest.org/latest/parametrize.html#pytest-generate-tests).
UnicodeDecodeError reading string in CSV
4,923,929
3
2011-02-07T16:48:29Z
4,924,011
7
2011-02-07T16:56:56Z
[ "python", "unicode", "csv" ]
I'm having a problem reading some chars in python. I have a csv file in UTF-8 format, and I'm reading, but when script read: ``` Preußen Münster-Kaiserslautern II ``` I get this error: ``` Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-d...
Try the `unicode_csv_reader()` generator described in the [csv module docs](http://docs.python.org/library/csv.html).
How to launch python Idle from a virtual environment (virtualenv)
4,924,068
19
2011-02-07T17:01:12Z
4,925,036
23
2011-02-07T18:34:38Z
[ "python", "virtualenv", "python-idle" ]
I have a package that I installed from a virtual environment. If I just launch the python interpreter, that package can be imported just fine. However, if I launch Idle, that package cannot be imported (since it's only available in one particular virtualenv and not global). How can I launch Idle from a virtualenv, so t...
IDLE is essentially ``` from idlelib.PyShell import main if __name__ == '__main__': main() ``` So you can launch it yourself unless you built the virtualenv without default packages.
How to launch python Idle from a virtual environment (virtualenv)
4,924,068
19
2011-02-07T17:01:12Z
10,367,004
9
2012-04-28T19:50:55Z
[ "python", "virtualenv", "python-idle" ]
I have a package that I installed from a virtual environment. If I just launch the python interpreter, that package can be imported just fine. However, if I launch Idle, that package cannot be imported (since it's only available in one particular virtualenv and not global). How can I launch Idle from a virtualenv, so t...
On Windows, a Python script run from command line like this `some_script.py` might be run by other Python interpreter than the one used when using `python some_script.py` command (it depends on `py` files association). If one wants to avoid this problem it's best to create a batch file `idle.bat` with the content `pyth...
How to properly url encode accents?
4,924,273
6
2011-02-07T17:17:23Z
4,924,342
11
2011-02-07T17:23:46Z
[ "python", "escaping", "urllib2", "urlencode" ]
I need to url encode foreign names, like "Misère". When I do: ``` urllib2.quote(name) ``` I get a the error: ``` File "/System/Library/Frameworks/Python.framework/Versions/ 2.5/lib/python2.5/urllib.py", line 1205, in quote res = map(safe_map.__getitem__, s) KeyError: u'\xe8' ``` What am I doing wrong?
try urllib2.quote(s.encode('utf8'))
Google App Engine deferred.defer() failing when method returns
4,924,648
3
2011-02-07T17:51:39Z
4,924,671
9
2011-02-07T17:54:10Z
[ "python", "google-app-engine", "exception", "task" ]
I'm trying to use google.appengine.ext.deferred to run a Task. I am passing a method to the defer() method, and that method runs successfully, but upon returning, a ValueError is thrown: ``` File ".../admin.py", line 73, in post result = deferred.defer(meeple_tasks.buildGames()) File "/Applications/GoogleA...
You should use: ``` result = deferred.defer(meeple_tasks.buildGames) ``` If you use `buildGames()`, that invokes the function *right then and there*, passing the *return value* to `defer()`. By removing the parenthesis, you pass the function itself to defer.
trouble installing rpy2 on win7 (R 2.12, Python 2.5)
4,924,917
13
2011-02-07T18:22:13Z
29,193,493
7
2015-03-22T10:55:19Z
[ "python", "windows-7", "matplotlib", "rpy2" ]
I'm brand new to Python (and programming in general) I come from a finance background, so please bear with me. I just started using Python (Enthought's Pylab/Scipy/Numpy) and R for statistical analysis. I'm trying to install rpy2 into Python to integrate R, but I get the error: > Tried to guess R's HOME but no R > com...
I know I'm a little late to the party, but I had the same problem and got it working on Windows 7 by doing the install via conda ``` conda install --channel https://conda.binstar.org/joshadel rpy2 ```
SQLAlchemy query where a column contains a substring
4,926,757
12
2011-02-07T21:22:30Z
4,926,793
18
2011-02-07T21:26:38Z
[ "python", "sqlite", "sqlalchemy" ]
I'm constructing a query using SQLAlchemy and SQLite3 in which I'd like to select rows in which a String column contains a particular substring. What is the best way to accomplish this?
Filter by `db.table.column.like('%needle%')`. There is also `ilike` for a case insensitive search. For a fancier interface you can allow for the known "dir" wildcards. ``` if '*' in needle or '_' in needle: looking_for = needle.replace('_', '__')\ .replace('*', '%')\ ...
SQLAlchemy query where a column contains a substring
4,926,757
12
2011-02-07T21:22:30Z
6,980,413
8
2011-08-08T09:56:57Z
[ "python", "sqlite", "sqlalchemy" ]
I'm constructing a query using SQLAlchemy and SQLite3 in which I'd like to select rows in which a String column contains a particular substring. What is the best way to accomplish this?
While `table.c.column.like("%...%")` should work, there is a more direct way to say what you want: ``` table.c.column.contains("needle") ``` This will usually generate the same SQL query but it is better to read for the uninitiated. Note that contains does not seem to escape **"\_"** and **"%"**.
SQLAlchemy query where a column contains a substring
4,926,757
12
2011-02-07T21:22:30Z
19,654,702
15
2013-10-29T09:48:11Z
[ "python", "sqlite", "sqlalchemy" ]
I'm constructing a query using SQLAlchemy and SQLite3 in which I'd like to select rows in which a String column contains a particular substring. What is the best way to accomplish this?
Try this ``` Model.query.filter(Model.columnName.contains('sub_string')) ```
What can be done to speed up this memoization decorator?
4,927,323
3
2011-02-07T22:19:31Z
4,927,493
12
2011-02-07T22:39:51Z
[ "python", "memoization" ]
What I want is a memoization decorator that: * can memoize instance methods with both arguments and keyword arguments * has a cache that can be cleared (globally) with one call (vs. this one that uses a per-function cache: [python resettable memoization decorator](http://stackoverflow.com/questions/4431703/python-rese...
You're not actually caching any data, because each time you set a new cached value you overwrite the previous: ``` Memoized.__cache[self.key] = {args : value} ``` eg. ``` import functools class Memoized(object): """Decorator that caches a function's return value each time it is called. If called later with ...
Iterate through PyMongo Cursor as key-value pair
4,928,274
13
2011-02-08T00:19:49Z
4,928,476
15
2011-02-08T00:49:21Z
[ "python", "mongodb", "pymongo" ]
Is it possible to iterate over a pymongo `Cursor` as a key-value pair like a `dict`? I'm using python 2.6 and pymongo 1.9. I've tried this: ``` import pymongo mongo = pymongo.Connection('localhost') mongo_db = mongo['my_database'] mongo_coll = mongo_db['my_collection'] cursor = mongo_coll.find() records = dict([(reco...
Try: ``` records = dict((record['_id'], record) for record in cursor) ```
all permutations of a binary sequence x bits long
4,928,297
12
2011-02-08T00:24:02Z
4,928,350
34
2011-02-08T00:31:14Z
[ "python", "algorithm", "combinatorics" ]
I would like to find a clean and clever way (in python) to find all permutations of strings of 1s and 0s x chars long. Ideally this would be fast and not require doing too many iterations... So, for x = 1 I want: ['0','1'] x =2 ['00','01','10','11'] etc.. Right now I have this, which is slow and seems inelegant: ``...
`itertools.product` is made for this: ``` >>> import itertools >>> ["".join(seq) for seq in itertools.product("01", repeat=2)] ['00', '01', '10', '11'] >>> ["".join(seq) for seq in itertools.product("01", repeat=3)] ['000', '001', '010', '011', '100', '101', '110', '111'] ```
python, format string
4,928,526
19
2011-02-08T00:58:05Z
4,928,539
30
2011-02-08T01:00:03Z
[ "python" ]
I am trying to build a format string with lazy argument, eg I need smth like: ``` "%s \%s %s" % ('foo', 'bar') # "foo %s bar" ``` how can i do this?
``` "%s %%s %s" % ('foo', 'bar') ``` you need %%
python, format string
4,928,526
19
2011-02-08T00:58:05Z
4,928,580
17
2011-02-08T01:05:43Z
[ "python" ]
I am trying to build a format string with lazy argument, eg I need smth like: ``` "%s \%s %s" % ('foo', 'bar') # "foo %s bar" ``` how can i do this?
with python 2.6: ``` >>> '{0} %s {1}'.format('foo', 'bar') 'foo %s bar' ``` or with python 2.7: ``` >>> '{} %s {}'.format('foo', 'bar') 'foo %s bar' ```
How can I work with Gzip files which contain extra data?
4,928,560
9
2011-02-08T01:02:51Z
4,928,651
14
2011-02-08T01:20:35Z
[ "python", "gzip" ]
I'm writing a script which will work with data coming from instrumentation as gzip streams. In about 90% of cases, the `gzip` module works perfectly, but some of the streams cause it to produce `IOError: Not a gzipped file`. If the gzip header is removed and the deflate stream fed directly to `zlib`, I instead get `Err...
This is a bug. The quality of the gzip module in Python falls far short of the quality that should be required in the Python standard library. The problem here is that the gzip module assumes that the file is a stream of gzip-format files. At the end of the compressed data, it starts from scratch, expecting a new gzip...
xlrd Excel script converting "#N/A" to 42
4,928,629
3
2011-02-08T01:15:35Z
5,842,150
7
2011-04-30T13:47:17Z
[ "python", "excel", "xlrd" ]
I have a script that pulls data out of an excel spreadsheet using the xlrd module, specifically the row\_values() method. It appears to do a great job, except for where "#N/A" has been auto-generated by previous VLookups, in which case xlrd gets "#N/A" as integer 42. I had a look at string formatting methods but could...
I found this useful. Thanks to John's initial help. ``` def xls_proc_text(cell, value_proc=None, text_proc=None): """Converts the given cell to appropriate text.""" """The proc will come in only when the given is value or text.""" ttype = cell.ctype if ttype == xlrd.XL_CELL_EMPTY or ttype == xlrd.XL_CE...
Python - How to clear a integer from a list completely?
4,928,941
2
2011-02-08T02:10:35Z
4,928,946
8
2011-02-08T02:11:39Z
[ "python", "python-3.x" ]
``` # Assign list "time" with the following time values. time = [15, 27, 32, 36.5, 38.5, 40.5, 41.5, 42, 43.5, 45.5, 47.5, 52.5] # Remove 1st value(0) from the list time[0] = [] # Show time time [[], 27, 32, 36.5, 38.5, 40.5, 41.5, 42, 43.5, 45.5, 47.5, 52.5] # Print time print(time) [[], 27, 32, 36.5, 38.5, 40.5,...
You want [`del`](http://docs.python.org/py3k/tutorial/datastructures.html#the-del-statement) for this. ``` del time[0] ```
Python regular expression with wiki text
4,929,082
3
2011-02-08T02:40:20Z
4,929,231
7
2011-02-08T03:16:36Z
[ "python", "regex", "wiki" ]
I'm trying to change wikitext into normal text using Python regular expressions substitution. There are two formatting rules regarding wiki link. * [[Name of page]] * [[Name of page | Text to display]] (http://en.wikipedia.org/wiki/Wikipedia:Cheatsheet) Here is some text that gives me a headache. > The CD is comp...
``` wikilink_rx = re.compile(r'\[\[(?:[^|\]]*\|)?([^\]]+)\]\]') return wikilink_rx.sub(r'\1', the_string) ``` Example: <http://ideone.com/7oxuz> Note: you may also find some MediaWiki parsers in <http://www.mediawiki.org/wiki/Alternative_parsers>.
Most efficient way to get several hashes in Redis?
4,929,202
15
2011-02-08T03:09:13Z
5,031,367
29
2011-02-17T16:00:02Z
[ "python", "database-design", "optimization", "redis" ]
So I've already read [this post](http://stackoverflow.com/questions/3329408/is-there-mget-analog-for-redis-hashes) about there not being an `MGET` analog for Redis hashes. One of the answers said to use `MULTI/EXEC` to do the operation in bulk, and that does work for lists and regular keys, but not for hashes, unfortun...
The most efficient way would be using a pipeline. Assuming you want everything for a given key and know all the keys already: ``` import redis r = redis.Redis(host='localhost', port=6379, db=0) p = r.pipeline() for key in keys: p.hgetall(key) for h in p.execute(): print h ``` More information about pipelin...
Can you step through python code to help debug issues?
4,929,251
50
2011-02-08T03:21:42Z
4,929,265
18
2011-02-08T03:24:35Z
[ "python" ]
In java/c# you can easily step through code to trace what might be going wrong, and IDE's make this process very user friendly. Can you trace through python code in a similiar fashion?
There is a module called 'pdb' in python. At the top of your python script you do ``` import pdb pdb.set_trace() ``` and you will enter into debugging mode. You can use 's' to step, 'n' to follow next line similar to what you would do with 'gdb' debugger.
Can you step through python code to help debug issues?
4,929,251
50
2011-02-08T03:21:42Z
4,929,267
80
2011-02-08T03:26:12Z
[ "python" ]
In java/c# you can easily step through code to trace what might be going wrong, and IDE's make this process very user friendly. Can you trace through python code in a similiar fashion?
Yes! There's a Python debugger called `pdb` just for doing that! You can launch a Python program through `pdb` by using `pdb myscript.py` or `python -m pdb myscript.py`. There are a few commands you can then issue, which are documented on the [`pdb`](http://docs.python.org/library/pdb.html) page. Some useful ones to...
What are WSGI and CGI in plain English?
4,929,626
55
2011-02-08T04:42:40Z
4,929,656
28
2011-02-08T04:46:45Z
[ "python", "cgi", "wsgi" ]
Every time I read either WSGI or CGI I cringe. I've tried reading on it before but nothing really has stuck. What is it really in plain English? Does it just pipe requests to a terminal and redirect the output?
WSGI runs the Python interpreter on web server start, either as part of the web server process (embedded mode) or as a separate process (daemon mode), and loads the script into it. Each request results in a specific function in the script being called, with the request environment passed as arguments to the function. ...
What are WSGI and CGI in plain English?
4,929,626
55
2011-02-08T04:42:40Z
5,120,610
122
2011-02-25T17:36:43Z
[ "python", "cgi", "wsgi" ]
Every time I read either WSGI or CGI I cringe. I've tried reading on it before but nothing really has stuck. What is it really in plain English? Does it just pipe requests to a terminal and redirect the output?
From a totally step-back point of view, Blankman, here is my "Intro Page" for Web Services Gateway Interface: **PART ONE: WEB SERVERS** Web servers serve up responses. They sit around, waiting patiently, and then with no warning at all, suddenly: * a client process sends a request. The client process could be a web ...
What are WSGI and CGI in plain English?
4,929,626
55
2011-02-08T04:42:40Z
9,932,746
9
2012-03-29T20:10:30Z
[ "python", "cgi", "wsgi" ]
Every time I read either WSGI or CGI I cringe. I've tried reading on it before but nothing really has stuck. What is it really in plain English? Does it just pipe requests to a terminal and redirect the output?
If you are unclear on all the terms in this space, and lets face it, its a confusing acronym-laden one, there's also a good background reader in the form of an official python HOWTO which discusses CGI vs. FastCGI vs. WSGI and so on: <http://docs.python.org/howto/webservers.html> . I wish I'd read it first.
Python lib to make nice command line scripts with options etc
4,929,851
2
2011-02-08T05:18:21Z
4,929,857
9
2011-02-08T05:19:14Z
[ "python" ]
I remember coming reading about a python module/lib that helped make nice command line scripts that takes in options. My python script (1 file) does many things, and currently I comment out/uncomment the function I want run in my **main** section. I was hoping someone knows the lib I'm talking about that would help m...
there is an `optparse` module. in newer variants of python, `argparse` is preferred. optparse: <http://docs.python.org/library/optparse.html> argparse: <http://docs.python.org/library/argparse.html> use optparse in <= 2.7, argparse in > 2.7
How to install easy_install in Python 2.7.1 on Windows 7
4,930,216
26
2011-02-08T06:29:07Z
4,931,095
42
2011-02-08T08:49:07Z
[ "python", "easy-install" ]
I have installed Python 2.7.1 on Windows 7, but I am unable to install easy\_install. Please help me.
I usually just run [ez\_setup.py](http://peak.telecommunity.com/dist/ez_setup.py). IIRC, that works fine, at least with UAC off. It also creates an easy\_install executable in your Python\scripts subdirectory, which should be in your PATH. UPDATE: I highly recommend not to bother with easy\_install anymore! Jump righ...
How to install easy_install in Python 2.7.1 on Windows 7
4,930,216
26
2011-02-08T06:29:07Z
6,418,235
19
2011-06-20T22:17:50Z
[ "python", "easy-install" ]
I have installed Python 2.7.1 on Windows 7, but I am unable to install easy\_install. Please help me.
for 32-bit Python, the installer is [here](http://pypi.python.org/packages/2.7/s/setuptools/). after you run the installer, you will have `easy_install.exe` in your `\Python27\Scripts` directory if you are looking for 64-bit installers, this is an excellent resource: <http://www.lfd.uci.edu/~gohlke/pythonlibs/> the ...
How do get more control over loop increments in Python?
4,930,404
12
2011-02-08T05:07:19Z
4,930,482
11
2011-02-08T07:11:23Z
[ "python", "syntax" ]
I'm trying to loop from 0 to 1 using step sizes of 0.01 (for example). How would I go about doing this? The `for i in range(start, stop, step)` only takes integer arguments so floats won't work.
``` for i in [float(j) / 100 for j in range(0, 100, 1)]: print i ```