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
Why does this line tell me a float can not be used as integer
9,475,599
2
2012-02-28T02:32:00Z
9,475,625
7
2012-02-28T02:34:31Z
[ "python", "python-3.x" ]
I have this one line that my script is getting caught up on: ``` for d in range(len(r)/2) ``` I am not sure what value is what value it thinks in a float. I try casting the length of r/2 as an int but still I get this error. I am really new to Python and really lost.
In Python 3.x, the `/` division operator *always* gives a float value. To use integer division, use `//`: ``` for d in range(len(r) // 2): ``` I suspect you tried `range(int(len(r))/2)` but that doesn't change how the division works.
How do I create character arrays in numpy?
9,476,797
8
2012-02-28T05:21:03Z
9,493,192
11
2012-02-29T03:28:17Z
[ "python", "string", "character-encoding", "numpy" ]
Say I have the following array: ``` import numpy as np a = ['hello','snake','plate'] ``` I want this to turn into a numpy array `b` so that: ``` b[0,0] = 'h' b[0,1] = 'e' b[0,2] = 'l' b[1,0] = 's' ... ``` I want the standard numpy tricks to work, like broadcasting, comparison, etc. How is it done? And where is thi...
Actually, you can do this without any copies or list comprehensions in numpy (caveats about non-equal-length strings aside...). Just view it as a 1 character string array and reshape it: ``` import numpy as np x = np.array(['hello','snake','plate'], dtype=str) y = x.view('S1').reshape((x.size, -1)) print repr(y) ```...
How do I catch "split" exceptions in python?
9,477,054
2
2012-02-28T05:51:14Z
9,477,105
7
2012-02-28T05:56:18Z
[ "python" ]
I am trying to parse a list of email addresses to remove the username and '@' symbol only leaving the domain name. Example: blahblah@gmail.com Desired output: gmail.com I have accomplished this with the following code: ``` for row in cr: emailaddy = row[0] (emailuser, domain) = row[0].split('@') print d...
You want something like this? ``` try: (emailuser, domain) = row[0].split('@') except ValueError: continue ```
Python - slice a list of list
9,477,640
2
2012-02-28T06:52:43Z
9,477,666
11
2012-02-28T06:55:05Z
[ "python", "list", "slice" ]
I think its called a slice... basically I have a list of lists: ``` [['fmt/10', 3L, 5L, Decimal('9500')], ['fmt/353', 1L, 1L, Decimal('500')], ['fmt/7', 3L, 5L, Decimal('9500')], ['fmt/8', 3L, 5L, Decimal('9500')], ['fmt/9', 3L, 5L, Decimal('9500')]] ``` and I want to pull out 4 new lists, all at position [0], [...
``` L = [['fmt/10', 3L, 5L, Decimal('9500')], ['fmt/353', 1L, 1L, Decimal('500')], ['fmt/7', 3L, 5L, Decimal('9500')], ['fmt/8', 3L, 5L, Decimal('9500')], ['fmt/9', 3L, 5L, Decimal('9500')]] ``` `zip(*L)` (the asterisk is being used to unpack the list) will give: ``` [('fmt/10', 'fmt/353', 'fm...
logit and inverse logit functions for extreme values
9,478,663
5
2012-02-28T08:33:17Z
9,478,781
7
2012-02-28T08:43:44Z
[ "python", "floating-point" ]
I need logit and inverse logit functions so that `logit(inv_logit(n)) == n`. I use numpy and here is what I have: ``` import numpy as np def logit(p): return np.log(p) - np.log(1 - p) def inv_logit(p): return np.exp(p) / (1 + np.exp(p)) ``` And here are the values: ``` print logit(inv_logit(2)) 2.0 print...
Either use 1. The bigfloat package with supports **arbitrary precision floating** point operations. 2. The SymPy **symbolic** math package. I'll give examples of both: First, bigfloat: <http://packages.python.org/bigfloat/> Here's a simple example: ``` from bigfloat import * def logit(p): with precision(10000...
Is there an "enhanced" numpy/scipy dot method?
9,478,791
25
2012-02-28T08:44:32Z
9,479,621
23
2012-02-28T09:44:26Z
[ "python", "math", "numpy", "scipy" ]
### Problem I would like to compute the following using numpy or scipy: ``` Y = A**T * Q * A ``` where `A` is a `m x n` matrix, `A**T` is the transpose of `A` and `Q` is an `m x m` diagonal matrix. Since `Q` is a diagonal matrix I store only its diagonal elements as a vector. ### Ways of solving for `Y` Currently...
(w/r/t the last sentence of the OP: i am *not* aware of such a numpy/scipy method but w/r/t the Question in the OP Title (i.e., improving NumPy dot performance) what's below should be of some help. In other words, my answer is directed to improving performance of most of the *steps comprising* your function for Y). Fi...
python string replace digits
9,479,626
3
2012-02-28T09:44:43Z
9,479,991
11
2012-02-28T10:10:23Z
[ "python", "regex", "string", "replace" ]
I am trying to replace certain parts of the string below. ``` '''<td align="center"> 5 </td> <td> align="center"> 0.0001 </td>''' ``` I need to remove the `<td>` tag if there is a '0.'(decmial occurrence). i.e. the output should be ``` '''<td align="center"> 5 </td>''' ``` I have tried this ``` data = ' '.join(dat...
While both of the regular expression examples work, I would advice **against** using regexp. *Especially if the data is a full html document*, you should go for html-aware parser, such as `lxml.html` e.g.: ``` from lxml import html t = html.fromstring(text) tds = t.xpath("table/tbody/tr[2]/td") for td in tds: if ...
How can I get the public IP using python2.7?
9,481,419
23
2012-02-28T11:54:36Z
9,481,595
57
2012-02-28T12:06:15Z
[ "python", "ip" ]
How can I get the public IP using python2.7? Not private IP.
Currently there are several options: * ip.42.pl * jsonip.com * httpbin.org * ipify.org Below are exact ways you can utilize each of the above. ## ip.42.pl ``` from urllib2 import urlopen my_ip = urlopen('http://ip.42.pl/raw').read() ``` This is the first option I have found. It is very convenient for scripts, you ...
Python - create dictionary from list of dictionaries
9,481,870
6
2012-02-28T12:26:30Z
9,481,895
18
2012-02-28T12:28:36Z
[ "python" ]
I have a list of dictionaries in Python ``` [ {'id':'1', 'name': 'test 1', 'slug': 'test1'}, {'id':'2', 'name': 'test 2', 'slug': 'test2'}, {'id':'3', 'name': 'test 3', 'slug': 'test3'}, {'id':'4', 'name': 'test 4', 'slug': 'test4'}, {'id':'5', 'name': 'test 5', 'slug': 'test4'} ] ``` I want to turn this list into a ...
Assuming your list is called `a`, you can use ``` my_dict = {d["slug"]: d for d in a} ``` In Python versions older than 2.7, you can use ``` my_dict = dict((d["slug"], d) for d in a) ``` This will implicitly remove duplicates (specifically by using the *last* item with a given key).
Argmax of numpy array returning non-flat indices
9,482,550
30
2012-02-28T13:12:04Z
9,482,667
9
2012-02-28T13:19:58Z
[ "python", "multidimensional-array", "numpy" ]
I'm trying to get the indices of the maximum element in a Numpy array. This can be done using `numpy.argmax`. My problem is, that I would like to find the biggest element in the whole array and get the indices of that. `numpy.argmax` can be either applied along one axis, which is not what I want, or on the flattened a...
``` np.where(a==a.max()) ``` returns coordinates of the maximum element(s), but has to parse the array twice. ``` >>> a = np.array(((3,4,5),(0,1,2))) >>> np.where(a==a.max()) (array([0]), array([2])) ``` This, comparing to `argmax`, returns coordinates of all elements equal to the maximum. `argmax` returns just one ...
Argmax of numpy array returning non-flat indices
9,482,550
30
2012-02-28T13:12:04Z
9,483,964
54
2012-02-28T14:42:18Z
[ "python", "multidimensional-array", "numpy" ]
I'm trying to get the indices of the maximum element in a Numpy array. This can be done using `numpy.argmax`. My problem is, that I would like to find the biggest element in the whole array and get the indices of that. `numpy.argmax` can be either applied along one axis, which is not what I want, or on the flattened a...
You could use [`numpy.unravel_index()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.unravel_index.html#numpy.unravel_index) on the result of `numpy.argmax()`: ``` >>> a = numpy.random.random((10, 10)) >>> numpy.unravel_index(a.argmax(), a.shape) (6, 7) >>> a[6, 7] == a.max() True ```
Is there a difference between `continue` and `pass` in a for loop in python?
9,483,979
81
2012-02-28T14:42:50Z
9,484,008
143
2012-02-28T14:44:19Z
[ "python", "syntax", "continue" ]
Is there any significant difference between between the two python keywords `continue` and `pass` like in the examples ``` for element in some_list: if not element: pass ``` and ``` for element in some_list: if not element: continue ``` I should be aware of?
Yes, they do completely different things. `pass` simply does nothing, while `continue` goes on with the next loop iteration. In your example, the difference would become apparent if you added another statement after the `if`: After executing `pass`, this further statement would be executed. After `continue`, it wouldn'...
Is there a difference between `continue` and `pass` in a for loop in python?
9,483,979
81
2012-02-28T14:42:50Z
9,484,042
34
2012-02-28T14:45:57Z
[ "python", "syntax", "continue" ]
Is there any significant difference between between the two python keywords `continue` and `pass` like in the examples ``` for element in some_list: if not element: pass ``` and ``` for element in some_list: if not element: continue ``` I should be aware of?
Yes, there is a difference. `continue` forces the loop to start at the next iteration while `pass` means "there is no code to execute here" and will continue through the remainder or the loop body. Run these and see the difference: ``` for element in some_list: if not element: pass print 1 # will prin...
Python: how to build a dict from plain list of keys and values
9,485,399
13
2012-02-28T16:05:25Z
9,485,425
13
2012-02-28T16:07:02Z
[ "python", "list", "dictionary" ]
I have a list of values like: ``` ["a", 1, "b", 2, "c", 3] ``` and I would like to build such a dict from it: ``` {"a": 1, "b": 2, "c": 3} ``` What is the natural way to do it in Python?
This seems rather succint, but I wouldn't call it very natural: ``` >>> l = ["a", 1, "b", 2, "c", 3] >>> dict(zip(l[::2], l[1::2])) {'a': 1, 'c': 3, 'b': 2} ```
Python: how to build a dict from plain list of keys and values
9,485,399
13
2012-02-28T16:05:25Z
9,485,467
34
2012-02-28T16:09:14Z
[ "python", "list", "dictionary" ]
I have a list of values like: ``` ["a", 1, "b", 2, "c", 3] ``` and I would like to build such a dict from it: ``` {"a": 1, "b": 2, "c": 3} ``` What is the natural way to do it in Python?
``` >>> x = ["a", 1, "b", 2, "c", 3] >>> i = iter(x) >>> dict(zip(i, i)) {'a': 1, 'c': 3, 'b': 2} ```
Setupterm could not find terminal, in Python program using curses
9,485,699
12
2012-02-28T16:23:45Z
21,571,407
8
2014-02-05T07:44:51Z
[ "python", "curses" ]
I am trying to get a simple curses script to run using Python (with PyCharm 2.0). This is my script: ``` import curses stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(1) while 1: c = stdscr.getch() if c == ord('p'): print("I pressed p") elif c == ord('q'): break curses.nocbreak();...
You must set enviroment variables `TERM` and `TERMINFO`, like this: ``` export TERM=linux export TERMINFO=/etc/terminfo ``` And, if you device have no this dir (`/etc/terminfo`), make it, and copy terminfo database. For "linux", and "pcansi" terminals you can download database: * <http://forum.xda-developers.com/at...
Mixing HTML5 Canvas and Python
9,485,761
10
2012-02-28T16:27:58Z
9,487,343
9
2012-02-28T18:06:40Z
[ "python", "django", "html5", "google-app-engine" ]
I have used both of these (Python and HTML5) seperately, however I'm keen to use the full power of Python over the web using HTML5 to draw things and handle the client side of things. I guess I'm looking for avenues to go down in terms of implementation. Here are some things I'd like to do if possible: 1. Have very in...
The server side is much more developed than the client side in this case. (Rich JS libraries are a newer phenomenon, is all.) Django is an acceptable choice on the server, although I would at least consider [Twisted](http://twistedmatrix.com/). My recommendation on the client side: 1. First choice is [paper.js](http:...
is there any kind of performance gain while using .pyc files in python?
9,485,905
6
2012-02-28T16:36:41Z
9,485,973
7
2012-02-28T16:41:02Z
[ "python", "pyc" ]
We can write a piece of python code and put it in already compiled ".pyc" file and use it. I am wondering that is there any kind of gain in terms of performance or it is just a kind of modular way of grouping the code. Thanks a lot
There is no performance gain over the course of your program. It only improves the startup time. > A program doesn't run any faster when it is read from a ‘.pyc’ or > ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing > that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with wh...
Does Python have anything Like Capybara/Cucumber?
9,485,962
31
2012-02-28T16:40:19Z
9,514,754
19
2012-03-01T10:44:51Z
[ "python", "functional-testing", "acceptance-testing" ]
Ruby has this great abstraction layer on top of Selenium called Capybara, which you can use do functional/acceptance/integration testing. It also has another library called Cucumber which takes this a step further and lets you actually write tests in English. Both libraries are built on top of Selenium, and can be use...
You can test Python code using Cucumber - see the [Cucumber wiki](https://github.com/cucumber/cucumber/wiki/Python) on github for more information. If you want a pure Python solution, check out [Lettuce](http://lettuce.it). I've never used it, but there is a fairly useful looking blog entry about it and splinter [here...
Does Python have anything Like Capybara/Cucumber?
9,485,962
31
2012-02-28T16:40:19Z
17,843,655
9
2013-07-24T19:55:04Z
[ "python", "functional-testing", "acceptance-testing" ]
Ruby has this great abstraction layer on top of Selenium called Capybara, which you can use do functional/acceptance/integration testing. It also has another library called Cucumber which takes this a step further and lets you actually write tests in English. Both libraries are built on top of Selenium, and can be use...
While the OP was happy with finding a Python Cucumber equivalent, what led me here was the question title: a Python equivalent of Capybara. While Cucumber uses Capybara, Cucumber itself is a whole different "solution" that is only incidentally related to Capybara. If you're looking for something Capybara-like without ...
Does Python have anything Like Capybara/Cucumber?
9,485,962
31
2012-02-28T16:40:19Z
21,743,965
8
2014-02-13T02:24:02Z
[ "python", "functional-testing", "acceptance-testing" ]
Ruby has this great abstraction layer on top of Selenium called Capybara, which you can use do functional/acceptance/integration testing. It also has another library called Cucumber which takes this a step further and lets you actually write tests in English. Both libraries are built on top of Selenium, and can be use...
How about Robot Framework. It's pretty awesome. And with Selenium2Library it works really well with SE2. <http://robotframework.org/>
Does Python have anything Like Capybara/Cucumber?
9,485,962
31
2012-02-28T16:40:19Z
28,763,847
11
2015-02-27T11:19:07Z
[ "python", "functional-testing", "acceptance-testing" ]
Ruby has this great abstraction layer on top of Selenium called Capybara, which you can use do functional/acceptance/integration testing. It also has another library called Cucumber which takes this a step further and lets you actually write tests in English. Both libraries are built on top of Selenium, and can be use...
A. Cucumber like: ( English like) * Lettuce (Approach Gherkin) or * Behave (Approach Gherkin) or * Robotframework (Approach keyword based) (Additional Info: RF is larger than English Like criteria. Its keyword-based and offers loads of helper method and inbuilt libraries. Great eco-sysstem for external libraries. An...
In python is there something like updated that is to update what sorted is to sort?
9,486,089
12
2012-02-28T16:46:35Z
9,486,146
17
2012-02-28T16:49:14Z
[ "python", "dictionary" ]
In python if I do the following: ``` >>> list = [ 3, 2, 1] >>> sorted_list = k.sort() ``` Then `sorted_list` is `None` and `list` is sorted: ``` >>> sorted_list = k.sort() >>> print list, sorted_list [1, 2, 3] None ``` However, if I do the following: ``` >>> list = [ 3, 2, 1] >>> sorted_list = sorted(list) ``` Th...
You can simply use the built-in `dict()`: ``` updated_dict = dict(old_dict, **extra_dict) ```
SQL Alchemy ORM returning a single column, how to avoid common post processing
9,486,180
35
2012-02-28T16:51:25Z
12,721,902
12
2012-10-04T07:01:50Z
[ "python", "orm", "sqlalchemy" ]
I'm using SQL Alchemy's ORM and I find when I return a single column I get the results like so: ``` [(result,), (result_2,)] # etc... ``` With a set like this I find that I have to do this often: ``` results = [r[0] for r in results] # So that I just have a list of result values ``` This isn't that "bad" because my...
Python's zip combined with the \* inline expansion operator is a pretty handy solution to this: ``` >>> results = [('result',), ('result_2',), ('result_3',)] >>> zip(*results) [('result', 'result_2', 'result_3')] ``` Then you only have to [0] index in once. For such a short list your comprehension is faster: ``` >>>...
SQL Alchemy ORM returning a single column, how to avoid common post processing
9,486,180
35
2012-02-28T16:51:25Z
13,118,371
8
2012-10-29T08:51:21Z
[ "python", "orm", "sqlalchemy" ]
I'm using SQL Alchemy's ORM and I find when I return a single column I get the results like so: ``` [(result,), (result_2,)] # etc... ``` With a set like this I find that I have to do this often: ``` results = [r[0] for r in results] # So that I just have a list of result values ``` This isn't that "bad" because my...
One way to decrease the clutter in the source is to iterate like this: ``` results = [r for (r, ) in results] ``` Although this solution is one character longer than using the `[]` operator, I think it's easier on the eyes. For even less clutter, remove the parenthesis. This makes it harder when reading the code, to...
Jinja2: Change the value of a variable inside a loop
9,486,393
25
2012-02-28T17:05:09Z
16,746,185
23
2013-05-25T03:47:43Z
[ "python", "jinja2" ]
I want to change the value of the variable declared outside the loop within a loop. But always changing, it keeps the initial value outside the loop. ``` {% set foo = False %} {% for item in items %} {% set foo = True %} {% if foo %} Ok(1)! {% endif %} {% endfor %} {% if foo %} Ok(2)! {% endif %} ``` This rende...
Try also dictionary-based approach. It seems to be less ugly. ``` {% set vars = {'foo': False} %} {% for item in items %} {% if vars.update({'foo': True}) %} {% endif %} {% if vars.foo %} Ok(1)! {% endif %} {% endfor %} {% if vars.foo %} Ok(2)! {% endif %} ``` This also renders: ``` Ok(1)! Ok(2)! ```
pydev breakpoints not working
9,486,871
18
2012-02-28T17:33:43Z
9,502,960
10
2012-02-29T16:32:59Z
[ "python", "unit-testing", "debugging", "pydev", "python-2.7" ]
I am working on a project using python 2.7.2, sqlalchemy 0.7, unittest, eclipse 3.7.2 and pydev 2.4. I am setting breakpoints in python files (unit test files), but they are completely ignored (before, at some point, they worked). By now i have upgraded all related software (see above), started new projects, played aro...
Seems really strange... I need some more info to better diagnose the issue: Open \plugins\org.python.pydev.debug\pysrc\pydevd\_constants.py and change ``` DEBUG_TRACE_LEVEL = 3 DEBUG_TRACE_BREAKPOINTS = 3 ``` run your use-case with the problem and add the output to your question... Also, it could be that for some ...
django redirect() with parameters
9,488,874
6
2012-02-28T20:03:48Z
9,489,307
16
2012-02-28T20:36:13Z
[ "python", "django" ]
There have been several similar questions asked already but I couldn't find answer to my problem after spending loong hours. In the code below when I redirect to "anotherView" from "myView" with parameter "username", it works fine as expected. But I need to include "range" parameter in this redirect too as this "range...
`redirect` is merely a wrapper around `HttpResponseRedirect` that automatically calls `reverse` for you to create the URL to redirect to. As a result, the parameters you pass to it, aren't arbitrary, they must be same you would pass to `reverse` and, specifically, only those required to create the URL. Many people see...
Fill area under curve in matlibplot python on log scale
9,488,955
12
2012-02-28T20:10:09Z
9,490,171
13
2012-02-28T21:41:00Z
[ "python", "matplotlib" ]
I'm trying to fill the area under a curve with matplotlib. The script below works fine. ``` import matplotlib.pyplot as plt from math import sqrt x = range(100) y = [sqrt(i) for i in x] plt.plot(x,y,color='k',lw=2) plt.fill_between(x,y,0,color='0.8') plt.show() ``` However if I set the y-scale to logarithmic (see bel...
With a logarithmic y-scale, `fill_between(x, y, 0)` tells matplotlib to fill the region between `log(0) = -infinity` and `log(y)`. Naturally, it balks. You can avoid the problem by changing `0` to some small number like `1e-6`.
How to split a huge csv file based on content of first column?
9,489,078
9
2012-02-28T20:19:55Z
9,489,862
11
2012-02-28T21:18:38Z
[ "python", "linux", "unix", "ubuntu" ]
* I have a 250MB+ huge csv file to upload * file format is `group_id, application_id, reading` and data could look like > ``` > 1, a1, 0.1 > 1, a1, 0.2 > 1, a1, 0.4 > 1, a1, 0.3 > 1, a1, 0.0 > 1, a1, 0.9 > 2, b1, 0.1 > 2, b1, 0.2 > 2, b1, 0.4 > 2, b1, 0.3 > 2, b1, 0.0 > 2, b1, 0.9 > ..... > n, x, 0.3(lets say) > ``` ...
`awk` is capable: ``` awk -F "," '{print $0 >> ("FILE" $1)}' HUGE.csv ```
Updating a matplotlib bar graph?
9,489,669
4
2012-02-28T21:03:03Z
9,489,768
7
2012-02-28T21:11:34Z
[ "python", "matplotlib" ]
I have a bar graph which retrieves its y values from a dict. Instead of showing several graphs with all the different values and me having to close every single one, I need it to update values on the same graph. Is there a solution for this?
Here is an example of how you can animate a bar plot. You call `plt.bar` only once, save the return value `rects`, and then call `rect.set_height` to modify the bar plot. Calling `fig.canvas.draw()` updates the figure. ``` import matplotlib matplotlib.use('TKAgg') import matplotlib.pyplot as plt import numpy as np de...
WebSocket + Django python WebService
9,489,720
11
2012-02-28T21:08:11Z
9,497,617
7
2012-02-29T10:43:53Z
[ "python", "django", "websocket" ]
I was wondering how to create a django webservice (responds with XML) with websockets. I have already a django webservice which accepts xml requests, parse those requests, makes a database query, creates a response xml and send that xml back to the requester/browser. Just a normal HTTP XML request, where the response i...
Sorry but django handles async requests very very poorly as it is wsgi. You'll be limited by your number of parallel instance if you have to handle real users. The best solution is to use tornado or node.js. Tornado handles websocket and long polling brilliantly. Here is my wrapper to allow getting user and sessions f...
WebSocket + Django python WebService
9,489,720
11
2012-02-28T21:08:11Z
13,674,300
7
2012-12-02T21:54:46Z
[ "python", "django", "websocket" ]
I was wondering how to create a django webservice (responds with XML) with websockets. I have already a django webservice which accepts xml requests, parse those requests, makes a database query, creates a response xml and send that xml back to the requester/browser. Just a normal HTTP XML request, where the response i...
Although it's a bit complicated to setup (but probably the way to go), you could use gunicorn + gevent + socket.io . I used [this article](http://curella.org/blog/django-push-using-server-sent-events-and-websocket/) to guide my way through it. You might also look at server sent events (the article mentioned above loo...
Why substring slicing index out of range works in Python?
9,490,058
23
2012-02-28T21:31:27Z
9,490,148
21
2012-02-28T21:39:06Z
[ "python", "string", "substring" ]
Why doesn't `'example'[999:9999]` result in error? Since `'example'[9]` does, what is the motivation behind it? From this behavior I can assume that `'example'[3]` is, essentially/internally, not the same as `'example'[3:4]`, even though both result in the same `'m'` string.
You've basically answered your own question. Slicing outside the bounds of a sequence (at least for built-ins) doesn't cause an error. It makes sense when you think about it. Indexing returns a single item, but slicing returns a subsequence of items. So when you try to index a nonexistent value, there's nothing to retu...
Reducing capabilities of markdown in python
9,490,112
3
2012-02-28T21:35:56Z
9,490,406
8
2012-02-28T21:59:28Z
[ "python", "parsing", "stack-overflow", "markdown", "markup" ]
I'm writing a comment system. It has to be have formatting system like stackoverflow's. Users can use some inline markdown syntax like **bold** or *italic*. I thought that i can solve that need with using regex replacements. But there is another thing i have to do: by giving 4 space indents users can create code bloc...
I'd just go ahead and use [python-markdown](http://freewisdom.org/projects/python-markdown/) and monkey-patch it. You can write your own `def_block_parser()` function and substitute that in for the default one to disable some of the Markdown functionality: ``` from markdown import blockprocessors as bp def build_block...
python - del statement executing early
9,490,876
3
2012-02-28T22:35:49Z
9,490,988
8
2012-02-28T22:44:42Z
[ "python", "jython" ]
I'm a self-taught programmer with no formal training, so please forgive me in advance if this is a stupid question. While programming in Python I found something weird: ``` from someModule import someClass def someFunction(): someInstance = someClass() print "foo" del someClass someFunction() ``` This ...
The `del` statement implicitly renders the name `someClass` local for the whole function, so the line ``` someInstance = someClass() ``` tries to look up a local name `someClass`, which is not defined at that point. The `del` statement isn't executed early -- the name isn't defined right from the beginning. If you r...
Browse a Windows directory GUI using Python 2.7
9,491,195
4
2012-02-28T23:04:34Z
9,508,509
8
2012-02-29T23:46:08Z
[ "python" ]
I'm using Windows XP with Python 2.7.2 & Tkinter GUI kit. I want to build a simple GUI that has a text field and "Browse" button that will select a file through directories such as C:\ (Just like Windows Explorer). That file selected will be displayed in the text field in the GUI. Hope this is descriptive enough.
I have something else that might help you: ``` ## {{{ http://code.activestate.com/recipes/438123/ (r1) # ======== Select a directory: import Tkinter, tkFileDialog root = Tkinter.Tk() dirname = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Please select a directory') if len(dirna...
Python configparser will not accept keys without values
9,491,521
13
2012-02-28T23:39:07Z
9,491,779
11
2012-02-29T00:07:37Z
[ "python", "python-3.x", "configparser" ]
So I'm writing a script that reads from a config file, and I want to use it exactly how configparser is designed to be used as outlined here: <http://docs.python.org/release/3.2.1/library/configparser.html> I am using Python 3.2.1. The script, when complete, will run on a Windows 2008 R2 machine using the same version...
The [ConfigParser constructor](http://docs.python.org/release/3.2.1/library/configparser.html#configparser.ConfigParser) has a keyword argument `allow_no_value` with a default value of `False`. Try setting that to true, and I'm betting it'll work for you.
Is there a list of characters that look similar to English letters?
9,491,890
14
2012-02-29T00:20:42Z
10,073,660
19
2012-04-09T13:06:44Z
[ "python", "unicode", "glyph", "profanity" ]
I’m having a crack at profanity filtering for a web forum written in Python. As part of that, I’m attempting to write a function that takes a word, and returns all possible mock spellings of that word that use visually similar characters in place of specific letters (e.g. s†å©køv€rƒ|øw). I expect I’ll ...
This is probably both vastly more deep than you need, yet not wide enough to cover your use case, but the Unicode consortium have had to deal with attacks against internationalised domain names and came up with this list of homographs (characters with the same or similar rendering): <http://www.unicode.org/Public/secu...
Is there a list of characters that look similar to English letters?
9,491,890
14
2012-02-29T00:20:42Z
20,551,123
7
2013-12-12T18:16:08Z
[ "python", "unicode", "glyph", "profanity" ]
I’m having a crack at profanity filtering for a web forum written in Python. As part of that, I’m attempting to write a function that takes a word, and returns all possible mock spellings of that word that use visually similar characters in place of specific letters (e.g. s†å©køv€rƒ|øw). I expect I’ll ...
<http://en.wikipedia.org/wiki/Letterlike_Symbols> It's much much much less comprehensive but is more comprehensible.
Quadruple Precision Eigenvalues, Eigenvectors and Matrix Logarithms
9,491,907
6
2012-02-29T00:22:46Z
9,594,783
8
2012-03-07T02:00:02Z
[ "python", "matlab", "numpy", "scipy", "sage" ]
I am attempting to diagonalize matrices in quadruple precision, and to take their logarithms. Is there a language in which I can accomplish this using built-in functions? Note, the languages/packages in the tags are insufficient, suffering from the following deficiencies: Matlab: Does not support quad precision. Pyt...
*@Matlab: Does not support quad precision.* [Multiprecision Computing Toolbox for MATLAB](http://www.advanpix.com/) provides routines for linear algebra computations in arbitrary precision. It covers many other fields - basic math, numerical methods (integration, ode, optimization), special functions and basic data a...
How to replace an object in python
9,491,956
2
2012-02-29T00:30:03Z
9,491,980
7
2012-02-29T00:33:17Z
[ "python" ]
Given the following example code: ``` def myfunc(item): if item == 2: item = 1 mylist = [1,2,3] for i in mylist: myfunc(i) print(mylist) # output is [1, 2, 3] # desired output is [1, 1, 3] ``` I would like to have a function that is called for some or all elements of a list. This function should be able to a...
If you don't need the list to be modified in-place, you can create a new list with the new values. To this end, your functions should simply return the new value: ``` def myfunc(item): if item == 2: return 1 return item ``` Then you can use `map()` or a list comprehension to construct the new list: `...
Inline comments for ConfigParser
9,492,430
4
2012-02-29T01:38:42Z
9,494,210
9
2012-02-29T05:55:32Z
[ "python", "comments", "ini", "configparser" ]
I have stuff like this in an .ini file ``` [General] verbosity = 3 ; inline comment [Valid Area Codes] ; Input records will be checked to make sure they begin with one of the area ; codes listed below. 02 ; Central East New South Wales & Australian Capital Territory 03 ; South East Victoria & Tasmania ;04...
According to the ConfigParser documentation "Configuration files may include comments, prefixed by specific characters (# and ;). Comments may appear on their own in an otherwise empty line, or **may be entered in lines holding values or section names**" **In your case you are adding comments in lines holding just ke...
Check that a *type* of file exists in Python
9,492,481
8
2012-02-29T01:46:28Z
9,492,511
7
2012-02-29T01:50:39Z
[ "python" ]
I realize this looks similar to other questions about checking if a file exists, but it is different. I'm trying to figure out how to check that a **type** of file exists and exit if it doesn't. The code I tried originally is this: ``` filenames = os.listdir(os.curdir) for filename in filenames: if os.path.isfile...
The [`for` statement in Python](http://docs.python.org/reference/compound_stmts.html#the-for-statement) has a little-known `else` clause: ``` for filename in filenames: if os.path.isfile(filename) and filename.endswith(".fna"): # do stuff break else: sys.stderr.write ('No database file found. E...
How do I randomize a list of strings with random.seed?
9,492,903
3
2012-02-29T02:46:28Z
9,492,994
8
2012-02-29T02:59:34Z
[ "python", "random" ]
So I have a list of 4 strings in Python and I want to return that list, but randomized and only up to a specific number (the variable 'players' in the code below). I CANNOT use the shuffle function, but trust me if I could, I would. Here is the code I have so far: ``` players = raw_input('How many players? ') players...
While [`random.shuffle`](http://docs.python.org/library/random.html) (or `random.sample`) is *The Python Way*, consider using an existing well-known approach if it is truly not an option. The code below is an implementation of the [Fisher-Yates Shuffle](http://en.wikipedia.org/wiki/Fisher-Yates_shuffle) (it is adapted ...
SymPy - Arbitrary number of Symbols
9,492,944
8
2012-02-29T02:52:19Z
9,493,306
20
2012-02-29T03:43:53Z
[ "python", "symbols", "sympy", "equation-solving" ]
I am coding a function that solves an arbitrary number of simultaneous equations. The number of equations is set by one of the parameters of the function and each equation is built from a number of symbols - as many symbols as there are equations. This means that I can't simply hardcode the equations, or even the symbo...
The `symbols` function can be used to easily generate lists of symbols ``` In [1]: symbols('a0:3') Out[1]: (a₀, a₁, a₂) In [2]: numEquations = 15 In [3]: symbols('a0:%d'%numEquations) Out[3]: (a₀, a₁, a₂, a₃, a₄, a₅, a₆, a₇, a₈, a₉, a₁₀, a₁₁, a₁₂, a₁₃, a₁₄) ```
Python - How do you run a .py file?
9,493,086
8
2012-02-29T03:13:11Z
9,493,147
12
2012-02-29T03:22:15Z
[ "python", "windows", "image", "download" ]
I've looked all around Google and its archives. There are several good articles, but none seem to help me out. So I thought I'd come here for a more specific answer. The Objective: I want to run [this code](http://stackoverflow.com/questions/257409/download-image-file-from-the-html-page-source-using-python) on a websi...
On windows platform, you have 2 choices: 1. In a command line terminal, type c:\python23\python xxxx.py 2. Open the python editor IDLE from the menu, and open xxxx.py, then press F5 to run it. For your posted code, the error is at this line: ``` def main(url, out_folder="C:\asdf\"): ``` It should be: ``` def m...
MPRIS + Python (dbus): reading and writing properties
9,493,494
12
2012-02-29T04:12:31Z
9,493,706
17
2012-02-29T04:46:27Z
[ "python", "linux", "dbus" ]
I have already checked this link: [How to handle properties of a dbus interface with python](http://stackoverflow.com/questions/4277814/how-to-handle-properties-of-a-dbus-interface-with-python). However, that only lists an API... but I don't know where that API comes from. I just started working with dbus (pretty exci...
Found how. ``` proxy = bus.get_object('org.mpris.MediaPlayer2.rhythmbox','/org/mpris/MediaPlayer2') properties_manager = dbus.Interface(proxy, 'org.freedesktop.DBus.Properties') properties_manager.Set('org.mpris.MediaPlayer2.Player', 'Volume', 100.0) curr_volume = properties_manager.Get('org.mpris.MediaPlayer2.Player'...
Stripping 's (apostrophe s) from a string
9,494,329
3
2012-02-29T06:07:56Z
9,494,360
8
2012-02-29T06:11:17Z
[ "python", "string" ]
I would like to strip 's (apostrophe s) from a string. For example: ``` a="it's tail was big".split() for i in range(len(a)): a[i]= a[i].strip(r"\'s") ``` a becomes ``` ['it', 'tail', 'wa', 'big'] ``` whereas I am expecting ``` ['it', 'tail', 'was', 'big'] ``` How do I make it strip 's and not s ? I tried st...
You can replace the `'s` with empty string and then split. ``` >>> txt ="it's tail was big" >>> txt.replace("'s", '').split() ['it', 'tail', 'was', 'big'] ```
Use of True, False, and None as return values in python functions
9,494,404
33
2012-02-29T06:16:29Z
9,494,439
12
2012-02-29T06:19:29Z
[ "python" ]
I think that I fully understand this, but I just want to make sure since I keep seeing people say to NEVER EVER test against `True`, `False`, or `None`. They suggest that routines should raise an error rather than return False or None. Anyway, I have many situations where I simply want to know if a flag is set or not s...
Use `if foo` or `if not foo`, there is no need for either `==` or `is` for that. For checking against None, `is None` and `is not None` are recommended. This allows you to distinguish it from False (or things that evaluate to False, like `""` and `[]`). Whether `get_attr` should return `None` would depend on the cont...
Use of True, False, and None as return values in python functions
9,494,404
33
2012-02-29T06:16:29Z
9,494,887
52
2012-02-29T07:04:32Z
[ "python" ]
I think that I fully understand this, but I just want to make sure since I keep seeing people say to NEVER EVER test against `True`, `False`, or `None`. They suggest that routines should raise an error rather than return False or None. Anyway, I have many situations where I simply want to know if a flag is set or not s...
The advice isn't that you should never **use** `True`, `False`, or `None`. It's just that you shouldn't use `if x == True`. `if x == True` is silly because `==` is just a binary operator! It has a return value of either `True` or `False`, depending on whether its arguments are equal or not. And `if condition` will pro...
How to build a SystemTray app for Windows?
9,494,739
11
2012-02-29T06:48:49Z
9,494,913
17
2012-02-29T07:07:33Z
[ "python", "windows", "osx", "desktop-application", "appcelerator" ]
I usually work on a Linux system, but I have a situation where I need to write a client app which would run on windows as a serivce. Can someone help me or direct to, on how to build a MenuBar app ( for example like dropbox) for windows environment, which gets started on OS startup and the icon sits in the TaskBar and ...
You do this using the [pywin32 (Python for Windows Extensions)](http://sourceforge.net/projects/pywin32/) module. [Example Code](http://www.brunningonline.net/simon/blog/archives/SysTrayIcon.py.html) [Similar Question](http://stackoverflow.com/questions/1085694/whats-the-simplest-way-to-put-a-python-script-into-the-...
How to implement associative array (not dictionary) in Python?
9,495,950
5
2012-02-29T08:44:26Z
9,495,992
12
2012-02-29T08:48:14Z
[ "python", "sorting", "dictionary", "associative-array" ]
I trying to print out a dictionary in Python: ``` Dictionary = {"Forename":"Paul","Surname":"Dinh"} for Key,Value in Dictionary.iteritems(): print Key,"=",Value ``` Although the item "Forename" is listed first, but dictionaries in Python **seem to be** sorted by values, so the result is like this: ``` Surname = Di...
You can use a list of tuples (or list of lists). Like this: ``` Arr= [("Forename","Paul"),("Surname","Dinh")] for Key,Value in Arr: print Key,"=",Value Forename = Paul Surname = Dinh ``` you can make a dictionary out of this with: ``` Dictionary=dict(Arr) ``` And the correctly sorted keys like this: ``` keys...
How to implement associative array (not dictionary) in Python?
9,495,950
5
2012-02-29T08:44:26Z
9,496,078
14
2012-02-29T08:53:58Z
[ "python", "sorting", "dictionary", "associative-array" ]
I trying to print out a dictionary in Python: ``` Dictionary = {"Forename":"Paul","Surname":"Dinh"} for Key,Value in Dictionary.iteritems(): print Key,"=",Value ``` Although the item "Forename" is listed first, but dictionaries in Python **seem to be** sorted by values, so the result is like this: ``` Surname = Di...
First of all dictionaries are not sorted at all nor by key, nor by value. And basing on your description. You actualy need [collections.OrderedDict](http://docs.python.org/library/collections.html#collections.OrderedDict) module ``` from collections import OrderedDict my_dict = OrderedDict([("Forename", "Paul"), ("S...
How would I sum a multi-dimensional array in the most succinct python?
9,497,290
8
2012-02-29T10:21:09Z
9,497,507
8
2012-02-29T10:36:53Z
[ "python", "multidimensional-array", "sum" ]
The closest was this one [summing columns](http://stackoverflow.com/questions/3223043/how-do-i-sum-the-columns-in-2d-list). So I'll do something similar in my question: Say I've a Python 2D list as below: ``` my_list = [ [1,2,3,4], [2,4,5,6] ] ``` I can get the row totals with a list comprehension: `...
You can do as easy as ``` sum(map(sum, my_list)) ``` or alternatively ``` sum(sum(x) for x in my_list)) ``` and call it a day, if you don't expect more than 2 dimensions. Note that the first solution is most likely not the fastest (as in execution time) solution, due to the usage of `map()`. Benchmark and compare a...
making exe file from python that uses command line arguments
9,497,370
5
2012-02-29T10:27:49Z
9,497,409
16
2012-02-29T10:30:46Z
[ "python", "py2exe" ]
I want to create an exe from a python script that uses command line arguments (argv) From what I've seen py2exe doesn't support command-line-arguments What can I do? EDIT: I was using a GUI2Exe tool, so I just missed the Console flag, but the accepted answer is perfectly correct
``` setup(console=['hello.py']) ``` I believe the line you want to use looks like this. I tested this with 2 files: hello.py ``` import sys for arg in sys.argv: print arg print "Hello World!" ``` And setup.py ``` from distutils.core import setup import py2exe setup(console=['hello.py']) ``` I ran these com...
Displaying 3 histograms on 1 axis in a legible way - matplotlib
9,497,524
10
2012-02-29T10:37:56Z
9,502,865
14
2012-02-29T16:26:44Z
[ "python", "matplotlib" ]
I have produced 3 sets of data which are organised in numpy arrays. I'm interested in plotting the probability distribution of these three sets of data as normed histograms. All three distributions should look almost identical so it seems sensible to plot all three on the same axis for ease of comparison. By default m...
There are two ways to plot three histograms simultaniously, but both are not what you've asked for. To do what you ask, you must calculate the histogram, e.g. by using [`numpy.histogram`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html), then plot using the `plot` method. Use `scatter` only if ...
Using Google OAuth2 with Flask
9,499,286
48
2012-02-29T12:35:52Z
12,918,081
31
2012-10-16T15:23:39Z
[ "python", "oauth", "oauth-2.0", "flask" ]
Can anyone point me to a complete example for authenticating with Google accounts using OAuth2 and Flask, and *not* on App Engine? I am trying to have users give access to Google Calendar, and then use that access to retrieve information from the calendar and process it further. I also need to store and later refresh ...
I've searched for quite a bit about using different libraries but all of them seemed ether overkill in some sense (you can use it on any platform but for that you need ton of code) or documentation did not explained what I wanted to. Long story short - I wrote it from scratch thus understanding process of authenticatio...
Using Google OAuth2 with Flask
9,499,286
48
2012-02-29T12:35:52Z
21,987,075
18
2014-02-24T11:55:47Z
[ "python", "oauth", "oauth-2.0", "flask" ]
Can anyone point me to a complete example for authenticating with Google accounts using OAuth2 and Flask, and *not* on App Engine? I am trying to have users give access to Google Calendar, and then use that access to retrieve information from the calendar and process it further. I also need to store and later refresh ...
Give [Authomatic](http://peterhudec.github.io/authomatic) a try (I'm the maintainer of that project). It is very simple to use, works with **any Python framework** and supports **16 OAuth 2.0**, **10 OAuth 1.0a** providers and **OpenID**. Here is a simple example about how to authenticate a user with Google and **get ...
Using Google OAuth2 with Flask
9,499,286
48
2012-02-29T12:35:52Z
29,629,536
23
2015-04-14T14:06:41Z
[ "python", "oauth", "oauth-2.0", "flask" ]
Can anyone point me to a complete example for authenticating with Google accounts using OAuth2 and Flask, and *not* on App Engine? I am trying to have users give access to Google Calendar, and then use that access to retrieve information from the calendar and process it further. I also need to store and later refresh ...
Another answer mentions [Flask-Rauth](http://flask-rauth.readthedocs.org/en/latest/), but doesn't go into detail about how to use it. There are a few Google-specific gotchas, but I have implemented it finally and it works well. I integrate it with Flask-Login so I can decorate my views with useful sugar like `@login_re...
How to install gevent on Windows?
9,499,835
12
2012-02-29T13:15:00Z
9,499,997
7
2012-02-29T13:26:31Z
[ "python", "pip", "gevent", "libevent" ]
I'm trying to install gevent on Windows. In order to do that, I've downloaded and compiled libevent, then I run `pip install gevent` and get an error: `Please provide path to libevent source with --libevent DIR`. How can I pass the `libevent` option to `setup.py` using `pip`? Thanks in advance, Ivan. UPD: running `pi...
Get a binary installer from <http://code.google.com/p/gevent/downloads/list>
How to install gevent on Windows?
9,499,835
12
2012-02-29T13:15:00Z
14,435,119
7
2013-01-21T08:48:24Z
[ "python", "pip", "gevent", "libevent" ]
I'm trying to install gevent on Windows. In order to do that, I've downloaded and compiled libevent, then I run `pip install gevent` and get an error: `Please provide path to libevent source with --libevent DIR`. How can I pass the `libevent` option to `setup.py` using `pip`? Thanks in advance, Ivan. UPD: running `pi...
Download the precompiled packages here: * <http://pypi.python.org/pypi/greenlet> * <http://pypi.python.org/pypi/gevent> This worked for me, python 2.7 32 bit build.
Coding Style: How to Make Obvious Determination of Parameter's Type We Have To Pass To a Function?
9,500,208
2
2012-02-29T13:41:21Z
9,500,293
7
2012-02-29T13:46:56Z
[ "coding-style", "python" ]
What is the best way to document the type of parameters that a function expects to receive? Sometimes a function uses only one or two fields of an object. Sometimes this fields have common names (get(), set(), reset(), etc.). In this situation we must leave a comments: ``` ... @staticmethod def get( post...
Given python's 'duck-typing' (late bound) behaviour, it would be a mistake to require a particular type. If you know which types your function must not take, you can raise an exception after detecting those; otherwise, simply raise an exception if the object passed does not support the appropriate protocol. As to doc...
Apache not serving django admin static files
9,500,598
35
2012-02-29T14:08:41Z
9,500,866
28
2012-02-29T14:26:54Z
[ "python", "django", "apache", "mod-wsgi" ]
Let me thanks you guys at the Stack Overflow community for helping me with various Django and Apache (with mod\_wsgi) errors. I've asked about 5 related questions so far and now I'm getting closer and closer to getting my content out on a production site! So I know there are many similar questions about this and I hav...
I think you should change: ``` Alias /media/ "/usr/lib/python2.6/site-packages/django/contrib/admin/media" ``` to: ``` Alias /static/admin/ "/usr/lib/python2.6/site-packages/django/contrib/admin/media" ``` Because you have: ``` ADMIN_MEDIA_PREFIX = '/static/admin/' ```
Apache not serving django admin static files
9,500,598
35
2012-02-29T14:08:41Z
26,962,932
11
2014-11-16T22:42:41Z
[ "python", "django", "apache", "mod-wsgi" ]
Let me thanks you guys at the Stack Overflow community for helping me with various Django and Apache (with mod\_wsgi) errors. I've asked about 5 related questions so far and now I'm getting closer and closer to getting my content out on a production site! So I know there are many similar questions about this and I hav...
That's because you haven't setup your STATIC files... Add to settings: ``` STATIC_URL = '/static/' STATIC_ROOT = '/var/www/static/' ``` Then run "python manage.py collectstatic" That will put all the files under STATIC\_ROOT which STATIC\_URL will serve... You shouldn't point Apache at your Python lib files!! If y...
Is it possible to use X-AppEngine-Country within an application
9,500,604
2
2012-02-29T14:08:56Z
9,500,973
11
2012-02-29T14:33:30Z
[ "python", "google-app-engine", "geolocation" ]
When serving a request, GAE automatically inserts response header `X-AppEngine-Country` set to a value indicating the country from which the request was emitted. However, before GAE issues the response, I’d like to be able to use this value in a snippet of mine. I wrote this code: ``` class TestPage(webapp2.Request...
You're trying to get the headers of the response (which you're about to make), rather than the headers of the request. Try this instead. ``` country = self.request.headers.get('X-AppEngine-Country') ``` <http://code.google.com/appengine/docs/python/tools/webapp/requestclass.html#Request_headers> > The request header...
How to use copyfile when there are spaces in the directory name?
9,500,735
4
2012-02-29T14:18:30Z
9,500,783
9
2012-02-29T14:22:22Z
[ "python", "windows", "copyfile" ]
I am trying to perform a simple file copy task under Windows and I am having some problems. My first attempt was to use ``` import shutils source = 'C:\Documents and Settings\Some directory\My file.txt' destination = 'C:\Documents and Settings\Some other directory\Copy.txt' shutil.copyfile(source, destination) ``` ...
I don't think spaces are to blame. You have to escape backslashes in paths, like this: ``` source = 'C:\\Documents and Settings\\Some directory\\My file.txt' ``` or, even better, use the `r` prefix: ``` source = r'C:\Documents and Settings\Some directory\My file.txt' ```
how enable requests async mode?
9,501,663
16
2012-02-29T15:15:00Z
9,525,558
7
2012-03-01T23:00:02Z
[ "python", "asynchronous", "urllib2", "gevent", "python-requests" ]
for this code: ``` import sys import gevent from gevent import monkey monkey.patch_all() import requests import urllib2 def worker(url, use_urllib2=False): if use_urllib2: content = urllib2.urlopen(url).read().lower() else: content = requests.get(url, prefetch=True).content.lower() titl...
As was pointed out by Kenneth, another thing we can do is to let the `requests` module handle the asynchronous part. I've made changes to your code accordingly. Again, for me, the results show consistently that `requests` module performs better than `urllib2` Doing this means that we cannot "thread" the call back part...
how enable requests async mode?
9,501,663
16
2012-02-29T15:15:00Z
9,563,781
13
2012-03-05T08:45:28Z
[ "python", "asynchronous", "urllib2", "gevent", "python-requests" ]
for this code: ``` import sys import gevent from gevent import monkey monkey.patch_all() import requests import urllib2 def worker(url, use_urllib2=False): if use_urllib2: content = urllib2.urlopen(url).read().lower() else: content = requests.get(url, prefetch=True).content.lower() titl...
Sorry Kenneth Reitz. His library is wonderful. I am stupid. I need select monkey patch for httplib like this: ``` gevent.monkey.patch_all(httplib=True) ``` Because patch for httplib is disabled by default.
Python: why is __dict__ attribute not in built-in class instances
9,502,183
6
2012-02-29T15:46:28Z
9,502,290
9
2012-02-29T15:52:34Z
[ "python" ]
If my understanding of the Python data model is correct, both classes and class instances have associated `__dict__` objects which contain all the attributes. However, I'm a little confused as to why certain class instances, such as instances of `str` for example, don't have a `__dict__` attribute. If I create a custo...
Instances of types defined in C don't have a \_\_dict\_\_ attribute by default.
generators that defer to sub-generators
9,502,242
6
2012-02-29T15:50:01Z
9,502,260
11
2012-02-29T15:51:05Z
[ "python" ]
I yould like to have generators that defer to other generators, e.g. ``` def gx(): for i in [1, 2, 3]: yield i def gy(): for i in [11, 12, 13]: yield i def gz(): """this should defer to gx and gy to generate [1, 2, 3, 11, 12, 13]""" for i in gx(): yield i for i in gy(): yie...
Using [`itertools.chain`](http://docs.python.org/library/itertools.html#itertools.chain): ``` import itertools gz = itertools.chain(gx(), gy()) ``` In the documentation of `chain` they describe it by implementation: ``` def chain(*iterables): for it in iterables: for element in it: yield ele...
generators that defer to sub-generators
9,502,242
6
2012-02-29T15:50:01Z
9,502,280
17
2012-02-29T15:51:53Z
[ "python" ]
I yould like to have generators that defer to other generators, e.g. ``` def gx(): for i in [1, 2, 3]: yield i def gy(): for i in [11, 12, 13]: yield i def gz(): """this should defer to gx and gy to generate [1, 2, 3, 11, 12, 13]""" for i in gx(): yield i for i in gy(): yie...
In currently released Python versions, an explicit loop is the only way to invoke sub-generators. (I presume your example is just, well, an example -- not the exact problem you want to solve.) Python 3.3 will add the special syntax `yield from` for this purpose: ``` def gz(): """this should defer to gx and gy to ...
Removing duplicate interaction pairs in python sets
9,502,469
3
2012-02-29T16:03:03Z
9,502,512
7
2012-02-29T16:05:40Z
[ "python", "set", "tuples" ]
suppose you have a list of tuples in a python set: ``` >>> pairs = set( [(0,1),(0,1),(1,0)] ) >>> print pairs set([(0, 1), (1, 0)]) ``` Obviously, the first two elements are duplicates and according to the definition of a set, "pairs" only holds unique elements. However, in my particular case the tuple (i,j) defines...
How about: ``` In [4]: pairs = set( [(0,1),(0,1),(1,0),(1,2),(1,0),(2,1)] ) In [5]: set((a,b) if a<=b else (b,a) for a,b in pairs) Out[5]: set([(0, 1), (1, 2)]) ```
How to know time spent on each test when using unittest?
9,502,516
13
2012-02-29T16:05:54Z
9,502,897
20
2012-02-29T16:28:40Z
[ "python", "performance", "unit-testing" ]
Unittest presents only total time spent on running all tests but does not present time spent on each test separately. How to add timing of each test when using unittest?
I suppose, that it's not possible for now: <http://bugs.python.org/issue4080>. But you can do something like this: ``` import unittest import time class SomeTest(unittest.TestCase): def setUp(self): self.startTime = time.time() def tearDown(self): t = time.time() - self.startTime pri...
Is it possible to use "exe installers" with pip?
9,503,194
10
2012-02-29T16:49:25Z
20,020,370
8
2013-11-16T15:46:32Z
[ "python", "pip" ]
It's possible with easy\_install to install exes from <http://www.lfd.uci.edu/~gohlke/pythonlibs/>. Is there a way to do the same thing with pip? Thanks.
I don't think this is possible with pip, but this can be done with easy\_install. e.g. easy\_install -U -Z "exe\_installer\_path"
Convert string into Date type on Python
9,504,356
10
2012-02-29T18:07:04Z
9,504,410
21
2012-02-29T18:10:47Z
[ "python", "string", "date", "type-conversion" ]
I have this string: ``` '2012-02-10' # (year-month-day) ``` and I need it to be as date type for me to use the date function `isoweekday()`. Does anyone know how I can convert this string into a date?
You can do that with [`datetime.strptime()`](http://docs.python.org/library/datetime.html#datetime.datetime.strptime) Example: ``` >>> from datetime import datetime >>> datetime.strptime('2012-02-10' , '%Y-%m-%d') datetime.datetime(2012, 2, 10, 0, 0) >>> _.isoweekday() 5 ``` You can find the table with all the `strp...
Convert string into Date type on Python
9,504,356
10
2012-02-29T18:07:04Z
24,476,708
19
2014-06-29T13:55:54Z
[ "python", "string", "date", "type-conversion" ]
I have this string: ``` '2012-02-10' # (year-month-day) ``` and I need it to be as date type for me to use the date function `isoweekday()`. Does anyone know how I can convert this string into a date?
While it seems the question was answered per the OP's request, none of the answers give a good way to get a `datetime.date` object instead of a `datetime.datetime`. So for those searching and finding this thread: `datetime.date` has no `.strptime` method; use the one on `datetime.datetime` instead and then call `.date...
Running jQuery on a static HTML file from Bash
9,504,390
6
2012-02-29T18:09:42Z
9,504,474
8
2012-02-29T18:15:16Z
[ "jquery", "python", "bash" ]
I'm trying to write a simple script to simply check a webpage for a specific value: ``` $("a#infgHeader").text() == "Delivered"; ``` I'd like to automate this from a Bash script to be run at an interval. I'm also fine with using Python. I need to essentially make an HTTP request, get the response, and have a way to i...
Xpath is great for querying html. Something like this: ``` //a[@id='infgHeader']/@text ``` In chrome developer tool you can use the search box in the Elements tab to test the expression. Quick run in terminal: ``` $echo '<div id="test" text="foo">Hello</div>' | xpath '//div[@id="test"]/@text' Found 1 nodes: -- NO...
Evaluate multiple variables in one 'if' statement?
9,504,638
9
2012-02-29T18:30:43Z
9,504,674
25
2012-02-29T18:33:28Z
[ "python", "if-statement" ]
Say I have a bunch of variables that are either `True` or `False`. I want to evaluate a set of these variables in one if statement to see if they are all `False` like so: ``` if var1, var2, var3, var4 == False: # do stuff ``` Except that doesn't work. I know I can do this: ``` if var1 == False and var2 == False ...
You should [never test a boolean variable with `== True` (or `== False`)](http://programmers.stackexchange.com/questions/12807/make-a-big-deal-out-of-true). Instead, either write: ``` if not (var1 or var2 or var3 or var4): ``` or use [`any`](http://docs.python.org/library/functions.html#any) (and in related problems ...
Static files not loaded in a Bottle application when the trailing slash is omitted
9,505,256
2
2012-02-29T19:19:53Z
9,525,572
14
2012-03-01T23:01:53Z
[ "python", "apache", "bottle" ]
I am serving a test file through apache using Bottle. Following are my apache config: ``` WSGIDaemonProcess temp user=www-data group=www-data processes=1 threads=5 WSGIScriptAlias /temp /opt/gridops/usage/temp/adapter.wsgi <Directory /opt/gridops/usage/temp> WSGIProcessGroup temp WSGIApplicationGroup...
# The Problem The problematic line is this one: ``` <link rel="stylesheet" type="text/css" href="static/prettify.css" /> ``` The address of the CSS file is a relative one, thus the full absolute address is computed from the loaded page location. For `http://192.168.1.3/temp/`, it will be `http://192.168.1.3/temp/st...
Split string into strings of repeating elements
9,505,526
8
2012-02-29T19:38:52Z
9,505,566
25
2012-02-29T19:42:36Z
[ "python" ]
I want to split a string like: ``` 'aaabbccccabbb' ``` into ``` ['aaa', 'bb', 'cccc', 'a', 'bbb'] ``` What's an elegant way to do this in Python? If it makes it easier, it can be assumed that the string will only contain a's, b's and c's.
That is *the* use case for [`itertools.groupby`](http://docs.python.org/library/itertools.html#itertools.groupby) :) ``` >>> from itertools import groupby >>> s = 'aaabbccccabbb' >>> [''.join(y) for _,y in groupby(s)] ['aaa', 'bb', 'cccc', 'a', 'bbb'] ```
Python: How to prepend the string 'ub' to every pronounced vowel in a string?
9,505,714
7
2012-02-29T19:57:09Z
9,505,868
9
2012-02-29T20:10:06Z
[ "python", "regex", "string", "nlp" ]
**Example**: Speak -> Spubeak, [more info here](http://en.wikipedia.org/wiki/Ubbi_dubbi) Don't give me a solution, but point me in the right direction or tell which which python library I could use? I am thinking of regex since I have to find a vowel, but then which method could I use to insert 'ub' in front of a vowe...
It is more complex then just a simple regex [e.g.,](http://en.wikipedia.org/wiki/Ubbi_dubbi) ``` "Hi, how are you?" → "Hubi, hubow ubare yubou?" ``` Simple regex won't catch that `e` is not pronounced in `are`. You need a library that provides a pronunciation dictionary such as `nltk.corpus.cmudict`: ``` from nlt...
getting line-numbers that were changed
9,505,822
4
2012-02-29T20:06:26Z
9,506,715
10
2012-02-29T21:13:49Z
[ "python" ]
Given two text files A,B, what is an easy way to get the line numbers of lines in B not present in A? I see there's difflib, but don't see an interface for retrieving line numbers
[difflib](http://docs.python.org/library/difflib.html#difflib.Differ) can give you what you need. Assume: **a.txt** ``` this is a bunch of lines ``` **b.txt** ``` this is a different bunch of other lines ``` code like this: ``` import difflib fileA = open("a.txt", "rt").readlines() fileB = open("b.txt"...
Conditional command line arguments in Python using argparse
9,505,898
18
2012-02-29T20:13:15Z
9,506,255
14
2012-02-29T20:39:04Z
[ "python", "argparse" ]
I'd like to have a program that takes a `--action=` flag, where the valid choices are `dump` and `upload`, with `upload` being the default. If (and only if) `dump` is selected, I'd like there to also be a `--dump-format=` option. Is there a way to express this using argparse, or do I need to just accept all the argumen...
You could use [`parser.error`](http://docs.python.org/library/argparse.html#argparse.ArgumentParser.error): ``` import argparse parser = argparse.ArgumentParser() parser.add_argument('--action', choices=['upload', 'dump'], default='dump') parser.add_argument('--dump-format') args = parser.parse_args() if args.action !...
Conditional command line arguments in Python using argparse
9,505,898
18
2012-02-29T20:13:15Z
9,506,443
27
2012-02-29T20:53:31Z
[ "python", "argparse" ]
I'd like to have a program that takes a `--action=` flag, where the valid choices are `dump` and `upload`, with `upload` being the default. If (and only if) `dump` is selected, I'd like there to also be a `--dump-format=` option. Is there a way to express this using argparse, or do I need to just accept all the argumen...
Another way to approach the problem is by using [subcommands](http://docs.python.org/dev/library/argparse.html#sub-commands) (a'la git) with "action" as the first argument: ``` script dump --dump-format="foo" script upload ```
Conditional command line arguments in Python using argparse
9,505,898
18
2012-02-29T20:13:15Z
13,706,448
14
2012-12-04T15:37:52Z
[ "python", "argparse" ]
I'd like to have a program that takes a `--action=` flag, where the valid choices are `dump` and `upload`, with `upload` being the default. If (and only if) `dump` is selected, I'd like there to also be a `--dump-format=` option. Is there a way to express this using argparse, or do I need to just accept all the argumen...
The argparse module offers a way to do this without implementing your own requiredness checks. The example below uses "subparsers" or "sub commands". I've implemented a subparser for "dump" and one for "format". ``` import argparse parser = argparse.ArgumentParser() parser.add_argument('file', help='The file you want...
The scope of names defined in class block doesn't extend to the methods' blocks. Why is that?
9,505,979
9
2012-02-29T20:19:39Z
9,506,080
8
2012-02-29T20:26:18Z
[ "python", "oop", "class", "scope" ]
Reading the [documentation](http://docs.python.org/release/3.1.3/reference/executionmodel.html#naming-and-binding) I came across the following paragraph: > A scope defines the visibility of a name within a block. If a local > variable is defined in a block, its scope includes that block. If the > definition occurs in ...
This seems to be related to the use of an explicit `self` parameter, and the requirement that all method calls and instance attribute accesses explicitly use `self`. It would be at least strange if the uncommon case of accessing a class scope function as a normal function would be much easier than the common case of ac...
The scope of names defined in class block doesn't extend to the methods' blocks. Why is that?
9,505,979
9
2012-02-29T20:19:39Z
9,508,816
8
2012-03-01T00:15:05Z
[ "python", "oop", "class", "scope" ]
Reading the [documentation](http://docs.python.org/release/3.1.3/reference/executionmodel.html#naming-and-binding) I came across the following paragraph: > A scope defines the visibility of a name within a block. If a local > variable is defined in a block, its scope includes that block. If the > definition occurs in ...
A class block is syntactic sugar for building a dictionary, which is then passed to the metaclass (usually `type`) to construct the class object. ``` class A: i = 1 def f(self): print(i) ``` Is roughly equivalent to: ``` def f(self): print(i) attributes = {'f': f, 'i': 1) A = type('A', (object,) ...
Using python PIL to turn a RGB image into a pure black and white image
9,506,841
20
2012-02-29T21:23:25Z
9,506,960
33
2012-02-29T21:32:40Z
[ "python", "python-imaging-library", "python-2.7" ]
I'm using the Python Imaging Library for some very simple image manipulation, however I'm having trouble converting a greyscale image to a monochrome (black and white) image. If I save after changing the image to greyscale (convert('L')) then the image renders as you would expect. However, if I convert the image to a m...
``` from PIL import Image image_file = Image.open("convert_image.png") # open colour image image_file = image_file.convert('1') # convert image to black and white image_file.save('result.png') ``` yields ![enter image description here](http://i.stack.imgur.com/LCLP2.png)
datetime from string in Python, best-guessing string format
9,507,648
11
2012-02-29T22:27:36Z
9,517,287
19
2012-03-01T13:42:39Z
[ "python", "datetime" ]
The function to get a datetime from a string, `datetime.strptime(date_string, format)` requires a string format as the second argument. Is there a way to build a datetime from a string without without knowing the exact format, and having Python best-guess it?
Use the [dateutil](http://pypi.python.org/pypi/python-dateutil/1.5) library. I was already using dateutil as an indispensable lib for handling timezones (See [Convert UTC datetime string to local datetime](http://stackoverflow.com/a/4771733/165673) and [How do I convert local time to UTC in Python?](http://stackover...
Can I have a non-greedy regex with dotall?
9,507,819
7
2012-02-29T22:41:09Z
9,508,065
14
2012-02-29T23:03:18Z
[ "python", "regex", "non-greedy" ]
I would like to match dotall and non-greedy. This is what I have: ``` img(.*?)(onmouseover)+?(.*?)a ``` However, this is not being non-greedy. This data is not matching as I expected: ``` <img src="icon_siteItem.gif" alt="siteItem" title="A version of this resource is available on siteItem" border="0"></a><br><br></...
It is being non-greedy. It is your understanding of non-greedy that is not correct. A regex will ***always*** try to match. Let me show a simplified example of what non-greedy actually means(as suggested by a comment): ``` re.findall(r'a*?bc*?', 'aabcc', re.DOTALL) ``` This will match: * as few repetitions of 'a' ...
RabbitMQ, Pika and reconnection strategy
9,508,246
12
2012-02-29T23:21:17Z
11,907,871
16
2012-08-10T19:14:27Z
[ "python", "rabbitmq", "pika" ]
I'm using Pika to process data from RabbitMQ. As I seemed to run into different kind of problems I decided to write a small test application to see how I can handle disconnects. I wrote this test app which does following: 1. Connect to Broker, retry until successful 2. When connected create a queue. 3. Consume this q...
The main problem with your script is that it is interacting with a single channel from both your main thread (where the ioloop is running) and the "Broker" thread (calls `submitData` in a loop). This is [not safe](https://pika.readthedocs.io/en/0.10.0/faq.html). Also, `SimpleReconnectionStrategy` does not seem to do a...
Reload Flask app when template file changes
9,508,667
22
2012-03-01T00:00:03Z
9,511,655
36
2012-03-01T06:31:12Z
[ "python", "flask", "jinja" ]
By default, when running Flask application using the built-in server (`Flask.run`), it monitors its Python files and automatically reloads the app if its code changes: ``` * Detected change in '/home/xion/hello-world/app.py', reloading * Restarting with reloader ``` Unfortunately, this seems to work for *\*.py* files...
In my experience, templates don't even need the application to restart to be refreshed, as they should be loaded from disk everytime `render_template()` is called. Maybe your templates are used differently though. To reload your application when the templates change (or any other file), you can pass the `extra_files` ...
Reload Flask app when template file changes
9,508,667
22
2012-03-01T00:00:03Z
38,371,484
8
2016-07-14T10:14:20Z
[ "python", "flask", "jinja" ]
By default, when running Flask application using the built-in server (`Flask.run`), it monitors its Python files and automatically reloads the app if its code changes: ``` * Detected change in '/home/xion/hello-world/app.py', reloading * Restarting with reloader ``` Unfortunately, this seems to work for *\*.py* files...
you can use TEMPLATES\_AUTO\_RELOAD = True From <http://flask.pocoo.org/docs/0.11/config/> > Whether to check for modifications of the template source and reload it automatically. By default the value is None which means that Flask checks original file only in debug mode.
How do I pass a parameter to a python Hadoop streaming job?
9,509,063
7
2012-03-01T00:43:46Z
9,509,200
13
2012-03-01T01:02:56Z
[ "python", "hadoop", "hadoop-streaming" ]
For a python Hadoop streaming job, how do I pass a parameter to, for example, the reducer script so that it behaves different based on the parameter being passed in? I understand that streaming jobs are called in the format of: hadoop jar hadoop-streaming.jar -input -output -mapper mapper.py -reducer reducer.py ... ...
The argument to the command line option `-reducer` can be any command, so you can try: ``` $HADOOP_HOME/bin/hadoop jar $HADOOP_HOME/hadoop-streaming.jar \ -input inputDirs \ -output outputDir \ -mapper myMapper.py \ -reducer 'myReducer.py 1 2 3' \ -file myMapper.py \ -file myReducer.py ``` as...
Efficient way to add a singleton dimension to a NumPy vector so that slice assignments work
9,510,252
16
2012-03-01T03:32:38Z
9,511,135
31
2012-03-01T05:35:38Z
[ "python", "numpy" ]
In NumPy, how can you efficiently make a 1-D object into a 2-D object where the singleton dimension is inferred from the current object (i.e. a list should go to either a 1xlength or lengthx1 vector)? ``` # This comes from some other, unchangeable code that reads data files. my_list = [1,2,3,4] # What I want to do...
In the most general case, the easiest way to add extra dimensions to an array is by using the keyword `None` when indexing at the position to add the extra dimension. For example ``` my_array = numpy.array([1,2,3,4]) my_array[None, :] # shape 1x4 my_array[:, None] # shape 4x1 ```
Removing pip's cache?
9,510,474
109
2012-03-01T04:06:35Z
9,510,610
122
2012-03-01T04:26:15Z
[ "python", "pip" ]
I need to install psycopg2 v2.4.1 specifically. I accidentally did: ``` pip install psycopg2 ``` Instead of: ``` pip install psycopg2==2.4.1 ``` That installs 2.4.4 instead of the earlier version. Now even after I pip uninstall psycopg2 and attempt to reinstall with the correct version, it appears that pip is re...
If using pip older than pip 6.0, try deleting the entry in `~/.pip/cache/` and or the directory `$PWD/build/` if it exists. You can also try the `--ignore-installed` option. In windows this is located under `%USERPROFILE%\AppData\Local\pip\cache`. If using pip 6.0 or newer, try using the `--no-cache-dir` option.
Removing pip's cache?
9,510,474
109
2012-03-01T04:06:35Z
10,082,293
7
2012-04-10T02:16:08Z
[ "python", "pip" ]
I need to install psycopg2 v2.4.1 specifically. I accidentally did: ``` pip install psycopg2 ``` Instead of: ``` pip install psycopg2==2.4.1 ``` That installs 2.4.4 instead of the earlier version. Now even after I pip uninstall psycopg2 and attempt to reinstall with the correct version, it appears that pip is re...
I just had a similar problem and found that the only way to get pip to upgrade the package was to delete the `$PWD/build` (`%CD%\build` on Windows) directory that might have been left over from a previously unfinished install or a previous version of pip (it now deletes the build directories after a successful install)...
Removing pip's cache?
9,510,474
109
2012-03-01T04:06:35Z
16,427,233
25
2013-05-07T19:42:54Z
[ "python", "pip" ]
I need to install psycopg2 v2.4.1 specifically. I accidentally did: ``` pip install psycopg2 ``` Instead of: ``` pip install psycopg2==2.4.1 ``` That installs 2.4.4 instead of the earlier version. Now even after I pip uninstall psycopg2 and attempt to reinstall with the correct version, it appears that pip is re...
On Ubuntu, I had to delete `/tmp/pip-build-root`.
Removing pip's cache?
9,510,474
109
2012-03-01T04:06:35Z
27,666,197
56
2014-12-27T10:04:16Z
[ "python", "pip" ]
I need to install psycopg2 v2.4.1 specifically. I accidentally did: ``` pip install psycopg2 ``` Instead of: ``` pip install psycopg2==2.4.1 ``` That installs 2.4.4 instead of the earlier version. Now even after I pip uninstall psycopg2 and attempt to reinstall with the correct version, it appears that pip is re...
From documentation at <https://pip.pypa.io/en/latest/reference/pip_install.html#caching>: Starting with v6.0, pip provides an on by default cache which functions similarly to that of a web browser. While the cache is on by default and is designed do the right thing by default you can disable the cache and always acces...