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 |
|---|---|---|---|---|---|---|---|---|---|
numpy convert categorical string arrays to an integer array | 3,172,509 | 9 | 2010-07-03T18:53:54Z | 32,337,581 | 9 | 2015-09-01T17:27:10Z | [
"python",
"statistics",
"numpy",
"machine-learning"
] | I'm trying to convert a string array of categorical variables to an integer array of categorical variables.
Ex.
```
import numpy as np
a = np.array( ['a', 'b', 'c', 'a', 'b', 'c'])
print a.dtype
>>> |S1
b = np.unique(a)
print b
>>> ['a' 'b' 'c']
c = a.desired_function(b)
print c, c.dtype
>>> [1,2,3,1,2,3] int32
``... | ... years later....
For completeness (because this isn't mentioned in the answers) and personal reasons (I *always* have `pandas` imported in my modules but not necessarily `sklearn`), this is also quite straightforward with `pandas.get_dummies()`
```
import numpy as np
import pandas
In [1]: a = np.array(['a', 'b', ... |
OperationalError: database is locked | 3,172,929 | 18 | 2010-07-03T21:26:42Z | 3,172,950 | 33 | 2010-07-03T21:33:56Z | [
"python",
"django",
"database",
"sqlite3",
"locked"
] | I have made some repetitive operations in my application (testing it), and suddenly Iâm getting a weird error:
```
OperationalError: database is locked
```
I've restarted the server, but the error persists. What can it be all about? | From django doc:
> SQLite is meant to be a lightweight
> database, and thus can't support a
> high level of concurrency.
> OperationalError: database is locked
> errors indicate that your application
> is experiencing more concurrency than
> sqlite can handle in default
> configuration. This error means that
> one thr... |
OperationalError: database is locked | 3,172,929 | 18 | 2010-07-03T21:26:42Z | 19,517,097 | 9 | 2013-10-22T11:52:38Z | [
"python",
"django",
"database",
"sqlite3",
"locked"
] | I have made some repetitive operations in my application (testing it), and suddenly Iâm getting a weird error:
```
OperationalError: database is locked
```
I've restarted the server, but the error persists. What can it be all about? | The practical reason for this is often that the python or django shells have opened a request to the DB and it wasn't closed properly; killing your terminal access often frees it up. I had this error on running command line tests today. |
Move an item inside a list? | 3,173,154 | 33 | 2010-07-03T23:14:15Z | 3,173,159 | 66 | 2010-07-03T23:15:44Z | [
"python",
"list"
] | In Python, how do I move an item to a definite index in a list? | Use the `insert` method of a list:
```
l = list(...)
l.insert(index, item)
```
Alternatively, you can use a slice notation:
```
l[index:index] = [item]
```
If you want to move an item that's already in the list to the specified position, you would have to delete it and insert it at the new position:
```
l.insert(n... |
Move an item inside a list? | 3,173,154 | 33 | 2010-07-03T23:14:15Z | 29,864,691 | 11 | 2015-04-25T11:43:32Z | [
"python",
"list"
] | In Python, how do I move an item to a definite index in a list? | A slightly shorter solution, that only moves the item to the end, not anywhere is this:
```
l += [l.pop(0)]
```
For example:
```
>>> l = [1,2,3,4,5]
>>> l += [l.pop(0)]
>>> l
[2, 3, 4, 5, 1]
``` |
Text Progress Bar in the Console | 3,173,320 | 165 | 2010-07-04T00:29:08Z | 3,173,331 | 70 | 2010-07-04T00:35:48Z | [
"python",
"console",
"progress",
"updating"
] | Is there a good way to do the following?
I wrote a simple console app to upload and download files from an FTP server using the ftplib.
Each time some data chunks are downloaded, I want to update a text progress bar, even if it's just a number.
But I don't want to erase all the text that's been printed to the consol... | Write a `\r` to the console. That is a ["carriage return"](http://en.wikipedia.org/wiki/Carriage_return) which causes all text after it to be echoed at the beginning of the line. Something like:
```
def update_progress(progress):
print '\r[{0}] {1}%'.format('#'*(progress/10), progress)
```
which will give you som... |
Text Progress Bar in the Console | 3,173,320 | 165 | 2010-07-04T00:29:08Z | 3,173,337 | 10 | 2010-07-04T00:39:07Z | [
"python",
"console",
"progress",
"updating"
] | Is there a good way to do the following?
I wrote a simple console app to upload and download files from an FTP server using the ftplib.
Each time some data chunks are downloaded, I want to update a text progress bar, even if it's just a number.
But I don't want to erase all the text that's been printed to the consol... | ~~Here's a nice example of a progressbar written in Python: <http://nadiana.com/animated-terminal-progress-bar-in-python>~~
But if you want to write it yourself. You could use the `curses` module to make things easier :)
[edit]
Perhaps easier is not the word for curses. But if you want to create a full-blown cui than... |
Text Progress Bar in the Console | 3,173,320 | 165 | 2010-07-04T00:29:08Z | 3,173,338 | 216 | 2010-07-04T00:39:34Z | [
"python",
"console",
"progress",
"updating"
] | Is there a good way to do the following?
I wrote a simple console app to upload and download files from an FTP server using the ftplib.
Each time some data chunks are downloaded, I want to update a text progress bar, even if it's just a number.
But I don't want to erase all the text that's been printed to the consol... | Writing '\r' will move the cursor back to the beginning of the line.
This displays a percentage counter:
```
import time
import sys
for i in range(100):
time.sleep(1)
sys.stdout.write("\r%d%%" % i)
sys.stdout.flush()
``` |
Text Progress Bar in the Console | 3,173,320 | 165 | 2010-07-04T00:29:08Z | 3,175,616 | 7 | 2010-07-04T17:50:46Z | [
"python",
"console",
"progress",
"updating"
] | Is there a good way to do the following?
I wrote a simple console app to upload and download files from an FTP server using the ftplib.
Each time some data chunks are downloaded, I want to update a text progress bar, even if it's just a number.
But I don't want to erase all the text that's been printed to the consol... | Run this *at the Python command line* (**not** in any IDE or development environment):
```
>>> import threading
>>> for i in range(50+1):
... threading._sleep(0.5)
... print "\r%3d" % i, ('='*i)+('-'*(50-i)),
```
Works fine on my Windows system. |
Text Progress Bar in the Console | 3,173,320 | 165 | 2010-07-04T00:29:08Z | 8,880,013 | 17 | 2012-01-16T12:25:12Z | [
"python",
"console",
"progress",
"updating"
] | Is there a good way to do the following?
I wrote a simple console app to upload and download files from an FTP server using the ftplib.
Each time some data chunks are downloaded, I want to update a text progress bar, even if it's just a number.
But I don't want to erase all the text that's been printed to the consol... | Check this library: [clint](https://github.com/kennethreitz/clint)
it has a lot of features including a progress bar:
```
from time import sleep
from random import random
from clint.textui import progress
if __name__ == '__main__':
for i in progress.bar(range(100)):
sleep(random() * 0.2)
for i ... |
Text Progress Bar in the Console | 3,173,320 | 165 | 2010-07-04T00:29:08Z | 13,685,020 | 28 | 2012-12-03T14:11:23Z | [
"python",
"console",
"progress",
"updating"
] | Is there a good way to do the following?
I wrote a simple console app to upload and download files from an FTP server using the ftplib.
Each time some data chunks are downloaded, I want to update a text progress bar, even if it's just a number.
But I don't want to erase all the text that's been printed to the consol... | I realize I'm late to the game, but here's a slightly Yum-style (Red Hat) one I wrote (not going for 100% accuracy here, but if you're using a progress bar for that level of accuracy, then you're WRONG anyway):
```
import sys
def cli_progress_test(end_val, bar_length=20):
for i in xrange(0, end_val):
perc... |
Text Progress Bar in the Console | 3,173,320 | 165 | 2010-07-04T00:29:08Z | 26,394,657 | 50 | 2014-10-16T01:08:03Z | [
"python",
"console",
"progress",
"updating"
] | Is there a good way to do the following?
I wrote a simple console app to upload and download files from an FTP server using the ftplib.
Each time some data chunks are downloaded, I want to update a text progress bar, even if it's just a number.
But I don't want to erase all the text that's been printed to the consol... | [tqdm: add a progress meter to your loops in a second](https://github.com/tqdm/tqdm):
```
>>> import time
>>> from tqdm import tqdm
>>> for i in tqdm(range(100)):
... time.sleep(1)
...
|###-------| 35/100 35% [elapsed: 00:35 left: 01:05, 1.00 iters/sec]
``` |
Text Progress Bar in the Console | 3,173,320 | 165 | 2010-07-04T00:29:08Z | 27,871,113 | 32 | 2015-01-09T23:45:03Z | [
"python",
"console",
"progress",
"updating"
] | Is there a good way to do the following?
I wrote a simple console app to upload and download files from an FTP server using the ftplib.
Each time some data chunks are downloaded, I want to update a text progress bar, even if it's just a number.
But I don't want to erase all the text that's been printed to the consol... | It is lesser than 10 lines of code.
The gist here: <https://gist.github.com/vladignatyev/06860ec2040cb497f0f3>
I was told to add GPL v.2 compatible license to this snippet, so I added MIT license attribution.
```
import sys
def progress(count, total, suffix=''):
bar_len = 60
filled_len = int(round(bar_len ... |
Text Progress Bar in the Console | 3,173,320 | 165 | 2010-07-04T00:29:08Z | 29,772,149 | 7 | 2015-04-21T12:24:04Z | [
"python",
"console",
"progress",
"updating"
] | Is there a good way to do the following?
I wrote a simple console app to upload and download files from an FTP server using the ftplib.
Each time some data chunks are downloaded, I want to update a text progress bar, even if it's just a number.
But I don't want to erase all the text that's been printed to the consol... | ```
import time,sys
for i in range(100+1):
time.sleep(0.1)
sys.stdout.write(('='*i)+(''*(100-i))+("\r [ %d"%i+"% ] "))
sys.stdout.flush()
```
output
[ 29% ] =================== |
Text Progress Bar in the Console | 3,173,320 | 165 | 2010-07-04T00:29:08Z | 30,740,258 | 24 | 2015-06-09T18:42:41Z | [
"python",
"console",
"progress",
"updating"
] | Is there a good way to do the following?
I wrote a simple console app to upload and download files from an FTP server using the ftplib.
Each time some data chunks are downloaded, I want to update a text progress bar, even if it's just a number.
But I don't want to erase all the text that's been printed to the consol... | Try the [click](http://click.pocoo.org/4/) library written by the Mozart of Python, Armin Ronacher.
```
$ pip install click # both 2 and 3 compatible
```
To create a simple progress bar:
```
import click
with click.progressbar(range(1000000)) as bar:
for i in bar:
pass
```
This is what it looks like:
... |
Text Progress Bar in the Console | 3,173,320 | 165 | 2010-07-04T00:29:08Z | 34,325,723 | 42 | 2015-12-17T02:39:16Z | [
"python",
"console",
"progress",
"updating"
] | Is there a good way to do the following?
I wrote a simple console app to upload and download files from an FTP server using the ftplib.
Each time some data chunks are downloaded, I want to update a text progress bar, even if it's just a number.
But I don't want to erase all the text that's been printed to the consol... | I've been using a modified version of @Vladimir Ignatyev's solution below and loving it : )
```
import sys
# Print iterations progress
def printProgress (iteration, total, prefix = '', suffix = '', decimals = 1, barLength = 100):
"""
Call in a loop to create terminal progress bar
@params:
iteratio... |
Download files from a list if not already downloaded | 3,173,372 | 2 | 2010-07-04T01:05:15Z | 3,173,388 | 9 | 2010-07-04T01:13:40Z | [
"python"
] | I can do this in c#, and the code is pretty long.
Would be cool if someone can show me how this would be done via python.
Pseudo code is:
```
url: www.example.com/somefolder/filename1.pdf
1. load file into an array (file contains a url on each line)
2. if file e.g. filename1.pdf doesn't exist, download file
```
Th... | This should do the trick, although I assume that the `urls.txt` file only contains the url. Not the `url:` prefix.
```
import os
import urllib
DOWNLOADS_DIR = '/python-downloader/downloaded'
# For every line in the file
for url in open('urls.txt'):
# Split on the rightmost / and take everything on the right side... |
Python MySQLDB SSL Connection | 3,173,650 | 4 | 2010-07-04T03:38:13Z | 3,175,553 | 7 | 2010-07-04T17:24:32Z | [
"python",
"mysql",
"database",
"django",
"ssl"
] | I set my database to require ssl. I've confirmed I can connect to the db via command line by passing the public key [and have confirmed I can't connect if I do not pass public key]
I get the same error in my django app as when I do not pass a key. It seems I've not setup my settings.py correctly to pass the path to th... | Found the answer. OPTIONS should look like this:
```
'OPTIONS': {'ssl': {'ca':'/path/to/cert.pem',},},
```
Make sure you keep the commas, parsing seemed to fail otherwise? |
difficulty with Python | 3,173,660 | 3 | 2010-07-04T03:47:54Z | 3,173,667 | 11 | 2010-07-04T03:51:53Z | [
"python"
] | ```
def myfunc(x):
y = x
y.append('How do I stop Python from modifying x here?')
return y
x = []
z = myfunc(x)
print(x)
``` | You do:
```
y = x[:]
```
to make a copy of list `x`. |
Does ruby have something similar to buildout or virtualenv? | 3,173,792 | 7 | 2010-07-04T05:12:56Z | 3,174,608 | 7 | 2010-07-04T12:16:52Z | [
"python",
"ruby",
"virtualenv",
"buildout"
] | I was wondering:
In python, canon says to use buildout or virtualenv, to avoid installing into the system packages. It's second nature now, I no longer see anything ludicrously bizarre to the practice. It makes a kind of sense.
In Ruby, is there something similar? How does ruby deal with this problem? Does ruby have ... | There are several projects trying to handle this issue:
* [rip](http://github.com/defunkt/rip#readme)
* [bundler](http://gembundler.com/)
* [rvm](http://rvm.beginrescueend.com/) via [gemsets](http://rvm.beginrescueend.com/gemsets/basics/)
* [sandbox](http://github.com/nkryptic/sandbox#readme) |
Modification of the list items in the loop (python) | 3,173,915 | 17 | 2010-07-04T06:21:58Z | 3,173,920 | 40 | 2010-07-04T06:24:15Z | [
"python",
"loops",
"items"
] | I'm trying to modify items in a list using a for loop, but I get an error (see below). Sample code:
```
#!/usr/bin/env python
# *-* coding: utf8 *-*
data = []
data.append("some")
data.append("example")
data.append("data")
data.append("here")
for item in data:
data[item] = "everything"
```
Error:
```
Traceback ... | Try this instead:
```
for i in xrange(len(data)):
data[i] = "everything"
```
The basic problem you're having is that when you write `data[i]`, with `data` being a list, the `i` needs to be an integer, a numerical index into the list. But in the loop
```
for item in data
```
`item` is the actual thing that's in ... |
Remote server command execute | 3,173,977 | 4 | 2010-07-04T07:02:08Z | 3,174,008 | 7 | 2010-07-04T07:11:18Z | [
"python"
] | What would be the best way to execute shell commands on remote servers and get output without actually logging in.
Maybe with shh keys. Preferably with python. | You mean without logging in *manually*? Because a server that actually let you execute commands without logging in at all would be a humongous security risk.
It looks like in the area of Python interfaces to SSH, Paramiko is what everybody's using these days. Here's a nice introductory article I found through Google:
... |
How to eject CD using WMI and Python? | 3,174,349 | 7 | 2010-07-04T10:13:10Z | 3,177,896 | 9 | 2010-07-05T07:58:06Z | [
"python",
"winapi",
"wmi",
"cd",
"eject"
] | Using Windows' WMI library, how can I eject CD rom mounted in a specific CD/DVD drive?
I am asking for sources from WMI docs or examples since I am using wmi.py library on Python.
It would be great if solution satisfies Windows computer newer than Windows 2000 and having multi CD-ROMs. (i.e. I have D: F: drives and b... | You can use [ctypes](http://docs.python.org/library/ctypes.html).
```
import ctypes
ctypes.windll.WINMM.mciSendStringW(u"set cdaudio door open", None, 0, None)
```
**UPDATE:**
If you have more that one drive, you can use to [open](http://msdn.microsoft.com/en-us/library/dd743638%28v=VS.85%29.aspx) command to initia... |
Is it Pythonic to use bools as ints? | 3,174,392 | 54 | 2010-07-04T10:43:12Z | 3,174,405 | 33 | 2010-07-04T10:48:44Z | [
"boolean",
"python"
] | `False` is equivalent to `0` and `True` is equivalent `1` so it's possible to do something like this:
```
def bool_to_str(value):
"""value should be a bool"""
return ['No', 'Yes'][value]
bool_to_str(True)
```
Notice how value is `bool` but is used as an `int`.
Is this this kind of use Pythonic or should it ... | surely:
```
def bool_to_str(value):
"value should be a bool"
return 'Yes' if value else 'No'
```
is more readable. |
Is it Pythonic to use bools as ints? | 3,174,392 | 54 | 2010-07-04T10:43:12Z | 3,175,293 | 140 | 2010-07-04T16:03:31Z | [
"boolean",
"python"
] | `False` is equivalent to `0` and `True` is equivalent `1` so it's possible to do something like this:
```
def bool_to_str(value):
"""value should be a bool"""
return ['No', 'Yes'][value]
bool_to_str(True)
```
Notice how value is `bool` but is used as an `int`.
Is this this kind of use Pythonic or should it ... | I'll be the odd voice out (since all answers are decrying the use of the fact that `False == 0` and `True == 1`, as the language guarantees) as I claim that the use of this fact to simplify your code is perfectly fine.
Historically, logical true/false operations tended to simply use `0` for false and `1` for true; in ... |
Is it Pythonic to use bools as ints? | 3,174,392 | 54 | 2010-07-04T10:43:12Z | 3,177,466 | 13 | 2010-07-05T06:10:26Z | [
"boolean",
"python"
] | `False` is equivalent to `0` and `True` is equivalent `1` so it's possible to do something like this:
```
def bool_to_str(value):
"""value should be a bool"""
return ['No', 'Yes'][value]
bool_to_str(True)
```
Notice how value is `bool` but is used as an `int`.
Is this this kind of use Pythonic or should it ... | Your code seems inaccurate in some cases:
```
>>> def bool_to_str(value):
... """value should be a bool"""
... return ['No', 'Yes'][value]
...
>>> bool_to_str(-2)
'No'
```
And I recommend you to use just the conditional operator for readability:
```
def bool_to_str(value):
"""value should be a bool"""
... |
Is it Pythonic to use bools as ints? | 3,174,392 | 54 | 2010-07-04T10:43:12Z | 6,865,824 | 111 | 2011-07-28T21:20:01Z | [
"boolean",
"python"
] | `False` is equivalent to `0` and `True` is equivalent `1` so it's possible to do something like this:
```
def bool_to_str(value):
"""value should be a bool"""
return ['No', 'Yes'][value]
bool_to_str(True)
```
Notice how value is `bool` but is used as an `int`.
Is this this kind of use Pythonic or should it ... | I'm with Alex. `False==0` and `True==1`, and there's nothing wrong with that.
Still, in Python 2.5 and later I'd write the answer to this particular question using Python's conditional expression:
```
def bool_to_str(value):
return 'Yes' if value else 'No'
```
That way there's no requirement that the argument is a... |
SQLAlchemy many-to-many relationship on declarative tables | 3,174,979 | 10 | 2010-07-04T14:33:48Z | 3,179,160 | 13 | 2010-07-05T11:38:51Z | [
"python",
"sqlalchemy"
] | I have the following tables defined declaratively (very simplified version):
```
class Profile(Base):
__tablename__ = 'profile'
id = Column(Integer, primary_key = True)
name = Column(String(65), nullable = False)
def __init__(self, name):
self.name = name
class Question(... | > The documentation says I need to use
> an association object to do this but
> it's confusing me and I can't get it
> to work.
That's right. And the Answer class is your association object as it maps to the association table 'answer'.
> How do I define the many-to-many
> relationship for the Profile and
> Question t... |
Set minimum column width to header width in PyQt4 QTableWidget | 3,175,665 | 7 | 2010-07-04T18:05:47Z | 3,175,876 | 7 | 2010-07-04T19:09:00Z | [
"python",
"table",
"pyqt4"
] | I'm working with the `QTableWidget` component in PyQt4 and I can't seem to get columns to size correctly, according to their respective header lengths.
Here's what the table layout should look like (sans pipes, obviously):
```
Index | Long_Header | Longer_Header
1 | 102402 | 100
2 | 123123 | 2
3 ... | ```
table.resizeColumnsToContents()
```
should do the trick for this specific example.
Be sure to bookmark the [PyQt documentation](http://pyqt.sourceforge.net/Docs/PyQt4/) if you haven't done so already (handy when you're looking for a specific function). |
OOPs paradigm in Python | 3,175,714 | 5 | 2010-07-04T18:19:21Z | 3,175,743 | 9 | 2010-07-04T18:32:21Z | [
"java",
"c++",
"python",
"oop"
] | Here is something I've been having a doubt about. Consider the following snippet.
```
class A(object):
def check(self):
super(A, self).check()
print "inside a"
class B(object):
def check(self):
print "inside b"
class C(A, B):
pass
c = C()
c.setup()
```
Now this gives the output,... | The algorithm is explained in [this excellent article](http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html).
In short,
`super(A,self)` looks in `self.__class__.__mro__` for the next class *after* `A`.
In your case, `self` is `c`, so `self.__class__` is `C`.
`C.__mro__` is `... |
Vim - run ctags on current python site-packages | 3,175,916 | 10 | 2010-07-04T19:19:52Z | 3,176,466 | 7 | 2010-07-04T22:49:37Z | [
"python",
"vim",
"ctags"
] | This is what I need - have a key that will create ctags of my python site-packages.
I have this command, that will print the site-packages path:
```
!python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"
```
This is how I to the key mapping:
```
map <F11> :!ctags -R -f ./tags *site-pack... | This should work:
```
map <F11> :exe '!ctags -R -f ./tags ' . shellescape(system('python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"'))<CR>
```
But if your shell supports it, why not just:
```
map <F11> :!ctags -R -f ./tags `python -c "from distutils.sysconfig import get_python_lib; p... |
How to add Google Analytics to reStructuredText? | 3,176,258 | 3 | 2010-07-04T21:20:15Z | 3,922,784 | 7 | 2010-10-13T10:40:41Z | [
"python",
"restructuredtext",
"docutils"
] | I am using reStructured text to create some easy websites.
So I have got a lot of \*.rst files in which I want to add the Google Analytics code.
But as far as I know it is not possible to add something like this?!
I am using rst2html to convert the files to html. | I've just discovered an easy way to add custom content to .rst files. All you need to do it to modify the template for html files.
Make a new template template.txt and the following contents to it (based on the default template):
```
%(head_prefix)s
%(head)s
<!--your tracking code-->
%(stylesheet)s
%(body_prefix)s
%(... |
cannot change font to Helvetica in Matplotlib in Python on Mac OS X 10.6 | 3,176,350 | 11 | 2010-07-04T21:54:53Z | 3,176,392 | 14 | 2010-07-04T22:17:55Z | [
"python",
"osx",
"numpy",
"matplotlib",
"scipy"
] | I am trying to change the matplotlib font to helvetica, which I'd like to use in a PDF plot. I try the following:
```
import matplotlib
matplotlib.use('PDF')
import matplotlib.pylab as plt
from matplotlib import rc
plt.rcParams['ps.useafm'] = True
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
plt.rcP... | The solution is to use fondu to convert the .dfont Helvetica font from Mac OS X into .ttf, and then place that in the mpl-data/fonts directory that Matplotlib looks in. That solved the issue. |
how to make a delete / put request in python | 3,176,409 | 3 | 2010-07-04T22:26:01Z | 6,860,521 | 7 | 2011-07-28T14:21:52Z | [
"python",
"rest",
"httpwebrequest"
] | I can make get or post request using urllib, but how do I make DELETE- and PUT-requests? | The [requests](https://github.com/kennethreitz/requests) library can handle POST, PUT, DELETE, and all other HTTP methods, and is significantly less scary than urllib, httplib and their variants. |
How can I speed up array generations in python? | 3,176,474 | 6 | 2010-07-04T22:51:30Z | 3,176,597 | 8 | 2010-07-04T23:43:44Z | [
"python",
"arrays",
"matrix",
"performance",
"opencv"
] | I'm thinking I need to use numpy or some other library to fill these arrays fast enough but I don't know much about it. Right now this operation takes about 1 second on a quad-core Intel PC, but I need it to be as fast as possible. Any help is greatly appreciated. Thanks!
```
import cv
class TestClass:
def __init_... | My eight year old (slow) computer is able to create a list of lists the same size as your matrix in 127 milliseconds.
```
C:\Documents and Settings\gdk\Desktop>python -m timeit "[[x for x in range(960)]
for y in range(540)]"
10 loops, best of 3: 127 msec per loop
```
I don't know what the cv module is and how it cre... |
How can I improve this code? | 3,176,773 | 4 | 2010-07-05T01:10:54Z | 3,176,809 | 11 | 2010-07-05T01:23:00Z | [
"python",
"rounding"
] | ```
# max_list = [83, 1350, 1, 100]
for i in range(len(max_list)):
new_value = 1
while new_value < max_list[i]:
new_value *= 10
max_list = new_value
```
What I'm doing is rounding numbers up to the closest, uhm, zero filled value? I'm not sure what it would be called. But basically, I want 83 ... | I'd do it mathematically:
```
from math import ceil, log10
int(pow(10, ceil(log10(abs(x or 0.1)))))
``` |
Django Templates - Printing Comma-separated ManyToManyField, sorting results list into dict? | 3,177,461 | 6 | 2010-07-05T06:08:19Z | 3,177,537 | 12 | 2010-07-05T06:29:34Z | [
"python",
"django",
"django-templates"
] | I have a Django project for managing a list of journal articles. The main model is `Article`. This has various fields to store things like title of the article, publication date, subject, as well as list of companies mentioned in the article. (`company` is it's own model).
I want a template that prints out a list of t... | Try `forloop.last` for your first question
```
{% for company in article.companys.all %}
{{company.name}}{% if not forloop.last %}, {% endif %}
{% endfor %}
``` |
Django Templates - Printing Comma-separated ManyToManyField, sorting results list into dict? | 3,177,461 | 6 | 2010-07-05T06:08:19Z | 3,177,750 | 14 | 2010-07-05T07:27:12Z | [
"python",
"django",
"django-templates"
] | I have a Django project for managing a list of journal articles. The main model is `Article`. This has various fields to store things like title of the article, publication date, subject, as well as list of companies mentioned in the article. (`company` is it's own model).
I want a template that prints out a list of t... | **first question**
Use the python like join filter
```
{{ article.company.all|join:", " }}
```
<http://docs.djangoproject.com/en/dev/ref/templates/builtins/#join>
**second question**
> My question is, is it better to use
> the dictsort template-tag to sort this
> inside the template, or should I use
> QuerySet's o... |
Python: Select subset from list based on index set | 3,179,106 | 27 | 2010-07-05T11:30:33Z | 3,179,119 | 32 | 2010-07-05T11:32:36Z | [
"python",
"list"
] | I have several lists having all the same number of entries (each specifying an object property):
```
property_a = [545., 656., 5.4, 33.]
property_b = [ 1.2, 1.3, 2.3, 0.3]
...
```
and list with flags of the same length
```
good_objects = [True, False, False, True]
```
(which could easily be substituted with an equ... | You could just use [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions):
```
property_asel = [val for is_good, val in zip(good_objects, property_a) if is_good]
```
or
```
property_asel = [property_a[i] for i in good_indices]
```
The latter one is faster because there are few... |
Python: Select subset from list based on index set | 3,179,106 | 27 | 2010-07-05T11:30:33Z | 3,179,137 | 10 | 2010-07-05T11:34:51Z | [
"python",
"list"
] | I have several lists having all the same number of entries (each specifying an object property):
```
property_a = [545., 656., 5.4, 33.]
property_b = [ 1.2, 1.3, 2.3, 0.3]
...
```
and list with flags of the same length
```
good_objects = [True, False, False, True]
```
(which could easily be substituted with an equ... | I see 2 options.
1. Using numpy:
```
property_a = numpy.array([545., 656., 5.4, 33.])
property_b = numpy.array([ 1.2, 1.3, 2.3, 0.3])
good_objects = [True, False, False, True]
good_indices = [0, 3]
property_asel = property_a[good_objects]
property_bsel = property_b[good_indices]
```
2. Using ... |
Python: Select subset from list based on index set | 3,179,106 | 27 | 2010-07-05T11:30:33Z | 3,179,138 | 11 | 2010-07-05T11:34:56Z | [
"python",
"list"
] | I have several lists having all the same number of entries (each specifying an object property):
```
property_a = [545., 656., 5.4, 33.]
property_b = [ 1.2, 1.3, 2.3, 0.3]
...
```
and list with flags of the same length
```
good_objects = [True, False, False, True]
```
(which could easily be substituted with an equ... | Use the built in function [zip](http://docs.python.org/library/functions.html#zip)
```
property_asel = [a for (a, truth) in zip(property_a, good_objects) if truth]
```
---
# EDIT
Just looking at the new features of 2.7. There is now a function in the itertools module which is similar to the above code.
<http://doc... |
Python: **kargs instead of overloading? | 3,179,460 | 5 | 2010-07-05T12:32:53Z | 3,180,455 | 7 | 2010-07-05T14:56:19Z | [
"python",
"design",
"design-patterns",
"method-overloading"
] | I have a conceptual Python design dilemma.
Say I have a `City` class, which represents a city in the database. The `City` object can be initialized in two ways:
1. An integer (actually, an ID of an existing city in a database)
2. A list of properties (`name`, `country`, `population`, ...), which will generate a new c... | How about:
```
class City(object):
def __init__(self, name, description, country, populations):
self.city_name = name
# etc.
@classmethod
def from_id(cls, city_id):
# initialise from DB
```
Then you can do normal object creation:
```
>>> c = City('Hollowberg', '', 'Densin', 3)
>>> c.id... |
Static properties in Python | 3,179,474 | 12 | 2010-07-05T12:36:10Z | 3,179,610 | 26 | 2010-07-05T12:57:52Z | [
"python"
] | I am relatively new to Python and was hoping someone could explain the following to me:
```
class MyClass:
Property1 = 1
Property2 = 2
print MyClass.Property1 # 1
mc = MyClass()
print mc.Property1 # 1
```
Why can I access Property1 both statically and through a MyClass instance? | The code
```
class MyClass:
Property1 = 1
```
creates a class `MyClass` which has a dict:
```
>>> MyClass.__dict__
{'Property1': 1, '__doc__': None, '__module__': '__main__'}
```
Notice the key-value pair `'Property1': 1`.
When you say `MyClass.Property1`, Python looks in the dict `MyClass.__dict__` for the key `... |
Python: Load module by its name | 3,179,940 | 2 | 2010-07-05T13:42:08Z | 3,179,987 | 9 | 2010-07-05T13:50:15Z | [
"python",
"django",
"import",
"module"
] | I'm working on a django project that serves multiple sites; depending on the site I want to import different functionality from a different module; how do I import a module in Python if I have the name of its package and the module name itself as a string? | in Python generally, you can use `__import__` builtin function or `imp` module features:
```
>>> sys1 = __import__("sys")
>>> import imp
>>> sys2 = imp.load_module("sys2", *imp.find_module("sys"))
>>> import sys
>>> sys is sys1 is sys2
True
``` |
Does it make sense to check for identity in __eq__? | 3,180,004 | 8 | 2010-07-05T13:53:37Z | 3,180,137 | 7 | 2010-07-05T14:11:13Z | [
"python",
"equality"
] | When implementing a custom equality function for a class, does it make sense to check for identity first? An example:
```
def __eq__(self, other):
return (self is other) or (other criteria)
```
This interesting is for cases when the other criteria may be more expensive (e.g. comparing some long strings). | It may be a perfectly reasonable shortcut to check for identity first, and in equality methods good shortcuts (for both equality and non equality) are what you should be looking for so that you can return as soon as possible.
But, on the other hand, it could also be a completely superfluous check if your test for equa... |
Python, ConfigParser: What is 'magical interpolation' | 3,180,489 | 9 | 2010-07-05T15:01:30Z | 3,180,514 | 7 | 2010-07-05T15:04:45Z | [
"python",
"configparser"
] | The documentation for ConfigParser in Python talks a lot about the so-called "magical interpolation" feature, but never explains what it actually does. I've tried searching for it, but haven't found any answers. | `bad_subj` below would be parsed into `'Notify [failure]'`
```
bad_subj: %(subj)s [failure]
subj: Notify
``` |
imap deleting messages | 3,180,891 | 6 | 2010-07-05T16:13:57Z | 3,180,916 | 9 | 2010-07-05T16:18:19Z | [
"python",
"imap"
] | How can I delete messages from the mail box? I am using this code, but the letters are not removed. Sorry for my English.
```
def getimap(self,server,port,login,password):
import imaplib, email
box = imaplib.IMAP4(server,port)
box.login(login,password)
box.select()
box.expunge()
typ, data = box... | I think you should mark the emails to be deleted, first.. For example:
```
for num in data[0].split():
box.store(num, '+FLAGS', '\\Deleted')
box.expunge()
``` |
Python boolean expression and or | 3,181,901 | 13 | 2010-07-05T20:09:30Z | 3,181,942 | 13 | 2010-07-05T20:18:30Z | [
"python",
"syntax",
"boolean-expression"
] | In python if you write something like
```
foo==bar and spam or eggs
```
python appears to return spam if the boolean statement is true and eggs otherwise. Could someone explain this behaviour? Why is the expression not being evaluated like one long boolean?
Edit: Specifically, I'm trying to figure out the mechanism ... | The operators `and` and `or` are short-circuiting which means that if the result of the expression can be deduced from evaluating only the first operand, the second is not evaluated. For example if you have the expression `a or b` and `a` evaluates to true then it doesn't matter what `b` is, the result of the expressio... |
Creating a list of objects in Python | 3,182,183 | 8 | 2010-07-05T21:10:21Z | 3,182,241 | 23 | 2010-07-05T21:24:28Z | [
"python"
] | How do I go about creating a list of objects (class instance) in Python?
Or is this a result of bad design? I need this cause I have different objects and I need to handle them at a later stage, so I would just keep on adding them to a list and call them later. | Storing a list of object instances is very simple
```
class MyClass(object):
def __init__(self, number):
self.number = number
my_objects = []
for i in range(100):
my_objects.append(MyClass(i))
# later
for obj in my_objects:
print obj.number
``` |
NLTK and language detection | 3,182,268 | 14 | 2010-07-05T21:30:32Z | 3,384,659 | 20 | 2010-08-02T02:34:33Z | [
"python",
"detection",
"nltk"
] | How do I detect what language a text is written in using NLTK?
The examples I've seen use nltk.detect, but when I've installed it on my mac, I cannot find this package.
Cheers
Nik | Have you come across the following code snippet?
```
english_vocab = set(w.lower() for w in nltk.corpus.words.words())
text_vocab = set(w.lower() for w in text if w.lower().isalpha())
unusual = text_vocab.difference(english_vocab)
```
from <http://groups.google.com/group/nltk-users/browse_thread/thread/a5f52af2cbc4cf... |
NLTK and language detection | 3,182,268 | 14 | 2010-07-05T21:30:32Z | 17,386,925 | 9 | 2013-06-30T03:43:43Z | [
"python",
"detection",
"nltk"
] | How do I detect what language a text is written in using NLTK?
The examples I've seen use nltk.detect, but when I've installed it on my mac, I cannot find this package.
Cheers
Nik | Although this is not in the NLTK, I have had great results with another Python-based library :
<https://github.com/saffsd/langid.py>
This is very simple to import and includes a large number of languages in its model. |
objects or closures - when to use? | 3,182,603 | 12 | 2010-07-05T23:06:41Z | 3,182,622 | 7 | 2010-07-05T23:12:38Z | [
"python",
"oop",
"functional-programming"
] | I can define an object and assign attributes and methods:
```
class object:
def __init__(self,a,b):
self.a = a
self.b = b
def add(self):
self.sum = self.a + self.b
def subtr(self):
self.fin = self.sum - self.b
def getpar(self):
return self.fin
obj = object(2,3)
... | In Python, closures can be harder to debug and to use than the more usual objects (you have to save the callables somewhere, access them with the goofy notation `clos['add']` etc, ...). Consider for example the impossibility of accessing the `sum` if you find something strange in the result... debugging this kind of th... |
objects or closures - when to use? | 3,182,603 | 12 | 2010-07-05T23:06:41Z | 3,183,573 | 14 | 2010-07-06T04:54:00Z | [
"python",
"oop",
"functional-programming"
] | I can define an object and assign attributes and methods:
```
class object:
def __init__(self,a,b):
self.a = a
self.b = b
def add(self):
self.sum = self.a + self.b
def subtr(self):
self.fin = self.sum - self.b
def getpar(self):
return self.fin
obj = object(2,3)
... | You should use the version that most clearly expresses what you are trying to achieve.
In the example given, I'd say that object version is more clear, since it seems to be modeling an object with state that changes. Looking at the code that uses the value, the object version seems to express the clear intent, whereas... |
Python unicode string with UTF-8? | 3,182,716 | 5 | 2010-07-05T23:38:34Z | 3,182,748 | 7 | 2010-07-05T23:48:41Z | [
"python",
"unicode"
] | I'm getting back from a library what looks to be an incorrect unicode string:
```
>>> title
u'Sopet\xc3\xb3n'
```
Now, those two hex escapes there are the UTF-8 encoding for U+00F3 LATIN SMALL LETTER O WITH ACUTE. So far as I understand, a unicode string in Python should have the actual character, not the the UTF-8 e... | a) Try to put it through the method below.
b)
```
>>> u'Sopet\xc3\xb3n'.encode('latin-1').decode('utf-8')
u'Sopet\xf3n'
``` |
Drawback to catch-all exception (at highest program level, followed by re-raising, just to log before exiting?) | 3,182,935 | 5 | 2010-07-06T01:04:43Z | 3,182,956 | 7 | 2010-07-06T01:13:13Z | [
"python",
"exception"
] | I have a long-running program on a remote machine and want to be sure that (1) I have a record of any exception that causes it to terminate and (2) someone is notified if it terminates. Does anyone see drawbacks to the method I am using? (or have recommendations for a better one?)
I've read the Python docs and many ex... | There is no specific drawback, but there *is* an excellent alternative -- [sys.excepthook](http://docs.python.org/library/sys.html?highlight=sys.excepthook#sys.excepthook).
In your specific version, consider using a bare `except:`, and `sys.exc_info()` to get the exception information; that will ensure you *do* catch ... |
shuffling a word | 3,182,964 | 7 | 2010-07-06T01:14:53Z | 3,182,970 | 7 | 2010-07-06T01:17:19Z | [
"python"
] | How do I shuffle a word's letters randomly in python?
For example, the word "cat" might be changed into 'act', 'tac' or 'tca'.
I would like to do this *without* using built-in functions | ```
import random
word = "cat"
shuffled = list(word)
random.shuffle(shuffled)
shuffled = ''.join(shuffled)
print shuffled
```
...or done in a different way, inspired by [Dominic's answer](http://stackoverflow.com/questions/3182964/3182983#3182983)...
```
import random
shuffled = ''.join(random.sample(word, len(word))... |
shuffling a word | 3,182,964 | 7 | 2010-07-06T01:14:53Z | 3,183,005 | 7 | 2010-07-06T01:31:20Z | [
"python"
] | How do I shuffle a word's letters randomly in python?
For example, the word "cat" might be changed into 'act', 'tac' or 'tca'.
I would like to do this *without* using built-in functions | Take a look at the [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle). It's extremely space and time-efficient, and easy to implement. |
Stripping off the seconds in datetime python | 3,183,707 | 24 | 2010-07-06T05:30:00Z | 3,183,720 | 53 | 2010-07-06T05:32:33Z | [
"python"
] | now() gives me
```
datetime.datetime(2010, 7, 6, 5, 27, 23, 662390)
```
How do I get just `datetime.datetime(2010, 7, 6, 5, 27, 0, 0)` (the datetime object) where everything after minutes is zero? | ```
dtwithoutseconds = dt.replace(second=0, microsecond=0)
```
<http://docs.python.org/library/datetime.html#datetime.datetime.replace> |
Stripping off the seconds in datetime python | 3,183,707 | 24 | 2010-07-06T05:30:00Z | 3,183,727 | 9 | 2010-07-06T05:33:49Z | [
"python"
] | now() gives me
```
datetime.datetime(2010, 7, 6, 5, 27, 23, 662390)
```
How do I get just `datetime.datetime(2010, 7, 6, 5, 27, 0, 0)` (the datetime object) where everything after minutes is zero? | You can use [`datetime.replace`](http://docs.python.org/library/datetime.html#datetime.datetime.replace) to obtain a new datetime object without the seconds and microseconds:
```
the_time = datetime.now()
the_time = the_time.replace(second=0, microsecond=0)
``` |
How to bind arguments to given values in Python functions? | 3,188,048 | 35 | 2010-07-06T16:10:42Z | 3,188,092 | 10 | 2010-07-06T16:16:27Z | [
"python"
] | I have a number of functions with a combination of positional and keyword arguments, and I would like to bind one of their arguments to a given value (which is known only after the function definition). Is there a general way of doing that?
My first attempt was:
```
def f(a,b,c): print a,b,c
def _bind(f, a): return ... | You probably want the [`partial`](http://docs.python.org/library/functools.html#functools.partial) function from functools. |
How to bind arguments to given values in Python functions? | 3,188,048 | 35 | 2010-07-06T16:10:42Z | 3,188,134 | 52 | 2010-07-06T16:20:25Z | [
"python"
] | I have a number of functions with a combination of positional and keyword arguments, and I would like to bind one of their arguments to a given value (which is known only after the function definition). Is there a general way of doing that?
My first attempt was:
```
def f(a,b,c): print a,b,c
def _bind(f, a): return ... | ```
>>> from functools import partial
>>> def f(a, b, c):
... print a, b, c
...
>>> bound_f = partial(f, 1)
>>> bound_f(2, 3)
1 2 3
``` |
Python : Operator Overloading a specific type | 3,188,666 | 5 | 2010-07-06T17:29:56Z | 3,188,723 | 9 | 2010-07-06T17:36:20Z | [
"python",
"operator-overloading"
] | I'd like to be able to have the operator of my class interact with regular types in a way that I define. Lets say, for example, I have:
```
class Mynum(object):
def __init__(self, x):
self.x = x
def __add__(self, other):
return self.x + other.x
a = Mynum(1)
b = Mynum(2)
print a+b
```
This works just fine,... | ```
def __add__(self, other):
if isinstance(other, self.__class__):
return self.x + other.x
elif isinstance(other, int):
return self.x + other
else:
raise TypeError("unsupported operand type(s) for +: '{}' and '{}'").format(self.__class__, type(other))
``` |
Why import when you need to use the full name? | 3,188,929 | 8 | 2010-07-06T18:05:10Z | 3,189,105 | 22 | 2010-07-06T18:28:01Z | [
"python"
] | In python, if you need a module from a different package you have to import it. Coming from a Java background, that makes sense.
```
import foo.bar
```
What doesn't make sense though, is why do I need to use the full name whenever I want to use bar? If I wanted to use the full name, why do I need to import? Doesn't u... | The thing is, even though Python's `import` statement is designed to *look* similar to Java's, they do completely different things under the hood. As you know, in Java an `import` statement is really little more than a hint to the compiler. It basically sets up an alias for a fully qualified class name. For example, wh... |
Is it possible to write a firewall in python? | 3,189,138 | 7 | 2010-07-06T18:34:01Z | 3,192,379 | 16 | 2010-07-07T06:24:33Z | [
"python",
"firewall"
] | Is it possible to write a firewall in python? Say it would block all traffic? | Yes, yes it is.
I have some Python code that interacts with Linux iptables to perform firewalling duties, using nfqueue. I can use a rule in iptables that looks like:
```
iptables -A INPUT -j NFQUEUE --queue-num 1
```
And then have some Python code that looks like:
```
import nfqueue
from dpkt import ip
q = None
... |
twisted: one client, many servers | 3,189,222 | 7 | 2010-07-06T18:44:57Z | 3,189,333 | 8 | 2010-07-06T18:58:12Z | [
"python",
"twisted"
] | I'm trying to use twisted to create a cluster of computers that run one program on a piece of a larger dataset.
My "servers" receive a chunk of data from the client and run command x on it.
My "client" connects to multiple servers giving them each a chunk of data and telling them what parameters to run command x with... | Just call `connectTCP` multiple times.
The trick, of course, is that `reactor.run()` blocks "forever" (the entire run-time of your program) so you don't want to call *that* multiple times.
You have several options; you can set up a timed call to make future connections, or you can start new connections from events on... |
TCP Socket file transfer | 3,189,844 | 4 | 2010-07-06T20:11:48Z | 3,189,942 | 9 | 2010-07-06T20:24:51Z | [
"python",
"sockets",
"buffer",
"file-transfer"
] | I'm trying to write a secure transfer file program using Python and AES and i've got a problem i don't totally understand. I send my file by parsing it with 1024 bytes chunks and sending them over but the server side who receive the data crashes ( I use AES CBC therefore my data length must be a multiple of 16 bytes ) ... | Welcome to network programming! You've just fallen into the same mistaken assumption that *everyone* makes the first time through in assuming that client sends & server recives should be symmetric. Unfortunately, this is not the case. The OS allows reception to occur in arbitrarily sized chunks. It's fairly easy to wor... |
Python: how to print range a-z? | 3,190,122 | 41 | 2010-07-06T20:51:20Z | 3,190,207 | 78 | 2010-07-06T21:01:01Z | [
"python",
"string",
"ascii"
] | **1. Print a-n:** a b c d e f g h i j k l m n
**2. Every second in a-n:** a c e g i k m
**3. Append a-n to index of urls{hello.com/, hej.com/, ..., hallo.com/}:** hello.com/a hej.com/b ... hallo.com/n | ```
>>> import string
>>> string.lowercase[:14]
'abcdefghijklmn'
>>> string.lowercase[:14:2]
'acegikm'
```
To do the urls, you could use something like this
```
[i + j for i, j in zip(list_of_urls, string.lowercase[:14])]
``` |
Python: how to print range a-z? | 3,190,122 | 41 | 2010-07-06T20:51:20Z | 3,190,215 | 16 | 2010-07-06T21:01:50Z | [
"python",
"string",
"ascii"
] | **1. Print a-n:** a b c d e f g h i j k l m n
**2. Every second in a-n:** a c e g i k m
**3. Append a-n to index of urls{hello.com/, hej.com/, ..., hallo.com/}:** hello.com/a hej.com/b ... hallo.com/n | Hints:
```
import string
print string.ascii_lowercase
```
and
```
for i in xrange(0, 10, 2):
print i
```
and
```
"hello{0}, world!".format('z')
``` |
Python: how to print range a-z? | 3,190,122 | 41 | 2010-07-06T20:51:20Z | 3,190,219 | 9 | 2010-07-06T21:02:51Z | [
"python",
"string",
"ascii"
] | **1. Print a-n:** a b c d e f g h i j k l m n
**2. Every second in a-n:** a c e g i k m
**3. Append a-n to index of urls{hello.com/, hej.com/, ..., hallo.com/}:** hello.com/a hej.com/b ... hallo.com/n | ```
for one in range(97,110):
print chr(one)
``` |
Python: how to print range a-z? | 3,190,122 | 41 | 2010-07-06T20:51:20Z | 3,191,012 | 20 | 2010-07-06T23:55:35Z | [
"python",
"string",
"ascii"
] | **1. Print a-n:** a b c d e f g h i j k l m n
**2. Every second in a-n:** a c e g i k m
**3. Append a-n to index of urls{hello.com/, hej.com/, ..., hallo.com/}:** hello.com/a hej.com/b ... hallo.com/n | Assuming this is a homework ;-) - no need to summon libraries etc - it probably expect you to use range() with chr/ord, like so:
```
for i in range(ord('a'), ord('n')+1):
print chr(i),
```
For the rest, just play a bit more with the range() |
Python - Call a function in a module dynamically | 3,190,583 | 7 | 2010-07-06T22:06:12Z | 3,190,596 | 11 | 2010-07-06T22:08:51Z | [
"python"
] | I'm pretty new to Python and I have a situation where I have a variable representing a function inside of a module and I'm wondering how to call it dynamically. I have `filters.py`:
```
def scale(image, width, height):
pass
```
And then in another script I have something like:
```
import filters
def process_ima... | you need built-in [`getattr`](http://docs.python.org//library/functions.html#getattr):
```
getattr(filters, method)(**options)
``` |
Python - Call a function in a module dynamically | 3,190,583 | 7 | 2010-07-06T22:06:12Z | 3,190,632 | 10 | 2010-07-06T22:13:52Z | [
"python"
] | I'm pretty new to Python and I have a situation where I have a variable representing a function inside of a module and I'm wondering how to call it dynamically. I have `filters.py`:
```
def scale(image, width, height):
pass
```
And then in another script I have something like:
```
import filters
def process_ima... | To avoid the problem, you could pass the function directly, instead of "by name":
```
def process_images(method=filters.scale, options):
method(**options)
```
If you have a special reason to use a string instead, you can use `getattr` as suggested by SilentGhost. |
nonlocal keyword in Python 2.x | 3,190,706 | 81 | 2010-07-06T22:31:11Z | 3,190,783 | 86 | 2010-07-06T22:50:58Z | [
"python",
"closures",
"python-2.x",
"python-nonlocal"
] | I'm trying to implement a closure in Python 2.6 and I need to access a nonlocal variable but it seems like this keyword is not available in python 2.x. How should one access nonlocal variables in closures in these versions of python? | Python can *read* nonlocal variables in 2.x, just not *change* them. This is annoying, but you can work around it. Just declare a dictionary, and store your variables as elements therein.
To use the example from Wikipedia:
```
def outer():
d = {'y' : 0}
def inner():
d['y'] += 1
return d['y']
... |
nonlocal keyword in Python 2.x | 3,190,706 | 81 | 2010-07-06T22:31:11Z | 3,190,786 | 10 | 2010-07-06T22:51:19Z | [
"python",
"closures",
"python-2.x",
"python-nonlocal"
] | I'm trying to implement a closure in Python 2.6 and I need to access a nonlocal variable but it seems like this keyword is not available in python 2.x. How should one access nonlocal variables in closures in these versions of python? | I think the key here is what you mean by "access". There should be no issue with reading a variable outside of the closure scope, e.g.,
```
x = 3
def outer():
def inner():
print x
inner()
outer()
```
should work as expected (printing 3). However, overriding the value of x does not work, e.g.,
```
x =... |
nonlocal keyword in Python 2.x | 3,190,706 | 81 | 2010-07-06T22:31:11Z | 13,794,589 | 10 | 2012-12-10T03:25:14Z | [
"python",
"closures",
"python-2.x",
"python-nonlocal"
] | I'm trying to implement a closure in Python 2.6 and I need to access a nonlocal variable but it seems like this keyword is not available in python 2.x. How should one access nonlocal variables in closures in these versions of python? | There is another way to implement nonlocal variables in Python 2, in case any of the answers here are undesirable for whatever reason:
```
def outer():
outer.y = 0
def inner():
outer.y += 1
return outer.y
return inner
f = outer()
print(f(), f(), f()) #prints 1 2 3
```
It is redundant to u... |
nonlocal keyword in Python 2.x | 3,190,706 | 81 | 2010-07-06T22:31:11Z | 16,032,631 | 26 | 2013-04-16T08:51:23Z | [
"python",
"closures",
"python-2.x",
"python-nonlocal"
] | I'm trying to implement a closure in Python 2.6 and I need to access a nonlocal variable but it seems like this keyword is not available in python 2.x. How should one access nonlocal variables in closures in these versions of python? | The following solution is inspired by the [answer by Elias Zamaria](http://stackoverflow.com/a/13794589/281545), but contrary to that answer does handle multiple calls of the outer function correctly. The "variable" `inner.y` is local to the current call of `outer`. Only it isn't a variable, since that is forbidden, bu... |
nonlocal keyword in Python 2.x | 3,190,706 | 81 | 2010-07-06T22:31:11Z | 28,433,571 | 14 | 2015-02-10T14:02:25Z | [
"python",
"closures",
"python-2.x",
"python-nonlocal"
] | I'm trying to implement a closure in Python 2.6 and I need to access a nonlocal variable but it seems like this keyword is not available in python 2.x. How should one access nonlocal variables in closures in these versions of python? | Rather than a dictionary, there's less clutter to a **nonlocal class**. Modifying @ChrisB's [example](http://stackoverflow.com/a/3190783/673991):
```
def outer():
class context:
y = 0
def inner():
context.y += 1
return context.y
return inner
```
Then
```
f = outer()
assert f() == ... |
Scale legend box border, dashed and dotted lines when the figure size is changed with matplotlib | 3,190,798 | 4 | 2010-07-06T22:53:26Z | 3,219,849 | 7 | 2010-07-10T15:49:16Z | [
"python",
"matplotlib",
"plot"
] | I'm trying to use matplotlib to prepare some figures for publication. In order to make the font sizes match the text of the manuscript I'm trying to create the figure in the final size to begin with, so that I avoid scaling the figure when inserting it into the manuscript.
The problem I'm having is that as the figure ... | To adjust the [dashes](http://matplotlib.sourceforge.net/api/artist_api.html?highlight=dashes#matplotlib.lines.Line2D.set_dashes), use
```
a.plot(x, y, '--', label='foo bar', dashes=(2,2))
```
and the [legend box](http://matplotlib.sourceforge.net/api/artist_api.html?highlight=legend#matplotlib.legend.Legend.get_fram... |
Saving stdout from subprocess.Popen to file, plus writing more stuff to the file | 3,190,825 | 12 | 2010-07-06T22:59:31Z | 3,190,839 | 11 | 2010-07-06T23:03:52Z | [
"python",
"linux",
"subprocess",
"stdout",
"python-2.4"
] | I'm writing a python script that uses subprocess.Popen to execute two programs (from compiled C code) which each produce stdout. The script gets that output and saves it to a file. Because the output is sometimes large enough to overwhelm subprocess.PIPE, causing the script to hang, I send the stdout directly to the lo... | You could call .wait() on each Popen object in order to be sure that it's finished and then call log.flush(). Maybe something like this:
```
def run(cmd, logfile):
p = subprocess.Popen(cmd, shell=True, universal_newlines=True, stdout=logfile)
ret_code = p.wait()
logfile.flush()
return ret_code
```
If ... |
How to create a user in linux using python | 3,190,955 | 9 | 2010-07-06T23:36:02Z | 3,190,970 | 17 | 2010-07-06T23:41:04Z | [
"python",
"linux",
"shell"
] | How do I create a user in Linux using Python? I mean, I know about the subprocess module and thought about calling 'adduser' and passing all the parameters at once, but the 'adduser' command asks some questions like password, full name, phone and stuff. How would I answer this questions using subprocess?
I've seen modu... | Use `useradd`, it doesn't ask any questions but accepts many command line options. |
How to create a user in linux using python | 3,190,955 | 9 | 2010-07-06T23:36:02Z | 3,191,025 | 7 | 2010-07-06T23:58:53Z | [
"python",
"linux",
"shell"
] | How do I create a user in Linux using Python? I mean, I know about the subprocess module and thought about calling 'adduser' and passing all the parameters at once, but the 'adduser' command asks some questions like password, full name, phone and stuff. How would I answer this questions using subprocess?
I've seen modu... | On Ubuntu, you could use the [python-libuser](http://packages.ubuntu.com/lucid/python-libuser) package |
__init__ method for form with additional arguments | 3,191,443 | 4 | 2010-07-07T02:04:17Z | 3,191,452 | 7 | 2010-07-07T02:07:22Z | [
"python",
"django",
"django-forms",
"initialization"
] | I'm calling my form, with additional parameter 'validate :
`form = MyForm(request.POST, request.FILES, validate=True)`
How should I write form's **init** method to have access to this parameter inside body of my form (for example in \_clean method) ? This is what I came up with :
```
def __init__(self, *args, **kwar... | The `validate=True` argument is a keyword argument, so it will show up in the `kwargs`dict. (Only positional arguments show up in `args`.)
You can use [kwargs.pop](http://docs.python.org/library/stdtypes.html#dict.pop) to try to get the value of `kwargs['validate']`.
If `validate` is a key in `kwargs`, then `kwargs.po... |
What's the best way to send an object over a network in Python? | 3,191,478 | 8 | 2010-07-07T02:14:18Z | 3,191,761 | 17 | 2010-07-07T03:44:51Z | [
"python",
"networking",
"twisted"
] | I need to send objects around a network. I'm going to be using Twisted, and I've just started looking around the documentation for it.
As far as I know, the only way python implements sockets is through text. So how would I send an object using strings? Pickle? Or is there something better? | The most general serialization on offer between Python end-points is the pickle format (in Python 2.any, be sure to use the `cPickle` module, and the `-1` aka `pickle.HIGHEST_PROTOCOL` protocol; if you need interoperability between Python 2.any and Python 3.any more care is needed). For especially simple objects, the `... |
CSV in Python adding an extra carriage return | 3,191,528 | 85 | 2010-07-07T02:34:25Z | 3,191,811 | 119 | 2010-07-07T03:57:34Z | [
"python",
"csv",
"newline"
] | In Python 2.7 running on Windows XP pro:
```
import csv
outfile = file('test.csv', 'w')
writer = csv.writer(outfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['hi','dude'])
writer.writerow(['hi2','dude2'])
outfile.close()
```
It generates a file, test.csv, with an extra \r at each row, like so:
## t... | On Windows, always open your files in binary mode ("rb" or "wb") before passing them to csv.reader or csv.writer.
CSV is really a *binary* format, with "\r\n" separating records. If that separator is written in text mode, the Python runtime replaces the "\n" with "\r\n" hence the "\r\r\n" that you observed in your fil... |
CSV in Python adding an extra carriage return | 3,191,528 | 85 | 2010-07-07T02:34:25Z | 17,725,590 | 117 | 2013-07-18T13:59:32Z | [
"python",
"csv",
"newline"
] | In Python 2.7 running on Windows XP pro:
```
import csv
outfile = file('test.csv', 'w')
writer = csv.writer(outfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['hi','dude'])
writer.writerow(['hi2','dude2'])
outfile.close()
```
It generates a file, test.csv, with an extra \r at each row, like so:
## t... | While @john-machin gives a good answer, it's not always the best approach. For example, it doesn't work on Python 3 unless you encode all of your inputs to the CSV writer. Also, it doesn't address the issue if the script wants to use sys.stdout as the stream.
I suggest instead setting the 'lineterminator' attribute wh... |
CSV in Python adding an extra carriage return | 3,191,528 | 85 | 2010-07-07T02:34:25Z | 29,116,560 | 15 | 2015-03-18T07:43:46Z | [
"python",
"csv",
"newline"
] | In Python 2.7 running on Windows XP pro:
```
import csv
outfile = file('test.csv', 'w')
writer = csv.writer(outfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['hi','dude'])
writer.writerow(['hi2','dude2'])
outfile.close()
```
It generates a file, test.csv, with an extra \r at each row, like so:
## t... | In Python 3 (I haven't tried this in Python 2), you can also simply do
```
with open('output.csv','w',newline='') as f:
writer=csv.writer(f)
writer.writerow(mystuff)
...
```
as per [documentation](https://docs.python.org/3/library/csv.html#csv.writer).
More on this in the doc's [footnote](https://docs.py... |
How does sympy work? How does it interact with the interactive Python shell, and how does the interactive Python shell work? | 3,191,749 | 14 | 2010-07-07T03:42:35Z | 3,429,392 | 7 | 2010-08-07T06:25:12Z | [
"python",
"scripting",
"eval",
"interactive",
"sympy"
] | What happens internally when I press `Enter`?
My motivation for asking, besides plain curiosity, is to figure out what happens when you
```
from sympy import *
```
and enter an expression. How does it go from `Enter` to calling
```
__sympifyit_wrapper(a,b)
```
in sympy.core.decorators? (That's the first place [win... | All right after playing around with it some more I think I've got it.. when I first asked the question I didn't know about [operator overloading](http://docs.python.org/reference/datamodel.html#special-method-names).
So, what's going on in this python session?
```
>>> from sympy import *
>>> x = Symbol(x)
>>> x + x
2... |
GetWindowRect too small on Windows 7 | 3,192,232 | 12 | 2010-07-07T05:53:42Z | 3,192,264 | 15 | 2010-07-07T06:00:27Z | [
"python",
"windows",
"winapi",
"pywin32"
] | The actual problem I'm trying to solve is, I want to automatically find out the size of the margins around windows. If you can find a better way, please by all means answer that instead of this.
To do this I decided to take a screenshot of a test window and measure the margins. This is simple enough, as I expect no ma... | My first thoughts were listed below but if, as you state, you're certain that `GetWindowRect` is returning incorrect values, see *RESOLUTION* further down.
---
"What's wrong with `GetSystemMetrics(SM_CXBORDER)` and `GetSystemMetrics(SM_CYBORDER)`?
The method you're using seems a very roundabout way of doing it and, ... |
how do i make this python code less ugly | 3,192,437 | 7 | 2010-07-07T06:35:38Z | 3,192,513 | 14 | 2010-07-07T06:49:33Z | [
"python",
"idioms",
"pyquery"
] | First of all python is an awesome language. This is my first project using python and I've made a ridiculous amount of progress already.
There's no way that this code below is the best way to do this. What's the most idiomatic way write a class definition?
```
class Course:
crn = course = title = tipe = cr_h... | ```
def__init__(self, pyQueryRow):
for i,attr in enumerate("crn course title tipe cr_hours seats instructor"
" days begin end location exam".split()):
setattr(self, attr, self.get_column(pyQueryRow, i))
```
This way avoids multiple calls to `self.get_column`
```
def__init__(sel... |
Python: Redis as session backend to Beaker | 3,192,677 | 7 | 2010-07-07T07:24:13Z | 3,200,355 | 8 | 2010-07-08T02:38:40Z | [
"python",
"session",
"pylons",
"redis",
"beaker"
] | Anyone had success with using Redis as Beaker backend? Can you tell me link or library how to do it? I am looking for any library which does this but could not get anything out of google search. | I have posted to pylons user group and this information resolve my question..
<http://groups.google.com/group/pylons-discuss/msg/a1144aa1ca8e0417>
Here are the steps that worked for me:
1. easy\_install redis
2. easy\_install pip
3. pip install git+git://github.com/bbangert/beaker\_extensions.git
4. Edit Pylons' dev... |
catch specific HTTP error in python | 3,193,060 | 41 | 2010-07-07T08:25:56Z | 3,193,387 | 67 | 2010-07-07T09:14:45Z | [
"python",
"http",
"urllib2",
"urllib"
] | I want to catch a specific http error and not any one of the entire family..
what I was trying to do is --
```
import urllib2
try:
urllib2.urlopen("some url")
except urllib2.HTTPError:
<whatever>
```
but what I end up is catching any kind of http error, but I want to catch only if the specified webpage doesn't ... | Just catch `urllib2.HTTPError`, handle it, and if it's not Error 404, simply use `raise` to re-raise the exception.
See the [Python tutorial](http://docs.python.org/tutorial/errors.html#handling-exceptions).
So you could do:
```
import urllib2
try:
urllib2.urlopen("some url")
except urllib2.HTTPError as err:
i... |
catch specific HTTP error in python | 3,193,060 | 41 | 2010-07-07T08:25:56Z | 19,172,223 | 12 | 2013-10-04T02:27:14Z | [
"python",
"http",
"urllib2",
"urllib"
] | I want to catch a specific http error and not any one of the entire family..
what I was trying to do is --
```
import urllib2
try:
urllib2.urlopen("some url")
except urllib2.HTTPError:
<whatever>
```
but what I end up is catching any kind of http error, but I want to catch only if the specified webpage doesn't ... | For Python 3.x
```
import urllib.request
try:
urllib.request.urlretrieve(url, fullpath)
except urllib.error.HTTPError as err:
print(err.code)
``` |
Search inside ipython history | 3,193,891 | 18 | 2010-07-07T10:30:28Z | 16,864,156 | 23 | 2013-05-31T19:05:40Z | [
"python",
"ipython"
] | [ipython](http://ipython.scipy.org/moin/)'s `%his` command outputs recent commands entered by the user. Is it possible to search within these commands? Something like this:
```
[c for c in %history if c.startswith('plot')]
```
**EDIT** I am not looking for a way to rerun a command, but to locate it in the history lis... | Even better: `%hist -g |pattern|` greps your past history for `|pattern|`. You can additionally restrict your search to the current session, or to a particular range of lines. See `%hist?` |
Search inside ipython history | 3,193,891 | 18 | 2010-07-07T10:30:28Z | 20,551,969 | 7 | 2013-12-12T19:00:50Z | [
"python",
"ipython"
] | [ipython](http://ipython.scipy.org/moin/)'s `%his` command outputs recent commands entered by the user. Is it possible to search within these commands? Something like this:
```
[c for c in %history if c.startswith('plot')]
```
**EDIT** I am not looking for a way to rerun a command, but to locate it in the history lis... | I usually find myself wanting to search the entire ipython history across all previous and current sessions. For this I use:
```
from IPython.core.history import HistoryAccessor
hista = HistoryAccessor()
z1 = hista.search('*numpy*corr*')
z1.fetchall()
```
**OR** (don't run both or you will corrupt/erase your history)... |
Wait the end of subprocesses with multiple parallel jobs | 3,194,018 | 9 | 2010-07-07T10:55:31Z | 3,195,673 | 7 | 2010-07-07T14:24:45Z | [
"python",
"subprocess"
] | I'm running some subprocesses from python in parallel. I want to wait until every subprocess have finished. I'm doing a non elegant solution:
```
runcodes = ["script1.C", "script2.C"]
ps = []
for script in runcodes:
args = ["root", "-l", "-q", script]
p = subprocess.Popen(args)
ps.append(p)
while True:
ps_stat... | If your platform is not Windows, you could probably select against the stdout pipes of your subprocesses. Your app will then block until either:
* One of the registered file descriptors has an I/O event (in this case, we're interested in a hangup on the subprocess's stdout pipe)
* The poll times out
Non-fleshed-out e... |
Replace special characters with ASCII equivalent | 3,194,516 | 15 | 2010-07-07T12:12:48Z | 3,194,567 | 19 | 2010-07-07T12:19:56Z | [
"python",
"unicode"
] | Is there any lib that can replace special characters to ASCII equivalents, like:
```
"CzeÅÄ"
```
to:
```
"Czesc"
```
I can of course create map:
```
{'Å':'s', 'Ä': 'c'}
```
and use some replace function. But I don't want to hardcode all equivalents into my program, if there is some function that already does ... | ```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unicodedata
text = u'CzeÅÄ'
print unicodedata.normalize('NFD', text).encode('ascii', 'ignore')
``` |
Replace special characters with ASCII equivalent | 3,194,516 | 15 | 2010-07-07T12:12:48Z | 3,226,244 | 11 | 2010-07-12T06:10:54Z | [
"python",
"unicode"
] | Is there any lib that can replace special characters to ASCII equivalents, like:
```
"CzeÅÄ"
```
to:
```
"Czesc"
```
I can of course create map:
```
{'Å':'s', 'Ä': 'c'}
```
and use some replace function. But I don't want to hardcode all equivalents into my program, if there is some function that already does ... | You can get most of the way by doing:
```
import unicodedata
def strip_accents(text):
return ''.join(c for c in unicodedata.normalize('NFKD', text) if unicodedata.category(c) != 'Mn')
```
Unfortunately, there exist accented Latin letters that cannot be decomposed into an ASCII letter + combining marks. You'll ha... |
Building a list of months by iterating between two dates in a list (Python) | 3,194,682 | 5 | 2010-07-07T12:34:59Z | 3,194,718 | 7 | 2010-07-07T12:40:40Z | [
"python"
] | I have an ordered (i.e. sorted) list that contains dates sorted (as datetime objects) in ascending order.
I want to write a function that iterates through this list and generates another list of the first available dates for each month.
For example, suppose my sorted list contains the following data:
```
A = [
'2001... | ```
>>> import itertools
>>> [min(j) for i, j in itertools.groupby(A, key=lambda x: x[:7])]
['2001/01/01', '2001/02/04', '2001/03/01', '2001/04/10', '2001/05/07', '2001/07/01', '2002/03/01', '2002/04/01']
``` |
AttributeError: 'datetime.date' object has no attribute 'date' | 3,195,405 | 3 | 2010-07-07T13:52:36Z | 3,195,426 | 10 | 2010-07-07T13:54:34Z | [
"python"
] | I have a script like this:
```
import datetime
# variable cal_start_of_week_date has type <type 'datetime.date'>
# variable period has type <type 'datetime.timedelta'>
cal_prev_monday = (cal_start_of_week_date - period).date()
```
When the above statement is executed, I get the error:
AttributeError: 'datetime.da... | Stop trying to call the `date()` method of a `date` object. It's already a `date`. |
How to use NumPy array with ctypes? | 3,195,660 | 8 | 2010-07-07T14:22:44Z | 3,671,889 | 12 | 2010-09-08T21:03:38Z | [
"python",
"numpy",
"ctypes"
] | I am still writing on a python interface for my c code with ctypes. Today I substituted my file reading function with a python version, which was programmed by somebody else usind NumPy. The 'old' c version was called with a byref(p\_data) while p\_data=PFloat() (see below). The main function takes the p\_data.
Old fi... | Your code looks like it has some confusion in it -- `ctypes.POINTER()` creates a new ctypes pointer *class*, not a ctypes instance. Anyway, the easiest way to pass a NumPy array to ctypes code is to use the `numpy.ndarray`'s `ctypes` attribute's `data_as` method. Just make sure the underlying data is the right type fir... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.