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 |
|---|---|---|---|---|---|---|---|---|---|
How to modify list entries during for loop? | 4,081,217 | 43 | 2010-11-02T19:04:29Z | 18,967,893 | 7 | 2013-09-23T20:07:07Z | [
"python"
] | Now I know that it is not safe to modify the list during an iterative looping. However, suppose I have a list of strings, and I want to strip the strings themselves. Does replacement of mutable values count as modification? | One more for loop variant, looks cleaner to me than one with enumerate():
```
for idx in range(len(list)):
list[idx]=... # set a new value
# some other code which doesn't let you use a list comprehension
``` |
What is the difference between list and list[:] in python? | 4,081,561 | 33 | 2010-11-02T19:52:49Z | 4,081,583 | 16 | 2010-11-02T19:54:56Z | [
"python"
] | What, if any, is the difference between `list` and `list[:]` in python? | The latter is a reference to a copy of the list and not a reference to the list. So it's very useful.
```
>>> li = [1,2,3]
>>> li2 = li
>>> li3 = li[:]
>>> li2[0] = 0
>>> li
[0, 2, 3]
>>> li3
[1, 2, 3]
``` |
What is the difference between list and list[:] in python? | 4,081,561 | 33 | 2010-11-02T19:52:49Z | 4,081,587 | 56 | 2010-11-02T19:55:11Z | [
"python"
] | What, if any, is the difference between `list` and `list[:]` in python? | When reading, `list` is a reference to the original list, and `list[:]` shallow-copies the list.
When assigning, `list` (re)binds the name and `list[:]` slice-assigns, replacing what was previously in the list.
Also, don't use `list` as a name since it shadows the built-in. |
Position in an list? (Python) | 4,081,672 | 9 | 2010-11-02T20:07:44Z | 4,081,693 | 21 | 2010-11-02T20:10:38Z | [
"python",
"list",
"position"
] | I will check if a word exists in a list.
How can I show the position of this word? | ```
list = ["word1", "word2", "word3"]
try:
print list.index("word1")
except ValueError:
print "word1 not in list."
```
This piece of code will print `0`, because that's the index of the first occurrence of `"word1"` |
Using the --quiet tag when extending Mercurial | 4,081,717 | 5 | 2010-11-02T20:15:03Z | 4,081,917 | 7 | 2010-11-02T20:43:16Z | [
"python",
"mercurial",
"mercurial-extension"
] | I'm writing a Mercurial extension in Python and need to call the "Pull" command using the [Mercurial API](http://mercurial.selenic.com/wiki/MercurialApi), but I want to suppress its output using the --quiet flag.
In Hg terms, I want to execute the following code, but from within my extension:
```
hg pull --quiet
```
... | Global options are affected through the ui object. It allows you to control many of the things you would normally set in your (or the repository's) hgrc. In this case, you want to set the `quiet` option in the `ui` section to True.
```
ui.setconfig('ui', 'quiet', True)
commands.pull(ui, repo)
``` |
How do I use the HtmlUnit driver with Selenium through the Python bindings? | 4,081,724 | 8 | 2010-11-02T20:16:11Z | 10,674,316 | 8 | 2012-05-20T14:35:48Z | [
"python",
"selenium",
"webdriver"
] | I'm using WebDriver through the Python bindings [located on Google's site](http://code.google.com/p/selenium/wiki/PythonBindings). According to the documentation [here](http://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions#Q%3a_Which_browsers_does_support?), it supports four browsers: Chrome, IE, Firefox, and... | I found the answer at <http://stackoverflow.com/a/5518175/125170>
> As of the 2.0b3 release of the python client you can create an
> HTMLUnit webdriver via a remote connection like so:
```
from selenium import webdriver
driver = webdriver.Remote(
desired_capabilities=webdriver.DesiredCapabilities.HTMLUNIT)
driver.g... |
why does python inspect.isclass think an instance is a class? | 4,081,819 | 5 | 2010-11-02T20:30:10Z | 4,081,911 | 10 | 2010-11-02T20:42:49Z | [
"python",
"introspection"
] | Given the following module:
```
class Dummy(dict):
def __init__(self, data):
for key, value in data.iteritems():
self.__setattr__(key, value)
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__=dict.__setitem__
__delattr__=dict.__delitem__
foo=Dummy({"one... | Prior to Python v2.7, `inspect.isclass` naively assumed anything with a `__bases__` attribute must be a class.
`Dummy`'s `__getattr__` makes `Dummy` instances appear to have *every* attribute (with a value of `None`).
Therefore, to `inspect.isclass`, `foo` appears to be a class.
Note: [`__getattr__` should raise`Att... |
Scatter plot with a huge amount of data | 4,082,298 | 9 | 2010-11-02T21:35:30Z | 4,082,392 | 16 | 2010-11-02T21:46:45Z | [
"python",
"numpy",
"matplotlib"
] | I would like to use [Matplotlib](http://en.wikipedia.org/wiki/Matplotlib) to generate a scatter plot with a huge amount of data (about 3 million points). Actually I've 3 vectors with the same dimension and I use to plot in the following way.
```
import matplotlib.pyplot as plt
import numpy as np
from numpy import *
fr... | Unless your graphic is huge, many of those 3 million points are going to overlap.
(A 400x600 image only has 240K dots...)
So the easiest thing to do would be to take a sample of say, 1000 points, from your data:
```
import random
delta_sample=random.sample(delta,1000)
```
and just plot that.
For example:
```
impor... |
Scatter plot with a huge amount of data | 4,082,298 | 9 | 2010-11-02T21:35:30Z | 4,146,498 | 7 | 2010-11-10T16:14:44Z | [
"python",
"numpy",
"matplotlib"
] | I would like to use [Matplotlib](http://en.wikipedia.org/wiki/Matplotlib) to generate a scatter plot with a huge amount of data (about 3 million points). Actually I've 3 vectors with the same dimension and I use to plot in the following way.
```
import matplotlib.pyplot as plt
import numpy as np
from numpy import *
fr... | What about trying [pyplot.hexbin](http://matplotlib.sourceforge.net/examples/pylab_examples/hexbin_demo.html)? It generates a sort of heatmap based on point density in a set number of bins. |
Calculate "Solar Noon" using ephem, translating to local time | 4,082,533 | 7 | 2010-11-02T22:09:09Z | 4,114,792 | 7 | 2010-11-06T19:30:18Z | [
"python",
"datetime",
"astronomy"
] | I have looked at the examples here on using ephem to calculate sunrise and sunset, and have that working great.
I get in trouble when I try to calculate the midpoint between those two times. Here's what I have:
```
import datetime
import ephem
o = ephem.Observer()
o.lat, o.long, o.date = '37.0625', '-95.677068', dat... | Solar noon is *not* the mean of sunrise and sunset (see [equation of time](http://en.wikipedia.org/wiki/Equation_of_time) for the explanation). The `ephem` package has [methods for getting transit times](http://rhodesmill.org/pyephem/quick.html#transit-rising-setting) which you should use instead:
```
>>> import ephem... |
Return a list of weekdays | 4,082,772 | 10 | 2010-11-02T22:44:49Z | 4,082,881 | 9 | 2010-11-02T23:03:01Z | [
"python"
] | My task is to deï¬ne a function `weekdays(weekday)` that returns a list of weekdays, starting with weekday. It should work like this:
```
>>> weekdays('Wednesday')
['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']
```
So far I've come up with this one:
```
def weekdays(weekday):
day... | A far quicker approach would be to keep in mind, that the weekdays *cycle*. As such, we just need to get the first day we want to include the list, and add the remaining 6 elements to the end. Or in other words, we get the weekday list starting from the starting day, append another full week, and return only the first ... |
Return a list of weekdays | 4,082,772 | 10 | 2010-11-02T22:44:49Z | 4,083,447 | 13 | 2010-11-03T01:09:29Z | [
"python"
] | My task is to deï¬ne a function `weekdays(weekday)` that returns a list of weekdays, starting with weekday. It should work like this:
```
>>> weekdays('Wednesday')
['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']
```
So far I've come up with this one:
```
def weekdays(weekday):
day... | The reason your code is only returning one day name is because `weekday` will never match more than one string in the `days` tuple and therefore won't add any of the days of the week that follow it (nor wrap around to those before it). Even if it did somehow, it would still return them all as one long string because yo... |
List comprehension and len() vs. simple for loop | 4,083,098 | 4 | 2010-11-02T23:46:27Z | 4,083,113 | 13 | 2010-11-02T23:50:15Z | [
"python",
"list-comprehension"
] | I'm supposed to take a list of words and count all words in it which are 2 or more characters long and where the first and last character are equal.
I came up with two possible solutions:
```
result = 0
for word in words:
if len(word) >= 2 and word[0] == word[-1]:
result += 1
return result
```
vs.
```
r... | In your second example a [generator expression](http://www.python.org/dev/peps/pep-0289/) would be better than list-comp if your list is large.
```
sum(1 for word in words if len(word) >= 2 and word[0] == word[-1])
``` |
negative zero in python | 4,083,401 | 30 | 2010-11-03T00:57:31Z | 4,083,417 | 7 | 2010-11-03T01:01:53Z | [
"python",
"floating-point",
"python-3.x",
"floating-accuracy",
"zero"
] | **[Python 3.1]**
I encountered negative zero in output from python; it's created for example as follows:
```
k = 0.0
print(-k)
```
The output will be `-0.0`.
However, when I compare the `-k` to 0.0 for equality, it yields True. Is there any difference between `0.0` and `-0.0` (I don't care that they presumably have... | Yes, there is a difference between 0.0 and -0.0 (though Python won't let me reproduce it :-P). If you divide a positive number by 0.0, you get positive infinity; if you divide that same number by -0.0 you get negative infinity.
Beyond that, though, there is no practical difference between the two values. |
negative zero in python | 4,083,401 | 30 | 2010-11-03T00:57:31Z | 4,083,431 | 17 | 2010-11-03T01:04:11Z | [
"python",
"floating-point",
"python-3.x",
"floating-accuracy",
"zero"
] | **[Python 3.1]**
I encountered negative zero in output from python; it's created for example as follows:
```
k = 0.0
print(-k)
```
The output will be `-0.0`.
However, when I compare the `-k` to 0.0 for equality, it yields True. Is there any difference between `0.0` and `-0.0` (I don't care that they presumably have... | Check out : [â0 (number) in Wikipedia](http://en.wikipedia.org/wiki/%E2%88%920_%28number%29)
Basically IEEE does actually define a negative zero
And by this definition for all purposes :
```
-0.0 == +0.0 == 0
```
I agree with aaronasterling that -0.0 and +0.0 are different objects. Making them equal (equality ope... |
negative zero in python | 4,083,401 | 30 | 2010-11-03T00:57:31Z | 4,084,219 | 13 | 2010-11-03T04:24:20Z | [
"python",
"floating-point",
"python-3.x",
"floating-accuracy",
"zero"
] | **[Python 3.1]**
I encountered negative zero in output from python; it's created for example as follows:
```
k = 0.0
print(-k)
```
The output will be `-0.0`.
However, when I compare the `-k` to 0.0 for equality, it yields True. Is there any difference between `0.0` and `-0.0` (I don't care that they presumably have... | It makes a difference in the [`atan2()`](http://docs.python.org/py3k/library/math.html#math.atan2) function (at least, in some implementations). In my Python 3.1 and 3.2 on Windows (which is based on the underlying C implementation, according to the note **CPython implementation detail** near the [bottom of the Python ... |
Multiple reactors (main loops) in one application through threading (or alternative means) | 4,084,090 | 15 | 2010-11-03T03:56:37Z | 4,086,052 | 17 | 2010-11-03T10:25:57Z | [
"python",
"multithreading",
"events",
"twisted",
"reactor"
] | I've got an idea for an app I'd like to work on to learn a bit more about [Twisted](http://twistedmatrix.com/trac/) and [WebSockets](http://en.wikipedia.org/wiki/WebSockets). I was thinking of integrating a previously written IRC Bot into a web application. As far as I can see it, I would need three reactors to make it... | Lucky for you, it is easy to reduce the number of reactors, specifically, to 1:
You can only ever have a single reactor, in a single thread, in any given Twisted process. If you try to have more, nothing will work.
The whole point of a reactor, actually, is to facilitate having multiple sources of events combined int... |
Creating a dictionary from an iterable | 4,084,749 | 6 | 2010-11-03T06:43:51Z | 4,084,767 | 11 | 2010-11-03T06:48:23Z | [
"python",
"dictionary"
] | What is the easiest way to create a dictionary from an iterable and assigning it some default value? I tried:
```
>>> x = dict(zip(range(0, 10), range(0)))
```
But that doesn't work since range(0) is not an iterable as I thought it would not be (but I tried anyways!)
So how do I go about it? If I do:
```
>>> x = di... | You need the `dict.fromkeys` method, which does exactly what you want.
From the docs:
```
fromkeys(...)
dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
v defaults to None.
```
So what you need is:
```
>>> x = dict.fromkeys(range(0, 10), 0)
>>> x
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, ... |
Creating a dictionary from an iterable | 4,084,749 | 6 | 2010-11-03T06:43:51Z | 4,084,787 | 8 | 2010-11-03T06:51:38Z | [
"python",
"dictionary"
] | What is the easiest way to create a dictionary from an iterable and assigning it some default value? I tried:
```
>>> x = dict(zip(range(0, 10), range(0)))
```
But that doesn't work since range(0) is not an iterable as I thought it would not be (but I tried anyways!)
So how do I go about it? If I do:
```
>>> x = di... | In python 3, You can use a dict comprehension.
```
>>> {i:0 for i in range(0,10)}
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}
```
Fortunately, this has been backported in python 2.7 so that's also available there. |
How to check the last element of a python list? | 4,085,417 | 6 | 2010-11-03T08:58:08Z | 4,085,427 | 15 | 2010-11-03T08:59:27Z | [
"python",
"list",
"stack"
] | In python I need a stack, and I'm using a *list* for it. In the documenation it says that you can use *append()* and *pop()* for stack operations but what about accessing the top of the stack without removing it?
How to do that in the most readable way? Because all I came up with is `stack[-1:][0]` which looks a bit u... | No need to slice.
```
stack[-1]
``` |
(python) meaning of st_mode | 4,087,427 | 4 | 2010-11-03T13:20:36Z | 4,087,441 | 17 | 2010-11-03T13:22:35Z | [
"python"
] | first, sorry if my English is bad
I'm newbie in python too...
Can anyone tell me what is the meaning of the number from the ST\_MODE function
example:
```
>>>import os
>>>stat = os.stat('/home')
>>>print stat.st_mode
16877
```
it prints '16877'. What is that for? | It's the permission bits of the file.
```
>>> oct(16877)
'040755'
```
See the various `stat.S_*` attributes for more info. |
django template date filter format string question | 4,087,717 | 3 | 2010-11-03T13:55:10Z | 4,087,761 | 13 | 2010-11-03T13:59:23Z | [
"python",
"django"
] | I have a datetime value that is available in a django template.
I am trying to format the date as "d-mmm"
so for example dates are formated as:
* 5-Mar
* 10-Mar
* 4-Apr
etc.
I have tried different combinations - NOTHING works so far?. I hope I dont have to write a custom filter just to format a date ?
**[Edit]**
... | Have you tried `{{ some_date|date:"j-M" }}`?
<http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date> |
How can I improve my paw detection? | 4,087,919 | 176 | 2010-11-03T14:13:05Z | 4,092,160 | 333 | 2010-11-03T22:18:10Z | [
"python",
"image-processing"
] | After my previous question on [finding toes within each paw](http://stackoverflow.com/questions/3684484), I started loading up other measurements to see how it would hold up. Unfortunately, I quickly ran into a problem with one of the preceding steps: recognizing the paws.
You see, my proof of concept basically took t... | If you're just wanting (semi) contiguous regions, there's already an easy implementation in Python: [SciPy](http://en.wikipedia.org/wiki/SciPy)'s [ndimage.morphology](http://www.scipy.org/doc/api_docs/SciPy.ndimage.morphology.html) module. This is a fairly common [image morphology](http://en.wikipedia.org/wiki/Mathemat... |
How can this very long if-statement be simplified? | 4,088,145 | 6 | 2010-11-03T14:35:47Z | 4,088,166 | 7 | 2010-11-03T14:37:55Z | [
"python",
"graphics",
"if-statement",
"modulus",
"simplification"
] | How can this if-statement be simplified? It makes a plus sign:
<http://i.stack.imgur.com/PtHO1.png>
If the statement is completed, then a block is set at the x and y coordinates.
```
for y in range(MAP_HEIGHT):
for x in range(MAP_WIDTH):
if (x%5 == 2 or x%5 == 3 or x%5 == 4) and \
(y%5 == 2 or... | There are two trivial fixes:
* Cache the result of `x % 5` and `y % 5`
* Use `in` or chained `<` to test the values:
Additionally, the test for `<= 4` (or `< 5`) is actually redundant because *every* value of `lx` and `ly` will be < 5.
```
for y in range(MAP_HEIGHT):
for x in range(MAP_WIDTH):
lx = x % 5... |
How can this very long if-statement be simplified? | 4,088,145 | 6 | 2010-11-03T14:35:47Z | 4,088,233 | 15 | 2010-11-03T14:44:26Z | [
"python",
"graphics",
"if-statement",
"modulus",
"simplification"
] | How can this if-statement be simplified? It makes a plus sign:
<http://i.stack.imgur.com/PtHO1.png>
If the statement is completed, then a block is set at the x and y coordinates.
```
for y in range(MAP_HEIGHT):
for x in range(MAP_WIDTH):
if (x%5 == 2 or x%5 == 3 or x%5 == 4) and \
(y%5 == 2 or... | This is the same:
```
if (x % 5 == 3 and y % 5 > 1) or (y % 5 == 3 and x % 5 > 1):
``` |
How can this very long if-statement be simplified? | 4,088,145 | 6 | 2010-11-03T14:35:47Z | 4,090,162 | 12 | 2010-11-03T18:08:08Z | [
"python",
"graphics",
"if-statement",
"modulus",
"simplification"
] | How can this if-statement be simplified? It makes a plus sign:
<http://i.stack.imgur.com/PtHO1.png>
If the statement is completed, then a block is set at the x and y coordinates.
```
for y in range(MAP_HEIGHT):
for x in range(MAP_WIDTH):
if (x%5 == 2 or x%5 == 3 or x%5 == 4) and \
(y%5 == 2 or... | Basically you're tiling a 5x5 binary pattern. Here's a clear expression of that:
```
pattern = [[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 1, 1, 1],
[0, 0, 0, 1, 0]]
for y in range(MAP_HEIGHT):
for x in range(MAP_WIDTH):
if pattern[x%5][y%5]:
... |
Sorted Word frequency count using python | 4,088,265 | 23 | 2010-11-03T14:48:07Z | 4,088,296 | 49 | 2010-11-03T14:50:11Z | [
"python",
"sorting",
"word-frequency"
] | I have to count the word frequency in a text using python. I thought of keeping words in a dictionary and having a count for each of these words.
Now if I have to sort the words according to # of occurrences. Can i do it with same dictionary instead of using a new dictionary which has the key as the count and array of... | **WARNING:** This example requires Python 2.7 or higher.
Python's built-in [`Counter`](http://docs.python.org/library/collections.html#collections.Counter) object is exactly what you're looking for. Counting words is even the first example in the documentation:
```
>>> # Tally occurrences of words in a list
>>> from ... |
Sorted Word frequency count using python | 4,088,265 | 23 | 2010-11-03T14:48:07Z | 4,088,333 | 16 | 2010-11-03T14:54:10Z | [
"python",
"sorting",
"word-frequency"
] | I have to count the word frequency in a text using python. I thought of keeping words in a dictionary and having a count for each of these words.
Now if I have to sort the words according to # of occurrences. Can i do it with same dictionary instead of using a new dictionary which has the key as the count and array of... | You can use the same dictionary:
```
>>> d = { "foo": 4, "bar": 2, "quux": 3 }
>>> sorted(d.items(), key=lambda item: item[1])
```
The second line prints:
```
[('bar', 2), ('quux', 3), ('foo', 4)]
```
If you only want a sorted word list, do:
```
>>> [pair[0] for pair in sorted(d.items(), key=lambda item: item[1])]... |
Is it possible to use Nose to run one test multiple times, concurrently? | 4,088,354 | 10 | 2010-11-03T14:55:45Z | 4,666,599 | 11 | 2011-01-12T08:21:35Z | [
"python",
"unit-testing",
"nose"
] | Is it possible to use [`nose`](http://somethingaboutorange.com/mrl/projects/nose) to run **a single test** concurrently (across multiple processes) and aggregate the result in to a single pass/fail result?
We have the need to run the same test multiple times concurrently to ensure resource locking isn't being affected... | This seems like something you want in the test definition itself because you want to assert on the aggregation of the results. I would take a look at using [multiprocessing](http://docs.python.org/library/multiprocessing.html) in the test. Create a pool to execute your code in parallel. You can use a [Queue](http://doc... |
Is it possible to use Nose to run one test multiple times, concurrently? | 4,088,354 | 10 | 2010-11-03T14:55:45Z | 4,668,147 | 9 | 2011-01-12T11:19:00Z | [
"python",
"unit-testing",
"nose"
] | Is it possible to use [`nose`](http://somethingaboutorange.com/mrl/projects/nose) to run **a single test** concurrently (across multiple processes) and aggregate the result in to a single pass/fail result?
We have the need to run the same test multiple times concurrently to ensure resource locking isn't being affected... | It is possible to [run tests concurrently with nose](http://packages.python.org/nose/doc_tests/test_multiprocess/multiprocess.html):
> Using the nose.plugin.multiprocess
> plugin, you can parallelize a test run
> across a configurable number of worker
> processes. While this can speed up
> CPU-bound test runs, it is m... |
Python in Windows: large number of inserts using pyodbc causes memory leak | 4,088,931 | 3 | 2010-11-03T15:54:36Z | 6,393,357 | 8 | 2011-06-18T01:50:06Z | [
"python",
"memory-leaks",
"pyodbc"
] | I am trying to populate a MS SQL 2005 database using python on windows. I am inserting millions of rows, and by 7 million I am using almost a gigabyte of memory. The test below eats up 4 megs of RAM for each 100k rows inserted:
```
import pyodbc
connection=pyodbc.connect('DRIVER={SQL Server};SERVER=x;DATABASE=x;UID=x;... | I had the same issue, and it looks like a pyodbc issue with parameterized inserts: <http://code.google.com/p/pyodbc/issues/detail?id=145>
Temporarily switching to a static insert with the VALUES clause populated eliminates the leak, until I try a build from the current source. |
What is the way data is stored in *.npy? | 4,090,080 | 12 | 2010-11-03T17:59:44Z | 4,090,115 | 23 | 2010-11-03T18:03:08Z | [
"python",
"numpy"
] | I'm saving NumPy arrays using numpy.save function.
I want other developers to have capability to read data from those file using C language.
So I need to know,how numpy organizes binary data in file.OK, it's obvious when I'm saving array of 'i4' but what about array of arrays that contains some structures?Can't find an... | The npy file format is documented in numpy's <https://github.com/numpy/numpy/blob/master/doc/neps/npy-format.rst>.
For instance, the code
```
>>> dt=numpy.dtype([('outer','(3,)<i4'),
... ('outer2',[('inner','(10,)<i4'),('inner2','f8')])])
>>> a=numpy.array([((1,2,3),((10,11,12,13,14,15,16,17,18,19),3.... |
plotting unix timestamps in matplotlib | 4,090,383 | 24 | 2010-11-03T18:32:48Z | 4,091,264 | 38 | 2010-11-03T20:16:19Z | [
"python",
"matplotlib"
] | I'd like to make a generic value -vs- time plot with python's matplotlib module. My times are in unix time but I'd like them to show up in a readable format on the plot's x-axis.
I have read answers about plotting with datetime objects but this method seems to remove hour/min/sec information and rails timestamps to th... | It is possible to call `plt.plot(dates,values)` with `dates` being a list of `datetime.datetime` objects. The plot will include xticks in a format like `'%Y-%m-%d'` and as you zoom in, automatically change to one that shows hours, minutes, seconds.
However, it sounds like you desire more control than this. Perhaps it ... |
Overriding default tab behaviour in Python Tkinter | 4,090,683 | 4 | 2010-11-03T19:08:11Z | 4,090,749 | 9 | 2010-11-03T19:15:31Z | [
"python",
"user-interface",
"tkinter"
] | I am writing an application in Python using Tkinter to manage my GUI.
There is a text entry box on which I am trying to implement an autocompletion function which will bind to the Tab key.
I have bound the tab key to my entry box, but when I press tab, the program attempts to cycle between GUI elements.
How do I ove... | Return `'break'` at the end of your event handler. It interrupts event propagation.
```
def my_tab_handler(event):
... # handle tab event
return 'break' # interrupts event propagation to default handlers
``` |
How do I create a numpy array from string? | 4,090,981 | 9 | 2010-11-03T19:42:46Z | 4,091,495 | 19 | 2010-11-03T20:42:44Z | [
"python",
"arrays",
"numpy",
"fft"
] | I have a file reader that reads *n* bytes from a file and returns a string of chars representing that (binary) data. I want to read up *n* bytes into a numpy array of numbers and run a FFT on it, but I'm having trouble creating an array from a string. A couple lines of example would be awesome.
**Edit:**
I'm reading r... | You can do this directly with `numpy.fromstring`:
```
import numpy as np
s = '\x01\x05\x03\xff'
a = np.fromstring(s, dtype='uint8')
```
Once completing this, `a` is `array([ 1, 5, 3, 255])` and you can use the regular scipy/numpy FFT routines. |
subprocess.call requiring all parameters to be separated by commas | 4,091,242 | 8 | 2010-11-03T20:13:38Z | 4,091,502 | 23 | 2010-11-03T20:43:50Z | [
"python"
] | I used to be able to do a `subprocess.call(["command","-option value -option value"])` and it would work there was a change to the command to work properly with things in quotes, but now I have to change my subprocess call command to look like this:
```
subprocess.call(["command","-option","value","-option","value"])
... | Avoid `shell=True` if you can -- it's a [security risk](http://stackoverflow.com/questions/3172470/actual-meaning-of-shelltrue-in-subprocess). For this purpose, [shlex.split](http://docs.python.org/library/shlex.html#shlex.split) suffices:
```
import subprocess
import shlex
subprocess.call(shlex.split("command -option... |
Splitting a list of dictionaries into several lists of dictionaries | 4,091,680 | 7 | 2010-11-03T21:06:11Z | 4,091,743 | 9 | 2010-11-03T21:12:13Z | [
"python",
"list",
"dictionary",
"split"
] | I've been whacking away at this for a while to no avail... Any help would be greatly
appreciated.
I have:
```
[{'event': 0, 'voltage': 1, 'time': 0},
{'event': 0, 'voltage': 2, 'time': 1},
{'event': 1, 'voltage': 1, 'time': 2},
{'event': 1, 'voltage': 2, 'time': 3},
{'event': 2, 'voltage': 1, 'time': 4},
{'event': 2,... | use `defaultdict`
```
import collections
result = collections.defaultdict(list)
for d in dict_list:
result[d['event']].append(d)
result_list = result.values()
```
This way, you don't have to make any assumptions about how many different events there are or if there are any events missing.
This gives you a lis... |
Why does setting a default parameter value make this function a closure? | 4,092,233 | 3 | 2010-11-03T22:28:50Z | 4,092,249 | 9 | 2010-11-03T22:30:56Z | [
"python",
"recursion",
"closures"
] | I'm writing an application where Tags are linkable and there's a need to retrieve the entire chain of linked Tags. Self-reference is not allowed. Running the following code ends up with some very strange results:
```
class Tag(object):
def __init__(self, name):
self.name = name
self.links = []
def __repr_... | This is a common mistake in Python:
```
def tag_chain(tag, known=[]):
# ...
```
`known=[]` doesn't mean that if known is unsupplied, make it an empty list; in fact, it binds known to an "anonymous" list. Each time that known defaults to that list, it is the same list.
The typical pattern to do what you intended he... |
How to clamp an integer to some range? (in Python) | 4,092,528 | 42 | 2010-11-03T23:18:28Z | 4,092,550 | 48 | 2010-11-03T23:21:03Z | [
"python",
"clamp"
] | I have the following code:
```
new_index = index + offset
if new_index < 0:
new_index = 0
if new_index >= len(mylist):
new_index = len(mylist) - 1
return mylist[new_index]
```
Basically, I calculate a new index and use that to find some element from a list. In order to make sure the index is inside the bounds... | This is pretty clear, actually. Many folks learn it quickly. You can use a comment to help them.
```
new_index = max(0, min(new_index, len(mylist)-1))
``` |
How to clamp an integer to some range? (in Python) | 4,092,528 | 42 | 2010-11-03T23:18:28Z | 4,092,565 | 9 | 2010-11-03T23:23:38Z | [
"python",
"clamp"
] | I have the following code:
```
new_index = index + offset
if new_index < 0:
new_index = 0
if new_index >= len(mylist):
new_index = len(mylist) - 1
return mylist[new_index]
```
Basically, I calculate a new index and use that to find some element from a list. In order to make sure the index is inside the bounds... | Whatever happened to my beloved readable Python language? :-)
Seriously, just make it a function:
```
def addInRange (val, add, minval, maxval):
newval = val + add
if newval < minval: return minval
if newval > maxval: return maxval
return newval
```
then just call it with something like:
```
val = a... |
How to clamp an integer to some range? (in Python) | 4,092,528 | 42 | 2010-11-03T23:18:28Z | 4,092,571 | 9 | 2010-11-03T23:25:32Z | [
"python",
"clamp"
] | I have the following code:
```
new_index = index + offset
if new_index < 0:
new_index = 0
if new_index >= len(mylist):
new_index = len(mylist) - 1
return mylist[new_index]
```
Basically, I calculate a new index and use that to find some element from a list. In order to make sure the index is inside the bounds... | Chaining `max()` and `min()` together is the normal idiom I've seen. If you find it hard to read, write a helper function to encapsulate the operation:
```
def clamp(minimum, x, maximum):
return max(minimum, min(x, maximum))
``` |
How to clamp an integer to some range? (in Python) | 4,092,528 | 42 | 2010-11-03T23:18:28Z | 4,092,677 | 43 | 2010-11-03T23:43:50Z | [
"python",
"clamp"
] | I have the following code:
```
new_index = index + offset
if new_index < 0:
new_index = 0
if new_index >= len(mylist):
new_index = len(mylist) - 1
return mylist[new_index]
```
Basically, I calculate a new index and use that to find some element from a list. In order to make sure the index is inside the bounds... | ```
sorted((minval, value, maxval))[1]
```
for example:
```
>>> minval=3
>>> maxval=7
>>> for value in range(10):
... print sorted((minval, value, maxval))[1]
...
3
3
3
3
4
5
6
7
7
7
``` |
How to clamp an integer to some range? (in Python) | 4,092,528 | 42 | 2010-11-03T23:18:28Z | 6,013,872 | 23 | 2011-05-16T06:28:49Z | [
"python",
"clamp"
] | I have the following code:
```
new_index = index + offset
if new_index < 0:
new_index = 0
if new_index >= len(mylist):
new_index = len(mylist) - 1
return mylist[new_index]
```
Basically, I calculate a new index and use that to find some element from a list. In order to make sure the index is inside the bounds... | See [numpy.clip](http://docs.scipy.org/doc/numpy/reference/generated/numpy.clip.html):
```
index = numpy.clip(index, 0, len(my_list) - 1)
``` |
How to clamp an integer to some range? (in Python) | 4,092,528 | 42 | 2010-11-03T23:18:28Z | 22,902,954 | 19 | 2014-04-07T03:05:47Z | [
"python",
"clamp"
] | I have the following code:
```
new_index = index + offset
if new_index < 0:
new_index = 0
if new_index >= len(mylist):
new_index = len(mylist) - 1
return mylist[new_index]
```
Basically, I calculate a new index and use that to find some element from a list. In order to make sure the index is inside the bounds... | many interesting answers here, all about the same, except... which one's faster?
```
import numpy
np_clip = numpy.clip
mm_clip = lambda x, l, u: max(l, min(u, x))
s_clip = lambda x, l, u: sorted((x, l, u))[1]
py_clip = lambda x, l, u: l if x < l else u if x > u else x
```
```
>>> import random
>>> rrange = random.ran... |
Generating movie from python without saving individual frames to files | 4,092,927 | 46 | 2010-11-04T00:30:21Z | 4,116,121 | 19 | 2010-11-07T01:39:32Z | [
"python",
"numpy",
"ffmpeg",
"matplotlib",
"x264"
] | I would like to create an h264 or divx movie from frames that I generate in a python script in matplotlib. There are about 100k frames in this movie.
In examples on the web [eg. 1], I have only seen the method of saving each frame as a png and then running mencoder or ffmpeg on these files. In my case, saving each fra... | After patching ffmpeg (see Joe Kington comments to my question), I was able to get piping png's to ffmpeg as follows:
```
import subprocess
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
outf = 'test.avi'
rate = 1
cmdstring = ('local/bin/ffmpeg',
'-r', '%d' % ... |
Generating movie from python without saving individual frames to files | 4,092,927 | 46 | 2010-11-04T00:30:21Z | 5,029,536 | 11 | 2011-02-17T13:26:56Z | [
"python",
"numpy",
"ffmpeg",
"matplotlib",
"x264"
] | I would like to create an h264 or divx movie from frames that I generate in a python script in matplotlib. There are about 100k frames in this movie.
In examples on the web [eg. 1], I have only seen the method of saving each frame as a png and then running mencoder or ffmpeg on these files. In my case, saving each fra... | Converting to image formats is quite slow and adds dependencies. After looking at these page and other I got it working using raw uncoded buffers using mencoder (ffmpeg solution still wanted).
Details at: <http://vokicodder.blogspot.com/2011/02/numpy-arrays-to-video.html>
```
import subprocess
import numpy as np
cl... |
Generating movie from python without saving individual frames to files | 4,092,927 | 46 | 2010-11-04T00:30:21Z | 13,983,801 | 29 | 2012-12-21T03:13:37Z | [
"python",
"numpy",
"ffmpeg",
"matplotlib",
"x264"
] | I would like to create an h264 or divx movie from frames that I generate in a python script in matplotlib. There are about 100k frames in this movie.
In examples on the web [eg. 1], I have only seen the method of saving each frame as a png and then running mencoder or ffmpeg on these files. In my case, saving each fra... | This functionality is now (at least as of 1.2.0, maybe 1.1) baked into matplotlib via the `MovieWriter` class and it's sub-classes in the `animation` module.
```
import matplotlib.animation as animation
import numpy as np
from pylab import *
dpi = 100
def ani_frame():
fig = plt.figure()
ax = fig.add_subplot... |
Unable to install matplotlib on Mac OS X | 4,092,994 | 17 | 2010-11-04T00:45:46Z | 4,744,219 | 7 | 2011-01-20T06:45:22Z | [
"python",
"osx",
"matplotlib",
"macports",
"freetype"
] | I'm trying to install matplotlib for graphing applications in Python on Mac OS X. When I run "python setup.py install", it gives me this load of errors: <http://pastebin.com/u7fL37ic>.
A quick snippet:
```
src/ft2font.cpp:2170: error: âFT_LOAD_TARGET_MONOâ was not declared in this scope
src/ft2font.cpp:2171: erro... | I was given a new work computer recently (MacBook Pro OS 10.6.5), and wanted to install numpy + scipy + matplotlib in a Python virtual environment. I'm not an expert, but the virtual environment seems to allow you to install packages such that they are isolated from the system-wide packages, essentially by redefining t... |
Unable to install matplotlib on Mac OS X | 4,092,994 | 17 | 2010-11-04T00:45:46Z | 10,843,478 | 30 | 2012-06-01T01:54:10Z | [
"python",
"osx",
"matplotlib",
"macports",
"freetype"
] | I'm trying to install matplotlib for graphing applications in Python on Mac OS X. When I run "python setup.py install", it gives me this load of errors: <http://pastebin.com/u7fL37ic>.
A quick snippet:
```
src/ft2font.cpp:2170: error: âFT_LOAD_TARGET_MONOâ was not declared in this scope
src/ft2font.cpp:2171: erro... | The root of the problem is that freetype and libpng are installed in non-canonical locations by XCode, in /usr/X11 instead of /usr or /usr/local.
All of the answers already given address the problem by re-building freetype and libpng, either manually or using a package manager like homebrew.
You can, however, get mat... |
Unable to install matplotlib on Mac OS X | 4,092,994 | 17 | 2010-11-04T00:45:46Z | 12,810,326 | 7 | 2012-10-10T00:31:29Z | [
"python",
"osx",
"matplotlib",
"macports",
"freetype"
] | I'm trying to install matplotlib for graphing applications in Python on Mac OS X. When I run "python setup.py install", it gives me this load of errors: <http://pastebin.com/u7fL37ic>.
A quick snippet:
```
src/ft2font.cpp:2170: error: âFT_LOAD_TARGET_MONOâ was not declared in this scope
src/ft2font.cpp:2171: erro... | Old, but still popped up in my search when I had the same problem on Snow Leopard.
You said you were using homebrew, so you need to
```
brew link freetype
```
after installing it (with "brew install freetype").
This got through that error. I had do the same thing with libpng, which resulted in a successful install. |
How to inherit and extend a list object in Python? | 4,093,029 | 18 | 2010-11-04T00:54:56Z | 4,093,037 | 31 | 2010-11-04T00:56:52Z | [
"python",
"list",
"inheritance"
] | I am interested in using the python list object, but with slightly altered functionality. In particular, I would like the list to be 1-indexed instead of 0-indexed. E.g.:
```
>> mylist = MyList()
>> mylist.extend([1,2,3,4,5])
>> print mylist[1]
```
output should be: 1
But when I changed the `__getitem__()` and `__se... | Use the `super()` function to call the method of the base class, or invoke the method directly:
```
class MyList(list):
def __getitem__(self, key):
return list.__getitem__(self, key-1)
```
or
```
class MyList(list):
def __getitem__(self, key):
return super(MyList, self).__getitem__(key-1)
```... |
How to inherit and extend a list object in Python? | 4,093,029 | 18 | 2010-11-04T00:54:56Z | 4,093,873 | 14 | 2010-11-04T04:22:18Z | [
"python",
"list",
"inheritance"
] | I am interested in using the python list object, but with slightly altered functionality. In particular, I would like the list to be 1-indexed instead of 0-indexed. E.g.:
```
>> mylist = MyList()
>> mylist.extend([1,2,3,4,5])
>> print mylist[1]
```
output should be: 1
But when I changed the `__getitem__()` and `__se... | Instead, subclass integer using the same method to define all numbers to be minus one from what you set them to. Voila.
Sorry, I had to. It's like the joke about Microsoft defining dark as the standard. |
Programmatically find the installed version of pywin32 | 4,093,041 | 10 | 2010-11-04T00:57:26Z | 5,071,777 | 12 | 2011-02-21T22:02:06Z | [
"python",
"version",
"pywin32"
] | Some Python packages provide a way for a program to get the installed version. E.g.
```
>>> import numpy
>>> numpy.version.version
'1.5.0'
```
But I can't find a way to do so for [`pywin32`](https://sourceforge.net/projects/pywin32/). What good way might there be to find out? | I found a blog post ["Include version information in your Python packages" by Jean-Paul Calderone](http://as.ynchrono.us/2010/03/include-version-information-in-your_03.html) which showed you can get the version of `pywin32` this way:
```
>>> import win32api
>>> fixed_file_info = win32api.GetFileVersionInfo(win32api.__... |
is there a way to use input("Press any key to continue") on version 2.6 | 4,093,556 | 5 | 2010-11-04T03:04:04Z | 4,093,586 | 8 | 2010-11-04T03:10:50Z | [
"python",
"input"
] | I want the program to pause and wait until you press any key to continue, but raw\_input() is going away, and input() is replacing it. So I have
var = input("Press enter to continue") and it waits until I press enter, but then it fails with `SyntaxError: unexpected EOF while Parsing`.
This works OK on a system with P... | Use this
```
try:
input= raw_input
except NameError:
pass
```
If `raw_input` exists, it will be used for input. If it doesn't exist, `input` still exists. |
How to use Django to get the name for the host server? | 4,093,999 | 20 | 2010-11-04T04:56:15Z | 4,103,564 | 18 | 2010-11-05T04:15:55Z | [
"python",
"django",
"url",
"host"
] | How to use Django to get the name for the host server?
I need the name of the hosting server instead of the client name? | I generally put something like this in `settings.py`:
```
import socket
try:
HOSTNAME = socket.gethostname()
except:
HOSTNAME = 'localhost'
``` |
How to use Django to get the name for the host server? | 4,093,999 | 20 | 2010-11-04T04:56:15Z | 8,711,377 | 41 | 2012-01-03T11:09:57Z | [
"python",
"django",
"url",
"host"
] | How to use Django to get the name for the host server?
I need the name of the hosting server instead of the client name? | If you have a request (eg, this is inside a view), you can look at [request.get\_host()](https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.get_host) which gets you a complete locname (host and port), taking into account reverse proxy headers if any. If you don't have a request, you sho... |
python re - split a string before a character | 4,094,382 | 9 | 2010-11-04T06:31:49Z | 4,094,419 | 15 | 2010-11-04T06:39:06Z | [
"python",
"regex",
"split"
] | how to split a string at positions before a character?
* split a string before 'a'
* input: "fffagggahhh"
* output: ["fff", "aggg", "ahhh"]
the obvious way doesn't work:
```
>>> h=re.compile("(?=a)")
>>> h.split("fffagggahhh")
['fffagggahhh']
>>>
``` | Ok, not exactly the solution you want but I thought it will be a useful addition to problem here.
> Solution without re
Without re:
```
>>> x = "fffagggahhh"
>>> k = x.split('a')
>>> j = [k[0]] + ['a'+l for l in k[1:]]
>>> j
['fff', 'aggg', 'ahhh']
>>>
``` |
Is there a standard function to iterate over base classes? | 4,094,624 | 5 | 2010-11-04T07:25:50Z | 4,094,654 | 10 | 2010-11-04T07:31:26Z | [
"python"
] | I would like to be able to iterate over all the base classes, both direct and indirect, of a given class, including the class itself. This is useful in the case where you have a metaclass that examines an internal Options class of all its bases.
To do this, I wrote the following:
```
def bases(cls):
yield cls
... | There is a method that can return them all, in Method Resolution Order (MRO): `inspect.getmro`. See here:
<http://docs.python.org/library/inspect.html#inspect.getmro>
It returns them as a tuple, which you can then iterate over in a single loop yourself:
```
import inspect
for base_class in inspect.getmro(foo):
#... |
Unittest tests order | 4,095,319 | 19 | 2010-11-04T09:32:43Z | 4,095,331 | 13 | 2010-11-04T09:34:19Z | [
"python",
"unit-testing"
] | How do I be sure of the unittest methods order? Is the alphabetical or numeric prefixes the proper way?
```
class TestFoo(TestCase):
def test_1(self):
...
def test_2(self):
...
```
or
```
class TestFoo(TestCase):
def test_a(self):
...
def test_b(self):
...
``` | Why do you need specific test order? The tests should be isolated and therefore it should be possible to run them in any order, or even in parallel.
If you need to test something like user unsubscribing, the test could create a fresh database with a test subscription and then try to unsubscribe. This scenario has its ... |
Unittest tests order | 4,095,319 | 19 | 2010-11-04T09:32:43Z | 4,095,465 | 9 | 2010-11-04T09:54:09Z | [
"python",
"unit-testing"
] | How do I be sure of the unittest methods order? Is the alphabetical or numeric prefixes the proper way?
```
class TestFoo(TestCase):
def test_1(self):
...
def test_2(self):
...
```
or
```
class TestFoo(TestCase):
def test_a(self):
...
def test_b(self):
...
``` | Don't rely on the order. If they use some common state like the filesystem or database, then you should create `setUp` and `tearDown` methods that get your environment into a testable state, then clean up after the tests have run. Each test should assume that the environment is as defined in `setUp`, and should make no... |
Unittest tests order | 4,095,319 | 19 | 2010-11-04T09:32:43Z | 7,916,322 | 10 | 2011-10-27T13:10:54Z | [
"python",
"unit-testing"
] | How do I be sure of the unittest methods order? Is the alphabetical or numeric prefixes the proper way?
```
class TestFoo(TestCase):
def test_1(self):
...
def test_2(self):
...
```
or
```
class TestFoo(TestCase):
def test_a(self):
...
def test_b(self):
...
``` | If you use 'nose' and you write your test cases as functions (and not as methods of some TestCase derived class) 'nose' doesn't fiddle with the order, but uses the order of the functions as defined in the file. In order to have the assert\_\* methods handy without needing to subclass TestCase I usually use the testing ... |
Unittest tests order | 4,095,319 | 19 | 2010-11-04T09:32:43Z | 11,981,424 | 7 | 2012-08-16T05:56:41Z | [
"python",
"unit-testing"
] | How do I be sure of the unittest methods order? Is the alphabetical or numeric prefixes the proper way?
```
class TestFoo(TestCase):
def test_1(self):
...
def test_2(self):
...
```
or
```
class TestFoo(TestCase):
def test_a(self):
...
def test_b(self):
...
``` | I half agree with the idea that tests souldn't be ordered. In some cases it helps (it's easier damn it!) to have them in order... after all that's the reason for the 'unit' in UnitTest.
That said one alternative is to use mock objects to mockout and patch the items that should run before that specific code under test.... |
Unittest tests order | 4,095,319 | 19 | 2010-11-04T09:32:43Z | 13,262,313 | 43 | 2012-11-07T02:17:44Z | [
"python",
"unit-testing"
] | How do I be sure of the unittest methods order? Is the alphabetical or numeric prefixes the proper way?
```
class TestFoo(TestCase):
def test_1(self):
...
def test_2(self):
...
```
or
```
class TestFoo(TestCase):
def test_a(self):
...
def test_b(self):
...
``` | There is no reason given that you can't build on what was done in a previous test or should rebuild it all from scratch for the next test. At least no reason is usually offered but instead people just confidently say "you shouldn't". That isn't helpful.
In general I am tired of reading too many answers here that say b... |
Unittest tests order | 4,095,319 | 19 | 2010-11-04T09:32:43Z | 22,317,851 | 26 | 2014-03-11T06:15:58Z | [
"python",
"unit-testing"
] | How do I be sure of the unittest methods order? Is the alphabetical or numeric prefixes the proper way?
```
class TestFoo(TestCase):
def test_1(self):
...
def test_2(self):
...
```
or
```
class TestFoo(TestCase):
def test_a(self):
...
def test_b(self):
...
``` | You can disable it by setting sortTestMethodsUsing to None:
<http://docs.python.org/2/library/unittest.html#unittest.TestLoader.sortTestMethodsUsing>
For pure unittests, you folks are right; but for component tests and integration tests...
I do not agree that you shall assume nothing about the state.
What if you are t... |
Running "unique" tasks with celery | 4,095,940 | 33 | 2010-11-04T10:57:57Z | 4,096,599 | 23 | 2010-11-04T12:25:30Z | [
"python",
"django",
"celery"
] | I use celery to update RSS feeds in my news aggregation site. I use one @task for each feed, and things seem to work nicely.
There's a detail that I'm not sure to handle well though: all feeds are updated once every minute with a @periodic\_task, but what if a feed is still updating from the last periodic task when a ... | From the official documentation: [*Ensuring a task is only executed one at a time*](http://docs.celeryproject.org/en/latest/tutorials/task-cookbook.html#ensuring-a-task-is-only-executed-one-at-a-time). |
Running "unique" tasks with celery | 4,095,940 | 33 | 2010-11-04T10:57:57Z | 7,668,350 | 33 | 2011-10-05T22:09:22Z | [
"python",
"django",
"celery"
] | I use celery to update RSS feeds in my news aggregation site. I use one @task for each feed, and things seem to work nicely.
There's a detail that I'm not sure to handle well though: all feeds are updated once every minute with a @periodic\_task, but what if a feed is still updating from the last periodic task when a ... | Based on MattH's answer, you could use a decorator like this:
```
def single_instance_task(timeout):
def task_exc(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
lock_id = "celery-single-instance-" + func.__name__
acquire_lock = lambda: cache.add(lock_id, "true",... |
Where's the standard python exception list for programmes to raise? | 4,096,087 | 12 | 2010-11-04T11:18:54Z | 4,096,168 | 12 | 2010-11-04T11:28:46Z | [
"python",
"exception",
"error-handling"
] | There is a list [standard python exceptions](http://docs.python.org/library/exceptions.html#exception-hierarchy) that we should watch out, but I don't think these are the ones we should raise ourselves, cause they are rarely applicable.
I'm curious if there exists a list within standard python library, with exceptions... | First, Python raises standard exceptions for you.
> It's better to ask forgiveness than to ask permission
Simply attempt the operation and let Python raise the exception. Don't bracket everything with `if would_not_work(): raise Exception`. Never worth writing. Python already does this in **all** cases.
If you think... |
Where's the standard python exception list for programmes to raise? | 4,096,087 | 12 | 2010-11-04T11:18:54Z | 4,096,453 | 9 | 2010-11-04T12:05:58Z | [
"python",
"exception",
"error-handling"
] | There is a list [standard python exceptions](http://docs.python.org/library/exceptions.html#exception-hierarchy) that we should watch out, but I don't think these are the ones we should raise ourselves, cause they are rarely applicable.
I'm curious if there exists a list within standard python library, with exceptions... | If the error matches the description of one of the standard python exception classes, then by all means throw it.
Common ones to use are `TypeError` and `ValueError`, the list you linked to already is the standard list.
If you want to have application specific ones, then subclassing Exception or one of it's descendan... |
how to find user id from session_data from django_session table? | 4,096,506 | 11 | 2010-11-04T12:13:51Z | 4,096,658 | 10 | 2010-11-04T12:32:44Z | [
"python",
"django",
"base64",
"pickle",
"pinax"
] | In `django_session` table `session_data` is stored which is first pickled using pickle module of python and then encoded in base64 by using base64 module of python.
I got the decoded pickled session\_data.
session\_data from django\_session table:
```
gAJ9cQEoVQ9fc2Vzc2lvbl9leHBpcnlxAksAVRJfYXV0aF91c2VyX2JhY2tlbmRxA... | NOTE: format changed since original answer, for 1.4 and above see the update below
```
import pickle
data = pickle.loads(base64.decode(session_data))
>>> print data
{'_auth_user_id': 2L, '_auth_user_backend': 'django.contrib.auth.backends.ModelBackend',
'_session_expiry': 0}
```
[update]
> My base64.decode requir... |
how to find user id from session_data from django_session table? | 4,096,506 | 11 | 2010-11-04T12:13:51Z | 12,056,240 | 16 | 2012-08-21T13:44:22Z | [
"python",
"django",
"base64",
"pickle",
"pinax"
] | In `django_session` table `session_data` is stored which is first pickled using pickle module of python and then encoded in base64 by using base64 module of python.
I got the decoded pickled session\_data.
session\_data from django\_session table:
```
gAJ9cQEoVQ9fc2Vzc2lvbl9leHBpcnlxAksAVRJfYXV0aF91c2VyX2JhY2tlbmRxA... | I had trouble with Paulo's method (see my comment on his answer), so I ended up using this method from a [scottbarnham.com blog post](http://scottbarnham.com/blog/2008/12/04/get-user-from-session-key-in-django/):
```
from django.contrib.sessions.models import Session
from django.contrib.auth.models import User
sessio... |
Missing Python.h while trying to compile a C extension module | 4,097,339 | 7 | 2010-11-04T13:53:59Z | 4,097,665 | 12 | 2010-11-04T14:30:48Z | [
"c++",
"python",
"compilation",
"extending"
] | I'm following [this tutorial](http://en.wikibooks.org/wiki/Python_Programming/Extending_with_C) on how to extend Python with C\C++ code.
The section named "Building the extension module with GCC for Microsoft Windows" fails for me with the following error:
```
fatal error: Python.h: No such file or directory
```
The... | 1. Do you have the python dev files so that you can find Python.h?
2. Do you have the location of Python.h specified to your compiler? with gcc this is usually done through a -I path to include.
Figuring out which of those is failing will solve your problem.
from the article you linked:
gcc -c hellomodule.c -I/Pytho... |
Missing Python.h while trying to compile a C extension module | 4,097,339 | 7 | 2010-11-04T13:53:59Z | 6,285,152 | 49 | 2011-06-08T20:56:27Z | [
"c++",
"python",
"compilation",
"extending"
] | I'm following [this tutorial](http://en.wikibooks.org/wiki/Python_Programming/Extending_with_C) on how to extend Python with C\C++ code.
The section named "Building the extension module with GCC for Microsoft Windows" fails for me with the following error:
```
fatal error: Python.h: No such file or directory
```
The... | For Linux, Ubuntu users to resolve the issue of missing Python.h while compiling, simply run the following command in your terminal to install the development package of python:
In Terminal: `sudo apt-get install python-dev`
Good luck |
Python ValueError error message | 4,097,461 | 10 | 2010-11-04T14:07:43Z | 4,097,494 | 24 | 2010-11-04T14:11:18Z | [
"python",
"exception",
"exception-handling",
"python-3.x"
] | How can I actually print out the ValueError's message after I catch it? | ```
try:
...
except ValueError as e:
print(e)
``` |
Intermediate variable in a list comprehension for simultaneous filtering and transformation | 4,097,518 | 12 | 2010-11-04T14:14:47Z | 4,097,720 | 10 | 2010-11-04T14:35:08Z | [
"python",
"list",
"mapping",
"filtering",
"list-comprehension"
] | I have a list of vectors (in Python) that I want to normalize, while at the same time removing the vectors that originally had small norms.
The input list is, e.g.
```
a = [(1,1),(1,2),(2,2),(3,4)]
```
And I need the output to be (x\*n, y\*n) with n = (x\**2+y*\*2)\*\*-0.5
If I just needed the norms, for example, t... | > ```
> Is this really the best way?
> ```
Well, it does work efficiently and if you really, really want to write oneliners then it's the best you can do.
On the other hand, a simple 4 line function would do the same much clearer:
```
def normfilter(vecs, min_norm):
for x,y in vecs:
n = (x**2.+y**2.)**-0... |
How to update a plot in matplotlib? | 4,098,131 | 52 | 2010-11-04T15:15:46Z | 4,098,938 | 71 | 2010-11-04T16:35:41Z | [
"python",
"matplotlib",
"tkinter"
] | I'm having issues with redrawing the figure here. I allow the user to specify the units in the time scale (x-axis) and then I recalculate and call this function `plots()`. I want the plot to simply update, not append another plot to the figure.
```
def plots():
global vlgaBuffSorted
cntr()
result = collec... | You essentially have two options:
1. Do exactly what you're currently doing, but call `graph1.clear()` and `graph2.clear()` before replotting the data. This is the slowest, but most simplest and most robust option.
2. Instead of replotting, you can just update the data of the plot objects. You'll need to make some cha... |
How to update a plot in matplotlib? | 4,098,131 | 52 | 2010-11-04T15:15:46Z | 10,253,974 | 7 | 2012-04-20T21:45:07Z | [
"python",
"matplotlib",
"tkinter"
] | I'm having issues with redrawing the figure here. I allow the user to specify the units in the time scale (x-axis) and then I recalculate and call this function `plots()`. I want the plot to simply update, not append another plot to the figure.
```
def plots():
global vlgaBuffSorted
cntr()
result = collec... | In case anyone comes across this article looking for what I was looking for, I found examples at
[How to visualize scalar 2D data with Matplotlib?](http://stackoverflow.com/questions/5127668/how-to-visualize-scalar-2d-data-with-matplotlib/10252292#10252292)
and
[http://mri.brechmos.org/2009/07/automatically-update-a... |
Anyone know this Python data structure? | 4,098,179 | 6 | 2010-11-04T15:19:55Z | 4,098,339 | 10 | 2010-11-04T15:35:24Z | [
"python",
"performance",
"sorting",
"insert",
"deque"
] | The Python class has six requirements as listed below. Only **bold terms** are to be read as requirements.
---
1. Close to **O(1) performance** for as many of the following four operations.
2. Maintaining **sorted order while inserting** an object into the container.
3. Ability to **peek at last value** (the largest ... | Your requirements seem to be:
1. O(1) pop from each end
2. Efficient `len`
3. Sorted order
4. Peek at last value
for which you can use a `deque` with a custom `insert` method which rotates the deque, appends to one end, and unrotates.
```
>>> from collections import deque
>>> import bisect
>>> class FunkyDeque(deque... |
Anyone know this Python data structure? | 4,098,179 | 6 | 2010-11-04T15:19:55Z | 4,099,031 | 7 | 2010-11-04T16:45:59Z | [
"python",
"performance",
"sorting",
"insert",
"deque"
] | The Python class has six requirements as listed below. Only **bold terms** are to be read as requirements.
---
1. Close to **O(1) performance** for as many of the following four operations.
2. Maintaining **sorted order while inserting** an object into the container.
3. Ability to **peek at last value** (the largest ... | Many thanks go out to `katrielalex` for providing the inspiration that led to the following Python class:
```
import collections
import bisect
class FastTable:
def __init__(self):
self.__deque = collections.deque()
def __len__(self):
return len(self.__deque)
def head(self):
retu... |
Strange result in python | 4,098,425 | 6 | 2010-11-04T15:45:13Z | 4,098,476 | 17 | 2010-11-04T15:49:21Z | [
"python",
"string",
"identity"
] | Could someone explain me this strange result on python 2.6.6 ?
```
>>> a = "xx"
>>> b = "xx"
>>> a.__hash__() == b.__hash__()
True
>>> a is b
True # ok.. was just to be sure
>>> a = "x" * 2
>>> b = "x" * 2
>>> a.__hash__() == b.__hash__()
True
>>> a is b
True # yeah.. looks ok so far !
>>> n = 2
>>> a = "x" * n
>>> ... | The `is` operator tells you whether two variables **point to the same object in memory**. It is rarely useful and often confused with the `==` operator, which tells you whether two objects "look the same".
It is particularly confusing when used with things like short string literals, because the Python compiler intern... |
Strange result in python | 4,098,425 | 6 | 2010-11-04T15:45:13Z | 4,098,560 | 12 | 2010-11-04T15:57:41Z | [
"python",
"string",
"identity"
] | Could someone explain me this strange result on python 2.6.6 ?
```
>>> a = "xx"
>>> b = "xx"
>>> a.__hash__() == b.__hash__()
True
>>> a is b
True # ok.. was just to be sure
>>> a = "x" * 2
>>> b = "x" * 2
>>> a.__hash__() == b.__hash__()
True
>>> a is b
True # yeah.. looks ok so far !
>>> n = 2
>>> a = "x" * n
>>> ... | To understand this, you need to understand a few different things.
* `a is b` returns true if `a` and `b` are *the same object*, not merely if they have *the same value*. Strings can have the same value but be a different instance of that value.
* When you say `a = "x"`, what you're actually doing is creating a string... |
Python urllib2.urlopen returning 302 error even though page exists | 4,098,702 | 3 | 2010-11-04T16:11:03Z | 4,098,890 | 16 | 2010-11-04T16:31:28Z | [
"python"
] | I am using the Python function `urllib2.urlopen` to read the <http://www.bad.org.uk/> website but I keep getting a 302 error even though when I visit the site it loads ok. Anyone have any idea why?
```
import socket
headers = { 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' }
socket.setdefaulttimeo... | The page at <http://www.bad.org.uk/> is broken when cookies are disabled.
<http://www.bad.org.uk/> returns:
```
HTTP/1.1 302 Found
Location: http://www.bad.org.uk/DesktopDefault.aspx
Set-Cookie: Esperantus_Language_bad=en-GB; path=/
Set-Cookie: Esperantus_Language_rainbow=en-GB; path=/
Set-Cookie: PortalAlias=rainbow... |
printing slowly (Simulate typing) | 4,099,422 | 5 | 2010-11-04T17:29:43Z | 4,099,459 | 12 | 2010-11-04T17:33:34Z | [
"python"
] | I am trying to make a textual game in python. All goes well however, I would like to make a function that will allow me to print something to the terminal, but in a fashion hat looks like typing.
Currently I have:
```
def print_slow(str):
for letter in str:
print letter,
time.sleep(.1)
print_slow... | In Python 2.x you can use [`sys.stdout.write`](http://docs.python.org/library/sys.html#sys.stdout) instead of `print`:
```
for letter in str:
sys.stdout.write(letter)
time.sleep(.1)
```
In Python 3.x you can set the optional argument `end` to the empty string:
```
print(letter, end='')
``` |
Why can my Django app not write to its log file? | 4,100,584 | 7 | 2010-11-04T19:41:18Z | 4,100,618 | 17 | 2010-11-04T19:44:37Z | [
"python",
"django",
"apache2",
"mod-wsgi"
] | **$ sudo /etc/init.d/apache2 restart**
```
* Restarting web server apache2
... waiting . ...done.
```
username@servername Thu Nov 04 18:54:37 ~/public\_html/IDM\_app
**$ sudo tail -n 60 /var/log/apache2/error.log**
```
[Thu Nov 04 18:54:27 2010] [error] [client 8.17.58.38] mod_wsgi (pid=28760): Exception occ... | Apache's probably running as the `apache` user, meaning that it doesn't have write access to the log file. It starts up fine because it only has to read the wsgi file, which has read permissions for all users. either `chmod a+w django.osqa.log` or `chown <apache-user> django.osqa.log`.
Note: the preferred method would... |
How do I add a placeholder on a CharField in Django? | 4,101,258 | 120 | 2010-11-04T20:51:57Z | 4,101,282 | 166 | 2010-11-04T20:54:08Z | [
"python",
"django",
"django-forms"
] | Take this very simple form for example.
```
class SearchForm(Form):
q = forms.CharField(label='search')
```
This gets rendered in the template:
```
<input type="text" name="q" id="id_q" />
```
However, I want to add the 'placeholder' attribute to this field with a value of "Search" so that the HTML would look so... | Look at the [widgets documentation](http://docs.djangoproject.com/en/dev/ref/forms/widgets/). Basically it would look like:
```
q = forms.CharField(label='search',
widget=forms.TextInput(attrs={'placeholder': 'Search'}))
```
More writing, yes, but the separation allows for better abstraction of m... |
How do I add a placeholder on a CharField in Django? | 4,101,258 | 120 | 2010-11-04T20:51:57Z | 12,292,472 | 19 | 2012-09-06T03:12:56Z | [
"python",
"django",
"django-forms"
] | Take this very simple form for example.
```
class SearchForm(Form):
q = forms.CharField(label='search')
```
This gets rendered in the template:
```
<input type="text" name="q" id="id_q" />
```
However, I want to add the 'placeholder' attribute to this field with a value of "Search" so that the HTML would look so... | You can use this code to add placeholder attr for every TextInput field in you form. Text for placeholders will be taken from model field labels.
```
class PlaceholderDemoForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(PlaceholderDemoForm, self).__init__(*args, **kwargs)
for field... |
How do I add a placeholder on a CharField in Django? | 4,101,258 | 120 | 2010-11-04T20:51:57Z | 19,385,230 | 34 | 2013-10-15T15:31:42Z | [
"python",
"django",
"django-forms"
] | Take this very simple form for example.
```
class SearchForm(Form):
q = forms.CharField(label='search')
```
This gets rendered in the template:
```
<input type="text" name="q" id="id_q" />
```
However, I want to add the 'placeholder' attribute to this field with a value of "Search" so that the HTML would look so... | For a ModelForm, you can use the Meta class thus:
```
from django import forms
from .models import MyModel
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
widgets = {
'name': forms.TextInput(attrs={'placeholder': 'Name'}),
'description': forms.Textarea(
... |
How do I add a placeholder on a CharField in Django? | 4,101,258 | 120 | 2010-11-04T20:51:57Z | 23,983,577 | 16 | 2014-06-01T19:24:41Z | [
"python",
"django",
"django-forms"
] | Take this very simple form for example.
```
class SearchForm(Form):
q = forms.CharField(label='search')
```
This gets rendered in the template:
```
<input type="text" name="q" id="id_q" />
```
However, I want to add the 'placeholder' attribute to this field with a value of "Search" so that the HTML would look so... | The other methods are all good. However, if you prefer to not specify the field (e.g. for some dynamic method), you can use this:
```
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['email'].widget.attrs['placeholder'] = self.fields['email'].label or 'email@addres... |
Multi-dimensional char array (array of strings) in python ctypes | 4,101,536 | 4 | 2010-11-04T21:22:44Z | 4,101,777 | 7 | 2010-11-04T21:55:44Z | [
"python",
"multidimensional-array",
"ctypes"
] | I'm trying to pass an array of character arrays to a C function using ctypes.
```
void cfunction(char ** strings)
{
strings[1] = "bad"; //works not what I need.
strings[1][2] = 'd'; //this will segfault.
return;
}
char *input[] = {"foo","bar"};
cfunction(input);
```
Since the array that I throw around is statical... | Use something like
```
input = ((c_char * 4) * 2)()
input[0].value = "str"
input[0][0] == "s"
input[0][1] == "t" # and so on...
```
Simple usage:
```
>>> a =((c_char * 4) * 2)()
>>> a
<__main__.c_char_Array_4_Array_2 object at 0x9348d1c>
>>> a[0]
<__main__.c_char_Array_4 object at 0x9348c8c>
>>> a[0].raw
'\x00\x00\x... |
8 Character Random Code | 4,102,409 | 2 | 2010-11-04T23:41:34Z | 4,102,438 | 10 | 2010-11-04T23:49:18Z | [
"java",
"python",
"database",
"algorithm",
"unique"
] | I've been through answers to a few similar questions asked on SO, but could not find what I was looking for.
Is there a more efficient way to generate 8 character unique IDs, base 36 (0-9A-Z), than generating a unique ID and querying the DB to see if it already exists and repeating until you get a unique ID that has n... | One option is to do it the other way round: generate a huge number of them in the database whenever you need to, then either fetch a single one from the DB when you need one, or reserve a whole bunch of them for your particular process (i.e. mark them as "potentially used" in the database) and then dole them out from m... |
8 Character Random Code | 4,102,409 | 2 | 2010-11-04T23:41:34Z | 4,103,718 | 7 | 2010-11-05T05:05:28Z | [
"java",
"python",
"database",
"algorithm",
"unique"
] | I've been through answers to a few similar questions asked on SO, but could not find what I was looking for.
Is there a more efficient way to generate 8 character unique IDs, base 36 (0-9A-Z), than generating a unique ID and querying the DB to see if it already exists and repeating until you get a unique ID that has n... | I question that your "inefficient" approach is actually inefficient. Consider this:
* There are 36^8 == 2,821,109,907,456 (2.8 Trillion) possible IDs.
* If you have N existing IDs, the chance of a new randomly generated ID colliding is N in ~2.8 trillion.
* Unless N is in the hundreds of billions, you "generate a uniq... |
python: avoiding bug with variable use before assignment in a loop | 4,103,031 | 2 | 2010-11-05T02:02:41Z | 4,103,059 | 7 | 2010-11-05T02:10:29Z | [
"python",
"namespaces",
"coding-style"
] | ```
for element in container:
# some code here
temp_variable = f1(element)
# more code
# much later in the code
for element in container:
# some code
another_variable = g(temp_variable)
# more code
temp_variable = f2(element)
# more code
```
In the second `for` loop, I accidentally used variable `tem... | If it's 'much later' in the code, then you should probably break the code up into multiple functions. It sounds like the function is too long.
Another tip is to use meaningful names. `temp_variable`, `tmp`, `temp`, etc. are not good names. Use a name that describes the value that it points to. This will eliminate a la... |
Getting NppExec to understand path of the current file in Notepad++ (for Python scripts) | 4,103,085 | 5 | 2010-11-05T02:15:43Z | 4,106,339 | 12 | 2010-11-05T13:40:43Z | [
"python",
"notepad++",
"nppexec"
] | Using windows for the first time in quite awhile and have picked up notepad++ and am using the nppexec plugin to run python scripts. However, I noticed that notepad++ doesn't pick up the directory that my script is saved in. For example, I place "script.py" in 'My Documents' however os.getcwd() prints "Program Files \ ... | Notepad++ >nppexec >follow $(current directory) |
Python's equivalent of C# LINQ's select | 4,103,107 | 6 | 2010-11-05T02:21:08Z | 4,103,130 | 10 | 2010-11-05T02:25:23Z | [
"python"
] | I'm quite new to python, and happen to have used C# for some time now. I saw that there was a filter method to use with the collections, which seems to be the equivalent of the LINQ's where clause.
I wondered, is there also an equivalent for the LINQ's select statement in python?
Example: `my_collection.select(my_... | ```
[my_object.my_property for my_object in my_collection]
``` |
What is the difference between pickle and shelve? | 4,103,430 | 27 | 2010-11-05T03:42:45Z | 4,103,454 | 40 | 2010-11-05T03:47:50Z | [
"python",
"object",
"pickle",
"shelve",
"object-serialization"
] | I am learning about object serialization for the first time. I tried reading and 'googling' for differences in the modules pickle and shelve but I am not sure I understand it. When to use which one?
Pickle can turn every python object into stream of bytes which can be persisted into a file. Then why do we need the modu... | `pickle` is for serializing some object (or objects) as a single bytestream in a file.
`shelve` builds on top of `pickle` and implements a serialization dictionary where objects are pickled, but associated with a key (some string), so you can load your shelved data file and access your pickled objects via keys. This c... |
Efficient way of having a function only execute once in a loop | 4,103,773 | 38 | 2010-11-05T05:25:09Z | 4,104,188 | 66 | 2010-11-05T07:41:21Z | [
"python"
] | At the moment, I'm doing stuff like the following, which is getting tedious:
```
run_once = 0
while 1:
if run_once == 0:
myFunction()
run_once = 1:
```
I'm guessing there is some more accepted way of handling this stuff?
What I'm looking for is having a function execute once, on demand. For examp... | I would use a decorator on the function to handle keeping track of how many times it runs.
```
def run_once(f):
def wrapper(*args, **kwargs):
if not wrapper.has_run:
wrapper.has_run = True
return f(*args, **kwargs)
wrapper.has_run = False
return wrapper
@run_once
def my_fu... |
Efficient way of having a function only execute once in a loop | 4,103,773 | 38 | 2010-11-05T05:25:09Z | 24,888,992 | 9 | 2014-07-22T13:39:33Z | [
"python"
] | At the moment, I'm doing stuff like the following, which is getting tedious:
```
run_once = 0
while 1:
if run_once == 0:
myFunction()
run_once = 1:
```
I'm guessing there is some more accepted way of handling this stuff?
What I'm looking for is having a function execute once, on demand. For examp... | Another option is to set the `func_code` [code object](http://akaptur.github.io/blog/2013/11/15/introduction-to-the-python-interpreter-2/) for your function to be a code object for a function that does nothing. This should be done at the end of your function body.
For example:
```
def run_once():
# Code for some... |
What is the vim feature: --enable-pythoninterp | 4,104,202 | 3 | 2010-11-05T07:44:08Z | 4,104,215 | 8 | 2010-11-05T07:46:50Z | [
"python",
"vim"
] | I am going to build vim and see that it supports the `pythoninterp` feature by
`--enable-pythoninterp`. What is it? Since I am a big Python fan, I'd like to know more about it.
And also, what's the `--with-python-config-dir=PATH` for? | vim supports scripting in various languages, Python being one of them. See `:h python` for more details. |
Read a number of random lines from a file in Python | 4,105,778 | 4 | 2010-11-05T12:21:08Z | 4,105,879 | 14 | 2010-11-05T12:35:29Z | [
"python"
] | Could someone show me how I could read a random number of lines from a file in Python? | Your requirement is a bit vague, so here's another slightly different method (for inspiration if nothing else):
```
from random import random
lines = [line for line in open("/some/file") if random() >= .5]
```
Compared with the other solutions, the *number* of lines varies less (distribution around half the total num... |
Read a number of random lines from a file in Python | 4,105,778 | 4 | 2010-11-05T12:21:08Z | 4,106,286 | 8 | 2010-11-05T13:35:05Z | [
"python"
] | Could someone show me how I could read a random number of lines from a file in Python? | To get a number of lines at random from your file you could do something like the following:
```
import random
with open('file.txt') as f:
lines = random.sample(f.readlines(),5)
```
The above example returns 5 lines but you can easily change that to the number you require. You could also change it to `randint()` ... |
Manage #TODO (lots of files) with VIM | 4,106,137 | 26 | 2010-11-05T13:14:52Z | 4,106,211 | 40 | 2010-11-05T13:26:27Z | [
"python",
"vim",
"todo",
"fixmetodo"
] | Hi stackoverflow community,
I've already search for this here and haven't found what I need. I use VIM/GVIM to develop my python projects and I randomly I leave #TODO comments in my code.
Is there any way to manage (search, list and link) all the #TODO occurrences inside VIM? I tried the [tasklist plugin](http://www.... | If you just want a list of the occurences of "TODO" in .py files in the working directory, you can just use `:vimgrep` like so:
```
:vimgrep TODO **/*.py
```
Then open the quickfix window with:
```
:cw
```
(it might open it automatically anyway, not sure) and just scroll through the results, hitting Enter to go to ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.