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 |
|---|---|---|---|---|---|---|---|---|---|
Weird Integer Cache inside Python | 15,171,695 | 26 | 2013-03-02T06:50:35Z | 15,172,182 | 36 | 2013-03-02T07:54:41Z | [
"python",
"code-analysis",
"literals",
"python-internals"
] | After dive into Python's source code, I find out that it maintains an array of `PyInt_Object`s ranging from int(-5) to int(256) (@src/Objects/intobject.c)
A little experiment proves it:
```
>>> a = 1
>>> b = 1
>>> a is b
True
>>> a = 257
>>> b = 257
>>> a is b
False
```
But if I run those code together in a py file ... | It's pretty simple. Python caches integers in the range `[-5, 256]`(if I remember correctly), so it is expected that integers in that range are also identical.
What you see is the Python compiler optimizing identical literals when part of the same text.
When typing in the Python shell each line is a completely differ... |
How to calculate cosine similarity given 2 sentence strings? - Python | 15,173,225 | 28 | 2013-03-02T10:06:29Z | 15,173,821 | 34 | 2013-03-02T11:15:56Z | [
"python",
"string",
"nlp",
"similarity",
"cosine-similarity"
] | From [Python: tf-idf-cosine: to find document similarity](http://stackoverflow.com/questions/12118720/python-tf-idf-cosine-to-find-document-similarity) , it is possible to calculate document similarity using tf-idf cosine. Without importing external libraries, are that any ways to calculate cosine similarity between 2 ... | The short answer is "no, it is not possible to do that in a principled way that works even remotely well". It is an unsolved problem in natural language processing research and also happens to be the subject of my doctoral work. I'll very briefly summarize where we are and point you to a few publications:
**Meaning of... |
How to calculate cosine similarity given 2 sentence strings? - Python | 15,173,225 | 28 | 2013-03-02T10:06:29Z | 15,174,569 | 61 | 2013-03-02T12:40:22Z | [
"python",
"string",
"nlp",
"similarity",
"cosine-similarity"
] | From [Python: tf-idf-cosine: to find document similarity](http://stackoverflow.com/questions/12118720/python-tf-idf-cosine-to-find-document-similarity) , it is possible to calculate document similarity using tf-idf cosine. Without importing external libraries, are that any ways to calculate cosine similarity between 2 ... | A simple pure-Python implementation would be:
```
import re, math
from collections import Counter
WORD = re.compile(r'\w+')
def get_cosine(vec1, vec2):
intersection = set(vec1.keys()) & set(vec2.keys())
numerator = sum([vec1[x] * vec2[x] for x in intersection])
sum1 = sum([vec1[x]**2 for x in vec1.ke... |
Python threads and queue example | 15,173,975 | 11 | 2013-03-02T11:32:36Z | 15,173,985 | 7 | 2013-03-02T11:34:32Z | [
"python",
"multithreading",
"queue"
] | I'm new to python (I come from PHP), I've been reading tutorials and trying things for a couple of days but I can't understand this queue example (<http://docs.python.org/2/library/queue.html>)
```
def worker():
while True:
item = q.get()
do_work(item)
q.task_done()
q = Queue()
for i in ra... | Threads do not exit normally in this code (they are indeed blocked when the queue is empty). The program doesn't wait for them because they're [daemon threads](http://docs.python.org/2/library/threading.html#thread-objects).
The program doesn't exit immediately and doesn't block forever because of [`q.join`](http://do... |
build scipy error cythonize failed | 15,175,135 | 23 | 2013-03-02T13:43:22Z | 15,176,470 | 43 | 2013-03-02T16:03:11Z | [
"python",
"scipy",
"cython"
] | I'm trying to build scipy and I get a RuntimeError:
```
$sudo python setup.py build
Processing scipy/cluster/_vq_rewrite.pyx
Traceback (most recent call last):
File "tools/cythonize.py", line 172, in <module>
main()
File "tools/cythonize.py", line 168, in main
find_process_files(root_dir)
File "tools/cyt... | Python setuptools solved the problem.
<http://docs.cython.org/src/quickstart/install.html>
`easy_install cython` or `pip install cython` |
How can I do multiple substitutions using regex in python? | 15,175,142 | 14 | 2013-03-02T13:43:48Z | 15,175,193 | 10 | 2013-03-02T13:49:59Z | [
"python",
"regex",
"string"
] | I can use this code below to create a new file with the substitution of `a` with `aa` using regular expressions.
```
import re
with open("notes.txt") as text:
new_text = re.sub("a", "aa", text.read())
with open("notes2.txt", "w") as result:
result.write(new_text)
```
I was wondering do I have to use ... | You can use capturing group and backreference:
```
re.sub(r"([characters])", r"\1\1", text.read())
```
Put characters that you want to double up in between `[]`. For the case of lower case `a`, `b`, `c`:
```
re.sub(r"([abc])", r"\1\1", text.read())
```
In the replacement string, you can refer to whatever matched by... |
How can I do multiple substitutions using regex in python? | 15,175,142 | 14 | 2013-03-02T13:43:48Z | 15,175,239 | 13 | 2013-03-02T13:53:31Z | [
"python",
"regex",
"string"
] | I can use this code below to create a new file with the substitution of `a` with `aa` using regular expressions.
```
import re
with open("notes.txt") as text:
new_text = re.sub("a", "aa", text.read())
with open("notes2.txt", "w") as result:
result.write(new_text)
```
I was wondering do I have to use ... | The answer proposed by @nhahtdh is valid, but I would argue less pythonic than the canonical example, which uses code less opaque than his regex manipulations and takes advantage of python's built-in data structures and anonymous function feature.
A dictionary of translations makes sense in this context. In fact, that... |
SQLAlchemy - what is declarative_base | 15,175,339 | 12 | 2013-03-02T14:01:48Z | 15,176,114 | 14 | 2013-03-02T15:25:58Z | [
"python",
"sqlalchemy"
] | I am learning sqlalchemy. Here is my initial code :
File : user.py
```
from sqlalchemy import Column,Integer,Sequence, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer,Sequence('user_seq'),primary_key=True)
use... | [`declarative_base()`](http://docs.sqlalchemy.org/en/rel_0_8/orm/extensions/declarative.html#sqlalchemy.ext.declarative.declarative_base) is a factory function that constructs a base class for declarative class definitions (which is assigned to `Base` variable in your example). The one you created in user.py is associa... |
Can I insert matplotlib graphs into Excel programmatically? | 15,177,705 | 8 | 2013-03-02T18:08:44Z | 15,177,991 | 7 | 2013-03-02T18:39:27Z | [
"python",
"excel",
"matplotlib"
] | I am saving matplotlib files as .tiff images. I'd like to be able to then open an excel file and paste the image there.
openpyxl doesnot seem to support image embedding. xlwt does but only bmp.
ALternatively if i can programmatically convert tiff to bmp, that might help also.
Ideas on either are welcome.
Similar to... | Here is what I found from two different links on the web, that worked perfectly for me. Matplotlib allows saving png files which is what I make use of here:
```
from PIL import Image
file_in = "image.png"
img = Image.open(file_in)
file_out = 'test1.bmp'
print len(img.split()) # test
if len(img.split()) == 4:
# pr... |
line smoothing algorithm in python? | 15,178,146 | 2 | 2013-03-02T18:56:23Z | 15,180,087 | 11 | 2013-03-02T22:20:10Z | [
"python",
"algorithm",
"numpy",
"line",
"smoothing"
] | I am doing research on line generalization, which will be applied to obtain generalized Road Network map from large scale map to small scale map. I am using two operation and two algorithms. It is done in python programming language using shapefile library, it is for vector data in 2d.
Operation: Selection and Eliminat... | You can smooth the path by following code:
```
from scipy.ndimage import gaussian_filter1d
import numpy as np
a=np.array([[78.03881018900006, 30.315651467000066],
[78.044901609000078, 30.31512798600005],
[78.04927981700007, 30.312510579000048],
[78.050041244000056, 30.301755415000059],
[78.072646124000073, 30.281... |
Converting subset of strings to integers in a list | 15,180,211 | 9 | 2013-03-02T22:32:03Z | 15,180,249 | 10 | 2013-03-02T22:35:59Z | [
"python"
] | I frequently find myself with a list that looks like this:
```
lst = ['A', '1', '2', 'B', '1', 'C', 'D', '4', '1', '4', '5', 'Z', 'D']
```
What is the most pythonic way to convert specific strings in this list to ints?
I typically do something like this:
```
lst = [lst[0], int(lst[1]), int(lst[2]), lst[3], ...]
```... | I would say something like:
```
>>> lst = ['A', '1', '2', 'B', '1', 'C', 'D', '4', '1', '4', '5', 'Z', 'D']
>>> lst = [int(s) if s.isdigit() else s for s in lst]
>>> lst
['A', 1, 2, 'B', 1, 'C', 'D', 4, 1, 4, 5, 'Z', 'D']
``` |
How to include third party Python packages in Sublime Text 2 plugins | 15,180,537 | 21 | 2013-03-02T23:12:59Z | 15,180,938 | 16 | 2013-03-03T00:08:17Z | [
"python",
"plugins",
"sublimetext2",
"distutils",
"python-requests"
] | I'm writing a sublime text 2 plugin that uses a module [SEAPI.py](http://stackapps.com/questions/3881/se-api-py-a-lightwight-python-wrapper-for-se-api) which in itself imports the [requests module](http://docs.python-requests.org/en/latest/).
Since sublime text 2 uses it's own embedded python interpreter, it doesn't s... | You need to bundle full requests distribution with your Python package and then modify Python's `sys.path` (where it looks for modules) to point to a folder containing `requests` folder.
* Download Requests library from a PyPi and extract it manually under your plugin folder
* **Before** importing requests in your plu... |
Using DictVectorizer with sklearn DecisionTreeClassifier | 15,181,311 | 10 | 2013-03-03T01:04:09Z | 15,184,234 | 13 | 2013-03-03T09:21:29Z | [
"python",
"machine-learning",
"scikit-learn"
] | I try to start a decision tree with python and sklearn.
Working approach was like this:
```
import pandas as pd
from sklearn import tree
for col in set(train.columns):
if train[col].dtype == np.dtype('object'):
s = np.unique(train[col].values)
mapping = pd.Series([x[0] for x in enumerate(s)], inde... | The way you enumerate your samples is not meaningful. Just print them to make it obvious:
```
>>> import pandas as pd
>>> train = pd.DataFrame({'a' : ['a', 'b', 'a'], 'd' : ['e', 'e', 'f'],
... 'b' : [0, 1, 1], 'c' : ['b', 'c', 'b']})
>>> samples = [dict(enumerate(sample)) for sample in train]
>>... |
How to get Job by id in RQ python? | 15,181,630 | 4 | 2013-03-03T01:56:34Z | 15,186,022 | 7 | 2013-03-03T13:12:30Z | [
"python",
"redis"
] | So, basically I want to build a long-polling application which is using RQ on heroku. I have looked at this question [Flask: passing around background worker job (rq, redis)](http://stackoverflow.com/questions/12162021/flask-passing-around-background-worker-job-rq-redis) but it doesn't help.
This is basically what I'm... | I found this out already, in case anybody is interested. It has to be this one instead.
```
Job.fetch(job_id, connection=conn)
``` |
Python 3.3 can't import Crypt | 15,181,739 | 2 | 2013-03-03T02:14:12Z | 15,181,900 | 7 | 2013-03-03T02:44:42Z | [
"python",
"python-3.3"
] | When I type in import Crypt on the command line it says:
```
>>>import crypt
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python33\lib\crypt.py", line 3, in <module>
import _crypt
ImportError: No module named '_crypt'
``` | The [`crypt` module](http://docs.python.org/3/library/crypt) is an interface to the Unix [`crypt` library](http://linux.die.net/man/3/crypt) which is used for encrypting Unix passwords. It is documented as not being available on Windows. It is not a general purpose cryptography library. |
Understanding the set() function | 15,181,867 | 23 | 2013-03-03T02:39:27Z | 15,181,903 | 35 | 2013-03-03T02:45:12Z | [
"python",
"set"
] | In python, `set()` is an unordered collection with no duplicate elements. However, I am not able to understand how it generates the output.
For example, consider the following:
```
>>> x = [1, 1, 2, 2, 2, 2, 2, 3, 3]
>>> set(x)
set([1, 2, 3])
>>> y = [1, 1, 6, 6, 6, 6, 6, 8, 8]
>>> set(y)
set([8, 1, 6])
>>> z = [1,... | Sets are unordered, as you say. Even though one way to implement sets is using a tree, they can also be implemented using a hash table (meaning getting the keys in sorted order may not be that trivial).
If you'd like to sort them, you can simply perform:
```
sorted(set(y))
```
Otherwise, the only thing guaranteed by... |
Understanding the set() function | 15,181,867 | 23 | 2013-03-03T02:39:27Z | 15,181,907 | 10 | 2013-03-03T02:46:28Z | [
"python",
"set"
] | In python, `set()` is an unordered collection with no duplicate elements. However, I am not able to understand how it generates the output.
For example, consider the following:
```
>>> x = [1, 1, 2, 2, 2, 2, 2, 3, 3]
>>> set(x)
set([1, 2, 3])
>>> y = [1, 1, 6, 6, 6, 6, 6, 8, 8]
>>> set(y)
set([8, 1, 6])
>>> z = [1,... | As an unordered collection type, `set([8, 1, 6])` is equivalent to `set([1, 6, 8])`.
While it might be nicer to display the set contents in sorted order, that would make the `repr()` call more expensive.
Internally, the `set` type is implemented using a hash table: a hash function is used to separate items into a num... |
New style formatting with tuple as argument | 15,181,927 | 15 | 2013-03-03T02:50:54Z | 15,181,942 | 28 | 2013-03-03T02:55:03Z | [
"python",
"string",
"formatting"
] | Why can't I use tuple as argument to formatter in new style ("string".format())? It works fine in old style ("string" %)?
This code works:
```
>>> tuple = (500000, 500, 5)
... print "First item: %d, second item: %d and third item: %d." % tuple
First item: 500000, second item: 500 and third item: 5.
```
And this... | The old way of formatting used a binary operator, `%`. By its nature, it can only accept two arguments. The new way of formatting uses a method. Methods can take any number of arguments.
Since you sometimes need to pass multiple things to format and it's somewhat clumsy to create tuples with one item all the time, the... |
New style formatting with tuple as argument | 15,181,927 | 15 | 2013-03-03T02:50:54Z | 15,181,946 | 14 | 2013-03-03T02:55:31Z | [
"python",
"string",
"formatting"
] | Why can't I use tuple as argument to formatter in new style ("string".format())? It works fine in old style ("string" %)?
This code works:
```
>>> tuple = (500000, 500, 5)
... print "First item: %d, second item: %d and third item: %d." % tuple
First item: 500000, second item: 500 and third item: 5.
```
And this... | As [icktoofay](http://stackoverflow.com/a/15181942/1907098) explained, in the old style of formatting, if you passed in a tuple, Python would automatically unpack it.
However, you can't use a tuple with the `str.format` method because Python thinks that you're only passing in one argument. You would have to unpack the... |
How to return a view of several columns in numpy structured array | 15,182,381 | 17 | 2013-03-03T04:13:14Z | 21,819,324 | 19 | 2014-02-17T01:36:26Z | [
"python",
"arrays",
"numpy"
] | I can see several columns (`fields`) at once in a `numpy` structured array by indexing with a list of the field names, for example
```
import numpy as np
a = np.array([(1.5, 2.5, (1.0,2.0)), (3.,4.,(4.,5.)), (1.,3.,(2.,6.))],
dtype=[('x',float), ('y',float), ('value',float,(2,2))])
print a[['x','y']]
#[(1.5,... | You can create a dtype object contains only the fields that you want, and use `numpy.ndarray()` to create a view of original array:
```
import numpy as np
strc = np.zeros(3, dtype=[('x', int), ('y', float), ('z', int), ('t', "i8")])
def fields_view(arr, fields):
dtype2 = np.dtype({name:arr.dtype.fields[name] for ... |
Multiple parameters in in Flask approute | 15,182,696 | 7 | 2013-03-03T05:16:46Z | 15,182,724 | 7 | 2013-03-03T05:20:22Z | [
"python",
"flash"
] | How to write the flask approute if i have multiple parameters in the URL call. Here is my URL i am calling from AJax
```
http://0.0.0.0:8888/createcm?summary=VVV&change=Feauure
```
i was trying to write my flask approute like this.
```
@app.route('/test/<summary,change> ,methods=['GET']
`... | Routes do not match a query string, which is passed to your method directly.
```
from flask import request
@app.route('/createcm', methods=['GET'])
def foo():
print request.args.get('summary')
print request.args.get('change')
``` |
Fit two normal distributions (histograms) with MCMC using pymc? | 15,184,293 | 13 | 2013-03-03T09:28:57Z | 15,190,160 | 15 | 2013-03-03T19:58:11Z | [
"python",
"statistics",
"pymc"
] | I am trying to fit line profiles as detected with a spectrograph on a CCD. For ease of consideration, I have included a demonstration that, if solved, is very similar to the one I *actually* want to solve.
I've looked at this:
<http://stats.stackexchange.com/questions/46626/fitting-model-for-two-normal-distributions-i... | Not the most concise PyMC code, but I made that decision to help the reader. This should run, and give (really) accurate results.
I made the decision to use Uniform priors, with liberal ranges, because I really have no idea what we are modelling. But probably one has an idea about the centroid locations, and can use a... |
Can pip be used with Python Tools in Visual Studio? | 15,185,827 | 16 | 2013-03-03T12:48:40Z | 32,545,749 | 41 | 2015-09-13T02:31:15Z | [
"python",
"visual-studio",
"pip",
"ptvs"
] | I'm collaborating with some fellow students to build a python app, and was hoping to use the 'training wheels' of Visual Studio intelli-sense. They use python on mac and linux, so ideally our source control repo would consist of just `*.py` source files that we wrote, and a `requirements.txt` export of pip dependancies... | Yep! Go to Tools -> Python Tools -> Python Environments.
From there you can install libraries like so (tested on Visual Studio 2015 Community Edition):
[](http://i.stack.imgur.com/Luz7E.png) |
Linestyle in matplotlib step function | 15,188,005 | 14 | 2013-03-03T16:48:07Z | 15,191,183 | 19 | 2013-03-03T21:34:01Z | [
"python",
"matplotlib",
"linestyle"
] | Is it possible to set the linestyle in a matplotlib step function to dashed, dotted, etc.?
I've tried:
```
step(x, linestyle='--'),
step(x, '--')
```
But it did not help. | As of mpl 1.3.0 this is fixed upstream
---
You have to come at it a bit sideways as `step` seems to ignore `linestyle`. If you look at what `step` is doing underneath, it is just a thin wrapper for plot.
You can do what you want by talking to `plot` directly:
```
import matplotlib.pyplot as plt
plt.plot(range(5), ... |
Python error : X() takes exactly 1 argument (8 given) | 15,188,972 | 5 | 2013-03-03T18:11:53Z | 15,189,023 | 8 | 2013-03-03T18:16:36Z | [
"python"
] | I'm trying to bulid an Anonymous FTP scanner , but i got an error about calling function X , i defined X to recieve ony 1 arguement which is the ip address , the same code works if i don't use the loop and send the IPs one by one .
The error is : X() takes exactly 1 argument (8 given)
```
from ftplib import FTP
impor... | When constructing `Thread` objects, `args` should be a sequence of arguments, but you are passing in a string. This causes Python to iterate over the string and treat each character as an argument.
You can use a tuple containing one element:
```
t = Thread (target = X, args = (ip,))
```
or a list:
```
t = Thread ... |
assigning class variable as default value to class method argument | 15,189,245 | 6 | 2013-03-03T18:34:34Z | 15,189,285 | 11 | 2013-03-03T18:37:21Z | [
"python",
"class",
"variable-assignment"
] | I would like to build a method inside a class with default values arguments taken from this class. In general I do filtering on some data. Inside my class I have a method where normally I pass vector of data. Sometimes I don't have the vector and I take simulated data. Every time I do not pass a particular vector I wou... | Your understanding is wrong. `self` is itself a parameter to that function definition, so there's no way it can be in scope at that point. It's only in scope within the function itself.
The answer is simply to default the argument to `None`, and then check for that inside the method:
```
def doSomething(self, a=None)... |
Why does this function return "None None" as well? | 15,189,954 | 2 | 2013-03-03T19:38:35Z | 15,189,965 | 7 | 2013-03-03T19:39:43Z | [
"python",
"printing",
"return"
] | *I've searched regarding this and came across list returning functions but I still don't understand it.*
I'm trying to understand why Print function to another function returns the following :
**Happy Birthday
Happy Birthday
None None**
My Code:
```
def happy():
print("Happy Birthday")
def main():
pr... | Every function always returns a value. If you don't explicitly return a value, and the function just gets all the way to the end, then it automatically returns None. Your function `happy` doesn't have any `return` statement, so at the end of the function, it automatically returns None. |
Sending a Dictionary using Sockets in Python? | 15,190,362 | 3 | 2013-03-03T20:18:13Z | 15,190,561 | 8 | 2013-03-03T20:37:09Z | [
"python",
"sockets",
"dictionary",
"translation"
] | My problem: Ok, I made a little chat program thing where I am basically using sockets in order to send messages over a network.
It works great, but when I decided to take it a step further, I ran into a problem.
I decided to add some encryption to the strings I was sending over the network, and so I went ahead and wr... | You have to serialize your data. there would be many ways to do it, but [json](http://docs.python.org/2/library/json.html) and [pickle](http://docs.python.org/2/library/pickle.html) will be the likely way to go for they being in standard library.
for json :
```
import json
data_string = json.dumps(data) #data serial... |
How to do a polynomial fit with fixed points | 15,191,088 | 6 | 2013-03-03T21:25:47Z | 15,193,360 | 7 | 2013-03-04T01:53:23Z | [
"python",
"numpy",
"scipy"
] | I have been doing some fitting in python using numpy (which uses least squares).
I was wondering if there was a way of getting it to fit data while forcing it through some fixed points? If not is there another library in python (or another language i can link to - eg c)?
**NOTE** I know it's possible to force through... | If you use `curve_fit()`, you can use `sigma` argument to give every point a weight. The following example gives the first , middle, last point very small sigma, so the fitting result will be very close to these three points:
```
N = 20
x = np.linspace(0, 2, N)
np.random.seed(1)
noise = np.random.randn(N)*0.2
sigma =n... |
How to do a polynomial fit with fixed points | 15,191,088 | 6 | 2013-03-03T21:25:47Z | 15,196,628 | 9 | 2013-03-04T07:32:20Z | [
"python",
"numpy",
"scipy"
] | I have been doing some fitting in python using numpy (which uses least squares).
I was wondering if there was a way of getting it to fit data while forcing it through some fixed points? If not is there another library in python (or another language i can link to - eg c)?
**NOTE** I know it's possible to force through... | The mathematically correct way of doing a fit with fixed points is to use [Lagrange multipliers](http://en.wikipedia.org/wiki/Lagrange_multiplier). Basically, you modify the objective function you want to minimize, which is normally the sum of squares of the residuals, adding an extra parameter for every fixed point. I... |
Different exceptions for pop from empty sets and lists? | 15,191,230 | 5 | 2013-03-03T21:38:45Z | 15,191,242 | 7 | 2013-03-03T21:40:18Z | [
"python",
"list",
"exception",
"set"
] | Why do empty sets and lists raise different exceptions when you call .pop()?
```
>>> l = []
>>> l.pop()
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
l.pop()
IndexError: pop from empty list
>>> l = set()
>>> l.pop()
Traceback (most recent call last):
File "<pyshell#17>", line 1, i... | Because `sets` are a lot like `dict`s but without the values:
```
>>> d = {}
>>> d.pop('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'pop(): dictionary is empty'
```
Both dictionaries and sets are not indexed, like lists are, so an `IndexError` makes no sense here. But *lik... |
Different exceptions for pop from empty sets and lists? | 15,191,230 | 5 | 2013-03-03T21:38:45Z | 15,191,244 | 7 | 2013-03-03T21:40:32Z | [
"python",
"list",
"exception",
"set"
] | Why do empty sets and lists raise different exceptions when you call .pop()?
```
>>> l = []
>>> l.pop()
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
l.pop()
IndexError: pop from empty list
>>> l = set()
>>> l.pop()
Traceback (most recent call last):
File "<pyshell#17>", line 1, i... | Lists are ordered sequences, accessed by index; sets are unordered and non-sequential, accessed by key, hence the error messages. |
How to avoid this four-line memory leak with NumPy+MKL? | 15,191,391 | 6 | 2013-03-03T21:59:10Z | 15,192,695 | 7 | 2013-03-04T00:28:24Z | [
"python",
"memory-leaks",
"numpy",
"intel-mkl"
] | The following simple four-line code produces a memory leak in my Python 2.6.6 / NumPy 1.7.0 / MKL 10.3.6 setup:
```
import numpy as np
t = np.random.rand(10,10)
while True:
t = t / np.trace(t)
```
With each operation, the used memory grows by the size of a 10x10 matrix. However, there is no such behaviour when I u... | This is indeed a NumPy bug, which has been known for some months and has been discussed [here](https://github.com/numpy/numpy/issues/2969); it will be fixed in 1.7.1. The fix is [this nice one-liner in item\_selection.c](https://github.com/numpy/numpy/commit/80b3a3401382cb3f14c5b76dd90d9f932f50ad15). After adding this ... |
Matplotlib Contourf Plots Unwanted Outlines when Alpha < 1 | 15,192,661 | 4 | 2013-03-04T00:23:33Z | 15,193,111 | 8 | 2013-03-04T01:23:25Z | [
"python",
"matplotlib",
"alpha"
] | I am using matplotlib in Python 2.7 to plot a filled contour plot. I want to overlay this over an image, so I am using the alpha keyword to make the plot semi-transparent. When I do this, the body of the contours are the correct transparency, but contourf() plots unwanted lines on the boundaries between different level... | Try turn on `antialiased=True`:
```
x, y = np.mgrid[-1:1:100j, -1:1:100j]
contourf(x, y, x**2+y**2 + np.random.rand(100, 100)*0.1, 10, alpha=0.3, antialiased=True)
```
here is my result:
 |
Saving arrays as columns with np.savetxt | 15,192,847 | 15 | 2013-03-04T00:48:26Z | 15,193,026 | 24 | 2013-03-04T01:12:12Z | [
"python",
"numpy"
] | I am trying to do something that is probable very simple. I would like to save three arrays to a file as columns using 'np.savetxt' When I try this
```
x = [1,2,3,4]
y = [5,6,7,8]
z = [9,10,11,12]
np.savetxt('myfile.txt', (x,y,z), fmt='%.18g', delimiter=' ', newline=os.linesep)
```
The arrays are saved like this
``... | Use [`numpy.c_[]`](http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.c_.html):
```
np.savetxt('myfile.txt', np.c_[x,y,z])
``` |
Saving arrays as columns with np.savetxt | 15,192,847 | 15 | 2013-03-04T00:48:26Z | 18,454,780 | 16 | 2013-08-26T23:42:36Z | [
"python",
"numpy"
] | I am trying to do something that is probable very simple. I would like to save three arrays to a file as columns using 'np.savetxt' When I try this
```
x = [1,2,3,4]
y = [5,6,7,8]
z = [9,10,11,12]
np.savetxt('myfile.txt', (x,y,z), fmt='%.18g', delimiter=' ', newline=os.linesep)
```
The arrays are saved like this
``... | Use numpy.transpose():
```
np.savetxt('myfile.txt', np.transpose([x,y,z]))
```
I find this more intuitive than using np.c\_[] |
Get vertex as single array | 15,193,506 | 4 | 2013-03-04T02:10:57Z | 15,193,571 | 7 | 2013-03-04T02:19:13Z | [
"python",
"api",
"maya"
] | I need to get all the selected vertices and store them in an array so I can loop through and find out information about each vert.
Although I cannot figure this out.
```
sel = cmds.ls(sl=1)
print sel
```
Returns:
```
//[u'pCube1.vtx[50:53]', u'pCube1.vtx[74:77]']
```
More or less I need my 'sel' variable to print ... | Well, it seems research has paid off!
```
cmds.ls(sl=1, fl=1)
```
the 'fl' flag stands for "Flatten", Flatten returns a list of objects so that each component is identified individually. |
How to generate n dimensional random variables in a specific range in python | 15,194,468 | 3 | 2013-03-04T04:16:37Z | 15,194,512 | 7 | 2013-03-04T04:22:24Z | [
"python",
"numpy",
"scipy"
] | I want to generate uniform random variables in the range of `[-10,10]` of various dimensions in python. Numbers of 2,3,4,5.... dimension.
I tried random.uniform(-10,10), but that is only one dimensional. I do not know how to do it for n-dimension.
By 2 dimension I mean,
```
[[1 2], [3 4]...]
``` | Since `numpy` is tagged, you can use the random functions in `numpy.random`:
```
>>> import numpy as np
>>> np.random.uniform(-10,10)
7.435802529756465
>>> np.random.uniform(-10,10,size=(2,3))
array([[-0.40137954, -1.01510912, -0.41982265],
[-8.12662965, 6.25365713, -8.093228 ]])
>>> np.random.uniform(-10,10,... |
Using python's eval() vs. ast.literal_eval()? | 15,197,673 | 53 | 2013-03-04T08:50:41Z | 15,197,694 | 21 | 2013-03-04T08:52:44Z | [
"python",
"eval",
"abstract-syntax-tree"
] | I have a situation with some code where `eval()` came up as a possible solution. Now I have never had
to use `eval()` before but, I have come across plenty of information about the potential
danger it can cause. That said, I'm very wary about using it.
My situation is that I have input being given by a user:
```
data... | Python's *eager* in its evaluation, so `eval(raw_input(...))` will evaluate the user's input as soon as it hits the `eval`, regardless of what you do with the data afterwards. Therefore, **this is not safe**, especially when you `eval` user input.
Use `ast.literal_eval`.
---
As an example, entering this at the promp... |
Using python's eval() vs. ast.literal_eval()? | 15,197,673 | 53 | 2013-03-04T08:50:41Z | 15,197,698 | 73 | 2013-03-04T08:52:53Z | [
"python",
"eval",
"abstract-syntax-tree"
] | I have a situation with some code where `eval()` came up as a possible solution. Now I have never had
to use `eval()` before but, I have come across plenty of information about the potential
danger it can cause. That said, I'm very wary about using it.
My situation is that I have input being given by a user:
```
data... | `datamap = eval(raw_input('Provide some data here: '))` means that you actually evaluate the code *before* you deem it to be unsafe or not. It evaluates the code as soon as the function is called. See also [the dangers of `eval`](http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html).
`ast.literal_eval` r... |
Using python's eval() vs. ast.literal_eval()? | 15,197,673 | 53 | 2013-03-04T08:50:41Z | 15,197,726 | 43 | 2013-03-04T08:54:35Z | [
"python",
"eval",
"abstract-syntax-tree"
] | I have a situation with some code where `eval()` came up as a possible solution. Now I have never had
to use `eval()` before but, I have come across plenty of information about the potential
danger it can cause. That said, I'm very wary about using it.
My situation is that I have input being given by a user:
```
data... | `ast.literal_eval()` only considers a small subset of Python's syntax to be valid:
> The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
Passing `__import__('os').system('rm -rf /a-path-you-really-care-about')` into `ast.... |
Using python's eval() vs. ast.literal_eval()? | 15,197,673 | 53 | 2013-03-04T08:50:41Z | 34,904,657 | 11 | 2016-01-20T15:56:33Z | [
"python",
"eval",
"abstract-syntax-tree"
] | I have a situation with some code where `eval()` came up as a possible solution. Now I have never had
to use `eval()` before but, I have come across plenty of information about the potential
danger it can cause. That said, I'm very wary about using it.
My situation is that I have input being given by a user:
```
data... | **eval:**
This is very powerful, but is also very dangerous if you accept strings to evaluate from untrusted input. Suppose the string being evaluated is "os.system('rm -rf /')" ? It will really start deleting all the files on your computer.
**ast.literal\_eval:**
Safely evaluate an expression node or a string con... |
Why does union consume more memory if the argument is a set? | 15,198,042 | 12 | 2013-03-04T09:14:18Z | 15,198,200 | 9 | 2013-03-04T09:24:28Z | [
"python",
"memory-management",
"set"
] | I'm puzzled by this behaviour of memory allocation of `set`s:
```
>>> set(range(1000)).__sizeof__()
32968
>>> set(range(1000)).union(range(1000)).__sizeof__() # expected, set doesn't change
32968
>>> set(range(1000)).union(list(range(1000))).__sizeof__() #expected, set doesn't change
32968
>>> set(range(1000)).u... | In Python 2.7.3, [`set.union()`](http://hg.python.org/cpython/file/0e41c4466d58/Objects/setobject.c#l1178) delegates to a C function called [`set_update_internal()`](http://hg.python.org/cpython/file/0e41c4466d58/Objects/setobject.c#l931). The latter uses several different implementations depending on the Python type o... |
Fixing invalid JSON escape | 15,198,426 | 5 | 2013-03-04T09:37:16Z | 15,198,886 | 9 | 2013-03-04T10:02:18Z | [
"python",
"json",
"string",
"parsing"
] | KISSmetrics generates invalid JSON strings I need to parse. I'm getting tons of errors like
```
ERROR 2013-03-04 04:31:12,253 Invalid \escape: line 1 column 132 (char 132): {"search engine":"Google","_n":"search engine hit","_p":"z392cpdpnm6silblq5mac8kiugq=","search terms":"happy new year animation 1920\303\2271080 h... | Your input data contains octal escapes; those would be invalid indeed. Replace them with decoded bytes using a regular expression:
```
import re
invalid_escape = re.compile(r'\\[0-7]{1,3}') # up to 3 digits for byte values up to FF
def replace_with_byte(match):
return chr(int(match.group(0)[1:], 8))
def repair... |
Django py.test does not find settings module | 15,199,700 | 14 | 2013-03-04T10:44:45Z | 15,280,963 | 19 | 2013-03-07T20:21:04Z | [
"python",
"django",
"py.test"
] | I do have the following project structure
```
base
__init.py
settings
__init__.py
settings.py
tests
pytest.ini
test_module.py
```
My `pytest.ini` looks like this:
```
[pytest]
#DJANGO_SETTINGS_MODULE =base.settings.settings
```
My `test_module.py` looks like this:
```
de... | Because django.conf.settings is lazy it will attempt to import settings module only when you try to access it. That's why your test doesn't fail when you simply import settings object.
Your problem is already discussed here: <https://github.com/pelme/pytest_django/issues/23>
This is an issue with pytest and not with ... |
What's the difference between a[] and a[:] when assigning values? | 15,201,946 | 3 | 2013-03-04T12:46:33Z | 15,202,032 | 7 | 2013-03-04T12:51:27Z | [
"python",
"variable-assignment",
"slice"
] | I happen to see this snippet of code:
```
a = []
a = [a, a, None]
# makes a = [ [], [], None] when print
a = []
a[:] = [a, a, None]
# makes a = [ [...], [...], None] when print
```
It seems the `a[:]` assignment assigns a pointer but I can't find documents about that. So anyone could give me an explicit explanatio... | The first will point `a` to a new object, the second will mutate `a`, so the list referenced by `a` is still the same.
For example:
```
a = [1, 2, 3]
b = a
print b # [1, 2, 3]
a[:] = [3, 2, 1]
print b # [3, 2, 1]
a = [1, 2, 3]
#b still references to the old list
print b # [3, 2, 1]
``` |
How to use virtualenvwrapper in Supervisor? | 15,202,760 | 15 | 2013-03-04T13:33:31Z | 15,203,447 | 31 | 2013-03-04T14:09:26Z | [
"python",
"deployment",
"virtualenv",
"supervisord",
"virtualenvwrapper"
] | When I was developing and testing my project, I used to use virtualenvwrapper to manage the environment and run it:
```
workon myproject
python myproject.py
```
Of course, once I was in the right virtualenv, I was using the right version of Python, and other corresponding libraries for running my project.
Now, I wan... | One way to use your virtualenv from the command line is to use the python executable located inside of your virtualenv.
for me i have my virtual envs in `.virtualenvs` directory. For example
`/home/ubuntu/.virtualenvs/yourenv/bin/python`
no need to `workon`
for a `supervisor.conf` managing a tornado app i do:
```
... |
Convert pandas DateTimeIndex to Unix Time? | 15,203,623 | 22 | 2013-03-04T14:17:41Z | 15,203,886 | 17 | 2013-03-04T14:31:21Z | [
"python",
"pandas"
] | What is the idiomatic way of converting a pandas DateTimeIndex to (an iterable of) Unix Time?
This is probably not the way to go:
```
[time.mktime(t.timetuple()) for t in my_data_frame.index.to_pydatetime()]
``` | Note: Timestamp is just unix time with nanoseconds (so divide it by 10\*\*9):
```
[t.value // 10 ** 9 for t in tsframe.index]
```
For example:
```
In [1]: t = pd.Timestamp('2000-02-11 00:00:00')
In [2]: t
Out[2]: <Timestamp: 2000-02-11 00:00:00>
In [3]: t.value
Out[3]: 950227200000000000L
In [4]: time.mktime(t.ti... |
Convert pandas DateTimeIndex to Unix Time? | 15,203,623 | 22 | 2013-03-04T14:17:41Z | 15,204,235 | 33 | 2013-03-04T14:47:36Z | [
"python",
"pandas"
] | What is the idiomatic way of converting a pandas DateTimeIndex to (an iterable of) Unix Time?
This is probably not the way to go:
```
[time.mktime(t.timetuple()) for t in my_data_frame.index.to_pydatetime()]
``` | As `DatetimeIndex` is `ndarray` under the hood, you can do the conversion without a comprehension (much faster).
```
In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: from datetime import datetime
In [4]: dates = [datetime(2012, 5, 1), datetime(2012, 5, 2), datetime(2012, 5, 3)]
...: index = pd.Date... |
Is there a python (scipy) function to determine parameters needed to obtain a target power? | 15,204,070 | 7 | 2013-03-04T14:39:47Z | 15,219,352 | 9 | 2013-03-05T08:47:15Z | [
"python",
"numpy",
"scipy"
] | In R there is a very useful function that helps with determining parameters for a two sided t-test in order to obtain a target statistical power.
The function is called `power.prop.test`.
<http://stat.ethz.ch/R-manual/R-patched/library/stats/html/power.prop.test.html>
You can call it using:
```
power.prop.test(p1 =... | I've managed to replicate the function using the below formula for n and the inverse survival function `norm.isf` from scipy.stats

```
from scipy.stats import norm, zscore
def sample_power_probtest(p1, p2, power=0.8, sig=0.05):
z = norm.isf([sig... |
Is there a python (scipy) function to determine parameters needed to obtain a target power? | 15,204,070 | 7 | 2013-03-04T14:39:47Z | 18,379,559 | 7 | 2013-08-22T11:47:50Z | [
"python",
"numpy",
"scipy"
] | In R there is a very useful function that helps with determining parameters for a two sided t-test in order to obtain a target statistical power.
The function is called `power.prop.test`.
<http://stat.ethz.ch/R-manual/R-patched/library/stats/html/power.prop.test.html>
You can call it using:
```
power.prop.test(p1 =... | Some of the basic power calculations are now available in statsmodels
<http://statsmodels.sourceforge.net/devel/stats.html#power-and-sample-size-calculations>
<http://jpktd.blogspot.ca/2013/03/statistical-power-in-statsmodels.html>
The blog article does not yet take the latest changes to the statsmodels code into acc... |
Find multiple values in a Numpy array | 15,204,991 | 4 | 2013-03-04T15:25:57Z | 15,205,214 | 11 | 2013-03-04T15:36:46Z | [
"python",
"numpy",
"pandas"
] | `a` and `b` are two Numpy arrays of integers. They are sorted and without repetitions. `b` is a subset of `a`. I need to find the index in `a` of every element of `b`. Is there an efficient Numpy function that could help, so I can avoid the python loop?
(Actually, the arrays are of `pandas.DatetimeIndex` and Numpy `da... | [`numpy.searchsorted()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html) can be used to do this:
```
In [15]: a = np.array([1, 2, 3, 5, 10, 20, 25])
In [16]: b = np.array([1, 5, 20, 25])
In [17]: a.searchsorted(b)
Out[17]: array([0, 3, 5, 6])
```
From what I understand, it doesn't requi... |
How to pass on argparse argument to function as kwargs? | 15,206,010 | 17 | 2013-03-04T16:16:50Z | 15,206,058 | 23 | 2013-03-04T16:19:09Z | [
"python",
"python-2.7",
"arguments",
"argparse"
] | I have a class defined as follows
```
class M(object):
def __init__(self, **kwargs):
...do_something
```
and I have the result of `argparse.parse_args()`, for example:
```
> args = parse_args()
> print args
Namespace(value=5, message='test', message_type='email', extra="blah", param="whatever")
```
I wa... | You need to pass in the result of `vars(args)` instead:
```
M(**vars(args))
```
The [`vars()` function](http://docs.python.org/2/library/functions.html#vars) returns the namespace of the Namespace instance (its `__dict__` attribute) as a dictionary.
Inside `M.__init__()`, simply ignore the `message_type` key. |
Using .pth files | 15,208,615 | 17 | 2013-03-04T18:37:07Z | 15,209,116 | 26 | 2013-03-04T19:06:13Z | [
"python"
] | I am trying to make a module discoverable on a system where I don't have write access to the global `site-packages` directory, and without changing the environment (`PYTHONPATH`). I have tried to place a `.pth` file in the same directory as a script I'm executing, but it seems to be ignored. E.g., I created a file `ext... | As described in [the documentation](http://docs.python.org/2/library/site.html), PTH files are only processed if they are in the site-packages directory. (More precisely, they are processed if they are in a "site directory", but "site directory" itself is a setting global to the Python installation and does not depend ... |
Python functions within lists | 15,209,552 | 6 | 2013-03-04T19:31:23Z | 15,209,564 | 11 | 2013-03-04T19:32:04Z | [
"python",
"list",
"functional-programming"
] | So today in computer science I asked about using a function as a variable. For example, I can create a function, such as returnMe(i) and make an array that will be used to call it. Like h = [help,returnMe] and then I can say h1 and it would call returnMe("Bob"). Sorry I was a little excited about this. My question is i... | You can create anonymous functions using the `lambda` keyword.
```
def func(x,keyword='bar'):
return (x,keyword)
```
is roughly equivalent to:
```
func = lambda x,keyword='bar':(x,keyword)
```
So, if you want to create a list with functions in it:
```
my_list = [lambda x:x**2,lambda x:x**3]
print my_list[0](2)... |
Get parents keys from nested dictionary | 15,210,148 | 5 | 2013-03-04T20:06:40Z | 15,210,253 | 7 | 2013-03-04T20:12:46Z | [
"python",
"dictionary",
"nested"
] | From the following nested dictionary, how can I get every parent dictionary key of `'value4ac'`? By starting the `'value4ac'` value, I want to get `'key4'`, `'key4a'`, `'Key4ac'`.
```
example_dict = { 'key1' : 'value1',
'key2' : 'value2',
'key3' : { 'key3a': 'value3a' },
... | recursion to the rescue!
```
example_dict = { 'key1' : 'value1',
'key2' : 'value2',
'key3' : { 'key3a': 'value3a' },
'key4' : { 'key4a': { 'key4aa': 'value4aa',
'key4ab': 'value4ab',
'key4ac... |
python regex get first part of an email address | 15,210,485 | 4 | 2013-03-04T20:27:43Z | 15,210,508 | 16 | 2013-03-04T20:28:47Z | [
"python",
"regex"
] | I am quite new to python and regex and I was wondering how to extract the first part of an email address upto the domain name. So for example if:
```
s='xjhgjg876896@domain.com'
```
I would like the regex result to be (taking into account all "sorts" of email ids i.e including numbers etc..):
```
xjhgjg876896
```
I... | You should just use the [`split`](http://docs.python.org/2/library/stdtypes.html#str.split) method of strings:
```
s.split("@")[0]
``` |
DJANGO: ModelChoiceField optgroup tag | 15,210,511 | 18 | 2013-03-04T20:28:56Z | 17,854,288 | 47 | 2013-07-25T09:37:27Z | [
"python",
"django",
"django-templates",
"django-forms"
] | How can I set in ModelChoiceField **optgroup** tag?
This is example:
**models.py**
```
class Link(models.Model):
config = models.ForeignKey(Config)
name = models.URLField(u'Name', null=True, max_length=50)
gateway = models.IPAddressField(u'Gateway', null=True)
weight = models.IntegerField(u'Weight', ... | You don't need to create any custom field, Djando already does the job, just pass the choices well formatted:
```
MEDIA_CHOICES = (
('Audio', (
('vinyl', 'Vinyl'),
('cd', 'CD'),
)
),
('Video', (
('vhs', 'VHS Tape'),
('dvd', 'DVD'),
)
),
)
``` |
I expect 'True' but get 'None' | 15,210,646 | 3 | 2013-03-04T20:36:08Z | 15,210,655 | 9 | 2013-03-04T20:36:46Z | [
"python"
] | I have a simple Python script that recursively checks to see if a range of `n` numbers are factors of a number `x`. If any of the numbers are not factors I return `False`, otherwise when the `n==1` I would like return `True`. However I keep returning `NoneType` and would appreciate suggestions on how to fix this.
```
... | You don't ever return the return value of the recursive call:
```
if x % n == 0:
#print "passed {}".format(n)
return recursive_factor_test(x,n-1)
```
When you omit the `return` statement there, your function ends without a return statement, thus falling back to the default `None` return value.
With the `ret... |
Combine Python Dictionary Permutations into List of Dictionaries | 15,211,568 | 6 | 2013-03-04T21:34:23Z | 15,211,805 | 16 | 2013-03-04T21:49:45Z | [
"python",
"dictionary",
"python-2.7"
] | Given a dictionary that looks like this:
```
{
'Color': ['Red', 'Yellow'],
'Size': ['Small', 'Medium', 'Large']
}
```
How can I create a list of dictionaries that combines the various values of the first dictionary's keys? What I want is:
```
[
{'Color': 'Red', 'Size': 'Small'},
{'Color': 'Red', 'Siz... | I think you want the Cartesian product, not a permutation, in which case [`itertools.product`](https://docs.python.org/2.7/library/itertools.html#itertools.product) can help:
```
>>> from itertools import product
>>> d = {'Color': ['Red', 'Yellow'], 'Size': ['Small', 'Medium', 'Large']}
>>> [dict(zip(d, v)) for v in p... |
Why does Django admin list_select_related not work in this case? | 15,211,799 | 6 | 2013-03-04T21:49:09Z | 15,212,142 | 12 | 2013-03-04T22:13:14Z | [
"python",
"django",
"performance",
"django-admin"
] | I've got a `ModelAdmin` class that includes a foreign key field in its `list_display`. But the admin list page for that model is doing hundreds of queries, one query per row to get the data from the other table instead of a join (`select_related()`).
The Django docs [indicate](https://docs.djangoproject.com/en/dev/ref... | The issue here is that setting `list_select_related = True` just adds a basic `select_related()` onto the query, but that call does not by default follow ForeignKeys with `null=True`. So the answer is to define the queryset the changelist uses yourself, and specify the FK to follow:
```
class EventAdmin(admin.ModelAdm... |
Accessing 802.11 Wireless Management Frames from Python | 15,214,189 | 6 | 2013-03-05T01:22:25Z | 15,236,772 | 7 | 2013-03-06T00:25:51Z | [
"python",
"linux",
"wifi",
"scapy",
"tshark"
] | From Python on Linux I would like to sniff 802.11 management 'probe-request' frames. This is possible from Scapy like so:
```
# -*- coding: utf-8 -*-
from scapy.all import *
def proc(p):
if ( p.haslayer(Dot11ProbeReq) ):
mac=re.sub(':','',p.addr2)
ssid=p[Dot11Elt].info
... | I've managed to work this out. Here's the process I went through:
1. Capture some 802.11 management 'probe-request' frames:
```
tshark -n -i mon0 subtype probereq -c 5 -w probe.pcap
```
2. Understand RadioTap
Reading [RadioTap](http://www.radiotap.org/) documentation, I realised that RadioTap frames are ... |
How can I copy an immutable object like tuple in Python? | 15,214,404 | 6 | 2013-03-05T01:46:00Z | 15,214,570 | 10 | 2013-03-05T02:03:53Z | [
"python",
"types"
] | `copy.copy()` and `copy.deepcopy()` just copy the reference for an immutable object like a tuple.
How can I create a duplicate copy of the first immutable object at a different memory location? | Add the empty tuple to it:
```
>>> a = (1, 2, 3)
>>> a is a+tuple()
False
```
Concatenating tuples always returns a new distinct tuple, even when the result turns out to be equal. |
How can I copy an immutable object like tuple in Python? | 15,214,404 | 6 | 2013-03-05T01:46:00Z | 15,214,597 | 11 | 2013-03-05T02:06:29Z | [
"python",
"types"
] | `copy.copy()` and `copy.deepcopy()` just copy the reference for an immutable object like a tuple.
How can I create a duplicate copy of the first immutable object at a different memory location? | You're looking for `deepcopy`.
```
from copy import deepcopy
tup = (1, 2, 3, 4, 5)
put = deepcopy(tup)
```
Admittedly, the ID of these two tuples will point to the same address. Because a tuple is immutable, there's really no rationale to create another copy of it that's the exact same. However, note that tuples can... |
depth of a tree python | 15,214,852 | 7 | 2013-03-05T02:35:35Z | 15,214,874 | 7 | 2013-03-05T02:38:08Z | [
"python",
"oop",
"methods",
"tree"
] | i am new to programming and am trying to calculate the depth of a python tree. I believe that my error is because depth is a method of the Node class and not a regular function. I am trying to learn oop and was hoping to use a method. This might be a new bee error...
Here is my code:
```
class Node:
def __init__(... | ```
def depth(self):
if self.left == None and self.right == None:
return 1
return max(depth(self.left), depth(self.right)) + 1
```
should be
```
def depth(self):
return max(self.left.depth() if self.left else 0, self.right.depth() if self.right else 0) + 1
```
A more readable version:
```
def d... |
SQLAlchemy Many-To-Many performance | 15,214,967 | 4 | 2013-03-05T02:49:49Z | 15,215,565 | 10 | 2013-03-05T03:58:40Z | [
"python",
"sql",
"sqlalchemy"
] | I have a database relationship with a Many-To-Many association but the association table itself contains a lot of attributes that need to be accessed, so I made three classes:
```
class User(Base):
id = Column(Integer, primary_key=True)
attempts = relationship("UserAttempt", backref="user", lazy="subquery")
c... | > What I actually want from SQLAlchemy is to pull all (or all relevant) Challenges at once and then associate it with the relevant attempts. It is not a big deal if all challenges are pulled or only does which have an actual association later,
You first want to take off that "lazy='subquery'" directive from relationsh... |
Python 2.7: %d, %s, and float() | 15,215,242 | 2 | 2013-03-05T03:22:09Z | 15,215,445 | 10 | 2013-03-05T03:44:03Z | [
"python"
] | I am attempting to teach myself a little coding through the "learn python the hard way" book and am struggling with %d / %s / %r when tying to display a floating point number. How do you properly pass a floating point number with a format character? First I tried %d but that made my answers display as integers.... I ha... | See [String Formatting Operations](http://docs.python.org/2/library/stdtypes.html#string-formatting):
`%d` is the format code for an integer. `%f` is the format code for a float.
`%s` prints the `str()` of an object (What you see when you `print(object)`).
`%r` prints the `repr()` of an object (What you see when you... |
Simple python list vs dictionary | 15,216,240 | 3 | 2013-03-05T05:05:43Z | 15,216,254 | 12 | 2013-03-05T05:06:51Z | [
"python"
] | So I am very new to python and I cant for the life of me figure out why these two statements evaluate differently,
> > > [3\*x for x in range(1,11) if x > 5]
[18, 21, 24, 27, 30]
> > > {3\*x for x in range(1,11) if x > 5}
set([24, 18, 27, 21, 30])
The top one makes perfect sense to me but why does the second print... | The second one is not a dictionary but a set. Both sets and dictionaries are *unordered*. The elements are not stored or displayed with any particular meaningful order. |
how to store a complex object in redis (using redis-py) | 15,219,858 | 23 | 2013-03-05T09:14:14Z | 15,220,010 | 27 | 2013-03-05T09:20:37Z | [
"python",
"redis"
] | The hmset function can set the value of each field, but I found that if the value itself is a complex structured object, the value return from hget is a serialized string, not the original object
e.g
```
images= [{'type':'big', 'url':'....'},
{'type':'big', 'url':'....'},
{'type':'big', 'url':'....'}]
r... | You can't create nested structures in Redis, meaning you can't (for example) store a native redis list inside a native redis hash-map.
If you really need nested structures, you might want to just store a JSON-blob (or something similar) instead. Another option is to store an "id"/key to a different redis object as the... |
how to store a complex object in redis (using redis-py) | 15,219,858 | 23 | 2013-03-05T09:14:14Z | 20,400,288 | 32 | 2013-12-05T12:39:05Z | [
"python",
"redis"
] | The hmset function can set the value of each field, but I found that if the value itself is a complex structured object, the value return from hget is a serialized string, not the original object
e.g
```
images= [{'type':'big', 'url':'....'},
{'type':'big', 'url':'....'},
{'type':'big', 'url':'....'}]
r... | Actually, you can store python objects in redis using the built-in module [pickle](http://docs.python.org/2/library/pickle.html).
Here is example.
```
import pickle
import redis
r = redis.StrictRedis(host='localhost', port=6379, db=0)
obj = ExampleObject()
pickled_object = pickle.dumps(obj)
r.set('some_key', pickled... |
how to store a complex object in redis (using redis-py) | 15,219,858 | 23 | 2013-03-05T09:14:14Z | 32,486,369 | 13 | 2015-09-09T18:01:38Z | [
"python",
"redis"
] | The hmset function can set the value of each field, but I found that if the value itself is a complex structured object, the value return from hget is a serialized string, not the original object
e.g
```
images= [{'type':'big', 'url':'....'},
{'type':'big', 'url':'....'},
{'type':'big', 'url':'....'}]
r... | **JSON Example:**
```
import json
import redis
r = redis.StrictRedis(host='localhost', port=6379, db=0)
images= [
{'type':'big', 'url':'....'},
{'type':'big', 'url':'....'},
{'type':'big', 'url':'....'},
]
json_images = json.dumps(images)
r.set('images', json_images)
unpacked_images = json.loads(r.get('... |
How do I update pip itself from inside my virtual environment? | 15,221,473 | 171 | 2013-03-05T10:29:18Z | 15,223,296 | 309 | 2013-03-05T12:03:10Z | [
"python",
"upgrade",
"virtualenv",
"pip",
"package-managers"
] | I'm able to update pip-managed packages, but how do I update pip itself? According to `pip --version`, I currently have pip 1.1 installed in my virtualenv and I want to update to the latest version.
What's the command for that? Do I need to use distribute or is there a native pip or virtualenv command? I've already tr... | `pip` is just a [PyPI package](https://pypi.python.org/pypi/pip) like any other; you could use it to upgrade itself the same way you would upgrade any package:
```
pip install --upgrade pip
```
On Windows the [recommended command](https://pip.pypa.io/en/stable/installing/#upgrading-pip) is:
```
python -m pip install... |
How do I update pip itself from inside my virtual environment? | 15,221,473 | 171 | 2013-03-05T10:29:18Z | 35,727,579 | 16 | 2016-03-01T16:00:17Z | [
"python",
"upgrade",
"virtualenv",
"pip",
"package-managers"
] | I'm able to update pip-managed packages, but how do I update pip itself? According to `pip --version`, I currently have pip 1.1 installed in my virtualenv and I want to update to the latest version.
What's the command for that? Do I need to use distribute or is there a native pip or virtualenv command? I've already tr... | The more safe method is to [run pip though a python module](https://pip.pypa.io/en/stable/installing/#upgrading-pip):
```
python -m pip install -U pip
```
On windows there seem to be a problem with binaries that try to replace themselves, this method works around that limitation. |
Printing one character at a time from a string, using the while loop | 15,221,516 | 4 | 2013-03-05T10:31:38Z | 15,221,587 | 8 | 2013-03-05T10:35:05Z | [
"python",
"while-loop"
] | Im reading "Core Python Programming 2nd Edition", They ask me to print a string, one character at a time using a "while" loop.
I know how the while loop works, but for some reason i can not come up with an idea how to do this. I've been looking around, and only see examples using for loops.
So what i have to do:
use... | I'm quite sure, that the internet is full of python while-loops, but one example:
```
i=0
while i < len(text):
print text[i]
i += 1
``` |
Group by pandas dataframe and select most common string factor | 15,222,754 | 12 | 2013-03-05T11:34:38Z | 15,223,034 | 36 | 2013-03-05T11:48:38Z | [
"python",
"pandas"
] | I have a data frame with three string columns. I know that the only one value in the 3rd column is valid for every combination of the first two. To clean the data I have to group by data frame by first two columns and select most common value of the third column for each combination.
My code:
```
import pandas as pd
... | You can use `value_counts()` to get a count series, and get the first row:
```
import pandas as pd
source = pd.DataFrame({'Country' : ['USA', 'USA', 'Russia','USA'],
'City' : ['New-York', 'New-York', 'Sankt-Petersburg', 'New-York'],
'Short name' : ['NY','New','Spb','NY']})
source... |
Celery chaining tasks sequentially | 15,224,234 | 5 | 2013-03-05T12:48:22Z | 15,224,504 | 12 | 2013-03-05T13:03:03Z | [
"python",
"django",
"celery",
"django-celery"
] | i need to download a file through ftp, change it and upload it back. I am using celery to do this but i am running into problems when trying to use chaining, where i am getting :
> TypeError: upload\_ftp\_image() takes exactly 5 arguments (6 given)
Also, can i use chains and be assured that the steps will be sequenti... | A chain is always passed the *previous* result as a first argument. From the [chains documentation](http://docs.celeryproject.org/en/latest/userguide/canvas.html#chains):
> The linked task will be applied with the result of its parent task as the first argument, which in the above case will result in `mul(4, 16)` sinc... |
Celery chaining tasks sequentially | 15,224,234 | 5 | 2013-03-05T12:48:22Z | 15,242,784 | 12 | 2013-03-06T08:55:01Z | [
"python",
"django",
"celery",
"django-celery"
] | i need to download a file through ftp, change it and upload it back. I am using celery to do this but i am running into problems when trying to use chaining, where i am getting :
> TypeError: upload\_ftp\_image() takes exactly 5 arguments (6 given)
Also, can i use chains and be assured that the steps will be sequenti... | Another option if you don't want the return value of the previous task to be used as an argument, is to use 'immutability'.
<http://docs.celeryproject.org/en/latest/userguide/canvas.html#immutability>
Instead of defining your subtasks as:
```
download_ftp_image.s(...) and upload_ftp_image.s(...)
```
define them as:... |
Array interpolation in python? | 15,224,970 | 3 | 2013-03-05T13:25:01Z | 15,225,010 | 9 | 2013-03-05T13:27:47Z | [
"python",
"arrays",
"numpy",
"scipy",
"interpolation"
] | I have two arrays :
```
array_x = [x1, x2, x3, x4... xn]
array_y = [y1, y2, y3, y4... yn]
```
I would like to have a function `f(array_x, array_y, value_x)` that returns the `value_y` associated to the `value_x` by interpolation into the arrays.
How to do that ? | I think that `numpy.interp` is exactly what you want. e.g.:
```
numpy.interp(value_x,array_x,array_y)
```
Note that here `value_x` can be a scalar or another array-like value. If it is an array-like value, you will be returned an array of corresponding interpolated values. |
how to store an image into redis using python / PIL | 15,225,053 | 3 | 2013-03-05T13:30:15Z | 15,226,368 | 10 | 2013-03-05T14:30:28Z | [
"python",
"redis",
"python-imaging-library"
] | I'm using python and the Image module(PIL) to process images.
I want to store the raw bits stream of the image object to redis so that others can directly read the images from redis using nginx & httpredis.
so, my question is how to get the raw bits of an Image object and store it into redis. | Using PIL 1.1.7, redis-2.7.2 pip module, and redis-2.4.10 I was able to get this working:
```
import Image
import redis
import StringIO
output = StringIO.StringIO()
im = Image.open("/home/cwgem/Pictures/portrait.png")
im.save(output, format=im.format)
r = redis.StrictRedis(host='localhost')
r.set('imagedata', output... |
Python class member lazy initialization | 15,226,721 | 5 | 2013-03-05T14:47:03Z | 15,226,813 | 10 | 2013-03-05T14:50:47Z | [
"python",
"lazy-evaluation",
"lazy-initialization"
] | I would like to know what is the python way of initializing a class member but only when accessing it, if accessed.
I tried the code below and it is working but is there something simpler than that?
```
class MyClass(object):
_MY_DATA = None
@staticmethod
def _retrieve_my_data():
my_data = ... #... | You could use a [`@property`](http://docs.python.org/2/library/functions.html#property) on [the metaclass](http://docs.python.org/2/reference/datamodel.html#customizing-class-creation) instead:
```
class MyMetaClass(type):
@property
def my_data(cls):
if getattr(cls, '_MY_DATA', None) is None:
... |
Python re.sub() weirdness | 15,226,899 | 6 | 2013-03-05T14:54:08Z | 15,227,289 | 7 | 2013-03-05T15:12:28Z | [
"python",
"regex"
] | I'm very new to Python, in fact this is my first script.
I'm struggling with Python's regular expressions. Specifically `re.sub()`
I have the following code:
```
variableTest = "192"
test = re.sub(r'(\$\{\d{1,2}\:)example.com(\})', r'\1' + variableTest + r'\2', searchString, re.M )
```
With this I'm trying to match... | The problem is that putting an IP in `variableTest` will result in a replacement string like this:
```
r'\18.8.8.8\2'
```
As you can see, the first group reference is to group 18, not group 1. Hence, `re` complains about the invalid group reference.
In this case, you want to use the [`\g<n>` syntax](http://docs.pyth... |
PyInstaller what are hiddenimports and hooks? | 15,229,658 | 4 | 2013-03-05T16:56:27Z | 15,318,447 | 10 | 2013-03-10T03:06:47Z | [
"python",
"exe",
"pyinstaller"
] | I recently tried pyInstaller and there are some things i don't quite get. i have been trying to create some executables (NOTE: all of them use numpy, scipy, OpenCV, BLAS etc) but i have been failing. There is always something missing. So my question is, can someone explain better to me what are hiddenimports and hooks,... | From the [pyinstaller documentation](http://www.pyinstaller.org/export/develop/project/doc/Manual.html#hooks)
> hiddenimports
>
> ```
> A list of modules names (relative or absolute) the module imports in some untrackable way.
> ```
Some Python imports are untrackable during static analysis of your program. eg Your c... |
matplotlib - 3D plots - combining scatter plot with surface plot | 15,229,896 | 9 | 2013-03-05T17:09:00Z | 15,231,187 | 14 | 2013-03-05T18:19:46Z | [
"python",
"matplotlib",
"scatter",
"geometry-surface"
] | I'm rather new to matplotlib.
I want to combine a 3D scatter plot with a 3D surface plot.
Do you have any hints for me? | To combine various types of plots in the same graph you should use the function
plt.hold(True).
The following code plots a 3D scatter plot with a 3D surface plot:
```
from mpl_toolkits.mplot3d import *
import matplotlib.pyplot as plt
import numpy as np
from random import random, seed
from matplotlib import cm
fig ... |
matplotlib - 3D plots - combining scatter plot with surface plot | 15,229,896 | 9 | 2013-03-05T17:09:00Z | 20,180,878 | 10 | 2013-11-24T20:55:29Z | [
"python",
"matplotlib",
"scatter",
"geometry-surface"
] | I'm rather new to matplotlib.
I want to combine a 3D scatter plot with a 3D surface plot.
Do you have any hints for me? | Using siluaty's example; instead of using transparency through the cmap=theCM command, you can adjust the alpha value. This may get you what you want?
```
ax.plot_surface(x_surf, y_surf, z_surf, cmap=cm.hot, alpha=0.2);
```
I don't have enough cred to post a picture, but try it out. It worked good enough for me. |
Python: 'For'loop only runs once, Project Euler | 15,230,393 | 2 | 2013-03-05T17:34:11Z | 15,230,558 | 7 | 2013-03-05T17:43:04Z | [
"python",
"primes"
] | I've been learning Python and playing with Project Euler to recondition some of my math skills. I ran into an issue with [Problem 35](http://projecteuler.net/problem=35). I've generated all Primes under 1 million, eliminated those containing any even numbers, and am now just trying to run the last check with the remain... | Whenever someone has a code which other people (myself included) can't reproduce the strange behaviour of, I immediately think: whitespace error. And looking at your code:
```
' def rotations(lst):'
' newlist = []'
' for i in lst: # Take each int it... |
Split Python Flask app into multiple files | 15,231,359 | 32 | 2013-03-05T18:29:13Z | 15,231,623 | 60 | 2013-03-05T18:43:06Z | [
"python",
"web-services",
"file-organization",
"flask"
] | I'm having trouble understanding how to split a flask app into multiple files.
I'm creating a web service and I want to split the api's into different files (AccountAPI.py, UploadAPI.py, ...), just so I don't have one huge python file.
I've read that you can do this with Blueprints, but I'm not entirely sure that rou... | Yes, Blueprints are the right way to do it. What you are trying to do can be achieved like this:
Main.py
```
from flask import Flask
from AccountAPI import account_api
app = Flask(__name__)
app.register_blueprint(account_api)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
ap... |
How to repeat try-except block | 15,232,465 | 5 | 2013-03-05T19:28:45Z | 15,232,484 | 10 | 2013-03-05T19:30:12Z | [
"python",
"exception-handling",
"python-3.x"
] | I have a try-except block in Python 3.3, and I want it to run indefinitely.
```
try:
imp = int(input("Importance:\n\t1: High\n\t2: Normal\n\t3: Low"))
except ValueError:
imp = int(input("Please enter a number between 1 and 3:\n> ")
```
Currently, if a user were to enter a non-integer it would work as planned,... | Put it inside a while loop and break out when you've got the input you expect. It's probably best to keep all code dependant on `imp` in the `try` as below, or set a default value for it to prevent `NameError`'s further down.
```
while True:
try:
imp = int(input("Importance:\n\t1: High\n\t2: Normal\n\t3: Low"))
... |
Python + Regex: AttributeError: 'NoneType' object has no attribute 'groups' | 15,232,832 | 11 | 2013-03-05T19:51:34Z | 15,233,321 | 17 | 2013-03-05T20:20:44Z | [
"python",
"regex"
] | I have a string which I want to extract a subset of. This is part of a larger Python script.
This is the string:
```
import re
htmlString = '</dd><dt> Fine, thank you. </dt><dd> Molt bé, grà cies. (<i>mohl behh, GRAH-syuhs</i>)'
```
Which I want to pull-out "*Molt bé, grà cies. mohl behh, GRAH-syuhs*". And f... | You are getting `AttributeError` because you're calling `groups` on `None`, which hasn't any methods.
`regex.search` returning `None` means the regex couldn't find anything matching the pattern from supplied string.
when using regex, it is nice to check whether a match has been made:
```
Result = re.search(SearchStr... |
Getting rid of \n when using .readlines() | 15,233,340 | 90 | 2013-03-05T20:22:19Z | 15,233,358 | 8 | 2013-03-05T20:23:39Z | [
"python",
"python-2.7",
"readline"
] | I have a .txt file with values in it.
The values are listed like so:
```
Value1
Value2
Value3
Value4
```
My goal is to put the values in a list. When I do so, the list looks like this:
['Value1\n', 'Value2\n',.....]
The \n is not needed.
Here is my code.
```
t = open('filename.txt', 'r+w')
contents = t.readline(... | for each string in your list, use `.strip()` which removes whitespace from the beginning or end of the string:
```
for i in contents:
alist.append(i.strip())
```
But depending on your use case, you might be better off using something like `numpy.loadtxt` or even `numpy.genfromtxt` if you need a nice array of the ... |
Getting rid of \n when using .readlines() | 15,233,340 | 90 | 2013-03-05T20:22:19Z | 15,233,379 | 19 | 2013-03-05T20:25:12Z | [
"python",
"python-2.7",
"readline"
] | I have a .txt file with values in it.
The values are listed like so:
```
Value1
Value2
Value3
Value4
```
My goal is to put the values in a list. When I do so, the list looks like this:
['Value1\n', 'Value2\n',.....]
The \n is not needed.
Here is my code.
```
t = open('filename.txt', 'r+w')
contents = t.readline(... | You can use [`.rstrip('\n')`](https://docs.python.org/3/library/stdtypes.html#str.rstrip) to *only* remove newlines from the end of the string:
```
for i in contents:
alist.append(i.rstrip('\n'))
```
This leaves all other whitespace intact. If you don't care about whitespace at the start and end of your lines, th... |
Getting rid of \n when using .readlines() | 15,233,340 | 90 | 2013-03-05T20:22:19Z | 15,233,739 | 51 | 2013-03-05T20:44:30Z | [
"python",
"python-2.7",
"readline"
] | I have a .txt file with values in it.
The values are listed like so:
```
Value1
Value2
Value3
Value4
```
My goal is to put the values in a list. When I do so, the list looks like this:
['Value1\n', 'Value2\n',.....]
The \n is not needed.
Here is my code.
```
t = open('filename.txt', 'r+w')
contents = t.readline(... | I'd do this:
```
alist = [line.rstrip() for line in open('filename.txt')]
```
or:
```
with open('filename.txt') as f:
alist = [line.rstrip() for line in f]
``` |
Getting rid of \n when using .readlines() | 15,233,340 | 90 | 2013-03-05T20:22:19Z | 20,756,176 | 137 | 2013-12-24T06:44:21Z | [
"python",
"python-2.7",
"readline"
] | I have a .txt file with values in it.
The values are listed like so:
```
Value1
Value2
Value3
Value4
```
My goal is to put the values in a list. When I do so, the list looks like this:
['Value1\n', 'Value2\n',.....]
The \n is not needed.
Here is my code.
```
t = open('filename.txt', 'r+w')
contents = t.readline(... | This should do what you want (file contents in a list, by line, without \n)
```
with open(filename) as f:
mylist = f.read().splitlines()
``` |
Making a variable accessible for any other module | 15,234,288 | 3 | 2013-03-05T21:17:47Z | 15,234,304 | 7 | 2013-03-05T21:19:05Z | [
"python"
] | I am a new user in Python, I have been following this web page and it has helped me a lot.
At this moment I am trying to solve an issue of a variables that can´t be accessed from other modules.
```
Modelu1.py
Texto = ' string'
textoMayus = texto.upper()
print textoMayus
cadena = textoMayus.split ()
moduel2.py
im... | When you do `import entrada` you import the module, not the names inside it. You can either do:
```
import entrada
size = len(entrada.cadena)
```
or
```
from entrada import cadena
size = len(cadena)
```
You should read [the Python tutorial](http://docs.python.org/2/tutorial/) to learn the basics of module importing... |
Running Django MySQL tests in memory | 15,234,679 | 3 | 2013-03-05T21:40:45Z | 15,235,891 | 11 | 2013-03-05T23:06:38Z | [
"python",
"mysql",
"django"
] | I have a django 1.4 project using mysql as the backend. I have the tests setup to run in memory
```
if 'test' in sys.argv:
DATABASES['default'] = {'ENGINE': 'django.db.backends.sqlite3'}
```
The issue is I need to use mysql functionality (full text indexes).
**Is there a way to have django run MySQL in memory for ... | MySQL has a `MEMORY` storage engine. You *can* activate it using the `OPTIONS` key:
```
if 'test' in sys.argv:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': 'localhost',
'NAME': 'foo',
'USER': 'bar',
'PASSWORD': 'baz',
... |
Selection Sort Python | 15,235,264 | 4 | 2013-03-05T22:19:36Z | 15,235,396 | 7 | 2013-03-05T22:29:59Z | [
"python",
"sorting"
] | This may seem like a simple question but when I attempted to implement selection sort in Python, I do not get a sorted list. Is there something wrong with my implementation? The subsetting may be a problem.
```
source = [4,2,1,10,5,3,100]
for i in range(len(source)):
mini = min(source[i:]) #find minimum element
mi... | I think there were a couple issues.
First, when your do source[i:], I believe that returns a new array of the sub-elements requested and not part of the original array, thus if you modify it, your don't modify the original. Second, you were subtracting 1 from an index when you shouldn't.
```
source = [4,2,1,10,5,3,10... |
Django RuntimeError: maximum recursion depth exceeded | 15,236,556 | 2 | 2013-03-06T00:02:36Z | 21,834,885 | 17 | 2014-02-17T16:55:41Z | [
"python",
"django",
"eclipse",
"pydev"
] | I'm new to Django. I installed Django using easy\_install (on a Mac) and PyDev Django plugin for eclipse. I followed standard procedures to create a new PyDev Django project. When I try to run the project as PyDev: Django, I get the following error.
```
Validating models...
RuntimeError: maximum recursion depth excee... | The problem is in functools.py file. This file is from Python.
To fix the problem replace this (about line 56 in python\Lib\fuctools.py):
```
convert = {
'__lt__': [('__gt__', lambda self, other: other < self),
('__le__', lambda self, other: not other < self),
('__ge__', lambda s... |
Python Unicode Encode Error ordinal not in range<128> with Euro Sign | 15,237,702 | 13 | 2013-03-06T02:06:54Z | 15,237,981 | 19 | 2013-03-06T02:38:23Z | [
"python",
"unicode",
"python-2.7",
"ascii"
] | I have to read an XML file in Python and grab various things, and I ran into a frustrating error with Unicode Encode Error that I couldn't figure out even with googling.
Here are snippets of my code:
```
#!/usr/bin/python
# coding: utf-8
from xml.dom.minidom import parseString
with open('data.txt','w') as fout:
#d... | when you are opening a file in python using the `open` built-in function you will always read the file in ascii. To access it in another encoding you have to use codecs:
```
import codecs
fout = codecs.open('data.txt','w','utf-8')
``` |
python modules hierarchy naming convention | 15,237,806 | 2 | 2013-03-06T02:17:56Z | 15,237,883 | 7 | 2013-03-06T02:27:13Z | [
"python",
"module",
"python-module"
] | I'd like to have modules/packages structure like following:
```
/__init__.py
/mymodule.py
/mymodule/
/mymodule/__init__.py
/mymodule/submodule.py
```
And then use modules like:
```
import mymodule
import mymodule.submodule
```
But it seems like file "**mymodule.py**" conflicts with "**mymodule**" directory.
What's... | If you want to make a package, you have to understand how Python translates filenames to module names.
The file `mymodule.py` will be available as the `mymodule`, assuming the interpreter finds it in a directory in the Python search path. If you're on a case-insensitive filesystem, it might also be importable with dif... |
Keep trailing zeroes in python | 15,238,120 | 3 | 2013-03-06T02:55:54Z | 15,238,187 | 8 | 2013-03-06T03:01:05Z | [
"python",
"parsing"
] | I am writing a class to represent money, and one issue I've been running into is that `"1.50" != str(1.50)`. str(1.50) equals 1.5, and alll of a sudden, POOF. 45 cents have vanished and the amount is now 1 dollar and 5 cents. not one dollar and 50 cents. Any way I could prevent str from doing this, or am I doing someth... | You can use the `format` method on strings to specify how many decimal places you want to represent:
```
>>> "{:.2f}".format(1.5)
'1.50'
```
But even better would be to use the [`decimal module`](http://docs.python.org/2/library/decimal.html) for representing money, since representation issues with binary floats can ... |
Task priority in celery with redis | 15,239,880 | 3 | 2013-03-06T05:47:25Z | 15,246,708 | 9 | 2013-03-06T11:55:45Z | [
"python",
"celery",
"distributed"
] | I would like to implement a distributed job execution system with celery. Given that rabbitMQ doesn't support priorities and I'm painfully needing this feature, I turned to celery+redis.
In my situation, the tasks are closely related to hardware, for example, task A could only run on Worker 1 since only the PC of Work... | The Celery Redis transport does honor the priority field,
but Redis itself has no notion of priorities.
The priority support is implemented by creating n lists for each queue
and using that order in the BRPOP command.
I say `n` here because even though there are 10 (0-9) priority levels, these are
consolidated into 4 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.