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 check a string for specific characters? | 5,188,792 | 78 | 2011-03-04T01:47:24Z | 5,189,069 | 14 | 2011-03-04T02:39:10Z | [
"python",
"string"
] | How can I check if a string value has exact characters in it using Python2?
Specifically, I am looking to detect if it has dollar signs ("$"), commas (","), and numbers. | user Jochen Ritzel said this in a comment to an answer to this question from user dappawit.
It should work:
```
('1' in var) and ('2' in var) and ('3' in var) ...
```
'1', '2', etc. should be replaced with the characters you are looking for.
See [this page in the Python 2.7 documentation](http://docs.python.org/2.7/... |
Is shelve in Python thread safe? | 5,189,137 | 7 | 2011-03-04T02:52:25Z | 5,191,340 | 9 | 2011-03-04T08:29:42Z | [
"python",
"thread-safety",
"shelve"
] | Is shelve in Python used for data persistence thread safe? If not, what's a good alternative? | From the [standard library documentation about the Shelve module, under the heading Restrictions](http://docs.python.org/library/shelve.html#restrictions):
> The **shelve module does not support
> concurrent read/write access** to
> shelved objects. (Multiple
> simultaneous read accesses are safe.)
I would assume tha... |
Bypass Confirmation Prompt for pip uninstall | 5,189,199 | 15 | 2011-03-04T03:04:34Z | 16,745,106 | 35 | 2013-05-24T23:56:46Z | [
"python",
"django",
"module",
"pip",
"easy-install"
] | I'm trying to uninstall all django packages in my superuser environment to ensure that all my webapp dependencies are installed to my virtualenv.
```
sudo su
sudo pip freeze | grep -E '^django-' | xargs pip -q uninstall
```
But pip wants to confirm every package uninstall, and there doesn't seem to be a -y option for... | Pip does NOT include a --yes option (as of pip version 1.3.1).
**WORKAROUND: pipe yes to it!**
```
$ sudo ls # enter pw so not prompted again
$ /usr/bin/yes | sudo pip uninstall pymongo
``` |
Bypass Confirmation Prompt for pip uninstall | 5,189,199 | 15 | 2011-03-04T03:04:34Z | 33,557,016 | 15 | 2015-11-05T23:51:40Z | [
"python",
"django",
"module",
"pip",
"easy-install"
] | I'm trying to uninstall all django packages in my superuser environment to ensure that all my webapp dependencies are installed to my virtualenv.
```
sudo su
sudo pip freeze | grep -E '^django-' | xargs pip -q uninstall
```
But pip wants to confirm every package uninstall, and there doesn't seem to be a -y option for... | starting with pip version 7.1.2 you can run `pip uninstall -y <python package>` |
How to auto register a class when it's defined | 5,189,232 | 20 | 2011-03-04T03:13:26Z | 5,189,271 | 23 | 2011-03-04T03:19:19Z | [
"python",
"oop",
"design-patterns",
"decorator",
"metaclass"
] | I want to have an instance of class registered when the class is defined. Ideally the code below would do the trick.
```
registry = {}
def register( cls ):
registry[cls.__name__] = cls() #problem here
return cls
@register
class MyClass( Base ):
def __init__(self):
super( MyClass, self ).__init__()
```... | Yes, meta classes can do this. A meta class' `__new__` method returns the class, so just register that class before returning it.
```
class MetaClass(type):
def __new__(cls, clsname, bases, attrs):
newclass = super(MetaClass, cls).__new__(cls, clsname, bases, attrs)
register(newclass) # here is yo... |
How to auto register a class when it's defined | 5,189,232 | 20 | 2011-03-04T03:13:26Z | 10,942,736 | 10 | 2012-06-08T03:29:54Z | [
"python",
"oop",
"design-patterns",
"decorator",
"metaclass"
] | I want to have an instance of class registered when the class is defined. Ideally the code below would do the trick.
```
registry = {}
def register( cls ):
registry[cls.__name__] = cls() #problem here
return cls
@register
class MyClass( Base ):
def __init__(self):
super( MyClass, self ).__init__()
```... | The problem isn't actually caused by the line you've indicated, but by the `super` call in the `__init__` method. The problem remains if you use a metaclass as suggested by dappawit; the reason the example from that answer works is simply that dappawit has simplified your example by omitting the `Base` class and theref... |
Regex: how to match overlapping patterns (maybe Python specific) | 5,189,396 | 5 | 2011-03-04T03:43:03Z | 5,189,446 | 7 | 2011-03-04T03:52:04Z | [
"python",
"regex"
] | I have a string that looks like this: "XaXbXcX". I'm looking to match any lowercase letters surrounded by X on either side. I tried this in Python, but I'm not getting what I'm looking for:
```
import re
str = "XaXbXcX"
pattern = r'X([a-z])X'
matches = re.findall(pattern, str) # gives me ['a', 'c']. What about b?
``` | You can use a lookbehind assertion:
```
pattern = r'(?<=X)([a-z])X'
``` |
get column names from query result using pymssql | 5,189,776 | 5 | 2011-03-04T04:46:21Z | 5,190,047 | 12 | 2011-03-04T05:27:20Z | [
"python",
"database",
"pymssql"
] | Is there any way to get the column names from the pymssql results? If i specify as\_dict=True I get back a dictionary, which does contain all the column headers, but since it is a dictionary they are not ordered. | pymssql claims to support the Python [DB-API](http://www.python.org/dev/peps/pep-0249/), so you should be able to get the `.description` attribute from your cursor object.
> .description
>
> ```
> This read-only attribute is a sequence of 7-item
> sequences.
>
> Each of these sequences contains ... |
Python: Adding 3 weeks to any date | 5,189,777 | 11 | 2011-03-04T04:46:22Z | 5,189,806 | 35 | 2011-03-04T04:49:35Z | [
"python",
"date"
] | I need help with a program.
How do I add 3 weeks (21 days) to any given date when the user can control the date?
The user will enter the date YYYY-MM-DD.
Below I'm trying to locate the hyphen and make sure there is only 2. This is what I have so far but all it does is repeat itself, can someone tell me where I went... | Use [datetime](http://docs.python.org/library/datetime.html) module to the task. You create a datetime aware object and add 21 days timedelta object to it.
```
>>> import datetime
>>> u = datetime.datetime.strptime("2011-01-01","%Y-%m-%d")
>>> d = datetime.timedelta(days=21)
>>> t = u + d
>>> print(t)
2011-01-22 00:00... |
Use frozenset as a pair in python | 5,189,909 | 6 | 2011-03-04T05:04:27Z | 5,189,940 | 14 | 2011-03-04T05:08:45Z | [
"python",
"set",
"immutability"
] | I would like to make a pair of two elements. I don't care about the order of the elements, so I use `frozenset`.
I can think of the following two methods to iterate the elements back from the frozenset. Isn't there any fancier method? Thanks in advance.
```
pair = frozenset([element1, element2])
pair2 = list(pair)
el... | ```
pair = frozenset([element1, element2])
elem1, elem2 = pair
``` |
Use frozenset as a pair in python | 5,189,909 | 6 | 2011-03-04T05:04:27Z | 5,191,319 | 8 | 2011-03-04T08:26:08Z | [
"python",
"set",
"immutability"
] | I would like to make a pair of two elements. I don't care about the order of the elements, so I use `frozenset`.
I can think of the following two methods to iterate the elements back from the frozenset. Isn't there any fancier method? Thanks in advance.
```
pair = frozenset([element1, element2])
pair2 = list(pair)
el... | If you have a lot of those pair things, using `frozenset()` is NOT a good idea. Use tuples instead.
```
>>> import sys
>>> fs1 = frozenset([42, 666])
>>> fs2 = frozenset([666, 42])
>>> fs1 == fs2
True
>>> t1 = tuple(sorted([42, 666]))
>>> t2 = tuple(sorted([666, 42]))
>>> t1 == t2
True
>>> sys.getsizeof(fs1)
116
>>> s... |
Python db-api: fetchone vs fetchmany vs fetchall | 5,189,997 | 41 | 2011-03-04T05:18:39Z | 5,190,785 | 8 | 2011-03-04T07:10:00Z | [
"python",
"mysql",
"python-db-api"
] | I just had a discussion today with some coworkers about python's db-api fetchone vs fetchmany vs fetchall.
I'm sure the use case for each of these is dependent on the implementation of the db-api that I'm using, but in general what are the use cases for fetchone vs fetchmany vs fetchall?
In other words are the follow... | I think it indeed depends on the implementation, but you can get an idea of the differences by looking into MySQLdb sources. Depending on the options, mysqldb fetch\* keep the current set of rows in memory or server side, so fetchmany vs fetchone has some flexibility here to know what to keep in (python's) memory and w... |
How do I create a line-break in Terminal? | 5,190,030 | 6 | 2011-03-04T05:25:31Z | 5,190,089 | 15 | 2011-03-04T05:35:56Z | [
"python",
"osx",
"terminal"
] | I'm using Python in Terminal on Mac OSX latest. When I press enter, it processes the code I've entered, and I am unable to figure out how to add an additional line of code e.g. for a basic loop. | In the python shell, if you are typing code that allows for continuation, pressing enter once should not execute the code...
The python prompt looks like this:
```
>>>
```
If you start a for loop or type something where python expects more from you the prompt should change to an elipse. For example:
```
>>> def hel... |
How does a lambda function refer to its parameters in python? | 5,190,146 | 6 | 2011-03-04T05:44:13Z | 5,190,174 | 9 | 2011-03-04T05:48:25Z | [
"python",
"lambda",
"functional-programming",
"closures"
] | I am new in Python. My task was quite simple -- I need a list of functions that I can use to do things in batch. So I toyed it with some examples like
```
fs = [lambda x: x + i for i in xrange(10)]
```
Surprisingly, the call of
```
[f(0) for f in fs]
```
gave me the result like `[9, 9, 9, 9, 9, 9, 9, 9, 9, 9]`. It ... | It looks a bit messy, but you can get what you want by doing something like this:
```
>>> fs = [(lambda y: lambda x: x + y)(i) for i in xrange(10)]
>>> [f(0) for f in fs]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```
Normally Python supports the "closure" concept similar to what you're used to in Javascript. However, for this *... |
Best way to log a Python exception | 5,191,830 | 145 | 2011-03-04T09:21:20Z | 5,191,885 | 247 | 2011-03-04T09:25:56Z | [
"python",
"exception",
"logging",
"exception-handling"
] | I'm printing my exceptions to a log file currently with:
```
try:
# coode in here
except Exception, e:
logging.error(e)
```
Could I be printing more information about the exception and the code that generated it than just the exception string? Things like line numbers or stack traces would be great. | [`logger.exception`](http://docs.python.org/library/logging.html#logging.Logger.exception) does that.
For example:
```
import logging
try:
1/0
except Exception as e:
logging.exception("message")
```
Output:
```
ERROR:root:message
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroD... |
Best way to log a Python exception | 5,191,830 | 145 | 2011-03-04T09:21:20Z | 17,397,512 | 109 | 2013-07-01T04:34:41Z | [
"python",
"exception",
"logging",
"exception-handling"
] | I'm printing my exceptions to a log file currently with:
```
try:
# coode in here
except Exception, e:
logging.error(e)
```
Could I be printing more information about the exception and the code that generated it than just the exception string? Things like line numbers or stack traces would be great. | One nice thing about `logging.exception` that [SiggyF's answer](http://stackoverflow.com/a/5191885) doesn't show is that you can pass in an arbitrary message, and logging will still show the full traceback with all the exception details:
```
import logging
try:
1/0
except Exception:
logging.exception("Delibera... |
Best way to log a Python exception | 5,191,830 | 145 | 2011-03-04T09:21:20Z | 29,556,251 | 27 | 2015-04-10T08:01:14Z | [
"python",
"exception",
"logging",
"exception-handling"
] | I'm printing my exceptions to a log file currently with:
```
try:
# coode in here
except Exception, e:
logging.error(e)
```
Could I be printing more information about the exception and the code that generated it than just the exception string? Things like line numbers or stack traces would be great. | Using exc\_info options may be better, to allow you to choose the error level (if you use `exception`, it will always show `error`):
```
try:
# do something here
except Exception, e:
logging.error(e, exc_info=True)
``` |
Best way to log a Python exception | 5,191,830 | 145 | 2011-03-04T09:21:20Z | 33,211,980 | 11 | 2015-10-19T10:21:36Z | [
"python",
"exception",
"logging",
"exception-handling"
] | I'm printing my exceptions to a log file currently with:
```
try:
# coode in here
except Exception, e:
logging.error(e)
```
Could I be printing more information about the exception and the code that generated it than just the exception string? Things like line numbers or stack traces would be great. | [Quoting](https://realpython.com/blog/python/the-most-diabolical-python-antipattern/)
> What if your application does logging some other way â not using the `logging` module?
Now, `traceback` could be used here.
```
import traceback
def log_traceback(ex, ex_traceback=None):
if ex_traceback is None:
ex... |
Change to sudo user within a python script | 5,191,878 | 16 | 2011-03-04T09:25:37Z | 5,191,937 | 7 | 2011-03-04T09:31:19Z | [
"python",
"security",
"sudo"
] | I have a problem. I am writing a piece of software, which is required to perform an operation which requires the user to be in sudo mode. running 'sudo python filename.py' isn't an option, which leads me to my question. Is there a way of changing to sudo half way through a python script, security isn't an issue as the ... | Don't try and make yourself sudo just check if you are and error if your not
```
class NotSudo(Exception):
pass
if os.getuid() != 0:
raise NotSudo("This program is not run as sudo or elevated this it will not work")
``` |
Change to sudo user within a python script | 5,191,878 | 16 | 2011-03-04T09:25:37Z | 9,527,553 | 13 | 2012-03-02T03:25:15Z | [
"python",
"security",
"sudo"
] | I have a problem. I am writing a piece of software, which is required to perform an operation which requires the user to be in sudo mode. running 'sudo python filename.py' isn't an option, which leads me to my question. Is there a way of changing to sudo half way through a python script, security isn't an issue as the ... | It is better to run as little of the program as possible without elevated privileges. You can run the small part that needs more privilege via the `subprocess.call()` function, e.g.
```
import subprocess
returncode = subprocess.call(["/usr/bin/sudo", "/usr/bin/id"])
``` |
use imaplib and oauth for connection with Gmail | 5,193,707 | 8 | 2011-03-04T12:30:06Z | 5,366,380 | 11 | 2011-03-20T02:26:55Z | [
"python",
"django",
"oauth",
"imaplib"
] | I want to use Oauth to connect to Gmail in Python. Right now I've got the xoauth.py script from Google ([link](http://code.google.com/p/google-mail-xoauth-tools/wiki/XoauthDotPyRunThrough)), and generating a token works all fine, but how can I then use that in another script? It's going to be in Django.
Right now my s... | Here's an example using the [`oauth2` module](https://github.com/simplegeo/python-oauth2) to authenticate using oauth, taken from the readme:
```
import oauth2 as oauth
import oauth2.clients.imap as imaplib
# Set up your Consumer and Token as per usual. Just like any other
# three-legged OAuth request.
consumer = oau... |
How can I check for a new line in string in Python 3.x? | 5,193,811 | 4 | 2011-03-04T12:38:43Z | 5,193,847 | 16 | 2011-03-04T12:42:31Z | [
"python",
"python-3.x"
] | How to check for a new line in a string?
Does python3.x have anything similar to java's regular operation where direct `if (x=='*\n')` would have worked? | If you just want to check if a newline (`\n`) is present, you can just use Python's `in` operator to check if it's in a string:
```
>>> "\n" in "hello\ngoodbye"
True
```
... or as part of an `if` statement:
```
if "\n" in foo:
print "There's a newline in variable foo"
```
You don't need to use regular expressio... |
How can I check for a new line in string in Python 3.x? | 5,193,811 | 4 | 2011-03-04T12:38:43Z | 5,193,849 | 7 | 2011-03-04T12:42:38Z | [
"python",
"python-3.x"
] | How to check for a new line in a string?
Does python3.x have anything similar to java's regular operation where direct `if (x=='*\n')` would have worked? | Yes, like this:
```
if '\n' in mystring:
...
```
(Python does have regular expressions, but they're overkill in this case.) |
Better way to convert file sizes in Python | 5,194,057 | 23 | 2011-03-04T13:04:31Z | 5,194,348 | 35 | 2011-03-04T13:30:57Z | [
"python",
"filesize"
] | I am using a library that reads a file and returns its size in bytes.
This file size is then displayed to the end user; to make it easier for them to understand it, I am explicitly converting the file size to `MB` by dividing it by `1024.0 * 1024.0`. Of course this works, but I am wondering is there a better way to do... | There is [hurry.filesize](http://pypi.python.org/pypi/hurry.filesize/) that will take the size in bytes and make a nice string out if it.
```
>>> from hurry.filesize import size
>>> size(11000)
'10K'
>>> size(198283722)
'189M'
```
Or if you want 1K == 1000 (which is what most users assume):
```
>>> from hurry.filesi... |
Better way to convert file sizes in Python | 5,194,057 | 23 | 2011-03-04T13:04:31Z | 14,822,210 | 26 | 2013-02-11T22:34:59Z | [
"python",
"filesize"
] | I am using a library that reads a file and returns its size in bytes.
This file size is then displayed to the end user; to make it easier for them to understand it, I am explicitly converting the file size to `MB` by dividing it by `1024.0 * 1024.0`. Of course this works, but I am wondering is there a better way to do... | Here is what I use:
```
import math
def convertSize(size):
if (size == 0):
return '0B'
size_name = ("KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size,1024)))
p = math.pow(1024,i)
s = round(size/p,2)
return '%s %s' % (s,size_name[i])
```
NB : size should be sent... |
Why is python's subprocess.call implemented like this? | 5,195,122 | 12 | 2011-03-04T14:37:14Z | 5,195,443 | 8 | 2011-03-04T15:07:01Z | [
"python",
"implementation",
"subprocess"
] | The subprocess module has the convenience function `call`, which is implemented like this in both 2.6 and 3.1:
```
def call(*popenargs, **kwargs):
return Popen(*popenargs, **kwargs).wait()
```
The documentation for this function carries a red warning, reading:
> **Warning**: Like Popen.wait(), this will deadlock... | I spent some time looking through [PEP-324](http://www.python.org/dev/peps/pep-0324/), which introduced the subprocess module, trying to figure out the design decisions involved, but I think the answer is actually very simple:
There's **no reason** to pass `stdout=PIPE` or `stderr=PIPE` to `subprocess.call`, so the fa... |
twisted conch filetransfer | 5,195,427 | 10 | 2011-03-04T15:05:41Z | 5,205,854 | 28 | 2011-03-05T18:25:47Z | [
"python",
"ssh",
"twisted",
"sftp",
"scp"
] | I am trying to implement a very simple file transfer client in python using twisted conch. The client should simply transfer a few files to a remote ssh/sftp server in a programatic way. The function is given username, password, file list, destination server:directory and just needs to carry out the authentication and ... | Doing an SFTP file transfer with Twisted Conch involves a couple distinct phases (well, they're distinct if you squint). Basically, first you need to get a connection set up with a channel open on it with an sftp subsystem running on it. Whew. Then you can use the methods of a [FileTransferClient](http://twistedmatrix.... |
Closing files in Python | 5,196,724 | 4 | 2011-03-04T16:48:28Z | 5,196,917 | 10 | 2011-03-04T17:07:54Z | [
"python",
"file-io",
"garbage-collection",
"with-statement"
] | In [this discussion](http://stackoverflow.com/q/5195122/25507) about the easiest way to run a process and discard its output, I suggested the following code:
```
with open('/dev/null', 'w') as dev_null:
subprocess.call(['command'], stdout=dev_null, stderr=dev_null)
```
Another developer suggested this version:
`... | You are correct, refcouting is *not* guaranteed. In fact, only CPython (which is the main implementation, yes, but not even remotely the only one) provdies refcounting. In case CPython ever changes that implementation detail (unlikely, yes, but possible), or your code is ever run on an alternate implementation, or you ... |
Tests and python package structure | 5,197,333 | 7 | 2011-03-04T17:45:36Z | 5,203,183 | 10 | 2011-03-05T10:22:37Z | [
"python",
"package"
] | I have some problems in structuring my python project. Currently it is a bunch of files in the same folder. I have tried to structure it like
```
proj/
__init__.py
foo.py
...
bar/
__init__.py
foobar.py
...
tests/
foo_test.py
foobar_test.py
...
```
The problem is that I'm not able, fr... | When you use the `-m` switch to run code, the current directory is added to `sys.path`. So the easiest way to run your tests is from the parent directory of `proj`, using the command:
```
python -m proj.tests.foo_test
```
To make that work, you will need to include an `__init__.py` file in your tests directory so tha... |
Broadcasting a python function on to numpy arrays | 5,197,650 | 7 | 2011-03-04T18:17:57Z | 5,197,901 | 9 | 2011-03-04T18:40:54Z | [
"python",
"numpy",
"scipy",
"numerical-methods",
"numerical-integration"
] | Let's say we have a particularly simple function like
```
import scipy as sp
def func(x, y):
return x + y
```
This function evidently works for several builtin python datatypes of `x` and `y` like string, list, int, float, array, etc. Since we are particularly interested in arrays, we consider two arrays:
```
x =... | `np.vectorize` is a general way to convert Python functions that operate on numbers into numpy functions that operate on ndarrays.
However, as you point out, it isn't very fast, since it is using a Python loop "under the hood".
To achieve better speed, you have to hand-craft a function that expects numpy arrays as in... |
Broadcasting a python function on to numpy arrays | 5,197,650 | 7 | 2011-03-04T18:17:57Z | 5,204,065 | 8 | 2011-03-05T13:25:28Z | [
"python",
"numpy",
"scipy",
"numerical-methods",
"numerical-integration"
] | Let's say we have a particularly simple function like
```
import scipy as sp
def func(x, y):
return x + y
```
This function evidently works for several builtin python datatypes of `x` and `y` like string, list, int, float, array, etc. Since we are particularly interested in arrays, we consider two arrays:
```
x =... | For this special case, you could also write a function that operates on both, NumPy arrays and plain Python floats:
```
def func2d(x, y):
z = 2.0 * (x > y) - 1.0
z *= y
return x + z
```
This version is also more than four times as fast as [unutbu's `func2a()`](http://stackoverflow.com/questions/5197650/br... |
No module named index | 5,198,336 | 2 | 2011-03-04T19:27:50Z | 5,198,355 | 11 | 2011-03-04T19:29:56Z | [
"python",
"django"
] | I am getting the error
**Exception Value:No module named index**. i have `__init__.py` in DjangoPhoneBook and phonebook folder. I'm newbie to django and i m following the tutorial on djangoproject website. I have googled this error but not getting any solutions.
What is cause and solution to this problem??
```
Enviro... | Remove the `include` from your first line. `include` is the syntax for adding a separate url conf, so python is looking for a `module` called `index`.
Change it to the full python dot path to your view function.
```
urlpatterns = patterns('',
(r'^Book/$', 'path.to.my.views.index'), # <-- and add a comma here
... |
Python - How are signals different from pubsub? | 5,198,956 | 28 | 2011-03-04T20:33:45Z | 14,822,910 | 13 | 2013-02-11T23:30:32Z | [
"python",
"django",
"signals",
"flask",
"publish-subscribe"
] | Django and Flask make use of signals â the latter uses the [Blinker](http://discorporate.us/projects/Blinker/) library. In the context of Python, [Blinker](http://discorporate.us/projects/Blinker/) and the Python [pubsub](http://pubsub.sourceforge.net/) library, how do signals and pubsub compare? When would I use one... | [Blinker docs](http://discorporate.us/projects/Blinker/docs/1.1/) and [PubSub docs](http://pubsub.sourceforge.net/usage/usage_advanced_other.html#messaging-protocol).
As far as `Blinker` and `PubSub` go, they are the same thing. The difference is in how they go about it:
With `Blinker` when you subscribe to a signal ... |
replace empty string(s) in tuple | 5,200,154 | 4 | 2011-03-04T22:52:00Z | 5,200,182 | 14 | 2011-03-04T22:55:26Z | [
"python"
] | Is there an easy way (hopefully a one liner) to replace '' with something like '-'?
Many thanks.
```
tup = (1,2,'ABC','','','','text')
``` | How about the following?
```
tuple('-' if x == '' else x for x in tup)
```
As [Felix Kling](http://stackoverflow.com/users/218196/felix-kling) comments, [tuples are immutable](http://diveintopython.net/getting_to_know_python/tuples.html), so the best you can do is to return a new one. |
Strange behavior from HTTP authentication with suds SOAP library | 5,201,037 | 6 | 2011-03-05T01:33:20Z | 5,216,345 | 9 | 2011-03-07T05:57:00Z | [
"python",
"suds"
] | I have a working python program that is fetching a large volume of data via SOAP using suds. The web service is implemented with a paging function such that I can grab *nnn* rows with each fetch call and grab the next *nnn* with subsequent calls. If I authenticate to the HTTP server with code like the following
```
cl... | The problem seems to be that an `urllib2.HTTPError` is being raised from a lower level, and its `fp` attribute is None:
Line 81 in `suds.transport.http`:
```
except u2.HTTPError, e:
if e.code in (202,204):
result = None
else:
raise TransportError(e.msg, e.code, e.fp)
```
That exception eventu... |
py2app built app displays `ERROR: pygame.macosx import FAILED` on other machines | 5,201,133 | 4 | 2011-03-05T02:03:23Z | 5,207,675 | 13 | 2011-03-06T00:01:59Z | [
"python",
"osx",
"pygame",
"py2app"
] | Trying to build an app on the Mac using py2app. Got everything working fine on my machine, but when moving the app to another, it crashes and the console displays this error.
`ERROR: pygame.macosx import FAILED`
Anybody have a solution to this? | Found the problem and solution after many hours. Turns out other people have experienced similar problems and their articles were quite helpful:
<http://b.atcg.us/blog/2010/04/13/py2app-hell-the-first.html>
<http://www.vijayp.ca/blog/?p=62>
In case someone else runs into the issue, this particular problem was caused... |
Method to sort a list of lists? | 5,201,191 | 7 | 2011-03-05T02:19:32Z | 5,201,203 | 16 | 2011-03-05T02:22:22Z | [
"python",
"list",
"sorting"
] | I have a list of lists (can't be tuples since I have to generate it dynamically) and it is structured as o list of lists of one int and one float Like so:
```
[[1,1.0345],[2,5.098],[3,4.89],[2,5.97]]
```
I want to get it sorted but I have only managed to get the built in sorting function to sort it by the first eleme... | Pass the `key` argument.
```
L.sort(key=operator.itemgetter(1))
``` |
Method to sort a list of lists? | 5,201,191 | 7 | 2011-03-05T02:19:32Z | 5,201,211 | 8 | 2011-03-05T02:24:47Z | [
"python",
"list",
"sorting"
] | I have a list of lists (can't be tuples since I have to generate it dynamically) and it is structured as o list of lists of one int and one float Like so:
```
[[1,1.0345],[2,5.098],[3,4.89],[2,5.97]]
```
I want to get it sorted but I have only managed to get the built in sorting function to sort it by the first eleme... | ```
>>> l = [[1,1.0345],[2,5.098],[3,4.89],[2,5.97]]
>>> l.sort(key=lambda x: x[1])
>>> l
[[1, 1.0345], [3, 4.8899999999999997], [2, 5.0979999999999999], [2, 5.9699999999999998]]
``` |
How do I go straight to template, in Django's urls.py? | 5,201,346 | 51 | 2011-03-05T03:00:54Z | 5,201,357 | 166 | 2011-03-05T03:03:08Z | [
"python",
"django",
"templates"
] | Instead of going to views.py, I want it to go to to a template, robots.txt. | # Django 1.5+
Use the class based generic views:
```
from django.views.generic import TemplateView
urlpatterns = patterns('',
(r'^foo/$', TemplateView.as_view(template_name='foo.html')),
)
```
Docs: <https://docs.djangoproject.com/en/1.8/topics/class-based-views/#simple-usage-in-your-urlconf>
# Django <= 1.4
... |
wxPython StaticText Widget Font | 5,201,817 | 12 | 2011-03-05T05:05:38Z | 5,201,842 | 29 | 2011-03-05T05:13:33Z | [
"python",
"wxpython"
] | How do I set the font on a wxPython StaticText widget? | use object.SetFont. For example (from wxpython in Action):
```
text = wx.StaticText(panel, -1, 'my text', (20, 100))
font = wx.Font(18, wx.DECORATIVE, wx.ITALIC, wx.NORMAL)
text.SetFont(font)
```
wx.Font has the following signature:
```
wx.Font(pointSize, family, style, weight, underline=False, faceName="", encoding... |
Objective-C (cocoa) equivalent to python's endswith/beginswith | 5,201,965 | 33 | 2011-03-05T05:44:01Z | 5,202,000 | 7 | 2011-03-05T05:51:39Z | [
"python",
"objective-c",
"cocoa"
] | Python has `string.startswith()` and `string.endswith()` functions which are pretty useful.
What NSString methods can I use to have the same function? | You want the [`hasPrefix`](http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/hasPrefix%3a) and [`hasSuffix`](http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/... |
Objective-C (cocoa) equivalent to python's endswith/beginswith | 5,201,965 | 33 | 2011-03-05T05:44:01Z | 5,202,006 | 46 | 2011-03-05T05:52:28Z | [
"python",
"objective-c",
"cocoa"
] | Python has `string.startswith()` and `string.endswith()` functions which are pretty useful.
What NSString methods can I use to have the same function? | Use [`-hasPrefix:`](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/hasPrefix%3a) and [`-hasSuffix:`](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Ref... |
Javascript equivalent of Python's rsplit | 5,202,085 | 8 | 2011-03-05T06:14:12Z | 5,202,185 | 10 | 2011-03-05T06:40:00Z | [
"javascript",
"python",
"string",
"split"
] | > str.rsplit([sep[, maxsplit]])
>
> Return a
> list of the words in the string, using
> sep as the delimiter string. If
> maxsplit is given, at most maxsplit
> splits are done, the rightmost ones.
> If sep is not specified or None, any
> whitespace string is a separator.
> Except for splitting from the right,
> rsplit(... | ```
String.prototype.rsplit = function(sep, maxsplit) {
var split = this.split(sep);
return maxsplit ? [ split.slice(0, -maxsplit).join(sep) ].concat(split.slice(-maxsplit)) : split;
}
```
This one functions more closely to the Python version
"blah,derp,blah,beep".rsplit(",",1) // [ 'blah,derp,blah', 'beep' ] |
Python reverse() for palindromes | 5,202,533 | 5 | 2011-03-05T08:06:10Z | 5,202,555 | 14 | 2011-03-05T08:09:43Z | [
"python",
"reverse",
"palindrome"
] | I'm just getting started in python, and I'm trying to test a user-entered string as a palindrome. My code is:
```
x=input('Please insert a word')
y=reversed(x)
if x==y:
print('Is a palindrome')
else:
print('Is not a palindrome')
```
This always returns false because y becomes something like `<reversed object ... | Try `y = x[::-1]`. This uses splicing to get the reverse of the string.
`reversed(x)` returns an iterator for looping over the characters in the string in reverse order, *not* a string you can directly compare to `x`. |
Python reverse() for palindromes | 5,202,533 | 5 | 2011-03-05T08:06:10Z | 5,202,564 | 8 | 2011-03-05T08:12:17Z | [
"python",
"reverse",
"palindrome"
] | I'm just getting started in python, and I'm trying to test a user-entered string as a palindrome. My code is:
```
x=input('Please insert a word')
y=reversed(x)
if x==y:
print('Is a palindrome')
else:
print('Is not a palindrome')
```
This always returns false because y becomes something like `<reversed object ... | `reversed` returns an iterator, which you can make into a string using the `join` method:
```
y = ''.join(reversed(x))
``` |
Adding BOM (unicode signature) while saving file in python | 5,202,648 | 9 | 2011-03-05T08:31:18Z | 5,202,815 | 10 | 2011-03-05T09:11:51Z | [
"python"
] | How can I add BOM (unicode signature) while saving file in python:
```
file_old = open('old.txt', mode='r', encoding='utf-8')
file_new = open('new.txt', mode='w', encoding='utf-16-le')
file_new.write(file_old.read())
```
I need to convert file to `utf-16-le + BOM`. Now script is working great, except that there is no... | Write it directly at the beginning of the file:
```
file_new.write('\ufeff')
``` |
Adding BOM (unicode signature) while saving file in python | 5,202,648 | 9 | 2011-03-05T08:31:18Z | 5,725,315 | 24 | 2011-04-20T03:58:18Z | [
"python"
] | How can I add BOM (unicode signature) while saving file in python:
```
file_old = open('old.txt', mode='r', encoding='utf-8')
file_new = open('new.txt', mode='w', encoding='utf-16-le')
file_new.write(file_old.read())
```
I need to convert file to `utf-16-le + BOM`. Now script is working great, except that there is no... | It's better to use constants from 'codecs' module.
```
import codecs
f.write(codecs.BOM_UTF16_LE)
``` |
Adding BOM (unicode signature) while saving file in python | 5,202,648 | 9 | 2011-03-05T08:31:18Z | 5,726,295 | 14 | 2011-04-20T06:22:02Z | [
"python"
] | How can I add BOM (unicode signature) while saving file in python:
```
file_old = open('old.txt', mode='r', encoding='utf-8')
file_new = open('new.txt', mode='w', encoding='utf-16-le')
file_new.write(file_old.read())
```
I need to convert file to `utf-16-le + BOM`. Now script is working great, except that there is no... | Why do you think you need to specifically make it UTF16LE? Just use 'utf16' as the encoding, Python will write it in your endianness with the appropriate BOM, and all the consumer needs to be told is that the file is UTF-16 ... that's the whole point of having a BOM.
If the consumer is insisting that the file must be ... |
how to get the first element and the last element using django , Location.objects.all() | 5,202,726 | 6 | 2011-03-05T08:52:45Z | 5,202,948 | 14 | 2011-03-05T09:37:09Z | [
"python",
"django"
] | this is my code :
```
obj_list=Location.objects.all()
first_element=obj_list[0]
last_element=obj_list[-1]
```
then
```
return render_to_response(template_name, {
'first_element':first_element,
'last_element':last_element,
})
```
and in the view :
```
{{ first_element.terminal_id}} {{last_elemen... | Have a look at <http://docs.djangoproject.com/en/dev/topics/db/queries/#limiting-querysets>
> Negative indexing (i.e. `Entry.objects.all()[-1]`) is not supported.
Try:
```
first_element = Location.objects.all()[0]
last_element = Location.objects.all().reverse()[0]
``` |
Printing a utf-8 encoded string | 5,203,105 | 13 | 2011-03-05T10:08:32Z | 5,203,130 | 12 | 2011-03-05T10:13:42Z | [
"python",
"unicode",
"encoding"
] | I'm using BeautifulSoup to extract some text from an HTML but I just can't figure out how to print it properly to the screen (or to a file for that matter).
Here's how my class containing the text looks like:
```
class Thread(object):
def __init__(self, title, author, date, content = u""):
self.title = ti... | To output a Unicode string to a file (or the console) you need to choose a *text encoding*. In Python the default text encoding is ASCII, but to support Hebrew characters you need to use a different encoding, such as UTF-8:
```
s = unicode(your_object).encode('utf8')
f.write(s)
``` |
Problem concatenating Python list | 5,203,238 | 2 | 2011-03-05T10:32:04Z | 5,203,252 | 10 | 2011-03-05T10:34:25Z | [
"python",
"list",
"concatenation"
] | I am trying to concatenate two lists, one with just one element, by doing this:
```
print([6].append([1,1,0,0,0]))
```
However, Python returns `None`. What am I doing wrong? | Use the + operator
```
>>> [6] + [1,1,0,0,0]
[6, 1, 1, 0, 0, 0]
```
What you were attempting to do, is append a list onto another list, which would result in
```
>>> [6].append([1,1,0,0,0])
[6, [1,1,0,0,0]]
```
Why you are seeing `None` returned, is because `.append` is destructive, modifying the original list, and... |
unittest colored output | 5,203,633 | 30 | 2011-03-05T11:53:09Z | 5,203,777 | 12 | 2011-03-05T12:22:21Z | [
"python",
"unit-testing"
] | I use `unittest` (actually `unittest2`) for Python testing, together with [Python Mock](http://www.voidspace.org.uk/python/mock/index.html) for mocking objects and [nose](http://code.google.com/p/python-nose/) to run all tests in a single pass.
I miss being able to tell what is working and what's wrong at a glance fro... | In python 2.x you could try [pyrg](http://pypi.python.org/pypi/pyrg). Does not work in Python 3 though. |
unittest colored output | 5,203,633 | 30 | 2011-03-05T11:53:09Z | 11,313,556 | 15 | 2012-07-03T14:52:52Z | [
"python",
"unit-testing"
] | I use `unittest` (actually `unittest2`) for Python testing, together with [Python Mock](http://www.voidspace.org.uk/python/mock/index.html) for mocking objects and [nose](http://code.google.com/p/python-nose/) to run all tests in a single pass.
I miss being able to tell what is working and what's wrong at a glance fro... | I'm having good success with nosetests and [rednose](http://gfxmonk.net/dist/0install/rednose.xml). It's still maintained at the time of writing this. |
unittest colored output | 5,203,633 | 30 | 2011-03-05T11:53:09Z | 22,211,036 | 16 | 2014-03-05T22:45:27Z | [
"python",
"unit-testing"
] | I use `unittest` (actually `unittest2`) for Python testing, together with [Python Mock](http://www.voidspace.org.uk/python/mock/index.html) for mocking objects and [nose](http://code.google.com/p/python-nose/) to run all tests in a single pass.
I miss being able to tell what is working and what's wrong at a glance fro... | Using a method very similar to [robert's answer](http://stackoverflow.com/a/5205341/400691), I have (today!) released a package that enables colour output in `unittest` test results. I have called it [colour-runner](https://github.com/meshy/colour-runner/).
To install it, run:
```
pip install colour-runner
```
Then,... |
Compiling pyx files with dependencies in different packages | 5,204,906 | 8 | 2011-03-05T15:54:57Z | 5,206,299 | 7 | 2011-03-05T19:40:25Z | [
"python",
"cython"
] | I am having problems compiling cdef-ed types in different packages and I couldn't find an explanation in cython docs.
I have this setup.py in the root of my python src tree:
```
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
cmdclass = {'bu... | Oh, well, for those having a similar problem, it looks like maybe I found the answer.
I was expecting python to automatically scan the symbols compiled into the shared library FragIdx.so, instead it looks like this information must be provided explicitly as a .pxd file (which becomes a C header file after Cython is ru... |
Parsing Message-ID header returned by imaplib | 5,205,417 | 3 | 2011-03-05T17:21:24Z | 5,370,576 | 7 | 2011-03-20T18:40:26Z | [
"python",
"imaplib",
"email-headers"
] | I'm fetching the messageid from emails in Gmail via IMAP.
This code:
```
messageid = m.fetch(num, '(BODY[HEADER.FIELDS (MESSAGE-ID)])')
print messageid
```
returns this:
```
[('1 (BODY[HEADER.FIELDS (MESSAGE-ID)] {78}', 'Message-ID: <actualmessageid@mail.mail.gmail.com>\r\n\r\n'), ')']
```
How would I parse just t... | You can also achieve what you want using the [`email` module](http://docs.python.org/library/email.html)'s [`HeaderParser.parsestr()` function](http://docs.python.org/library/email.parser.html#parser-class-api) (*same API as Parser but doesn't worry about the email's body*) and the [`parseaddr()` function](http://docs.... |
How to write individual bits to a text file in python? | 5,205,487 | 5 | 2011-03-05T17:31:27Z | 5,206,585 | 8 | 2011-03-05T20:29:26Z | [
"python",
"file-io"
] | Suppose I have a number like 824 and I write it to a text file using python. In the text file, it will take 3 bytes space. However, If i represent it using bits, it has the following representation 0000001100111000 which is 2 bytes (16 bits). I was wondering how can I write bits to file in python, not bytes. If I can d... | The [struct](http://docs.python.org/library/struct.html?highlight=struct#module-struct) module is what you want. From your example, 824 = 0000001100111000 binary or 0338 hexadecimal. This is the two bytes 03H and 38H. [struct.pack](http://docs.python.org/library/struct.html?highlight=struct#struct.pack) will convert 82... |
How do I get a empty array of any size I want in python? | 5,205,575 | 29 | 2011-03-05T17:43:16Z | 5,205,580 | 61 | 2011-03-05T17:44:29Z | [
"python",
"arrays",
"dynamic-arrays"
] | I basically want a python equivalent of this in C
```
int a[x];
```
but in python I declare an array like
```
a = []
```
but the problem is I want to assign random slots with values like
```
a[4] = 1
```
but I can't do that with python, since the array is empty | If by "array" you actually mean a Python list, you can use
```
a = [0] * 10
```
or
```
a = [None] * 10
``` |
Why empty string is on every string? | 5,206,466 | 6 | 2011-03-05T20:08:03Z | 5,206,477 | 14 | 2011-03-05T20:09:19Z | [
"python",
"string"
] | For example:
```
>>> s = 'python'
>>> s.index('')
0
>>> s.index('p')
0
``` | This is because the substring of length 0 starting at index 0 in `'python'` is equal to the empty string:
```
>>> s[0:0]
''
```
Of course *every* substring of length zero of any string is equal to the empty string. |
Performance between Django and raw Python | 5,208,158 | 4 | 2011-03-06T02:06:16Z | 5,208,366 | 10 | 2011-03-06T03:00:11Z | [
"python",
"django"
] | I was wondering what the performance difference is between using plain python files to make web pages and using Django. I was just wondering if there was a significant difference between the two. Thanks | Django IS plain Python. So the execution time of each like statement or expression will be the same. What needs to be understood, is that many many components are put together to offer several advantages when developing for the web:
* Removal of common tasks into libraries (auth, data access, templating, routing)
* Co... |
zip(list1, list2) in Jinja2? | 5,208,252 | 13 | 2011-03-06T02:31:05Z | 5,223,810 | 22 | 2011-03-07T18:51:55Z | [
"python",
"code-generation",
"jinja2"
] | I'm doing code generation in Jinja2 and I frequently want to iterate through two lists together (i.e. variables names and types), is there a simple way to do this or do I need to just pass a pre-zipped list? I was unable to find such a function in the [docs](http://jinja.pocoo.org/docs/templates/) or googling. | Modify the jinja2.Environment [global namespace](http://jinja.pocoo.org/docs/api/#the-global-namespace) itself if you see fit.
```
import jinja2
env = jinja2.Environment()
env.globals.update(zip=zip)
# use env to load template(s)
```
This may be helpful in separating view (template) logic from application logic, but ... |
Python - seek in http response stream | 5,209,087 | 8 | 2011-03-06T06:24:37Z | 5,693,902 | 21 | 2011-04-17T13:52:55Z | [
"python",
"http"
] | Using `urllibs` (or `urllibs2`) and wanting what I want is hopeless.
Any solution? | I'm not sure how the C# implementation works, but, as internet streams are generally not seekable, my guess would be it downloads all the data to a local file or in-memory object and seeks within it from there. The Python equivalent of this would be to do as Abafei suggested and write the data to a file or StringIO and... |
Cant Get a result form random.shuffle in python | 5,209,745 | 4 | 2011-03-06T09:43:15Z | 5,209,759 | 10 | 2011-03-06T09:45:56Z | [
"python"
] | I have never had this problem before but when i try and shuffle a list i get a return of 'None'
```
import random
c=[1,4,67,3]
c=random.shuffle(c)
print c
```
The print statement returns 'None' and i dont know why, I have looked around for an answer to this problem but there doesent seem to be anything. I hope i am n... | The `random.shuffle` function sorts the list in-place, and to avoid causing confusion on that point, it doesn't return the shuffled list. Try just:
```
random.shuffle(c)
print(c)
```
This is a nice bit of API design, I think - it means that if you misunderstand what `random.shuffle` is doing, then you'll get a obvi... |
Python frameworks for developing facebook apps | 5,210,692 | 7 | 2011-03-06T13:13:01Z | 5,246,462 | 10 | 2011-03-09T13:26:56Z | [
"python",
"facebook"
] | I'd like to ask you about your experiences in developing facebook applications in Python. Which of the popular web frameworks for this language you think best suits this purpose? I know "best" is a very subjective word, so I'm specifically interested in the following:
* Most reusable libraries. For example one might w... | I would almost undoubtedly go with [Django](http://www.djangoproject.com/) as the easiest and most popular framework for developing any type of web applications, if there's a need for a full-stack framework.
Specifically, in regards to Django's app universe, it is plentiful with many active applications -- but that ha... |
Elegant way to make all dirs in a path | 5,210,778 | 9 | 2011-03-06T13:32:26Z | 5,210,790 | 19 | 2011-03-06T13:35:18Z | [
"python",
"path"
] | Here are four paths:
```
p1=r'\foo\bar\foobar.txt'
p2=r'\foo\bar\foo\foo\foobar.txt'
p3=r'\foo\bar\foo\foo2\foobar.txt'
p4=r'\foo2\bar\foo\foo\foobar.txt'
```
The directories may or may not exist on a drive. What would be the most elegant way to create the directories in each path?
I was thinking about using `os.pat... | You are looking for [`os.makedirs()`](http://docs.python.org/library/os.html#os.makedirs) which does exactly what you need.
The documentation states:
> Recursive directory creation function.
> Like mkdir(), but makes all
> intermediate-level directories needed
> to contain the leaf directory. Raises
> an error except... |
Python join a process without blocking parent | 5,210,866 | 13 | 2011-03-06T13:50:27Z | 5,210,951 | 10 | 2011-03-06T14:07:24Z | [
"python",
"multiprocessing"
] | I'm writing a program that will watch a particular directory for new files containing download URLs. Once a new file is detected, it will create a new process to do the actual download while the parent continues to watch the directory. I'm using the `Process` interface from `multiprocessing`. The problem I have is that... | You can set up a separate thread which does the joining. Have it listen on a [queue](http://docs.python.org/library/queue.html) into which you push the subprocess handles:
```
class Joiner(Thread):
def __init__(self, q):
self.__q = q
def run(self):
while True:
child = self.__q.get()... |
How to test twisted web resource with trial? | 5,210,889 | 9 | 2011-03-06T13:55:12Z | 5,211,416 | 10 | 2011-03-06T15:36:29Z | [
"python",
"twisted",
"trial"
] | I'm developing a twisted.web server - it consists of some resources that apart from rendering stuff use adbapi to fetch some data and write some data to postgresql database. I'm trying to figoure out how to write a trial unittest that would test resource rendering without using net (in other words: that would initializ... | Here's a function that will render a request and convert the result into a Deferred that fires when rendering is complete:
```
def _render(resource, request):
result = resource.render(request)
if isinstance(result, str):
request.write(result)
request.finish()
return succeed(None)
el... |
Normalizing colors in matplotlib | 5,211,174 | 5 | 2011-03-06T14:53:34Z | 12,479,942 | 18 | 2012-09-18T15:15:33Z | [
"python",
"matplotlib",
"geometry-surface"
] | I am trying to plot a surface using matplotlib using the code below:
```
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import axes3d, Axes3D
import pylab as p
vima=0.5
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(0, 16.67, vima)
Y = np.arange... | I realise that the poster's issue has already been resolved, but the question of normalizing the colors was never dealt with. Since I've figured out how I thought I'd just drop this here for anyone else who might need it.
First you create a norm and pass that to the plotting function, I've tried to add this to the OP'... |
Django manage.py syncdb doing nothing when used with sqlite3 | 5,211,340 | 4 | 2011-03-06T15:26:33Z | 5,212,797 | 10 | 2011-03-06T19:19:54Z | [
"python",
"django",
"sqlite",
"sqlite3"
] | I'm not sure if this is an issue specific to sqlite databases but after adding some properties I executed syncdb successfully but still the the columns were not added to the database and when I try the access the model in admin I get `no such column` error.
Why is this happening and how do I overcome this issue?
Deta... | sync db doesn't make integrate schema changes once the tables are created. You have to delete the database manually and do syncdb again. See the boxed information in this link
<http://docs.djangoproject.com/en/dev/ref/django-admin/#syncdb> |
Store jpg, gif, png, etc it gae-datastore | 5,211,780 | 2 | 2011-03-06T16:33:08Z | 5,212,207 | 7 | 2011-03-06T17:44:16Z | [
"python",
"image",
"google-app-engine",
"file-upload"
] | I found an [example](http://code.google.com/p/google-app-engine-samples/source/browse/trunk/image_sharing/image_sharing.py) on how to store png in datastore:
```
img = images.Image(img_data)
# Basically, we just want to make sure it's a PNG
# since we don't have a good way to determine image type
# through the... | ## The quick answer
You can store binary data of any file type by using `db.BlobProperty()` in your model.
If you use the `Image` API to manipulate the image data, you're limited to inputting `.jpg`, `.png`, `.gif`, `.bmp`, `.tiff`, and `.ico` types, and outputting to either `.jpg` or `.png`.
---
## Storing images
... |
python class design (staticmethod vs method) | 5,212,071 | 7 | 2011-03-06T17:21:30Z | 5,212,190 | 7 | 2011-03-06T17:41:00Z | [
"python",
"design",
"static-methods",
"oop"
] | What's the nicer way for methods that don't need any passed information (object instance or class) because for example they just do a simple conversion. **@staticmethod** or **method** ?
```
class Foo(object):
def __init__(self, trees):
self.money = Foo.trees2money(trees)
@staticmethod
def trees2m... | The choice of the type of method depends on other factors.
You have two cases. The first case is when the method has to be part of the class interface - e.g. it has to be called by users, or it has to be overridable in subclasses, or it uses the information in self, or it's likely that in a future version of the softw... |
Sorting a Python list by two criteria | 5,212,870 | 67 | 2011-03-06T19:36:08Z | 5,212,885 | 74 | 2011-03-06T19:38:25Z | [
"python",
"sorting"
] | I have the following list created from a sorted csv
```
list1 = sorted(csv1, key=operator.itemgetter(1))
```
I would actually like to sort the list by two criteria: first by the value in field 1 and then by the value in field 2. How do I do this? | like this:
```
import operator
list1 = sorted(csv1, key=operator.itemgetter(1, 2))
``` |
Sorting a Python list by two criteria | 5,212,870 | 67 | 2011-03-06T19:36:08Z | 5,212,940 | 12 | 2011-03-06T19:49:41Z | [
"python",
"sorting"
] | I have the following list created from a sorted csv
```
list1 = sorted(csv1, key=operator.itemgetter(1))
```
I would actually like to sort the list by two criteria: first by the value in field 1 and then by the value in field 2. How do I do this? | Python has a stable sort, so provided that performance isn't an issue the simplest way is to sort it by field 2 and then sort it again by field 1.
That will give you the result you want, the only catch is that if it is a big list (or you want to sort it often) calling sort twice might be an unacceptable overhead.
```... |
Sorting a Python list by two criteria | 5,212,870 | 67 | 2011-03-06T19:36:08Z | 17,109,098 | 122 | 2013-06-14T13:01:30Z | [
"python",
"sorting"
] | I have the following list created from a sorted csv
```
list1 = sorted(csv1, key=operator.itemgetter(1))
```
I would actually like to sort the list by two criteria: first by the value in field 1 and then by the value in field 2. How do I do this? | Replying to this dead thread for archive.
No need to import anything when using lambda functions.
The following sorts `list` by the first element, then by the second element.
```
sorted(list, key=lambda x: (x[0], -x[1]))
``` |
Sort list of list with custom compare function in Python | 5,213,033 | 23 | 2011-03-06T20:05:38Z | 5,213,093 | 14 | 2011-03-06T20:16:35Z | [
"python",
"list",
"sorting",
"callback"
] | I know there are several questions named like this, but I can't seems to get their answers to work.
I have a list of lists, 50 times 5 elements. Now I want to sort this list by applying a custom compare function to each element. This function calculates the fitness of the list by which the elements shall be sorted. I ... | ```
>>> l = [list(range(i, i+4)) for i in range(10,1,-1)]
>>> l
[[10, 11, 12, 13], [9, 10, 11, 12], [8, 9, 10, 11], [7, 8, 9, 10], [6, 7, 8, 9], [5, 6, 7, 8], [4, 5, 6, 7], [3, 4, 5, 6], [2, 3, 4, 5]]
>>> sorted(l, key=sum)
[[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9], [7, 8, 9, 10], [8, 9, 10,... |
Sort list of list with custom compare function in Python | 5,213,033 | 23 | 2011-03-06T20:05:38Z | 13,239,857 | 38 | 2012-11-05T20:27:54Z | [
"python",
"list",
"sorting",
"callback"
] | I know there are several questions named like this, but I can't seems to get their answers to work.
I have a list of lists, 50 times 5 elements. Now I want to sort this list by applying a custom compare function to each element. This function calculates the fitness of the list by which the elements shall be sorted. I ... | Also, your compare function is incorrect. It needs to return -1, 0, or 1, not a boolean as you have it. The correct compare function would be:
```
def compare(item1, item2):
if fitness(item1) < fitness(item2):
return -1
elif fitness(item1) > fitness(item2):
return 1
else:
return 0
`... |
Converting a string that represents a list, into an actual list object | 5,214,344 | 3 | 2011-03-06T23:48:11Z | 5,214,353 | 12 | 2011-03-06T23:49:49Z | [
"python",
"string",
"list",
"type-conversion"
] | I have a string that represents a list:
```
"[22, 33, 36, 41, 46, 49, 56, 72, 85, 92, 95, 98, 107, 118, 120, 123, 124, 126, 127, 130, 149, 157, 161, 171, 174, 177, 187, 195, 225, 302, 316, 359, 360, 363, 396, 479, 486, 491]"
```
I would like to turn that litteral string into an actual list. I suppose to could regex o... | Use [ast.literal\_eval](http://docs.python.org/library/ast.html#ast.literal_eval).
```
>>> import ast
>>> i = ast.literal_eval('[22, 33, 36, 41, 46, 49, 56]')
>>> i[3]
41
``` |
Python vs Matlab | 5,214,369 | 20 | 2011-03-06T23:52:56Z | 5,214,460 | 13 | 2011-03-07T00:08:29Z | [
"python",
"matlab",
"ide"
] | I'm considering making the switch from Matlab to Python. The application is quantitative trading and cost is not really an issue. There are a few things I love about Matlab and am wondering how Python stacks up (could not find any answers in the reviews I've read).
1) Is there an IDE for Python that is as good as Matl... | IDE: No. Python IDEs are nowhere near as good or mature as Matlab's, though I've heard good things about Wing IDE. Generally, I find IDEs to be total overkill for Python development, and find that I'm more productive with a well-setup text editor (vim in my case) and a separate visual debugger (WinPDB).
Changing funct... |
Python vs Matlab | 5,214,369 | 20 | 2011-03-06T23:52:56Z | 6,088,759 | 10 | 2011-05-22T15:03:40Z | [
"python",
"matlab",
"ide"
] | I'm considering making the switch from Matlab to Python. The application is quantitative trading and cost is not really an issue. There are a few things I love about Matlab and am wondering how Python stacks up (could not find any answers in the reviews I've read).
1) Is there an IDE for Python that is as good as Matl... | I've been getting on very well with the Spyder IDE in the Python(x,y) distribution. I'm a long term user of Matlab and have known of the existence of Python for 10 years or so but it's only since I installed Python(x,y) that I've started using Python regularly. |
Python Print String To Text File | 5,214,578 | 214 | 2011-03-07T00:31:57Z | 5,214,587 | 406 | 2011-03-07T00:34:38Z | [
"python",
"string",
"text",
"file-io"
] | I'm using Python to open a text document:
```
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: " 'TotalAmount')
text_file.close()
```
I want to enter the string called "TotalAmount" into the text document. Can someone please let me know how to do this? | ```
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()
```
If you use a context manager, the file is closed automatically for you
```
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s" % TotalAmount)
```
If you're using Python2... |
Python Print String To Text File | 5,214,578 | 214 | 2011-03-07T00:31:57Z | 27,708,256 | 11 | 2014-12-30T15:36:36Z | [
"python",
"string",
"text",
"file-io"
] | I'm using Python to open a text document:
```
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: " 'TotalAmount')
text_file.close()
```
I want to enter the string called "TotalAmount" into the text document. Can someone please let me know how to do this? | In case you want to pass multiple arguments you can use a tuple
```
price = 33.3
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price))
```
More: [Print multiple arguments in python](http://stackoverflow.com/questions/15286401/print-multiple-arguments-in-... |
Python - Add Date Stamp To Text File | 5,214,866 | 9 | 2011-03-07T01:28:23Z | 5,215,012 | 18 | 2011-03-07T01:53:08Z | [
"python",
"datetime",
"text"
] | In Python v2, is there a way to get a date/time stamp and put it into creating a new text file?
IE: When I want to create a new text file and write the contents of my program to it, it will create a new text file with the time/date in it.
Thanks for any help. | ```
import datetime
def timeStamped(fname, fmt='%Y-%m-%d-%H-%M-%S_{fname}'):
return datetime.datetime.now().strftime(fmt).format(fname=fname)
with open(timeStamped('myfile.txt'),'w') as outf:
outf.write('data!')
``` |
Redirecting django manage.py output (in windows) to a text file | 5,215,106 | 5 | 2011-03-07T02:09:19Z | 5,215,188 | 16 | 2011-03-07T02:26:09Z | [
"python",
"windows",
"django",
"command-line",
"stdout"
] | I'm trying to redirect the output from manage.py to a text file, but only some output is getting redirected to the text file. How do I redirect all output to the text file?
My command prompt:
```
C:\Development\web-py\p1st2\pianos1st-system>python manage.py test > test_results.txt
....................................... | Certain types of console messages will bypass the output redirection (or whatever using ">" is called). I noticed that sys.stderr.write() for instance did this.
Adding a "2>&1" at the end helps with this:
```
python manage.py test purchaseplans > test_results.txt 2>&1
```
Edit: Explanation of what is going on:
<ht... |
in python for loop,, jump over values | 5,215,530 | 5 | 2011-03-07T03:29:12Z | 5,215,551 | 17 | 2011-03-07T03:32:59Z | [
"python",
"for-loop",
"range"
] | ```
time=0
gold=0
level=1
for time in range(100):
gold+=level
if gold>20*level:
level+=1
time+=10
```
with this program gold is added until it reaches a critical amount, then it takes 20s to upgrade a mine so it produces more gold. i'd like to skip those 20s (or 20 steps) in the loop? this works in c++, i'... | Don't do it in `range(100)`. The `for` loop doesn't offer a way to skip ahead like that; `time` will be set to the next value in the list regardless of what you change it to in the body of the loop. Use a `while` loop instead, e.g.
```
time = 0
while time < 100:
gold += level
if gold > 20 * level:
level +=... |
How to create list field in django | 5,216,162 | 27 | 2011-03-07T05:26:08Z | 7,394,475 | 34 | 2011-09-12T21:49:48Z | [
"python",
"django",
"google-app-engine"
] | How do I create a ListField in Django (Python) like the [ListProperty](https://developers.google.com/appengine/docs/python/datastore/typesandpropertyclasses#ListProperty) property in Google App Engine (Python)? My data is a list like this : `3,4,5,6,7,8`.
What property do I have to define and how would I fetch values ... | Revisiting this with a `ListField` type you can use. But it makes a few of assumptions, such as the fact that you're not storing complex types in your list. For this reason I used `ast.literal_eval()` to enforce that only simple, built-in types can be stored as members in a `ListField`:
```
from django.db import model... |
Python - slice array until certain condition is met | 5,216,260 | 5 | 2011-03-07T05:42:10Z | 5,216,612 | 7 | 2011-03-07T06:38:11Z | [
"python",
"arrays",
"numpy",
"slice"
] | I need to slice an array from a given index until a certain condition is met.
```
>>> a = numpy.zeros((10), dtype='|S1')
>>> a[2] = 'A'
>>> a[4] = 'X'
>>> a[8] = 'B'
>>> a
array(['', '', 'A', '', 'X', '', '', '', 'B', ''], dtype='|S1')
```
For instance, for the above array I want a subset from a given index until fir... | If you set up your problem like this:
```
import numpy
a = numpy.zeros((10), dtype=str)
a[2] = 'A'
a[4] = 'X'
a[8] = 'B'
```
You can easily get the indices of non-empty strings like so:
```
i = numpy.where(a!='')[0] # array([2, 4, 8])
```
Alternatively, `numpy.argwhere(..)` also works well.
Then you can slice awa... |
How to reassemble TCP packets in Python? | 5,216,332 | 4 | 2011-03-07T05:53:53Z | 5,446,713 | 10 | 2011-03-27T01:54:35Z | [
"python",
"tcp",
"packet"
] | How to reassemble TCP packets in Python? Is there any existing tools for this?
Thanks! :-) | To do perform TCP reassembly you'll need to use something like pynids <http://jon.oberheide.org/pynids/>.
You can also build your own using pylibpcap, dpkt or scapy.
TCP reassembly is very tricky with a LOT of edge cases. I wouldn't recommend doing it yourself if you need a robust solution. |
Django: what is the difference (rel & field) | 5,216,891 | 29 | 2011-03-07T07:17:24Z | 13,583,807 | 30 | 2012-11-27T11:59:56Z | [
"python",
"django",
"entity-relationship"
] | What is the difference between Django's `models.ManyToManyField` and `models.ManyToManyRel`? I'm confused about this stuff. | ManyToManyRel is used by the ManyToManyField to implement the relationship object for the Field base class which it extends. If you were to create a new field class that extended the Field class and contained a many-to-many relationship you might find this class convenient but it should not be used in your models (whic... |
Reformat a Python file to have 4 space indentations | 5,217,058 | 19 | 2011-03-07T07:38:04Z | 5,217,130 | 12 | 2011-03-07T07:48:00Z | [
"python",
"vim"
] | I'm editing a Python file that uses two spaces for programmatic indents - I prefer 4 spaces. In my .vimrc I have the following settings related to indentation:
```
set tabstop=4 "Indentation levels every four columns
set expandtab "Convert all tabs typed to spaces
set shiftwidth... | Pressing `gg=G` is the command to re-indent everything in a file. If you have other elements that can be re-indented, vim will indent these as well, which doesn't always give the desired effects. You'll have to clean these up manually if they're ugly.
Alternately, you can use the `>` command to indent, with ranges to ... |
Reformat a Python file to have 4 space indentations | 5,217,058 | 19 | 2011-03-07T07:38:04Z | 5,217,702 | 41 | 2011-03-07T09:02:39Z | [
"python",
"vim"
] | I'm editing a Python file that uses two spaces for programmatic indents - I prefer 4 spaces. In my .vimrc I have the following settings related to indentation:
```
set tabstop=4 "Indentation levels every four columns
set expandtab "Convert all tabs typed to spaces
set shiftwidth... | In order to double the number of spaces at the beginning of every line (and only at the beginning):
```
:%s/^\s*/&&/g
```
`&` in replacement pattern is the matched pattern.
Probably it will not have any side-effect for you. |
How do I convert kilometres to degrees in Geodjango/GEOS? | 5,217,348 | 10 | 2011-03-07T08:18:38Z | 5,217,427 | 9 | 2011-03-07T08:29:08Z | [
"python",
"django",
"gis",
"geodjango"
] | I'm using the "buffer" method from the GEOS API to create a circle based on a point and a radius in GeoDjango, according to this answer: [GeoDjango: How to create a circle based on point and radius](http://stackoverflow.com/questions/4985222/geodjango-how-to-create-a-circle-based-on-point-and-radius)
As one commenter ... | The answer may depend upon location on earth. Near the equator, 1km is going to equal roughly 0.008 degrees (1 km / 40,000 km \* 360 degrees) of latitude and longitude, but near the poles, 1km is going to equal roughly 0.008 degrees latitude, but could be many many degrees longitude. (If you're 1km away from the pole, ... |
Check if a predicate evaluates true for all elements in an iterable in python | 5,217,489 | 26 | 2011-03-07T08:36:21Z | 5,217,518 | 45 | 2011-03-07T08:41:16Z | [
"python"
] | pretty sure there is a common idiom but couldn't find it with google..
Here is what I want to do (in java):
```
// Applies the predicate to all elements of the iterable, and returns
// true if all evaluated to true, otherwise false
boolean allTrue = Iterables.all(someIterable, somePredicate);
```
How is this done "... | Do you mean something like:
```
allTrue = all(somePredicate(elem) for elem in someIterable)
anyTrue = any(somePredicate(elem) for elem in someIterable)
``` |
How do I perform binary search on a text file to search a keyword in python? | 5,217,650 | 7 | 2011-03-07T08:56:21Z | 5,219,275 | 9 | 2011-03-07T11:43:47Z | [
"python",
"search",
"binary",
"text-files"
] | The text file contains two columns- index number(5 spaces) and characters(30 spaces).
It is arranged in lexicographic order. I want to perform binary search to search for the keyword. | Here's an interesting way to do it with Python's built-in bisect module.
```
import bisect
import os
class Query(object):
def __init__(self, query, index=5):
self.query = query
self.index = index
def __lt__(self, comparable):
return self.query < comparable[self.index:]
class FileS... |
using inet_ntoa function in Python | 5,217,732 | 5 | 2011-03-07T09:05:17Z | 5,217,780 | 11 | 2011-03-07T09:10:48Z | [
"python"
] | I've recently started to program in python and I'm having some trouble understanding how `inet_nota` and `inet_aton` work in Python. Coming from php/mysql I've always stored ip addresses in the database as long variables. Also the `inet_ntoa` method in mysql receives a long variable as parameter and returns the dotted ... | In Python 3.3+ (or with [this backport](http://pypi.python.org/pypi/ipaddress) for 2.6 and 2.7), you can simply use [`ipaddress`](http://docs.python.org/3/library/ipaddress):
```
import ipaddress
addr = str(ipaddress.ip_address(167772160))
assert addr == '10.0.0.0'
```
Alternatively, you can manually pack the value
... |
Python - How To Rename A Text File With DateTime | 5,218,261 | 3 | 2011-03-07T10:03:35Z | 5,218,322 | 8 | 2011-03-07T10:09:50Z | [
"python",
"datetime"
] | I'm using Python v2.x and am wondering how I can rename a known text file, for my example say "text.txt", to include the current date and time.
Any help would be greatly appreciated. | To get the current datetime use:
```
import datetime
dt = str(datetime.datetime.now())
```
Then to rename file:
```
import os
newname = 'file_'+dt+'.txt'
os.rename('text.txt', newname)
``` |
Python - How To Rename A Text File With DateTime | 5,218,261 | 3 | 2011-03-07T10:03:35Z | 5,218,328 | 22 | 2011-03-07T10:10:20Z | [
"python",
"datetime"
] | I'm using Python v2.x and am wondering how I can rename a known text file, for my example say "text.txt", to include the current date and time.
Any help would be greatly appreciated. | `os.rename("text.txt", time.strftime("%Y%m%d%H%M%S.txt"))`. Note that you have to `import` `os` and `time`.
Have a look over [here](http://docs.python.org/library/time.html#time.strftime) for time stuff and over [here](http://docs.python.org/library/os.html#os.rename) for renaming files. |
Python nested functions variable scoping | 5,218,895 | 43 | 2011-03-07T11:05:45Z | 5,219,055 | 31 | 2011-03-07T11:22:34Z | [
"python",
"variables",
"scope"
] | I've read almost all the other questions about the topic, but my code still doesn't work.
I think I'm missing something about python variable scope.
Here is my code:
```
PRICE_RANGES = {
64:(25, 0.35),
32:(13, 0.40),
16:(7, 0.45),
8:(4, 0.5)
... | When I run your code I get this error:
```
UnboundLocalError: local variable '_total' referenced before assignment
```
This problem is caused by this line:
```
_total += PRICE_RANGES[key][0]
```
[The documentation about Scopes and Namespaces](http://docs.python.org/tutorial/classes.html#python-scopes-and-namespaces... |
Python nested functions variable scoping | 5,218,895 | 43 | 2011-03-07T11:05:45Z | 8,178,808 | 49 | 2011-11-18T06:54:17Z | [
"python",
"variables",
"scope"
] | I've read almost all the other questions about the topic, but my code still doesn't work.
I think I'm missing something about python variable scope.
Here is my code:
```
PRICE_RANGES = {
64:(25, 0.35),
32:(13, 0.40),
16:(7, 0.45),
8:(4, 0.5)
... | In Python 3, you can use the [`nonlocal` statement](http://docs.python.org/py3k/reference/simple_stmts.html#the-nonlocal-statement) to access non-local, non-global scopes. |
Python nested functions variable scoping | 5,218,895 | 43 | 2011-03-07T11:05:45Z | 13,277,359 | 63 | 2012-11-07T20:08:02Z | [
"python",
"variables",
"scope"
] | I've read almost all the other questions about the topic, but my code still doesn't work.
I think I'm missing something about python variable scope.
Here is my code:
```
PRICE_RANGES = {
64:(25, 0.35),
32:(13, 0.40),
16:(7, 0.45),
8:(4, 0.5)
... | Here's an illustration that gets to the essence of David's answer.
```
def outer():
a = 0
b = 1
def inner():
print a
print b
#b = 4
inner()
outer()
```
With the statement `b = 4` commented out, this code outputs `0 1`, just what you'd expect.
But if you uncomment that line,... |
Python nested functions variable scoping | 5,218,895 | 43 | 2011-03-07T11:05:45Z | 13,283,581 | 7 | 2012-11-08T06:18:45Z | [
"python",
"variables",
"scope"
] | I've read almost all the other questions about the topic, but my code still doesn't work.
I think I'm missing something about python variable scope.
Here is my code:
```
PRICE_RANGES = {
64:(25, 0.35),
32:(13, 0.40),
16:(7, 0.45),
8:(4, 0.5)
... | You probably have gotten the answer to your question. But i wanted to indicate a way i ussually get around this and that is by using lists. For instance, if i want to do this:
```
X=0
While X<20:
Do something. ..
X+=1
```
I would instead do this:
```
X=[0]
While X<20:
Do something....
X[0]+=1
```
This... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.