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: if/else in dict comprehension?
9,442,724
36
2012-02-25T09:04:45Z
9,442,777
65
2012-02-25T09:17:15Z
[ "python", "dictionary", "dictionary-comprehension" ]
In python2.7+ exist any way to make something like: ``` { something_if_true if condition else something_if_false for key, value in dict_.items() } ``` I know you can make anything with just 'if' ``` { something_if_true for key, value in dict_.items() if condition} ```
You've already got it: `A if test else B` is a valid python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon: ``` { (some_key if condition else default_key):(something_if_true if condition ...
how to install Cython on lion
9,443,980
3
2012-02-25T12:27:56Z
9,521,322
7
2012-03-01T17:50:25Z
[ "python", "gcc", "cython", "llvm-gcc" ]
I'm trying to install cython on lion but this is what I get: ``` $ export CC=gcc-4.2 $ gcc --version i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00) $ python setup.py install error: command 'gcc-4.2' failed with exit status 255 ``` I'm not sure that llvm-gcc is r...
You need to adjust at least your PATH and LD\_LIBRARY\_PATH environment variables. The PATH environment variable also needs to include `/Developer/usr/bin`. I've written a ~/.bash\_devenv file, which I source every time I want to compile C code on my Mac Pro mid-2010 (upgraded from Snow Leopard to Lion to Lion Server)...
Adding a javascript script tag some place so that it works for every file in sphinx documentation
9,444,342
11
2012-02-25T13:18:42Z
9,454,654
13
2012-02-26T16:11:00Z
[ "javascript", "python", "python-sphinx" ]
I am using Sphinx to write some notes. I am using the Mathjax extension for Math in the notes. The default size of the math is little larger than I would like. On the Mathjax page I found that I can change that size by adding the following script to the HTML file. ``` MathJax.Hub.Config({ "HTML-CSS": {scale: 90} });...
This can be done with a template: 1. Create a folder called `templates` in the Sphinx project directory. 2. In conf.py, add ``` templates_path = ["templates"] ``` 3. In the `templates` directory, create a file called `layout.html` with the following contents: ``` {% extends "!layout.html" %} {%- b...
gunicorn and websockets
9,444,405
3
2012-02-25T13:28:29Z
11,301,797
8
2012-07-02T22:02:55Z
[ "python", "websocket", "gevent", "gunicorn" ]
I'm trying to get <http://www.gelens.org/code/gevent-websocket/> running and keep getting the following error. ``` socket_id=1 already closed. result = self._run(*self.args, **self.kwargs) File "/home/walt/virtualenv/ws/local/lib/python2.7/site-packages/gevent/pywsgi.py", line 571, in handle handler.handle()...
used @bkad's code and added to main main app file ``` def log_request(self): log = self.server.log if log: if hasattr(log, "info"): log.info(self.format_request() + '\n') else: log.write(self.format_request() + '\n') import gevent gevent.pywsgi.WSGIHandler.log_request =...
Why is numpy much slower than matlab on a digitize example?
9,444,409
14
2012-02-25T13:28:48Z
9,445,500
17
2012-02-25T15:49:12Z
[ "python", "performance", "matlab", "numpy" ]
I am comparing performance of *numpy vs matlab*, in several cases I observed that numpy is significantly slower (indexing, simple operations on arrays such as absolute value, multiplication, sum, etc.). Let's look at the following example, which is somehow striking, involving the function **digitize** (which I plan to ...
First, let's look at why `numpy.digitize` is slow. If your bins are found to be monotonic, then one of these functions is called depending on whether the bins are nondecreasing or nonincreasing (the code for this is found in `numpy/lib/src/_compiled_base.c` in the numpy git repo): ``` static npy_intp incr_slot_(double...
TypeError: __init__() takes exactly 3 arguments (2 given)
9,444,992
4
2012-02-25T14:48:20Z
9,445,002
7
2012-02-25T14:50:17Z
[ "python", "class", "arguments" ]
I've seen a few of the answers on here regarding my error but its not helped me. I am an absolute noob at classes on python and just started doing this code back in September. Anyway have a look at my code ``` class SimpleCounter(): def __init__(self, startValue, firstValue): firstValue = startValue ...
The `__init__()` definition calls for 2 input values, `startValue` and `firstValue`. You have only supplied one value. ``` def __init__(self, startValue, firstValue): # Need another param for firstValue a = SimpleCounter(5) # Something like a = SimpleCounter(5, 5) ``` Now, whether you actually need 2 values is a di...
Python: size of strings in memory
9,445,201
8
2012-02-25T15:13:50Z
9,445,244
14
2012-02-25T15:18:33Z
[ "python", "arrays", "memory-management" ]
Consider the following code: ``` arr = [] for (str, id, flag) in some_data: arr.append((str, id, flag)) ``` Imagine the input strings being 2 chars long in average and 5 chars max and some\_data having 1 million elements. What will the memory requirement of such a structure be? May it be that a lot of memory is ...
In this case, because the strings are quite short, and there are so many of them, you stand to save a fair bit of memory by using [`intern`](https://docs.python.org/2/library/functions.html#intern) on the strings. Assuming there are only lowercase letters in the strings, that's 26 \* 26 = 676 possible strings, so there...
lists or dicts over zeromq in python
9,445,370
7
2012-02-25T15:35:13Z
9,445,903
13
2012-02-25T16:45:07Z
[ "python", "zeromq" ]
What is the correct/best way to send objects like lists or dicts over zeromq in python? What if we use a PUB/SUB pattern, where the first part of the string would be used as a filter? * I am aware that there are multipart messages, but they where originally meant for a different purpose. Further you can not subscribe ...
**Manual serialization** You turn the data into a string, concatenate or else, do your stuff. It's fast and doesn't take much space but requires work and maintenance, and it's not flexible. If another language wants to read the data, you need to code it again. No DRY. Ok for very small data, but really the amount of...
How to make a Python HTTP Request with POST data and Cookie?
9,445,491
10
2012-02-25T15:48:09Z
9,445,989
25
2012-02-25T16:53:51Z
[ "python", "cookies", "http-post", "urllib2" ]
I am trying to do a HTTP POST using cookies in Python. I have the values of URL, POST data and cookie. ``` import urllib2 url="http://localhost/testing/posting.php" data="subject=Alice-subject&addbbcode18=%23444444&addbbcode20=0&helpbox=Close+all+open+bbCode+tags&message=alice-body&poll_title=&add_poll_option_text=&p...
You can try *requests*, which makes life easier when dealing with HTTP queries. ``` import requests url="http://localhost/testing/posting.php" data= { 'subject': 'Alice-subject', 'addbbcode18': '%23444444', 'addbbcode20': '0', 'helpbox': 'Close all open bbCode tags', 'message': 'alice-body', 'p...
How to retry urllib2.request when fails?
9,446,387
22
2012-02-25T17:46:16Z
9,446,765
46
2012-02-25T18:27:00Z
[ "python", "urllib2", "decorator" ]
When `urllib2.request` reaches timeout, a `urllib2.URLError` exception is raised. What is the pythonic way to retry establishing a connection?
I would use a [retry](http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/) decorator. There are other ones out there, but this one works pretty well. Here's how you can use it: ``` @retry(urllib2.URLError, tries=4, delay=3, backoff=2) def urlopen_with_retry(): return urllib2.urlopen("http://e...
Sorting a nesting list by the first item -- itemgetter not doing the trick
9,446,953
7
2012-02-25T18:45:40Z
9,447,273
13
2012-02-25T19:25:09Z
[ "python", "list", "sorting", "nested" ]
I have a dictionary that I've converted to a list so I can sort by the first item. The key in the dictionary is a string (of numbers), the value is an integer which is maintained in the list. The list from the dictionary conversion looks like: ``` [('228055', 1), ('228054', 1), ('228057', 2), ('228056', 1), ('228051...
That's because they're strings. ``` key=lambda x: int(x[0]) ```
TypeError: count() takes exactly one argument
9,447,986
4
2012-02-25T20:57:42Z
9,448,024
8
2012-02-25T21:01:34Z
[ "python", "django" ]
I'm new to Python and Django, and I modified this code from a tutorial. I'm getting `TypeError: count() takes exactly one argument (0 given)` when I load the page. I've been troubleshooting and googling and can't seem to figure it out. What am I doing wrong? ``` def report(request): flashcard_list = [] for fla...
`count` requires an argument. It returns the number of instances of a particular item in a list. ``` >>> l = range(10) + range(10) >>> l.count(5) 2 ``` `2` here is the number of `5`s in the list. If you want the length of a list, use `len`. ``` >>> len(l) 20 ```
Python - implement __iter__ or return a list's __iter__
9,448,025
10
2012-02-25T21:01:39Z
9,448,055
16
2012-02-25T21:04:50Z
[ "python", "iterator" ]
I'm implementing what is essentially a container object (although it does have a little of it's own logic). I want to be able to iterate over items in a field in this class (which is just a plain list). Should I re-implement `__iter__` and `next` for my class or is it acceptable to return the iterator of the list, like...
It is fine to use the iterator of the built-in `list` type. I'd suggest not to call `__iter__()` explicitly, though, but rather use the built-in function `iter()`: ``` def __iter__(self): return iter(self.list) ``` Another option might be to derive `X` from `list`. (In Python 2.x, you should at least derive from ...
Print an integer array as hexadecimal numbers
9,448,029
8
2012-02-25T21:02:11Z
9,448,080
8
2012-02-25T21:08:39Z
[ "python", "arrays", "numpy" ]
I have an array created by using ``` array1 = np.array([[25, 160, 154, 233], [61, 244, 198, 248], [227, 226, 141, 72 ], [190, 43, 42, 8]],np.int) ; ``` which displays as ``` [[25, 160, 154, 233] [61, 244, 198, 248] [227, 226, 141, 72] [190, 43, 4...
Python has a built-in hex function for converting integers to their hex representation (a string). You can use numpy.vectorize to apply it over the elements of the multidimensional array. ``` >>> import numpy as np >>> A = np.array([[1,2],[3,4]]) >>> vhex = np.vectorize(hex) >>> vhex(A) array([['0x1', '0x2'], [...
Print an integer array as hexadecimal numbers
9,448,029
8
2012-02-25T21:02:11Z
9,448,099
16
2012-02-25T21:10:36Z
[ "python", "arrays", "numpy" ]
I have an array created by using ``` array1 = np.array([[25, 160, 154, 233], [61, 244, 198, 248], [227, 226, 141, 72 ], [190, 43, 42, 8]],np.int) ; ``` which displays as ``` [[25, 160, 154, 233] [61, 244, 198, 248] [227, 226, 141, 72] [190, 43, 4...
You can set the print options for numpy to do this. ``` import numpy as np np.set_printoptions(formatter={'int':hex}) np.array([1,2,3,4,5]) ``` gives ``` array([0x1L, 0x2L, 0x3L, 0x4L, 0x5L]) ``` The L at the end is just because I am on a 64-bit platform and it is sending longs to the formatter. To fix this you can...
Calculating Probability of a Random Variable in a Distribution in Python
9,448,246
3
2012-02-25T21:29:23Z
9,448,324
7
2012-02-25T21:40:22Z
[ "python", "math", "probability", "probability-theory" ]
Given a mean and standard-deviation defining a [normal distribution](http://en.wikipedia.org/wiki/Normal_distribution), how would you calculate the following probabilities in pure-Python (i.e. no Numpy/Scipy or other packages not in the standard library)? 1. The probability of a random variable r where r < x or r <= x...
All these are very similar: If you can compute #1 using a function `cdf(x)`, then the solution to #2 is simply `1 - cdf(x)`, and for #3 it's `cdf(x) - cdf(y)`. Since Python includes the (gauss) error function built in since version 2.7 you can do this by calculating the cdf of the normal distribution using the equatio...
Get list of dictionary elements ordered by dictionary key
9,448,406
2
2012-02-25T21:51:15Z
9,448,409
14
2012-02-25T21:51:57Z
[ "python" ]
I have a dictionary `d` for which the keys are all strings. Now when I do: ``` for key in d: print(d[key]) ``` I get the elements of `d` is some "random" order. How can I force the element of `d` to come out sorted by the lexicographical order?
Sort before iterating. ``` for key in sorted(d): ```
Get list of dictionary elements ordered by dictionary key
9,448,406
2
2012-02-25T21:51:15Z
9,448,412
7
2012-02-25T21:52:18Z
[ "python" ]
I have a dictionary `d` for which the keys are all strings. Now when I do: ``` for key in d: print(d[key]) ``` I get the elements of `d` is some "random" order. How can I force the element of `d` to come out sorted by the lexicographical order?
Use `sorted()` to sort any iterable, including a dictionary: ``` for key in sorted(d): print(d[key]) ```
How to stop Flask from initialising twice in Debug Mode?
9,449,101
29
2012-02-25T23:35:01Z
9,453,947
15
2012-02-26T14:36:14Z
[ "python", "flask" ]
When building a Flask service in Python and setting the debug mode on, the Flask service will initialise twice. When the initialisation loads caches and the like, this can take a while. Having to do this twice is annoying when in development (debug) mode. When debug is off, the Flask service only initialises once. How...
You can use the `before_first_request` hook: ``` @app.before_first_request def initialize(): print "Called only once, when the first request comes in" ```
How to stop Flask from initialising twice in Debug Mode?
9,449,101
29
2012-02-25T23:35:01Z
9,476,701
49
2012-02-28T05:06:49Z
[ "python", "flask" ]
When building a Flask service in Python and setting the debug mode on, the Flask service will initialise twice. When the initialisation loads caches and the like, this can take a while. Having to do this twice is annoying when in development (debug) mode. When debug is off, the Flask service only initialises once. How...
The simplest thing to do here would be to add `use_reloader=False` to your call to `app.run` - that is: `app.run(debug=True, use_reloader=False)` Alternatively, you can check for the value of [`WERKZEUG_RUN_MAIN`](https://github.com/mitsuhiko/werkzeug/blob/cbd049d88727936173386d2e80bb5ffa51fedd6e/werkzeug/_reloader.py...
Taking the union of sets
9,449,196
4
2012-02-25T23:49:01Z
9,449,226
9
2012-02-25T23:53:07Z
[ "python" ]
I have a list `l` of sets. To take the union of all the sets in `l` I do: ``` union = set() for x in l: union |= x ``` I have a feeling there is a more economical/functional way of writing this. Can I improve upon this?
Here's how I would do it (some corrections as per comments): ``` union_set = set() union_set.update(*l) ``` or ``` union_set = set.union(*l) ```
Python function expects a tuple, what I have is a list. How do I call this function?
9,449,693
2
2012-02-26T01:20:28Z
9,449,713
10
2012-02-26T01:24:01Z
[ "python", "list", "tuples" ]
The function `record()` in the [pyshp](https://code.google.com/p/pyshp/) module expects a sequence as input: ``` outfile.record('First','Second','Third') ``` What I have is a list: ``` row = ['First','Second','Third'] ``` When I call the `record()` function like this: ``` outfile.record(row) ``` I get a `tuple in...
``` outfile.record(*row) ``` This will unpack a sequence into individual arguments. This is a [formal description of this syntax from the language reference](http://docs.python.org/reference/expressions.html#calls), and this is an [informal description from the tutorial](http://docs.python.org/tutorial/controlflow.htm...
Python function expects a tuple, what I have is a list. How do I call this function?
9,449,693
2
2012-02-26T01:20:28Z
9,449,718
7
2012-02-26T01:25:05Z
[ "python", "list", "tuples" ]
The function `record()` in the [pyshp](https://code.google.com/p/pyshp/) module expects a sequence as input: ``` outfile.record('First','Second','Third') ``` What I have is a list: ``` row = ['First','Second','Third'] ``` When I call the `record()` function like this: ``` outfile.record(row) ``` I get a `tuple in...
``` outfile.record(*row) ``` The \* in this case means "unpack." It will unpack a list into a series of arguments. <http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists>
How to surpress python's start-up information?
9,449,707
4
2012-02-26T01:22:46Z
9,449,738
7
2012-02-26T01:28:26Z
[ "python" ]
When I type "python" and return in shell, the following lines will come out: ``` Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. ``` How to surpress these lines please?
An easy way is to call Python as `python -i -c ""`. This will also disable any start-up scripts, though. If you have a start-up script, you can also use `python -i ~/.pythonrc.py` (or however that script is named).
sqlalchemy tutorial example not working
9,449,840
12
2012-02-26T01:51:25Z
9,451,373
23
2012-02-26T07:34:19Z
[ "python", "sqlalchemy" ]
I'm trying to work my way through the example given in the [sqlalchemy tutorial](http://docs.sqlalchemy.org/en/latest/orm/tutorial.html) but I'm getting errors. As far as I can tell I'm following the example to the letter. Here's the code that I have from it so far. It fails when I `.first()` after I query the DB. I'm...
You are getting this error because database is missing the table structure (you apparently missed this line in the tutorial, it's in the **Declare Mapping** subsection). Create the schema by adding following just after your table/model definitions: ``` Class User(Base) ... # Initialize database schema (create tab...
Django and models with multiple foreign keys
9,449,882
3
2012-02-26T02:00:00Z
9,450,491
11
2012-02-26T04:14:58Z
[ "python", "django", "django-models", "django-templates", "django-views" ]
I am new to Django and I've been impressed so far by its capabilities. I am playing with more complex models and I am have problem to use them properly. Using Django 1.3, I am trying to write a summary page which would present the three models below with the following structure. In other words, a list of trips with the...
There is plenty of room for improvement. By using through on ManyToManyField you can explicitly define the join table, which we can conveniently consider as a single visit to a city during a particular trip. During that visit we had activities, so activity should have a foreignkey to a visit. For each foreignkey in a ...
how does list(string) split the string to an array of characters in python?
9,450,042
5
2012-02-26T02:36:59Z
9,450,053
7
2012-02-26T02:39:16Z
[ "python" ]
``` a = "Stack" aList = list(a) ``` This gives me an array like this `['S','t',a','c','k']` I want to know how this `list(string)` function works!
A string is an iterable type. For example, if you do this: ``` for c in 'string': print c ``` You get ``` s t r i n g ``` So passing a string to `list` just iterates over the characters in the string, and places each one in the list.
How do I use a C-style for loop in Python?
9,450,446
10
2012-02-26T04:06:24Z
9,450,469
18
2012-02-26T04:10:13Z
[ "python" ]
I want to use the traditional C-style for loop in python. I want to loop through characters of a string, but also know what it is, and be able to jump through characters (eg i = 5 somewhere in the code). for with range doesn't give me the flexibility of an actual for loop.
In `C`: ``` for(int i=0; i<9; i+=2) { dosomething(i); } ``` In `python3`: ``` for i in range(0, 9, 2): dosomething(i) ``` You just express the same idea in different languages.
How do I use a C-style for loop in Python?
9,450,446
10
2012-02-26T04:06:24Z
9,450,760
8
2012-02-26T05:17:24Z
[ "python" ]
I want to use the traditional C-style for loop in python. I want to loop through characters of a string, but also know what it is, and be able to jump through characters (eg i = 5 somewhere in the code). for with range doesn't give me the flexibility of an actual for loop.
The simple answer is that there is no simple, precise equivalent of C's `for` statement in Python. Other answers covered using a Python `for` statement with a range. If you want to be able to modify the loop variable in the loop (and have it affect subsequent iterations), you have to use a `while` loop: ``` i = 0 whil...
Positional argument v.s. keyword argument
9,450,656
14
2012-02-26T04:56:37Z
9,450,673
35
2012-02-26T04:59:57Z
[ "python" ]
Based on [this](http://infohost.nmt.edu/tcc/help/pubs/python/web/def.html) > A positional argument is a name that is not followed by an equal sign > (=) and default value. > > A keyword argument is followed by an equal sign and an expression that > gives its default value. ``` def rectangleArea(width, height): re...
That text you quote is for the *definition* of the function and has nothing to do with calls to the function. In the *call* to that function, you're using the "named argument" feature. That link you provide is not a very good quality one, the authors seem confused between two different things. The Python reference ref...
Does pypy handle threads and sockets quickly compared to hand written C?
9,450,812
7
2012-02-26T05:29:37Z
9,857,904
11
2012-03-25T04:22:39Z
[ "python", "c", "multithreading", "sockets", "pypy" ]
Does pypy handle threads and sockets quickly compared to hand written C? Compared to normal python? I would just try it, but the python code in question was written for a small cluster of computers on which I am not an admin. I'm asking here because my attempts to google only provided comparisons to cython, unladen sw...
> Does pypy handle threads and sockets quickly compared to hand written C? No. It's usually the same or worse. PyPy retains the Global Interpreter Lock (GIL) that CPython has. This means native threads cannot run Python code in parallel. Python threads also have additional semantics that come at a cost. Much synchron...
python class initialization
9,451,142
2
2012-02-26T06:43:43Z
9,451,158
7
2012-02-26T06:46:47Z
[ "python", "class", "initialization" ]
Folks, I am wondering if the following two definitions of the node class are the same or not? ``` class node: left = None right= None def __init__(self, data): self.data = data class node: def __init__(self, data): self.data = data self.left = None self.right= None ``...
No, they are not the same. In the second definition, `node.left` and `node.right` don't exist. The `right` and `left` attributes would only exist on an initialized instance of the class. However, in the first definition, you can access `node.left` and `node.right` directly on the class; you don't have to instantiate i...
Customize x-axis in matplotlib
9,451,395
12
2012-02-26T07:37:22Z
9,456,046
31
2012-02-26T18:51:57Z
[ "python", "matplotlib" ]
In the figure below, each unit in the x-axis represents a 10mins interval. I would like to customize the labels of x-axis, so that it shows hours, i.e. it displays a ticker every 6 units (60mins). I am new to matplotlib. Could someone help me? Thanks~ ![enter image description here](http://i.stack.imgur.com/p0UGC.png) ...
There's more than one way to do this. Let's start out with an example plot: ``` import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np # Generate some data... x, y = np.mgrid[:141, :101] z = np.cos(np.hypot(x, y)) # Plot the figure... plt.pcolormesh(x, y, z, cmap=mpl.cm.Reds) plt.show() ``` !...
Base language of python
9,451,929
11
2012-02-26T09:23:18Z
9,451,956
10
2012-02-26T09:27:16Z
[ "python", "python-3.x", "python-2.7" ]
What is the base language python written in? Actually I did a google search but not found any satisfying result.
The sources are [public](http://hg.python.org/cpython/). Python is written in C (actually the default implementation is called CPython).
Base language of python
9,451,929
11
2012-02-26T09:23:18Z
9,452,128
8
2012-02-26T09:55:12Z
[ "python", "python-3.x", "python-2.7" ]
What is the base language python written in? Actually I did a google search but not found any satisfying result.
[Python](http://docs.python.org/reference/index.html) is written in English. But there are several implementations: * [PyPy](http://pypy.org/) (written in Python) * [CPython](http://python.org/) (written in C) * [IronPython](http://ironpython.net/) (written in C#) * [Jython](http://www.jython.org/) (written in Java)
Base language of python
9,451,929
11
2012-02-26T09:23:18Z
9,452,140
33
2012-02-26T09:56:39Z
[ "python", "python-3.x", "python-2.7" ]
What is the base language python written in? Actually I did a google search but not found any satisfying result.
You can't say that Python is written in some programming language, since Python as a language is just a set of rules (like syntax rules, or descriptions of standard functionality). So we might say, that it is written in English :). However, mentioned rules can be implemented in some programming language. Hence, if you ...
How to use string.replace() in python 3.x
9,452,108
32
2012-02-26T09:50:20Z
9,452,120
35
2012-02-26T09:53:27Z
[ "python", "python-3.x" ]
The string.replace() is deprecated on python 3.x. What is the new way of doing this?
`replace()` is a method of `<class 'str'>` in python3: ``` >>> 'hello, world'.replace(',', ':') 'hello: world' ```
How to use string.replace() in python 3.x
9,452,108
32
2012-02-26T09:50:20Z
9,452,122
26
2012-02-26T09:53:43Z
[ "python", "python-3.x" ]
The string.replace() is deprecated on python 3.x. What is the new way of doing this?
As in 2.x, use `str.replace()`.
Numpy->Cython conversion: Compile error:Cannot convert 'npy_intp *' to Python object
9,452,427
10
2012-02-26T10:39:17Z
9,456,949
11
2012-02-26T20:41:06Z
[ "python", "numpy", "scipy", "python-2.7", "cython" ]
I have the following code that is to be propperly converted to cython: ``` from numpy import * ## returns winning players or [] if undecided. def score(board): scores = [] checked = zeros(board.shape) for i in xrange(len(board)): for j in xrange(len(board)): if checked[i,j] == 0 and b...
I don't think tuple unpacking works in Cython like it does in Python. You have to specify the size of `checked` using `(board.shape[0], board.shape[1])`. You also need to specify the datatype of `checked`. By default `np.zeros` returns a `float64`. You need to change that to an `int32` to be compatible with the declar...
Why does Python have an __ne__ operator method instead of just __eq__?
9,452,536
29
2012-02-26T11:01:14Z
9,455,185
25
2012-02-26T17:09:32Z
[ "python", "operator-overloading" ]
The answer [here](http://stackoverflow.com/questions/4352244/python-implementing-ne-operator-based-on-eq) gives a handwaving reference to cases where you'd want `__ne__` to return something other than just the logical inverse of `__eq__`, but I can't imagine any such case. Any examples?
Some libraries do fancy things and don't return a bool from these operations. For example, with numpy: ``` >>> import numpy as np >>> np.array([1,2,5,4,3,4,5,4,4])==4 array([False, False, False, True, False, True, False, True, True], dtype=bool) >>> np.array([1,2,5,4,3,4,5,4,4])!=4 array([ True, True, True, Fals...
Why does Python have an __ne__ operator method instead of just __eq__?
9,452,536
29
2012-02-26T11:01:14Z
9,455,214
23
2012-02-26T17:12:17Z
[ "python", "operator-overloading" ]
The answer [here](http://stackoverflow.com/questions/4352244/python-implementing-ne-operator-based-on-eq) gives a handwaving reference to cases where you'd want `__ne__` to return something other than just the logical inverse of `__eq__`, but I can't imagine any such case. Any examples?
SQLAlchemy is a great example. For the uninitiated, SQLAlchemy is a ORM and uses Python expression to generate SQL statements. In a expression such as ``` meta.Session.query(model.Theme).filter(model.Theme.id == model.Vote.post_id) ``` the `model.Theme.id == model.VoteWarn.post_id` does not return a boolean, but a ob...
Why does Python have an __ne__ operator method instead of just __eq__?
9,452,536
29
2012-02-26T11:01:14Z
9,455,635
7
2012-02-26T18:04:06Z
[ "python", "operator-overloading" ]
The answer [here](http://stackoverflow.com/questions/4352244/python-implementing-ne-operator-based-on-eq) gives a handwaving reference to cases where you'd want `__ne__` to return something other than just the logical inverse of `__eq__`, but I can't imagine any such case. Any examples?
More generally, in [many valued logic](http://en.wikipedia.org/wiki/Many-valued_logic) systems, `equals` and `not equals` are not necessarily exact inverses of each other. The obvious example is SQL where `True == True`, `False == False` and `Null != Null`. Although I don't know if there are any specific Python exampl...
Converting numpy dtypes to native python types
9,452,775
57
2012-02-26T11:40:11Z
9,453,240
7
2012-02-26T12:55:26Z
[ "python", "numpy" ]
If I have a numpy dtype, how do I automatically convert it to its closest python data type? For example, ``` numpy.float32 -> "python float" numpy.float64 -> "python float" numpy.uint32 -> "python int" numpy.int16 -> "python int" ``` I could try to come up with a mapping of all of these cases, but does numpy provi...
How about: ``` In [51]: dict([(d, type(np.zeros(1,d).tolist()[0])) for d in (np.float32,np.float64,np.uint32, np.int16)]) Out[51]: {<type 'numpy.int16'>: <type 'int'>, <type 'numpy.uint32'>: <type 'long'>, <type 'numpy.float32'>: <type 'float'>, <type 'numpy.float64'>: <type 'float'>} ```
Converting numpy dtypes to native python types
9,452,775
57
2012-02-26T11:40:11Z
11,389,998
76
2012-07-09T06:27:00Z
[ "python", "numpy" ]
If I have a numpy dtype, how do I automatically convert it to its closest python data type? For example, ``` numpy.float32 -> "python float" numpy.float64 -> "python float" numpy.uint32 -> "python int" numpy.int16 -> "python int" ``` I could try to come up with a mapping of all of these cases, but does numpy provi...
Use either [`a.item()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.item.html) or [`np.asscalar(a)`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.asscalar.html) to convert most NumPy values to a native Python type: ``` import numpy as np # examples using a.item() type(np.float32(0).i...
Alternative to python string item assignment
9,453,820
17
2012-02-26T14:18:00Z
9,453,840
22
2012-02-26T14:19:44Z
[ "python", "string" ]
What is the best / correct way to use item assignment for python string ? i.e `s = "ABCDEFGH"` `s[1] = 'a'` `s[-1]='b'` ? Normal way will throw : `'str' object does not support item assignment`
Strings are immutable. That means you can't assign to them at all. You could use formatting: ``` >>> s = 'abc{0}efg'.format('d') >>> s 'abcdefg' ``` Or concatenation: ``` >>> s = 'abc' + 'd' + 'efg' >>> s 'abcdefg' ``` Or replacement (thanks Odomontois for reminding me): ``` >>> s = 'abc0efg' >>> s.replace('0', 'd...
easy_install lxml on Python 2.7 on Windows
9,453,986
22
2012-02-26T14:41:24Z
9,643,941
43
2012-03-10T04:30:15Z
[ "python", "lxml", "python-2.7", "setuptools", "easy-install" ]
I'm using python 2.7 on Windows. How come the following error occurs when I try to install [lxml][1] using [setuptools][2]'s easy\_install? ``` C:\>easy_install lxml Searching for lxml Reading http://pypi.python.org/simple/lxml/ Reading http://codespeak.net/lxml Best match: lxml 2.3.3 Downloading http://lxml.de/files/...
**lxml >= 3.x.x** 1. download one of the MS Windows Installer packages 2. `easy_install "c:/lxml_installer.exe"` [(credit kobejohn)](https://stackoverflow.com/questions/9453986/easy-install-lxml-on-python-2-7-on-windows#comment19604831_9819303) MS Windows Installer [downloads available for lxml 3.3.5](https://pypi.py...
easy_install lxml on Python 2.7 on Windows
9,453,986
22
2012-02-26T14:41:24Z
9,819,303
25
2012-03-22T09:18:06Z
[ "python", "lxml", "python-2.7", "setuptools", "easy-install" ]
I'm using python 2.7 on Windows. How come the following error occurs when I try to install [lxml][1] using [setuptools][2]'s easy\_install? ``` C:\>easy_install lxml Searching for lxml Reading http://pypi.python.org/simple/lxml/ Reading http://codespeak.net/lxml Best match: lxml 2.3.3 Downloading http://lxml.de/files/...
you can download Unofficial Windows Binaries at: <http://www.lfd.uci.edu/~gohlke/pythonlibs/> e.g. for python 2.7 32bit: <http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml> It is the easiest way in win32.
easy_install lxml on Python 2.7 on Windows
9,453,986
22
2012-02-26T14:41:24Z
18,511,963
8
2013-08-29T13:09:53Z
[ "python", "lxml", "python-2.7", "setuptools", "easy-install" ]
I'm using python 2.7 on Windows. How come the following error occurs when I try to install [lxml][1] using [setuptools][2]'s easy\_install? ``` C:\>easy_install lxml Searching for lxml Reading http://pypi.python.org/simple/lxml/ Reading http://codespeak.net/lxml Best match: lxml 2.3.3 Downloading http://lxml.de/files/...
I ran into the same problem. I don't know about the vcvarsall.bat issue but if you just want to install lxml you can use the graphical installers here: <https://pypi.python.org/pypi/lxml/3.2.3> That worked for me.
Python: multidimensional dict
9,454,179
2
2012-02-26T15:08:32Z
9,454,218
7
2012-02-26T15:14:14Z
[ "python", "data-structures", "multidimensional-array" ]
I ran several times an application with different input parameters in order to collect execution times. The input parameters are 6: `v`, `n`, `m`, `b`, `p` and `c`. Conceptually I can think of my results as a multidimensional array, where any dimension is a different parameter: `times[A][B][C][D][E][F]` would contain...
First, if you have to use a dictionary, why not just create a single dictionary, using tuples to index it? Second, use `itertools.product` to avoid troublesome nested loops: ``` >>> import itertools >>> d = {} >>> for tup in itertools.product(range(5), repeat=2): ... d[tup] = tup ... >>> d {(1, 3): (1, 3), (3, 0)...
save time zone in Django Models
9,454,212
6
2012-02-26T15:13:52Z
9,454,369
9
2012-02-26T15:36:34Z
[ "python", "django", "django-models", "timezone" ]
I am creating a form in Django. I have to put a input type field, which only stores the timezone in database(which will be chosen by a user from a drop Down list at form). I am not able to find out any approach to create this timezone model and how it will return the local time according to saved timezone. I choose fol...
Neither django nor python provide a set of timezones for you to use. For that, you will need an additional module like `pytz`. You can get a list of all timezones like this: ``` >>> import pytz >>> pytz.all_timezones ['Africa/Abidjan', 'Africa/Accra', 'Africa/Addis_Ababa', 'Africa/Algiers', 'Africa/Asmara', 'Africa/A...
save time zone in Django Models
9,454,212
6
2012-02-26T15:13:52Z
18,448,373
7
2013-08-26T16:10:32Z
[ "python", "django", "django-models", "timezone" ]
I am creating a form in Django. I have to put a input type field, which only stores the timezone in database(which will be chosen by a user from a drop Down list at form). I am not able to find out any approach to create this timezone model and how it will return the local time according to saved timezone. I choose fol...
[django-timezone-field](https://github.com/mfogel/django-timezone-field) is an app that handles this nicely.
How do I build a dict using list comprehension?
9,454,619
3
2012-02-26T16:07:09Z
9,454,637
10
2012-02-26T16:09:11Z
[ "python" ]
How do I build a dict using list comprehension? I have two lists. ``` series = [1,2,3,4,5] categories = ['A', 'B', 'A', 'C','B'] ``` I want to build a dict where the categories are the keys. Thanks for your answers I'm looking to produce: ``` {'A' : [1, 3], 'B' : [2, 5], 'C' : [4]} ``` Because the keys can't e...
You have to have a list of tuples. The tuples are key/value pairs. You don't need a comprehension in this case, just zip: ``` dict(zip(categories, series)) ``` Produces `{'A': 3, 'B': 5, 'C': 4}` (as pointed out by comments) Edit: After looking at the keys, note that you can't have duplicate keys in a dictionary. So...
Python define method outside of class definition?
9,455,111
21
2012-02-26T17:02:41Z
9,455,442
33
2012-02-26T17:41:15Z
[ "python", "class", "methods" ]
``` class MyClass: def myFunc(self): pass ``` Can I create MyFunc outisde of the class definition? Maybe even in another module?
Yes. You can define a function outside of a class and then use it in the class body as a method: ``` def func(self): print "func" class MyClass(object): myMethod = func ``` You can also add a function to a class after it has been defined: ``` class MyClass(object): pass def func(self): print "func"...
Python: How to allow duplicates in a set?
9,455,750
2
2012-02-26T18:16:19Z
9,455,773
8
2012-02-26T18:19:03Z
[ "python", "set", "duplicates" ]
I ran into a problem regarding set in Python 2.7. Here's the appropriate example code block: ``` letters = set(str(raw_input("Type letters: "))) ``` As you can see, the point is to write some letters to assign to "letters" for later use. But if I type "aaabbcdd", the output of "letters" returns ``` set(['a', 'c', '...
`set` doesn't store duplicates, which is why it's called a [set](https://en.wikipedia.org/wiki/Set_%28mathematics%29). You should use an ordinary `str` or `list` and sort it if necessary. ``` >>> sorted(raw_input("Type letters: ")) Type letters: foobar ['a', 'b', 'f', 'o', 'o', 'r'] ``` An alternative (but overkill f...
Scipy/Numpy FFT Frequency Analysis
9,456,037
30
2012-02-26T18:50:58Z
9,458,803
44
2012-02-27T00:50:59Z
[ "python", "numpy", "scipy" ]
I'm looking for how to turn the frequency axis in a fft (taken via scipy.fftpack.fftfreq) into a frequency in Hertz, rather than bins or fractional bins. I tried to code below to test out the FFT: ``` t = scipy.linspace(0,120,4000) acc = lambda t: 10*scipy.sin(2*pi*2.0*t) + 5*scipy.sin(2*pi*8.0*t) + 2*scipy.random.ra...
I think you don't need to do fftshift(), and you can pass sampling period to fftfreq(): ``` import scipy import scipy.fftpack import pylab from scipy import pi t = scipy.linspace(0,120,4000) acc = lambda t: 10*scipy.sin(2*pi*2.0*t) + 5*scipy.sin(2*pi*8.0*t) + 2*scipy.random.random(len(t)) signal = acc(t) FFT = abs(s...
Scipy/Numpy FFT Frequency Analysis
9,456,037
30
2012-02-26T18:50:58Z
9,460,151
11
2012-02-27T04:41:07Z
[ "python", "numpy", "scipy" ]
I'm looking for how to turn the frequency axis in a fft (taken via scipy.fftpack.fftfreq) into a frequency in Hertz, rather than bins or fractional bins. I tried to code below to test out the FFT: ``` t = scipy.linspace(0,120,4000) acc = lambda t: 10*scipy.sin(2*pi*2.0*t) + 5*scipy.sin(2*pi*8.0*t) + 2*scipy.random.ra...
**[scipy.fftpack.fftfreq(n, d)](http://docs.scipy.org/doc/scipy/reference/generated/scipy.fftpack.fftfreq.html#scipy.fftpack.fftfreq)** gives you the frequencies directly. If you set `d=1/33.34`, this will tell you the frequency in Hz for each point of the fft.
Easy way to suppress output of fabric run?
9,456,419
17
2012-02-26T19:32:33Z
9,621,835
22
2012-03-08T17:12:19Z
[ "python", "fabric" ]
I am running a command on the remote machine: ``` remote_output = run('mysqldump --no-data --user=username --password={0} database'.format(password)) ``` I would like to capture the output, but not have it all printed to the screen. What's the easiest way to do this?
It sounds like [Managing output](http://docs.fabfile.org/en/1.4.0/usage/output_controls.html) section is what you're looking for. To hide the output from the console, try something like this: ``` from __future__ import with_statement from fabric.api import hide, run, get with hide('output'): run('mysqldump --no-...
Easy way to suppress output of fabric run?
9,456,419
17
2012-02-26T19:32:33Z
17,250,300
11
2013-06-22T11:36:35Z
[ "python", "fabric" ]
I am running a command on the remote machine: ``` remote_output = run('mysqldump --no-data --user=username --password={0} database'.format(password)) ``` I would like to capture the output, but not have it all printed to the screen. What's the easiest way to do this?
Try this if you want to hide everything from log and avoid fabric throwing exceptions when command fails: ``` from __future__ import with_statement from fabric.api import env,run,hide,settings env.host_string = 'username@servernameorip' env.key_filename = '/path/to/key.pem' def exec_remote_cmd(cmd): with hide('o...
How can I close the browser window without closing the browser?
9,456,739
3
2012-02-26T20:13:55Z
9,460,078
9
2012-02-27T04:28:37Z
[ "python", "webdriver" ]
How can I close the browser window without closing the browser in webdriver? I have something like ``` from selenium import webdriver driver = webdriver.Firefox() driver.get("http://www.google.com") # so far so good driver.close() # quits the app altogether :( driver.get("http://www.google.com") # doesn't do anythin...
Use `driver.get("");` instead of `driver.close();`.
what does .dtype do?
9,457,037
9
2012-02-26T20:52:19Z
9,457,302
28
2012-02-26T21:24:20Z
[ "python", "numpy" ]
I am new to Python, and don't understand what .dtype does. For example: ``` >>> aa array([1, 2, 3, 4, 5, 6, 7, 8]) >>> aa.dtype = "float64" >>> aa array([ 4.24399158e-314, 8.48798317e-314, 1.27319747e-313, 1.69759663e-313]) ``` I thought dtype is a property of aa, which should be int, and if I assign aa.dty...
First off, the code you're learning from is flawed. It almost certainly doesn't do what the original author thought it did based on the comments in the code. What the author probably meant was this: ``` def to_1d(array): """prepares an array into a 1d real vector""" return array.astype(np.float64).ravel() ```...
Python reuse regular expression
9,457,525
4
2012-02-26T21:52:16Z
9,457,554
8
2012-02-26T21:57:22Z
[ "python", "expression" ]
I have to match a text. Ej: ``` text = 'C:x=-10.25:y=340.1:z=1;' ``` Where the values after x,y or z accept values matched by: ``` -?\d{1,3}(\.\d{1,2})? ``` How can i reuse that? Those are the only values that are variables. All others characters must be fixed. I mean, they must be in that exact order. There is ...
Folks do this kind of thing sometimes ``` label_value = r'\w=-?\d{1,3}(\.\d{1,2})?' line = r'^C:{0}:{0}:{0};$'.format( label_value ) line_pat= re.compile( line ) ``` This is slightly smarter. ``` label_value = r'(\w)=(-?\d{1,3}(?:\.\d{1,2})?)' line = r'^C:{0}:{0}:{0};$'.format( label_value ) line_pat= re.compile( li...
Currying decorator in python
9,458,271
13
2012-02-26T23:21:49Z
9,458,386
21
2012-02-26T23:38:28Z
[ "python", "decorator", "currying" ]
I am trying to write a currying decorator in python, and I think I've got the general idea down, but still got some cases that aren't working right... ``` def curry(fun): cache = [] numargs = fun.func_code.co_argcount def new_fun(*args, **kargs): print args print kargs cache.exten...
The below implementation is naive, google for "currying python" for more accurate examples. ``` def curry(x, argc=None): if argc is None: argc = x.func_code.co_argcount def p(*a): if len(a) == argc: return x(*a) def q(*b): return x(*(a + b)) return curry(...
Assign value to an individual cell in a two dimensional python array
9,459,337
10
2012-02-27T02:26:49Z
9,459,343
24
2012-02-27T02:28:52Z
[ "python", "arrays", "list" ]
Let's say I have the following empty two dimensional array in Python: ``` q = [[None]*5]*4 ``` I want to assign a value of `5` to the first row in the first column of `q`. Instinctively, I do the following: ``` q[0][0] = 5 ``` However, this produces: ``` [[5, None, None, None, None], [5, None, None, None, None...
This doesn't do what you hoped. ``` q = [[None]*5]*4 ``` It reuses `list` objects multiple times. As you can see when you made a change to one cell, which was in a reused list object. A single list with a value of `[None]` is used five times. A single list with a value of `[[None]*5]` is used four times. ``` q = [...
How do I define a Python class that I can use with the with statement?
9,459,730
4
2012-02-27T03:35:50Z
9,459,771
8
2012-02-27T03:42:47Z
[ "python" ]
I understand that `StringIO` acts like a file object, duck-typing what you would get from `open('somefile.txt')`. Now I want to use `StringIO` with the `with` statement: ``` with StringIO('some string') as fh: # fh as in "file handle" data = [stuff from stuff in fh.read()] ``` But Python complains that type `Str...
You need to write a [context manager](http://docs.python.org/library/stdtypes.html#context-manager-types). If you don't want to write the whole protocol, there's a simplified way around it using the [contextlib.contextmanager](http://docs.python.org/library/contextlib.html#module-contextlib) decorator.
Find words and combinations of words that can be spoken the quickest
9,459,745
12
2012-02-27T03:38:07Z
9,464,413
7
2012-02-27T11:41:02Z
[ "python", "algorithm", "word", "nlp", "linguistics" ]
I'm a big fan of discovering sentences that can be rapped very quickly. For example, "gotta read a little bit of Wikipedia" or "don't wanna wind up in the gutter with a bottle of malt." (George Watsky) I wanted to write a program in Python that would enable me to find words (or combinations of words) that can be artic...
This is just a stab in the dark as I'm not a linguist (although, I have written a voice synthesizer), the metric that be useful here is the number of [phonemes](http://en.wikipedia.org/wiki/Phoneme) that make up each word, since the phonemes themselves are going to be the same approximate duration regardless of use. Th...
format string syntax: printing percentage with at least one significant digit
9,461,065
3
2012-02-27T06:46:40Z
9,461,560
9
2012-02-27T07:46:44Z
[ "python", "formatting", "python-3.x" ]
I want to format a number as a percent, with at least 2 digits after the decimal point; and in addition, with at least one significant digit. For example, I want 0.123456 to look like '12.34%'; and 0.00000123456 to look like '0.0001%'. Is there a simple way to achieve that? The reason is that my standard output shou...
``` import math def format_percent(x, at_least=2): return '{1:.{0}%}'.format(max(at_least, int(-math.log10(x))-1), x) for x in (1., .1, .123456, .0123, .00123, .000123, .0000123, .00000123): print x, format_percent(x, 2) 1.0 100.00% 0.1 10.00% 0.123456 12.35% 0.0123 1.23% 0.00123 0.12% 0.000123 0.01% 1.23e...
string.upper(<str>) and <str>.upper() won't execute
9,461,071
2
2012-02-27T06:47:37Z
9,461,082
7
2012-02-27T06:48:44Z
[ "python", "string", "operation" ]
I have the following bit of code: ``` def test(): fragment = '' fragment = raw_input('Enter input') while fragment not in string.ascii_letters: fragment = raw_input('Invalid character entered, try again: ') fragment.upper() print fragment*3 ``` However when I run it, say for an input value...
You're not realizing that strings in Python are immutable and that string methods and operations return new strings. ``` >>> print 'ppp'.upper() PPP ```
string.upper(<str>) and <str>.upper() won't execute
9,461,071
2
2012-02-27T06:47:37Z
9,461,187
10
2012-02-27T07:04:45Z
[ "python", "string", "operation" ]
I have the following bit of code: ``` def test(): fragment = '' fragment = raw_input('Enter input') while fragment not in string.ascii_letters: fragment = raw_input('Invalid character entered, try again: ') fragment.upper() print fragment*3 ``` However when I run it, say for an input value...
Strings are [immutable](http://en.wikipedia.org/wiki/Immutable_object). So functions like `str.upper()` will not modify `str` but return a new string. ``` >>> name = "xyz" >>> name.upper() 'XYZ' >>> print name xyz # Notice that it's still in lower case. >>> name_upper = name.upper() >>> print name_upper XYZ ``` So i...
Import Error: No module named django
9,462,212
9
2012-02-27T08:48:15Z
9,462,280
10
2012-02-27T08:53:51Z
[ "python", "django", "centos", "pythonpath" ]
I am using centos linux. I had python 2.6 with django and now i upgraded to python 2.7. Python 2.6 is located in /usr/lib/python2.6. Python 2.7 is located in /usr/local/lib/python2.7. They both have site-packages directory and they both contain django 1.2. If i run python i get the 2.7 version. My problem is ...
To check your path, you can use the following code: ``` import sys print sys.path ``` If you already know where django is installed, it should be easy to test if the desired directory is in your path with `directory in sys.path`. Regarding where your `PYTHONPATH` is defined. Note that it's an environment variable, s...
Import Error: No module named django
9,462,212
9
2012-02-27T08:48:15Z
9,462,309
7
2012-02-27T08:56:57Z
[ "python", "django", "centos", "pythonpath" ]
I am using centos linux. I had python 2.6 with django and now i upgraded to python 2.7. Python 2.6 is located in /usr/lib/python2.6. Python 2.7 is located in /usr/local/lib/python2.7. They both have site-packages directory and they both contain django 1.2. If i run python i get the 2.7 version. My problem is ...
Try printing `sys.path` to see what's in your path. Django need to be in one of the dirs listed. Example on Windows: ``` >>> import sys >>> for p in sys.path: print p C:\Python27\Lib\idlelib C:\Windows\system32\python27.zip C:\Python27\DLLs C:\Python27\lib C:\Python27\lib\plat-win C:\Python27\lib\lib-tk C:\Python27 C...
Import Error: No module named django
9,462,212
9
2012-02-27T08:48:15Z
9,462,426
11
2012-02-27T09:08:05Z
[ "python", "django", "centos", "pythonpath" ]
I am using centos linux. I had python 2.6 with django and now i upgraded to python 2.7. Python 2.6 is located in /usr/lib/python2.6. Python 2.7 is located in /usr/local/lib/python2.7. They both have site-packages directory and they both contain django 1.2. If i run python i get the 2.7 version. My problem is ...
Under linux, you can set the PYTHONPATH environment variable in your .profile or .bashrc. You can either edit it directly from the terminal by changing to your home directory (cd ~), and then edit the file (nano .bashrc), or by opening the file with gtkedit or vim or whatever, and add: ``` PYTHONPATH=/usr/local/lib/py...
is there a library for parsing US addresses?
9,463,471
12
2012-02-27T10:29:35Z
9,463,609
15
2012-02-27T10:39:50Z
[ "python", "parsing", "street-address" ]
I have a list of US addresses I need to break into city,state, zip code,state etc. example address : "16100 Sand Canyon Avenue, Suite 380 Irvine, CA 92618" Does anyone know of a library or a free API to do this? Google/Yahoo geocoder is forbidden to use by the TOS for commercial projects.. It would be awesome to fin...
`Pyparsing` has a bunch of functionality for parsing street addresses, check out an example for this here: <http://pyparsing.wikispaces.com/file/view/streetAddressParser.py>
is there a library for parsing US addresses?
9,463,471
12
2012-02-27T10:29:35Z
16,973,022
8
2013-06-06T22:05:50Z
[ "python", "parsing", "street-address" ]
I have a list of US addresses I need to break into city,state, zip code,state etc. example address : "16100 Sand Canyon Avenue, Suite 380 Irvine, CA 92618" Does anyone know of a library or a free API to do this? Google/Yahoo geocoder is forbidden to use by the TOS for commercial projects.. It would be awesome to fin...
Check out this Python Package: <https://github.com/SwoopSearch/pyaddress> It also allows flexibility if you know enough details about the addresses to be parsed.
is there a library for parsing US addresses?
9,463,471
12
2012-02-27T10:29:35Z
28,912,552
10
2015-03-07T07:32:17Z
[ "python", "parsing", "street-address" ]
I have a list of US addresses I need to break into city,state, zip code,state etc. example address : "16100 Sand Canyon Avenue, Suite 380 Irvine, CA 92618" Does anyone know of a library or a free API to do this? Google/Yahoo geocoder is forbidden to use by the TOS for commercial projects.. It would be awesome to fin...
Quite a few of these answers are a few years old now. The most bulletproof library I've seen recently is `usaddress`: <https://github.com/datamade/usaddress>: * Far more accurate than `address` which we'd been using for a year now <https://pypi.python.org/pypi/address/0.1.1>. * Yet to see it fail on an address * Stil...
Python - Twisted, Proxy and modifying content
9,465,236
15
2012-02-27T12:45:04Z
9,469,400
14
2012-02-27T17:30:58Z
[ "python", "proxy", "twisted" ]
So i've looked around at a few things involving writting an HTTP Proxy using python and the Twisted framework. Essentially, like some other questions, I'd like to be able to modify the data that will be sent back to the browser. That is, the browser requests a resource and the proxy will fetch it. Before the resource ...
To create `ProxyFactory` that can modify server response headers, content you could override [`ProxyClient.handle*()` methods](http://twistedmatrix.com/trac/browser/trunk/twisted/web/proxy.py#L62): ``` from twisted.python import log from twisted.web import http, proxy class ProxyClient(proxy.ProxyClient): """Mang...
Python creating multiple instances for a single object/class
9,467,604
2
2012-02-27T15:30:17Z
9,467,833
9
2012-02-27T15:44:43Z
[ "python", "class", "object", "instance" ]
I'm using Python. I've read a bit about this and can't seem to wrap my mind around it. What I want to do is have a class called Potions with various potion objects in it. For now there's one potion, a simple HealthPotion. I want potions to be stackable in inventories and shop stocks. So I need an instance of the potion...
I think you may have a slightly misguided concept of how classes and instances work. It might make more sense if you think about people instead. Suppose we want to model people in our class hierarchy. For now, a person has to have a name, and if you ask them to speak they say their name: ``` class Person(object): ...
Look how to fix column calculation in Python readline if use color prompt
9,468,435
13
2012-02-27T16:24:55Z
9,468,954
19
2012-02-27T16:59:01Z
[ "python", "terminal", "interpreter", "readline" ]
I use standard tips for customizing interactive Python session: ``` $ cat ~/.bashrc export PYTHONSTARTUP=~/.pystartup $ cat ~/.pystartup import os import sys import atexit import readline import rlcompleter historyPath = os.path.expanduser("~/.pyhistory") def save_history(historyPath=historyPath): import re...
I open **info readline** and found: ``` -- Function: int rl_expand_prompt (char *prompt) Expand any special character sequences in PROMPT and set up the local Readline prompt redisplay variables. This function is called by `readline()'. It may also be called to expand the primary prompt if the `...
Changing edge attributes in networkx multigraph
9,469,515
7
2012-02-27T17:38:41Z
9,469,733
12
2012-02-27T17:53:34Z
[ "python", "networkx" ]
In a multigraph each call to \*add\_edge(a,b,weight=1)\* will add a new edge between nodes *a* and *b*. When building the graph, is it possible to modify this weight when *a* and *b* are found again. Right now I make a check to find whether (a, b) or (b, a) are connected, then have to *delete* the edge, and *add* a new...
The [Multigraph.add\_edge](http://networkx.lanl.gov/reference/generated/networkx.MultiGraph.add_edge.html) documentation indicates that you should use the `key` argument to uniquely identify edges in a multigraph. Here's an example: ``` >>> import networkx as nx >>> G = nx.MultiGraph() >>> G.add_edge(1, 2, key='xyz', ...
Windows: Slow application start
9,469,932
12
2012-02-27T18:08:44Z
9,470,393
7
2012-02-27T18:42:00Z
[ "python", "windows", "performance", "pyinstaller" ]
I have an application written in Python and 'compiled' with PyInstaller. It also uses PyQt for the GUI framework. Running this application has a delay of about 10 seconds before the main window loads and is shown. As far as I can tell, this is not due to slowness in my code. Instead, I suspect this is due to the Pytho...
I suspect that you're using pyinstaller's "one file" mode -- this mode means that it has to unpack all of the libraries to a temporary directory before the app can start. In the case of Qt, these libraries are quite large and take a few seconds to decompress. Try using the "one directory" mode and see if that helps?
Windows: Slow application start
9,469,932
12
2012-02-27T18:08:44Z
9,474,575
10
2012-02-28T00:25:58Z
[ "python", "windows", "performance", "pyinstaller" ]
I have an application written in Python and 'compiled' with PyInstaller. It also uses PyQt for the GUI framework. Running this application has a delay of about 10 seconds before the main window loads and is shown. As far as I can tell, this is not due to slowness in my code. Instead, I suspect this is due to the Pytho...
Tell PyInstaller to create a console-mode executable. This gives you a working console you can use for debugging. At the top of your main script, even before the first import is run, add a print "Python Code starting". Then run your packaged executable from the command line. This way you can get a clear picture whethe...
Increase celery retry time each retry cycle
9,470,089
11
2012-02-27T18:20:17Z
9,470,129
7
2012-02-27T18:23:06Z
[ "python", "celery", "celeryd" ]
I do retries with celery like in the Docs-Example: ``` @task() def add(x, y): try: ... except Exception, exc: add.retry(exc=exc, countdown=60) # override the default and # retry in 1 minute ``` How can I increase the retry-countdown everytime the retr...
Keep a variable with your last retry time in it, and multiply it by 2 each time until it exceeds whatever level you want (or, keep a count if you prefer a certain number of times...)
Increase celery retry time each retry cycle
9,470,089
11
2012-02-27T18:20:17Z
23,015,275
16
2014-04-11T14:22:08Z
[ "python", "celery", "celeryd" ]
I do retries with celery like in the Docs-Example: ``` @task() def add(x, y): try: ... except Exception, exc: add.retry(exc=exc, countdown=60) # override the default and # retry in 1 minute ``` How can I increase the retry-countdown everytime the retr...
Here is a simple way to create bigger delay each time the task is evaluated. This value is updated by celery itself so you don't need to manage anything yourself. ``` @task() def add(x, y): try: ... except Exception as exc: raise add.retry(exc=exc, countdown=60 * add.request.retries) ``` Note:...
Remove string between 2 characters from text string
9,470,142
8
2012-02-27T18:24:11Z
9,470,225
10
2012-02-27T18:29:09Z
[ "python", "regex" ]
I have text string like: ``` "abcd[e]yth[ac]ytwec" ``` I need just ``` "abcdythytwec" ``` What is the easiest way to do it using regex or otherwise in python? I am using `.split('[')` method which is cumbersome.
``` In [11]: re.sub(r'\[.*?\]', '', 'abcd[e]yth[ac]ytwec') Out[11]: 'abcdythytwec' ```
Named dtype array: Difference between a[0]['name'] and a['name'][0]?
9,470,604
15
2012-02-27T18:58:33Z
10,645,505
7
2012-05-18T01:09:13Z
[ "python", "arrays", "numpy", "user-defined-types" ]
I came across the following oddity in numpy which may or may not be a bug: ``` import numpy as np dt = np.dtype([('tuple', (int, 2))]) a = np.zeros(3, dt) type(a['tuple'][0]) # ndarray type(a[0]['tuple']) # ndarray a['tuple'][0] = (1,2) # ok a[0]['tuple'] = (1,2) # ValueError: shape-mismatch on array construction...
I get a different error than you do (using numpy 1.7.0.dev): ``` ValueError: setting an array element with a sequence. ``` so the explanation below may not be correct for your system (or it could even be the wrong explanation for what I see). First, notice that indexing a row of a [structured array](http://docs.scip...
Named dtype array: Difference between a[0]['name'] and a['name'][0]?
9,470,604
15
2012-02-27T18:58:33Z
10,696,301
8
2012-05-22T05:42:40Z
[ "python", "arrays", "numpy", "user-defined-types" ]
I came across the following oddity in numpy which may or may not be a bug: ``` import numpy as np dt = np.dtype([('tuple', (int, 2))]) a = np.zeros(3, dt) type(a['tuple'][0]) # ndarray type(a[0]['tuple']) # ndarray a['tuple'][0] = (1,2) # ok a[0]['tuple'] = (1,2) # ValueError: shape-mismatch on array construction...
I asked that on the numpy-discussion list. Travis Oliphant answered [here](http://permalink.gmane.org/gmane.comp.python.numeric.general/50058). Citing his answer: > The short answer is that this is not really a "normal" bug, but it could be considered a "design" bug (although the issues may not be straightforward to ...
How to do an inverse `range`, i.e. create a compact range based on a set of numbers?
9,470,611
6
2012-02-27T18:59:04Z
9,471,386
10
2012-02-27T19:55:28Z
[ "python", "numbers", "range", "pcre" ]
Python has a `range` method, which allows for stuff like: ``` >>> range(1, 6) [1, 2, 3, 4, 5] ``` What I’m looking for is kind of the opposite: take a list of numbers, and return the start and end. ``` >>> magic([1, 2, 3, 4, 5]) [1, 5] # note: 5, not 6; this differs from `range()` ``` This is easy enough to do fo...
A nice trick to simplify the code is to look at the difference of each element of the sorted list and its index: ``` a = [4, 2, 1, 5] a.sort() print [x - i for i, x in enumerate(a)] ``` prints ``` [1, 1, 2, 2] ``` Each run of the same number corresponds to a run of consecutive numbers in `a`. We can now use `iterto...
How do I upgrade a dependency in a Python project on Heroku
9,471,017
10
2012-02-27T19:30:42Z
9,471,488
13
2012-02-27T20:04:43Z
[ "python", "heroku", "pip" ]
For my (Django) project on Heroku, I updated one of the dependencies in my requirements.txt file to a newer version, and now I want Heroku to upgrade the version installed. I tried: ``` heroku run "pip install -r requirements.txt --upgrade -E ." ``` Which spits the right output to the terminal, but apparently does no...
You should be able to upgrade it locally then re-run pip freeze. Within your requirements.txt the ==versionhere should be the version that installs each time you push. When you run heroku run, its run in an isolated dyno that it is upgraded on then destroyed. For the change to persist it must occur during git push to ...
Print the concatenation of the digits of two numbers in Python
9,472,410
4
2012-02-27T21:17:32Z
9,472,442
9
2012-02-27T21:19:23Z
[ "python", "python-3.x", "concatenation" ]
Is there a way to concat numbers in Python, lets say I have the code ``` print(2, 1) ``` I want it to print `21`, not `2 1`and if i use "+", it prints 3. Is there a way to do this?
Use the string formatting operator: ``` print "%d%d" % (2, 1) ``` EDIT: In Python 2.6+, you can also use the format() method of a string: ``` print("{0}{1}".format(2, 1)) ```
Print the concatenation of the digits of two numbers in Python
9,472,410
4
2012-02-27T21:17:32Z
9,472,448
8
2012-02-27T21:19:40Z
[ "python", "python-3.x", "concatenation" ]
Is there a way to concat numbers in Python, lets say I have the code ``` print(2, 1) ``` I want it to print `21`, not `2 1`and if i use "+", it prints 3. Is there a way to do this?
You could perhaps convert the integers to strings: ``` print(str(2)+str(1)) ```
Print the concatenation of the digits of two numbers in Python
9,472,410
4
2012-02-27T21:17:32Z
9,472,492
8
2012-02-27T21:23:51Z
[ "python", "python-3.x", "concatenation" ]
Is there a way to concat numbers in Python, lets say I have the code ``` print(2, 1) ``` I want it to print `21`, not `2 1`and if i use "+", it prints 3. Is there a way to do this?
You can change the separator used by the print function: ``` print(2, 1, sep="") ``` If you're using python2.x, you can use ``` from __future__ import print_function ``` at the top of the file.
Python: Reading CSV file and plotting a scatter
9,473,459
3
2012-02-27T22:35:31Z
9,473,504
9
2012-02-27T22:39:30Z
[ "python", "csv", "matplotlib", "scatter" ]
I've written a script to compute large csv files in dimensions: 27000 rows x 22 column. How can I read in the CSV file in order to use it in matplotlib in a scattered plot like the one in this thread? [axis range in scatter graphs](http://stackoverflow.com/questions/7376330/axis-range-in-scatter-graphs) The concept o...
Here is a quick solution ``` def getColumn(filename, column): results = csv.reader(open(filename), delimiter="\t") return [result[column] for result in results] ``` and then you can use it like this ``` time = getColumn("filename",0) volt = getColumn("filaname",1) plt.figure("Time/Volt") plt.xlabel("Time(ms...
How to break up a paragraph by sentences in Python
9,474,395
5
2012-02-28T00:06:14Z
9,474,645
16
2012-02-28T00:34:26Z
[ "python", "regex", "text-segmentation" ]
I need to parse sentences from a paragraph in Python. Is there an existing package to do this, or should I be trying to use regex here?
The [`nltk.tokenize`](http://nltk.github.com/api/nltk.tokenize.html) module is designed for this and handles edge cases. For example: ``` >>> from nltk import tokenize >>> p = "Good morning Dr. Adams. The patient is waiting for you in room number 3." >>> tokenize.sent_tokenize(p) ['Good morning Dr. Adams.', 'The patie...
Formatting SQLAlchemy code
9,474,397
12
2012-02-28T00:06:33Z
9,474,615
7
2012-02-28T00:30:36Z
[ "python", "formatting", "sqlalchemy", "pep8" ]
We're trying to follow the [PEP8](http://www.python.org/dev/peps/pep-0008/) guidelines for formatting our Python code and staying below 80 characters per line. Our SQLAlchemy lines are particularly troublesome, having lots of chained methods and tons of complex parameters, logic, and nested functions. Are there any p...
pep-8 discourages backslashes but for SQLAlchemy code I can't help but think they're the most readable, as you can keep each generative function at the start of its own line. If there's many arguments inside of parenthesis I'll break them out on individual lines too. ``` subkeyword = Session.query( S...
Formatting SQLAlchemy code
9,474,397
12
2012-02-28T00:06:33Z
18,969,989
17
2013-09-23T22:31:20Z
[ "python", "formatting", "sqlalchemy", "pep8" ]
We're trying to follow the [PEP8](http://www.python.org/dev/peps/pep-0008/) guidelines for formatting our Python code and staying below 80 characters per line. Our SQLAlchemy lines are particularly troublesome, having lots of chained methods and tons of complex parameters, logic, and nested functions. Are there any p...
Came here hoping for a better solution, but I think I prefer the parentheses wrapping style: ``` subkeyword = ( Session.query( Subkeyword.subkeyword_id, Subkeyword.subkeyword_word ) .filter_by(subkeyword_company_id=self.e_company_id) .filter_by(subkeyword_word=subkeyword_word) .fil...
Python alternative to reduce()
9,474,412
22
2012-02-28T00:07:39Z
9,474,435
17
2012-02-28T00:09:59Z
[ "python", "functional-programming" ]
There is a [semi-famous article written by Guido himself](http://www.artima.com/weblogs/viewpost.jsp?thread=98196) hinting that `reduce()` should go the way of the dodo and leave the language. It was even demoted from being a top-level function in Python 3 ([instead getting stuffed in the `functools` module](http://doc...
As Guido's linked article says, you should just write an explicit for loop if you want to avoid `reduce()`. You can replace the line ``` result = reduce(function, iterable, start) ``` by ``` result = start for x in iterable: result = function(result, x) ```
Reading an integer string in the form of xxx,yyy,zzz with python
9,474,761
3
2012-02-28T00:48:29Z
9,474,781
9
2012-02-28T00:50:49Z
[ "python", "string", "integer" ]
Is there a built in easy way to convert a string into an integer, with the format of the string being xxx,yyy,zzz? like 325,121,565 instead of 325121565. I know I can build a function that does that but I was wondering if someone else has already done so that I wont reinvent the wheel.
Set an appropriate locale, then use [`locale.atoi()`](http://docs.python.org/library/locale.html#locale.atoi). ``` >>> locale.setlocale(locale.LC_NUMERIC, 'en_US') 'en_US' >>> locale.atoi('123,456,789') 123456789 ```
Split python string every nth character?
9,475,241
146
2012-02-28T01:48:24Z
9,475,270
39
2012-02-28T01:53:25Z
[ "python" ]
> **Possible Duplicate:** > [What is the most “pythonic” way to iterate over a list in chunks?](http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks) Is it possible to split a python string every nth character? For example, suppose I have a string containing the f...
I think this is shorter and more readable than the itertools version: ``` def split_by_n( seq, n ): """A generator to divide a sequence into chunks of n units.""" while seq: yield seq[:n] seq = seq[n:] print list(split_by_n("1234567890",2)) ```
Split python string every nth character?
9,475,241
146
2012-02-28T01:48:24Z
9,475,354
231
2012-02-28T02:02:36Z
[ "python" ]
> **Possible Duplicate:** > [What is the most “pythonic” way to iterate over a list in chunks?](http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks) Is it possible to split a python string every nth character? For example, suppose I have a string containing the f...
``` >>> line = '1234567890' >>> n = 2 >>> [line[i:i+n] for i in range(0, len(line), n)] ['12', '34', '56', '78', '90'] ```
Split python string every nth character?
9,475,241
146
2012-02-28T01:48:24Z
9,475,538
37
2012-02-28T02:25:33Z
[ "python" ]
> **Possible Duplicate:** > [What is the most “pythonic” way to iterate over a list in chunks?](http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks) Is it possible to split a python string every nth character? For example, suppose I have a string containing the f...
Another common way of grouping elements into n-length groups: ``` >>> s = '1234567890' >>> map(''.join, zip(*[iter(s)]*2)) ['12', '34', '56', '78', '90'] ``` This method comes straight from the docs for [`zip()`](http://docs.python.org/library/functions.html#zip).
Split python string every nth character?
9,475,241
146
2012-02-28T01:48:24Z
9,477,447
86
2012-02-28T06:31:13Z
[ "python" ]
> **Possible Duplicate:** > [What is the most “pythonic” way to iterate over a list in chunks?](http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks) Is it possible to split a python string every nth character? For example, suppose I have a string containing the f...
Just to be complete, you can do this with a regex: ``` >>> import re >>> re.findall('..','1234567890') ['12', '34', '56', '78', '90'] ``` As pointed out in the comment, you can do this: ``` >>> import re >>> re.findall('..?', '123456789') ['12', '34', '56', '78', '9'] ``` You can also do the following, to simplify ...