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 |
|---|---|---|---|---|---|---|---|---|---|
Turning off logging in Selenium (from Python) | 9,226,519 | 9 | 2012-02-10T10:46:10Z | 15,400,334 | 10 | 2013-03-14T02:52:14Z | [
"python",
"selenium",
"selenium-webdriver"
] | I've recently inherited some Selenium Webdriver code, written in Python 2.7. It is logging copious amounts of data to /tmp on Ubuntu - so much that it is becoming a problem. I am trying to turn it off (or at least down).
I have been running around trying to RTFM, but this is a new version of Selenium (2.19.0) and the ... | ```
import logging
selenium_logger = logging.getLogger('selenium.webdriver.remote.remote_connection')
# Only display possible problems
selenium_logger.setLevel(logging.WARNING)
``` |
Extract different values from list of tuples | 9,226,931 | 3 | 2012-02-10T11:16:50Z | 9,226,977 | 11 | 2012-02-10T11:19:48Z | [
"python",
"list",
"tuples"
] | How to extract a list of different values from following list of tuples?
```
tuple = ((("test", 123), ("test", 465), ("test", 8910), ("test2", 123)))
```
I want to get a list like:
```
different_values = ("test", "test2")
```
Now I want to access all values by this "keys" and get them by a list:
```
test_values = ... | I'd transform your data to a dictionary of lists:
```
d = {}
for k, v in tuples:
d.setdefault(k, []).append(v)
```
Now you can access the keys as `d.keys()`, and the list of values for each key `k` as `d[k]`.
(Shortly, someone will step forward and claim a `defaultdict` would be better for this. Don't listen to ... |
Really fancy printing on python | 9,227,368 | 4 | 2012-02-10T11:56:04Z | 9,227,401 | 9 | 2012-02-10T11:58:54Z | [
"python",
"text"
] | Since python has way to do nearly everything I was wondering is there any API which would help me print out really fancy text to my log e.g.
```
# # ####### # # ##########
# # # # # # #
# # # # # # #
##### #### # # # ... | Here is a Python recipe that does just that: [Banner](http://code.activestate.com/recipes/577537-banner/).
On some systems, there also exists a [`banner`](http://www.manpagez.com/man/6/banner/) command:
```
aix@aix:~$ banner HELLO
# # ####### # # #######
# # # # # # #
# #... |
Are there any classes in NLTK for text normalizing and canonizing? | 9,227,527 | 15 | 2012-02-10T12:08:27Z | 9,228,783 | 12 | 2012-02-10T13:51:49Z | [
"python",
"nltk"
] | The prevalent amount of NLTK documentation and examples is devoted to lemmatization and stemming but is very sparse on such matters of normalization as:
* converting all letters to lower or upper case
* removing punctuation
* **converting numbers into words**
* removing accent marks and other diacritics
* **expanding ... | Also in NLTK spec a lot of (sub-)tasks are solved using purely python [methods](http://docs.python.org/release/2.5.2/lib/string-methods.html).
**a) converting all letters to lower or upper case**
```
text='aiUOd'
print text.lower()
>> 'aiuod'
print text.upper()
>> 'AIUOD'
```
**b) removing punctuation**
```
text='S... |
Tokenizing unicode using nltk | 9,228,202 | 9 | 2012-02-10T13:00:26Z | 9,228,708 | 15 | 2012-02-10T13:46:02Z | [
"python",
"unicode",
"nltk",
"tokenize"
] | I have textfiles that use utf-8 encoding that contain characters like 'ö', 'ü', etc. I would like to parse the text form these files, but I can't get the tokenizer to work properly. If I use standard nltk tokenizer:
```
f = open('C:\Python26\text.txt', 'r') # text = 'müsli pöök rääk'
text = f.read()
f.close
ite... | It's more likely that the `\uFEFF` char is part of the content read from the file. I doubt it was inserted by the tokeniser. `\uFEFF` at the beginning of a file is a deprecated form of [Byte Order Mark](http://en.wikipedia.org/wiki/Byte_Order_Mark). If it appears anywhere else, then it is treated as a [zero width non-b... |
Tokenizing unicode using nltk | 9,228,202 | 9 | 2012-02-10T13:00:26Z | 9,926,783 | 7 | 2012-03-29T13:52:49Z | [
"python",
"unicode",
"nltk",
"tokenize"
] | I have textfiles that use utf-8 encoding that contain characters like 'ö', 'ü', etc. I would like to parse the text form these files, but I can't get the tokenizer to work properly. If I use standard nltk tokenizer:
```
f = open('C:\Python26\text.txt', 'r') # text = 'müsli pöök rääk'
text = f.read()
f.close
ite... | You should make sure that you're passing unicode strings to nltk tokenizers. I get the following identical tokenizations of your string with both tokenizers on my end:
```
import nltk
nltk.wordpunct_tokenize('müsli pöök rääk'.decode('utf8'))
# output : [u'm\xfcsli', u'p\xf6\xf6k', u'r\xe4\xe4k']
nltk.word_tokeni... |
Dot product of a vector in SciPy/NumPy (getting ValueError: objects are not aligned) | 9,228,821 | 12 | 2012-02-10T13:54:48Z | 9,229,040 | 11 | 2012-02-10T14:09:20Z | [
"python",
"numpy",
"scipy"
] | I just started learning SciPy and am struggling with the most basic features.
Consider the following standard vector:
```
In [6]: W=array([[1],[2]])
In [7]: print W
[[1]
[2]]
```
If I understand it correctly, this should be the SciPy representation of a standard 2x1 mathematical vector, like this:
```
(1)
(2)... | The key here is that numpy/scipy honours the shape of arrays when computing dot products. Looking at your first example, `W` is a 2x1 array:
```
In [7]: W=array([[1],[2]])
In [8]: print W.shape
------> print(W.shape)
(2, 1)
```
it is, therefore, necessary to use the transpose operator to compute the dot (inner) prod... |
Dot product of a vector in SciPy/NumPy (getting ValueError: objects are not aligned) | 9,228,821 | 12 | 2012-02-10T13:54:48Z | 15,373,690 | 8 | 2013-03-12T22:41:35Z | [
"python",
"numpy",
"scipy"
] | I just started learning SciPy and am struggling with the most basic features.
Consider the following standard vector:
```
In [6]: W=array([[1],[2]])
In [7]: print W
[[1]
[2]]
```
If I understand it correctly, this should be the SciPy representation of a standard 2x1 mathematical vector, like this:
```
(1)
(2)... | You should use `vdot`: "Return the dot product of two vectors." This function flattens the input arguments and gives the results you expect. For your example:
```
>>> W = np.array([[1], [2]])
>>> np.vdot(W, W)
5
>>>
``` |
Why is matplotlib plotting my circles as ovals? | 9,230,389 | 14 | 2012-02-10T15:41:45Z | 9,232,513 | 22 | 2012-02-10T18:00:39Z | [
"python",
"matplotlib"
] | Is there a way to get matplotlib to plot a perfect circle? They look more like ovals. | Just to expand on DSM's correct answer. By default, plots have more pixels along one axis over the other. When you add a circle, it's traditionally added in data units. If your axes have a symmetric range, that means one step along the x axis will involve a different number of pixels than one step along your y axis. So... |
Using boto, set content_type on files which are already present on s3 | 9,231,029 | 7 | 2012-02-10T16:21:41Z | 9,232,045 | 14 | 2012-02-10T17:26:05Z | [
"python",
"django",
"amazon-s3",
"boto"
] | I'm using django storages with the s3boto backend. As per this issue, <http://code.larlet.fr/django-storages/issue/5/s3botostorage-set-content-type-header-acl-fixed-use-http-and-disable-query-auth-by> I have a bunch of files (all of them) that have content type 'application/octet-stream'. Given that I have an instance ... | There is no way to modify the content type (or any other metadata) associated with a file after it has been created. You can, however, copy the file on the server side and modify the metadata in the process. Here is a gist on github that should help:
<https://gist.github.com/1791086>
Contents:
```
import boto
s3 = ... |
Round up to Third decimal Place in Python | 9,232,256 | 9 | 2012-02-10T17:41:23Z | 9,232,294 | 14 | 2012-02-10T17:44:28Z | [
"python",
"rounding"
] | How can i round up a number to the third decimal Place in python for example:
0.022499999999999999
Should round up to 0.03
0.1111111111111000
Should round up to 0.12
if there is any value in the third decimal place, i want it to always round up leaving me 2 values behind the decimal point | ```
from math import ceil
num = 0.1111111111000
num = ceil(num * 100) / 100.0
```
See:
[`math.ceil` documentation](http://docs.python.org/library/math.html#math.ceil)
[`round` documentation](http://docs.python.org/library/functions.html#round) - You'll probably want to check this out anyway for future reference |
Round up to Third decimal Place in Python | 9,232,256 | 9 | 2012-02-10T17:41:23Z | 9,232,295 | 23 | 2012-02-10T17:44:29Z | [
"python",
"rounding"
] | How can i round up a number to the third decimal Place in python for example:
0.022499999999999999
Should round up to 0.03
0.1111111111111000
Should round up to 0.12
if there is any value in the third decimal place, i want it to always round up leaving me 2 values behind the decimal point | Python includes the `round()` function which [lets you specify](http://docs.python.org/library/functions.html#round) the number of digits you want. From the documentation:
> `round(x[, n])`
>
> Return the floating point value x rounded to n digits after the decimal point. If n is omitted, it defaults to zero. The resu... |
Round up to Third decimal Place in Python | 9,232,256 | 9 | 2012-02-10T17:41:23Z | 9,232,310 | 8 | 2012-02-10T17:45:30Z | [
"python",
"rounding"
] | How can i round up a number to the third decimal Place in python for example:
0.022499999999999999
Should round up to 0.03
0.1111111111111000
Should round up to 0.12
if there is any value in the third decimal place, i want it to always round up leaving me 2 values behind the decimal point | ```
x = math.ceil(x * 100.0) / 100.0
``` |
Round up to Third decimal Place in Python | 9,232,256 | 9 | 2012-02-10T17:41:23Z | 9,232,628 | 7 | 2012-02-10T18:09:38Z | [
"python",
"rounding"
] | How can i round up a number to the third decimal Place in python for example:
0.022499999999999999
Should round up to 0.03
0.1111111111111000
Should round up to 0.12
if there is any value in the third decimal place, i want it to always round up leaving me 2 values behind the decimal point | Extrapolating from Edwin's answer:
```
from math import ceil, floor
def float_round(num, places = 0, direction = floor):
return direction(num * (10**places)) / float(10**places)
```
To use:
```
>>> float_round(0.21111, 3, ceil) #round up
>>> 0.212
>>> float_round(0.21111, 3) #round down
>>> 0.211
>>> flo... |
Identifying the dependency relationship for python packages installed with pip | 9,232,568 | 47 | 2012-02-10T18:04:22Z | 10,319,754 | 41 | 2012-04-25T16:23:24Z | [
"python",
"pip"
] | When I do a pip freeze I see large number of Python packages that I didn't explicitly install, e.g.
```
$ pip freeze
Cheetah==2.4.3
GnuPGInterface==0.3.2
Landscape-Client==11.01
M2Crypto==0.20.1
PAM==0.4.2
PIL==1.1.7
PyYAML==3.09
Twisted-Core==10.2.0
Twisted-Web==10.2.0
(etc.)
```
Is there a way for me to determine w... | The `pip show` command will show what packages are required for the specified package (note that the specified package must already be installed):
```
$ pip show specloud
Package: specloud
Version: 0.4.4
Requires:
nose
figleaf
pinocchio
```
`pip show` was introduced in pip version 1.4rc5 |
Identifying the dependency relationship for python packages installed with pip | 9,232,568 | 47 | 2012-02-10T18:04:22Z | 30,450,999 | 36 | 2015-05-26T06:28:24Z | [
"python",
"pip"
] | When I do a pip freeze I see large number of Python packages that I didn't explicitly install, e.g.
```
$ pip freeze
Cheetah==2.4.3
GnuPGInterface==0.3.2
Landscape-Client==11.01
M2Crypto==0.20.1
PAM==0.4.2
PIL==1.1.7
PyYAML==3.09
Twisted-Core==10.2.0
Twisted-Web==10.2.0
(etc.)
```
Is there a way for me to determine w... | You could try [pipdeptree](https://github.com/naiquevin/pipdeptree) which displays dependencies as a tree structure e.g.:
```
$ pipdeptree
Lookupy==0.1
wsgiref==0.1.2
argparse==1.2.1
psycopg2==2.5.2
Flask-Script==0.6.6
- Flask [installed: 0.10.1]
- Werkzeug [required: >=0.7, installed: 0.9.4]
- Jinja2 [requi... |
Saving and loading Python dict with savemat results in error | 9,232,751 | 5 | 2012-02-10T18:21:07Z | 9,233,028 | 7 | 2012-02-10T18:44:00Z | [
"python",
"scipy",
"mat-file"
] | Here is an minimal example of the error I get. If I understood the documentation correctly, this should be working, but it seems I did not.
```
a={}
a['test1']=1
a['test2']=2
a['test3']=3
import scipy.io as io
io.savemat('temp',{'a':a})
b = io.loadmat('temp')
b['a'].keys()
Traceback (most recent call last):
File "<... | You seem to be operating under the assumption that `scipy.io.savemat` is intended to be able to save a standard dictionary. I don't believe that is the case. The dictionary argument holds the names of *numpy arrays* which are written out into the Matlab file. So you can do something like this
```
import scipy.io as io... |
Memory dump formatted like xxd from gdb | 9,233,095 | 23 | 2012-02-10T18:47:58Z | 9,234,007 | 37 | 2012-02-10T19:56:22Z | [
"python",
"debugging",
"gdb",
"pretty-print"
] | I'm trying to inspect a buffer which contains a binary formatted message, but also contains string data. As an example, I'm using this C code:
```
int main (void) {
char buf[100] = "\x01\x02\x03\x04String Data\xAA\xBB\xCC";
return 0;
}
```
I'd like to get a hex dump of what's in `buf`, of a format similar to... | ```
(gdb) define xxd
>dump binary memory dump.bin $arg0 $arg0+$arg1
>shell xxd dump.bin
>end
(gdb) xxd &j 10
0000000: 0000 0000 0000 0000 0000 0000 4d8c a7f7 ............M...
0000010: ff7f 0000 0000 0000 0000 0000 c8d7 ffff ................
0000020: ff7f 0000 0000 0000
```
Seems easy enough ;-)
You could likely wr... |
Memory dump formatted like xxd from gdb | 9,233,095 | 23 | 2012-02-10T18:47:58Z | 9,237,555 | 18 | 2012-02-11T03:22:59Z | [
"python",
"debugging",
"gdb",
"pretty-print"
] | I'm trying to inspect a buffer which contains a binary formatted message, but also contains string data. As an example, I'm using this C code:
```
int main (void) {
char buf[100] = "\x01\x02\x03\x04String Data\xAA\xBB\xCC";
return 0;
}
```
I'd like to get a hex dump of what's in `buf`, of a format similar to... | So, I ended up playing around with the python interface and came up with this:
```
import gdb
from curses.ascii import isgraph
def groups_of(iterable, size, first=0):
first = first if first != 0 else size
chunk, iterable = iterable[:first], iterable[first:]
while chunk:
yield chunk
chunk, ... |
Project Euler 10 - Why the first python code runs much faster than the second one? | 9,233,408 | 3 | 2012-02-10T19:11:35Z | 9,236,311 | 7 | 2012-02-10T23:30:53Z | [
"python",
"primes",
"number-theory"
] | 10 problem in the Project Euler is:
> The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
>
> Find the sum of all the primes below two million.
I found this snippet :
```
sieve = [True] * 2000000 # Sieve is faster for 2M primes
def mark(sieve, x):
for i in xrange(x+x, len(sieve), x):
sieve[i] = False
... | Your algorithm is checking every number from 2 to 2000000 for primality.
Snippet-1 uses the **[sieve of Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)** algorithm, discovered about 2200 years ago.
It does not check every number but:
* Makes a "sieve" of all numbers from 2 to 2000000.
* Finds the fi... |
Setting delete-orphan on SQLAlchemy relationship causes AssertionError: This AttributeImpl is not configured to track parents | 9,234,082 | 16 | 2012-02-10T20:01:27Z | 9,264,556 | 49 | 2012-02-13T16:58:18Z | [
"python",
"sqlalchemy",
"flask",
"flask-sqlalchemy"
] | this is my Flask-SQLAlchemy Declarative code:
```
from sqlalchemy.ext.associationproxy import association_proxy
from my_flask_project import db
tagging = db.Table('tagging',
db.Column('tag_id', db.Integer, db.ForeignKey('tag.id', ondelete='cascade'), primary_key=True),
db.Column('role_id', db.Integer, db.For... | OK in this case, you need to look more closely, though there is a warning here that likely should become an exception, and I'll look into that. Here's a working version of your example:
```
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalche... |
In Python argparse, is it possible to have paired --no-something/--something arguments? | 9,234,258 | 25 | 2012-02-10T20:15:53Z | 9,236,426 | 18 | 2012-02-10T23:45:00Z | [
"python",
"python-3.x",
"argparse"
] | I'm writing a program in which I would like to have arguments like this:
```
--[no-]foo Do (or do not) foo. Default is do.
```
Is there a way to get argparse to do this for me?
I'm using Python 3.2.
---
**Edit:**
Since there seems to be no way to do this, I'm opting for this idea instead...
```
parser.add_argu... | Well, none of the answers so far are quite satisfactory for a variety of reasons. So here is my own answer:
```
class ActionNoYes(argparse.Action):
def __init__(self, opt_name, dest, default=True, required=False, help=None):
super(ActionNoYes, self).__init__(['--' + opt_name, '--no-' + opt_name], dest, nar... |
What is the least-bad way to create Python classes at runtime? | 9,234,608 | 8 | 2012-02-10T20:47:28Z | 9,234,705 | 10 | 2012-02-10T20:55:41Z | [
"python",
"class"
] | I am working with an ORM that accepts classes as input and I need to be able to feed it some dynamically generated classes. Currently, I am doing something like this contrived example:
```
def make_cls(_param):
def Cls(object):
param = _param
return Cls
A, B = map(make_cls, ['A', 'B'])
print A().foo
pri... | What is class? It is just an instance of `type`. For example:
```
>>> A = type('A', (object,), {'s': 'i am a member', 'double_s': lambda self: self.s * 2})
>>> a = A()
>>> a
<__main__.A object at 0x01229F50>
>>> a.s
'i am a member'
>>> a.double_s()
'i am a memberi am a member'
```
From the [doc](http://docs.python.or... |
Convert BibTex file to database entries using Python | 9,235,853 | 13 | 2012-02-10T22:43:40Z | 14,061,849 | 20 | 2012-12-27T22:00:09Z | [
"python",
"mysql",
"bibtex"
] | Given a bibTex file, I need to add the respective fields(author, title, journal etc.) to a table in a MySQL database (with a custom schema).
After doing some initial research, I found that there exists [Bibutils](http://sourceforge.net/p/bibutils/home/Bibutils/) which I could use to convert a bib file to xml. My initi... | Old question, but I am doing the same thing at the moment using the [Pybtex](http://pybtex.sourceforge.net/) library, which has an inbuilt parser:
```
from pybtex.database.input import bibtex
#open a bibtex file
parser = bibtex.Parser()
bibdata = parser.parse_file("myrefs.bib")
#loop through the individual reference... |
CSV files with quote and comma chars inside fields | 9,236,044 | 8 | 2012-02-10T23:02:58Z | 9,236,100 | 11 | 2012-02-10T23:08:53Z | [
"python",
"csv",
"quote"
] | I have a stack of CSV files I want to parse - the problem is half of the have quote marks used as quote marks, and commas inside main field. They are not really CSV, but they do have a fixed number of fields that are identifiable. The dialect=csv."excel" setting works perfectly on files with out the extra " and , chars... | Have you tried passing [`csv.QUOTE_NONE`](http://docs.python.org/library/csv.html#csv.QUOTE_NONE) via the `quoting` keyword arg? Without having some code or data to test this on, I have no way to know whether this actually works on your data, but it seems to work with the fragment you provided.
```
>>> import csv
>>> ... |
Python 3 operator >> to print to file | 9,236,198 | 12 | 2012-02-10T23:18:03Z | 9,236,221 | 7 | 2012-02-10T23:21:13Z | [
"python",
"python-3.x"
] | I have the following Python code to write dependency files of a project. It works fine with Python 2.x, but while testing it with Python 3 it reports an error.
```
depend = None
if not nmake:
depend = open(".depend", "a")
dependmak = open(".depend.mak", "a")
depend = open(".depend", "a")
print >>depend, s,
```
He... | [`print()`](http://docs.python.org/release/3.1/library/functions.html#print) is a function in Python 3.
Change your code to `print(s, end="", file=depend)`, [or let the `2to3` tool do it for you.](http://docs.python.org/library/2to3.html) |
Python 3 operator >> to print to file | 9,236,198 | 12 | 2012-02-10T23:18:03Z | 9,236,236 | 23 | 2012-02-10T23:22:12Z | [
"python",
"python-3.x"
] | I have the following Python code to write dependency files of a project. It works fine with Python 2.x, but while testing it with Python 3 it reports an error.
```
depend = None
if not nmake:
depend = open(".depend", "a")
dependmak = open(".depend.mak", "a")
depend = open(".depend", "a")
print >>depend, s,
```
He... | In Python 3 the print statement has become a function. The new syntax looks like this:
```
print(s, end="", file=depend)
```
This breaking change in Python 3 means that it is not possible to use the same code in Python 2 and 3 when writing to a file using the `print` statement/function. One possible option would be t... |
How can I sort 1 million numbers, and only print the top 10 in Python? | 9,236,387 | 13 | 2012-02-10T23:40:15Z | 9,236,412 | 26 | 2012-02-10T23:43:14Z | [
"python"
] | I have a file that has 1 million numbers. I need to know how I can sort it efficiently, so that it doesn't stall the computer, and it prints ONLY the top 10.
```
#!/usr/bin/python3
#Find the 10 largest integers
#Don't store the whole list
import sys
def fOpen(fname):
try:
fd = open(fname,"r"... | The best sort is a partial sort, available in the Python library as [`heapq.nlargest`](http://docs.python.org/library/heapq.html#heapq.nlargest). |
How can I sort 1 million numbers, and only print the top 10 in Python? | 9,236,387 | 13 | 2012-02-10T23:40:15Z | 9,236,436 | 30 | 2012-02-10T23:46:04Z | [
"python"
] | I have a file that has 1 million numbers. I need to know how I can sort it efficiently, so that it doesn't stall the computer, and it prints ONLY the top 10.
```
#!/usr/bin/python3
#Find the 10 largest integers
#Don't store the whole list
import sys
def fOpen(fname):
try:
fd = open(fname,"r"... | If you only need the top 10 values, then you'd waste a lot of time sorting every single number.
Just go through the list of numbers and keep track of the top 10 largest values seen so far. Update the top ten as you go through the list, and print them out when you reach the end.
This will mean you only need to make a ... |
How can I sort 1 million numbers, and only print the top 10 in Python? | 9,236,387 | 13 | 2012-02-10T23:40:15Z | 9,236,477 | 13 | 2012-02-10T23:53:22Z | [
"python"
] | I have a file that has 1 million numbers. I need to know how I can sort it efficiently, so that it doesn't stall the computer, and it prints ONLY the top 10.
```
#!/usr/bin/python3
#Find the 10 largest integers
#Don't store the whole list
import sys
def fOpen(fname):
try:
fd = open(fname,"r"... | ```
import heapq
with open('nums.txt') as f:
numbers=map(int,f.readlines())
print heapq.nlargest(10,numbers)
print heapq.nsmallest(10,numbers)
"""
[1132513251, 13252365, 23512, 2000, 1251, 1235, 324, 100, 82, 82]
[1, 1, 7, 13, 15, 21, 22, 22, 33, 82]
"""
``` |
Concatenating two one-dimensional NumPy arrays | 9,236,926 | 98 | 2012-02-11T01:11:06Z | 9,236,952 | 13 | 2012-02-11T01:17:24Z | [
"python",
"arrays",
"numpy",
"concatenation"
] | I have two simple one-dimensional arrays in [NumPy](http://en.wikipedia.org/wiki/NumPy). I should be able to concatenate them using [numpy.concatenate](http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html). But I get this error for the code below:
> TypeError: only length-1 arrays can be converte... | The first parameter to `concatenate` should itself be a *sequence of arrays* to concatenate:
```
numpy.concatenate((a,b)) # Note the extra parentheses.
``` |
Concatenating two one-dimensional NumPy arrays | 9,236,926 | 98 | 2012-02-11T01:11:06Z | 9,236,970 | 138 | 2012-02-11T01:21:04Z | [
"python",
"arrays",
"numpy",
"concatenation"
] | I have two simple one-dimensional arrays in [NumPy](http://en.wikipedia.org/wiki/NumPy). I should be able to concatenate them using [numpy.concatenate](http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html). But I get this error for the code below:
> TypeError: only length-1 arrays can be converte... | The line should be:
```
numpy.concatenate([a,b])
```
The arrays you want to concatenate need to passed in as a sequence, not as separate arguments.
From the [NumPy documentation](http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html):
> `numpy.concatenate((a1, a2, ...), axis=0)`
>
> Join a sequ... |
Python - how to read file with NUL delimited lines? | 9,237,246 | 6 | 2012-02-11T02:13:48Z | 9,237,265 | 12 | 2012-02-11T02:17:33Z | [
"python",
"nul"
] | I usually use the following Python code to read lines from a file :
```
f = open('./my.csv', 'r')
for line in f:
print line
```
But how about if the file is line delimited by "\0" (not "\n") ? Is there a Python module that could handle this ?
Thanks for any advice. | If your file is small enough that you can read it all into memory you can use split:
```
for line in f.read().split('\0'):
print line
```
Otherwise you might want to try this recipe from the discussion about this [feature request](http://bugs.python.org/issue1152248):
```
def fileLineIter(inputFile,
... |
How do I ignore PyCharm configuration files in a git repository? | 9,237,345 | 25 | 2012-02-11T02:34:33Z | 9,237,490 | 13 | 2012-02-11T03:06:51Z | [
"python",
"git",
"pycharm"
] | I don't want to commit my PyCharm config files (e.g. .idea/codeStyleSettings.xml) to my git repository, so I added the following to my .gitignore file:
```
.idea/
mydjangosite/.idea/
```
However, every time I try to make a commit within PyCharm (command k), it still wants to commit these files. How do I get PyCharm t... | You can [configure ignored files](http://www.jetbrains.com/pycharm/webhelp/configuring-ignored-files.html).
> Under the Version Control node, of the Settings dialog box, click Ignored Files. The Ignored Files dialog box opens.
More easily:
> Tip
>
> You can also add files to ignore list on-the-fly. A new file under ... |
How do I ignore PyCharm configuration files in a git repository? | 9,237,345 | 25 | 2012-02-11T02:34:33Z | 9,264,229 | 37 | 2012-02-13T16:35:07Z | [
"python",
"git",
"pycharm"
] | I don't want to commit my PyCharm config files (e.g. .idea/codeStyleSettings.xml) to my git repository, so I added the following to my .gitignore file:
```
.idea/
mydjangosite/.idea/
```
However, every time I try to make a commit within PyCharm (command k), it still wants to commit these files. How do I get PyCharm t... | If PyCharm offers you to commit the files, it means that you have already added them to Git. You need to remove them using 'git rm --cached' and commit the change. After that, they will be ignored by the integration according to your .gitignore settings. |
python capitalize() on a string starting with space | 9,237,419 | 8 | 2012-02-11T02:50:33Z | 9,237,429 | 23 | 2012-02-11T02:53:34Z | [
"python",
"string",
"capitalize"
] | I was using the capitalize method on some strings in Python and one of strings starts with a space:
```
phrase = ' Lexical Semantics'
```
`phrase.capitalize()` returns ' lexical semantics' all in lower case. Why is that? | This is the [listed behaviour](http://docs.python.org/library/stdtypes.html#str.capitalize):
> Return a copy of the string with its first character capitalized and the rest lowercased.
The first character is a space, the space is unchanged, the rest lowercased.
If you want to make it all uppercase, see [`str.upper()... |
Scrapy crawl a local website by IP address | 9,237,545 | 2 | 2012-02-11T03:20:10Z | 9,237,890 | 9 | 2012-02-11T04:44:45Z | [
"python",
"web-crawler",
"scrapy"
] | I'm still experimenting with Scrapy, and I'm trying to crawl a website on my local network. The website has the IP address 192.168.0.185. This is my spider:
```
from scrapy.spider import BaseSpider
class 192.168.0.185_Spider(BaseSpider):
name = "192.168.0.185"
allowed_domains = ["192.168.0.185"]
st... | ```
class 192.168.0.185_Spider(BaseSpider):
...
```
You can't use class name which begins with digit or contains dots in Python. See documentation [Identifiers and keywords](http://docs.python.org/reference/lexical_analysis.html#identifiers)
You can create this spider with correct name:
```
$ scrapy startproject... |
How to force http.client to send chunked-encoding HTTP body in python? | 9,237,961 | 3 | 2012-02-11T05:03:44Z | 9,238,565 | 7 | 2012-02-11T07:23:20Z | [
"python",
"http",
"chunked"
] | I want to send chunked HTTP body to test my own HTTP server.
So I wrote this python code:
```
import http.client
body = 'Hello World!' * 80
conn = http.client.HTTPConnection("some.domain.com")
url = "/some_path?arg=true_arg"
conn.request("POST", url, body, {"Transfer-Encoding":"chunked"})
resp = conn.getresponse()... | OK, I get it.
First, write my own chunked encode function.
Then use putrequest(), putheader(), endheaders() and send() instead of request()
```
import http.client
def chunk_data(data, chunk_size):
dl = len(data)
ret = ""
for i in range(dl // chunk_size):
ret += "%s\r\n" % (hex(chunk_size)[2:])
... |
Is YQL not reliably returning the correct data - Any replacements? | 9,238,515 | 2 | 2012-02-11T07:12:52Z | 9,242,370 | 7 | 2012-02-11T17:33:37Z | [
"python",
"finance",
"yql",
"yahoo-finance",
"google-finance-api"
] | I'm writing an application that chooses companies based upon market cap and dividend yield. It uses Yahoo!'s YQL REST API to get this data. It seemed to work well yesterday, but today I saw that my program says that one of the companies had a yield of 65.95%! No problem - a bug in my code. So I thought. But when I view... | Not an answer per se, but to shed some more light on what you're seeing:
Yahoo does not have an official API for Yahoo Finance. Instead, these YQL community tables are reading from CSV files that people have reverse-engineered from the Yahoo Finance website. These change from time to time, so it's not a reliable sourc... |
filedialog, tkinter and opening files | 9,239,514 | 18 | 2012-02-11T10:34:44Z | 9,239,756 | 33 | 2012-02-11T11:14:39Z | [
"python",
"python-3.x",
"tkinter",
"global-variables",
"filedialog"
] | I'm working for the first time on coding a Browse button for a program in Python3. I've been searching the internet and this site, and even python standard library.
I have found sample code and very superficial explanations of things, but I haven't been able to find anything that addresses the problem I'm having direc... | The exception you get is telling you `filedialog` is not in your namespace.
`filedialog` (and btw `messagebox`) is a tkinter module, so it is not imported just with `from tkinter import *`
```
>>> from tkinter import *
>>> filedialog
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
... |
Error when testing SciPy | 9,239,989 | 6 | 2012-02-11T11:54:44Z | 9,240,424 | 11 | 2012-02-11T13:02:56Z | [
"python",
"scipy"
] | When testing scipy using the nose package using `scipy.test()`, the test fails under Ubuntu 12.04 with all the vanilla packages installed. Do I have to worry, and if yes how can I fix this?
```
In [8]: scipy.test()
Running unit tests for scipy
NumPy version 1.5.1
NumPy is installed in /usr/lib/python2.7/dist-packages/... | If you take a look inside `/usr/lib/python2.7/dist-packages/scipy/ndimage/tests/test_io.py` you should see:
```
def test_imread():
lp = os.path.join(os.path.dirname(__file__), 'dots.png')
img = ndi.imread(lp)
assert_array_equal(img.shape, (300, 420, 3))
img = ndi.imread(lp, flatten=True)
assert_ar... |
PyParsing lookaheads and greedy expressions | 9,242,561 | 8 | 2012-02-11T17:57:10Z | 9,246,314 | 10 | 2012-02-12T03:58:58Z | [
"python",
"pyparsing"
] | I'm writing a parser for a query language using PyParsing, and I've gotten stuck on (what I believe to be) an issue with lookaheads. One clause type in the query is intended to split strings into 3 parts (fieldname,operator, value) such that fieldname is one word, operator is one or more words, and value is a word, a q... | This is a good place to Be The Parser. Or more accurately, Make The Parser Think Like You Do. Ask yourself, "In 'author is shakespeare', how do I know that 'shakespeare' is not part of the operator?" You know that 'shakespeare' is the value because it is at the end of the query, there is nothing more after it. So opera... |
Python 3.2 print( end='') error | 9,243,123 | 2 | 2012-02-11T19:00:17Z | 9,243,142 | 7 | 2012-02-11T19:03:07Z | [
"python",
"printing",
"python-3.x"
] | I'm a born again amateur programming novice trying to learn Python 3 (3.2) using Geany on Linux. I've been trying to rework the following example in [Swaroop C H's Python 3 tutorial](http://www.swaroopch.com/notes/Python_en%3aInput_Output#Files) My code is as follows:
```
#!/usr/bin/env python3
# Filename: poem.py
po... | You don't have Python 3.x installed, or are not using it. This runs fine for me under Python 3.x, but I get the error you have under Python 2.x. Shebangs are not a guarentee, they have to be honoured by whatever you are using to run the script, and if you run the interpreter directly, will be ignored. So try making sur... |
Python 3.2 print( end='') error | 9,243,123 | 2 | 2012-02-11T19:00:17Z | 9,243,168 | 11 | 2012-02-11T19:07:09Z | [
"python",
"printing",
"python-3.x"
] | I'm a born again amateur programming novice trying to learn Python 3 (3.2) using Geany on Linux. I've been trying to rework the following example in [Swaroop C H's Python 3 tutorial](http://www.swaroopch.com/notes/Python_en%3aInput_Output#Files) My code is as follows:
```
#!/usr/bin/env python3
# Filename: poem.py
po... | Your file contains a correct "shebang" line for Python 3:
```
#!/usr/bin/env python3
```
However, in order for this shebang line to take effect, you must run your script directly as:
```
./poem.py
```
(You may have to do `chmod +x poem.py` to make the script executable.)
If you choose to explicitly run the Python ... |
django commands cannot find the command module | 9,243,434 | 5 | 2012-02-11T19:38:20Z | 9,243,505 | 12 | 2012-02-11T19:48:10Z | [
"python",
"django",
"django-command-extensions"
] | When I do `./manage.py process_email` in my app, I get `ImportError: No module named commands.process_email`.
My directory layout is:
```
./
âââ __init__.py
âââ admin.py
âââ forms.py
âââ management
â âââ __init__.py
â âââ commands
â âââ __init.py__
â â... | Is `__init.py__` named correctly? I am not sure if that's a typo in your tree, or actually named like that.
Python treats directories containing `__init__.py` as modules - however, if that file does not exist it will not process that directory - so it won't process `__init.py__` or that "module". It is perfectly ok fo... |
Python: Get dictionary keys as list sorted by sub dictionary value | 9,243,958 | 4 | 2012-02-11T20:51:05Z | 9,244,003 | 9 | 2012-02-11T20:56:55Z | [
"python",
"sorting",
"dictionary"
] | I have the following structure:
```
structure = {
'pizza': {
# other fields
'sorting': 2,
},
'burger': {
# other fields
'sorting': 3,
},
'baguette': {
# other fields
'sorting': 1,
}
}
```
From this structure I need the keys of the outer dictionar... | The `list.sort()` method and the `sorted()` builtin function take a `key` argument, which is a function that's called for each item to be sorted, and the item is sorted based on the returnvalue of that keyfunction. So, write a function that takes a key in `structure` and returns the thing you want to sort on:
```
>>> ... |
Python: Get dictionary keys as list sorted by sub dictionary value | 9,243,958 | 4 | 2012-02-11T20:51:05Z | 9,244,005 | 7 | 2012-02-11T20:57:02Z | [
"python",
"sorting",
"dictionary"
] | I have the following structure:
```
structure = {
'pizza': {
# other fields
'sorting': 2,
},
'burger': {
# other fields
'sorting': 3,
},
'baguette': {
# other fields
'sorting': 1,
}
}
```
From this structure I need the keys of the outer dictionar... | You can use the `sorted` builtin function.
```
sorted(structure.keys(), key = lambda x: structure[x]['sorting'])
``` |
Python: Removing entries from ordered list, that are not in unordered list | 9,244,768 | 4 | 2012-02-11T22:53:45Z | 9,244,791 | 9 | 2012-02-11T22:58:27Z | [
"python",
"list",
"sorting"
] | I have two lists:
```
ordered = ['salat', 'baguette', 'burger', 'pizza']
unordered = ['pizza', 'burger']
```
Now I want to remove all entries from the ordered list, that are not in the unordered list while preserving the ordering.
How can I do this? | ```
ordered = [item for item in ordered if item in unordered]
```
This method creates a new list based on the old ones using Python's list comprehension.
For large amounts of data, turning the *unordered* list into a set first, as people suggested in comments, makes a huge difference in performance, e.g.:
```
unorde... |
Python conditional string formatting | 9,244,909 | 26 | 2012-02-11T23:16:00Z | 9,244,925 | 39 | 2012-02-11T23:19:02Z | [
"python",
"string-formatting"
] | I've been working on a text-based game in Python, and I've come across an instance where I want to format a string differently based on a set of conditions.
Specifically, I want to display text describing items in a room. I want this to be displayed, in the room's description, if and only if the item object in questio... | Your code actually *is* valid Python if you remove two characters, the comma and the colon.
```
>>> gender= "male"
>>> print "At least, that's what %s told me." %("he" if gender == "male" else "she")
At least, that's what he told me.
```
More modern style uses [`.format`](https://docs.python.org/library/string.html#f... |
Which Python Trove classifiers do I use? | 9,244,985 | 15 | 2012-02-11T23:28:12Z | 9,245,443 | 12 | 2012-02-12T00:47:25Z | [
"python",
"setup.py",
"pypi"
] | The list of Trove classifers is at: <http://pypi.python.org/pypi?:action=list_classifiers>
When I'm creating a PyPI package, I'm unsure whether I need to include the 'parents' to the trove classifiers that obviously apply to my project.
For example, if I've tested my project on Windows XP, then which of the following... | Technically, you don't need to include parent tags. For instance [lxml](http://pypi.python.org/pypi/lxml/2.3) lists these tags (but none of their parents):
```
Topic :: Text Processing :: Markup :: HTML
Topic :: Text Processing :: Markup :: XML
```
And browsing to the list of packages classified [Topic :: Text Proces... |
Is it reasonable in Python to check for a specific type of exception using isinstance? | 9,245,067 | 7 | 2012-02-11T23:41:39Z | 9,245,079 | 14 | 2012-02-11T23:43:54Z | [
"python",
"exception-handling",
"introspection",
"dnspython"
] | Is it reasonable in Python to catch a generic exception, then use `isinstance()` to detect the specific type of exception in order to handle it appropriately?
I'm playing around with the dnspython toolkit at the moment, which has a range of exceptions for things like a timeout, an NXDOMAIN response, etc. These excepti... | That's what multiple `except` clauses are for:
```
try:
answers = dns.resolver.query(args.host)
except dns.resolver.NXDOMAIN:
print "No such domain %s" % args.host
except dns.resolver.Timeout:
print "Timed out while resolving %s" % args.host
except dns.exception.DNSException:
print "Unhandled exception... |
Is Celery as efficient on a local system as python multiprocessing is? | 9,245,656 | 7 | 2012-02-12T01:32:12Z | 15,882,943 | 11 | 2013-04-08T15:20:50Z | [
"python",
"parallel-processing",
"multiprocessing",
"celery",
"pp"
] | I'm having a bit of trouble deciding whatever to use python multiprocessing or celery or pp for my application.
My app is very IO heavy and currently uses only one cpu so I need to spread it across all available cpus(which caused me to look at python's multiprocessing library) but I read that this library doesn't scal... | I just finished a test to decide how much celery adds as overhead over `multiprocessing.Pool` and shared arrays. The test runs the wiener filter on a (292, 353, 1652) uint16 array. Both versions use the same chunking (roughly:divide the 292,353 dimensions by the square root of the number of available cpu's). Two celery... |
TypeError: unbound method "method name" must be called with "Class name" instance as first argument (got str instance instead) | 9,245,657 | 8 | 2012-02-12T01:32:40Z | 9,245,676 | 17 | 2012-02-12T01:35:51Z | [
"python"
] | I think this should be a simple question to answer.
I have the next classes:
```
class GruposHandler(webapp.RequestHandler):
def get(self):
self.obtenerPagina()
def obtenerPagina(self, pOpcion = None, pMensajeInformacion = None):
opcion = pOpcion if pOpcion is not None else self.request.get('... | ```
grupoHandler = GruposHandler
```
==>
```
grupoHandler = GruposHandler()
```
---
UPDATE:
`GruposHandler.obtenerPagina()` method accepts 3 arguments:
`self`, `pOpcion=None` and `pMensajeInformacion=None`.
Since 2 of them are optional, you don't get:
```
TypeError: ... takes exactly 3 arguments (2 given)
```
... |
Jinja2 Inheritance with Blocks and Includes | 9,245,708 | 16 | 2012-02-12T01:43:11Z | 9,247,724 | 10 | 2012-02-12T09:25:36Z | [
"python",
"pyramid",
"jinja2"
] | I can't figure out how to modify blocks from included templates using Jinja2. Here's an example where I use three files.
base.html:
```
<html>{% include "content.html" %}</html>
```
content.html:
```
<h1>{% block title %}Title{% endblock title%}</h1>
<div>{% block content_body %}Content Body{% endblock content_body... | `base.html` is not rendered because it's not invoked by any template. What you *could* do is a second level of extension:
base.html:
```
<html>{% block html %}{% endblock %}</html>
```
content.html:
```
{% extends "base.html" %}
{% block html %}
<h1>{% block title %}Title{% endblock title%}</h1>
<div>{% block conte... |
How to print one character at a time on one line? | 9,246,076 | 11 | 2012-02-12T03:04:15Z | 9,246,096 | 19 | 2012-02-12T03:08:02Z | [
"python"
] | How would one print the string "hello world" onto one line, but one character at a time so that there is a delay between the printing of each letter? My solutions have either resulted in one character per line, or a delayed printing of the entire string at once. This is the closest I've gotten.
```
import time
string ... | Two tricks here, you need to use a stream to get everything in the right place and you also need to flush the stream buffer.
```
import time
import sys
def delay_print(s):
for c in s:
sys.stdout.write( '%s' % c )
sys.stdout.flush()
time.sleep(0.25)
delay_print("hello world")
``` |
Split string without non-characters | 9,246,589 | 4 | 2012-02-12T05:06:02Z | 9,246,634 | 10 | 2012-02-12T05:17:21Z | [
"python",
"split"
] | I'm trying to split a string that looks like this for example:
```
':foo [bar]'
```
Using `str.split()` on this of course returns `[':foo','[bar]']`
But how can I make it return just `['foo','bar']` containing only these characters? | I don't like regular expressions, but do like Python, so I'd probably write this as
```
>>> s = ':foo [bar]'
>>> ''.join(c for c in s if c.isalnum() or c.isspace())
'foo bar'
>>> ''.join(c for c in s if c.isalnum() or c.isspace()).split()
['foo', 'bar']
```
The ''.join idiom is a little strange, I admit, but you can ... |
Issue a POST request with url_for in Flask | 9,246,889 | 5 | 2012-02-12T06:16:43Z | 9,246,910 | 8 | 2012-02-12T06:23:31Z | [
"python",
"http-post",
"flask",
"jinja"
] | I'm trying to issue a POST request within a jinja template in Flask. However, parameters are passed in via GET by default, and this particular method only accepts POST requests.
I tried specifying \_method, as below, but it still passes the parameter with GET instead of POST.
```
<li><a href = "{{ url_for('save_info'... | All links are `GET` requests. You can't force a `POST`.
An alternative would be this:
```
@app.route('/save_info/<filepath>', methods=['GET', 'POST'])
def save_info(filepath):
if request.method == 'POST' or filepath:
...
```
You'll have to find a nice way to force your code to ignore that you sent a `GET` requ... |
Does python have a shorthand for this simple task? | 9,247,032 | 5 | 2012-02-12T06:53:37Z | 9,247,046 | 17 | 2012-02-12T06:56:34Z | [
"python"
] | I've just started to learn the long-heard python language. I've been working with C before. And I find python, as a modern script language is much concise on various tasks.
So I was wondering, if I have a list `foo = [1, 2, 3, 4, 5]`, and I want to pick all the odd numbers out of it into `bar`. In C, I might use a loo... | ```
bar = [x for x in foo if x % 2 == 1]
```
This form is called ["list comprehension"](http://www.secnetix.de/olli/Python/list_comprehensions.hawk). In its basic form, it has 4 parts:
1. What you want to include in the output list. Can be any expression involving the variable(s) defined in the second part (below). I... |
Table 'MyDjango.django_admin_log' doesn't exist | 9,247,489 | 8 | 2012-02-12T08:37:28Z | 9,247,508 | 7 | 2012-02-12T08:40:43Z | [
"python",
"django",
"django-admin"
] | I cannot create users and blogs in my django application.It simply shows an error("Table 'MyDjango.django\_admin\_log' doesn't exist") while press save button.The error message as shown below.
 | try running `python manage.py syncdb` |
Table 'MyDjango.django_admin_log' doesn't exist | 9,247,489 | 8 | 2012-02-12T08:37:28Z | 9,247,521 | 14 | 2012-02-12T08:43:33Z | [
"python",
"django",
"django-admin"
] | I cannot create users and blogs in my django application.It simply shows an error("Table 'MyDjango.django\_admin\_log' doesn't exist") while press save button.The error message as shown below.
 | Have you recently enabled admin history, but forgot to run `syncdb`? From what I see, Django had no problem locating your model tables, but when you tried to modify them through the admin interface it couldn't find the right table to store your actions. |
Textrank: complementing pagerank for sentence extraction using networkx | 9,247,538 | 5 | 2012-02-12T08:48:08Z | 9,247,791 | 9 | 2012-02-12T09:35:13Z | [
"python",
"pagerank",
"networkx",
"summarization"
] | I am trying to implement textrank algorithm for sentence extraction as described [here](http://acl.ldc.upenn.edu/acl2004/emnlp/pdf/Mihalcea.pdf). For that in need to complement pagerank algorithm with weighted edges and get it to run on undirected graphs.
Networkx pagerank algorithm implementation allows me to easely i... | I think you misinterpreted the note on the networkx documentation. Though, I must admit it might be worded better.
> The PageRank algorithm was designed for directed graphs but this
> algorithm does not check if the input graph is directed and will
> execute on undirected graphs by converting each oriented edge in the... |
Location of @classmethod | 9,247,625 | 5 | 2012-02-12T09:07:04Z | 9,247,713 | 8 | 2012-02-12T09:22:32Z | [
"python",
"decorator",
"python-2.7"
] | Where is the source code for the decorator classmethod located in the python source code. Specifically I am having trouble finding the exact file it's defined in version 2.7.2 | ```
tar -zxf Python-2.7.2.tgz
vim Python-2.7.2/Objects/funcobject.c
...
589 /* Class method object */
590
591 /* A class method receives the class as implicit first argument,
592 just like an instance method receives the instance.
593 To declare a class method, use this idiom:
594
595 class C:
596 de... |
Location of @classmethod | 9,247,625 | 5 | 2012-02-12T09:07:04Z | 9,248,432 | 9 | 2012-02-12T11:30:34Z | [
"python",
"decorator",
"python-2.7"
] | Where is the source code for the decorator classmethod located in the python source code. Specifically I am having trouble finding the exact file it's defined in version 2.7.2 | I am not answering what you asked - but bellow goes what could be a decorator equivalent to `classmethod`, written in Pure Python - since the one in the source code is in C, inside [`Python-2.7.2/Objects/funcobject.c`](http://hg.python.org/cpython/file/8527427914a2/Objects/funcobject.c#l589) as Mishna puts in his answe... |
django csrf_token not printing hidden input field | 9,247,669 | 6 | 2012-02-12T09:15:42Z | 9,247,725 | 7 | 2012-02-12T09:25:37Z | [
"python",
"django",
"csrf",
"django-csrf"
] | my `views.py` :
```
from django.core.context_processors import csrf
from django.views.decorators.csrf import csrf_protect
from django.http import *
from django.template import *
from django.shortcuts import *
# Create your views here.
@csrf_protect
def homepage(request):
return render_to_response('index.html',... | You need to use RequestContext in order to use CSRF middleware:
```
from django.template import RequestContext
# In your view:
return render_to_response('index.html'
{'files':os.listdir('/home/username/public_html/posters') },
context_instance=RequestContext(request))
```
BTW: Use of `csrf_protect` decorator... |
PySide / PyQt detect if user trying to close window | 9,249,500 | 10 | 2012-02-12T14:22:30Z | 9,249,527 | 35 | 2012-02-12T14:26:36Z | [
"python",
"pyqt",
"tkinter",
"pyqt4",
"pyside"
] | is there a way to detect if user trying to close window?
For example, in Tkinter we can do something like this:
```
def exit_dialog():
#do stuff
pass
root = Tk()
root.protocol("WM_DELETE_WINDOW", exit_dialog)
root.mainloop()
```
Thanks. | Override the [**`closeEvent`**](http://www.pyside.org/docs/pyside/PySide/QtGui/QWidget.html#PySide.QtGui.PySide.QtGui.QWidget.closeEvent) method of `QWidget` in your main window.
For example:
```
class MainWindow(QWidget): # or QMainWindow
...
def closeEvent(self, event):
# do stuff
if can_ex... |
mechanize cannot read form with SubmitControl that is disabled and has no value | 9,249,996 | 8 | 2012-02-12T15:33:10Z | 15,188,268 | 8 | 2013-03-03T17:12:26Z | [
"python",
"mechanize"
] | I'm attempting to use mechanize (v0.2.5) to work with a form on a page that has a disabled image as one of the form elements. When I try to select the form, mechanize raises an `AttributeError: control 'test' is disabled` where `test` is the name of the disabled control. For example,
```
br = mechanize.Browser(factory... | Sadly it's been more than a year and the mechanize upstream has [still not merged the pull request](https://github.com/jjlee/mechanize/pull/58).
Meanwhile you can use this monkey-patch I wrote to work around the bug without needing to manually install a patched version. Hopefully this bug will be resolved when (if) 0.... |
using class methods as celery tasks | 9,250,317 | 24 | 2012-02-12T16:12:52Z | 9,261,471 | 35 | 2012-02-13T13:36:08Z | [
"python",
"django-celery"
] | I'm trying to use the methods of class as the django-celery tasks, marking it up using @task decorator. The same situation is discribed [here](http://stackoverflow.com/questions/8846489/celery-python-object-methods), asked by Anand Jeyahar.
It's something like this
```
class A:
@task
def foo(self, bar):
... | Celery has experimental support for using methods as tasks since version 3.0.
The documentation for this is in `celery.contrib.methods`, and also mentions some caveats you should be aware of:
<http://docs.celeryproject.org/en/latest/reference/celery.contrib.methods.html> |
Fast IPC/Socket communication in Java/Python | 9,250,648 | 6 | 2012-02-12T16:57:25Z | 9,251,718 | 10 | 2012-02-12T19:02:41Z | [
"java",
"python",
"sockets",
"ipc"
] | Two processes (Java and Python) need to communicate in my application. I noticed that the socket communication takes 93% of the run time. Why is communication so slow? Should I be looking for alternatives to socket communication or can this be made faster?
Update: I discovered a simple fix. It seems like the Buffered ... | You have a number of options. Since you are using Linux you could use UNIX domain sockets. Or, you could serialise the data as ASCII or JSon or some other format and feed it through a pipe, SHM (shared memory segment), message queue, DBUS or similar. It's worth thinking about what sort of data you have, as these IPC me... |
Cross product of a vector in NumPy | 9,250,796 | 6 | 2012-02-12T17:13:40Z | 9,250,881 | 9 | 2012-02-12T17:23:12Z | [
"python",
"numpy"
] | Consider the following vectors (essentially`2x1` matrices):
```
a = sc.array([[1], [2], [3]])
>>> a
[[1]
[2]
[3]]
b = sc.array([[4], [5], [6]])
>>> b
[[4]
[5]
[6]]
```
The cross product of these vectors can be calculated using `numpy.cross()`. Why does this not work:
```
import numpy as np
np.cross(a, b)
Valu... | To compute the cross product using `numpy.cross`, the dimension (length) of the array dimension which defines the two vectors must either by two or three. To quote the documentation:
> If `a` and `b` are arrays of vectors, the vectors
> are defined by the last axis of `a` and `b` by default, and these axes
> can have ... |
Stacking astronomy images with Python | 9,251,580 | 17 | 2012-02-12T18:47:57Z | 9,254,288 | 19 | 2012-02-13T00:54:56Z | [
"python",
"image",
"python-imaging-library",
"astronomy",
"color-depth"
] | I thought this was going to be easier but after a while I'm finally giving up on this, at least for a couple of hours...
I wanted to reproduce this a trailing stars image from a timelapse set of pictures. Inspired by this:

[The original author](http://www.reddit.com/... | The problem here is that you are averaging the brightness at each pixel. This may seem sensible but it is actually not what you want at all -- the bright stars will get "averaged away" because they move accross the image. Take the following four frames:
```
1000 0000 0000 0000
0000 0100 0000 0000
0000 0000 0010 0000
0... |
Python: Resize an existing array and fill with zeros | 9,251,635 | 15 | 2012-02-12T18:54:26Z | 9,251,708 | 14 | 2012-02-12T19:01:49Z | [
"python",
"arrays",
"matrix",
"numpy",
"resize"
] | I think that my issue should be really simple, yet I can not find any help
on the Internet whatsoever. I am very new to Python, so it is possible that
I am missing something very obvious.
I have an array, S, like this `[x x x] (one-dimensional)`. I now create a
diagonal matrix, `sigma`, with `np.diag(S)` - so far, so ... | `sigma.resize()` returns `None` because it operates in-place. [`np.resize(sigma, shape)`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.resize.html), on the other hand, returns the result but **instead of padding with zeros, it pads with repeats of the array**.
Also, the `shape()` function returns the shap... |
Python: Resize an existing array and fill with zeros | 9,251,635 | 15 | 2012-02-12T18:54:26Z | 16,401,332 | 36 | 2013-05-06T14:50:08Z | [
"python",
"arrays",
"matrix",
"numpy",
"resize"
] | I think that my issue should be really simple, yet I can not find any help
on the Internet whatsoever. I am very new to Python, so it is possible that
I am missing something very obvious.
I have an array, S, like this `[x x x] (one-dimensional)`. I now create a
diagonal matrix, `sigma`, with `np.diag(S)` - so far, so ... | There is a new numpy function in version 1.7.0 [`numpy.pad`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.pad.html) that can do this in one-line. Like the other answers, you can construct the diagonal matrix with [`np.diag`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.diag.html) before the pa... |
random iteration in Python | 9,252,373 | 12 | 2012-02-12T20:26:43Z | 9,252,382 | 17 | 2012-02-12T20:28:07Z | [
"python",
"random",
"for-loop"
] | When you want to iterate sequentially over a list of numbers you will write:
```
for i in range(1000):
# do something with i
```
But what if you want to iterate over the list of numbers from the range (0..999) randomly? There is a need (in every iteration) to choose randomly the number that wasn't chosen in any pre... | You can use [`random.shuffle()`](http://docs.python.org/library/random.html#random.seed) to, well, shuffle a list:
```
import random
r = list(range(1000))
random.shuffle(r)
for i in r:
# do something with i
```
By the way, in many cases where you'd use a `for` loop over a range of integers in other programming lan... |
random iteration in Python | 9,252,373 | 12 | 2012-02-12T20:26:43Z | 9,253,366 | 13 | 2012-02-12T22:37:10Z | [
"python",
"random",
"for-loop"
] | When you want to iterate sequentially over a list of numbers you will write:
```
for i in range(1000):
# do something with i
```
But what if you want to iterate over the list of numbers from the range (0..999) randomly? There is a need (in every iteration) to choose randomly the number that wasn't chosen in any pre... | People often miss opportunities for modularization. You can define a function to encapsulate the idea of "iterate randomly":
```
def randomly(seq):
shuffled = list(seq)
random.shuffle(shuffled)
return iter(shuffled)
```
then:
```
for i in randomly(range(1000)):
#.. we're good to go ..
``` |
ImportError: Cannot import name X | 9,252,543 | 157 | 2012-02-12T20:49:23Z | 9,252,628 | 161 | 2012-02-12T21:01:26Z | [
"python",
"importerror",
"python-import"
] | I have four different files named: main, vector, entity, and physics. I will not post all the code, mostly just the imports, because I think that's where the error is. But if you want, I can post more.
Main:
```
import time
from entity import Ent
from vector import Vect
#the rest just creates an entity and prints the... | You have circular dependent imports. `physics.py` is imported from `entity` before class `Ent` is defined and `physics` tries to import `entity` that is already initializing. Remove the depency to `physics` from `entity` module. |
ImportError: Cannot import name X | 9,252,543 | 157 | 2012-02-12T20:49:23Z | 18,486,863 | 56 | 2013-08-28T11:40:12Z | [
"python",
"importerror",
"python-import"
] | I have four different files named: main, vector, entity, and physics. I will not post all the code, mostly just the imports, because I think that's where the error is. But if you want, I can post more.
Main:
```
import time
from entity import Ent
from vector import Vect
#the rest just creates an entity and prints the... | While you should definitely avoid circular dependencies, you can defer imports in python.
for example:
```
import SomeModule
def someFunction(arg):
from some.dependency import DependentClass
```
this ( at least in some instances ) will circumvent the error. |
ImportError: Cannot import name X | 9,252,543 | 157 | 2012-02-12T20:49:23Z | 23,836,838 | 29 | 2014-05-23T19:11:46Z | [
"python",
"importerror",
"python-import"
] | I have four different files named: main, vector, entity, and physics. I will not post all the code, mostly just the imports, because I think that's where the error is. But if you want, I can post more.
Main:
```
import time
from entity import Ent
from vector import Vect
#the rest just creates an entity and prints the... | This is a circular dependency. It can be solved without any structural modifications to the code. The problem occurs because in `vector` you demand that `entity` be made available for use immediately, and vice versa. The reason for this problem is that you asking to access the contents of the module before it is ready ... |
Using csvreader against a gzipped file in Python | 9,252,812 | 10 | 2012-02-12T21:25:57Z | 9,252,832 | 18 | 2012-02-12T21:28:27Z | [
"python",
"csv",
"gzip"
] | I have a bunch of gzipped CSV files that I'd like to open for inspection using Python's built in CSV reader. I'd like to do this without having first to manually unzip them to disk. I guess I want to somehow get a stream to the uncompressed data, and pass this into the CSV reader. Is this possible in Python? | Use the `gzip` module:
```
with gzip.open(filename) as f:
reader = csv.reader(f)
#...
``` |
Using csvreader against a gzipped file in Python | 9,252,812 | 10 | 2012-02-12T21:25:57Z | 20,731,454 | 12 | 2013-12-22T16:23:02Z | [
"python",
"csv",
"gzip"
] | I have a bunch of gzipped CSV files that I'd like to open for inspection using Python's built in CSV reader. I'd like to do this without having first to manually unzip them to disk. I guess I want to somehow get a stream to the uncompressed data, and pass this into the CSV reader. Is this possible in Python? | I've tried the above version for writing and reading and it didn't work in Python 3.3 due to "bytes" error. However, after some trial and error I could get the following to work. Maybe it also helps others:
```
import csv
import gzip
import io
with gzip.open("test.gz", "w") as file:
writer = csv.writer(io.TextIO... |
coding guidelines for python dictionaries | 9,253,432 | 3 | 2012-02-12T22:46:32Z | 9,253,478 | 8 | 2012-02-12T22:53:13Z | [
"python",
"coding-style"
] | I have a python dictionary, definition of which does not fit in a single line. Could anyone please tell me guidelines for python dictionaries. I currently have this which does not look good to my eyes.
```
initialstate = {
'state':grid,
'f':find_manhattan_distance(grid,goal),
... | `pep8.py` says:
```
mydict.py:2:28: E231 missing whitespace after ':'
mydict.py:1:15: E222 multiple spaces after operator
```
Try this:
```
initialstate = {
'state': grid,
'f': find_manhatten_distance(grid, goal),
'g': 0,
'h': find_manhatten_distance(grid, goal),
'ancestor': None
}
```
Notice th... |
Selecting specific <tr> tags with BeautifulSoup | 9,253,684 | 4 | 2012-02-12T23:21:55Z | 9,264,760 | 7 | 2012-02-13T17:11:27Z | [
"python",
"beautifulsoup"
] | I am fetching some html table rows with BeautifulSoup with this piece of code:
```
from bs4 import BeautifulSoup
import urllib2
import re
page = urllib2.urlopen('www.something.bla')
soup = BeautifulSoup(page)
rows = soup.findAll('tr', attrs={'class': re.compile('class1.*')})
```
This is what I get as a result:
```
... | Perhaps it's easier without regex. This works with BeautifulSoup 3:
```
from BeautifulSoup import BeautifulSoup
page = """
<tr class="class1 class2 class3">1</tr>
<tr class="class1 class2 class3">2</tr>
<tr class="class1 class5">3</tr>
<tr class="class1_a class5_a">4</tr>
<tr class="class1 class5">5</tr>
<tr class="c... |
the sample python twisted event driven web application increments request count by 2, why? | 9,253,773 | 6 | 2012-02-12T23:35:31Z | 9,253,792 | 7 | 2012-02-12T23:38:27Z | [
"python",
"twisted"
] | The sample code for a basic web server given by <http://twistedmatrix.com/trac/> seems to increment the request counter by two for each request, rather than by 1.
The code:
```
from twisted.web import server, resource
from twisted.internet import reactor
class HelloResource(resource.Resource):
isLeaf = True
... | Browsers can behave in surprising ways. If you try printing the full request, you might find it is requesting "/" and also "favicon.ico", for example. |
Python: is index() buggy at all? | 9,254,173 | 2 | 2012-02-13T00:34:47Z | 9,254,210 | 8 | 2012-02-13T00:41:45Z | [
"python",
"indexing"
] | I'm working through this thing on pyschools and it has me mystified.
Here's the code:
```
def convertVector(numbers):
totes = []
for i in numbers:
if i!= 0:
totes.append((numbers.index(i),i))
return dict((totes))
```
Its supposed to take a 'sparse vector' as input (ex: `[1, 0, 1 , 0, 2... | index() only returns the first:
```
>>> a = [1,2,3,3]
>>> help(a.index)
Help on built-in function index:
index(...)
L.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
```
If you want both the number and the index, you can take advantage o... |
Python 2: different meaning of the 'in' keyword for sets and lists | 9,255,440 | 8 | 2012-02-13T04:02:35Z | 9,255,474 | 14 | 2012-02-13T04:07:19Z | [
"python",
"list",
"set",
"equality"
] | Consider this snippet:
```
class SomeClass(object):
def __init__(self, someattribute="somevalue"):
self.someattribute = someattribute
def __eq__(self, other):
return self.someattribute == other.someattribute
def __ne__(self, other):
return not self.__eq__(other)
list_of_objects ... | The meaning is the same, but the implementation is different. Lists simply examine each object, checking for equality, so it works for your class. Sets first hash the objects, and if they don't implement hash properly, the set appears not to work.
Your class defines `__eq__`, but doesn't define `__hash__`, and so won'... |
Using defaultdict with multiprocessing? | 9,256,687 | 4 | 2012-02-13T07:03:42Z | 9,258,192 | 7 | 2012-02-13T09:31:35Z | [
"python",
"multiprocessing",
"defaultdict"
] | Just experimenting and learning, and I know how to create a shared dictionary that can be accessed with multiple proceses but I'm not sure how to keep the dict synced. `defaultdict`, I believe, illustrates the problem I'm having.
```
from collections import defaultdict
from multiprocessing import Pool, Manager, Proces... | You can subclass `BaseManager` and register additional types for sharing. You need to provide a suitable proxy type in cases where the default `AutoProxy`-generated type does not work. For `defaultdict`, if you only need to access the attributes that are already present in `dict`, you can use `DictProxy`.
```
from mul... |
Behaviour of Mutlple inheritance in python | 9,256,781 | 5 | 2012-02-13T07:13:35Z | 9,256,850 | 8 | 2012-02-13T07:21:14Z | [
"python",
"class",
"default-constructor"
] | ```
In [5]: class a(object):
...: def __init__(self):
...: print "In class a"
...: self.a = 1
...:
In [6]: class b(object):
...: def __init__(self):
...: print "In class b"
...: self.b = 2
...:
...:
In [7]: class c(b, a):
... | In python, initialization methods from upper classes aren't called by default. To do that, you have to explicitly call them using [super](http://docs.python.org/library/functions.html#super) as follows:
```
class a(object):
def __init__(self):
super(a, self).__init__()
print "In class a"
se... |
How to change a string into uppercase | 9,257,094 | 304 | 2012-02-13T07:48:56Z | 9,257,122 | 543 | 2012-02-13T07:51:59Z | [
"python",
"string",
"uppercase"
] | I have problem in changing a string into uppercase with Python. In my research, I got `string.ascii_uppercase` but it doesn't work.
The following code:
```
>>s = 'sdsd'
>>s.ascii_uppercase
```
Gives this error message:
```
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: ... | ```
>>> s = 'sdsd'
>>> s.upper()
'SDSD'
```
See [String Methods](https://docs.python.org/2/library/stdtypes.html#string-methods). |
How to change a string into uppercase | 9,257,094 | 304 | 2012-02-13T07:48:56Z | 9,257,158 | 59 | 2012-02-13T07:56:24Z | [
"python",
"string",
"uppercase"
] | I have problem in changing a string into uppercase with Python. In my research, I got `string.ascii_uppercase` but it doesn't work.
The following code:
```
>>s = 'sdsd'
>>s.ascii_uppercase
```
Gives this error message:
```
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: ... | To get upper case version of a string you can use [`str.upper`](http://docs.python.org/library/stdtypes.html#str.upper):
```
s = 'sdsd'
s.upper()
#=> 'SDSD'
```
On the other hand [`string.ascii_uppercase`](http://docs.python.org/library/string.html#string.ascii_uppercase) is a string containing all ASCII letters in u... |
How to get the original python data from QVariant | 9,257,422 | 9 | 2012-02-13T08:25:36Z | 9,267,495 | 10 | 2012-02-13T20:26:17Z | [
"python",
"pyqt",
"pyqt4",
"data-conversion",
"qvariant"
] | I am just learning python and Qt these days. So please consider that this will be a newbie question, but I am stuck here.
```
import sys
from PyQt4.QtCore import *
data1 = 'string'
data2 = QVariant(data1)
data3 = data2.toPyObject()
```
I expected data3 is the same as data1, 'string'. However in my system data3 is
`... | You can work around this issue by wrapping your data in an immutable container:
```
>>> from PyQt4.QtCore import QVariant
>>> data = {'key1': 123, 'key2': 456}
>>> v = QVariant((data,))
>>> v.toPyObject()[0]
{'key2': 456, 'key1': 123}
``` |
Elegant pythonic cumsum | 9,258,602 | 9 | 2012-02-13T10:03:22Z | 9,258,634 | 28 | 2012-02-13T10:06:19Z | [
"python"
] | What would be an elegant and pythonic way to implement cumsum?
Alternatively - if there'a already a built-in way to do it, that would be even better of course... | It's available in [Numpy](http://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html):
```
>>> import numpy as np
>>> np.cumsum([1,2,3,4,5])
array([ 1, 3, 6, 10, 15])
```
Or use [`itertools.accumulate`](http://docs.python.org/dev/library/itertools.html#itertools.accumulate) since Python 3.2:
```
>>> fro... |
Tutorial for Django CMS App Hook | 9,258,926 | 4 | 2012-02-13T10:29:50Z | 9,263,286 | 12 | 2012-02-13T15:38:46Z | [
"python",
"django",
"django-views",
"django-urls",
"django-cms"
] | I have a Django CMS Project, which needs to create a Non CMS App "Achievemnets". The Customer wants full control over the page design, that means the page should be a CMS Page. However I have created specific views to show all the achievemtns in a page and clicking on the more link, it will show in detail. I need to po... | When you "hook" an application's URLs to a Django-CMS page, your app's URLs and view functions take over from there.
Let's say your Django-CMS page URL is: /achievements/
On this page, you want to display a list of achievements, which is going to come from your application.
```
#your_app.urls
from django.conf.urls.d... |
How to write to a file using non blocking IO? | 9,259,380 | 11 | 2012-02-13T11:04:17Z | 13,644,499 | 12 | 2012-11-30T11:36:07Z | [
"python",
"file-io",
"nonblocking"
] | I want to write to a file using a non-blocking method in Python. On some googling, I found that the language supports `fcntl` in order to do so, but the method to implement the same is not very clear to me.
This is the code snippet (I don't know where I am going wrong):
```
import os, fcntl
nf = fcntl.fcntl(0,fcntl.F... | This is how you turn non-blocking mode on for a file in UNIX:
```
fd = os.open("filename", os.O_CREAT | os.O_WRONLY | os.O_NONBLOCK)
os.write(fd, "data")
os.close(fd)
```
On UNIX, however, [turning on non-blocking mode has no visible effect for regular files](http://www.remlab.net/op/nonblock.shtml)! Even though the ... |
Select random item with weight | 9,259,989 | 3 | 2012-02-13T11:49:48Z | 9,260,168 | 9 | 2012-02-13T12:02:01Z | [
"python",
"random"
] | I have a list of approx. 10000 items. The current situation is that every item has an associated weight (priority or importance). Now the smallest weight is `-100` (negative and zero values can be removed) and the highest weight is `1500`. Weight is determined by intuition by people (how somebody thinks the item is imp... | Have a look at this, i think it's what you need with some nice comparision between different methods [Weighted random generation in Python](http://eli.thegreenplace.net/2010/01/22/weighted-random-generation-in-python/)
The simplest approach suggested is:
```
import random
def weighted_choice(weights):
totals = [... |
Django view returning json without using template | 9,262,278 | 45 | 2012-02-13T14:36:19Z | 9,262,330 | 7 | 2012-02-13T14:39:49Z | [
"python",
"html",
"django",
"json"
] | This related to this question: [Django return json and html depending on client python](http://stackoverflow.com/questions/9260249/django-return-json-and-html-depending-on-client-python)
I have a command line python api for a django app. When I access the app through the api it should return json and with a browser it... | In the case of the JSON response there is no template to be rendered. Templates are for generating HTML responses. The JSON is the HTTP response.
However, you can have HTML that is rendered from a template withing your JSON response.
```
html = render_to_string("some.html", some_dictionary)
serialized_data = simplejs... |
Django view returning json without using template | 9,262,278 | 45 | 2012-02-13T14:36:19Z | 9,263,606 | 91 | 2012-02-13T15:57:38Z | [
"python",
"html",
"django",
"json"
] | This related to this question: [Django return json and html depending on client python](http://stackoverflow.com/questions/9260249/django-return-json-and-html-depending-on-client-python)
I have a command line python api for a django app. When I access the app through the api it should return json and with a browser it... | I think the issue has gotten confused regarding what you want. I imagine you're not actually trying to put the HTML in the JSON response, but rather want to alternatively return either HTML or JSON.
First, you need to understand the core difference between the two. HTML is a presentational format. It deals more with h... |
Django view returning json without using template | 9,262,278 | 45 | 2012-02-13T14:36:19Z | 26,726,893 | 47 | 2014-11-04T02:43:28Z | [
"python",
"html",
"django",
"json"
] | This related to this question: [Django return json and html depending on client python](http://stackoverflow.com/questions/9260249/django-return-json-and-html-depending-on-client-python)
I have a command line python api for a django app. When I access the app through the api it should return json and with a browser it... | In Django 1.7 this is even easier with the built-in JsonResponse.
<https://docs.djangoproject.com/en/dev/ref/request-response/#jsonresponse-objects>
```
# import it
from django.http import JsonResponse
def my_view(request):
# do something with the your data
data = {}
# just return a JsonResponse
re... |
compare year and month of date field to be greater than | 9,264,094 | 3 | 2012-02-13T16:27:20Z | 9,264,293 | 8 | 2012-02-13T16:40:15Z | [
"python",
"django"
] | I'm going to do this query:
```
today = datetime.date.today()
year=today.year
month=today.month
news=News.objects.filter(date__year__lt = year,date__month__lt=month)
```
Note:News object has a field named `date`
but I get this error:
```
Join on field 'date' not permitted. Did you misspell 'year' for the lookup type... | You can't append `__lt` onto to `__year` or `__month`. Only the last double-underscored bit is consider the qualifier, everything before it is treated as a traversal, i.e. Django will try to look up a field named `year` on join table named `date`, which is obviously not correct.
For something like this you'll need to ... |
Given a matrix of type `scipy.sparse.coo_matrix` how to determine index and value of maximum of each row? | 9,268,710 | 3 | 2012-02-13T22:01:51Z | 9,337,071 | 7 | 2012-02-17T23:52:35Z | [
"python",
"matrix",
"scipy",
"max",
"sparse-matrix"
] | Given a sparse matrix`R` of type `scipy.sparse.coo_matrix` of shape `1.000.000 x 70.000` I figured out that
```
row_maximum = max(R.getrow(i).data)
```
will give me the maximum value of the i-th row.
**What I need now is the index corresponding to the value `row_maximum`.**
Any ideas how to achieve that?
Thanks fo... | `getrow(i)` returns a 1 x n CSR matrix, which has an `indices` attribute that gives the row indices of the corresponding values in the `data` attribute. (We know the shape is 1 x n, so we don't have to deal with the `indptr` attribute.) So this will work:
```
row = R.getrow(i)
max_index = row.indices[row.data.argmax()... |
how to capture a traceback in gevent | 9,268,916 | 5 | 2012-02-13T22:21:40Z | 9,273,337 | 14 | 2012-02-14T07:44:37Z | [
"python",
"exception-handling",
"gevent",
"greenlets"
] | I've spawned a Greenlet and linked it to a callable. Some time later, the Greenlet fails with an Exception. The linked callable gets called. That's all great!
Here's the issue:
The traceback for the Exception appears on my console, as you'd expect. But I want do things with that traceback within the linked callable. ... | The traceback is intentionally not saved when the Greenlet dies. If it was saved, it would keep a lot of objects alive that are expected to be deleted, which matters especially if the object manages some resource (open file or socket).
If you want to save the traceback you have to do it yourself. |
Is there a way to create subclasses on-the-fly? | 9,269,902 | 3 | 2012-02-13T23:59:04Z | 9,269,964 | 12 | 2012-02-14T00:08:04Z | [
"python",
"class",
"singleton",
"subclass",
"subclassing"
] | I'm creating a game in which I have a somewhat complex method for creating entities.
When a level is loaded, the loading code reads a bunch of YAML files that contain attributes of all the different possible units. Using the YAML file, it creates a so-called `EntityResource` object. This EntityResource object serves a... | I'm not sure if this is what you're looking for, but you can use [`type`](http://docs.python.org/library/functions.html#type) to create subclasses dynamically:
```
SubClass = type('SubClass', (EntityResource,), {})
```
Edit: To understand how `type` works, you just need to translate how would you write the class and ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.