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 |
|---|---|---|---|---|---|---|---|---|---|
__del__ method being called in python when it is not expected | 1,935,153 | 6 | 2009-12-20T07:42:46Z | 1,935,179 | 18 | 2009-12-20T07:54:26Z | [
"python",
"object-lifetime",
"del"
] | I am new to python and have been working through the examples in Swaroop CH's "A Byte of Python". I am seeing some behavior with the `__del__` method that is puzzling me.
Basically, if I run the following script (in Python 2.6.2)
```
class Person4:
'''Represents a person'''
population = 0
def __init__(se... | There are a couple of things going on here. When your `Person4` class is instantiated, it initialises its `population` class variable to 0. From your interactive console, you appear to be running your "test1.py" file multiple times. The second time you run it, the `Person4` class is declared again which makes it techni... |
How to extract the first hit elements from an XML NCBI BLAST file? | 1,935,385 | 6 | 2009-12-20T09:44:19Z | 1,937,694 | 7 | 2009-12-21T01:03:29Z | [
"python",
"xml",
"bioinformatics",
"elementtree",
"ncbi"
] | Im trying to extract only the first hit from an NCBI xml BLAST file. next I would like to get only the first HSP. at the final stage I would like to get these based on best score.
to make things clear here a sample of the xml file:
```
<?xml version="1.0"?>
<!DOCTYPE BlastOutput PUBLIC "-//NCBI//NCBI BlastOutput/EN" "... | While building your own parser may be "fun" there is already a package out there that can parse BLAST xml files ... it can even do the intermediate calling of a local BLAST instance for you if you so desire.
The main site is here:
[http://biopython.org/wiki/Biopython](http://biopython.org/wiki/Main_Page)
and the XML ... |
Excluding last element in 0-based indexing | 1,935,990 | 2 | 2009-12-20T14:31:01Z | 1,936,048 | 8 | 2009-12-20T14:52:55Z | [
"python",
"arrays",
"programming-languages"
] | Once when I was reading some python docs I came across a reference to an article that explained why programming languages with 0-based indexing should always exclude the last element during operations like slicing:
```
>> a = [1, 2, 3]
>> a[0:1]
[1] #and not [1,2]
```
Unfortunately I did not bookmark it. Does anyone... | Could it be [this note](http://www.cs.utexas.edu/~EWD/ewd08xx/EWD831.PDF) from E. W. Dijkstra? |
Is it true that I can't use curly braces in Python? | 1,936,190 | 21 | 2009-12-20T15:57:52Z | 1,936,195 | 8 | 2009-12-20T15:59:50Z | [
"python"
] | I was reading that Python does all it's "code blocks" by indentation, rather than with curly braces. Is that right? So functions, if's and stuff like that all appear without surrounding their block with curly braces? | Yup :)
And there's (usually) a difference between 4 spaces and a tab, so make sure you standardize the usage .. |
Is it true that I can't use curly braces in Python? | 1,936,190 | 21 | 2009-12-20T15:57:52Z | 1,936,197 | 22 | 2009-12-20T16:00:20Z | [
"python"
] | I was reading that Python does all it's "code blocks" by indentation, rather than with curly braces. Is that right? So functions, if's and stuff like that all appear without surrounding their block with curly braces? | Yes. Curly braces are not used. Instead, you use the `:` symbol to introduce new blocks, like so:
```
if True:
do_something()
something_else()
else:
something()
``` |
Is it true that I can't use curly braces in Python? | 1,936,190 | 21 | 2009-12-20T15:57:52Z | 1,936,200 | 24 | 2009-12-20T16:01:43Z | [
"python"
] | I was reading that Python does all it's "code blocks" by indentation, rather than with curly braces. Is that right? So functions, if's and stuff like that all appear without surrounding their block with curly braces? | Correct for code blocks. However, you do define dictionaries in Python using curly braces:
```
a_dict = {
'key': 'value',
}
```
Ahhhhhh. |
Is it true that I can't use curly braces in Python? | 1,936,190 | 21 | 2009-12-20T15:57:52Z | 1,936,210 | 189 | 2009-12-20T16:04:23Z | [
"python"
] | I was reading that Python does all it's "code blocks" by indentation, rather than with curly braces. Is that right? So functions, if's and stuff like that all appear without surrounding their block with curly braces? | ```
if foo: #{
print "it's true"
#}
else: #{
print "it's false!"
#}
```
(Obviously, this is a joke.) |
Is it true that I can't use curly braces in Python? | 1,936,190 | 21 | 2009-12-20T15:57:52Z | 1,936,223 | 68 | 2009-12-20T16:07:44Z | [
"python"
] | I was reading that Python does all it's "code blocks" by indentation, rather than with curly braces. Is that right? So functions, if's and stuff like that all appear without surrounding their block with curly braces? | You can try to add support for braces using a [future import](http://python.org/doc/2.5.2/ref/future.html) statement, but it's not yet supported, so you'll get a syntax error:
```
>>> from __future__ import braces
File "<stdin>", line 1
SyntaxError: not a chance
``` |
Is it true that I can't use curly braces in Python? | 1,936,190 | 21 | 2009-12-20T15:57:52Z | 6,305,655 | 8 | 2011-06-10T11:24:03Z | [
"python"
] | I was reading that Python does all it's "code blocks" by indentation, rather than with curly braces. Is that right? So functions, if's and stuff like that all appear without surrounding their block with curly braces? | Use Whyton:
<http://writeonly.wordpress.com/2010/04/01/whython-python-for-people-who-hate-whitespace/> |
Sub-classing float type in Python, fails to catch exception in __init__() | 1,936,457 | 9 | 2009-12-20T17:51:35Z | 1,936,463 | 7 | 2009-12-20T17:54:54Z | [
"python",
"exception-handling"
] | On Python 2.5 I need to use float numbers with a modified `__str__()` method. Also I need to know when the constructor fails.
Why I can't catch exceptions raised from `float.__init__()`?
What is the best way to consult the numeric value of my derived float object? In my code I'm using `float(self)`.
```
class My_Num... | try `__new__` instead:
```
class F(float):
def __new__(cls, *arg, **kw):
try:
return float.__new__(cls, *arg, **kw)
except ValueError:
raise Exception("foo")
print F("3.5")
print F("asdf")
```
Also "self" is a float already so no need to say float(self), just "... |
Sub-classing float type in Python, fails to catch exception in __init__() | 1,936,457 | 9 | 2009-12-20T17:51:35Z | 1,936,487 | 17 | 2009-12-20T18:02:40Z | [
"python",
"exception-handling"
] | On Python 2.5 I need to use float numbers with a modified `__str__()` method. Also I need to know when the constructor fails.
Why I can't catch exceptions raised from `float.__init__()`?
What is the best way to consult the numeric value of my derived float object? In my code I'm using `float(self)`.
```
class My_Num... | `float` is immutable, therefore its `__init__`, the **initializer**, is basically a no-op -- nothing substantial can happen there, because the `self` object cannot be altered (if it's actually an instance of `float` rather than of a subclass -- but of course `float`'s own `__init__` must operate on that assumption;-).
... |
BeautifulSoup Grab Visible Webpage Text | 1,936,466 | 71 | 2009-12-20T17:55:58Z | 1,983,219 | 106 | 2009-12-31T00:06:12Z | [
"python",
"text",
"beautifulsoup",
"html-content-extraction"
] | Basically, I want to use BeautifulSoup to grab strictly the *visible text* on a webpage. For instance, [this webpage](http://www.nytimes.com/2009/12/21/us/21storm.html) is my test case. And I mainly want to just get the body text (article) and maybe even a few tab names here and there. I have tried the suggestion in th... | Try this:
```
html = urllib.urlopen('http://www.nytimes.com/2009/12/21/us/21storm.html').read()
soup = BeautifulSoup(html, 'html.parser')
texts = soup.findAll(text=True)
def visible(element):
if element.parent.name in ['style', 'script', '[document]', 'head', 'title']:
return False
elif re.match('<!--... |
BeautifulSoup Grab Visible Webpage Text | 1,936,466 | 71 | 2009-12-20T17:55:58Z | 19,760,007 | 17 | 2013-11-04T00:35:55Z | [
"python",
"text",
"beautifulsoup",
"html-content-extraction"
] | Basically, I want to use BeautifulSoup to grab strictly the *visible text* on a webpage. For instance, [this webpage](http://www.nytimes.com/2009/12/21/us/21storm.html) is my test case. And I mainly want to just get the body text (article) and maybe even a few tab names here and there. I have tried the suggestion in th... | The approved answer from @jbochi does not work for me. The str() function call raises an exception because it cannot encode the non-ascii characters in the BeautifulSoup element. Here is a more succinct way to filter the example web page to visible text.
```
html = open('21storm.html').read()
soup = BeautifulSoup(html... |
BeautifulSoup Grab Visible Webpage Text | 1,936,466 | 71 | 2009-12-20T17:55:58Z | 24,968,429 | 10 | 2014-07-26T06:54:26Z | [
"python",
"text",
"beautifulsoup",
"html-content-extraction"
] | Basically, I want to use BeautifulSoup to grab strictly the *visible text* on a webpage. For instance, [this webpage](http://www.nytimes.com/2009/12/21/us/21storm.html) is my test case. And I mainly want to just get the body text (article) and maybe even a few tab names here and there. I have tried the suggestion in th... | ```
import urllib
from bs4 import BeautifulSoup
url = "https://www.yahoo.com"
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
# kill all script and style elements
for script in soup(["script", "style"]):
script.extract() # rip it out
# get text
text = soup.get_text()
# break into lines and remov... |
How get sound input from microphone in python, and process it on the fly? | 1,936,828 | 32 | 2009-12-20T20:01:28Z | 1,937,058 | 25 | 2009-12-20T21:10:42Z | [
"python",
"microphone"
] | Greetings,
I'm trying to write a program in Python which would print a string every time it gets a tap in the microphone. When I say 'tap', I mean a loud sudden noise or something similar.
I searched in SO and found this post: <http://stackoverflow.com/questions/1797631/recognising-tone-of-the-audio>
I think PyAudio... | If you are using LINUX, you can use [pyALSAAUDIO](http://larsimmisch.github.io/pyalsaaudio/).
For windows, we have [PyAudio](http://people.csail.mit.edu/hubert/pyaudio/) and there is also a library called [SoundAnalyse](http://code.google.com/p/pygalaxy/wiki/SoundAnalyse).
I found an example for Linux [here](http://ub... |
exposing std::vector<double> with boost.python | 1,937,135 | 4 | 2009-12-20T21:31:21Z | 2,044,860 | 11 | 2010-01-11T20:55:54Z | [
"c++",
"python",
"boost-python"
] | I have written some C++ code that generates a std::vector.
I also have a python script that manipulates some data that, for now, I am declaring like this (below).
```
import numpy
x = numpy.random.randn(1000)
y = numpy.random.randn(1000)
```
I can run the script fine. From my C++ code:
```
using namespace boost... | The following code works for me (Python 2.6, Boost 1.39). This is almost the same as your code, except without the `BOOST_PYTHON_MODULE` line itself (but with the `class_` definition for the vector). `BOOST_PYTHON_MODULE` only needs to be used when creating extension modules.
```
#include <iostream>
#include <boost/py... |
How to iterate over a string using a buffer (python) | 1,937,519 | 2 | 2009-12-20T23:46:44Z | 1,937,545 | 12 | 2009-12-20T23:56:52Z | [
"python",
"string",
"iteration",
"buffer"
] | I'm trying to find some code that, given a string, will allow me to iterate over each line using the for loop construct, but with the added requirement that separate for loop constructs will not reset the iteration back to the beginning.
At the moment I have
```
sList = [line for line in theString.split(os.linesep)]
... | Just use a generator expression (genexp) instead of the list comprehension (listcomp) you're now using - i.e.:
```
sList = (line for line in theString.split(os.linesep))
```
that's all -- if you're otherwise happy with your code (splitting by os.linesep, even though normal text I/O in Python will already have transla... |
Convert date to datetime in Python | 1,937,622 | 329 | 2009-12-21T00:26:01Z | 1,937,629 | 68 | 2009-12-21T00:30:24Z | [
"python",
"datetime",
"date"
] | Silly question, but is there a built-in method for converting a `date` to a `datetime` in Python, ie. getting the `datetime` for the midnight of the `date`? The opposite conversion is easy - `datetime` has a `.date()` method. Do I really have to manually call `datetime(d.year, d.month, d.day)` ? | There are several ways, although I do believe the one you mention (and dislike) is the most readable one.
```
>>> t=datetime.date.today()
>>> datetime.datetime.fromordinal(t.toordinal())
datetime.datetime(2009, 12, 20, 0, 0)
>>> datetime.datetime(t.year, t.month, t.day)
datetime.datetime(2009, 12, 20, 0, 0)
>>> dateti... |
Convert date to datetime in Python | 1,937,622 | 329 | 2009-12-21T00:26:01Z | 1,937,631 | 30 | 2009-12-21T00:31:30Z | [
"python",
"datetime",
"date"
] | Silly question, but is there a built-in method for converting a `date` to a `datetime` in Python, ie. getting the `datetime` for the midnight of the `date`? The opposite conversion is easy - `datetime` has a `.date()` method. Do I really have to manually call `datetime(d.year, d.month, d.day)` ? | You can use the timetuple() method and varargs.
```
datetime.datetime(*(d.timetuple()[:6]))
``` |
Convert date to datetime in Python | 1,937,622 | 329 | 2009-12-21T00:26:01Z | 1,937,636 | 402 | 2009-12-21T00:33:40Z | [
"python",
"datetime",
"date"
] | Silly question, but is there a built-in method for converting a `date` to a `datetime` in Python, ie. getting the `datetime` for the midnight of the `date`? The opposite conversion is easy - `datetime` has a `.date()` method. Do I really have to manually call `datetime(d.year, d.month, d.day)` ? | You can use [datetime.combine](https://docs.python.org/2/library/datetime.html#datetime.datetime.combine)(date, time); for the time, you create a `datetime.time` object initialized to midnight.
```
from datetime import date
from datetime import datetime
d = date.today()
datetime.combine(d, datetime.min.time())
``` |
Convert date to datetime in Python | 1,937,622 | 329 | 2009-12-21T00:26:01Z | 22,514,625 | 23 | 2014-03-19T18:12:22Z | [
"python",
"datetime",
"date"
] | Silly question, but is there a built-in method for converting a `date` to a `datetime` in Python, ie. getting the `datetime` for the midnight of the `date`? The opposite conversion is easy - `datetime` has a `.date()` method. Do I really have to manually call `datetime(d.year, d.month, d.day)` ? | The accepted answer is correct, but I would prefer to avoid using `datetime.min.time()` because it's not obvious to me exactly what it does. If it's obvious to you, then more power to you. I also feel the same way about the `timetuple` method and the reliance on the ordering.
In my opinion, the most readable, explicit... |
High-precision clock in Python | 1,938,048 | 23 | 2009-12-21T03:41:54Z | 1,938,096 | 22 | 2009-12-21T03:57:29Z | [
"python",
"time"
] | Is there a way to measure time with high-precision in Python --- more precise than one second? I doubt that there is a cross-platform way of doing that; I'm interesting in high precision time on Unix, particularly Solaris running on a Sun SPARC machine.
[timeit](http://docs.python.org/library/timeit.html) seems to be ... | You can simply use the standard `time` module:
```
>>> import time
>>> time.time()
1261367718.971009
``` |
High-precision clock in Python | 1,938,048 | 23 | 2009-12-21T03:41:54Z | 1,940,109 | 11 | 2009-12-21T13:30:30Z | [
"python",
"time"
] | Is there a way to measure time with high-precision in Python --- more precise than one second? I doubt that there is a cross-platform way of doing that; I'm interesting in high precision time on Unix, particularly Solaris running on a Sun SPARC machine.
[timeit](http://docs.python.org/library/timeit.html) seems to be ... | You can also use time.clock() It counts the time used by the process on Unix and time since the first call to it on Windows. It's more precise than time.time().
It's the usually used function to measure performance.
Just call
```
import time
t_ = time.clock()
#Your code here
print 'Time in function', time.clock() - ... |
High-precision clock in Python | 1,938,048 | 23 | 2009-12-21T03:41:54Z | 3,444,174 | 14 | 2010-08-09T21:02:51Z | [
"python",
"time"
] | Is there a way to measure time with high-precision in Python --- more precise than one second? I doubt that there is a cross-platform way of doing that; I'm interesting in high precision time on Unix, particularly Solaris running on a Sun SPARC machine.
[timeit](http://docs.python.org/library/timeit.html) seems to be ... | Python tries hard to use the most precise time function for your platform to implement `time.time()`:
```
/* Implement floattime() for various platforms */
static double
floattime(void)
{
/* There are three ways to get the time:
(1) gettimeofday() -- resolution in microseconds
(2) ftime() -- resolutio... |
High-precision clock in Python | 1,938,048 | 23 | 2009-12-21T03:41:54Z | 21,301,124 | 11 | 2014-01-23T06:40:00Z | [
"python",
"time"
] | Is there a way to measure time with high-precision in Python --- more precise than one second? I doubt that there is a cross-platform way of doing that; I'm interesting in high precision time on Unix, particularly Solaris running on a Sun SPARC machine.
[timeit](http://docs.python.org/library/timeit.html) seems to be ... | David's post was attempting to show what the clock resolution is on Windows. I was confused by his output, so I wrote some code that shows that `time.time()` on my Windows 8 x64 laptop has a resolution of 1 msec:
```
# measure the smallest time delta by spinning until the time changes
def measure():
t0 = time.time... |
int object is not iterable? | 1,938,227 | 9 | 2009-12-21T04:42:14Z | 1,938,295 | 17 | 2009-12-21T05:01:38Z | [
"python",
"int",
"loops"
] | ```
inp = int(input("Enter a number:"))
for i in inp:
n = n + i;
print (n)
```
... throws an error: `'int' object is not iterable`
I wanted to find out the total by adding each digit, for eg, 110. 1 + 1 + 0 = 2. How do I do that?
Thanks | First, lose that absurd call to `int` -- which is taking you **farther** from what you want, so, what ever possessed you to put it in?! Change:
```
inp = int(input("Enter a number:"))
```
to the simpler
```
inp = input("Enter a number:")
```
so that `inp` is a string of digits and you can indeed loop over it, digit... |
Does anyone had success getting Django to send emails when hosting on Dreamhost? | 1,938,609 | 7 | 2009-12-21T06:57:48Z | 1,938,625 | 17 | 2009-12-21T07:06:43Z | [
"python",
"django",
"dreamhost"
] | Greetings,
Does anyone know what are the required fields to have Django send emails when a "500 Internal Server Error" happend? I am hosting my project on Dreamhost and for the life of me I can't get Django to send emails. What are the required fields when hosting on Dreamhost? | As proposed by S.Mark, you can use gmail. Here is what you need in your settings.py
```
ADMINS = (
('Your Name', 'your_name@email.com'),
)
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_PASSWORD = 'password'
EMAIL_HOST_USER = 'gmail_account'
EMAIL_SUBJECT_PREFIX = 'something'
EMAIL_USE_TLS = True
``` |
In what case would I use a tuple as a dictionary key? | 1,938,614 | 30 | 2009-12-21T07:01:29Z | 1,938,623 | 15 | 2009-12-21T07:06:10Z | [
"python",
"list",
"tuples"
] | I was studying the [difference between lists and tuples](http://www.python.org/doc/faq/general/#why-are-there-separate-tuple-and-list-data-types) (in Python). An obvious one is that tuples are immutable (the values cannot be changed after initial assignment), while lists are mutable.
A sentence in the article got me:
... | ```
salaries = {}
salaries[('John', 'Smith')] = 10000.0
salaries[('John', 'Parker')] = 99999.0
```
**EDIT 1**
Of course you can do `salaries['John Smith'] = whatever`, but then you'll have to do extra work to separate the key into first and last names. What about `pointColor[(x, y, z)] = "red"`, here the benefit of tu... |
In what case would I use a tuple as a dictionary key? | 1,938,614 | 30 | 2009-12-21T07:01:29Z | 1,938,638 | 43 | 2009-12-21T07:14:10Z | [
"python",
"list",
"tuples"
] | I was studying the [difference between lists and tuples](http://www.python.org/doc/faq/general/#why-are-there-separate-tuple-and-list-data-types) (in Python). An obvious one is that tuples are immutable (the values cannot be changed after initial assignment), while lists are mutable.
A sentence in the article got me:
... | Classic Example: You want to store point value as tuple of (x, y) |
Checking if A is superclass of B in Python | 1,938,755 | 20 | 2009-12-21T07:49:15Z | 1,938,779 | 30 | 2009-12-21T07:58:39Z | [
"python",
"reflection",
"superclass"
] | ```
class p1(object): pass
class p2(p1): pass
```
So p2 is the subclass of p1. Is there a way to find out programmatically that p1 is [one of] the superclass[es] of p2 ? | Yes, there is way. You can use a [issubclass](http://docs.python.org/library/functions.html#issubclass) function.
As follows:
```
class p1(object):pass
class p2(p1):pass
issubclass(p2, p1)
``` |
Checking if A is superclass of B in Python | 1,938,755 | 20 | 2009-12-21T07:49:15Z | 1,938,860 | 40 | 2009-12-21T08:24:07Z | [
"python",
"reflection",
"superclass"
] | ```
class p1(object): pass
class p2(p1): pass
```
So p2 is the subclass of p1. Is there a way to find out programmatically that p1 is [one of] the superclass[es] of p2 ? | using <class>.\_\_bases\_\_ seems to be what you're looking for...
```
>>> class p1(object): pass
>>> class p2(p1): pass
>>> p2.__bases__
(<class '__main__.p1'>,)
``` |
csv to sparse matrix in python | 1,938,894 | 6 | 2009-12-21T08:35:36Z | 1,939,102 | 10 | 2009-12-21T09:29:16Z | [
"python",
"data-structures",
"sparse-matrix"
] | I have a big csv file which lists connections between nodes in a graph. example:
0001,95784
0001,98743
0002,00082
0002,00091
So this means that node id 0001 is connected to node 95784 and 98743 and so on.
I need to read this into a sparse matrix in numpy. How can i do this?
I am new to python so tutorials on th... | Example using [lil\_matrix](http://www.scipy.org/doc/api%5Fdocs/SciPy.sparse.sparse.lil%5Fmatrix.html) (list of list matrix) of scipy.
> Row-based linked list matrix.
>
> This contains a list (`self.rows`) of rows, each of which is a sorted list of column indices of non-zero elements. It also contains a list (`self.da... |
Simple example of use of __setstate__ and __getstate__ | 1,939,058 | 25 | 2009-12-21T09:17:07Z | 1,939,384 | 23 | 2009-12-21T10:36:52Z | [
"python",
"serialization"
] | I don't know what the `__setstate__` and `__getstate__` methods do, so help me with a simple example. | Here's a very simple example for Python 2 that should supplement the [pickle docs](http://docs.python.org/library/pickle.html#pickle-protocol).
```
class Foo(object):
def __init__(self, val=2):
self.val = val
def __getstate__(self):
print "I'm being pickled"
self.val *= 2
return self.__dict__
... |
python libraries for ssh handling | 1,939,107 | 17 | 2009-12-21T09:31:28Z | 1,939,148 | 17 | 2009-12-21T09:41:15Z | [
"python",
"ssh",
"libraries",
"paramiko",
"pexpect"
] | I'm going to write first code for handling ssh commands on python and I did search over the stackoverflow and can see that there are several python libraries that can be used for handling commands passed through ssh, like [paramiko](https://github.com/paramiko/paramiko), [pexpect](http://pexpect.sourceforge.net/pexpect... | Libraries, Wrappers:
1. <http://media.commandline.org.uk/code/ssh.txt> (example usage: <http://commandline.org.uk/python/sftp-python-really-simple-ssh/>)
```
s = ssh.Connection('example.com', 'warrior', password = 'lennalenna')
s.put('/home/warrior/hello.txt', '/home/zombie/textfiles/report.txt')
s.get('/... |
python libraries for ssh handling | 1,939,107 | 17 | 2009-12-21T09:31:28Z | 1,939,188 | 14 | 2009-12-21T09:51:15Z | [
"python",
"ssh",
"libraries",
"paramiko",
"pexpect"
] | I'm going to write first code for handling ssh commands on python and I did search over the stackoverflow and can see that there are several python libraries that can be used for handling commands passed through ssh, like [paramiko](https://github.com/paramiko/paramiko), [pexpect](http://pexpect.sourceforge.net/pexpect... | Since you're not doing anything special at the protocol level, you presumably don't need the protocol to be entirely implemented in python, and you could simply run ssh/scp commands using the `subprocess` module.
```
import subprocess
subprocess.check_call(['ssh', 'server', 'command'])
subprocess.check_call(['scp', 's... |
Constructing a python set from a numpy matrix | 1,939,228 | 10 | 2009-12-21T10:02:03Z | 1,939,241 | 7 | 2009-12-21T10:06:42Z | [
"python",
"arrays",
"numpy",
"set"
] | I'm trying to execute the following
```
>> from numpy import *
>> x = array([[3,2,3],[4,4,4]])
>> y = set(x)
TypeError: unhashable type: 'numpy.ndarray'
```
How can I easily and efficiently create a set from a numpy array? | The immutable counterpart to an array is the tuple, hence, try convert the array of arrays into an array of tuples:
```
>> from numpy import *
>> x = array([[3,2,3],[4,4,4]])
>> x_hashable = map(tuple, x)
>> y = set(x_hashable)
set([(3, 2, 3), (4, 4, 4)])
``` |
Constructing a python set from a numpy matrix | 1,939,228 | 10 | 2009-12-21T10:02:03Z | 1,939,362 | 13 | 2009-12-21T10:31:18Z | [
"python",
"arrays",
"numpy",
"set"
] | I'm trying to execute the following
```
>> from numpy import *
>> x = array([[3,2,3],[4,4,4]])
>> y = set(x)
TypeError: unhashable type: 'numpy.ndarray'
```
How can I easily and efficiently create a set from a numpy array? | If you want a set of the elements, here is another, probably faster way:
```
y = set(x.flatten())
```
PS: after performing comparisons between `x.flat`, `x.flatten()`, and `x.ravel()` on a 10x100 array, I found out that they all perform at about the same speed. For a 3x3 array, the fastest version is the iterator ver... |
Python sorts "u11-Phrase 1000.wav" before "u11-Phrase 101.wav"; how can I overcome this? | 1,940,056 | 6 | 2009-12-21T13:17:45Z | 1,940,088 | 16 | 2009-12-21T13:23:39Z | [
"python",
"sorting"
] | I'm running Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win 32
When I'm asking Python
```
>>> "u11-Phrase 099.wav" < "u11-Phrase 1000.wav"
True
```
That's fine. When I ask
```
>>> "u11-Phrase 100.wav" < "u11-Phrase 1000.wav"
True
```
That's fine, too. **But** when I ask
```
>>> ... | You are looking for [human sorting](http://nedbatchelder.com/blog/200712/human%5Fsorting.html).
The reason 101.wav is not less than 1000.wav is that computers (not just Python) sort strings character by character, and the first difference between these two strings is where the first string has a '1' and the second str... |
Python sorts "u11-Phrase 1000.wav" before "u11-Phrase 101.wav"; how can I overcome this? | 1,940,056 | 6 | 2009-12-21T13:17:45Z | 1,940,105 | 9 | 2009-12-21T13:29:23Z | [
"python",
"sorting"
] | I'm running Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win 32
When I'm asking Python
```
>>> "u11-Phrase 099.wav" < "u11-Phrase 1000.wav"
True
```
That's fine. When I ask
```
>>> "u11-Phrase 100.wav" < "u11-Phrase 1000.wav"
True
```
That's fine, too. **But** when I ask
```
>>> ... | You need to construct a proper sort key for each filename. Something like this should do what you want:
```
import re
def k(s):
return [w.isdigit() and int(w) or w for w in re.split(r'(\d+)', s)]
files = ["u11-Phrase 099.wav", "u11-Phrase 1000.wav", "u11-Phrase 100.wav"]
print files
print sorted(files, key=k)
`... |
Django index page best/most common practice | 1,940,528 | 20 | 2009-12-21T14:51:08Z | 1,940,720 | 19 | 2009-12-21T15:24:57Z | [
"python",
"django",
"indexing"
] | I am working on a site currently (first one solo) and went to go make an index page. I have been attempting to follow django best practices as I go, so naturally I go search for this but couldn't a real standard in regards to this.
I have seen folks creating apps to serve this purpose named various things (main, home,... | If all of your dynamic content is handled in the template (for example, if it's just simple checking if a user is present on the request), then I recommend using a generic view, specificially the [direct to template](http://docs.djangoproject.com/en/1.1/ref/generic-views/#django-views-generic-simple-direct-to-template)... |
WindowsError: [Error 126] The specified module could not be found | 1,940,578 | 7 | 2009-12-21T14:59:12Z | 6,087,086 | 8 | 2011-05-22T09:31:06Z | [
"python",
"ctypes"
] | I am loading a dll in python using following code:
```
if os.path.exists(dll_path):
my_dll = ctypes.cdll.LoadLibrary(dll_path)
```
But I am continuously getting the following error
**WindowsError: [Error 126] The specified module could not be found**
dll is present at the specified path, but I didn't understan... | When I see things like this - it is usually because there are backslashes in the path which get converted.
For example - the following will fail - because \t in the string is converted to TAB character.
```
>>> import ctypes
>>> ctypes.windll.LoadLibrary("c:\tools\depends\depends.dll")
Traceback (most recent call las... |
WindowsError: [Error 126] The specified module could not be found | 1,940,578 | 7 | 2009-12-21T14:59:12Z | 25,492,172 | 8 | 2014-08-25T18:28:40Z | [
"python",
"ctypes"
] | I am loading a dll in python using following code:
```
if os.path.exists(dll_path):
my_dll = ctypes.cdll.LoadLibrary(dll_path)
```
But I am continuously getting the following error
**WindowsError: [Error 126] The specified module could not be found**
dll is present at the specified path, but I didn't understan... | Note that even if the DLL is in your path. If that DLL relies on other DLLs that are NOT in your path, you can get the same error. Windows could not find a dependency in this case. Windows is not real good at telling you what it could not find, only that it did not find something. It is up to you to figure that out. Th... |
Syntax quirks or why is that valid python | 1,940,710 | 7 | 2009-12-21T15:23:16Z | 1,940,715 | 8 | 2009-12-21T15:24:16Z | [
"python",
"syntax"
] | In python 2.6, why is the following line valid?
```
my_line = 'foo' 'bar'
```
and if that is valid, why isn't the following:
```
my_list = 1 2
```
The first example is string concatenation, however, the following isn't valid either (thanks god):
```
foo = 'foo'
bar = 'bar'
foo_bar = foo bar
``` | `my_line = 'foo' 'bar'` is string concatenation. |
Syntax quirks or why is that valid python | 1,940,710 | 7 | 2009-12-21T15:23:16Z | 1,940,793 | 20 | 2009-12-21T15:36:25Z | [
"python",
"syntax"
] | In python 2.6, why is the following line valid?
```
my_line = 'foo' 'bar'
```
and if that is valid, why isn't the following:
```
my_list = 1 2
```
The first example is string concatenation, however, the following isn't valid either (thanks god):
```
foo = 'foo'
bar = 'bar'
foo_bar = foo bar
``` | This is doing [string literal concatenation](http://docs.python.org/reference/lexical%5Fanalysis.html#string-literal-concatenation). As noted in the documentation, advantages include the following:
> This feature can be used to reduce the
> number of backslashes needed, to split
> long strings conveniently across long... |
Upper limit in Python time.sleep()? | 1,941,177 | 2 | 2009-12-21T16:39:12Z | 1,941,697 | 7 | 2009-12-21T18:14:01Z | [
"python",
"time",
"limit",
"sleep"
] | Is there an upper limit to how long you can specify a thread to sleep with time.sleep()? I have been having issues with sleeping my script for long periods (i.e., over 1k seconds). This issue has appeared on both Windows and Unix platforms. | Others have explained why you might sleep for less than you asked for, but didn't show you how to deal with this. If you need to make sure you sleep for at least n seconds you can use code like:
```
from time import time, sleep
def trusty_sleep(n):
start = time()
while (time() - start < n):
sleep(n - (... |
Python, Huge Iteration Performance Problem | 1,941,712 | 9 | 2009-12-21T18:16:07Z | 1,941,852 | 10 | 2009-12-21T18:42:06Z | [
"python",
"iteration",
"bioinformatics"
] | I'm doing an iteration through 3 words, each about 5 million characters long, and I want to find sequences of 20 characters that identifies each word. That is, I want to find all sequences of length 20 in one word that is unique for that word. My problem is that the code I've written takes an extremely long time to run... | ```
def slices(seq, length, prefer_last=False):
unique = {}
if prefer_last: # this doesn't have to be a parameter, just choose one
for start in xrange(len(seq) - length + 1):
unique[seq[start:start+length]] = start
else: # prefer first
for start in xrange(len(seq) - length, -1, -1):
unique[seq... |
Convert an RFC 3339 time to a standard Python timestamp | 1,941,927 | 14 | 2009-12-21T19:00:30Z | 1,941,968 | 9 | 2009-12-21T19:06:26Z | [
"python",
"datetime",
"rfc3339"
] | Is there an easy way to convert an [RFC 3339](http://www.ietf.org/rfc/rfc3339.txt) time into a regular Python timestamp?
I've got a script which is reading an ATOM feed and I'd like to be able to compare the timestamp of an item in the ATOM feed to the modification time of a file.
I notice from the [ATOM spec](http:/... | No builtin, afaik.
**feed.date.rfc3339**
This is a Python library module with functions for converting timestamp strings in RFC 3339 format to Python time float values, and vice versa. RFC 3339 is the timestamp format used by the Atom feed syndication format.
It is BSD-licensed.
<http://home.blarg.net/~steveha/pyfee... |
Convert an RFC 3339 time to a standard Python timestamp | 1,941,927 | 14 | 2009-12-21T19:00:30Z | 1,942,000 | 7 | 2009-12-21T19:13:29Z | [
"python",
"datetime",
"rfc3339"
] | Is there an easy way to convert an [RFC 3339](http://www.ietf.org/rfc/rfc3339.txt) time into a regular Python timestamp?
I've got a script which is reading an ATOM feed and I'd like to be able to compare the timestamp of an item in the ATOM feed to the modification time of a file.
I notice from the [ATOM spec](http:/... | <http://pypi.python.org/pypi/iso8601/> seems to be able to parse iso 8601, which RFC 3339 is a subset of, maybe this could be useful, but again, not built-in. |
Convert an RFC 3339 time to a standard Python timestamp | 1,941,927 | 14 | 2009-12-21T19:00:30Z | 1,942,049 | 18 | 2009-12-21T19:20:43Z | [
"python",
"datetime",
"rfc3339"
] | Is there an easy way to convert an [RFC 3339](http://www.ietf.org/rfc/rfc3339.txt) time into a regular Python timestamp?
I've got a script which is reading an ATOM feed and I'd like to be able to compare the timestamp of an item in the ATOM feed to the modification time of a file.
I notice from the [ATOM spec](http:/... | You don't include an example, but if you don't have a Z-offset or timezone, and assuming you don't want durations but just the basic time, then maybe this will suit you:
```
import datetime as dt
>>> dt.datetime.strptime('1985-04-12T23:20:50.52', '%Y-%m-%dT%H:%M:%S.%f')
datetime.datetime(1985, 4, 12, 23, 20, 50, 52000... |
Python 3: create a list of possible ip addresses from a CIDR notation | 1,942,160 | 5 | 2009-12-21T19:39:03Z | 1,942,848 | 15 | 2009-12-21T21:50:12Z | [
"python",
"subnet",
"cidr"
] | I have been handed the task of creating a function in python (3.1) that will take a CIDR notation and return the list of possible ip addresses. I have looked around python.org and found this:
<http://docs.python.org/dev/py3k/library/ipaddr.html>
but i haven't seen anything that will fill this need... I would be very g... | If you aren't married to using the built-in module, there is a project called [netaddr](http://code.google.com/p/netaddr/) that is the best module I have used for working with IP networks.
Have a look at the [IP Tutorial](http://code.google.com/p/netaddr/wiki/IPTutorial) which illustrates how easy it is working with n... |
Wrapping a C library in Python: C, Cython or ctypes? | 1,942,298 | 185 | 2009-12-21T20:05:51Z | 1,942,321 | 18 | 2009-12-21T20:09:31Z | [
"python",
"c",
"ctypes",
"cython"
] | I want to call a C library from a Python application. I don't want to wrap the whole API, only the functions and datatypes that are relevant to my case. As I see it, I have three choices:
1. Create an actual extension module in C. Probably overkill, and I'd also like to avoid the overhead of learning extension writing... | I'll throw another one out there: [SWIG](http://www.swig.org/Doc1.3/Python.html)
It's easy to learn, does a lot of things right, and supports many more languages so the time spent learning it can be pretty useful.
If you use SWIG, you are creating a new python extension module, but with SWIG doing most of the heavy l... |
Wrapping a C library in Python: C, Cython or ctypes? | 1,942,298 | 185 | 2009-12-21T20:05:51Z | 1,942,437 | 84 | 2009-12-21T20:32:22Z | [
"python",
"c",
"ctypes",
"cython"
] | I want to call a C library from a Python application. I don't want to wrap the whole API, only the functions and datatypes that are relevant to my case. As I see it, I have three choices:
1. Create an actual extension module in C. Probably overkill, and I'd also like to avoid the overhead of learning extension writing... | Cython is a pretty cool tool in itself, well worth learning, and is surprisingly close to the Python syntax. If you do any scientific computing with Numpy, then Cython is the way to go because it integrates with Numpy for fast matrix operations.
Cython is a superset of Python language. You can throw any valid Python f... |
Wrapping a C library in Python: C, Cython or ctypes? | 1,942,298 | 185 | 2009-12-21T20:05:51Z | 1,942,468 | 15 | 2009-12-21T20:36:42Z | [
"python",
"c",
"ctypes",
"cython"
] | I want to call a C library from a Python application. I don't want to wrap the whole API, only the functions and datatypes that are relevant to my case. As I see it, I have three choices:
1. Create an actual extension module in C. Probably overkill, and I'd also like to avoid the overhead of learning extension writing... | Personally, I'd write an extension module in C. Don't be intimidated by Python C extensions -- they're not hard at all to write. The documentation is very clear and helpful. When I first wrote a C extension in Python, I think it took me about an hour to figure out how to write one -- not much time at all. |
Wrapping a C library in Python: C, Cython or ctypes? | 1,942,298 | 185 | 2009-12-21T20:05:51Z | 1,942,472 | 76 | 2009-12-21T20:37:14Z | [
"python",
"c",
"ctypes",
"cython"
] | I want to call a C library from a Python application. I don't want to wrap the whole API, only the functions and datatypes that are relevant to my case. As I see it, I have three choices:
1. Create an actual extension module in C. Probably overkill, and I'd also like to avoid the overhead of learning extension writing... | `ctypes` is your best bet for getting it done quickly, and it's a pleasure to work with as you're still writing Python!
I recently wrapped an [FTDI](http://www.ftdichip.com/) driver for communicating with a USB chip using ctypes and it was great. I had it all done and working in less than one work day. (I only impleme... |
Wrapping a C library in Python: C, Cython or ctypes? | 1,942,298 | 185 | 2009-12-21T20:05:51Z | 1,942,482 | 9 | 2009-12-21T20:37:56Z | [
"python",
"c",
"ctypes",
"cython"
] | I want to call a C library from a Python application. I don't want to wrap the whole API, only the functions and datatypes that are relevant to my case. As I see it, I have three choices:
1. Create an actual extension module in C. Probably overkill, and I'd also like to avoid the overhead of learning extension writing... | If you have already a library with a defined API, I think `ctypes` is the best option, as you only have to do a little initialization and then more or less call the library the way you're used to.
I think Cython or creating an extension module in C (which is not very difficult) are more useful when you need new code, ... |
Wrapping a C library in Python: C, Cython or ctypes? | 1,942,298 | 185 | 2009-12-21T20:05:51Z | 1,966,170 | 9 | 2009-12-27T15:13:27Z | [
"python",
"c",
"ctypes",
"cython"
] | I want to call a C library from a Python application. I don't want to wrap the whole API, only the functions and datatypes that are relevant to my case. As I see it, I have three choices:
1. Create an actual extension module in C. Probably overkill, and I'd also like to avoid the overhead of learning extension writing... | [ctypes](http://python.net/crew/theller/ctypes/) is great when you've already got a compiled library blob to deal with (such as OS libraries). The calling overhead is severe, however, so if you'll be making a lot of calls into the library, and you're going to be writing the C code anyway (or at least compiling it), I'd... |
Wrapping a C library in Python: C, Cython or ctypes? | 1,942,298 | 185 | 2009-12-21T20:05:51Z | 5,686,873 | 89 | 2011-04-16T13:41:45Z | [
"python",
"c",
"ctypes",
"cython"
] | I want to call a C library from a Python application. I don't want to wrap the whole API, only the functions and datatypes that are relevant to my case. As I see it, I have three choices:
1. Create an actual extension module in C. Probably overkill, and I'd also like to avoid the overhead of learning extension writing... | Warning: a Cython core developer's opinion ahead.
I almost always recommend Cython over ctypes. The reason is that it has a much smoother upgrade path. If you use ctypes, many things will be simple at first, and it's certainly cool to write your FFI code in plain Python, without compilation, build dependencies and all... |
Wrapping a C library in Python: C, Cython or ctypes? | 1,942,298 | 185 | 2009-12-21T20:05:51Z | 14,942,060 | 26 | 2013-02-18T17:33:30Z | [
"python",
"c",
"ctypes",
"cython"
] | I want to call a C library from a Python application. I don't want to wrap the whole API, only the functions and datatypes that are relevant to my case. As I see it, I have three choices:
1. Create an actual extension module in C. Probably overkill, and I'd also like to avoid the overhead of learning extension writing... | For calling a C library from a Python application there is also [**cffi**](http://cffi.readthedocs.org/en/latest/) which is a new alternative for *ctypes*. It brings a fresh look for FFI:
* it handles the problem in a fascinating, clean way (as opposed to *ctypes*)
* it doesn't require to write non Python code (as in ... |
Add a member variable / method to a Python generator? | 1,942,328 | 5 | 2009-12-21T20:10:17Z | 1,942,387 | 8 | 2009-12-21T20:21:10Z | [
"python",
"generator",
"local"
] | Can I add a member variable / method to a Python generator?
I want something along the following lines, so that I can "peek" at member variable j:
```
def foo():
for i in range(10):
self.j = 10 - i
yield i
gen = foo()
for k in gen:
print gen.j
print k
```
Yes, I know that I can return i ... | You could create an object and manipulate the [\_\_iter\_\_](http://docs.python.org/library/stdtypes.html#container.%5F%5Fiter%5F%5F) interface:
```
class Foo(object):
def __init__(self):
self.j = None
def __iter__(self):
for i in range(10):
self.j = 10 - i
yield i
my_g... |
Python regular expression inconsistency | 1,943,400 | 2 | 2009-12-21T23:54:19Z | 1,943,414 | 12 | 2009-12-21T23:59:01Z | [
"python",
"regex",
"documentation"
] | I am getting different results based on whether I precompile a regular expression:
```
>>> re.compile('mr', re.IGNORECASE).sub('', 'Mr Bean')
' Bean'
>>> re.sub('mr', '', 'Mr Bean', re.IGNORECASE)
'Mr Bean'
```
The [Python documentation](http://docs.python.org/library/re.html) says *Some of the functions are simplifi... | `re.sub()` can't accept the `re.IGNORECASE`, it appears.
The documentation states:
> `sub(pattern, repl, string, count=0)`
>
> ```
> Return the string obtained by replacing the leftmost
> non-overlapping occurrences of the pattern in string by the
> replacement repl. repl can be either a string or a callable;
> if a... |
Python logging before you run logging.basicConfig? | 1,943,747 | 24 | 2009-12-22T01:46:53Z | 1,943,809 | 9 | 2009-12-22T02:05:27Z | [
"python",
"logging"
] | It appears that if you invoke logging.info() **BEFORE** you run logging.basicConfig, the logging.basicConfig call doesn't have any effect. In fact, no logging occurs.
Where is this behavior documented? I don't really understand. | Yes.
You've asked to log something. Logging must, therefore, fabricate a default configuration. Once logging is configured... well... it's configured.
> "With the logger object configured,
> the following methods create log
> messages:"
Further, you can read about creating handlers to prevent spurious logging. But t... |
Python logging before you run logging.basicConfig? | 1,943,747 | 24 | 2009-12-22T01:46:53Z | 2,588,054 | 26 | 2010-04-06T20:28:07Z | [
"python",
"logging"
] | It appears that if you invoke logging.info() **BEFORE** you run logging.basicConfig, the logging.basicConfig call doesn't have any effect. In fact, no logging occurs.
Where is this behavior documented? I don't really understand. | You can remove the default handlers and reconfigure logging like this:
```
# if someone tried to log something before basicConfig is called, Python creates a default handler that
# goes to the console and will ignore further basicConfig calls. Remove the handler if there is one.
root = logging.getLogger()
if root.hand... |
How to get value on a certain index, in a python list? | 1,943,824 | 6 | 2009-12-22T02:10:45Z | 1,943,831 | 11 | 2009-12-22T02:13:06Z | [
"python"
] | I have a list which looks something like this
```
List = [q1,a1,q2,a2,q3,a3]
```
I need the final code to be something like this
```
dictionary = {q1:a1,q2:a2,q3:a3}
```
if only I can get values at a certain index e.g List[0] I can accomplish this, is there any way I can get it? | Python dictionaries can be constructed using the `dict` class, given an iterable containing tuples. We can use this in conjunction with the `range` builtin to produce a collection of tuples as in (every-odd-item, every-even-item), and pass it to `dict`, such that the values organize themselves into key/value pairs in t... |
How to get value on a certain index, in a python list? | 1,943,824 | 6 | 2009-12-22T02:10:45Z | 1,943,849 | 12 | 2009-12-22T02:20:21Z | [
"python"
] | I have a list which looks something like this
```
List = [q1,a1,q2,a2,q3,a3]
```
I need the final code to be something like this
```
dictionary = {q1:a1,q2:a2,q3:a3}
```
if only I can get values at a certain index e.g List[0] I can accomplish this, is there any way I can get it? | Using extended slice notation:
```
dictionary = dict(zip(List[0::2], List[1::2]))
``` |
How do I write good/correct package __init__.py files | 1,944,569 | 112 | 2009-12-22T06:48:52Z | 1,944,610 | 78 | 2009-12-22T06:59:24Z | [
"python",
"packages"
] | My package has the following structure:
```
mobilescouter/
__init__.py #1
mapper/
__init__.py #2
lxml/
__init__.py #3
vehiclemapper.py
vehiclefeaturemapper.py
vehiclefeaturesetmapper.py
...
basemapper.py
vehicle/
__init... | My own `__init__.py` files are empty more often than not. In particular, I never have a `from blah import *` as part of `__init__.py` -- if "importing the package" means getting all sort of classes, functions etc defined directly as part of the package, then I would lexically copy the contents of `blah.py` into the pac... |
How do I write good/correct package __init__.py files | 1,944,569 | 112 | 2009-12-22T06:48:52Z | 1,947,834 | 75 | 2009-12-22T17:16:14Z | [
"python",
"packages"
] | My package has the following structure:
```
mobilescouter/
__init__.py #1
mapper/
__init__.py #2
lxml/
__init__.py #3
vehiclemapper.py
vehiclefeaturemapper.py
vehiclefeaturesetmapper.py
...
basemapper.py
vehicle/
__init... | `__all__` is very good - it helps guide import statements without automatically importing modules
<http://docs.python.org/tutorial/modules.html#importing-from-a-package>
using `__all__` and `import *` is redundant, only `__all__` is needed
I think one of the most powerful reasons to use `import *` in an `__init__.py`... |
What is the relationship between __getattr__ and getattr? | 1,944,625 | 25 | 2009-12-22T07:04:18Z | 1,944,663 | 31 | 2009-12-22T07:14:16Z | [
"python",
"getattr"
] | I know this code is right:
```
class A:
def __init__(self):
self.a = 'a'
def method(self):
print "method print"
a = A()
print getattr(a, 'a', 'default')
print getattr(a, 'b', 'default')
print getattr(a, 'method', 'default')
getattr(a, 'method', 'default')()
```
And this is ... | `getattr` is a built-in function taking (at least) two arguments: the object from which you're getting the attribute, and the string name of the attribute.
If the string name is a constant, say `'foo'`, `getattr(obj, 'foo')` is **exactly the same thing** as `obj.foo`.
So, the main use case for the built-in function `... |
What is the relationship between __getattr__ and getattr? | 1,944,625 | 25 | 2009-12-22T07:04:18Z | 1,944,708 | 43 | 2009-12-22T07:26:49Z | [
"python",
"getattr"
] | I know this code is right:
```
class A:
def __init__(self):
self.a = 'a'
def method(self):
print "method print"
a = A()
print getattr(a, 'a', 'default')
print getattr(a, 'b', 'default')
print getattr(a, 'method', 'default')
getattr(a, 'method', 'default')()
```
And this is ... | Alex's answer was good, but providing you with a sample code since you asked for it :)
```
class foo:
def __init__(self):
self.a = "a"
def __getattr__(self, attribute):
return "You asked for %s, but I'm giving you default" % attribute
>>> bar = foo()
>>> bar.a
'a'
>>> bar.b
"You asked for b, ... |
What is the relationship between __getattr__ and getattr? | 1,944,625 | 25 | 2009-12-22T07:04:18Z | 1,944,714 | 11 | 2009-12-22T07:28:59Z | [
"python",
"getattr"
] | I know this code is right:
```
class A:
def __init__(self):
self.a = 'a'
def method(self):
print "method print"
a = A()
print getattr(a, 'a', 'default')
print getattr(a, 'b', 'default')
print getattr(a, 'method', 'default')
getattr(a, 'method', 'default')()
```
And this is ... | `__getattr__()` is a special method function that you can define. When a member lookup fails, this function will be called.
`getattr()` is a function you can call to attempt a member lookup. If the lookup succeeds, you get the member (perhaps a method function object, or perhaps a data attribute object). `getattr()` c... |
Python Format string "}" fill | 1,945,230 | 3 | 2009-12-22T09:37:28Z | 1,945,687 | 7 | 2009-12-22T11:05:20Z | [
"python",
"string-formatting"
] | Python 2.6 defines [`str.format(â¦)`](http://docs.python.org/library/stdtypes.html#str.format), which, from Python 3.0, is preferred to the old `%` style of string formatting. Looking at the "[mini-language](http://docs.python.org/library/string.html#format-specification-mini-language)", however, it seems that it is i... | You could always specify it as a separate parameter like so:
```
>>> "The word is {0:{1}<10}".format("spam", "}")
'The word is spam}}}}}}'
```
See, it gets passed in and used in place of {1}. |
Why does the following code always output 16? | 1,945,270 | 4 | 2009-12-22T09:45:51Z | 1,945,321 | 23 | 2009-12-22T09:54:41Z | [
"python"
] | ```
def makeActions():
acts=[]
for i in range(5):
print len(acts)
acts.append(lambda x: i ** x)
print acts[i]
return acts
acts=makeActions()
for i in range(5):
print acts[i](2)
```
Output:
```
16
16
16
16
16
```
Expected output:
```
0
1
4
9
16
``` | Because the `i` in the lambda is probably not what you expect. To verify this, change the code:
```
acts.append(lambda x: (i, i ** x))
```
Now the `print` tells you the value of `i`:
```
(4, 16)
(4, 16)
(4, 16)
(4, 16)
(4, 16)
```
This means that the `lambda` doesn't copy the value of `i` but keeps a reference to t... |
python add a new div every 3rd iteration | 1,945,379 | 13 | 2009-12-22T10:05:45Z | 1,945,399 | 7 | 2009-12-22T10:08:56Z | [
"python",
"django-templates"
] | I have a product list that put 3 products on a row and clears the row and adds another 3, this works fine everywhere but IE6, i know that adding `<div>` around each group of 3 products will solve this is the template file at the moment
```
{% for product in category.products.all %}
<div class="{% cycle 'clear' ''... | Use `forloop.counter` and a modulo operator inside the loop:
```
{% for ... %}
{% if forloop.counter|divisibleby:3 %}<div>{% endif %}
...
{% if forloop.counter|divisibleby:3 %}</div>{% endif %}
{% endfor %}
```
See <http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for>
**EDIT:**
Fixed the code example. |
python add a new div every 3rd iteration | 1,945,379 | 13 | 2009-12-22T10:05:45Z | 1,945,620 | 29 | 2009-12-22T10:54:50Z | [
"python",
"django-templates"
] | I have a product list that put 3 products on a row and clears the row and adds another 3, this works fine everywhere but IE6, i know that adding `<div>` around each group of 3 products will solve this is the template file at the moment
```
{% for product in category.products.all %}
<div class="{% cycle 'clear' ''... | codeape's solution only works if you are using a very recent SVN checkout of Django trunk. If you're using version 1.1 or below, that syntax is not supported.
Instead, you can use the `divisibleby` filter:
```
{% if forloop.counter|divisibleby:3 %}<div>{% endif %}
``` |
Why doesn't os.path.join() work in this case? | 1,945,920 | 135 | 2009-12-22T11:53:28Z | 1,945,930 | 187 | 2009-12-22T11:55:44Z | [
"python",
"path"
] | The below code will not join, when debugged the command does not store the whole path but just the last entry.
```
os.path.join('/home/build/test/sandboxes/', todaystr, '/new_sandbox/')
```
When I test this it only stores the `/new_sandbox/` part of the code. | The latter strings shouldn't start with a slash. If they start with a slash, then they're considered an "absolute path" and everything before them is discarded.
Quoting the [Python docs for `os.path.join`](http://docs.python.org/library/os.path.html#os.path.join):
> If any component is an absolute path, all previous ... |
Why doesn't os.path.join() work in this case? | 1,945,920 | 135 | 2009-12-22T11:53:28Z | 1,945,935 | 9 | 2009-12-22T11:56:54Z | [
"python",
"path"
] | The below code will not join, when debugged the command does not store the whole path but just the last entry.
```
os.path.join('/home/build/test/sandboxes/', todaystr, '/new_sandbox/')
```
When I test this it only stores the `/new_sandbox/` part of the code. | do not use forward slashes at the beginning of path components, except when refering to the root dir:
```
os.path.join('/home/build/test/sandboxes', todaystr, 'new_sandbox')
```
see also: <http://docs.python.org/library/os.path.html#os.path.join> |
Why doesn't os.path.join() work in this case? | 1,945,920 | 135 | 2009-12-22T11:53:28Z | 1,945,939 | 8 | 2009-12-22T11:57:06Z | [
"python",
"path"
] | The below code will not join, when debugged the command does not store the whole path but just the last entry.
```
os.path.join('/home/build/test/sandboxes/', todaystr, '/new_sandbox/')
```
When I test this it only stores the `/new_sandbox/` part of the code. | It's because your `'/new_sandbox/'` begins with a `/` and thus is assumed to be relative to the root directory. Remove the leading `/`. |
Why doesn't os.path.join() work in this case? | 1,945,920 | 135 | 2009-12-22T11:53:28Z | 1,948,595 | 99 | 2009-12-22T19:29:50Z | [
"python",
"path"
] | The below code will not join, when debugged the command does not store the whole path but just the last entry.
```
os.path.join('/home/build/test/sandboxes/', todaystr, '/new_sandbox/')
```
When I test this it only stores the `/new_sandbox/` part of the code. | The idea of `os.path.join()` is to make your program cross-platform (linux/win32/etc).
Even one slash ruins it.
So it only makes sense when being used with some kind of reference point like
`os.environ['HOME']` or `os.path.dirname(__file__)`. |
Why doesn't os.path.join() work in this case? | 1,945,920 | 135 | 2009-12-22T11:53:28Z | 14,962,135 | 36 | 2013-02-19T16:14:54Z | [
"python",
"path"
] | The below code will not join, when debugged the command does not store the whole path but just the last entry.
```
os.path.join('/home/build/test/sandboxes/', todaystr, '/new_sandbox/')
```
When I test this it only stores the `/new_sandbox/` part of the code. | `os.path.join()` can be used in conjunction with `os.path.sep()` to create an absolute rather than relative path.
```
os.path.join(os.path.sep, 'home','build','test','sandboxes',todaystr,'new_sandbox')
``` |
In Django, How do I get escaped html in HttpResponse? | 1,946,281 | 4 | 2009-12-22T13:07:26Z | 11,558,474 | 10 | 2012-07-19T10:06:39Z | [
"python",
"django",
"django-templates",
"escaping",
"httpresponse"
] | The following code in one of my views returns unescaped html string which cannot be parsed in frontend since it is an Ajax request.
```
return render_to_response(template_name, {
'form': form,
redirect_field_name: redirect_to,
'site': current_site,
'site_name': current_site.name,
},... | **Lakshman Prasad**'s answer is technically correct, but a bit cumbersome. A better way to *escape* text would be (as suggested in a comment by **miku** above):
```
from django.utils.html import escape
return HttpResponse(escape(some_string))
``` |
How does the Python conditional operator workaround work? | 1,947,030 | 21 | 2009-12-22T15:22:26Z | 1,947,050 | 9 | 2009-12-22T15:24:40Z | [
"python",
"indexing",
"boolean",
"conditional-operator"
] | From what I have read, I found that a built-in ternary operator does not exist (I will be happy to know more about it.).
I found the following code as a substitute:
```
def val():
var = float(raw_input("Age:"))
status = ("Working","Retired")[var>65]
print "You should be:",status
```
I couldn't understand... | Python (2.5 and above) does indeed have a syntax for what you are looking for:
```
x = foo if condition else bar
```
If `condition` is True, `x` will be set to `foo`, otherwise it will be set to `bar`.
Examples:
```
>>> age = 68
>>> x = 'Retired' if age > 65 else 'Working'
>>> x
'Retired'
>>> age = 35
>>> y = 'Reti... |
How does the Python conditional operator workaround work? | 1,947,030 | 21 | 2009-12-22T15:22:26Z | 1,947,102 | 8 | 2009-12-22T15:31:01Z | [
"python",
"indexing",
"boolean",
"conditional-operator"
] | From what I have read, I found that a built-in ternary operator does not exist (I will be happy to know more about it.).
I found the following code as a substitute:
```
def val():
var = float(raw_input("Age:"))
status = ("Working","Retired")[var>65]
print "You should be:",status
```
I couldn't understand... | because True casts to 1 and False casts to 0 so if var = 70
```
("Working","Retired")[var>65]
```
becomes
```
("Working", "Retired")[1]
```
a nice little shortcut ... but I find it can be a little confusing with anything but a simple condition, so I would go with TM's suggestion
```
"Retired" if var > 65 else "Wor... |
How does the Python conditional operator workaround work? | 1,947,030 | 21 | 2009-12-22T15:22:26Z | 1,947,109 | 51 | 2009-12-22T15:31:54Z | [
"python",
"indexing",
"boolean",
"conditional-operator"
] | From what I have read, I found that a built-in ternary operator does not exist (I will be happy to know more about it.).
I found the following code as a substitute:
```
def val():
var = float(raw_input("Age:"))
status = ("Working","Retired")[var>65]
print "You should be:",status
```
I couldn't understand... | Python has a construct that is sort of like the ternary operator in C, et al. It works something like this:
```
my_var = "Retired" if age > 65 else "Working"
```
and is equivalent to this C code:
```
my_var = age > 65 ? "Retired" : "Working";
```
As for how the code you posted works, let's step through it:
```
("W... |
urllib2.urlopen() vs urllib.urlopen() - urllib2 throws 404 while urllib works! WHY? | 1,947,133 | 15 | 2009-12-22T15:34:59Z | 1,947,232 | 34 | 2009-12-22T15:50:59Z | [
"python",
"url",
"http-status-code-404",
"urllib2",
"urllib"
] | ```
import urllib
print urllib.urlopen('http://www.reefgeek.com/equipment/Controllers_&_Monitors/Neptune_Systems_AquaController/Apex_Controller_&_Accessories/').read()
```
The above script works and returns the expected results while:
```
import urllib2
print urllib2.urlopen('http://www.reefgeek.com/equipment/Contr... | That URL does indeed result in a 404, but with lots of HTML content. `urllib2` is handling it (correctly) as an error condition. You can recover the content of that site's 404 page like so:
```
import urllib2
try:
print urllib2.urlopen('http://www.reefgeek.com/equipment/Controllers_&_Monitors/Neptune_Systems_AquaC... |
fastcgi, cherrypy, and python | 1,947,344 | 5 | 2009-12-22T16:09:21Z | 1,947,512 | 8 | 2009-12-22T16:33:44Z | [
"python",
"fastcgi",
"lighttpd",
"cherrypy"
] | So I'm trying to do more web development in python, and I've picked cherrypy, hosted by lighttpd w/ fastcgi. But my question is a very basic one: why do I need to restart lighttpd (or apache) every time I change my application code, or the code for an underlying library?
I realize this question extends from a basic mi... | This is because of performance. For development, autoreloading is helpful. But for production, you *don't* want to autoreload. This is actually a decently-sized bottleneck in say PHP. Every time you access a PHP webpage, the server has to parse and load each page from scratch. With Python, the script is already loaded ... |
python email error | 1,947,701 | 2 | 2009-12-22T16:58:43Z | 1,947,769 | 7 | 2009-12-22T17:08:11Z | [
"python"
] | I am trying to email a results file. I am getting an import error:
```
Traceback (most recent call last):
File "email_results.py", line 5, in ?
from email import encoders
ImportError: cannot import name encoders
```
I am also unsure on how to get this to connect to the server. Can anyone help? Thanks
```... | The problem isn't that you can't connect to the server, it's that you aren't able to import email.encoders for some reason. Do you have a file named email.py or email.pyc by any chance? |
Does Python support MySQL prepared statements? | 1,947,750 | 37 | 2009-12-22T17:06:46Z | 1,947,993 | 42 | 2009-12-22T17:40:05Z | [
"python",
"mysql",
"prepared-statement"
] | I worked on a PHP project earlier where prepared statements made the SELECT queries 20% faster.
I'm wondering if it works on Python? I can't seem to find anything that specifically says it does or does NOT. | Most languages provide a way to do generic parameterized statements, Python is no different. When a parameterized query is used databases that support preparing statements will automatically do so.
In python a parameterized query looks like this:
```
cursor.execute("SELECT FROM tablename WHERE fieldname = %s", [value... |
Does Python support MySQL prepared statements? | 1,947,750 | 37 | 2009-12-22T17:06:46Z | 1,948,130 | 11 | 2009-12-22T18:04:14Z | [
"python",
"mysql",
"prepared-statement"
] | I worked on a PHP project earlier where prepared statements made the SELECT queries 20% faster.
I'm wondering if it works on Python? I can't seem to find anything that specifically says it does or does NOT. | After a quick look through an execute() method of a Cursor object of a MySQLdb package (a kind of de-facto package for integrating with mysql, I guess), it seems, that (at least by default) it only does string interpolation and quoting and not the actual parametrized query:
```
if args is not None:
query = query %... |
Does Python support MySQL prepared statements? | 1,947,750 | 37 | 2009-12-22T17:06:46Z | 17,237,567 | 10 | 2013-06-21T14:18:19Z | [
"python",
"mysql",
"prepared-statement"
] | I worked on a PHP project earlier where prepared statements made the SELECT queries 20% faster.
I'm wondering if it works on Python? I can't seem to find anything that specifically says it does or does NOT. | **Direct answer, no it doesn't.**
[joshperry's answer](http://stackoverflow.com/a/1947993/20774) is a good explanation of what it does instead.
From [eugene y answer to a similar question](http://stackoverflow.com/questions/2424531/does-the-mysqldb-module-support-prepared-statements/2425500#2425500),
> Check the MyS... |
How can I pickle a nested class in python? | 1,947,904 | 22 | 2009-12-22T17:25:36Z | 1,948,057 | 21 | 2009-12-22T17:51:23Z | [
"python",
"class",
"nested",
"pickle"
] | I have a nested class:
```
class WidgetType(object):
class FloatType(object):
pass
class TextType(object):
pass
```
.. and an oject that refers the nested class type (not an instance of it) like this
```
class ObjectToPickle(object):
def __init__(self):
self.type = WidgetType.... | The pickle module is trying to get the TextType class from the module. But since the class is nested it doesn't work. jasonjs's suggestion will work.
Here are the lines in pickle.py responsible for the error message:
```
try:
__import__(module)
mod = sys.modules[module]
klass = getattr(mod,... |
How can I pickle a nested class in python? | 1,947,904 | 22 | 2009-12-22T17:25:36Z | 11,493,777 | 17 | 2012-07-15T16:50:45Z | [
"python",
"class",
"nested",
"pickle"
] | I have a nested class:
```
class WidgetType(object):
class FloatType(object):
pass
class TextType(object):
pass
```
.. and an oject that refers the nested class type (not an instance of it) like this
```
class ObjectToPickle(object):
def __init__(self):
self.type = WidgetType.... | I know this is a **very** old question, but I have never explicitly seen a satisfactory solution to this question other than the obvious, and most likely correct, answer to re-structure your code.
Unfortunately, it is not always practical to do such a thing, in which case as a very last resort, it **is** possible to p... |
"painting" one array onto another using python / numpy | 1,949,225 | 6 | 2009-12-22T21:17:03Z | 1,949,306 | 7 | 2009-12-22T21:29:28Z | [
"python",
"image-processing",
"numpy",
"scipy"
] | I'm writing a library to process gaze tracking in Python, and I'm rather new to the whole numpy / scipy world. Essentially, I'm looking to take an array of (x,y) values in time and "paint" some shape onto a canvas at those coordinates. For example, the shape might be a blurred circle.
The operation I have in mind is m... | In your question you describe a Gaussian filter, for which scipy has support via a [package](http://www.scipy.org/SciPyPackages/Ndimage).
For example:
```
from scipy import * # rand
from pylab import * # figure, imshow
from scipy.ndimage import gaussian_filter
# random "image"
I = rand(100, 100)
figure(1)
imshow(I)
... |
How to add clickable links to a field in Django admin? | 1,949,248 | 22 | 2009-12-22T21:20:49Z | 1,949,340 | 45 | 2009-12-22T21:35:23Z | [
"python",
"django"
] | I have this admin.py
```
class LawyerAdmin(admin.ModelAdmin):
fieldsets = [
('Name', {'fields': ['last', 'first', 'firm_name', 'firm_url', 'school', 'year_graduated']}),
]
list_display = ('last', 'first', 'school', 'year_graduated', 'firm_name', 'firm_url')
list_filter = ['school', 'year_grad... | Define a custom method in your LawyerAdmin class that returns the link as HTML:
```
def show_firm_url(self, obj):
return '<a href="%s">%s</a>' % (obj.firm_url, obj.firm_url)
show_firm_url.allow_tags = True
```
See [the documentation](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.Mod... |
How to add clickable links to a field in Django admin? | 1,949,248 | 22 | 2009-12-22T21:20:49Z | 31,745,953 | 19 | 2015-07-31T12:14:38Z | [
"python",
"django"
] | I have this admin.py
```
class LawyerAdmin(admin.ModelAdmin):
fieldsets = [
('Name', {'fields': ['last', 'first', 'firm_name', 'firm_url', 'school', 'year_graduated']}),
]
list_display = ('last', 'first', 'school', 'year_graduated', 'firm_name', 'firm_url')
list_filter = ['school', 'year_grad... | Use the `format_html` utility. This will escape any html from parameters and mark the string as safe to use in templates. The `allow_tags` method attribute has been deprecated in Django 1.9.
```
from django.utils.html import format_html
class LawyerAdmin(admin.ModelAdmin):
list_display = ['show_firm_url', ...]
... |
Checking if a website is up via Python | 1,949,318 | 21 | 2009-12-22T21:31:41Z | 1,949,360 | 39 | 2009-12-22T21:38:11Z | [
"python",
"http",
"scripting",
"httprequest",
"http-head"
] | By using python, how can I check if a website is up? From what I read, I need to check the "HTTP HEAD" and see status code "200 OK", but how to do so ?
Cheers
### Related
* [How do you send a HEAD HTTP request in Python?](http://stackoverflow.com/questions/107405/how-do-you-send-a-head-http-request-in-python) | You could try to do this with `getcode()` from [**urllib**](http://docs.python.org/library/urllib.html)
```
>>> print urllib.urlopen("http://www.stackoverflow.com").getcode()
>>> 200
``` |
Checking if a website is up via Python | 1,949,318 | 21 | 2009-12-22T21:31:41Z | 1,949,393 | 7 | 2009-12-22T21:44:21Z | [
"python",
"http",
"scripting",
"httprequest",
"http-head"
] | By using python, how can I check if a website is up? From what I read, I need to check the "HTTP HEAD" and see status code "200 OK", but how to do so ?
Cheers
### Related
* [How do you send a HEAD HTTP request in Python?](http://stackoverflow.com/questions/107405/how-do-you-send-a-head-http-request-in-python) | You can use [httplib](http://docs.python.org/library/httplib.html)
```
import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD", "/")
r1 = conn.getresponse()
print r1.status, r1.reason
```
prints
```
200 OK
```
Of course, only if `www.python.org` is up. |
Suspicious Operation Django | 1,950,069 | 23 | 2009-12-23T00:32:32Z | 1,950,178 | 28 | 2009-12-23T01:13:17Z | [
"python",
"django"
] | I've been running into a problem while trying to delete uploaded images.
The error is along these lines:
```
SuspiciousOperation: Attempted access to '/media/artists/12-stones/154339.jpg' denied.
```
After reading around it looks like the error is due to the fact that it's looking for the image in the wrong place (n... | Well, a little grepping around in the code shows that there may be a deeper error message that got homogenized along the way.
in django/core/files/storage.py, line 210 (this is in 1.1.1) we have:
```
def path(self, name):
try:
path = safe_join(self.location, name)
except ValueError:
raise Susp... |
Suspicious Operation Django | 1,950,069 | 23 | 2009-12-23T00:32:32Z | 6,204,619 | 53 | 2011-06-01T16:34:42Z | [
"python",
"django"
] | I've been running into a problem while trying to delete uploaded images.
The error is along these lines:
```
SuspiciousOperation: Attempted access to '/media/artists/12-stones/154339.jpg' denied.
```
After reading around it looks like the error is due to the fact that it's looking for the image in the wrong place (n... | I got this error when I put a leading slash in the upload\_to definition.
BAD
```
pic = models.ImageField(upload_to="/uploads/product_images/")
```
GOOD
```
pic = models.ImageField(upload_to="uploads/product_images/")
``` |
Suspicious Operation Django | 1,950,069 | 23 | 2009-12-23T00:32:32Z | 11,346,592 | 7 | 2012-07-05T14:36:48Z | [
"python",
"django"
] | I've been running into a problem while trying to delete uploaded images.
The error is along these lines:
```
SuspiciousOperation: Attempted access to '/media/artists/12-stones/154339.jpg' denied.
```
After reading around it looks like the error is due to the fact that it's looking for the image in the wrong place (n... | As a note for others this issue can be caused when you have a double '//' in the static file resource you are looking for.
```
{{ STATIC_URL }}/style.css # Causes the issue it should be
{{ STATIC_URL }}style.css
``` |
Does Python have any for loop equivalent (not foreach) | 1,950,098 | 13 | 2009-12-23T00:41:31Z | 1,950,179 | 30 | 2009-12-23T01:13:27Z | [
"python",
"loops",
"for-loop"
] | Python's iterators are great and all, but sometimes I really do want a C-style for loop - not a foreach loop. For example, I have a start date and an end date and I want to do something for every day in that range. I can do this with a while loop, of course:
```
current = start
while current <= finish:
... | The elegant and Pythonic way to do it is to encapsulate the idea of a range of dates in its own generator, then use that generator in your code:
```
import datetime
def daterange(start, end, delta):
""" Just like `range`, but for dates! """
current = start
while current < end:
yield current
... |
Distributing Python programs | 1,950,218 | 8 | 2009-12-23T01:28:56Z | 1,950,223 | 11 | 2009-12-23T01:29:50Z | [
"python"
] | How do I let my friends use my Python programs? They don't have python installed, but they can use command line programs. I don't have the skill to write GUI.
Let, say I am writing some calculus calculator, with a lot of custom modules and files. How do I share it? | You could use something like [py2exe](http://www.py2exe.org/) to convert your Python program into an executable. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.