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 |
|---|---|---|---|---|---|---|---|---|---|
creating a heap in python | 12,749,622 | 14 | 2012-10-05T15:40:29Z | 12,749,951 | 7 | 2012-10-05T16:01:39Z | [
"python"
] | The collections.Count.most\_common function in python uses the heapq module to return the count of the most common word in a file for instance.
I have traced through the heapq.py file, but I'm having a bit of trouble understanding how a heap is created/updated with respect to words let's say.
So I think the best way ... | this is a slightly modified version of the code found here : <http://code.activestate.com/recipes/577086-heap-sort/>
```
def HeapSort(A,T):
def heapify(A):
start = (len(A) - 2) / 2
while start >= 0:
siftDown(A, start, len(A) - 1)
start -= 1
def siftDown(A, start, end):
... |
creating a heap in python | 12,749,622 | 14 | 2012-10-05T15:40:29Z | 12,756,982 | 23 | 2012-10-06T05:19:24Z | [
"python"
] | The collections.Count.most\_common function in python uses the heapq module to return the count of the most common word in a file for instance.
I have traced through the heapq.py file, but I'm having a bit of trouble understanding how a heap is created/updated with respect to words let's say.
So I think the best way ... | In Python 2.X and 3.x, heaps are supported through an importable library, heapq. It supplies numerous functions to work with the heap data structure modelled in a Python list.
Example:
```
>>> from heapq import heappush, heappop
>>> heap = []
>>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
>>> for item in data:
heap... |
Python Matplotlib figure title overlaps axes label when using twiny | 12,750,355 | 60 | 2012-10-05T16:26:49Z | 12,751,200 | 26 | 2012-10-05T17:28:12Z | [
"python",
"matplotlib",
"title",
"figure"
] | I am trying to plot two separate quantities on the same graph using twiny as follows:
```
fig = figure()
ax = fig.add_subplot(111)
ax.plot(T, r, 'b-', T, R, 'r-', T, r_geo, 'g-')
ax.set_yscale('log')
ax.annotate('Approx. sea level', xy=(Planet.T_day*1.3,(Planet.R)/1000), xytext=(Planet.T_day*1.3, Planet.R/1000))
ax.an... | Forget using `plt.title` and place the text directly with `plt.text`. An over-exaggerated example is given below:
```
import pylab as plt
fig = plt.figure(figsize=(5,10))
figure_title = "Normal title"
ax1 = plt.subplot(1,2,1)
plt.title(figure_title, fontsize = 20)
plt.plot([1,2,3],[1,4,9])
figure_title = "Raised ... |
Python Matplotlib figure title overlaps axes label when using twiny | 12,750,355 | 60 | 2012-10-05T16:26:49Z | 23,338,363 | 105 | 2014-04-28T10:14:27Z | [
"python",
"matplotlib",
"title",
"figure"
] | I am trying to plot two separate quantities on the same graph using twiny as follows:
```
fig = figure()
ax = fig.add_subplot(111)
ax.plot(T, r, 'b-', T, R, 'r-', T, r_geo, 'g-')
ax.set_yscale('log')
ax.annotate('Approx. sea level', xy=(Planet.T_day*1.3,(Planet.R)/1000), xytext=(Planet.T_day*1.3, Planet.R/1000))
ax.an... | I'm not sure whether it is a new feature in later versions of matplotlib, but at least for 1.3.1, this is simply:
```
plt.title(figure_title, y=1.08)
```
This also works for `plt.suptitle()`, but not (yet) for `plt.xlabel()`, etc. |
Booleans in ConfigParser always return True | 12,750,778 | 2 | 2012-10-05T16:57:23Z | 12,750,865 | 13 | 2012-10-05T17:03:29Z | [
"python",
"boolean",
"configparser"
] | This is my example script:
```
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('conf.ini')
print bool(config.get('main', 'some_boolean'))
print bool(config.get('main', 'some_other_boolean'))
```
And this is `conf.ini`:
```
[main]
some_boolean: yes
some_other_boolean: no
```
When running the s... | Use [`getboolean()`](http://docs.python.org/library/configparser.html#ConfigParser.RawConfigParser.getboolean):
```
print config.getboolean('main', 'some_boolean')
print config.getboolean('main', 'some_other_boolean')
```
From the [Python manual](http://docs.python.org/library/configparser.html#ConfigParser.RawConfi... |
UnicodeDecodeError in Python 3 when importing a CSV file | 12,752,313 | 7 | 2012-10-05T18:49:54Z | 12,752,390 | 8 | 2012-10-05T18:55:15Z | [
"python",
"unicode",
"csv",
"python-3.x",
"non-ascii-characters"
] | I'm trying to import a CSV, using this code:
```
import csv
import sys
def load_csv(filename):
# Open file for reading
file = open(filename, 'r')
# Read in file
return csv.reader(file, delimiter=',', quotechar='\n')
def main(argv):
csv_file = load_csv("myfile.... | From the [python docs](http://docs.python.org/py3k/library/csv.html?highlight=csv#csv), you have to set the encoding for the file. Here is an example from the site:
```
import csv
with open('some.csv', newline='', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
print(row)
```
Edit: Your... |
UnicodeDecodeError in Python 3 when importing a CSV file | 12,752,313 | 7 | 2012-10-05T18:49:54Z | 12,752,945 | 7 | 2012-10-05T19:37:09Z | [
"python",
"unicode",
"csv",
"python-3.x",
"non-ascii-characters"
] | I'm trying to import a CSV, using this code:
```
import csv
import sys
def load_csv(filename):
# Open file for reading
file = open(filename, 'r')
# Read in file
return csv.reader(file, delimiter=',', quotechar='\n')
def main(argv):
csv_file = load_csv("myfile.... | It seems your problem boils down to:
```
print("α")
```
You could fix it by specifying [`PYTHONIOENCODING`](http://docs.python.org/dev/using/cmdline.html):
```
$ PYTHONIOENCODING=utf-8 python3 test.py > output.txt
```
Note:
```
$ python3 test.py
```
should work as is if your terminal configuration supports it, w... |
Is Multiple Inheritance problematic in Python? | 12,753,260 | 2 | 2012-10-05T20:01:55Z | 12,753,310 | 7 | 2012-10-05T20:06:08Z | [
"python",
"python-3.x",
"multiple-inheritance"
] | Hello i was searching about class inheritance in python and i saw that it supports Multiple Inheritance as well but somehow seems problematic :o
I ve found an example:
```
class ParentOne:
def __init__(self):
print "Parent One says: Hello my child!"
self.i = 1
def methodOne(self):
prin... | This is what [`super`](http://docs.python.org/py3k/library/functions.html#super) is for:
```
class ParentOne():
def __init__(self):
super().__init__()
print("Parent One says: Hello my child!")
self.i = 1
def methodOne(self):
print(self.i)
class ParentTwo():
def __i... |
Sqlalchemy mixins / and event listener | 12,753,450 | 6 | 2012-10-05T20:17:00Z | 12,754,068 | 11 | 2012-10-05T21:09:24Z | [
"python",
"events",
"model",
"sqlalchemy"
] | I am attempting 2 new things at once, so assistance in both simplifying and clarifying is appreciated.
```
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy import Column, Float, event
class TimeStampMixin(object):
@declared_attr
def __tablename__(cls):
return cls.__name__.lower()
... | Here's what I'd do to listen on `before_insert` events: add a `classmethod` to your `TimeStampMixin` that registers the current class and handles setting creation time.
E.g.
```
class TimeStampMixin(object):
# other class methods
@staticmethod
def create_time(mapper, connection, target):
target.... |
Sqlalchemy mixins / and event listener | 12,753,450 | 6 | 2012-10-05T20:17:00Z | 13,617,585 | 29 | 2012-11-29T01:52:39Z | [
"python",
"events",
"model",
"sqlalchemy"
] | I am attempting 2 new things at once, so assistance in both simplifying and clarifying is appreciated.
```
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy import Column, Float, event
class TimeStampMixin(object):
@declared_attr
def __tablename__(cls):
return cls.__name__.lower()
... | Attach your listener inside the class method and it will attach the event to the child class.
```
class TimeStampMixin(object):
@staticmethod
def create_time(mapper, connection, target):
target.created = time()
@classmethod
def __declare_last__(cls):
# get called after mappings are com... |
Overriding Python mock's patch decorator | 12,753,909 | 8 | 2012-10-05T20:55:47Z | 12,804,065 | 15 | 2012-10-09T16:08:02Z | [
"python",
"testing",
"mocking"
] | I have a Python `TestCase` class where all test methods, except one, need to patch an object the same way. The other method need some other behavior from the same object. I'm using [mock](http://www.voidspace.org.uk/python/mock/), so I did:
```
@mock.patch('method_to_patch', mock.Mock(return_value=1))
class Tests(Test... | Well, turns out that a good night sleep and a cold shower made me rethink the whole issue.
I'm still very new to the concept of mocking, so it still hasn't sunk in quite right.
The thing is, there's no need to override the patch to a mocked object. It's a mocked object and that means I can make it do anything. So my f... |
Modulo operator in Python | 12,754,680 | 24 | 2012-10-05T22:07:43Z | 12,754,708 | 37 | 2012-10-05T22:11:46Z | [
"python",
"python-3.x",
"operators"
] | What does modulo in the following piece of code do?
```
from math import *
3.14 % 2 * pi
```
How do we calculate modulo on a floating point number? | Mathematically, the modulo operator can be represented as:
```
a % b = c
a - n*b = c
```
Where `n` is an integer that makes `c` as small as possible, but positive.
In this case:
```
3.14 % 2
= 3.14 - 1 * 2
= 1.14
```
Also, `3.14 % 2 * pi` is interpreted as `(3.14 % 2) * pi`. I'm not sure if you meant to write `3... |
Modulo operator in Python | 12,754,680 | 24 | 2012-10-05T22:07:43Z | 12,754,727 | 17 | 2012-10-05T22:14:01Z | [
"python",
"python-3.x",
"operators"
] | What does modulo in the following piece of code do?
```
from math import *
3.14 % 2 * pi
```
How do we calculate modulo on a floating point number? | In addition to the other answers, the [`fmod` documentation](http://docs.python.org/library/math.html#math.fmod) has some interesting things to say on the subject:
> `math.fmod(x, y)`
>
> Return `fmod(x, y)`, as defined by the platform C
> library. Note that the Python expression `x % y` may not return the same
> resu... |
Insert xml element as first child using ElementTree in python | 12,754,872 | 4 | 2012-10-05T22:32:31Z | 12,755,007 | 7 | 2012-10-05T22:47:27Z | [
"python",
"xml",
"elementtree"
] | I'm using python to create an element in an xml document and then insert it as the FIRST CHILD of the document. So, if I were creating an elment named `newChild` I would want xml like this...
```
<root>
<childA></childA>
<childB></childB>
<childC></childC>
</root>
```
to become...
```
<root>
<newChild></newC... | The [xml.etree.ElementTree.Element.insert](http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.insert) method allows you to add a new sub-element to an element inserted at a specific position.
In your case `element.insert(0, new_sub_element)` should do the trick. |
Python insertion sort | 12,755,568 | 8 | 2012-10-06T00:15:02Z | 12,755,815 | 7 | 2012-10-06T01:02:55Z | [
"python"
] | Here's a Python implementation of insertion sort, I tried to follow the values on paper but once the counting variable i gets bigger than len(s) I don't know what to do, how/why does it still run?
```
def sort_numbers(s):
for i in range(1, len(s)):
val = s[i]
j = i - 1
while (j >= 0) and (s... | Consider [3, 2, 1]
The loop starts with 3. Since it is the first item in the list there is nothing else to do.
```
[3, 2, 1]
```
The next item is 2. It compares 2 to 3 and since 2 is less than 3 it swaps them, first putting 3 in the second position and then placing 2 in the first position.
```
[2, 3, 1]
```
The la... |
Using python to write specific lines from one file to another file | 12,755,587 | 5 | 2012-10-06T00:18:12Z | 12,755,708 | 10 | 2012-10-06T00:40:43Z | [
"python"
] | I have ~200 short text files (50kb) that all have a similar format. I want to find a line in each of those files that contains a certain string and then write that line plus the next three lines (but not rest of the lines in the file) to another text file. I am trying to teach myself python in order to do this and have... | As pointed out by @ajon, I don't think there's anything fundamentally wrong with your code except the indentation. With the indentation fixed it works for me. However there's a couple opportunities for improvement.
**1)** In Python, the standard way of iterating over things is by using a [`for` loop](http://docs.pytho... |
Sending Arrow Keys to Popen | 12,755,968 | 5 | 2012-10-06T01:41:28Z | 12,756,084 | 8 | 2012-10-06T02:09:52Z | [
"python",
"popen"
] | I know that it's possible to send printable input to `subprocess`es by `write`ing to their `stdin`
```
from subprocess import, Popen, PIPE
proc = Popen([command, goes, here], stdin=PIPE)
proc.stdin.write("m")
```
How would I go about sending input such as arrow key presses, space, return, or backspace? | I found someone who was trying to solve the opposite problem, create a program that could recognize the arrow keys: [Recognizing arrow keys with stdin](http://stackoverflow.com/questions/4130048/recognizing-arrow-keys-with-stdin)
I also found
<http://compgroups.net/comp.unix.programmer/how-to-send-up-arrow-key-to-pope... |
Use different .ini file for alembic.ini | 12,756,976 | 7 | 2012-10-06T05:18:25Z | 12,757,266 | 14 | 2012-10-06T06:11:08Z | [
"python",
"pyramid",
"alembic"
] | I'm attempting to configure SQLAlchemy Alembic for my Pyramid project and I want to use my developement.ini (or production.ini) for the configuration settings for Alembic. Is it possible to specify the .ini file I wish to use anywhere within Alembic? | Just specify `alembic -c /some/path/to/another.ini` when running alembic commands. You could even put the `[alembic]` section in your development.ini and production.ini files and just `alembic -c production.ini upgrade head`. |
Installer and Updater for a python desktop application | 12,758,088 | 30 | 2012-10-06T08:25:06Z | 12,807,729 | 7 | 2012-10-09T20:13:45Z | [
"python",
"windows",
"nsis",
"auto-update",
"pyinstaller"
] | I am building a desktop app with python and packaging it to an exe with Pyinstaller.
I would like to ship my application with an installer and also provide automatic and silent updates to the software like Google Chrome, Dropbox or Github for Windows does.
I have found the following software to be able to do this:
* ... | [WiX](http://wixtoolset.org/) (Windows Installer XML toolset) is an open source project for an MSI authoring tool.
Part of the project is [ClickThrough](http://wix.sourceforge.net/ctvision.html), a set of add-on tools, including a tool to automatically detect available updates (via an RSS feed), notify users and inst... |
Installer and Updater for a python desktop application | 12,758,088 | 30 | 2012-10-06T08:25:06Z | 12,823,983 | 13 | 2012-10-10T16:19:49Z | [
"python",
"windows",
"nsis",
"auto-update",
"pyinstaller"
] | I am building a desktop app with python and packaging it to an exe with Pyinstaller.
I would like to ship my application with an installer and also provide automatic and silent updates to the software like Google Chrome, Dropbox or Github for Windows does.
I have found the following software to be able to do this:
* ... | There is a suite of tools from the cloudmatrix guys that addresses that problem.
[esky](http://pypi.python.org/pypi/esky) is an auto-update framework for frozen apps that is compatible with the common python "packaging" frameworks. [signedimp](http://pypi.python.org/pypi/signedimp/0.3.2) tries to ensure that apps are ... |
Python Text to Speech in Macintosh | 12,758,591 | 5 | 2012-10-06T09:39:40Z | 12,761,406 | 22 | 2012-10-06T16:12:14Z | [
"python",
"osx",
"text-to-speech"
] | Are there any libraries in Python that does or allows Text To Speech Conversion using Mac Lion's built in text to speech engine?
I did google but most are windows based. I tried pyttx.
I tried to run
```
import pyttsx
engine = pyttsx.init()
engine.say('Sally sells seashells by the seashore.')
engine.say('The quick bro... | Wouldn't it be much simpler to do this?
```
from os import system
system('say Hello world!')
```
You can enter `man say` to see other things you can do with the `say` command.
However, if you want some more advanced features, importing `AppKit` would also be a possibility, although some Cocoa/Objective C knowledge i... |
Python command line interaction library? | 12,758,638 | 4 | 2012-10-06T09:47:09Z | 12,761,605 | 7 | 2012-10-06T16:33:44Z | [
"python"
] | I want to develop a small Python app that interacts with the user via the console/command line. Are there any good libraries I can use to get user input and display the output in a nice-looking way? I tried searching but most of what I found was command-line argument processing, didn't see anything about user interacti... | A really excellent library is [cmd](http://docs.python.org/py3k/library/cmd.html) which is part of the python standard library. It is cross platform Windows, Linux, Mac. You just have to implement one class and it offers so many great features:
1. provides list of supported commands(they end up being implemented as me... |
Green-threads and thread in python | 12,758,952 | 26 | 2012-10-06T10:28:14Z | 16,641,452 | 12 | 2013-05-20T01:48:03Z | [
"python",
"multithreading",
"pthreads",
"gil",
"green-threads"
] | As [**Wikipedia States**](http://en.wikipedia.org/wiki/Green_threads):
> Green threads emulate multi-threaded environments without relying on any native OS capabilities, and they are managed in user space instead of kernel space, enabling them to work in environments that do not have native thread support.
Python's t... | You can think of greenlets more like cooperative threads. What this means is that there is no scheduler pre-emptively switching between your threads at any given moment - instead your greenlets voluntarily/explicitly give up control to one another at specified points in your code.
> Does the GIL affect them? Can there... |
Image conversion in PIL, pgm file error | 12,759,013 | 2 | 2012-10-06T10:35:52Z | 12,759,080 | 8 | 2012-10-06T10:46:27Z | [
"python",
"image-processing",
"python-imaging-library"
] | When trying to do the following in the PIL python library:
```
Image.open('Apple.gif').save('Apple.pgm')
```
the code fails with:
```
Traceback (most recent call last):
File "/home/eran/.eclipse/org.eclipse.platform_3.7.0_155965261/plugins/org.python.pydev_2.6.0.2012062818/pysrc/pydevd_comm.py", line 765, in doI... | You need to convert the image to `RGB` mode to make this work.
```
im = Image.open('Apple.gif')
im = im.convert('RGB')
im.save('Apple.pgm')
``` |
python pip: force install ignoring dependencies | 12,759,761 | 32 | 2012-10-06T12:21:56Z | 12,759,996 | 55 | 2012-10-06T12:55:19Z | [
"python",
"pip"
] | Is there any way to force install a pip python package ignoring all it's dependencies that cannot be satisfied?
(I don't care how "wrong" it is to do so, I just need to do it, any logic and reasoning aside...) | pip has a `--no-dependencies` switch. You should use that.
For more information, run `pip install -h`, where you'll see this line:
```
--no-deps, --no-dependencies
Ignore package dependencies
``` |
How do I convert the three letter amino acid codes to one letter code with python or R? | 12,760,271 | 8 | 2012-10-06T13:39:20Z | 12,760,399 | 7 | 2012-10-06T13:55:39Z | [
"python",
"bioinformatics",
"biopython"
] | I have a fasta file as shown below. I would like to convert the [three letter codes](https://en.wikipedia.org/wiki/Amino_acid#Table_of_standard_amino_acid_abbreviations_and_properties) to one letter code. How can I do this with python or R?
```
>2ppo
ARGHISLEULEULYS
>3oot
METHISARGARGMET
```
desired output
```
>2ppo... | Use a dictionary to look up the one letter codes:
```
d = {'CYS': 'C', 'ASP': 'D', 'SER': 'S', 'GLN': 'Q', 'LYS': 'K',
'ILE': 'I', 'PRO': 'P', 'THR': 'T', 'PHE': 'F', 'ASN': 'N',
'GLY': 'G', 'HIS': 'H', 'LEU': 'L', 'ARG': 'R', 'TRP': 'W',
'ALA': 'A', 'VAL':'V', 'GLU': 'E', 'TYR': 'Y', 'MET': 'M'}
```
... |
How do I convert the three letter amino acid codes to one letter code with python or R? | 12,760,271 | 8 | 2012-10-06T13:39:20Z | 20,939,694 | 7 | 2014-01-05T21:55:27Z | [
"python",
"bioinformatics",
"biopython"
] | I have a fasta file as shown below. I would like to convert the [three letter codes](https://en.wikipedia.org/wiki/Amino_acid#Table_of_standard_amino_acid_abbreviations_and_properties) to one letter code. How can I do this with python or R?
```
>2ppo
ARGHISLEULEULYS
>3oot
METHISARGARGMET
```
desired output
```
>2ppo... | BioPython already has built-in dictionaries to help with such translations. Following commands will show you a whole list of available dictionaries:
```
import Bio
help(Bio.SeqUtils.IUPACData)
```
The predefined dictionary you are looking for:
```
Bio.SeqUtils.IUPACData.protein_letters_3to1['Ala']
``` |
imshow(img, cmap=cm.gray) shows a white for 128 value | 12,760,797 | 11 | 2012-10-06T14:45:24Z | 12,760,890 | 18 | 2012-10-06T14:59:41Z | [
"python",
"matplotlib"
] | I'm moving from MatLab to python and playing around with the imshow function.
I can't seem to get my head around why it doesn't show the value 128 as grey with I have chosen the cmap to be gray-scale.

It seems as it uses the grayscale for highest (128) and lowest v... | Use the `vmin` and `vmax` parameters:
```
plt.imshow(bg, cmap = plt.get_cmap('gray'), vmin = 0, vmax = 255)
```
Without specifying `vmin` and `vmax`, `plt.imshow` auto-adjusts its range to the min and max of the data.
---
I do not know of a way to set default `vmin` and `vmax` parameters for all imshow plots, but y... |
matplotlib: 2 different legends on same graph | 12,761,806 | 23 | 2012-10-06T16:55:30Z | 12,762,069 | 32 | 2012-10-06T17:25:29Z | [
"python",
"matplotlib",
"legend"
] | I have a plot where different colors are used for different parameters, and where different line styles are used for different algorithms. The goal is to compare the results of the different algorithms performed with similar parameters. It means in total I use 4 different colors, and 3 different line styles, for a tota... | There's a section in the matplotlib documentation on that exact subject: <http://matplotlib.org/users/legend_guide.html#multiple-legend>
Here's code for your specific example:
```
import itertools
from matplotlib import pyplot
colors = ['b', 'r', 'g', 'c']
cc = itertools.cycle(colors)
plot_lines = []
for p in parame... |
How to use append with pickle in python? | 12,761,991 | 5 | 2012-10-06T17:17:53Z | 12,762,056 | 17 | 2012-10-06T17:24:33Z | [
"python",
"python-2.7"
] | i need to append to a pickle file (as i don't have the entire dictionary with me at one go). So for doing the same I have written the following code:
```
import pickle
p={}
p[1]=2
q={}
q['a']=p
p={}
p[2]=0
pickle.dump(q, open("save12.p","ab"))
f={}
f['b']=p
pickle.dump(f,open("save12.p","ab"))
```
However,... | Pickle streams are entirely self-contained, and so unpickling will unpickle one object at a time.
Therefore, to unpickle multiple streams, you should repeatedly unpickle the file until you get an EOFError:
```
>>> f=open('a.p', 'wb')
>>> pickle.dump({1:2}, f)
>>> pickle.dump({3:4}, f)
>>> f.close()
>>>
>>> f=open('a... |
Python: "import ... as" causes incorrect reference | 12,762,153 | 2 | 2012-10-06T17:34:44Z | 12,762,197 | 10 | 2012-10-06T17:38:30Z | [
"python",
"import",
"module"
] | I've noticed a peculiar behavior in how python handles module names.
If I write:
```
import a.b
import a
```
and then attempt to reference something in module a.b, it works without a problem.
However, if I attempt something only slightly different:
```
import a.b
import c as a
```
and then attempt to reference so... | Why do you expect it to work? All 4 of your import statements are assignments to the variable `a`. Thus if you assign `c` to `a`, it overwrites the contents with something that doesn't have a `.b` attribute.
---
Here's what happens in the first case:
1. When `import a.b` is run, Python loads module `a`, and then loa... |
How do I connect to an existing CloudSearch domain in boto? | 12,763,129 | 6 | 2012-10-06T19:33:51Z | 12,763,628 | 10 | 2012-10-06T20:33:52Z | [
"python",
"amazon-web-services",
"boto",
"amazon-cloudsearch"
] | I'm just starting to work with boto to connect to Amazon CloudSearch.
I got the examples working, but I can't find any examples of connecting to an existing domain, all the examples create a new domain.
Poking around, I found get\_domain, but that fails if I call it on the connection object.
```
>>> conn.get_domain(... | You can either do `conn.list_domains()` which will return a list of Domain objects for all of your current domains or you can do `conn.lookup('foo')` which will return a Domain object for the specified domain name. |
How to Access files on Heroku? | 12,763,440 | 4 | 2012-10-06T20:13:08Z | 12,763,635 | 7 | 2012-10-06T20:34:29Z | [
"python",
"heroku"
] | I have a project on Heroku. This project allows me to update a json file. If update something on heroku via the project's web interface. I see the update. I can close the browers, open it and the update presists.
Now, I want to push something to project. If I do the json file will be overwritten. So, I pulled first to... | I don't think this is possible, for one reason: A Heroku dyno has it's own [ephemeral filesystem](https://devcenter.heroku.com/articles/dynos#ephemeral-filesystem) with a git checkout of the most recent code. It cannot go the other way around however, it's not possible to check file changes in the dyno in into the git ... |
Python regex - why does end of string ($ and \Z) not work with group expressions? | 12,763,548 | 7 | 2012-10-06T20:25:21Z | 12,763,567 | 20 | 2012-10-06T20:27:52Z | [
"python",
"regex"
] | In Python 2.6. it seems that markers of the end of string `$` and `\Z` are not compatible with group expressions. Fo example
```
import re
re.findall("\w+[\s$]", "green pears")
```
returns
```
['green ']
```
(so `$` effectively does not work). And using
```
re.findall("\w+[\s\Z]", "green pears")
```
results in an... | A `[..]` expression is a *character group*, meaning it'll match any one character contained therein. You are thus matching a literal `$` character. A character group always applies to one input character, and thus can never contain an anchor.
If you wanted to match either a whitespace character *or* the end of the str... |
Fractions in Python | 12,763,757 | 4 | 2012-10-06T20:50:06Z | 12,763,771 | 9 | 2012-10-06T20:51:23Z | [
"python",
"fractions"
] | Is there anyway to compute a fraction, e.g. 2/3 or 1/2, in Python without importing the `math` module?
The code snippet is simple:
```
# What is the cube root of your number
n = float(raw_input('Enter a number: '))
print(n**(1/3))
```
Extraordinarily simple code, but everywhere I look it's telling me to import the `... | You can use `from __future__ import division` to make integer division return floats where necessary (so that 1/3 will result in 0.333333...).
Even without doing that, you can get your fractional value by doing `1.0/3` instead of `1/3`. (The `1.0` makes the first number a float rather than an integer, which makes divi... |
Django: invalid keyword argument for this function | 12,764,347 | 6 | 2012-10-06T22:13:06Z | 12,764,382 | 16 | 2012-10-06T22:18:34Z | [
"python",
"django"
] | I want to insert some data into a many to many field. I 'm getting this Error
> user is an invalid keyword argument for this function
i also tried it with the relatedName...but still is not working...
My model looks like this:
models.py
```
class Workspace(models.Model):
user = models.ManyToManyField(User,null... | You used a [`ManyToMany`](https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ManyToManyField) field for the `user` field of your `Workspace` object, you can't give it one user, that's not how a `ManyToMany` works, that would be a [`ForeignKey`](https://docs.djangoproject.com/en/dev/ref/models/fie... |
Python Unicode Encoding | 12,764,589 | 5 | 2012-10-06T22:54:33Z | 12,764,646 | 11 | 2012-10-06T23:04:53Z | [
"python",
"unicode",
"encode",
"argparse"
] | I am using `argparse` to read in arguments for my python code. One of those inputs is a title of a file [`title`] which can contain Unicode characters. I have been using `22å°å¥³æä»£22` as a test string.
I need to write the value of the input `title` to a file, but when I try to convert the string to `UTF-8` it alw... | It looks like your input data is in [SJIS encoding](https://en.wikipedia.org/wiki/Shift_JIS) (a legacy encoding for Japanese), which produces the byte 0x8f at position 2 in the bytestring:
```
>>> '22å°å¥³æä»£22'.encode('sjis')
b'22\x8f\xad\x8f\x97\x8e\x9e\x91\xe322'
```
(At Python 3 prompt)
Now, ~~I'm guessing t... |
Python, Overriding an inherited class method | 12,764,995 | 20 | 2012-10-07T00:11:08Z | 12,765,029 | 11 | 2012-10-07T00:17:54Z | [
"python",
"inheritance",
"methods",
"super",
"overwrite"
] | I have two classes, `Field` and `Background`. They look a little bit like this:
```
class Field( object ):
def __init__( self, a, b ):
self.a = a
self.b = b
self.field = self.buildField()
def buildField( self ):
field = [0,0,0]
return field
class Background( Field ):
... | > I expected Background init() to be called
Actually `Background init()` is getting called..
But **take a look at your Background class..**
```
class Background( Field ):
def __init__( self, a, b, c ):
super(Background, self).__init__( a, b )
self.field = self.buildField( c )
```
So, the first s... |
Python, Overriding an inherited class method | 12,764,995 | 20 | 2012-10-07T00:11:08Z | 12,765,092 | 7 | 2012-10-07T00:32:32Z | [
"python",
"inheritance",
"methods",
"super",
"overwrite"
] | I have two classes, `Field` and `Background`. They look a little bit like this:
```
class Field( object ):
def __init__( self, a, b ):
self.a = a
self.b = b
self.field = self.buildField()
def buildField( self ):
field = [0,0,0]
return field
class Background( Field ):
... | Coming from a C++ perspective, there might be two misconceptions here.
First, overriding a method with a different signature does not overload it like in C++. If one of your Background objects tries to call buildField with no arguments, the original version from Field will not be called -- it has been completely hidde... |
Python, Overriding an inherited class method | 12,764,995 | 20 | 2012-10-07T00:11:08Z | 12,765,103 | 26 | 2012-10-07T00:35:03Z | [
"python",
"inheritance",
"methods",
"super",
"overwrite"
] | I have two classes, `Field` and `Background`. They look a little bit like this:
```
class Field( object ):
def __init__( self, a, b ):
self.a = a
self.b = b
self.field = self.buildField()
def buildField( self ):
field = [0,0,0]
return field
class Background( Field ):
... | > I expected Background init() to be called. To pass "a, b" to Fields
> init(), Field to assign a and b
So far, so good.
> then to assign a list with three 0's
> in it to field.
Ah. This is where we get the error.
```
self.field = self.buildField()
```
Even though this line occurs within `Field.__init__`, `sel... |
pyramid AuthTktAuthenticationPolicy secret parameter | 12,765,349 | 5 | 2012-10-07T01:22:25Z | 12,767,843 | 13 | 2012-10-07T10:06:31Z | [
"python",
"authentication",
"pyramid"
] | What exactly is the 'secret' parameter of Pyramid's `pyramid.authentication.AuthTktAuthenticationPolicy` function? The [documentation](http://pyramid.readthedocs.org/en/latest/api/authentication.html#pyramid.authentication.AuthTktAuthenticationPolicy) says that it's "(a string) used for auth\_tkt cookie signing. Requir... | A tkt auth cookie is a secure hash of several pieces of information, including the username and optionally a timestamp, but not the user password. Once authenticated, you give such a cookie to the user, and every time the user returns you just extract the username again and know it's the same user.
To *keep* this cook... |
Counting the number of True Booleans in a Python List | 12,765,833 | 50 | 2012-10-07T03:12:41Z | 12,765,840 | 62 | 2012-10-07T03:13:56Z | [
"python",
"list",
"boolean",
"counting"
] | I have a list of Booleans:
```
[True, True, False, False, False, True]
```
and I am looking for a way to count the number of `True` in the list (so in the example above, I want the return to be `3`.) I have found examples of looking for the number of occurrences of specific elements, but is there a more efficient way... | `True` is equal to `1`.
```
>>> sum([True, True, False, False, False, True])
3
``` |
Counting the number of True Booleans in a Python List | 12,765,833 | 50 | 2012-10-07T03:12:41Z | 12,766,000 | 25 | 2012-10-07T03:56:50Z | [
"python",
"list",
"boolean",
"counting"
] | I have a list of Booleans:
```
[True, True, False, False, False, True]
```
and I am looking for a way to count the number of `True` in the list (so in the example above, I want the return to be `3`.) I have found examples of looking for the number of occurrences of specific elements, but is there a more efficient way... | If you are only concerned with the constant `True`, a simple `sum` is fine. However, keep in mind that in Python other values evaluate as `True` as well. A more robust solution would be to use the `bool` builtin:
```
>>> l = [1, 2, True, False]
>>> sum(bool(x) for x in l)
3
```
UPDATE: Here's another similarly robust... |
Counting the number of True Booleans in a Python List | 12,765,833 | 50 | 2012-10-07T03:12:41Z | 12,766,783 | 51 | 2012-10-07T06:57:39Z | [
"python",
"list",
"boolean",
"counting"
] | I have a list of Booleans:
```
[True, True, False, False, False, True]
```
and I am looking for a way to count the number of `True` in the list (so in the example above, I want the return to be `3`.) I have found examples of looking for the number of occurrences of specific elements, but is there a more efficient way... | `list` has a `count` method:
```
>>> [True,True,False].count(True)
2
``` |
Subprocess management with python | 12,766,026 | 2 | 2012-10-07T04:04:51Z | 12,766,265 | 10 | 2012-10-07T05:07:54Z | [
"python",
"parallel-processing"
] | I have a data analysis script that takes an argument specifying the segments of the analysis to perform. I want to run up to 'n' instances of the script at a time where 'n' is the number of cores on the machine. The complication is that there are more segments of the analysis than there are cores so I want to run at mo... | I do think that ***multiprocessing*** module will help you achieve what you need.
Take look at the example technique.
```
import multiprocessing
def do_calculation(data):
"""
@note: you can define your calculation code
"""
return data * 2
def start_process():
print 'Starting', multiprocessing.cur... |
Python regex with question mark literal | 12,766,953 | 11 | 2012-10-07T07:31:39Z | 12,766,981 | 11 | 2012-10-07T07:36:00Z | [
"python",
"regex",
"django"
] | I'm using Django's URLconf, the URL I will receive is `/?code=authenticationcode`
I want to match the URL using `r'^\?code=(?P<code>.*)$'` , but it doesn't work.
Then I found out it is the problem of '?'.
Becuase I tried to match `/aaa?aaa` using `r'aaa\?aaa'` `r'aaa\\?aaa'` even `r'aaa.*aaa'` , all failed, but ... | ```
>>> s="aaa?aaa"
>>> import re
>>> re.findall(r'aaa\?aaa', s)
['aaa?aaa']
```
The reason `/aaa?aaa` won't match inside your URL is because a `?` begins a new GET query.
So, the matchable part of the URL is only up to the first 'aaa'. The remaining '?aaa' is a new *query string* separated by the '?' mark, containin... |
Python Packaging | 12,767,023 | 7 | 2012-10-07T07:42:13Z | 12,767,051 | 21 | 2012-10-07T07:47:44Z | [
"python",
"package"
] | Trying to create a python package. Seems to work, but i get a warning.
my setup.py is:
```
#! /usr/bin/env python
from distutils.core import setup
setup(
name='myPKG',
version='0.02.01',
url='http://someURL.02.01',
packages=['scripts',
'statistics'],
author = 'Research-Team',
... | You're using distutils, but you need at least [setuptools](http://pypi.python.org/pypi/setuptools) in order to use those options.
```
from setuptools import setup
``` |
Sort dict in jinja2 loop | 12,767,550 | 9 | 2012-10-07T09:16:15Z | 12,768,183 | 8 | 2012-10-07T10:56:23Z | [
"python",
"flask",
"jinja2",
"jinja"
] | I'm still learning jinja2 and flask and I'm having a difficulty using dictsort in jinja2.
So I'm passing this dict into a jinja2 template:
```
{'PEDD United': {'id': 37828, 'rank': 12, 'totalpts': 307},'Fc Mbonabushia': {'id': 205633, 'rank': 6, 'totalpts': 356},'FC Slurp': {'id': 933573, 'rank': 11, 'totalpts': 312}... | The way you're doing this will not work, because as soon as you use `{% for team in league %}`, you're already using the unsorted dict and extracting the key,value pair from it.
I think `|dictsort` may not be able to help you in this case because you cannot sort by either key or value, but by the value's (sub-dict's) ... |
lambda can't have 2+ return values? | 12,767,579 | 2 | 2012-10-07T09:21:24Z | 12,767,599 | 12 | 2012-10-07T09:24:53Z | [
"python",
"lambda"
] | ```
>>> def itself_and_plusone(x):
... return x, x+1
...
>>> itself_and_plusone(1)
(1, 2)
>>> (lambda x: x,x+1)(10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
```
why? and workaround with lambda? not by
```
>>> (lambda x: (x,x+1))(10)
(10, 11)
```... | Without the parentheses it is interpreted as follows:
```
((lambda x: x),x+1)(10)
```
This fails because the second `x` is outside the lambda expression. And even if `x` were defined, it would still fail because you can't use a tuple as if it were a function.
This simple variation shows what is going on:
```
>>> x=... |
Python: an efficient way to slice a list with a index list | 12,768,504 | 4 | 2012-10-07T11:42:43Z | 12,768,534 | 12 | 2012-10-07T11:45:18Z | [
"python",
"performance",
"list",
"indexing",
"slice"
] | I wish to know an efficient way and code saving to slice a list of thousand of elements
example:
```
b = ["a","b","c","d","e","f","g","h"]
index = [1,3,6,7]
```
I wish a result like as:
```
c = ["b","d","g","h"]
``` | The most direct way to do this with lists is to use a list comprehension:
```
c = [b[i] for i in index]
```
But, depending on exactly what your data looks like and what else you need to do with it, you could use numpy arrays - in which case:
```
c = b[index]
```
would do what you want, and would avoid the potential... |
How can I estimate the compressibility of a file without compressing it? | 12,769,933 | 8 | 2012-10-07T15:04:21Z | 12,770,967 | 8 | 2012-10-07T17:11:10Z | [
"python",
"compression",
"twisted"
] | I'm using an event loop based server in twisted python that stores files, and I'd like to be able to classify the files according to their compressibility.
If the probability that they'd benefit from compression is high, they would go to a directory with btrfs compression switched on, otherwise they'd go elsewhere.
I... | Just 1K from the *middle* of the file will do the trick. You don't want the beginning or the end, since they may contain header or trailer information that is not representative of the rest of the file. 1K is enough to get some amount of compression with any typical algorithm. That will predict a relative amount of com... |
Will users be able to open my program without downloading Python? | 12,769,987 | 4 | 2012-10-07T15:11:15Z | 12,770,064 | 10 | 2012-10-07T15:20:09Z | [
"python",
"compilation",
"cross-platform",
"cross-compiling"
] | I'm making a program in python, but once I'm finished with the program, will the users have to download the python environment in order to use my program, or will it work without the python environment once compiled? Also, will it automatically be cross-platform or will I have to download a conversion program to make i... | Many Linux systems come with Python installed already. However, there are some tools to help if it is not:
* [pyinstaller](http://www.pyinstaller.org/) for Windows, Linux, and Mac OS X (does not work for Python 3)
* [bbfreeze](http://pypi.python.org/pypi/bbfreeze/) for Windows and Linux
* [py2exe](http://www.py2exe.or... |
Flask request.remote_addr is wrong on webfaction and not showing real user IP | 12,770,950 | 10 | 2012-10-07T17:09:15Z | 12,771,438 | 20 | 2012-10-07T18:12:32Z | [
"python",
"flask",
"webfaction"
] | I just deployed a Flask app on Webfaction and I've noticed that `request.remote_addr` is always `127.0.0.1`. which is of course isn't of much use.
How can I get the real IP address of the user in Flask on Webfaction?
Thanks! | If there is a proxy in front of Flask, then something like this will get the real IP in Flask:
```
if request.headers.getlist("X-Forwarded-For"):
ip = request.headers.getlist("X-Forwarded-For")[0]
else:
ip = request.remote_addr
```
**Update:** Very good point mentioned by Eli in his comment. There could be some... |
how to format date in ISO using python? | 12,772,057 | 5 | 2012-10-07T19:23:39Z | 12,772,093 | 14 | 2012-10-07T19:27:24Z | [
"python",
"date",
"iso"
] | I have some dates which format is d/m/yyyy, for example : 2/28/1987
I would like to have it in the ISO format : 1987-02-28
I think we can do it that way, but it seems a little heavy:
```
str_date = '2/28/1987'
arr_str = re.split('/', str_date)
iso_date = arr_str[2]+'-'+arr_str[0][:2]+'-'+arr_str[1]
```
Is there an... | You could use the [`datetime` module](http://docs.python.org/library/datetime.html):
```
datetime.datetime.strptime(str_date, '%m/%d/%Y').date().isoformat()
```
or, as running code:
```
>>> import datetime
>>> str_date = '2/28/1987'
>>> datetime.datetime.strptime(str_date, '%m/%d/%Y').date().isoformat()
'1987-02-28'... |
gunicorn autoreload on source change | 12,773,763 | 44 | 2012-10-07T23:36:01Z | 17,079,278 | 14 | 2013-06-13T04:30:54Z | [
"python",
"django",
"reload",
"gunicorn"
] | Finally I migrated my development env from runserver to gunicorn/nginx.
It'd be convenient to replicate the autoreload feature of runserver to gunicorn, so the server automatically restarts when source changes. Otherwise I have to restart the server manually with `kill -HUP`.
Any way to avoid the manual restart? | One option would be to use the [--max-requests](http://docs.gunicorn.org/en/latest/configure.html#max-requests) to limit each spawned process to serving only one request by adding `--max-requests 1` to the startup options. Every newly spawned process should see your code changes and in a development environment the ext... |
gunicorn autoreload on source change | 12,773,763 | 44 | 2012-10-07T23:36:01Z | 19,502,993 | 10 | 2013-10-21T19:24:55Z | [
"python",
"django",
"reload",
"gunicorn"
] | Finally I migrated my development env from runserver to gunicorn/nginx.
It'd be convenient to replicate the autoreload feature of runserver to gunicorn, so the server automatically restarts when source changes. Otherwise I have to restart the server manually with `kill -HUP`.
Any way to avoid the manual restart? | [Bryan Helmig](http://bryanhelmig.com/auto-reload-gunicorn-on-file-change-event/) came up with this and I modified it to use `run_gunicorn` instead of launching `gunicorn` directly, to make it possible to just cut and paste these 3 commands into a shell in your django project root folder (with your virtualenv activated... |
gunicorn autoreload on source change | 12,773,763 | 44 | 2012-10-07T23:36:01Z | 24,893,069 | 89 | 2014-07-22T16:40:00Z | [
"python",
"django",
"reload",
"gunicorn"
] | Finally I migrated my development env from runserver to gunicorn/nginx.
It'd be convenient to replicate the autoreload feature of runserver to gunicorn, so the server automatically restarts when source changes. Otherwise I have to restart the server manually with `kill -HUP`.
Any way to avoid the manual restart? | While this is old question, just for consistency - since version 19.0 gunicorn has [`--reload`](http://docs.gunicorn.org/en/19.0/settings.html#reload) option.
So no third party tools needed more. |
"read more" in django posts | 12,775,565 | 3 | 2012-10-08T04:59:54Z | 12,775,861 | 8 | 2012-10-08T05:38:01Z | [
"python",
"html",
"django",
"django-templates"
] | I am creating a blog on django/webfaction. Currently my home page displays all the contents from all the posts. I would like to tweak it to show only few lines from each post and each post ending with a "read more" link. How to achieve this? I am new to django and python. Kindly help me.
Code in home.html:
> ```
> {%... | You can use built-in template filter truncate [doc](https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#truncatewords)
```
<div class = "post_body">
{{ post.body|safe|truncatewords:"50"|linebreaks }}
<a href="{{ url_for_full_content }}">read more</a>
</div>
``` |
Unit testing a function that returns a generator object | 12,775,794 | 7 | 2012-10-08T05:29:44Z | 12,775,843 | 11 | 2012-10-08T05:34:35Z | [
"python"
] | The title pretty much sums it up: I tried to use assertEqual to test a function that returns a generator object, but that results in:
> AssertionError: generator object genexpr> at 0x2e70c80> != (1,2,...)
Is there a clever way to do this other than iterating over the function and running assertEqual for each individu... | ```
assertEqual(tuple(generator_object), (1, 2, ...))
```
if it's an infinite generator, or you just wish to look at the first `n` results for some reason, you can combint this with `itertools.islice`
```
assertEqual(tuple(islice(generator_object, n)), (1, 2, ...))
``` |
Django - How does order_by work? | 12,775,844 | 2 | 2012-10-08T05:34:48Z | 12,775,949 | 7 | 2012-10-08T05:45:54Z | [
"python",
"django",
"postgresql",
"order"
] | I'd like to know how Django's `order_by` works if the given `order_by` field's values are same for a set of records. Consider I have a `score` field in DB and I'm filtering the queryset using `order_by('score')`. How will records having the same values for score arrange themselves?
Every time, they're ordered randomly... | `order_by` can have multiple params, I think `order_by('score', '-create_time')` will always return the same queryset. |
Pyramid security based on attribute of record | 12,776,532 | 3 | 2012-10-08T06:41:17Z | 12,776,995 | 7 | 2012-10-08T07:18:02Z | [
"python",
"pyramid"
] | I have tables in DB with the same interface for view and edit them with Pyramid app. For example:
Example of route for view record of `report` table: `/birdreport/report/871`;
Example of route for edit record of `report` table: `/birdreport/report/871/edit`;
Each record of `report` table has field which contains `us... | You can use the [Pyramid authorization policy](http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/security.html) by defining `__acl__()` inside your `Report` model. For example:
```
from sqlalchemy.orm import relationship, backref
from pyramid.security import Everyone, Allow
class Report(Base):
# ...
... |
How can I zip file with a flattened directory structure when zipping file using Zipfile in Python? | 12,777,222 | 10 | 2012-10-08T07:36:03Z | 12,777,267 | 13 | 2012-10-08T07:38:56Z | [
"python",
"python-2.7"
] | I'm using the `ZipFile` package to zip file in Python. Here's my code:
```
archive = zipfile.ZipFile(join(settings.ARCHIVES_DIR, 'test.zip'), "a")
for pdffile in glob.glob(join(settings.IBILLING_DIR, '*.pdf')):
archive.write(pdffile)
archive.close()
```
The issue I'm facing is that the ZIP file that is created,... | First add
```
import os
```
then modify the `archive.write` line to be:
```
archive.write(pdffile, os.path.basename(pdffile))
```
This specifies that each pdf should be written into the zip file with a path equivalent to only the filename portion of the path from which you are reading it (by specifying the [arcname... |
Python : How and why is this syntax working ? {1,2,3,4} | 12,779,053 | 4 | 2012-10-08T09:40:25Z | 12,779,071 | 11 | 2012-10-08T09:41:41Z | [
"python",
"list",
"syntax",
"dictionary",
"set"
] | As we know,
```
{} # Represents a dict
```
And
```
{'one': 1} # Again a dict
```
How and why is this a set :
```
{'one', 'two', 'three', 'four'} # I thought it should give syntax error
```
But it gives :
```
set(['one', 'two', 'three', 'four']) # Strange ?? [ Should this happen ? ]
```
Can you provide a link to... | [Set literals](http://docs.python.org/dev/whatsnew/2.7.html#other-language-changes) are a 3.x feature that has been backported into 2.7.
This is a useful feature - note that set comprehensions are also allowed. |
How to deploy a Scrapy spider on Heroku cloud | 12,779,184 | 7 | 2012-10-08T09:48:06Z | 12,964,418 | 9 | 2012-10-18T21:58:44Z | [
"python",
"python-2.7",
"heroku",
"scrapy"
] | I developed few spiders in scrapy & I want to test those on Heroku cloud. Does anybody have any idea about how to deploy a Scrapy spider on Heroku cloud? | Yes, it's fairly simple to deploy and run your Scrapy spider on Heroku.
Here are the steps using a real Scrapy project as example:
1. Clone the project (note that it must have a `requirements.txt` file for Heroku to recognize it as a Python project):
`git clone https://github.com/scrapinghub/testspiders.git`
2. A... |
Cannot install PyPdf 2 module | 12,780,668 | 10 | 2012-10-08T11:19:28Z | 12,782,958 | 20 | 2012-10-08T13:40:03Z | [
"python",
"module",
"importerror",
"pypdf"
] | Trying to install [PyPdf2](https://github.com/knowah/PyPDF2) module, I downloaded the zip and unzipped it, I executed `python setup.py build` and `python setup.py install`, but it seems that it has not been installed , when I try to import it from a python script, it returns an `ImportError`:
```
import pyPdf
Tracebac... | It appears the README file for [PyPDF2](https://github.com/knowah/PyPDF2) is incorrect. It suggests that
```
import pyPdf
```
should work, but it doesn't. This new module is imported as
```
import PyPDF2
```
(as suggested by the document structure on github, and after verifying myself).
For convenience, when e.g. ... |
__contains__ syntax | 12,780,949 | 3 | 2012-10-08T11:37:28Z | 12,780,987 | 10 | 2012-10-08T11:39:43Z | [
"python"
] | Ive written a python program that used multiple instances of the **contains** syntax to look inside dictionaries and lists.
```
if not test_map[var].__contains__(string):
```
It seems that I would of been better to use :
```
if string not in test_map[var]:
```
Does anyone know the issues that can occur is using the... | It's very very ugly.
Using the implementation directly instead of using the actual intended top-level syntax can also hurt you if the semantics are changed in the future. Plus, it makes the code much harder to comprehend and explain.
It's quite possible to be a competent Python programmer without knowing that `in` us... |
PDB.run - restarting a pdb session | 12,783,321 | 5 | 2012-10-08T14:02:29Z | 12,978,164 | 7 | 2012-10-19T16:04:22Z | [
"python",
"pdb"
] | I'm relatively new to python and pdb, but I have a lot of experience with gdb.
My problem is that if I set a number of breakpoints in my code at some point I will want to change something and re-run my debug session retaining these break points. However entering "run" in my pdb session cases my session to terminate wi... | So if anyone cares the problem was that "run" in pdb is not the exact same as "run" in gdb. In gdb if I enter run the program restarts and continues to the first break point. In pdb the program restarts and goes to the start of the file. I then have to press 'n' followed by 'c' to get to the first break point. If, atte... |
If any item of list starts with string? | 12,783,705 | 5 | 2012-10-08T14:23:08Z | 12,783,729 | 16 | 2012-10-08T14:24:28Z | [
"python",
"list",
"startswith"
] | I'm trying to check is any item of a list starts with a certain string. How could I do this with a for loop? IE:
```
anyStartsWith = False
for item in myList:
if item.startsWith('qwerty'):
anyStartsWith = True
``` | Use [`any()`](http://docs.python.org/library/functions.html#any):
```
any(item.startswith('qwerty') for item in myList)
``` |
unpacking function argument | 12,786,102 | 10 | 2012-10-08T16:58:13Z | 12,786,141 | 11 | 2012-10-08T17:00:15Z | [
"python",
"function"
] | if a function takes n number of arguments, and there is another function that returns a sequence with n number of items(or I have a sequence with n number of items), is there a way to 'map' these two functions(or make the first function take a sequence of n number of items as input and return result) I don't want (and ... | You are looking for the `*args` argument syntax:
```
>>> def foo(bar, baz, spam):
... print bar, baz, spam
...
>>> arguments = [1, 2, 3]
>>> foo(*arguments)
1, 2, 3
```
When passing arguments to a callable, any expression preceded by a `*` asterix, is interpreted as a sequence of positional arguments, and expande... |
unpacking function argument | 12,786,102 | 10 | 2012-10-08T16:58:13Z | 12,786,152 | 9 | 2012-10-08T17:00:56Z | [
"python",
"function"
] | if a function takes n number of arguments, and there is another function that returns a sequence with n number of items(or I have a sequence with n number of items), is there a way to 'map' these two functions(or make the first function take a sequence of n number of items as input and return result) I don't want (and ... | It's called argument unpacking and is written as:
```
func1(*func2(...))
```
Refer: <https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists> |
Paste a string as a variable, not as executable code snippet, into IPython | 12,787,045 | 15 | 2012-10-08T18:00:44Z | 12,794,700 | 24 | 2012-10-09T07:14:51Z | [
"python",
"copy-paste",
"ipython",
"magic-methods"
] | I'm aware of the magic IPython `%paste` command, which is quite useful, if you have valid code to insert. Now I don't want to insert code, I just want to store some string from the copy buffer as a variable. Is there a simpler way to do that, except copying the string to some separate text editor and modifying it first... | ```
%paste strvar
```
gives you a list of the lines from the copied text. You can do
```
strvar = '\n'.join(strvar)
```
to get the text in a single string. |
Sqlalchemy: secondary relationship update | 12,787,452 | 8 | 2012-10-08T18:33:01Z | 20,834,991 | 8 | 2013-12-30T07:11:39Z | [
"python",
"postgresql",
"orm",
"sqlalchemy",
"relationship"
] | I have two tables, say A and B. Both have a primary key id. They have a many-to-many relationship, SEC.
```
SEC = Table('sec', Base.metadata,
Column('a_id', Integer, ForeignKey('A.id'), primary_key=True, nullable=False),
Column('b_id', Integer, ForeignKey('B.id'), primary_key=True, nullable=False)
)
class A()... | The problem is you want to make sure the instances you create are unique. We can create an alternate constructor that checks a cache of existing uncommited instances or queries the database for existing commited instance before returning a new instance.
Here is a demonstration of such a method:
```
from sqlalchemy im... |
matlab's "permute" in python | 12,787,475 | 15 | 2012-10-08T18:34:38Z | 12,787,676 | 16 | 2012-10-08T18:50:36Z | [
"python",
"matlab"
] | I'm translating a program from matlab to Python.
The matlab code uses the method permute:
```
B = PERMUTE(A,ORDER) rearranges the dimensions of A so that they
% are in the order specified by the vector ORDER. The array produced
% has the same values as A but the order of the subscripts needed to
% access any ... | This is rolled into the [`transpose`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html) function in `numpy.ndarray`. The default behavior reverses the order, but you can supply a list of your own order. |
Finding the Index of N biggest elements in Python Array / List Efficiently | 12,787,650 | 14 | 2012-10-08T18:48:33Z | 12,787,706 | 10 | 2012-10-08T18:52:38Z | [
"python",
"performance",
"numpy"
] | I'm sorry in advance if this is a duplicated question, I looked for this information but still couldn't find it.
Is it possible to arrange a numpy array (or python list) by using the indexes of the N biggest elements in decreasing order very efficiently?
For instance, the array:
```
a = array([4, 1, 0, 8, 5, 2])
```... | ```
L = [4, 1, 0, 8, 5, 2]
sorted(range(len(L)), key=lambda i:L[i])
``` |
Finding the Index of N biggest elements in Python Array / List Efficiently | 12,787,650 | 14 | 2012-10-08T18:48:33Z | 12,787,780 | 15 | 2012-10-08T18:58:31Z | [
"python",
"performance",
"numpy"
] | I'm sorry in advance if this is a duplicated question, I looked for this information but still couldn't find it.
Is it possible to arrange a numpy array (or python list) by using the indexes of the N biggest elements in decreasing order very efficiently?
For instance, the array:
```
a = array([4, 1, 0, 8, 5, 2])
```... | Have you looked at the built-in numpy `argsort` method?:
<http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html>
I can sort an array with 300,000 random floats in about 29 ms on my machine using that method.
```
def f(a,N):
return np.argsort(a)[::-1][:N]
``` |
Extract single value from JSON response Python | 12,788,217 | 6 | 2012-10-08T19:30:29Z | 12,788,284 | 9 | 2012-10-08T19:35:45Z | [
"python",
"json"
] | First off, I will freely concede to being little more than a clumsy liberal arts guy who is completely self taught in this scripting thing. That said, I am attempting to get values from a the USGS Water Data Service using the code below:
```
def main(gaugeId):
# import modules
import urllib2, json
# crea... | using `json.loads` will turn your data into a python [dictionary](http://docs.python.org/tutorial/datastructures.html#dictionaries).
Dictionaries values are accessed using `['key']`
```
resp_str = {
"name" : "ns1:timeSeriesResponseType",
"declaredType" : "org.cuahsi.waterml.TimeSeriesResponseType",
"scope" : "j... |
Why can't I register multiple Django ModelAdmin with same Model? | 12,790,220 | 6 | 2012-10-08T22:14:20Z | 12,790,232 | 15 | 2012-10-08T22:15:29Z | [
"python",
"django",
"django-models",
"django-admin"
] | I have the following ModelAdmin:
```
class EventAdmin(admin.ModelAdmin):
# ModelAdmin config
def queryset(self, request):
queryset = super(EventAdmin, self).queryset(request)
return queryset.exclude(date_end__lt=date.today())
admin.site.register(Event, EventAdmin)
```
Now I want to add a mod... | Use proxy models:
```
class Event(db.Model):
...
class ActiveEventManager(models.Manager):
def get_queryset(self):
return super(ActiveEventManager, self).get_queryset().filter(active=True)
class ActiveEvent(Event):
class Meta:
proxy = True
objects = ActiveEventManager()
class Archi... |
How to silence "sys.excepthook is missing" error? | 12,790,328 | 31 | 2012-10-08T22:25:26Z | 12,807,285 | 52 | 2012-10-09T19:42:15Z | [
"python",
"exception",
"io"
] | NB: I have not attempted to reproduce the problem described below under Windows, or with versions of Python other than 2.7.3.
The most reliable way to elicit the problem in question is to pipe the output of the following test script through `:` (under `bash`):
```
try:
for n in range(20):
print n
except:
... | > How can I modify the test script above to avoid the error message when the script is run as shown (under Unix/`bash`)?
You will need to prevent the script from writing anything to standard output. That means removing any `print` statements and any use of `sys.stdout.write`, as well as any code that calls those.
The... |
Running a Python Script Inside Another Directory | 12,790,986 | 4 | 2012-10-08T23:45:02Z | 12,791,056 | 9 | 2012-10-08T23:54:08Z | [
"python"
] | I have the following Python script inside a directory called 'test' on my Linux desktop:
```
#!/usr/bin/python
f = open('test.txt','w')
f.write('testing the script')
```
So it's `/Home/Desktop/test/script.py`
If I go inside the directory and type `./script.py` it works fine and creates the test.txt file.
However f... | You can use `os.path.dirname()` and `__file__` to get absolute paths like this:
```
#!/usr/bin/python
import os # We need this module
# Get path of the current dir, then use it to create paths:
CURRENT_DIR = os.path.dirname(__file__)
file_path = os.path.join(CURRENT_DIR, 'test.txt')
# Then work using the absolute ... |
After creating python exe file with cx_freeze the file doesn't do anything | 12,791,666 | 4 | 2012-10-09T01:27:15Z | 16,135,089 | 10 | 2013-04-21T19:07:17Z | [
"python",
"exe",
"cx-freeze"
] | I recently created used cx\_freeze to create a python 3.2.2 exe file. When I tried to run the exe file nothing happened.
Here is the code for my test.py file:
```
print("hello world")
for i in range(5):
print(i)
```
Here is the code for my testSetup.py file:
```
from cx_Freeze import setup, Executable
exe = E... | My suggestion:
1. set `base = None` (try it: maybe that's all you want? `base = Win32GUI` does "hide" the console - this is useful when you're building a GUI)
2. In the same folder with your .exe make a batch-file (a text-file with .bat) calling your .exe:
this goes into your batch-file:
```
name-of-your-app.exe %1
... |
How do you do a simple "chmod +x" from within python? | 12,791,997 | 53 | 2012-10-09T02:18:47Z | 12,792,002 | 91 | 2012-10-09T02:19:58Z | [
"python",
"chmod"
] | I want to create a file from within a python script that is executable.
```
import os
import stat
os.chmod('somefile', stat.S_IEXEC)
```
it appears `os.chmod` doesn't 'add' permissions the way unix `chmod` does. With the last line commented out, the file has the filemode `-rw-r--r--`, with it not commented out, the f... | Use `os.stat()` to get the current permissions, use `|` to or the bits together, and use `os.chmod()` to set the updated permissions.
Example:
```
import os
import stat
st = os.stat('somefile')
os.chmod('somefile', st.st_mode | stat.S_IEXEC)
``` |
ElementTree iterparse strategy | 12,792,998 | 11 | 2012-10-09T04:51:47Z | 12,793,991 | 15 | 2012-10-09T06:24:35Z | [
"python",
"xml",
"sax",
"elementtree",
"iterparse"
] | I have to handle xml documents that are big enough (up to 1GB) and parse them with python. I am using the [iterparse()](http://effbot.org/zone/element-iterparse.htm) function (SAX style parsing).
My concern is the following, imagine you have an xml like this
```
<?xml version="1.0" encoding="UTF-8" ?>
<families>
<f... | Here's one possible approach: we maintain a path list and peek backwards to find the parent node(s).
```
path = []
for event, elem in ET.iterparse(file_path, events=("start", "end")):
if event == 'start':
path.append(elem.tag)
elif event == 'end':
# process the tag
if elem.tag == 'name'... |
ElementTree iterparse strategy | 12,792,998 | 11 | 2012-10-09T04:51:47Z | 12,794,855 | 10 | 2012-10-09T07:24:14Z | [
"python",
"xml",
"sax",
"elementtree",
"iterparse"
] | I have to handle xml documents that are big enough (up to 1GB) and parse them with python. I am using the [iterparse()](http://effbot.org/zone/element-iterparse.htm) function (SAX style parsing).
My concern is the following, imagine you have an xml like this
```
<?xml version="1.0" encoding="UTF-8" ?>
<families>
<f... | [pulldom](http://docs.python.org/py3k/library/xml.dom.pulldom.html) is excellent for this. You get a sax stream. You can iterate through the stream, and when you find a node that your are interested in, load that node in to a dom fragment.
```
import xml.dom.pulldom as pulldom
import xpath # from http://code.google.co... |
Python Selenium Webdriver to check if element does NOT exist takes time | 12,793,390 | 3 | 2012-10-09T05:33:37Z | 12,795,623 | 7 | 2012-10-09T08:11:11Z | [
"python",
"selenium",
"selenium-webdriver",
"xpath"
] | Trying to verify after few GUI operations some button does not exist (expected not to be present). I am using find\_element\_by\_xpath() but its very slow. Any solution of timeout? | Actually WebDriver's find\_element method will wait for implicit time for the element if the specified element is not found.
There is no predefined method in WebDriver like isElementPresent() to check. You should write your own logic for that.
**Logic**
```
public boolean isElementPresent()
{
try
{
set_t... |
Sending a binary file in Tornado | 12,793,697 | 7 | 2012-10-09T06:02:42Z | 12,793,810 | 9 | 2012-10-09T06:11:23Z | [
"python",
"python-3.x",
"tornado"
] | In a certain `GET` request, I need to read a file locally, depending on parameters in the request, and send it on request's input stream. How do I do it?
```
class GetArchives(tornado.web.RequestHandler):
def get(self, param1, param2):
path = calculate_path(param1, param2)
try:
f = open... | Try this(not for big file):
```
try:
with open(path, 'rb') as f:
data = f.read()
self.write(data)
self.finish()
```
There is `StaticFileHandler` in tornado, see [tornado doc](https://github.com/facebook/tornado/blob/master/tornado/web.py#L1630) |
Sending a binary file in Tornado | 12,793,697 | 7 | 2012-10-09T06:02:42Z | 12,794,419 | 8 | 2012-10-09T06:56:10Z | [
"python",
"python-3.x",
"tornado"
] | In a certain `GET` request, I need to read a file locally, depending on parameters in the request, and send it on request's input stream. How do I do it?
```
class GetArchives(tornado.web.RequestHandler):
def get(self, param1, param2):
path = calculate_path(param1, param2)
try:
f = open... | Here's a solution that works for arbitrary-sized files:
```
with open(path, 'rb') as f:
while 1:
data = f.read(16384) # or some other nice-sized chunk
if not data: break
self.write(data)
self.finish()
``` |
Build list of links using Jinja2 | 12,794,148 | 3 | 2012-10-09T06:37:12Z | 13,094,287 | 8 | 2012-10-26T20:55:00Z | [
"python",
"jinja2"
] | I have passed a list of strings to my Jinja2 template. I want to use Jinja2 to `join` the list but I want to also convert each list item to a `href`. Is it possible or do I need to somehow pass the links to the template?
```
# I use this to join the list items.
{{ my_list|join(', ') }}
# I use this to make links ind... | Use the [`loop` special variable of `for` loops](http://jinja.pocoo.org/docs/templates/#for):
```
{% for i in my_list %}
<a href="/edit/{{ i }}">i</a>{% if not loop.last %}, {% endif %}
{% endfor %}
```
You could also wrap this in a macro:
```
{% macro listlinks(mylist, urltemplate="/edit/%s", connective=", ") -... |
Get joined string from list of lists of strings in Python | 12,794,833 | 11 | 2012-10-09T07:23:03Z | 12,794,948 | 16 | 2012-10-09T07:29:55Z | [
"python"
] | I have a list of lists and a separator string like this:
```
lists = [
['a', 'b'],
[1, 2],
['i', 'ii'],
]
separator = '-'
```
As result I want to have a list of strings combined with separator string from the strings in the sub lists:
```
result = [
'a-1-i',
'a-1-ii',
'a-2-i',
'a-2-ii'... | ```
from itertools import product
result = [separator.join(map(str,x)) for x in product(*lists)]
```
`itertools.product` returns an iterator that produces the cartesian product of the provided iterables. We need to `map` `str` over the resultant tuples, since some of the values are ints. Finally, we can join the strin... |
Python: get last Monday of July 2010 | 12,796,389 | 4 | 2012-10-09T09:01:23Z | 12,796,484 | 8 | 2012-10-09T09:06:54Z | [
"python",
"calendar"
] | How do I get the last Monday (or other day) of a given month? | Have a look at [**dateutil**](http://labix.org/python-dateutil):
```
from datetime import datetime
from dateutil import relativedelta
datetime(2010,7,1) + relativedelta.relativedelta(day=31, weekday=relativedelta.MO(-1))
```
returns
```
datetime.datetime(2010, 7, 26, 0, 0)
``` |
Python: get last Monday of July 2010 | 12,796,389 | 4 | 2012-10-09T09:01:23Z | 12,796,542 | 7 | 2012-10-09T09:10:47Z | [
"python",
"calendar"
] | How do I get the last Monday (or other day) of a given month? | Using the [calendar](http://docs.python.org/library/calendar.html) module from the stdlib:
```
import calendar
cal = calendar.Calendar(0)
month = cal.monthdatescalendar(2010, 7)
lastweek = month[-1]
monday = lastweek[0]
print(monday)
2010-07-26
``` |
python's scipy.stats.ranksums vs. R's wilcox.test | 12,797,658 | 11 | 2012-10-09T10:07:45Z | 12,799,337 | 17 | 2012-10-09T11:45:05Z | [
"python",
"scipy"
] | Both python's scipy.stats.ranksums and R's wilcox.test are supposed to calculate two-sided p-values for a Wilcoxon rank sum test. But when I run both functions on the same data, I get p-values that differ by orders of magnitude:
R:
```
> x=c(57.07168,46.95301,31.86423,38.27486,77.89309,76.78879,33.29809,58.61569,18.2... | It depends on the choice of options (exact vs a normal approximation, with or without continuity correction):
R's default:
> By default (if âexactâ is not specified), an exact p-value is computed
> if the samples contain less than 50 finite values and there are no
> ties. Otherwise, a normal approximation is used... |
Python and reference passing. Limitation? | 12,797,749 | 4 | 2012-10-09T10:13:35Z | 12,797,915 | 12 | 2012-10-09T10:21:57Z | [
"python",
"pass-by-reference"
] | I would like to do something like the following:
```
class Foo(object):
def __init__(self):
self.member = 10
pass
def factory(foo):
foo = Foo()
aTestFoo = None
factory(aTestFoo)
print aTestFoo.member
```
However it crashes with `AttributeError: 'NoneType' object has no attribute 'member'`:
... | Python does not have pass by reference. One of the few things it shares with Java, by the way. Some people describe argument passing in Python as call by value (and define the values as references, where reference means not what it means in C++), some people describe it as pass by reference with reasoning I find quite ... |
Python and reference passing. Limitation? | 12,797,749 | 4 | 2012-10-09T10:13:35Z | 12,797,976 | 9 | 2012-10-09T10:25:42Z | [
"python",
"pass-by-reference"
] | I would like to do something like the following:
```
class Foo(object):
def __init__(self):
self.member = 10
pass
def factory(foo):
foo = Foo()
aTestFoo = None
factory(aTestFoo)
print aTestFoo.member
```
However it crashes with `AttributeError: 'NoneType' object has no attribute 'member'`:
... | You are making a mistake here because in Python
> ```
> "We call the argument passing technique _call by sharing_,
> because the argument objects are shared between the
> caller and the called routine. This technique does not
> correspond to most traditional argument passing techniques
> (it is similar to argument pa... |
File upload with Tornado | 12,797,772 | 7 | 2012-10-09T10:14:41Z | 12,798,126 | 10 | 2012-10-09T10:33:19Z | [
"python",
"python-3.x",
"tornado"
] | How do I access the uploaded file in Tornado, when using a `put` request?
```
@require_basic_auth
class UploadFile(tornado.web.RequestHandler):
def put(self, params):
path = calculate_path(params)
# TODO: create an empty binary file at path and then copy
# the request input stream to it.
`... | `self.request.files` should be fine. Here is an [example](http://technobeans.wordpress.com/2012/09/17/tornado-file-uploads/). |
File upload with Tornado | 12,797,772 | 7 | 2012-10-09T10:14:41Z | 12,798,413 | 7 | 2012-10-09T10:48:08Z | [
"python",
"python-3.x",
"tornado"
] | How do I access the uploaded file in Tornado, when using a `put` request?
```
@require_basic_auth
class UploadFile(tornado.web.RequestHandler):
def put(self, params):
path = calculate_path(params)
# TODO: create an empty binary file at path and then copy
# the request input stream to it.
`... | ```
@require_basic_auth
class UploadFile(tornado.web.RequestHandler):
def put(self, params):
path = calculate_path(params)
with open(path, 'wb') as out:
body = self.request.get_argument('data')
out.write(bytes(body, 'utf8'))
```
...was what I needed.
Found on some ActiveSta... |
Getting 405 Method Not Allowed while using POST method in bottle | 12,798,095 | 4 | 2012-10-09T10:31:43Z | 12,799,247 | 8 | 2012-10-09T11:39:52Z | [
"python",
"bottle"
] | I am developing one simple code for force download now problem is that i'm not getting any error in GET method but getting error "405 Method Not Allowed" in post method request. My code for GET method.
```
@route('/down/<filename:path>',method=['GET', 'POST'])
def home(filename):
key = request.get.GET('key... | Router takes only one method in `method` parameter, not list of methods. Use several `@route` decorators instead:
```
@route('/down/<filename:path>', method='GET')
@route('/down/<filename:path>', method='POST')
def home(filename):
pass
```
Check documentation for more information: <http://bottlepy.org/docs/dev/ro... |
Returning the highest 6 names in a List of tuple in Python | 12,801,444 | 7 | 2012-10-09T13:41:58Z | 12,801,523 | 11 | 2012-10-09T13:45:25Z | [
"python",
"list",
"tuples"
] | Please I want to return first 6 names (only the names) with the highest corresponding integers from the list of tuple below.
I have been able to return all the names from highest (sms) to lowest (boss).
```
[('sms', 10), ('bush', 9), ('michaels', 7), ('operations', 6), ('research', 5), ('code', 4), ('short', 3), ('uka... | `heapq.nlargest` is what you want here:
```
import heapq
from operator import itemgetter
largest_names = [x[0] for x in heapq.nlargest(6,your_list,key=itemgetter(1))]
```
It will be more efficient than sorting as it only takes the biggest elements and discards the rest. Of course, it is less efficient than slicing if... |
Difference between setattr and object manipulation in python/django | 12,801,586 | 20 | 2012-10-09T13:48:19Z | 12,801,623 | 9 | 2012-10-09T13:50:38Z | [
"python",
"django",
"django-models",
"setattribute",
"setattr"
] | I have the following model:
```
class Ticket(models.Model):
title = models.CharField()
merged_to = models.ForeignKey("self", related_name='merger_ticket', null=True, blank=True)
looser_ticket = models.BooleanField(default=False)
```
There are couple of ways of manipulating the model:
**First**
```
ticke... | If you know the objects properties before hand you should probably be using the first method. Just assign property values directly.
The second can be useful when you need to dynamically assign a value to a property. Perhaps a user has the ability to change the values of a number of different attributes and you don't k... |
Difference between setattr and object manipulation in python/django | 12,801,586 | 20 | 2012-10-09T13:48:19Z | 12,801,950 | 26 | 2012-10-09T14:09:09Z | [
"python",
"django",
"django-models",
"setattribute",
"setattr"
] | I have the following model:
```
class Ticket(models.Model):
title = models.CharField()
merged_to = models.ForeignKey("self", related_name='merger_ticket', null=True, blank=True)
looser_ticket = models.BooleanField(default=False)
```
There are couple of ways of manipulating the model:
**First**
```
ticke... | This is more of a Python question.
Python is very dynamic language. You can code things (classes) ahead of time, or Python allows you to create classes completely dynamically at run-time. Consider the following example of a simple vector class. You can create/code the class ahead of time like:
```
class MyVector(obje... |
How to read numbers in python conveniently? | 12,803,566 | 4 | 2012-10-09T15:35:09Z | 12,803,592 | 8 | 2012-10-09T15:36:43Z | [
"python"
] | ```
x1, y1, a1, b1, x2, y2 = int(input()), int(input()), int(input()), int(input()), int(input()), int(input())
```
My problem is to read 6 numbers each given on a new line. How to do that more laconically than my code above? | ```
x1, y1, a1, b1, x2, y2 = (int(input()) for _ in range(6))
```
Replace `range` with `xrange` and `input` with `raw_input` in Python 2. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.