title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Python: how to join entries in a set into one string? | 7,323,782 | 32 | 2011-09-06T17:30:37Z | 7,323,815 | 61 | 2011-09-06T17:33:15Z | [
"python",
"list",
"set",
"python-2.7"
] | Basically, I am trying to join together the entries in a set in order to output one string. I am trying to use syntax similar to the join function for lists. Here is my attempt:
```
list = ["gathi-109","itcg-0932","mx1-35316"]
set_1 = set(list)
set_2 = set(["mx1-35316"])
set_3 = set_1 - set_2
print set_3.join(", ")
``... | ```
', '.join(set_3)
```
The `join` is a string method, not a set method. |
Python: how to join entries in a set into one string? | 7,323,782 | 32 | 2011-09-06T17:30:37Z | 7,323,861 | 18 | 2011-09-06T17:37:22Z | [
"python",
"list",
"set",
"python-2.7"
] | Basically, I am trying to join together the entries in a set in order to output one string. I am trying to use syntax similar to the join function for lists. Here is my attempt:
```
list = ["gathi-109","itcg-0932","mx1-35316"]
set_1 = set(list)
set_2 = set(["mx1-35316"])
set_3 = set_1 - set_2
print set_3.join(", ")
``... | Sets don't have a `join` method but you can use [`str.join`](http://docs.python.org/library/stdtypes.html#str.join) instead.
```
', '.join(set_3)
```
The `str.join` method will work on any iterable object including lists and sets.
Note: be careful about using this on sets containing integers; you will need to conver... |
Downloaded filename with Google App Engine Blobstore | 7,324,895 | 9 | 2011-09-06T19:11:35Z | 7,327,530 | 10 | 2011-09-07T00:07:58Z | [
"python",
"google-app-engine",
"blobstore"
] | I'm using the Google App Engine Blobstore to store a range of file types (PDF, XLS, etc) and am trying to find a mechanism by which the original filename of the uploaded file - as stored in blob\_info - can be used to name the downloaded file i.e. so that the user sees 'some\_file.pdf' in the save dialogue rather than ... | There is an optional 'save\_as' parameter in the send\_blob function. By default this is set to False. Setting it to True will cause the file to be treated as an attachment (ie it will trigger a 'Save/Open' download dialog) and the user will see the proper filename.
Example:
```
class ServeHandler(blobstore_handlers.... |
Determine whether any files have been added, removed, or modified in a directory | 7,325,072 | 7 | 2011-09-06T19:26:40Z | 7,325,126 | 7 | 2011-09-06T19:30:34Z | [
"python",
"md5",
"tar",
"hashlib",
"tarfile"
] | I'm trying to write a Python script that will get the md5sum of all files in a directory (in Linux). Which I believe I have done in the code below.
I want to be able to run this to make sure no files within the directory have changed, and no files have been added for deleted.
The problem is if I make a change to a fi... | TAR file headers include a field for the modified time of the file; the act of changing a file, even if that change is later changed back, will mean the TAR file headers will be different, leading to different hashes. |
Determine whether any files have been added, removed, or modified in a directory | 7,325,072 | 7 | 2011-09-06T19:26:40Z | 7,325,320 | 8 | 2011-09-06T19:47:14Z | [
"python",
"md5",
"tar",
"hashlib",
"tarfile"
] | I'm trying to write a Python script that will get the md5sum of all files in a directory (in Linux). Which I believe I have done in the code below.
I want to be able to run this to make sure no files within the directory have changed, and no files have been added for deleted.
The problem is if I make a change to a fi... | As the other answers mentioned, two tar files can be different even if the contents are the same either due to tar metadata changes or to file order changes. You should run the checksum on the file data directly, sorting the directory lists to ensure they are always in the same order. If you want to include some metada... |
installing Reportlab (error: command 'gcc' failed with exit status 1 ) | 7,325,305 | 13 | 2011-09-06T19:46:07Z | 7,414,038 | 14 | 2011-09-14T09:23:15Z | [
"python",
"virtualenv",
"openerp"
] | I'm trying to install ReportLab 2.4 on a 10.04.2 server with virtualenv.
In the ReportLab\_2\_4 folder I use:
```
python setup.py install
```
and the error I get:
> error: command 'gcc' failed with exit status 1 | As Skimantas said, I think you should install python-dev. `sudo apt-get install python-dev` and I was able to install reportlab into my home directory with command "`pip install reportlab`" without sudo as mentioned earlier answer. I need only root access to install python-dev.
Shortly..
I installed virtualenv
```
s... |
Suggestions on processing large file - python or command line? | 7,325,949 | 2 | 2011-09-06T20:46:20Z | 7,326,069 | 8 | 2011-09-06T20:57:08Z | [
"python",
"parsing",
"command-line"
] | Given two files, one containing entries of the form:
```
label1 label2 name1
label1 label3 name2
```
and the other of the form:
```
label1 label2 name1 0.1 1000
label9 label6 name7 0.8 0.5
```
Suppose you want to extract those lines from file two for which the first three elements appear in a line (order important)... | Your python version is rather inefficient because you're testing for membership in a list, rather than a set or a dict (i.e. O(n) lookup time instead of O(1)).
Try using a `set` of tuples or a `set` of strings instead. Tuples would be a better choice as the two files could be split on different delimiters, but I don't... |
Numpy multidimensional array slicing | 7,326,924 | 7 | 2011-09-06T22:31:24Z | 7,327,148 | 9 | 2011-09-06T23:01:09Z | [
"python",
"arrays",
"multidimensional-array",
"indexing",
"numpy"
] | Suppose I have defined a 3x3x3 numpy array with
```
x = numpy.arange(27).reshape((3, 3, 3))
```
Now, I can get an array containing the (0,1) element of each 3x3 subarray with `x[:, 0, 1]`, which returns `array([ 1, 10, 19])`. What if I have a tuple (m,n) and want to retrieve the (m,n) element of each subarray(0,1) st... | you can create the index tuple first:
```
index = (numpy.s_[:],)+t
x[index]
``` |
Iterating a loop with a pause | 7,326,950 | 4 | 2011-09-06T22:35:05Z | 7,326,971 | 7 | 2011-09-06T22:37:10Z | [
"python"
] | I am working to integrate with an API that has a limit on the number of requests per second. Is there a way, when running a `for` loop in python to delay each cycle? Conceptually, something like --
```
def function(request):
for x in [a,b,c,d,...]:
do something
wait y seconds
```
Thank you. | ```
import time
...
time.sleep(5)
```
This will sleep for 5 seconds. See <http://docs.python.org/library/time.html#time.sleep> |
How can I classify data with the nearest-neighbor algorithm using Python? | 7,326,958 | 41 | 2011-09-06T22:35:58Z | 7,330,224 | 60 | 2011-09-07T07:23:52Z | [
"python",
"machine-learning"
] | I need to classify some data with (I hope) nearest-neighbour algorithm. I've googled this problem and found a lot of libraries (including PyML, mlPy and Orange), but I'm unsure of where to start here.
How should I go about implementing k-NN using Python? | Particularly given the technique (k-Nearest Neighbors) that you mentioned in your Q, i would strongly recommend ***[scikits.learn](http://scikit-learn.sourceforge.net/stable/)***. [*Note*: after this Answer was posted, the lead developer of this Project informed me of a [new homepage](http://scikit-learn.org) for this ... |
WYSIWYG tool for programming GUI in Python? | 7,328,338 | 7 | 2011-09-07T02:40:35Z | 7,328,344 | 7 | 2011-09-07T02:42:34Z | [
"python",
"qt",
"user-interface",
"wxpython",
"pyqt4"
] | I was hoping to find a tool similar to Borland Delphi or VisualBasic for Python. Basically, I want to be able to program Windows apps with ease, without actually having to code every single widget. Does such a software exist? Thanks! | Here's one for [wxPython](http://www.wxpython.org/):
<http://wxglade.sourceforge.net/> |
Python pytz Converting a timestamp (string format) from one timezone to another | 7,328,630 | 5 | 2011-09-07T03:40:28Z | 7,328,690 | 7 | 2011-09-07T03:53:44Z | [
"python",
"timezone",
"timestamp",
"pytz"
] | I have a timestamp with timezone information in string format and I would like to convert this to display the correct date/time using my local timezone. So for eg... I have
```
timestamp1 = 2011-08-24 13:39:00 +0800
```
and I would like to convert this to say timezone offset +1000 to dsiplay
```
timestamp2 = 2011-08... | [datetime.astimezone](http://docs.python.org/library/datetime.html#datetime.datetime.astimezone) will do your basic conversion once you have a datetime object. If you're trying to get a datetime object from a string, pip install [python-dateutil](http://labix.org/python-dateutil) and it's as simple as:
```
>>> from da... |
WebDriverException:can't load profile error in selenium python script | 7,328,658 | 9 | 2011-09-07T03:46:04Z | 8,270,048 | 11 | 2011-11-25T13:47:14Z | [
"python",
"unit-testing",
"selenium",
"webdriver",
"web-testing"
] | I am using selenium webdriver in python to drive Firefox automaticly, the python script is exported from the selenium IDE add-on in Firefox. But when I run the script it raise error:
```
======================================================================
ERROR: test_selenium (__main__.SeleniumTest)
... | I had this issue after upgrading to Firefox 8, when running selenium v 2.9.0.
It was fixed by **upgrading to the latest version of selenium** (2.13).
```
sudo pip install selenium --upgrade
```
(if you're using the Python flavour) |
Nested for loops in Python compared to map function | 7,330,300 | 4 | 2011-09-07T07:32:04Z | 7,330,346 | 8 | 2011-09-07T07:35:33Z | [
"python",
"loops"
] | I'm working in python and currently have the following code:
```
list = []
for a in range(100):
for b in range(100):
for c in range(100):
list.append(run(a,b,c))
```
where run(a,b,c) returns an integer (for example, it could multiply the three numbers together). Is there a faster way to either... | Have a look at the [itertools-module](http://docs.python.org/library/itertools.html#module-itertools) and particulary the [product method](http://docs.python.org/library/itertools.html#itertools.product)
example usage:
```
for i in itertools.product(range(0,100), repeat=3):
#do stuff with i
list.append(run(i[... |
Python - email header decoding UTF-8 | 7,331,351 | 14 | 2011-09-07T09:10:03Z | 7,331,577 | 25 | 2011-09-07T09:29:38Z | [
"python",
"email",
"email-headers"
] | is there any Python module which helps to decode the various forms of encoded mail headers, mainly Subject, to simple - say - UTF-8 strings?
Here are example Subject headers from mail files that I have:
```
Subject: [ 201105311136 ]=?UTF-8?B?IMKnIDE2NSBBYnM=?=. 1 AO;
Subject: [ 201105161048 ] GewSt:=?UTF-8?B?IFdlZ2Zh... | This type of encoding is known as [MIME encoded-word](http://en.wikipedia.org/wiki/MIME#Encoded-Word) and the [email](http://docs.python.org/library/email.html#module-email) module can decode it:
```
from email.header import decode_header
print decode_header("""=?UTF-8?B?IERyZWltb25hdHNmcmlzdCBmw7xyIFZlcnBmbGVndW5nc21... |
Python - email header decoding UTF-8 | 7,331,351 | 14 | 2011-09-07T09:10:03Z | 21,715,870 | 15 | 2014-02-12T00:02:21Z | [
"python",
"email",
"email-headers"
] | is there any Python module which helps to decode the various forms of encoded mail headers, mainly Subject, to simple - say - UTF-8 strings?
Here are example Subject headers from mail files that I have:
```
Subject: [ 201105311136 ]=?UTF-8?B?IMKnIDE2NSBBYnM=?=. 1 AO;
Subject: [ 201105161048 ] GewSt:=?UTF-8?B?IFdlZ2Zh... | I was just testing with encoded headers in Python 3.3, and I found that this is a very convenient way to deal with them:
```
>>> from email.header import Header, decode_header, make_header
>>> subject = '[ 201105161048 ] GewSt:=?UTF-8?B?IFdlZ2ZhbGwgZGVyIFZvcmzDpHVmaWdrZWl0?='
>>> h = make_header(decode_header(subject... |
Check if a string is a possible abbrevation for a name | 7,331,462 | 7 | 2011-09-07T09:20:02Z | 7,331,558 | 7 | 2011-09-07T09:28:07Z | [
"python",
"string-matching",
"slug",
"abbreviation",
"text-analysis"
] | I'm trying to develop a python algorithm to check if a string could be an abbrevation for another word. For example
* `fck` is a match for `fc kopenhavn` because it matches the first characters of the word. `fhk` would not match.
* `fco` should not match `fc kopenhavn` because no one irl would abbrevate FC Kopenhavn a... | This passes all the tests, including a few extra I created. It uses recursion. Here are the rules that I used:
* The first letter of the abbreviation must match the first letter of
the text
* The rest of the abbreviation (the abbrev minus the first letter) must be an abbreviation for:
+ the remaining words, or
... |
Trace Python imports | 7,332,299 | 14 | 2011-09-07T10:23:59Z | 7,334,681 | 22 | 2011-09-07T13:30:35Z | [
"python",
"debugging",
"import",
"trace"
] | My Python library just changed it's main module name from `foo.bar` to `foobar`. For backward compat, `foo.bar` still exists, but importing it raises a few warnings. Now, it seems some example program still imports from the old module, but not directly.
I'd like to find the erroneous `import` statement. Is there any t... | Start the python interpreter with `-v`:
```
$ python -v -m /usr/lib/python2.6/timeit.py
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# /usr/lib/python2.6/site.pyc matches /usr/lib/python2.6/site.py
import site # precompiled from /usr/lib/python2.6/site.pyc
# /usr/lib/python2.6/os.p... |
Add single element to array in numpy | 7,332,841 | 25 | 2011-09-07T11:09:07Z | 7,332,880 | 9 | 2011-09-07T11:12:41Z | [
"python",
"arrays",
"numpy"
] | I have a numpy array containing:
```
[1, 2, 3]
```
I want to create an array containing:
```
[1, 2, 3, 1]
```
That is, I want to add the first element on to the end of the array.
I have tried the obvious:
```
np.concatenate((a, a[0]))
```
But I get an error saying `ValueError: arrays must have same number of dim... | `a[0]` isn't an array, it's the first element of `a` and therefore has no dimensions.
Try using `a[0:1]` instead, which will return the first element of `a` inside a single item array. |
Add single element to array in numpy | 7,332,841 | 25 | 2011-09-07T11:09:07Z | 7,332,902 | 7 | 2011-09-07T11:15:00Z | [
"python",
"arrays",
"numpy"
] | I have a numpy array containing:
```
[1, 2, 3]
```
I want to create an array containing:
```
[1, 2, 3, 1]
```
That is, I want to add the first element on to the end of the array.
I have tried the obvious:
```
np.concatenate((a, a[0]))
```
But I get an error saying `ValueError: arrays must have same number of dim... | try this
```
np.concatenate((a, np.array([a[0]]))
```
<http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html>
concatenate needs both elements to be array, however a[0] is not an array. That's why it does not work. |
Add single element to array in numpy | 7,332,841 | 25 | 2011-09-07T11:09:07Z | 7,332,977 | 40 | 2011-09-07T11:21:09Z | [
"python",
"arrays",
"numpy"
] | I have a numpy array containing:
```
[1, 2, 3]
```
I want to create an array containing:
```
[1, 2, 3, 1]
```
That is, I want to add the first element on to the end of the array.
I have tried the obvious:
```
np.concatenate((a, a[0]))
```
But I get an error saying `ValueError: arrays must have same number of dim... | I think it's more normal to use the proper method for adding an element:
```
numpy.append(a, a[0])
``` |
"getaddrinfo failed", what does that mean? | 7,334,199 | 15 | 2011-09-07T12:52:36Z | 7,335,972 | 20 | 2011-09-07T14:54:29Z | [
"python",
"bottle"
] | > File "C:\Python27\lib\socket.py", line 224, in meth
> return getattr(self.\_sock,name)(\*args) gaierror: [Errno 11004]
> getaddrinfo failed
Getting this error when launching the hello world sample from here:
<http://bottlepy.org/docs/dev/> | It most likely means the hostname you're passing to `run` can't be resolved.
```
import socket
socket.getaddrinfo('localhost', 8080)
```
If it doesn't work there, it's not going to work in the Bottle example. You can try '127.0.0.1' instead of 'localhost' in case that's the problem. |
Python: Get local IP-Address used to send IP data to a specific remote IP-Address | 7,334,349 | 8 | 2011-09-07T13:04:19Z | 7,335,145 | 10 | 2011-09-07T13:59:51Z | [
"python",
"ip"
] | I am using a Python script to send UDP packets to a server which will register my script to receive notifications from the server. The protocol requires that I send my own IP-Address and port on which I want to receive these notifications, so this should be an address that is reachable from the server's network.
Solut... | I had to solve the same problem once, and spent considerable time trying to find a better way, without success. I also started with gethostname, but discovered, as you did, that it doesn't always return the right result, and can even throw an exception in cases where there is a problem with the hosts file.
The only so... |
Problem due to double quote while parsing csv. | 7,334,752 | 3 | 2011-09-07T13:34:44Z | 7,334,797 | 8 | 2011-09-07T13:38:00Z | [
"python",
"csv"
] | I have csv file in the follwing format,
```
"1";"A";"A:"61 B & BA";"C"
```
Following is my code to read csv file,
```
with open(path, 'rb') as f:
reader = csv.reader(f, delimiter = ';', quotechar = '"')
for row in reader:
print row
```
The problem is, it breaks row in 5 fields,
```
['1', 'A', '... | Your csv file is invalid. If a quote occurs inside a (quoted) string, it must be escaped by doubling it.
```
"1";"A";"A:""61 B & BA";"C"
```
would result in
```
['1', 'A', 'A:"61 B & BA', 'C']
```
How should the CSV module guess the difference between quotes that delimit an item and quotes within the item? |
Can I load a multi-frame TIFF through OpenCV? | 7,335,308 | 6 | 2011-09-07T14:10:21Z | 7,344,847 | 8 | 2011-09-08T07:54:59Z | [
"python",
"image",
"opencv"
] | Anyone know if OpenCV is capable of loading a multi-frame TIFF stack?
I'm using OpenCV 2.2.0 with python 2.6. | While OpenCV can't open multi-frame TIFF files, you can open the image using PIL and then pass the data on to OpenCV. I haven't yet been able to get it working with the new "cv2" namespace
```
tiff = Image.open('sample.tif')
try:
while 1:
# Convert PIL image to OpenCV
image = cv.CreateImageHeader(t... |
mysql-python installation problems (on mac os x lion) | 7,335,853 | 10 | 2011-09-07T14:44:51Z | 7,336,998 | 11 | 2011-09-07T16:04:38Z | [
"python",
"mysql",
"osx",
"installation"
] | I installed everything successfully, or so I thought:
* MySQL 5.5 for x86\_64.
* Python 2.7, x86\_64.
* mysql-python 1.2.3, x86\_64.
But when I try:
```
import MySQLdb
```
I get:
```
ImportError:
dlopen(/Users/aj/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.6-ix86_64.egg-tmp/_mysql.so, 2):
no suitable ima... | I think there might be slight quirks with doing this on Mac 64-bit (and if you google this problem shows up a lot too).
I've run into it, and there are a couple things you can do:
### Override the environment
You can change the `DYLD_LIBRARY_PATH` environment variable, which tells the linker where to look for dynami... |
mysql-python installation problems (on mac os x lion) | 7,335,853 | 10 | 2011-09-07T14:44:51Z | 7,337,194 | 9 | 2011-09-07T16:17:37Z | [
"python",
"mysql",
"osx",
"installation"
] | I installed everything successfully, or so I thought:
* MySQL 5.5 for x86\_64.
* Python 2.7, x86\_64.
* mysql-python 1.2.3, x86\_64.
But when I try:
```
import MySQLdb
```
I get:
```
ImportError:
dlopen(/Users/aj/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.6-ix86_64.egg-tmp/_mysql.so, 2):
no suitable ima... | With the help of the comment from @birryree I found the problem. I would probably be better off following the procedure suggested by @birryree in his answer but I did try this before and it worked:
As suggested, I did:
```
file /Users/aj/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.6-ix86_64.egg-tmp/_mysql.so
```
... |
Python Glob without the whole path - only the filename | 7,336,096 | 15 | 2011-09-07T15:02:31Z | 7,336,115 | 28 | 2011-09-07T15:04:13Z | [
"python",
"glob"
] | Is there a way I can use glob on a directory, to get files with a specific extension, but only the filename itself, not the whole path? | Use `os.path.basename(path)` to get the filename. |
Python Glob without the whole path - only the filename | 7,336,096 | 15 | 2011-09-07T15:02:31Z | 7,336,122 | 9 | 2011-09-07T15:04:35Z | [
"python",
"glob"
] | Is there a way I can use glob on a directory, to get files with a specific extension, but only the filename itself, not the whole path? | Use glob in combination with `os.path.basename`. |
Python Glob without the whole path - only the filename | 7,336,096 | 15 | 2011-09-07T15:02:31Z | 20,384,686 | 22 | 2013-12-04T19:55:43Z | [
"python",
"glob"
] | Is there a way I can use glob on a directory, to get files with a specific extension, but only the filename itself, not the whole path? | This might help someone:
`names = [os.path.basename(x) for x in glob.glob('/your_path')]` |
Testing REST API with database backend | 7,336,101 | 10 | 2011-09-07T15:03:06Z | 7,355,552 | 8 | 2011-09-08T23:09:08Z | [
"python",
"unit-testing",
"testing",
"rest",
"flask"
] | I want to know the best/different ways to test a REST API which uses a database backend. I've developed my API with Flask in Python and want to use unittest or nose.
But my problem, is that some resources require another resource to create them in the first place. Is there a way to say that to test the creation of a b... | There are 2 standard ways of approaching a test that depends on something else (object, function call, etc).
* You can use mocks in place of the objects the code you are testing depends on.
* You can load a fixture or do the creation/call in the test setup.
Some people like "classical" unit tests where only the "unit... |
Missing Table When Running Django Unittest with Sqlite3 | 7,336,130 | 14 | 2011-09-07T15:04:56Z | 27,117,091 | 12 | 2014-11-25T01:01:37Z | [
"python",
"database",
"django",
"unit-testing",
"sqlite"
] | I'm trying to run a unittest with Django 1.3. Normally, I use MySQL as my database backend, but since this is painfully slow to spinup for a single unittest, I'm using Sqlite3.
So to switch to Sqlite3 just for my unittests, in my settings.py I have:
```
import sys
if 'test' in sys.argv:
DATABASES = {
'def... | In Django 1.4, 1.5, 1.6, 1.7, or 1.8 it *should* be sufficient to use:
```
if 'test' in sys.argv:
DATABASES['default']['ENGINE'] = 'django.db.backends.sqlite3'
```
It should not be necessary to override `TEST_NAME`1, nor to call `syncdb` in order to run tests. As @osa points out, the default with the SQLite engin... |
How to avoid circular imports in Python? | 7,336,802 | 37 | 2011-09-07T15:49:53Z | 7,336,880 | 48 | 2011-09-07T15:55:37Z | [
"python",
"import",
"circular-dependency"
] | I know the issue of circular imports in python has come up many times before and I have read these discussions. The comment that is made repeatedly in these discussions is that a circular import is a sign of a bad design and the code should be reorganised to avoid the circular import.
Could someone tell me how to avoi... | Only import the module, don't import from the module:
Consider `a.py`:
```
import b
class A:
def bar(self):
return b.B()
```
and `b.py`:
```
import a
class B:
def bar(self):
return a.A()
```
This works perfectly fine. |
How to avoid circular imports in Python? | 7,336,802 | 37 | 2011-09-07T15:49:53Z | 37,126,790 | 25 | 2016-05-09T23:05:09Z | [
"python",
"import",
"circular-dependency"
] | I know the issue of circular imports in python has come up many times before and I have read these discussions. The comment that is made repeatedly in these discussions is that a circular import is a sign of a bad design and the code should be reorganised to avoid the circular import.
Could someone tell me how to avoi... | Consider the following example python package where `a.py` and `b.py` depend on each other:
```
/package
__init__.py
a.py
b.py
```
There are several ways to import a module in python
```
import package.a # Absolute import
import package.a as a_mod # Absolute import bound to different name
from... |
Python: Assign Value if None Exists | 7,338,501 | 18 | 2011-09-07T18:08:47Z | 7,338,567 | 37 | 2011-09-07T18:13:22Z | [
"python",
"variable-assignment",
"python-2.7"
] | I am a RoR programmer new to Python. I am trying to find the syntax that will allow me to set a variable to a specific value only if it wasn't previously assigned. Basically I want:
`# only if var1 has not been previously assigned`
`var1 = 4` | You should initialize variables to None and then check it:
```
var1 = None
if var1 is None:
var1 = 4
```
Which can be written in one line as:
```
var1 = 4 if var1 is None else var1
```
or using shortcut (but checking against None is recommended)
```
var1 = var1 or 4
```
alternatively if you will not have anyt... |
Python: Assign Value if None Exists | 7,338,501 | 18 | 2011-09-07T18:08:47Z | 7,338,687 | 10 | 2011-09-07T18:24:38Z | [
"python",
"variable-assignment",
"python-2.7"
] | I am a RoR programmer new to Python. I am trying to find the syntax that will allow me to set a variable to a specific value only if it wasn't previously assigned. Basically I want:
`# only if var1 has not been previously assigned`
`var1 = 4` | This is a very different style of programming, but I always try to rewrite things that looked like
```
bar = None
if foo():
bar = "Baz"
if bar is None:
bar = "Quux"
```
into just:
```
if foo():
bar = "Baz"
else:
bar = "Quux"
```
That is to say, I try hard to avoid a situation where some code paths ... |
Python: Assign Value if None Exists | 7,338,501 | 18 | 2011-09-07T18:08:47Z | 22,736,342 | 8 | 2014-03-29T20:15:09Z | [
"python",
"variable-assignment",
"python-2.7"
] | I am a RoR programmer new to Python. I am trying to find the syntax that will allow me to set a variable to a specific value only if it wasn't previously assigned. Basically I want:
`# only if var1 has not been previously assigned`
`var1 = 4` | ```
var1 = var1 or 4
```
The only issue this might have is that if var1 is a falsey value, like False or 0 or [], it will choose 4 instead. That might be an issue. |
Assigning the value returned by a function to a variable in Python | 7,338,781 | 3 | 2011-09-07T18:32:57Z | 7,338,818 | 8 | 2011-09-07T18:36:07Z | [
"python"
] | I began coding in Python recently and encountered a problem assigning the value returned by a function to a variable.
```
class Combolock:
def _init_(self,num1,num2,num3):
self.x = [num1,num2,num3]
def next(self, state):
print "Enter combination"
combo = raw_input(">")
if combo ... | You should use `self.next(currentState)`, as you want the `next` method in the class scope.
The function `next` is global and `next(obj)` works only if `obj` is an [iterator](http://docs.python.org/library/stdtypes.html#iterator-types).
You might want to have a look at the [yield statement](http://docs.python.org/re... |
Multiple data set plotting with matplotlib.pyplot.plot_date | 7,340,547 | 5 | 2011-09-07T21:08:12Z | 7,340,993 | 9 | 2011-09-07T21:55:54Z | [
"python",
"numpy",
"matplotlib",
"scipy"
] | this might be really a simple question for most of you guys using matplotlib. Please help me out. I want to plot two array like [1,2,3,4] and [4,5,6,7] versus time in a same plot. I am trying to use matplotlib.pyplot.plot\_date but couldn't figure out how to do it. It seems to me that only one trend can be plotted with... | To use plot date with multiple trends, it's easiest to call it multiple times. For example:
```
import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# Generate Data
time = mdates.drange(datetime.datetime(2010, 1, 1),
datetime.datetime(2011, 1, 1),
... |
Problem with the __str__ method | 7,340,786 | 2 | 2011-09-07T21:35:31Z | 7,340,810 | 10 | 2011-09-07T21:38:08Z | [
"python"
] | This is my script:
```
import math
class Vector:
def __init__(self, x=0.0, y=0.0):
self.x = x
self.y = y
def ___str___(self):
return "{0}, {1}".format(self.x, self.y)
@classmethod
def vectorPoints(cls, p1, p2):
a = p2[0] - p1[0]
b = p2[1] - p1[1]
return... | The method name should be `__str__` (2 underscores surrounding), not `___str___` (3 underscores surrounding). |
Python: Conditional variables based on whether nosetest is running | 7,341,005 | 7 | 2011-09-07T21:57:44Z | 7,341,671 | 9 | 2011-09-07T23:41:43Z | [
"python",
"nose",
"peewee"
] | I'm running nosetests which have a setup function that needs to load a different database than the production database. The ORM I'm using is peewee which requires that the database for a model is set in the definition.
So I need to set a conditional variable but I don't know what condition to use in order to check if ... | Perhaps examining `sys.argv[0]` to see what command is running? |
Can I make an admin field not required in Django without creating a form? | 7,341,066 | 43 | 2011-09-07T22:05:55Z | 7,341,194 | 81 | 2011-09-07T22:21:56Z | [
"python",
"django",
"django-models",
"django-admin",
"django-forms"
] | Every time I enter in a new player in the Admin portion of Django I get an error message that says "This field is required.".
Is there a way to make a field not required without having to create a custom form? Can I do this within models.py or admin.py?
Here's what my class in models.py looks like.
```
class PlayerS... | Just Put
```
blank=True
```
in your model i.e.:
```
rushing_attempts = models.CharField(
max_length = 100,
verbose_name = "Rushing Attempts",
blank=True
)
``` |
Get original indices of a sorted Numpy array | 7,341,557 | 22 | 2011-09-07T23:18:28Z | 7,341,589 | 36 | 2011-09-07T23:25:31Z | [
"python",
"numpy"
] | I have an array of distances `a = np.array([20.5 ,5.3 ,60.7 ,3.0 ], 'double')` and I need the indices of the sorted array (for example `[3, 1, 0, 2]`, for `a.sort()`). Is there a function in Numpy to do that? | Yes, there's the `x = numpy.argsort(a)` function or `x = numpy.ndarray.argsort(a)` method. It does exactly what you're asking for. You can also call `argsort` as a method on an `ndarray` object like so: `a.argsort()`.
Here's a link to the documentation: <http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsor... |
Django - Change a ForeignKey relation to OneToOne | 7,341,722 | 16 | 2011-09-07T23:50:17Z | 8,277,945 | 10 | 2011-11-26T10:57:12Z | [
"python",
"mysql",
"django",
"django-south"
] | I am using South with my Django app. I have two models that I am changing from having a `ForeignKey` relation to having a `OneToOneField` relation. When I ran this migration on my dev database, it ran fine. When the migrations get ran as part of creating a test database, the latest migration fails with a MySQL 1005 err... | You actually don't need a migration at all. OneToOne and ForeignKey relations have a compatible database schema under the hook: a simple column witht the other object ID in one of the table.
Just fake the migration with `migrate --fake` if you don't want to enter in the trouble of telling south to ignore this change. |
How to convert python tuple into a two dimentional table? | 7,342,054 | 2 | 2011-09-08T00:53:16Z | 7,342,147 | 7 | 2011-09-08T01:15:13Z | [
"python"
] | a flat (one dimension) tuple on input:
```
data = ('a','b','c'.....'z');
```
output: table (two dimensions) that has n (say 9) columns
```
table = ?what code here?
```
so
```
print table
( ('a','b','c'...), ('k','l','m','n'...), ....)
```
which is the shortest way to do so? | Here's the short version if you find the rest of this too wordy:
```
n = 9
table = zip(*[iter(data)]*n)
```
Let's say you start with a list:
```
>>> data = range(1,101)
>>> data
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
35, 36, 37,... |
Linear Interpolation - Python | 7,343,697 | 9 | 2011-09-08T05:58:05Z | 7,343,815 | 10 | 2011-09-08T06:11:21Z | [
"python",
"linear",
"interpolation"
] | I'm fairly new to programming and thought I'd try writing a linear-interpolation function.
Say I am given data as follows:
x= [1, 2.5, 3.4, 5.8, 6]
y=[2, 4, 5.8, 4.3, 4]
I want to design a function that will interpolate linearly between 1 and 2.5, 2.5 to 3.4 and so on using Python.
I have tried looking through
<http... | As I understand your question, you want to write some function `y = interpolate(x_values, y_values, x)`, which will give you the `y` value at some `x`? The basic idea then follows these steps:
1. Find the indices of the values in `x_values` which define an interval containing `x`. For instance, for `x=3` with your exa... |
Linear Interpolation - Python | 7,343,697 | 9 | 2011-09-08T05:58:05Z | 7,345,691 | 7 | 2011-09-08T09:10:56Z | [
"python",
"linear",
"interpolation"
] | I'm fairly new to programming and thought I'd try writing a linear-interpolation function.
Say I am given data as follows:
x= [1, 2.5, 3.4, 5.8, 6]
y=[2, 4, 5.8, 4.3, 4]
I want to design a function that will interpolate linearly between 1 and 2.5, 2.5 to 3.4 and so on using Python.
I have tried looking through
<http... | I thought up a rather elegant solution (IMHO), so I can't resist posting it:
```
from bisect import bisect_left
class Interpolate(object):
def __init__(self, x_list, y_list):
if any(y - x <= 0 for x, y in zip(x_list, x_list[1:])):
raise ValueError("x_list must be in strictly ascending order!")... |
Linear Interpolation - Python | 7,343,697 | 9 | 2011-09-08T05:58:05Z | 13,688,798 | 19 | 2012-12-03T17:44:05Z | [
"python",
"linear",
"interpolation"
] | I'm fairly new to programming and thought I'd try writing a linear-interpolation function.
Say I am given data as follows:
x= [1, 2.5, 3.4, 5.8, 6]
y=[2, 4, 5.8, 4.3, 4]
I want to design a function that will interpolate linearly between 1 and 2.5, 2.5 to 3.4 and so on using Python.
I have tried looking through
<http... | ```
import scipy.interpolate
y_interp = scipy.interpolate.interp1d(x, y)
print y_interp(5.0)
```
[`scipy.interpolate.interp1d`](http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html#d-interpolation-interp1d) does linear interpolation by and can be customized to handle error conditions. |
What is the easiest way of deleting all my blobstore data? | 7,345,893 | 4 | 2011-09-08T09:28:26Z | 8,023,202 | 7 | 2011-11-05T20:54:05Z | [
"python",
"google-app-engine",
"blobstore",
"task-queue"
] | What is your best way to remove all of the blob from blobstore? I'm using Python.
I have quite a lot of blobs and I'd like to delete them all. I'm
currently doing the following:
```
class deleteBlobs(webapp.RequestHandler):
def get(self):
all = blobstore.BlobInfo.all();
more = (all.count()>0)
... | I use this approach:
```
import datetime
import logging
import re
import urllib
from google.appengine.ext import blobstore
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp import util
from google.ap... |
$PYTHONSTARTUP with python 2.7 and python 3.2 | 7,346,984 | 12 | 2011-09-08T11:00:12Z | 7,347,047 | 13 | 2011-09-08T11:05:03Z | [
"python",
"python-3.x",
"startupscript"
] | I finally started using python 3 alongside python 2.7 on Linux.
I setup my python shell using a startup-script defined by $PYTHONSTARTUP.
Due to incompatibilities I am unable to use the same script for both versions.
What is the easiest way to get one script for python 2.7, and another for python 3.2? | If you use Python 2 for some projects and Python 3 for others, then change the environment variable when you change projects.
Or, have your startup script look like this:
```
import sys
if sys.version_info[0] == 2:
import startup2
else:
import startup3
```
and split your real startup code into `startup2.py` ... |
Jenkins with pylint gives build failure | 7,347,233 | 5 | 2011-09-08T11:20:00Z | 7,347,681 | 8 | 2011-09-08T12:01:34Z | [
"python",
"jenkins",
"pylint"
] | I added a build step to execute a Python script.
In this script pylint is called with the lint.Run(..args) to check the code.
The script works but in the end, the build fails with the only error message:
`Build step 'Execute Python script' marked build as failure`
Someone has an idea why this happens? | Pylint has the unpleasant behavior to return a non-zero exit code even only if a small warning issue was found. Only when everything was fine, 0 is returned (see man page).
As usually a non-zero code denotes an error, Jenkins fails the build.
I see two ways to overcome this:
* Use a small script around pylint that a... |
Jenkins with pylint gives build failure | 7,347,233 | 5 | 2011-09-08T11:20:00Z | 9,049,403 | 10 | 2012-01-28T23:05:23Z | [
"python",
"jenkins",
"pylint"
] | I added a build step to execute a Python script.
In this script pylint is called with the lint.Run(..args) to check the code.
The script works but in the end, the build fails with the only error message:
`Build step 'Execute Python script' marked build as failure`
Someone has an idea why this happens? | You can also simply put a
> pylint || exit 0
in the shell cmdline. The Pylint plugin will fail the build anyway by checking the result of pyllint. |
How do I check if a file on http exists, using Python/django? | 7,347,888 | 2 | 2011-09-08T12:18:22Z | 7,347,995 | 7 | 2011-09-08T12:27:41Z | [
"python"
] | How do I check if a file on http exists, using Python/Django?
I try to check if file in <http://hostname/directory/file.jpg> exist | Try [urllib2.urlopen](http://docs.python.org/library/urllib2.html#urllib2.urlopen):
```
import urllib2
ret = urllib2.urlopen('http://hostname/directory/file.jpg')
if ret.code == 200:
print "Exists!"
```
Note that you don't check if *file* exists - you check if *resource* exists
EDIT: The other answer by user *Ge... |
How to right-align columns content in reStructuredText simple tables? | 7,348,208 | 20 | 2011-09-08T12:43:40Z | 7,351,383 | 13 | 2011-09-08T16:26:50Z | [
"python",
"table",
"alignment",
"python-sphinx",
"restructuredtext"
] | I'm editing the documentation for a project of mine using [Sphinx](http://sphinx.pocoo.org/), which in turn uses [reStructuredText](http://docutils.sourceforge.net/rst.html) as markup language.
I have a *simple table* (as opposed to *grid table*) in which the rightmost column reports contains numbers that I would like... | Sadly I don't think rst offers that ability... the table styling options are rather limited. That said, if you're rendering to HTML, you could add a custom stylesheet with a css rule such as:
```
table.right-align-right-col td:last-child {
text-align: right
}
```
and then add the directive:
```
.. rst-class:: ri... |
eval calling lambda don't see self | 7,349,785 | 12 | 2011-09-08T14:37:18Z | 7,349,855 | 9 | 2011-09-08T14:41:53Z | [
"python"
] | Here is a simple code illustrating the essence of a problem:
```
class test:
def __init__(self):
self.var = 0
def set(self, val):
self.var = val
print eval('map(lambda x: self.var*x, [1,2,3,4,5])')
f = test()
f.set(10)
```
It says
```
NameError: global name 'self' is not defined
```
... | Try:
```
eval('map(lambda x, self=self: self.var*x, [1,2,3,4,5])')
```
The odd `self=self` will create a copy of `self` from the outer context into the inner context (the "body" of the lambda expression). |
eval calling lambda don't see self | 7,349,785 | 12 | 2011-09-08T14:37:18Z | 7,349,969 | 7 | 2011-09-08T14:48:17Z | [
"python"
] | Here is a simple code illustrating the essence of a problem:
```
class test:
def __init__(self):
self.var = 0
def set(self, val):
self.var = val
print eval('map(lambda x: self.var*x, [1,2,3,4,5])')
f = test()
f.set(10)
```
It says
```
NameError: global name 'self' is not defined
```
... | This is a tricky situation. First of all as workaround you can use:
```
class test:
def __init__(self):
self.var = 0
def set(self, val):
self.var = val
print eval('map(lambda x,self=self: self.var*x, [1,2,3,4,5])')
f = test()
f.set(10)
```
The reason is not simple to explain... but let... |
How to access the specific locations of an integer list in Python? | 7,350,301 | 4 | 2011-09-08T15:09:09Z | 7,350,323 | 8 | 2011-09-08T15:10:40Z | [
"python",
"numpy"
] | I have an integer list which should be used as indices of another list to retrieve a value. Lets say we have following array
```
a = [1,2,3,4,5,6,7,8,9]
```
We can get the specific elements using following code
```
import operator
operator.itemgetter(1,2,3)(a)
```
It will return the 2nd, 3rd and 4th ite... | Use \*:
```
operator.itemgetter(*b)(a)
```
The \* in a function call means, unpack this value, and use its elements as the arguments to the function. |
Need to do a math operation on every line in several CSV files in Python | 7,350,851 | 2 | 2011-09-08T15:46:24Z | 7,351,246 | 7 | 2011-09-08T16:14:15Z | [
"python",
"csv",
"datestamp"
] | I have about 100 CSV files I have to operate on once a month and I was trying to wrap my head around this but I'm running into a wall. I'm starting to understand some things about Python, but combining several things is still giving me issues, so I can't figure this out.
Here's my problem:
I have many CSV files, and ... | There's a tool in the standard library for each of these tasks:
To iterate over all CSV files in a directory, use the [`glob` module](http://docs.python.org/library/glob.html):
```
import glob
for csvfilename in glob.glob(r"C:\mydirectory\*.csv"):
#do_something
```
To parse a CSV file, use the [`csv` module](htt... |
Control a print format when printing a list in Python | 7,351,270 | 7 | 2011-09-08T16:17:04Z | 7,351,292 | 14 | 2011-09-08T16:19:40Z | [
"python",
"list",
"printing",
"format"
] | I have a list with floating point number named `a`. When I print the list with `print a`. I get the result as follows.
`[8.364, 0.37, 0.09300000000000003, 7.084999999999999, 0.469, 0.303, 9.469999999999999, 0.28600000000000003, 0.2290000000
000001, 9.414, 0.9860000000000001, 0.534, 2.1530000000000005]`
Can I tell the... | ```
In [4]: print ['%5.3f' % val for val in l]
['8.364', '0.370', '0.093', '7.085', '0.469', '0.303', '9.470', '0.286', '0.229', '1.000', '9.414', '0.986', '0.534', '2.153']
```
where `l` is your list.
**edit:** If the quotes are an issue, you could use
```
In [5]: print '[' + ', '.join('%5.3f' % v for v in l) + ']'... |
split string in to 2 based on last occurrence of a separator | 7,351,744 | 42 | 2011-09-08T16:56:50Z | 7,351,782 | 33 | 2011-09-08T16:59:26Z | [
"python",
"string"
] | I would like to know if there is any built in function in python to break the string in to 2 parts, based on the last occurrence of a separator.
for eg:
consider the string "a b c,d,e,f" , after the split over separator ",", i want the output as
"a b c,d,e" and "f".
I know how to manipulate the string to get the des... | ```
>>> "a b c,d,e,f".rsplit(',',1)
['a b c,d,e', 'f']
``` |
split string in to 2 based on last occurrence of a separator | 7,351,744 | 42 | 2011-09-08T16:56:50Z | 7,351,789 | 49 | 2011-09-08T16:59:47Z | [
"python",
"string"
] | I would like to know if there is any built in function in python to break the string in to 2 parts, based on the last occurrence of a separator.
for eg:
consider the string "a b c,d,e,f" , after the split over separator ",", i want the output as
"a b c,d,e" and "f".
I know how to manipulate the string to get the des... | Use `rpartition(s)`. It does exactly that.
You can also use `rsplit(s, 1)`. |
split string in to 2 based on last occurrence of a separator | 7,351,744 | 42 | 2011-09-08T16:56:50Z | 7,351,792 | 20 | 2011-09-08T16:59:56Z | [
"python",
"string"
] | I would like to know if there is any built in function in python to break the string in to 2 parts, based on the last occurrence of a separator.
for eg:
consider the string "a b c,d,e,f" , after the split over separator ",", i want the output as
"a b c,d,e" and "f".
I know how to manipulate the string to get the des... | [`rsplit`](http://docs.python.org/library/stdtypes.html#str.rsplit)
```
>>> "a b c,d,e,f".rsplit(',', 1)
['a b c,d,e', 'f']
``` |
python: deleting numbers in a file | 7,351,939 | 4 | 2011-09-08T17:13:01Z | 7,351,989 | 8 | 2011-09-08T17:16:56Z | [
"python",
"file"
] | I need to delete numbers from a text file on windows XP. I am new to python and just installed it for data scrubbing.
I have stored the test file in C:\folder1\test1.txt
The contexts on test1.txt is just 1 line:
> This must not b3 delet3d, but the number at the end yes 134411
I want to created a file result1.txt wh... | You're using `open()` in the `os` module, which takes a numeric file mode. You want instead the builtin `open()` function. Also, backslashes in strings take on a special meaning in Python; you need to double them up if you really mean backslashes. Try:
```
fin = open('C:\\folder1\\test1.txt','r')
``` |
How to plot 1-d data at given y-value with pylab | 7,352,220 | 9 | 2011-09-08T17:36:26Z | 7,352,558 | 8 | 2011-09-08T18:08:25Z | [
"python",
"matplotlib"
] | I want to plot the data points that are in a 1-D array just along the horizontal axis [edit: at a given y-value], like in this plot:

How can I do this with pylab? | This will plot the array "ar":
```
import matplotlib.pyplot as pp
ar = [1, 2, 3, 8, 4, 5]
pp.plot(ar)
pp.show()
```
If you are using ipython, you can start it with the "-pylab" option and it will import numpy and matplotlib automatically on startup, so you just need to write:
```
ar = [1, 2, 3, 8, 4, 5]
plot(ar)
```... |
Nosetests & Combined Coverage | 7,352,319 | 8 | 2011-09-08T17:45:00Z | 7,352,942 | 13 | 2011-09-08T18:43:33Z | [
"python",
"unit-testing",
"nose"
] | I have many projects that I'm programatically running:
`nosetest --with-coverage --cover-html-dir=happy-sauce/`
The problem is that for each project, the coverage module overwrites the index.html file, instead of appending to it. Is there a way to generate a combined super-index.html file, that contains the results f... | You can't combine the HTML directories. You can combine the .coverage data files, but you'll have to use coverage directly, rather than through nose:
```
$ nosetest --with-coverage proj1
$ mv .coverage .coverage.1
$ nosetest --with-coverage proj2
$ mv .coverage .coverage.2
$ coverage combine
(combines .coverage.1 and ... |
how to find the groups of consecutive elements from an array in numpy? | 7,352,684 | 21 | 2011-09-08T18:21:36Z | 7,353,070 | 9 | 2011-09-08T18:56:31Z | [
"python",
"numpy"
] | I have to cluster the consecutive elements from a numpy array. considering the following example
```
a = [ 0, 47, 48, 49, 50, 97, 98, 99]
```
The output should a list of tuples as follows
```
[(0),(47, 48, 49, 50),(97, 98, 99)]
```
here the difference is just one. between the element. It will be great if the... | Here's a lil func that might help:
```
def group_consecutives(vals, step=1):
"""Return list of consecutive lists of numbers from vals (number list)."""
run = []
result = [run]
expect = None
for v in vals:
if (v == expect) or (expect is None):
run.append(v)
else:
... |
how to find the groups of consecutive elements from an array in numpy? | 7,352,684 | 21 | 2011-09-08T18:21:36Z | 7,353,335 | 65 | 2011-09-08T19:21:13Z | [
"python",
"numpy"
] | I have to cluster the consecutive elements from a numpy array. considering the following example
```
a = [ 0, 47, 48, 49, 50, 97, 98, 99]
```
The output should a list of tuples as follows
```
[(0),(47, 48, 49, 50),(97, 98, 99)]
```
here the difference is just one. between the element. It will be great if the... | ```
def consecutive(data, stepsize=1):
return np.split(data, np.where(np.diff(data) != stepsize)[0]+1)
a = np.array([0, 47, 48, 49, 50, 97, 98, 99])
consecutive(a)
```
yields
```
[array([0]), array([47, 48, 49, 50]), array([97, 98, 99])]
``` |
Call a shell command containing a 'pipe' from Python and capture STDOUT | 7,353,054 | 16 | 2011-09-08T18:54:28Z | 7,353,141 | 25 | 2011-09-08T19:03:35Z | [
"python",
"pipe"
] | How would one call a shell command from Python which contains a pipe and capture the output?
Suppose the command was something like:
```
cat file.log | tail -1
```
The Perl equivalent of what I am trying to do would be something like:
```
my $string = `cat file.log | tail -1`;
``` | Use a subprocess.PIPE, as explained in the subprocess docs section ["Replacing shell pipeline"](http://docs.python.org/library/subprocess.html#replacing-shell-pipeline):
```
import subprocess
p1 = subprocess.Popen(["cat", "file.log"], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["tail", "-1"], stdin=p1.stdout, stdou... |
Why str can't get a second parameter,when __str__ can? | 7,353,486 | 5 | 2011-09-08T19:35:42Z | 7,353,510 | 7 | 2011-09-08T19:37:42Z | [
"python",
"string",
"methods",
"tree",
"operator-overloading"
] | I decided to use str for printing the contents of a tree in tree-like structure,using something like
```
print tree
```
The nodes of the tree are all objects of user-created classes and I overload their `__str__` magic method in order to use the child nodes' str after indent t tabs like that
```
def __str__ (self,t=... | Imagine it this way.
```
def str(obj):
try:
return obj.__str__()
except ...:
...
```
Just because `__str__` can take more parameters, doesn't mean that `str` is configured to pass those parameters through. |
Python: can I modify a Tuple? | 7,353,589 | 3 | 2011-09-08T19:45:59Z | 7,353,615 | 8 | 2011-09-08T19:48:26Z | [
"python",
"list",
"tuples",
"immutability"
] | I have a 2 D tuple (Actually I thought, it was a list.. but the error says its a tuple)
But anyways..
The tuple is of form:
(floatnumber\_val, prod\_id)
now I have a dictionary which contains key-> prod\_id and value prod\_name
now.. i want to change the prod\_id in tuple to prod\_name
So this is waht I did
```
#if pr... | Tuples are not mutable, you cannot change them.
The thing to do is probably to find out why you are creating tuples instead of the list you expected. |
Checking if first letter of string is in uppercase | 7,353,968 | 4 | 2011-09-08T20:19:10Z | 7,353,987 | 8 | 2011-09-08T20:21:01Z | [
"python"
] | I want to create a function that would check if first letter of string is in uppercase. This is what I've came up with so far:
```
def is_lowercase(word):
if word[0] in range string.ascii_lowercase:
return True
else:
return False
```
When I try to run it I get this error:
```
if word[0] i... | This is built-in for strings:
```
word = "Hello"
word.istitle() # True
```
but note that `str.istitle` looks whether **every word** in the string is title-cased, so this might give you a surprise:
```
"Hello world".istitle() # returns False!
```
If you just want to check the very first character of a string use thi... |
Checking if first letter of string is in uppercase | 7,353,968 | 4 | 2011-09-08T20:19:10Z | 7,354,011 | 16 | 2011-09-08T20:22:25Z | [
"python"
] | I want to create a function that would check if first letter of string is in uppercase. This is what I've came up with so far:
```
def is_lowercase(word):
if word[0] in range string.ascii_lowercase:
return True
else:
return False
```
When I try to run it I get this error:
```
if word[0] i... | Why not use str.isupper();
```
In [2]: word = 'asdf'
In [3]: word[0].isupper()
Out[3]: False
In [4]: word = 'Asdf'
In [5]: word[0].isupper()
Out[5]: True
``` |
Override default installation directory for Python bdist Windows installer | 7,354,096 | 7 | 2011-09-08T20:30:09Z | 13,191,956 | 10 | 2012-11-02T08:45:38Z | [
"python",
"distutils"
] | Is it possible to specify during the installer generation (or during the actual installation) a custom path for Python modules? By way of example, let's say I have 5 modules for which I generate an installer using:
c:>python setup.py bdist
Everything gets packaged up correctly, but when I install, I am forced to inst... | You should write setup.cfg where you can specify installation options(see python setup.py install --help output) and then run python setup.py bdist. When creating binary distro python will do the dumb installation under the "build" subdir with this options and create the installer from this dumb installation. For examp... |
Format an un-decorated phone number in django? | 7,354,212 | 8 | 2011-09-08T20:41:45Z | 7,354,910 | 7 | 2011-09-08T21:44:18Z | [
"python",
"django",
"string"
] | I've got a DB chock full o' phone numbers as strings, they're all formatted like 1112223333, I'd like to display it as 111-222-3333 in my django template
I know I can do
```
n = contacts.objects.get(name=name)
n.phone = n.phone[:3] + '-' + n.phone[3:6] + '-' + n.phone[6:]
```
but is there a better / more pythonic wa... | Just one other solution:
```
n.phone = "%c%c%c-%c%c%c-%c%c%c%c" % tuple(map(ord, n.phone))
```
or
```
n.phone = "%s%s%s-%s%s%s-%s%s%s%s" % tuple(n.phone)
``` |
Format an un-decorated phone number in django? | 7,354,212 | 8 | 2011-09-08T20:41:45Z | 7,355,230 | 12 | 2011-09-08T22:24:24Z | [
"python",
"django",
"string"
] | I've got a DB chock full o' phone numbers as strings, they're all formatted like 1112223333, I'd like to display it as 111-222-3333 in my django template
I know I can do
```
n = contacts.objects.get(name=name)
n.phone = n.phone[:3] + '-' + n.phone[3:6] + '-' + n.phone[6:]
```
but is there a better / more pythonic wa... | It may be overkill for your use case if all your numbers are formatted the same way, but you might consider using the [phonenumbers](https://github.com/daviddrysdale/python-phonenumbers) module. It would allow you to add functionality (e.g. international phone numbers, different formatting, etc) very easily.
You can p... |
Format an un-decorated phone number in django? | 7,354,212 | 8 | 2011-09-08T20:41:45Z | 11,889,781 | 7 | 2012-08-09T18:33:44Z | [
"python",
"django",
"string"
] | I've got a DB chock full o' phone numbers as strings, they're all formatted like 1112223333, I'd like to display it as 111-222-3333 in my django template
I know I can do
```
n = contacts.objects.get(name=name)
n.phone = n.phone[:3] + '-' + n.phone[3:6] + '-' + n.phone[6:]
```
but is there a better / more pythonic wa... | This is quite a bit belated, but I figured I'd post my solution anyway. It's super simple and takes advantage of creating your own template tags (for use throughout your project). The other part of this is using the parenthesis around the area code.
```
from django import template
register = template.Library()
def ph... |
Beautiful Soup and Tables | 7,355,806 | 4 | 2011-09-08T23:53:42Z | 7,355,944 | 7 | 2011-09-09T00:22:23Z | [
"python",
"beautifulsoup",
"html-table"
] | Hi I'm trying to parse an html table using Beautiful Soup.
The table looks something like this:
```
<table width=100% border=1 cellpadding=0 cellspacing=0 bgcolor=#e0e0cc>
<tr>
<td width=12% height=1 align=center valign=middle bgcolor=#e0e0cc bordercolorlight=#000000 bordercolordark=white> <b><font face="Verdana" ... | The first problem is with this statement: "t=soup.find(id='table')" There is nothing with an id of table. I think what you mean is "t=soup.find('table')" this finds a table. Unfortunately it only finds the *first* table.
You could do "t=soup.findAll(table)[1]" but this would be quite brittle.
I would suggest somethin... |
Pythonic way to populate numpy array | 7,356,042 | 5 | 2011-09-09T00:40:12Z | 7,356,065 | 7 | 2011-09-09T00:46:56Z | [
"python",
"arrays",
"numpy"
] | I find myself parsing lots of data files (usually in a .csv file or similar) using the csv reader and a for loop to iterate over every line. The data is usually a table of floats so for example.
```
reader = csv.reader(open('somefile.csv'))
header = reader.next()
res_list = [list() for i in header]
for line in r... | There is `numpy.loadtxt`:
```
X = numpy.loadtxt('somefile.csv', delimiter=',')
```
[Documentation.](http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html)
---
Edit: for a list of numpy arrays,
```
X = [scipy.array(line.split(','), dtype='float')
for line in open('somefile.csv', 'r')]
``` |
Google Sites API + OAuth2 (on Appengine) | 7,359,725 | 3 | 2011-09-09T09:39:31Z | 14,060,410 | 9 | 2012-12-27T19:49:15Z | [
"python",
"google-app-engine",
"oauth-2.0",
"google-data-api"
] | I've been trying to make use of the Python Library to access the Google Sites API.
The first step requires a user to authorize our application, they recommend to use OAuth2 and they provide a library that can be found [here](http://code.google.com/p/google-api-python-client/wiki/OAuth2).
At the end of the authorizati... | I spent quite a few hours trying to do exactly this and finally found the answer in this blog post:
<https://groups.google.com/forum/m/#!msg/google-apps-developer-blog/1pGRCivuSUI/3EAIioKp0-wJ>
Here is a soup to nuts example of using the oauth2client together with the gdata API to access Google Sites including the 'M... |
How to repeat a function n times | 7,359,828 | 3 | 2011-09-09T09:47:54Z | 7,359,949 | 15 | 2011-09-09T09:59:01Z | [
"python",
"higher-order-functions"
] | I'm trying to write a function in python that is like:
```
def repeated(f, n):
...
```
where `f` is a function that takes one argument and `n` is a positive integer.
For example if I defined square as:
```
def square(x):
return x * x
```
and I called
```
repeated(square, 2)(3)
```
this would square 3, 2 ... | That should do it:
```
def repeated(f, n):
def rfun(p):
return reduce(lambda x, _: f(x), xrange(n), p)
return rfun
def square(x):
print "square(%d)" % x
return x * x
print repeated(square, 5)(3)
```
output:
```
square(3)
square(9)
square(81)
square(6561)
square(43046721)
18530... |
How to determine whether a substring is in a different string | 7,361,253 | 74 | 2011-09-09T11:55:39Z | 7,361,274 | 132 | 2011-09-09T11:57:08Z | [
"python",
"string"
] | I have a sub-string:
```
substring = "please help me out"
```
I have another string:
```
string = "please help me out so that I could solve this"
```
How do I find if `substring` is a subset of `string` using Python? | with `in`: `substring in string`:
```
>>> substring = "please help me out"
>>> string = "please help me out so that I could solve this"
>>> substring in string
True
``` |
How to determine whether a substring is in a different string | 7,361,253 | 74 | 2011-09-09T11:55:39Z | 7,361,292 | 18 | 2011-09-09T11:57:55Z | [
"python",
"string"
] | I have a sub-string:
```
substring = "please help me out"
```
I have another string:
```
string = "please help me out so that I could solve this"
```
How do I find if `substring` is a subset of `string` using Python? | ```
foo = "blahblahblah"
bar = "somethingblahblahblahmeep"
if foo in bar:
# do something
```
(By the way - try to not name a variable `string`, since there's a Python standard library with the same name. You might confuse people if you do that in a large project, so avoiding collisions like that is a good habit to... |
How to determine whether a substring is in a different string | 7,361,253 | 74 | 2011-09-09T11:55:39Z | 8,243,577 | 11 | 2011-11-23T14:09:31Z | [
"python",
"string"
] | I have a sub-string:
```
substring = "please help me out"
```
I have another string:
```
string = "please help me out so that I could solve this"
```
How do I find if `substring` is a subset of `string` using Python? | If you're looking for more than a True/False, you'd be best suited to use the re module, like:
```
import re
search="please help me out"
fullstring="please help me out so that I could solve this"
s = re.search(search,fullstring)
print(s.group())
```
`s.group()` will return the string "please help me out". |
Getting video dimension from ffmpeg -i | 7,362,130 | 5 | 2011-09-09T13:12:08Z | 29,585,066 | 18 | 2015-04-12T01:47:19Z | [
"python",
"video",
"ffmpeg",
"ffprobe"
] | How would I get the height and width of a video from `ffmpeg`'s information output. For example, with the following output --
```
$ ffmpeg -i 1video.mp4
...
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '/Users/david/Desktop/1video.mp4':
Metadata:
major_brand : isom
minor_version : 1
compatible_brands: ... | Use `ffprobe`:
```
$ ffprobe -v error -show_entries stream=width,height \
-of default=noprint_wrappers=1 input.mp4
width=1280
height=720
```
What the options do:
* `-v error` Make a quiet output, but allow errors to be displayed. Excludes the usual generic FFmpeg output info including version, config, and input de... |
Python: asserting that I'm running on POSIX? | 7,362,225 | 2 | 2011-09-09T13:18:46Z | 7,362,279 | 11 | 2011-09-09T13:23:02Z | [
"python",
"posix"
] | I'm writing some POSIX-specific code, and although I'm not supporting other platforms I'd like to make sure they get a nice clear error at import time rather than strange errors, if they tried to use my code.
Is there a neat way to check that? I guess I could to an `import posix` and catch the `ImportError` but that s... | Take a look at [`os.name`](http://docs.python.org/library/os.html#os.name):
> The name of the operating system dependent module imported. The
> following names have currently been registered: 'posix', 'nt', 'os2',
> 'ce', 'java', 'riscos'.
There are also [`sys.platform`](http://docs.python.org/library/sys.html#sys.pl... |
Behaviour of Python's "yield" | 7,362,900 | 8 | 2011-09-09T14:06:45Z | 7,363,045 | 11 | 2011-09-09T14:17:09Z | [
"python",
"yield"
] | I'm reading about the `yield` keyword in python, and trying to understand running this sample:
```
def countfrom(n):
while True:
print "before yield"
yield n
n += 1
print "after yield"
for i in countfrom(10):
print "enter for loop"
if i <= 20:
print i
else:
... | You can think of it as if the function which `yield`s simply "pauses" when it comes across the `yield`. The next time you call it, it will resume after the `yield` *keeping the state that it was in when it left*. |
Mocking a Django Queryset in order to test a function that takes a queryset | 7,362,952 | 18 | 2011-09-09T14:10:42Z | 7,363,326 | 12 | 2011-09-09T14:38:03Z | [
"python",
"django",
"unit-testing",
"django-queryset",
"django-testing"
] | I have a utility function in my Django project, it takes a queryset, gets some data from it and returns a result. I'd like to write some tests for this function. Is there anyway to 'mock' a QuerySet? I'd like to create an object that doesn't touch the database, and i can provide it with a list of values to use (i.e. so... | Of course you can mock a QuerySet, you can mock anything.
You can create an object yourself, and give it the interface you need, and have it return any data you like. At heart, mocking is nothing more than providing a "test double" that acts enough like the real thing for your tests' purposes.
The low-tech way to get... |
Mocking a Django Queryset in order to test a function that takes a queryset | 7,362,952 | 18 | 2011-09-09T14:10:42Z | 12,351,822 | 7 | 2012-09-10T12:33:40Z | [
"python",
"django",
"unit-testing",
"django-queryset",
"django-testing"
] | I have a utility function in my Django project, it takes a queryset, gets some data from it and returns a result. I'd like to write some tests for this function. Is there anyway to 'mock' a QuerySet? I'd like to create an object that doesn't touch the database, and i can provide it with a list of values to use (i.e. so... | I am having the same issue, and it looks like some nice person has written a library for mocking QuerySets, it is called [mock-django](https://github.com/dcramer/mock-django) and the specific code you will need is here <https://github.com/dcramer/mock-django/blob/master/mock_django/query.py> I think you can then just p... |
HTTP referer issue | 7,364,054 | 2 | 2011-09-09T15:34:10Z | 7,364,099 | 7 | 2011-09-09T15:38:29Z | [
"python",
"django",
"http"
] | I have this view rendering a static page, but I cannot seem to catch the referer of the page
```
def landing(request, referer='google'):
''' Loads the landing page '''
msg = ''
if request.method == 'GET':
referer = request.META['HTTP_REFERER']
return render_to_response('index.html',
... | You should be using `request.META.get('HTTP_REFERER')`. Not every request will have a `Referer` header, and if one doesn't you will get exactly this exception. Test if the result of `get()` is not `None` to see if the header was sent. |
Python multiprocess/multithreading use for concurrent file copy operation | 7,365,174 | 4 | 2011-09-09T17:17:16Z | 7,365,452 | 7 | 2011-09-09T17:46:23Z | [
"python",
"multithreading"
] | I am writing python code to copy bunch of big files/folders from one location to other location on desktop (no network, everything is local). I am using shutil module for that.
But the problem is it takes more time so I want to speed up this copy process. I tried using threading and multiprocessing modules. But to my ... | Your problem is likely IO-bound, so more computational parallelization won't help. As you've seen, you're probably making the problem worse by now requiring the IO requests to jump back and forth between the various threads/processes. There are practical limits to how fast you can move data on a computer, especially wh... |
Detecting if a triangle flips when changing a point | 7,365,531 | 2 | 2011-09-09T17:53:53Z | 7,365,805 | 7 | 2011-09-09T18:17:57Z | [
"python",
"math",
"geometry"
] | I need to change a triangle by replacing one of its points. However, I need to detect if doing so would cause the triangle to flip.
For example, the triangle defined by the points:
```
[(1.0,1.0), (2.0,3.0), (3.0,1.0)]
```
would look like this:

If I change t... | Compute the [cross-product](http://en.wikipedia.org/wiki/Cross_product) of two vectors generated from your three points.
If the direction of the cross product changes sign, the triangle has flipped.
For example:
Given `[(1.0,1.0), (2.0,3.0), (3.0,1.0)]`:
Form two (3D) vectors
`(2-1,3-1,0) = (1,2,0)` and `(3-1,1-1,0)... |
How can I handle NameError and AttributeError gracefully in the Mako runtime environment? | 7,365,848 | 3 | 2011-09-09T18:21:18Z | 7,368,323 | 9 | 2011-09-09T23:01:50Z | [
"python",
"templates",
"template-engine",
"mako"
] | I've found that trying to access an undefined variable within a Mako template raises a `NameError`, and quite logically so. In some applications, however, it's desirable to fail more gracefully, perhaps substituting the empty string on such errors (`AttributeError` is another candidate). This is the default behavior in... | Well, turns out that a little more googling [makes it plain](http://markmail.org/message/qxwkijhbz5rdx3dg):
```
import mako.runtime
mako.runtime.UNDEFINED = ''
```
Now undefined variables will produce the empty string.
Reading the source for the original value of UNDEFINED is enlightening:
```
class Undefined(objec... |
Adding Custom Django Model Validation | 7,366,363 | 24 | 2011-09-09T19:10:20Z | 7,366,555 | 7 | 2011-09-09T19:30:40Z | [
"python",
"django",
"django-models"
] | I have a Django model with a start and end date range. I want to enforce validation so that no two records have overlapping date ranges. What's the simplest way to implement this so that I don't have to repeat myself writing this logic?
e.g. I don't want to re-implement this logic in a Form *and* a `ModelForm` *and* a... | I think you should use this:
<https://docs.djangoproject.com/en/dev/ref/models/instances/#validating-objects>
Just define clean() method in your model like this: (example from the docs link)
```
def clean(self):
from django.core.exceptions import ValidationError
# Don't allow draft entries to have a pub_date.... |
Adding Custom Django Model Validation | 7,366,363 | 24 | 2011-09-09T19:10:20Z | 7,366,731 | 15 | 2011-09-09T19:50:19Z | [
"python",
"django",
"django-models"
] | I have a Django model with a start and end date range. I want to enforce validation so that no two records have overlapping date ranges. What's the simplest way to implement this so that I don't have to repeat myself writing this logic?
e.g. I don't want to re-implement this logic in a Form *and* a `ModelForm` *and* a... | I would override the [`validate_unique`](https://docs.djangoproject.com/en/1.3/ref/models/instances/#django.db.models.Model.validate_unique) method on the model. To make sure you ignore the current object when validating, you can use the following:
```
from django.db.models import Model, DateTimeField
from django.core... |
Adding Custom Django Model Validation | 7,366,363 | 24 | 2011-09-09T19:10:20Z | 18,876,223 | 21 | 2013-09-18T15:20:47Z | [
"python",
"django",
"django-models"
] | I have a Django model with a start and end date range. I want to enforce validation so that no two records have overlapping date ranges. What's the simplest way to implement this so that I don't have to repeat myself writing this logic?
e.g. I don't want to re-implement this logic in a Form *and* a `ModelForm` *and* a... | The basic pattern I've found useful is to put all my custom validation in `clean()` and then simply call [`full_clean()`](https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.full_clean) (which calls `clean()` and a few other methods) from inside `save()`, e.g.:
```
class BaseModel(models... |
Django's syncdb fails with MySQL errno: 150 | 7,366,528 | 10 | 2011-09-09T19:27:57Z | 19,133,667 | 12 | 2013-10-02T09:18:15Z | [
"python",
"mysql",
"django"
] | First off, here's my current setup:
Django : version 1.3
MySQL : version 4.0.18 (not my 1st choice...)
When I run syncdb, I get the following error:
```
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Traceback (most recent call last):
File "C:\path_to_app\manage.py", line... | using Django 1.5, the error was that mysql creating tables with Innodb as default engine. Solution was to add the following to settings for the database and this created issues with constraints:
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'etc....',
'OPTIONS': {
... |
introspective code completion with VIM? ... or other lightweight editor with this feature? | 7,366,550 | 6 | 2011-09-09T19:30:03Z | 7,366,985 | 7 | 2011-09-09T20:17:39Z | [
"python",
"vim",
"ide",
"autocomplete",
"code-completion"
] | I've been all over the web trying to find a way to get VIM to have code completion similar to PyDev. It doesn't seem like it is possible!
-I have tried to use the omnicompletion suggested at this link: <http://blog.dispatched.ch/2009/05/24/vim-as-python-ide/> .
-I have tried several addons to alleviate the problem, n... | No, the omni completion functionality is EXACTLY what you are looking for.
You are using `<C-n>` instead of `<C-x><C-o>`:
* type `<C-n>` & `<C-p>` to complete with words from the buffer (after and before the cursor respectively)
* type `<C-x><C-o>` to complete method/properties names
It's specifically explained in t... |
Python script won't run | 7,366,568 | 4 | 2011-09-09T19:32:41Z | 7,366,607 | 9 | 2011-09-09T19:37:25Z | [
"python"
] | I have some scripts in the folder ~/Scripts which I have added to the path. So I tried to test if I can run them, just by calling them. I have python 3.1 over Linux Mint 11.
```
user@pc ~/Scripts $ python aek.py
AEK
user@pc ~/Scripts $ aek.py
/home/user/Scripts/aek.py: line 1: syntax error near unexpected token `'AE... | You need to add the very first line in your script:
```
#!/usr/bin/python
```
Or whatever interpreter you want to use. If not, the shell (probably bash) will think that it is a shell script and choke.
If you want to get the python interpreter from the path, do instead:
```
#!/usr/bin/env python
```
For extra infor... |
Stop argparse from globbing filepath | 7,366,791 | 3 | 2011-09-09T19:56:22Z | 7,366,844 | 7 | 2011-09-09T20:01:52Z | [
"python",
"argparse"
] | I am using python argparse with the following argument definition:
```
parser.add_argument('path', nargs=1, help='File path to process')
```
But when I enter my command with a `wildcard` argument, `argparse` globs all the file paths and terminates with an error.
How do I get `argparse` not to glob the files? | > How do I get argparse not to glob the files?
You don't.
You get the shell to stop globbing.
However. Let's think for a moment.
You're saying this in your code
```
parser.add_argument('path', nargs=1, help='File path to process')
```
But you are actually providing wild-cards when you run it.
One of those two is... |
Python, date validation | 7,367,204 | 4 | 2011-09-09T20:41:24Z | 7,367,307 | 7 | 2011-09-09T20:50:47Z | [
"python",
"datetime"
] | I'm trying to think of a way to accomplish this in the best pythonic way possible. Right now the only method I can think of is to brute force it.
User inputs a date (via command line) in one of the following manners (ex. ./mypy.py date='20110909.00 23' )
```
date='20110909'
date='20110909.00 23'
date='20110909.00 201... | You can create a mask and parse it, using `try...except` to determine whether the date string matches one of the many masks. I had this code for a project, so I've slightly modified it:
```
from time import mktime, strptime
from datetime import datetime
date = '20110909.00 20110909.23'.split(' ')[0]
result = None
fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.