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 |
|---|---|---|---|---|---|---|---|---|---|
Continuing in Python's unittest when an assertion fails | 4,732,827 | 43 | 2011-01-19T07:38:08Z | 8,795,354 | 21 | 2012-01-09T21:20:41Z | [
"python",
"unit-testing"
] | EDIT: switched to a better example, and clarified why this is a real problem.
I'd like to write unit tests in Python that continue executing when an assertion fails, so that I can see multiple failures in a single test. For example:
```
class Car(object):
def __init__(self, make, model):
self.make = make
se... | One option is assert on all the values at once as a tuple.
For example:
```
class CarTest(unittest.TestCase):
def test_init(self):
make = "Ford"
model = "Model T"
car = Car(make=make, model=model)
self.assertEqual(
(car.make, car.model, car.has_seats, car.wheel_count),
(make,... |
Is there a way to keep docstrings separate from the functions they document? | 4,732,850 | 3 | 2011-01-19T07:41:11Z | 4,732,910 | 8 | 2011-01-19T07:48:17Z | [
"python",
"docstring"
] | I'm working on a module with many small functions but whose docstrings tend to be quite long. The docstrings make working on the module irritating as I have to constantly scroll over a long docstring to find a little bit of actual code.
Is there a way to keep docstrings separate from the functions they document? I'd r... | The docstring for a function is available as the special attribute `__doc__`.
```
>>> def f(x):
... "return the square of x"
... return x * x
>>> f.__doc__
'return the square of x'
>>> help(f)
(help page with appropriate docstring)
>>> f.__doc__ = "Return the argument squared"
>>> help(f)
(help page with new d... |
What is the purpose of python 2.7's download package "Windows x86 MSI program database"? | 4,732,940 | 18 | 2011-01-19T07:53:54Z | 4,733,144 | 11 | 2011-01-19T08:27:17Z | [
"python",
"release",
"file-format"
] | Upgrading from python 2.5/2.6 to python 2.7 on WinXP, I've found new download package forms for python at <http://www.python.org/download/releases/2.7.1/>.
So I'm wondering what is the purpose of python 2.7's download package "[Windows x86 MSI program database](http://www.python.org/ftp/python/2.7.1/python-2.7.1-pdb.z... | It is the Python windows executable with debugging extensions. Having it as part of standard release was costly in terms of size and It was made available because in Windows due to differences in Windows versions and Visual studio versions and updates, building one by the user may not represent the DLL that distributed... |
how can i show an irrational number to 100 decimal places in python? | 4,733,173 | 12 | 2011-01-19T08:32:15Z | 4,733,196 | 27 | 2011-01-19T08:36:27Z | [
"python",
"math",
"decimal-point"
] | I am trying to find the square root of 2 to 100 decimal places, but it only shows to like 10 by default, how can I change this? | [decimal](http://docs.python.org/library/decimal.html) module comes in handy.
```
>>> from decimal import *
>>> getcontext().prec = 100
>>> Decimal(2).sqrt()
Decimal('1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573')
``` |
how can i show an irrational number to 100 decimal places in python? | 4,733,173 | 12 | 2011-01-19T08:32:15Z | 4,733,238 | 7 | 2011-01-19T08:41:13Z | [
"python",
"math",
"decimal-point"
] | I am trying to find the square root of 2 to 100 decimal places, but it only shows to like 10 by default, how can I change this? | You can use the [decimal](http://docs.python.org/library/decimal.html) module for arbitrary precision numbers:
```
import decimal
d2 = decimal.Decimal(2)
# Add a context with an arbitrary precision of 100
dot100 = decimal.Context(prec=100)
print d2.sqrt(dot100)
```
If you need the same kind of ability coupled to s... |
What is the difference between active python and python? | 4,733,252 | 21 | 2011-01-19T08:42:45Z | 4,733,301 | 17 | 2011-01-19T08:49:56Z | [
"python",
"activepython"
] | I am new to Python. I am supposed to launch an application and perform some tasks on the application from python. I found Python from python.org and ActivePython from activestate.com, but what is the difference between them? Which should I install? | ActiveState is an Open Source Company which bundles Python with some additional packages and makes it available for variety of platforms. Sometimes they support platforms which the standard python distrubution does not. For e.g. AIX comes to my mind.
Many beginners to python on Windows have this doubt when they start ... |
How do I clone a Django model instance object and save it to the database? | 4,733,609 | 143 | 2011-01-19T09:30:36Z | 4,733,702 | 15 | 2011-01-19T09:40:26Z | [
"python",
"django"
] | ```
Foo.objects.get(pk="foo")
<Foo: test>
```
In the database, I want to add another object which is a copy of the object above.
Suppose my table has one row. I want to insert the first row object into another row with a different primary key. How can I do that? | There's a clone snippet [here](http://djangosnippets.org/snippets/904/), which you can add to your model which does this:
```
def clone(self):
new_kwargs = dict([(fld.name, getattr(old, fld.name)) for fld in old._meta.fields if fld.name != old._meta.pk]);
return self.__class__.objects.create(**new_kwargs)
``` |
How do I clone a Django model instance object and save it to the database? | 4,733,609 | 143 | 2011-01-19T09:30:36Z | 4,736,172 | 206 | 2011-01-19T14:10:07Z | [
"python",
"django"
] | ```
Foo.objects.get(pk="foo")
<Foo: test>
```
In the database, I want to add another object which is a copy of the object above.
Suppose my table has one row. I want to insert the first row object into another row with a different primary key. How can I do that? | Just change the primary key of your object and run save().
```
obj = Foo.objects.get(pk="foo")
obj.pk = "bar"
obj.save()
```
If you want auto-generated key, set the new key to None.
More on UPDATE/INSERT [here](https://docs.djangoproject.com/en/dev/ref/models/instances/#how-django-knows-to-update-vs-insert). |
How do I clone a Django model instance object and save it to the database? | 4,733,609 | 143 | 2011-01-19T09:30:36Z | 10,134,542 | 89 | 2012-04-13T02:34:29Z | [
"python",
"django"
] | ```
Foo.objects.get(pk="foo")
<Foo: test>
```
In the database, I want to add another object which is a copy of the object above.
Suppose my table has one row. I want to insert the first row object into another row with a different primary key. How can I do that? | The Django documentation for database queries includes [a section on copying model instances](https://docs.djangoproject.com/en/1.7/topics/db/queries/#copying-model-instances). Assuming your primary keys are autogenerated, you get the object you want to copy, set the primary key to `None`, and save the object again:
`... |
How do I clone a Django model instance object and save it to the database? | 4,733,609 | 143 | 2011-01-19T09:30:36Z | 12,925,333 | 14 | 2012-10-17T00:12:58Z | [
"python",
"django"
] | ```
Foo.objects.get(pk="foo")
<Foo: test>
```
In the database, I want to add another object which is a copy of the object above.
Suppose my table has one row. I want to insert the first row object into another row with a different primary key. How can I do that? | How to do this was added to the official Django docs in Django1.4
<https://docs.djangoproject.com/en/1.4/topics/db/queries/#copying-model-instances>
The official answer is similar to miah's answer, but the docs point out some difficulties with inheritance and related objects, so you should probably make sure you read... |
How do I clone a Django model instance object and save it to the database? | 4,733,609 | 143 | 2011-01-19T09:30:36Z | 16,727,397 | 25 | 2013-05-24T03:50:30Z | [
"python",
"django"
] | ```
Foo.objects.get(pk="foo")
<Foo: test>
```
In the database, I want to add another object which is a copy of the object above.
Suppose my table has one row. I want to insert the first row object into another row with a different primary key. How can I do that? | Be careful here. This can be extremely expensive if you're in a loop of some kind and you're retrieving objects one by one. If you don't want the call to the database, just do:
```
from copy import deepcopy
new_instance = deepcopy(object_you_want_copied)
new_instance.id = None
new_instance.save()
```
It does the sam... |
How do I clone a Django model instance object and save it to the database? | 4,733,609 | 143 | 2011-01-19T09:30:36Z | 24,243,330 | 12 | 2014-06-16T12:04:23Z | [
"python",
"django"
] | ```
Foo.objects.get(pk="foo")
<Foo: test>
```
In the database, I want to add another object which is a copy of the object above.
Suppose my table has one row. I want to insert the first row object into another row with a different primary key. How can I do that? | Use the below code :
```
from django.forms import model_to_dict
instance = Some.objects.get(slug='something')
kwargs = model_to_dict(instance, exclude=['id'])
new_instance = Some.objects.create(**kwargs)
``` |
When is StringIO used? | 4,733,693 | 30 | 2011-01-19T09:39:21Z | 4,733,795 | 20 | 2011-01-19T09:51:42Z | [
"python",
"stringio"
] | Using StringIO as string buffer is slower than using list as buffer.
When is StringIO used?
```
from io import StringIO
def meth1(string):
a = []
for i in range(100):
a.append(string)
return ''.join(a)
def meth2(string):
a = StringIO()
for i in range(100):
a.write(string)
re... | If you measure for speed, you should use `cStringIO`.
From the [docs](http://docs.python.org/library/stringio.html):
> The module cStringIO provides an
> interface similar to that of the
> StringIO module. Heavy use of
> StringIO.StringIO objects can be made
> more efficient by using the function
> StringIO() from th... |
When is StringIO used? | 4,733,693 | 30 | 2011-01-19T09:39:21Z | 4,733,799 | 27 | 2011-01-19T09:51:57Z | [
"python",
"stringio"
] | Using StringIO as string buffer is slower than using list as buffer.
When is StringIO used?
```
from io import StringIO
def meth1(string):
a = []
for i in range(100):
a.append(string)
return ''.join(a)
def meth2(string):
a = StringIO()
for i in range(100):
a.write(string)
re... | The main advantage of StringIO is that it can be used where a file was expected. So you can do for example:
```
import sys, StringIO
out = StringIO.StringIO()
sys.stdout = out
print "hi, I'm going out"
sys.stdout = sys.__stdout__
print out.getvalue()
``` |
When is StringIO used? | 4,733,693 | 30 | 2011-01-19T09:39:21Z | 4,733,983 | 13 | 2011-01-19T10:10:14Z | [
"python",
"stringio"
] | Using StringIO as string buffer is slower than using list as buffer.
When is StringIO used?
```
from io import StringIO
def meth1(string):
a = []
for i in range(100):
a.append(string)
return ''.join(a)
def meth2(string):
a = StringIO()
for i in range(100):
a.write(string)
re... | Well, I don't know if I would like to call that using it as a "buffer", you are just multiplying a string a 100 times, in two complicated ways. Here is an uncomplicated way:
```
def meth3(string):
return string * 100
```
If we add that to your test:
```
if __name__ == '__main__':
from timeit import Timer
... |
Specifying where to install 'tests_require' dependencies of a distribute/setuptools package | 4,734,292 | 19 | 2011-01-19T10:43:13Z | 7,747,140 | 25 | 2011-10-12T22:01:01Z | [
"python",
"testing",
"setuptools",
"distribute"
] | When I run `python setup.py test` the dependencies listed in `tests_require` in setup.py are downloaded to the current directory. I would like to have those dependencies installed in site-packages, just as the dependencies listed in `requires` when I run `python setup.py install`. | You haven't asked a question, but you've implicitly asked the question, "How do I force setuptools to install test dependencies (as specified by the tests\_require parameter) to the Python environment when running install?" I'll answer that question.
You cannot specify where the test requirements are installed. The wh... |
Specifying where to install 'tests_require' dependencies of a distribute/setuptools package | 4,734,292 | 19 | 2011-01-19T10:43:13Z | 8,899,659 | 11 | 2012-01-17T18:22:15Z | [
"python",
"testing",
"setuptools",
"distribute"
] | When I run `python setup.py test` the dependencies listed in `tests_require` in setup.py are downloaded to the current directory. I would like to have those dependencies installed in site-packages, just as the dependencies listed in `requires` when I run `python setup.py install`. | I am using *pip* to achieve something like that. Instead of adding *tests\_requires* or *extras* to my setup.py I have created a [pip requirements file](https://pip.pypa.io/en/stable/user_guide/#requirements-files).
Example my **dev\_requirements.txt** file:
```
pytest
webtest
```
Then to install it run:
```
$ pip ... |
How do I make my wxpython top frame show in the middle of my desktop? | 4,734,390 | 5 | 2011-01-19T10:54:44Z | 4,738,232 | 10 | 2011-01-19T17:00:50Z | [
"python",
"user-interface",
"wxpython"
] | I want to make my GUI program top frame both vertically and horizontally aligned.
```
wx.Frame.__init__(self, parent=None, id= -1, title="Test Frame", pos=(-1, -1), size=(1280, 770), style=wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX)
```
What should I do(except do the calculation to find the absolute... | Simply use
```
self.Center()
```
in the class `__init__()` instead of `pos=(-1,-1)`. |
sqrt: ValueError: math domain error | 4,735,448 | 4 | 2011-01-19T12:52:40Z | 4,735,475 | 11 | 2011-01-19T12:55:54Z | [
"python",
"math"
] | I'm facing a problem with "`distance ValueError: math domain error`" when using `sqrt` function in python.
Here is my code:
```
from math import sqrt
def distance(x1,y1,x2,y2):
x3 = x2-x1
xFinal = x3^2
y3 = y2-y1
yFinal = y3^2
final = xFinal + yFinal
d = sqrt(final)
return d
``` | Your issue is that exponentiation in Python is done using `a ** b` and not `a ^ b` (`^` is bitwise XOR) which causes final to be a negative value, which causes a domain error.
Your fixed code:
```
def distance(x1, y1, x2, y2):
return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** .5 # to the .5th power equals sqrt
``` |
python: unicode problem | 4,735,566 | 5 | 2011-01-19T13:06:07Z | 4,735,609 | 12 | 2011-01-19T13:10:53Z | [
"python",
"unicode"
] | I am trying to decode a string I took from file:
```
file = open ("./Downloads/lamp-post.csv", 'r')
data = file.readlines()
data[0]
```
> '\xff\xfeK\x00e\x00y\x00w\x00o\x00r\x00d\x00\t\x00C\x00o\x00m\x00p\x00e\x00t\x00i\x00t\x00i\x00o\x00n\x00\t\x00G\x00l\x00o\x00b\x00a\x00l\x00
> \x00M\x00o\x00n\x00t\x00h\x00l\x00y\... | This looks like UTF-16 data. So try
```
data[0].rstrip("\n").decode("utf-16")
```
Edit (for your update): Try to decode the whole file at once, that is
```
data = open(...).read()
data.decode("utf-16")
```
The problem is that the line breaks in UTF-16 are "\n\x00", but using `readlines()` will split at the "\n", le... |
Split from a specific delimiter | 4,736,195 | 2 | 2011-01-19T14:12:22Z | 4,736,230 | 8 | 2011-01-19T14:15:32Z | [
"python",
"parsing",
"url"
] | How to rip a URL like <http://www.facebook.com/pages/create.php> to have a result like this: `www.facebook.com`?
I tried this way, but doesn't work:
```
line.split('/', 2)[2]
```
My problem is probably with that two forward slashes // and some of the URLs start from the www strings.
Thanks for your help, Adia | You might want to look at Python's [urlparse](http://docs.python.org/library/urlparse.html) module.
```
>>> from urlparse import urlparse
>>> o = urlparse('http://www.facebook.com/pages/create.php')
>>> o.netloc
'www.facebook.com'
``` |
Python: Build a dictionary from a file's contents | 4,736,563 | 2 | 2011-01-19T14:44:59Z | 4,736,609 | 13 | 2011-01-19T14:49:18Z | [
"python",
"list",
"dictionary"
] | Say that I have a file of names and values with entries like this:
```
lasker:22,45,77,101
kramnik:45,22,15,105
```
What's the most Pythonic way to get them into a dictionary with the name as the key and the values as a list like this:
```
{ 'lasker': (22,45,77,101), 'kramnik': (45,22,15,105) }
```
**EDIT**
And is... | I think it is pretty clear how this code works:
```
def get_entries( infile ):
with open( infile, 'rt') as file:
for line in file:
name, nums = line.split(':', 1)
yield name, tuple(int(x) for x in nums.split(','))
# dict takes a sequence of `(key, value)` pairs and turns in into a... |
IOError: [Errno 13] Permission denied: | 4,736,616 | 2 | 2011-01-19T14:49:50Z | 4,736,921 | 9 | 2011-01-19T15:13:54Z | [
"python",
"file-permissions"
] | I have built this code to specifically identify a load of .XML files and to extract co-ordinates from those files. Here is my code:
```
from xml.etree import ElementTree as ET
import sys, string, os, arcgisscripting
gp = arcgisscripting.create(9.3)
workspace = "D:/J040083"
gp.workspace = workspace
for root, dirs, fi... | You need to change the line
```
tree = ET.parse(workspace)
```
to
```
tree = ET.parse(filename)
```
because workspace is a directory and the parse method takes a filename. |
Python Object Oriented Programming | 4,737,088 | 2 | 2011-01-19T15:28:01Z | 4,737,115 | 9 | 2011-01-19T15:29:51Z | [
"python",
"variables"
] | Am trying to understand object oriented programming with python. Am new to programming.
I have this class that is giving me an error I don't understand and I will be glad if anyone can throw more light on this for me:
```
class TimeIt(object):
def __init__(self, name):
self.name = name
def test_one(s... | You're overwriting `i` within loop. When you're "preceding" `i` with `self`, you're creating different variable, which is not overwritten. |
Creating a dictionary from two iterables and consuming both of them | 4,737,901 | 3 | 2011-01-19T16:31:09Z | 4,737,926 | 12 | 2011-01-19T16:33:25Z | [
"python",
"dictionary",
"iterable"
] | Suppose I have two lists and I want to make a dictionary from them. Like:
```
>>> l = [1, 2, 3, 4, 5]
>>> x = ['a', 'b', 'c']
>>> dict(zip(l, x))
{1: 'a', 2: 'b', 3: 'c'}
```
This works as I'd want it to and since the lists are not of equal length, the elements `4` and `5` are left out and there is no corresponding v... | Use
```
dict(itertools.izip_longest(l, x))
# {1: 'a', 2: 'b', 3: 'c', 4: None, 5: None}
``` |
Python Twisted JSON RPC | 4,738,209 | 18 | 2011-01-19T16:59:38Z | 4,738,563 | 19 | 2011-01-19T17:30:06Z | [
"python",
"twisted",
"rpc",
"json-rpc"
] | Can anyone recommend some simple code to set up a simple JSON RPC client and server using twisted?
I found txJSON-RPC, but I was wondering if someone had some experience using some of these anc could recommend something. | txJSONRPC is great. I use it and it works. I suggest you give it a try.
# SERVER:
```
from txjsonrpc.web import jsonrpc
from twisted.web import server
from twisted.internet import reactor
class Math(jsonrpc.JSONRPC):
"""
An example object to be published.
"""
def jsonrpc_add(self, a, b):
"""
... |
what does <> mean in Python | 4,738,285 | 6 | 2011-01-19T17:05:28Z | 4,738,303 | 15 | 2011-01-19T17:06:43Z | [
"python"
] | What is the meaning of <> in Python?
I have tried searching for it on Google but I cannot seem to get inside the search term...
I have not seen this in any other language also otherwise I would have tried to find it. | `<>` is an alternate spelling of `!=`, the inequality test operator. IIRC, it has been removed in Python3.
```
>>> "foo" <> "bar"
True
>>> "foo" <> "foo"
False
``` |
Finding out whether a is a power of b | 4,738,908 | 6 | 2011-01-19T18:03:36Z | 4,739,055 | 8 | 2011-01-19T18:16:44Z | [
"python"
] | I'm currently using singpath.com to practice on my python, but I face an issue with a problem:
A number, a, is a power of b if it is divisible by b and a/b is a power of b.
Write a function called is\_power that takes parameters a and b and returns True if a is a power of b.
```
def is_power(a,b):
c = a/b
if ... | The reason reason why your original code does not work is the following: You just check `(c%b) == 0)` aka `(a/b) is divisible by b`, which is much weaker than the `a/b is a power of b` part of the definition.
When you want to solve a problem such as this you should always start with the trivial cases. In this case the... |
Python 3.1.3 Win 7: csv writerow Error "must be bytes or buffer, not str" | 4,739,066 | 3 | 2011-01-19T18:18:08Z | 4,743,320 | 13 | 2011-01-20T04:04:32Z | [
"python",
"python-3.x"
] | Got a simple script which worked perfectly under Python 2.7.1 at my Win xp machine.
Now got a win 7 machine with python 3.1.3.
The code is:
```
owriter.writerow(dtime[1][1])
dtime[1][1]=['30-Aug-10 16:00:00', '2.5', '15']
```
Got this error message: `TypeError: must be bytes or buffer, not str`
What changes should... | In Python 2.X, it was [required](http://docs.python.org/library/csv.html?highlight=csv#csv.writer) to open the csvfile with 'b' because the csv module does its own line termination handling.
In Python 3.X, the csv module still does its own line termination handling, but still needs to know an encoding for Unicode stri... |
Any easy way to plot a 3d scatter in Python that I can rotate around? | 4,739,360 | 12 | 2011-01-19T18:49:48Z | 4,739,704 | 9 | 2011-01-19T19:28:12Z | [
"python",
"charts",
"matplotlib",
"scatter-plot"
] | Currently I'm using matplotlib to plot a 3d scatter and while it gets the job done, I can't seem to find a way to rotate it to see my data better.
Here's an example:
```
import pylab as p
import mpl_toolkits.mplot3d.axes3d as p3
#data is an ndarray with the necessary data and colors is an ndarray with
#'b', 'g' and ... | Using [mayavi](http://mayavi.sourceforge.net/), you can create such a plot with
```
import enthought.mayavi.mlab as mylab
import numpy as np
x, y, z, value = np.random.random((4, 40))
mylab.points3d(x, y, z, value)
mylab.show()
```
The GUI allows rotation via clicking-and-dragging, and zooming in/out via right-clicki... |
Any easy way to plot a 3d scatter in Python that I can rotate around? | 4,739,360 | 12 | 2011-01-19T18:49:48Z | 4,739,805 | 19 | 2011-01-19T19:37:07Z | [
"python",
"charts",
"matplotlib",
"scatter-plot"
] | Currently I'm using matplotlib to plot a 3d scatter and while it gets the job done, I can't seem to find a way to rotate it to see my data better.
Here's an example:
```
import pylab as p
import mpl_toolkits.mplot3d.axes3d as p3
#data is an ndarray with the necessary data and colors is an ndarray with
#'b', 'g' and ... | Well, first you need to define what you mean by "see my data better"...
You can rotate and zoom in on the plot using the mouse, if you're wanting to work interactively.
If you're just wanting to rotate the axes programatically, then use `ax.view_init(elev, azim)` where `elev` and `azim` are the elevation and azimuth ... |
Getter with side effect | 4,739,597 | 13 | 2011-01-19T19:16:12Z | 4,739,627 | 15 | 2011-01-19T19:17:53Z | [
"python",
"design-patterns",
"for-loop",
"getter-setter",
"side-effects"
] | I create a class whose objects are initialized with
a bunch of XML code. The class has the ability to extract various parameters out of that XML and to cache them inside the object state variables. The potential amount of these parameters is large and most probably, the user will not need most of them. That is why I ha... | This design pattern is called [Lazy initialization](http://en.wikipedia.org/wiki/Lazy_initialization) and it has legitimate use. |
How do you a double factorial in python? | 4,740,172 | 3 | 2011-01-19T20:09:26Z | 4,740,229 | 13 | 2011-01-19T20:15:23Z | [
"python",
"math",
"factorial"
] | I've been stucked on this question for a really long time.
I've managed to do a single recursive factorial.
```
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
```
Double factorial
For an even integer n, the double factorial is the product of all even positive integer... | ```
reduce(int.__mul__,range(n,0,-2))
``` |
parentheses in Python Conditionals | 4,740,419 | 8 | 2011-01-19T20:37:38Z | 4,740,444 | 7 | 2011-01-19T20:40:09Z | [
"python",
"conditional",
"parentheses"
] | I have a simple question regarding the use of parentheses in Python conditional statements.
The following two snippets works just the same but I wonder if this is only true because of it's simplicity;
```
>>> import os, socket
>>> if ((socket.gethostname() == "bristle") or (socket.gethostname() == "rete")):
... D... | The parentheses are redundant in this case. Comparison has a higher precedence than Boolean operators, so the comparisons will always be performed first regardless of the parentheses.
That said, a guideline I once saw (perhaps in *Practical C Programming)* said something like this:
1. Multiplication and division firs... |
parentheses in Python Conditionals | 4,740,419 | 8 | 2011-01-19T20:37:38Z | 4,740,493 | 29 | 2011-01-19T20:43:39Z | [
"python",
"conditional",
"parentheses"
] | I have a simple question regarding the use of parentheses in Python conditional statements.
The following two snippets works just the same but I wonder if this is only true because of it's simplicity;
```
>>> import os, socket
>>> if ((socket.gethostname() == "bristle") or (socket.gethostname() == "rete")):
... D... | The other answers that Comparison takes place before Boolean are 100% correct. As an alternative (for situations like what you've demonstrated) you can also use this as a way to combine the conditions:
```
if socket.gethostname() in ('bristle', 'rete'):
# Something here that operates under the conditions.
```
That ... |
setup.py examples? | 4,740,473 | 43 | 2011-01-19T20:42:24Z | 4,740,640 | 29 | 2011-01-19T20:54:11Z | [
"python",
"rpm"
] | After studying this page:
<http://docs.python.org/distutils/builtdist.html>
I am hoping to find some setup.py files to study so as to make my own (with the goal of making a fedora rpm file).
Could the s.o. community point me towards some good examples? | Complete walkthrough of writing `setup.py` scripts [here](http://docs.python.org/distutils/setupscript.html). (with some examples)
If you'd like a real-world example, I could point you towards the `setup.py` scripts of a couple major projects. Django's is [here](http://code.djangoproject.com/browser/django/trunk/setup... |
setup.py examples? | 4,740,473 | 43 | 2011-01-19T20:42:24Z | 4,740,685 | 19 | 2011-01-19T20:58:23Z | [
"python",
"rpm"
] | After studying this page:
<http://docs.python.org/distutils/builtdist.html>
I am hoping to find some setup.py files to study so as to make my own (with the goal of making a fedora rpm file).
Could the s.o. community point me towards some good examples? | You may find the [HitchHiker's Guide to Packaging](http://the-hitchhikers-guide-to-packaging.readthedocs.org/en/latest/) helpful, even though it is incomplete. I'd start with the [Quick Start tutorial](http://the-hitchhikers-guide-to-packaging.readthedocs.org/en/latest/quickstart.html). Try also just browsing through P... |
setup.py examples? | 4,740,473 | 43 | 2011-01-19T20:42:24Z | 11,710,693 | 14 | 2012-07-29T16:04:40Z | [
"python",
"rpm"
] | After studying this page:
<http://docs.python.org/distutils/builtdist.html>
I am hoping to find some setup.py files to study so as to make my own (with the goal of making a fedora rpm file).
Could the s.o. community point me towards some good examples? | **READ THIS FIRST** <https://packaging.python.org/en/latest/current.html>
> # Installation Tool Recommendations
>
> 1. Use pip to install Python packages
> from PyPI.
> 2. Use virtualenv, or pyvenv to isolate application specific dependencies from a shared Python installation.
> 3. Use pip wheel to create a cache o... |
Using Mako Templates in Pyramid with Google App Engine | 4,740,644 | 4 | 2011-01-19T20:54:47Z | 4,765,850 | 8 | 2011-01-22T02:44:10Z | [
"python",
"pyramid"
] | With Pyramid and mod\_wsgi, to use mako templates you just add this line to development.ini:
```
mako.directories = house:templates
```
Unfortunately, Pyramid in the Google App Engine doesn't have an development.ini file, and I get the following error:
```
File "appengine-monkey/pyramidapp/app/lib/python/pyramid-1.0... | I found out from the pylons-devel mailing list. Figured I would post the answer here.
The way to do this is pass it to the Configurator as a setting. So in the `__init__.py` file make the following change:
```
config = Configurator(settings={'mako.directories':['house:templates']})
``` |
python multiline regex | 4,740,739 | 5 | 2011-01-19T21:05:04Z | 4,741,112 | 9 | 2011-01-19T21:41:36Z | [
"python",
"regex"
] | I'm having an issue compiling the correct regular expression for a multiline match. Can someone point out what I'm doing wrong. I'm looping through a basic dhcpd.conf file with hundreds of entries such as:
```
host node20007 ... | **Update** I've just noticed the real reason that you are getting the results that you got; in your code:
```
for host in f:
match = re_hostinfo.search(host)
if match:
print match.groups()
```
`host` *refers to a single line, but your pattern needs to work over two lines.*
Try this:
```
data = f.rea... |
Add new navigate modes in matplotlib | 4,740,988 | 8 | 2011-01-19T21:29:39Z | 4,762,187 | 7 | 2011-01-21T18:03:12Z | [
"python",
"matplotlib",
"toolbar"
] | I'm writing a wx/matplotlib application, and I'm having considerable difficulty adding a new tool to the matplotlib NavigationToolbar.
Basically I want to add tools for selection (marquee, lasso, etc) that will toggle the controlled subplots mouse mode. As of yet I have been unable to find any features that will let m... | Here's an improved version of `MyNavToolbar`. The main thing to note is the addition of the `add_user_tool` method. I call it from within `__init__`, but you'd probably want to call it from outside the `MyNavToolbar` class. This way you could have different tools for plot types.
```
class MyNavToolbar(NavigationToolba... |
how to pick just one item from a generator (in python)? | 4,741,243 | 64 | 2011-01-19T21:55:28Z | 4,741,269 | 94 | 2011-01-19T21:58:10Z | [
"python",
"iterator",
"generator",
"python-2.x"
] | I have a generator function like the following:
```
def myfunct():
...
yield result
```
The usual way to call this function would be:
```
for r in myfunct():
dostuff(r)
```
My question, is there a way to get just one element from the generator whenever I like?
For example, I'd like to do something like:
```
... | Create an generator using
```
g = myfunct()
```
Everytime you would like an item, use
```
g.next()
```
or
```
next(g)
```
If the generator exits, it will raise `StopIteration`. You can either catch this exception if necessary, or use the `default` argument to `next()`:
```
next(g, default_value)
``` |
Sqlite update don't working right - python | 4,741,251 | 3 | 2011-01-19T21:56:02Z | 11,526,394 | 26 | 2012-07-17T15:59:25Z | [
"python",
"sqlite"
] | EDIT: after some test i found out that it don't was the addpoint method that failed.
I'm working on a small game to a irc bot. This method will update the score in database called 'score', the are only two players. It's a sqlite database. It's mostly the update sql that ain't working right.
Thanks
```
def addpointo(... | Although the original author has most likely moved on, I figured I'd leave an answer here for future Googler's (like me ^\_^).
I think what's happening here is that the following error...
`ValueError: parameters are of unsupported type`
... is actually coming from the following line (contrary to what the author said... |
Is nested recursion possible or should we avoid recursion? | 4,741,307 | 2 | 2011-01-19T22:02:15Z | 4,741,500 | 9 | 2011-01-19T22:23:24Z | [
"python",
"algorithm",
"recursion",
"big-o"
] | I came across a question like this
* F(1) = 1
* F(2n) = F(n)
* F(2n+1) = F(n) + F(n+1)
Develop a recursive program to compute F
The answer some user mentioned uses two recursive function calls:
```
def calc(n):
if n=1 :
return 1
else if(n%2)==0:
return calc(n/2)
else :
return calc(n/2)+calc(n/2+1)... | Both of these approaches are correct. It is indeed legal to have multiple recursive calls from a function, and the meaning is what you'd think - just do one call, then the next, then the next, etc.
Interestingly, I don't think that the recursive version does make exponentially many calls. It makes at most two recursiv... |
Append elements of a set to a list in Python | 4,741,537 | 5 | 2011-01-19T22:28:12Z | 4,741,543 | 16 | 2011-01-19T22:29:02Z | [
"python",
"list",
"set"
] | How do you append the elements of a set to a list in Python in the most succinct way?
```
>>> a = [1,2]
>>> b = set([3,4])
>>> a.append(list(b))
>>> a
[1, 2, [3, 4]]
```
But what I want is:
```
[1, 2, 3, 4]
``` | Use
```
a.extend(list(b))
```
or even easier
```
a.extend(b)
```
instead. |
Why doesn't this Python work? Simple Oop | 4,742,145 | 2 | 2011-01-19T23:58:18Z | 4,742,152 | 7 | 2011-01-19T23:59:31Z | [
"python"
] | ```
class UserDict:
def __init__(self, dict=None):
self.data = {}
if dict is not None: self.update(dict)
```
I created a file "abc.py" and put above in it.
```
>>> import abc
>>> d = abc.UserDict()
Traceback (most recent call last):
File "<stdin>", line 1, ... | Most certainly you are importing the Python `abc` module for abstract base classes instead of your own `abc.py`. Better choose a different name for your module.
Edit: Of course it **is** possible to have your own module with the same name as a built-in module and to import it. You have to make sure that your module is... |
how to test for a regex match | 4,742,662 | 11 | 2011-01-20T01:35:36Z | 4,742,783 | 14 | 2011-01-20T01:57:34Z | [
"python",
"regex"
] | I have a string. Let's call it 'test'.
I want to test a match for this string, but only using the backref of a regex.
Can I do something like this:
import re
```
for line in f.readlines():
if '<a href' in line:
if re.match('<a href="(.*)">', line) == 'test':
print 'matched!'
```
?
This of course, ... | [`re.match`](http://docs.python.org/library/re.html#re.match) matches only at the [beginning](http://docs.python.org/library/re.html#matching-vs-searching) of the string.
```
def url_match(line, url):
match = re.match(r'<a href="(?P<url>[^"]*?)"', line)
return match and match.groupdict()['url'] == url:
```
ex... |
Change IntegerProperty to FloatProperty of existing AppEngine DataStore | 4,742,875 | 5 | 2011-01-20T02:16:56Z | 4,743,139 | 12 | 2011-01-20T03:22:44Z | [
"python",
"django",
"google-app-engine",
"gae-datastore"
] | I built an appengine application (python) which need to convert existing datastore entities in integer value (100) to float value (100.00) for currency conversion issue.
How's the right way doing this? Since my query returning error when i just change property type in my model.
**Old Model:**
```
class Learn(search.S... | The easiest way to do this is to change the model to inherit from db.Expando, and delete the integer properties from the definion. Then, load each instance and do "instance.foo = float(instance.foo)" on each, before saving them back to the datastore - you'll probably want to use the mapreduce API for this. Finally, mak... |
Python 3.1 - Obtaining the least common element in array | 4,743,035 | 12 | 2011-01-20T02:58:06Z | 4,743,059 | 14 | 2011-01-20T03:02:20Z | [
"python",
"python-3.x"
] | To find the most common, I know I can use something like this:
```
most_common = collections.Counter(array).most_common(to_find)
```
However, I can't seem to find anything comparable, for finding the least common element.
Could I please get recommendations on how to do.
Thank you for your time! | `most_common` without any argument returns *all* the entries, ordered from most common to least.
So to find the least common, just start looking at it from the other end. |
Python 3.1 - Obtaining the least common element in array | 4,743,035 | 12 | 2011-01-20T02:58:06Z | 4,743,286 | 8 | 2011-01-20T03:56:05Z | [
"python",
"python-3.x"
] | To find the most common, I know I can use something like this:
```
most_common = collections.Counter(array).most_common(to_find)
```
However, I can't seem to find anything comparable, for finding the least common element.
Could I please get recommendations on how to do.
Thank you for your time! | Borrowing the source of collections.Counter.most\_common and inverting as appropriate:
```
from operator import itemgetter
import heapq
import collections
def least_common_values(array, to_find=None):
counter = collections.Counter(array)
if to_find is None:
return sorted(counter.items(), key=itemgetter... |
How to ensure list contains unique elements? | 4,743,409 | 5 | 2011-01-20T04:21:24Z | 4,743,418 | 16 | 2011-01-20T04:23:37Z | [
"python",
"list"
] | I have a class containing a list of strings. Say:
```
ClassName:
- list_of_strings
```
I need to enforce that this list of strings contains unique elements. Unfortunately, I can't change this list\_of\_strings to another type, like a set.
In the `addToList(str_to_add)` function, I want to guarantee string uniquenes... | ```
def addToList(self, str_to_add):
if str_to_add not in self.list_of_strings:
self.list_of_strings.append(str_to_add)
``` |
When should a Python script be split into multiple files/modules? | 4,743,497 | 14 | 2011-01-20T04:40:25Z | 4,743,520 | 10 | 2011-01-20T04:45:03Z | [
"python",
"coding-style",
"conventions"
] | In Java, this question is easy (if a little tedious) - every class requires its own file. So the number of .java files in a project is the number of classes (not counting anonymous/nested classes).
In Python, though, I can define multiple classes in the same file, and I'm not quite sure how to find the point at which ... | Remember that in Python, a file is a module that you will most likely import in order to use the classes contained therein. Also remember one of the basic principles of software development "[the unit of packaging is the unit of reuse](http://openlibrary.org/books/OL9297484M/Agile_Software_Development_Principles_Patter... |
Python: TypeError: takes exactly 1 argument (2 given) | 4,743,673 | 3 | 2011-01-20T05:14:56Z | 4,743,686 | 16 | 2011-01-20T05:17:25Z | [
"python"
] | I'm currently using singpath.com to practice my python, but I face an issue with a problem:
The expected result is:
```
>>>CurryPuff(3)
3.60
>>>CurryPuff(3,'Fish')
4.2
```
This is something I tried:
```
def CurryPuff(x,typePuff):
if(typePuff==''):
return x*1.2
if(typePuff=='Fish'):
return x... | You can't call a function with 1 argument if it expects 2, as `CurryPuff()` does. However, you can define a default argument that is used if no argument is passed:
```
def CurryPuff(x, typePuff=None):
if typePuff is None:
# and so on...
```
You can do this with any value for any argument. You may only omit... |
How do I connect a Python and a C program? | 4,743,748 | 3 | 2011-01-20T05:29:10Z | 4,743,925 | 7 | 2011-01-20T05:57:15Z | [
"python",
"c"
] | I have a python-based program that reads serial data off an a port connected to an rs232 cable. I want to pass the data I get here to a C-program that will handle the computation-intensive side of things. I have been checking up the net and all I've found are linux-based. | My suggestion would be the `inline` function from the `instant` module, though that only works if you can do everything you need to in a single c function. You just pass it a c function and it compiles a c extension at runtime.
```
from instant import inline
sieve_code = """
PyObject* prime_list(int max) {... |
Never use reflection in production code! What about Python? | 4,745,071 | 8 | 2011-01-20T08:53:29Z | 4,745,093 | 16 | 2011-01-20T08:56:48Z | [
"c#",
"java",
"python",
"reflection"
] | I've written C# and the mantra coming from on high seems to be "never use reflection in production code". I have used it for test code, but never anything that runs in the wild. All the arguments seem reasonable, and there's always a way to do it by adding another layer of abstraction or design pattern or whatever.
No... | As a dynamic language Python is fundamentally different than statically typed languages, so everything is reflection in it :-) Also *never use reflection in production code* (for static languages) seems a bit extreme to me. |
find and replace within a text file | 4,746,190 | 15 | 2011-01-20T10:52:16Z | 4,746,215 | 27 | 2011-01-20T10:55:05Z | [
"python",
"file",
"text",
"replace"
] | I have a text file which is about 400,000 lines long. I need to import this text file into a program which only accepts text files which are delimited with spaces or tabs, but this text file is delimited with semi-colons. There is no option in the program I am exporting the text file from (Arcmap) to change the delimin... | How about this:
```
sed -i 's/;/ /g' yourBigFile.txt
```
This is not a Python solution. You have to start this in a shell. But if you use Notepad, I guess you are on Windows. So here a Python solution:
```
f1 = open('yourBigFile.txt', 'r')
f2 = open('yourBigFile.txt.tmp', 'w')
for line in f1:
f2.write(line.repla... |
find and replace within a text file | 4,746,190 | 15 | 2011-01-20T10:52:16Z | 4,746,474 | 17 | 2011-01-20T11:23:01Z | [
"python",
"file",
"text",
"replace"
] | I have a text file which is about 400,000 lines long. I need to import this text file into a program which only accepts text files which are delimited with spaces or tabs, but this text file is delimited with semi-colons. There is no option in the program I am exporting the text file from (Arcmap) to change the delimin... | with Python, you can use [fileinput](http://docs.python.org/library/fileinput.html).
```
import fileinput
for line in fileinput.FileInput("file",inplace=1):
line = line.replace(";"," ")
print line,
```
this will replace all your ";" to spaces in place. |
Syntax highlighting in vim for python | 4,746,579 | 30 | 2011-01-20T11:33:17Z | 4,746,609 | 42 | 2011-01-20T11:37:03Z | [
"python",
"vim",
"syntax",
"vi",
"vim-syntax-highlighting"
] | How do I do I set the syntax highlighting in Vim 7 for python?
I would like to set my own colorschemes, and syntax highlighting for a type of code file. | The command to enable syntax highlighting in vim is `:syntax on`, if you want it to be active everytime you launch vim, just add a line containing `syntax on` in your .vimrc file. |
Syntax highlighting in vim for python | 4,746,579 | 30 | 2011-01-20T11:33:17Z | 20,776,280 | 7 | 2013-12-25T19:56:55Z | [
"python",
"vim",
"syntax",
"vi",
"vim-syntax-highlighting"
] | How do I do I set the syntax highlighting in Vim 7 for python?
I would like to set my own colorschemes, and syntax highlighting for a type of code file. | ## Syntax highlighting in vim for python (target is Ubuntu 12.10)
[Here is a walkthrough](http://i.imgur.com/W26xaan.png) on how to setup syntax highlighting in Python for Ubuntu 12.10. What you see is what you get:

<https://github.com/sentientmachine/P... |
matplotlib - subplots with fixed aspect ratio | 4,747,051 | 15 | 2011-01-20T12:22:33Z | 4,751,975 | 12 | 2011-01-20T20:04:29Z | [
"python",
"matplotlib"
] | I have a problem with plotting multiple subplots. I would like to set the PHYSICAL aspect ratio of the subplots to a fixed value.
In my example I have 12 subplots (4 rows and 3 columns) on a landscape A4 figure. There all subplots are nicely placed on the whole figure, and for all subplots the height is nearly equal to... | Actually, what you're wanting is quite simple... You just need to make sure that `adjustable` is set to `'box'` on your axes, and you have a set aspect ratio for the axes (anything other than `'auto'`).
You can either do this with the `adjustable` kwarg when you create the subplots. Alternatively, you can do this afte... |
Is there anything static about python function / method invocations? | 4,747,093 | 3 | 2011-01-20T12:27:34Z | 4,747,229 | 7 | 2011-01-20T12:41:14Z | [
"python",
"binding",
"cpython",
"dynamic-binding"
] | In [asking a question about reflection](http://stackoverflow.com/questions/4745071/never-use-reflection-in-production-code-what-about-python) I asked:
> Nice answer. But there is a difference between saying `myobject.foo()` and `x = getattr(myobject, "foo"); x();`. Even if it is only cosmetic. In the first the foo() i... | They're not entirely identical, but they are both dictionary lookups, as can be shown with the disassembler [`dis.dis`](http://docs.python.org/library/dis.html).
In particular, note the `LOAD_ATTR` instruction with dynamically looks up the attribute by name. According to the docs, it "replaces TOS [top of stack] with ... |
Calling base class method in Python | 4,747,397 | 21 | 2011-01-20T12:58:18Z | 4,747,427 | 25 | 2011-01-20T13:01:05Z | [
"python",
"class"
] | I have two classes A and B and A is base class of B.
I read that all methods in Python are virtual.
So how do I call a method of the base because when I try to call it, the method of the derived class is called as expected?
```
>>> class A(object):
def print_it(self):
print 'A'
>>> class B(A):
def ... | Using [super](http://docs.python.org/library/functions.html#super):
```
>>> class A(object):
... def print_it(self):
... print 'A'
...
>>> class B(A):
... def print_it(self):
... print 'B'
...
>>> x = B()
>>> x.print_it() # calls derived class method as expected
B
>>> s... |
Calling base class method in Python | 4,747,397 | 21 | 2011-01-20T12:58:18Z | 4,747,439 | 21 | 2011-01-20T13:02:37Z | [
"python",
"class"
] | I have two classes A and B and A is base class of B.
I read that all methods in Python are virtual.
So how do I call a method of the base because when I try to call it, the method of the derived class is called as expected?
```
>>> class A(object):
def print_it(self):
print 'A'
>>> class B(A):
def ... | Two ways:
```
>>> A.print_it(x)
'A'
>>> super(B, x).print_it()
'A'
``` |
What's the reverse of shlex.split? | 4,748,344 | 25 | 2011-01-20T14:33:11Z | 4,748,788 | 16 | 2011-01-20T15:11:33Z | [
"python",
"shell",
"split",
"shlex"
] | How can I reverse the results of a [`shlex.split`](http://docs.python.org/library/shlex.html#shlex.split)? That is, how can I obtain a quoted string that would ["resemble that of a Unix shell"](http://docs.python.org/library/shlex.html), given a `list` of strings I wish quoted?
## Update0
I've located a Python bug, a... | How about using `pipes.quote`?
```
import pipes
strings = ["ls", "/etc/services", "file with spaces"]
" ".join(pipes.quote(s) for s in strings)
# "ls /etc/services 'file with spaces'"
```
. |
What's the reverse of shlex.split? | 4,748,344 | 25 | 2011-01-20T14:33:11Z | 6,874,028 | 16 | 2011-07-29T13:39:08Z | [
"python",
"shell",
"split",
"shlex"
] | How can I reverse the results of a [`shlex.split`](http://docs.python.org/library/shlex.html#shlex.split)? That is, how can I obtain a quoted string that would ["resemble that of a Unix shell"](http://docs.python.org/library/shlex.html), given a `list` of strings I wish quoted?
## Update0
I've located a Python bug, a... | We now (3.3) have a [shlex.quote](http://docs.python.org/3/library/shlex.html#shlex.quote) function. Itâs none other that `pipes.quote` moved and documented (code using `pipes.quote` will still work). See <http://bugs.python.org/issue9723> for the whole discussion.
`subprocess.list2cmdline` is a private function tha... |
Python threading and GIL | 4,748,787 | 6 | 2011-01-20T15:11:26Z | 4,748,838 | 10 | 2011-01-20T15:16:46Z | [
"python",
"multithreading",
"locking",
"gil"
] | I was reading about the GIL and it never really specified if this includes the main thread or not (i assume so). Reason I ask is because I have a program with threads setup that modify a dictionary. The main thread adds/deletes based on player input while a thread loops the data updating and changing data.
However in ... | They are **running** at the same time, they just don't **execute** at the same time. The iterations might be interleaved. Quote Python:
> The mechanism used by the CPython interpreter to assure that only one thread **executes** Python **bytecode** at a time.
So two `for` loops might run at the same time, there will j... |
Django and root processes | 4,748,971 | 4 | 2011-01-20T15:27:24Z | 4,749,073 | 7 | 2011-01-20T15:33:16Z | [
"python",
"django",
"django-views",
"root",
"ping"
] | In my Django project I need to be able to check whether a host on the LAN is *up* using an ICMP ping. I found [this SO question](http://stackoverflow.com/questions/316866/ping-a-site-in-python) which answers how to ping something in Python and [this SO question](http://stackoverflow.com/questions/3767841/using-celery-i... | Absolutely no way, do not run the Django code as root!
I would run a daemon as root (written in Python, why not) and then [IPC](http://docs.python.org/library/ipc.html) between the Django instance and your daemon. As long as you're sure to validate the content and properly handle it (e.g. use `subprocess.call` with an... |
is there a way to script in Python to change user passwords in Linux? if so, how? | 4,749,083 | 5 | 2011-01-20T15:33:49Z | 4,749,227 | 7 | 2011-01-20T15:46:10Z | [
"python",
"linux",
"authentication"
] | I'm trying to write some scripts in Python and stumbled upon the need of making something to update the password of a given user in a Linux system...
UPDATE: the objective is to achieve the script to update the password automatically from a given data/algorithm. The important thing is to have no human intervention...
... | You can use `openssl` and `usermod`:
```
#!/usr/bin/env python
import subprocess
login = 'username'
password = 'somepassword'
# OpenSSL doesn't support stronger hash functions, mkpasswd is preferred
#p = subprocess.Popen(('openssl', 'passwd', '-1', password), stdout=subprocess.PIPE)
p = subprocess.Popen(('mkpasswd',... |
Lock free read only List in Python? | 4,750,141 | 8 | 2011-01-20T17:00:16Z | 4,750,231 | 10 | 2011-01-20T17:08:16Z | [
"python",
"performance",
"numpy"
] | I've done some basic performance and memory consumption benchmarks and I was wondering if there is any way to make things even faster...
1. I have a giant 70,000 element list with a numpy ndarray, and the file path in a tuple in the said list.
2. My first version passed a sliced up copy of the list to each of the proc... | The `multiprocessing` module provides exactly what you need: a shared array with optional locking, namely the [`multiprocessing.Array`](http://docs.python.org/library/multiprocessing.html#multiprocessing.Array) class. Pass `lock=False` to the constructor to disable locking.
Edit (taking into account your update): Thin... |
Python-Scapy or the like-How can I create an HTTP GET request at the packet level | 4,750,793 | 19 | 2011-01-20T18:07:46Z | 4,751,020 | 28 | 2011-01-20T18:31:54Z | [
"python",
"http",
"networking",
"get",
"scapy"
] | I am a moderate programmer, just getting into network programming.
As an attempt to improve my understanding of networks in general, I am trying to perform several basic HTTP actions from the packet level. My question is this: How might I use a library such as SCAPY to build an HTTP GET request and assosciated items a... | If you want to do a full three-way handshake, you'll have to do it manually.
Start with your SYN packet:
```
>>> syn = IP(dst='www.google.com') / TCP(dport=80, flags='S')
>>> syn
<IP frag=0 proto=tcp dst=Net('www.google.com') |<TCP dport=www flags=S |>>
```
Then receive the SYN-ACK packet from the server, sr1 work... |
How do I install pip on Windows? | 4,750,806 | 1,662 | 2011-01-20T18:08:59Z | 4,750,846 | 30 | 2011-01-20T18:13:36Z | [
"python",
"windows",
"pip"
] | pip is a replacement for easy\_install. But should I install pip using easy\_install on Windows? Is there a better way? | When I have to use Windows, I use ActivePython, which automatically adds everything to your PATH and includes a package manager called [PyPM](http://code.activestate.com/pypm/) which provides *binary* package management making it faster and simpler to install packages.
`pip` and `easy_install` aren't exactly the same ... |
How do I install pip on Windows? | 4,750,806 | 1,662 | 2011-01-20T18:08:59Z | 4,921,215 | 266 | 2011-02-07T12:21:55Z | [
"python",
"windows",
"pip"
] | pip is a replacement for easy\_install. But should I install pip using easy\_install on Windows? Is there a better way? | ~~-- **Outdated** -- use distribute, not setuptools as described here. --~~
-- **Outdated #2** -- use setuptools as distribute is deprecated.
As you mentioned pip doesn't include an independent installer, but you can install it with its predecessor easy\_install.
So:
1. Download the last pip version from here: <ht... |
How do I install pip on Windows? | 4,750,806 | 1,662 | 2011-01-20T18:08:59Z | 7,581,341 | 9 | 2011-09-28T09:51:21Z | [
"python",
"windows",
"pip"
] | pip is a replacement for easy\_install. But should I install pip using easy\_install on Windows? Is there a better way? | To install pip *globally* on Python 2.x, easy\_install appears to be the best solution as Adrián states.
However the [installation instructions](http://www.pip-installer.org/en/latest/installing.html) for pip recommend using [virtualenv](http://www.virtualenv.org) since every virtualenv has pip installed in it automa... |
How do I install pip on Windows? | 4,750,806 | 1,662 | 2011-01-20T18:08:59Z | 9,038,397 | 187 | 2012-01-27T18:43:14Z | [
"python",
"windows",
"pip"
] | pip is a replacement for easy\_install. But should I install pip using easy\_install on Windows? Is there a better way? | **2014 UPDATE:**
1) If you have installed Python 3.4 or later, pip is included with Python and should already be working on your system.
2) If you are running a version below Python 3.4 or if pip was not installed with Python 3.4 for some reason, then you'd probably use pip's official installation script `get-pip.py`... |
How do I install pip on Windows? | 4,750,806 | 1,662 | 2011-01-20T18:08:59Z | 9,448,989 | 8 | 2012-02-25T23:15:47Z | [
"python",
"windows",
"pip"
] | pip is a replacement for easy\_install. But should I install pip using easy\_install on Windows? Is there a better way? | I just wanted to add one more solution for those having issues installing setuptools from Windows 64-bit. The issue is discussed in this bug on python.org and is still unresolved as of the date of this comment. A simple workaround is mentioned and it works flawlessly. One registry change did the trick for me.
Link: <h... |
How do I install pip on Windows? | 4,750,806 | 1,662 | 2011-01-20T18:08:59Z | 11,311,788 | 19 | 2012-07-03T13:17:38Z | [
"python",
"windows",
"pip"
] | pip is a replacement for easy\_install. But should I install pip using easy\_install on Windows? Is there a better way? | ## Installers
I've built Windows installers for both [distribute](http://pypi.python.org/pypi/distribute) and [pip](http://www.pip-installer.org/) here (the goal being to use `pip` without having to either bootstrap with `easy_install` or save and run Python scripts):
* [distribute-0.6.27.win32.exe](http://download.s... |
How do I install pip on Windows? | 4,750,806 | 1,662 | 2011-01-20T18:08:59Z | 12,476,379 | 1,171 | 2012-09-18T11:45:33Z | [
"python",
"windows",
"pip"
] | pip is a replacement for easy\_install. But should I install pip using easy\_install on Windows? Is there a better way? | ## Python 2.7.9+ and 3.4+
Good news! [Python 3.4](https://docs.python.org/3/whatsnew/3.4.html) (released March 2014) and [Python 2.7.9](https://docs.python.org/2/whatsnew/2.7.html#pep-477-backport-ensurepip-pep-453-to-python-2-7) (released December 2014) ship with Pip. This is the best feature of any Python release. I... |
How do I install pip on Windows? | 4,750,806 | 1,662 | 2011-01-20T18:08:59Z | 13,505,059 | 8 | 2012-11-22T02:25:07Z | [
"python",
"windows",
"pip"
] | pip is a replacement for easy\_install. But should I install pip using easy\_install on Windows? Is there a better way? | This is now described at <http://www.pip-installer.org/en/latest/installing.html>.
Be sure that your Windows environment variable PATH includes Python's folders (for Python 2.7.x default install: C:\Python27 and C:\Python27\Scripts, for Python 3.3x: C:\Python33 and C:\Python33\Scripts, etc)
Then download and run <htt... |
How do I install pip on Windows? | 4,750,806 | 1,662 | 2011-01-20T18:08:59Z | 14,407,505 | 144 | 2013-01-18T20:58:21Z | [
"python",
"windows",
"pip"
] | pip is a replacement for easy\_install. But should I install pip using easy\_install on Windows? Is there a better way? | **March 2016 Update:**
These answers are outdated or otherwise wordy and difficult.
If you've got Python 3.4+ or 2.7.9+, it will be [installed by default](https://docs.python.org/3.4/whatsnew/3.4.html#whatsnew-pep-453) on Windows. Otherwise, in short:
1. Download the pip installer:
<https://bootstrap.pypa.io/get-... |
How do I install pip on Windows? | 4,750,806 | 1,662 | 2011-01-20T18:08:59Z | 15,294,806 | 21 | 2013-03-08T13:13:17Z | [
"python",
"windows",
"pip"
] | pip is a replacement for easy\_install. But should I install pip using easy\_install on Windows? Is there a better way? | **Update March 2015**
Python 2.7.9 and later (on the Python 2 series), and Python 3.4 and later include pip by default, so you may have pip already.
If you don't, run this one line command on your prompt (which may require administrator access):
```
python -c "exec('try: from urllib2 import urlopen \nexcept: from ur... |
How do I install pip on Windows? | 4,750,806 | 1,662 | 2011-01-20T18:08:59Z | 15,626,900 | 7 | 2013-03-25T23:46:21Z | [
"python",
"windows",
"pip"
] | pip is a replacement for easy\_install. But should I install pip using easy\_install on Windows? Is there a better way? | The best way I found so far, is just two lines of code:
```
curl http://python-distribute.org/distribute_setup.py | python
curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python
```
It was tested on Windows 8 with [PowerShell](http://en.wikipedia.org/wiki/Windows_PowerShell), Cmd, and [Git](http://en... |
How do I install pip on Windows? | 4,750,806 | 1,662 | 2011-01-20T18:08:59Z | 15,915,700 | 9 | 2013-04-10T02:05:31Z | [
"python",
"windows",
"pip"
] | pip is a replacement for easy\_install. But should I install pip using easy\_install on Windows? Is there a better way? | To use pip, it is not mandatory that you need to install pip in the system directly. You can use it through [`virtualenv`](https://pypi.python.org/pypi/virtualenv). What you can do is follow these steps:
* Download virtualenv tar.gz file from <https://pypi.python.org/pypi/virtualenv>
* Unzip it with 7zip or some other... |
How do I install pip on Windows? | 4,750,806 | 1,662 | 2011-01-20T18:08:59Z | 15,966,898 | 27 | 2013-04-12T08:49:11Z | [
"python",
"windows",
"pip"
] | pip is a replacement for easy\_install. But should I install pip using easy\_install on Windows? Is there a better way? | The up-to-date way is to use Windows' package manager [Chocolatey](http://chocolatey.org/).
Once this is installed, all you have to do is open a command prompt and run the following the three commands below, which will install Python 2.7, easy\_install and pip. It will automatically detect whether you're on x64 or x86... |
How do I install pip on Windows? | 4,750,806 | 1,662 | 2011-01-20T18:08:59Z | 21,182,892 | 35 | 2014-01-17T09:58:34Z | [
"python",
"windows",
"pip"
] | pip is a replacement for easy\_install. But should I install pip using easy\_install on Windows? Is there a better way? | Python 3.4, which was released in March 2014, comes with `pip` included:
<http://docs.python.org/3.4/whatsnew/3.4.html>
So since the release of Python 3.4, the up-to-date way to install pip on Windows is to just install Python.
When sticking to all defaults during installation, pip will be installed to
`C:\Python... |
How do I install pip on Windows? | 4,750,806 | 1,662 | 2011-01-20T18:08:59Z | 21,647,356 | 12 | 2014-02-08T14:41:21Z | [
"python",
"windows",
"pip"
] | pip is a replacement for easy\_install. But should I install pip using easy\_install on Windows? Is there a better way? | The following works for Python 2.7. Save this script and launch it:
<https://raw.github.com/pypa/pip/master/contrib/get-pip.py>
Pip is installed, then add the path to your environment :
```
C:\Python27\Scripts
```
Finally
```
pip install virtualenv
```
Also you need Microsoft [Visual C++ 2008 Express]... |
Identify which iteration you are on in a loop in python | 4,751,092 | 4 | 2011-01-20T18:38:22Z | 4,751,107 | 20 | 2011-01-20T18:40:05Z | [
"python",
"loops",
"dictionary",
"iterator"
] | Basically I would like to be able to tell when I'm on the Nth item in a loop iteration.
Any thoughts?
```
d = {1:2, 3:4, 5:6, 7:8, 9:0}
for x in d:
if last item: # <-- this line is psuedo code
print "last item :", x
else:
print x
``` | Use [`enumerate`](http://docs.python.org/library/functions.html?highlight=enumerate#enumerate):
```
#!/usr/bin/env python
d = {1:2, 3:4, 5:6, 7:8, 9:0}
# If you want an ordered dictionary (and have python 2.7/3.2),
# uncomment the next lines:
# from collections import OrderedDict
# d = OrderedDict(sorted(d.items()... |
How to serve file in webpy? | 4,751,508 | 6 | 2011-01-20T19:21:30Z | 4,751,532 | 10 | 2011-01-20T19:23:45Z | [
"python",
"web.py"
] | I am using webpy framefork. I want to serve static file on one of requests. Is there special method in webpy framework or I just have to read and return that file? | If you are running the dev server (without apache):
> Create a directory (also known as a folder) called static in the location of the script that runs the web.py server. Then place the static files you wish to serve in the static folder.
>
> For example, the URL <http://localhost/static/logo.png> will send the image ... |
Python OverflowError: cannot fit 'long' into an index=sized integer | 4,751,725 | 13 | 2011-01-20T19:39:18Z | 4,754,427 | 9 | 2011-01-21T01:05:38Z | [
"python",
"rsa",
"primes"
] | I want to generate two really large prime numbers using an algorithm I found online and changed slightly.
I get this error on line 5:
```
Python OverflowError: cannot fit 'long' into an index=sized integer
```
My code:
```
import math
def atkin(end):
if end < 2: return []
lng = ((end/2)-1+end%2)
... | The following code demonstrates the problem that you are running into:
```
import sys
x = [True]*(sys.maxint+1)
```
which yields an `OverflowError`. If you instead do:
```
x = [True]*(sys.maxint)
```
then you should get a `MemoryError`.
Here is what is going on. Python can handle arbitrarily large integers with it... |
Proving the primality of strong probable primes | 4,752,190 | 20 | 2011-01-20T20:26:39Z | 4,752,509 | 10 | 2011-01-20T20:58:09Z | [
"python",
"linux",
"algorithm",
"primes"
] | Using the probabilistic version of the Miller-Rabin test, I have generated a list of medium-large (200-300 digit) probable primes. But probable ain't good enough! I need to *know* these numbers are prime. Is there a library -- preferably wrapped or wrappable in Python -- that implements one of the more efficient primal... | As an algorithm that gives a reliable polynomial primality test, consider [AKS](http://en.wikipedia.org/wiki/AKS_primality_test). There is an [older SO article](http://stackoverflow.com/questions/347811/aks-primes-algorithm-in-python) referencing implementations and presentations of the algorithm. |
Proving the primality of strong probable primes | 4,752,190 | 20 | 2011-01-20T20:26:39Z | 4,770,955 | 7 | 2011-01-22T22:11:22Z | [
"python",
"linux",
"algorithm",
"primes"
] | Using the probabilistic version of the Miller-Rabin test, I have generated a list of medium-large (200-300 digit) probable primes. But probable ain't good enough! I need to *know* these numbers are prime. Is there a library -- preferably wrapped or wrappable in Python -- that implements one of the more efficient primal... | I've found that the Pari/GP library and language use APR-CL to prove primality, which is actually the preferred algorithm for numbers in this size range, as it turns out. GP proves a 291-digit candidate prime in under 20 seconds on an atom processor, which is sufficient for my needs, and it comes with a c library that ... |
Opening and using Safari | 4,752,473 | 4 | 2011-01-20T20:54:52Z | 4,752,615 | 9 | 2011-01-20T21:10:39Z | [
"python",
"osx"
] | I am relatively new to the mac world. My question concerns opening an application using python on mac osx. From what I've found so far, it seems as if applications are stored in app format that are actually directories. Are these parsed somehow by the OS when opening the app? I would like to open Safari using python an... | The Python standard library includes the [webbrowser](http://docs.python.org/library/webbrowser.html) module which allows you to open a new browser window or tab in a platform-independent way. It does support Safari on OS X if it is the user's default:
```
>>> import webbrowser
>>> webbrowser.open("http://stackoverflo... |
Python as a web scripting language? | 4,752,574 | 11 | 2011-01-20T21:06:04Z | 4,752,668 | 11 | 2011-01-20T21:15:34Z | [
"php",
"python"
] | I've recently been developing with Python, and I absolutely love it. It's a *huge* step up from PHP as a quick scripting language (imagine, no crazy function names!), and I would love to be able to use it as a web development language.
I've heard about Django, but I want something a bit more simple.
I run Lighttpd, a... | If you want a dead simple but powerful framework, try [Flask](http://flask.pocoo.org/).
(Then learn some [SQLAlchemy](http://www.sqlalchemy.org/), and things will suddenly become even easier.) |
Python IndexError when trying to go through a large list | 4,752,866 | 3 | 2011-01-20T21:33:36Z | 4,752,910 | 7 | 2011-01-20T21:38:00Z | [
"python"
] | I have a list of approximately 200 000+ objects, each one representing a file (but not actually holding the file's contents, just the full path name and date).
The program I am writing copies any subset of these files, depending on the user-provided date range. I first create a list of all of the files in the source d... | From [the docs](http://docs.python.org/tutorial/controlflow.html):
> It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate ... |
Python CSV: Remove quotes from value | 4,753,704 | 6 | 2011-01-20T23:08:21Z | 4,753,831 | 8 | 2011-01-20T23:24:10Z | [
"python",
"csv"
] | I have a process where a CSV file can be downloaded, edited then uploaded again. On the download, the CSV file is in the correct format, with no wrapping double quotes
```
1, someval, someval2
```
When I open the CSV in a spreadsheet, edit and save, it adds double quotes around the strings
```
1, "someEditVal", "som... | For you example, the following works:
```
import csv
writer = csv.writer(open("out.csv", "wb"), quoting=csv.QUOTE_NONE)
reader = csv.reader(open("in.csv", "rb"), skipinitialspace=True)
writer.writerows(reader)
```
You might need to play with the dialect options of the CSV reader and writer -- see the [documentation o... |
Perl equivalent of Python's list comprehensions with the embedded if statement? | 4,753,969 | 5 | 2011-01-20T23:44:35Z | 4,754,029 | 12 | 2011-01-20T23:52:31Z | [
"python",
"perl"
] | In python, I can do the following to get all the objects in a list with a specific property. In this example I grab the list of `id` fields of every `obj` in list `objs` where `obj.id` is greater than 100:
```
ids = [ obj.id for obj in objs if obj.id > 100]
```
How would I do the same in perl? I think I want to use `... | The `map` block can return 0 or more elements for each element in the original list. To omit an element, just return the empty list `()`:
```
my @ids = map { $_->id > 100 ? $_->id : () } @objs;
```
This assumes that the objects in `@objs` have an `id` attribute and associated accessor. If you want direct hash access,... |
django query based on dynamic property() | 4,754,283 | 9 | 2011-01-21T00:38:47Z | 4,755,450 | 7 | 2011-01-21T04:41:54Z | [
"python",
"django",
"django-queryset"
] | I was wondering if there was a way to use Django's filter() on query sets using a dynamically generated python property using `property()`. I have `first_name` and `last_name` of every user, and I want to filter based on their concatenated name `first_name last_name`. (The reason behind this is that when I do autocompl... | `filter()` operates on the database level (it actually writes SQL), so it won't be possible to use it for any queries based on your python code `(dynamic property in your question)`.
This is an answer put together from many other answers in this department : ) |
django query based on dynamic property() | 4,754,283 | 9 | 2011-01-21T00:38:47Z | 19,040,011 | 9 | 2013-09-26T22:53:12Z | [
"python",
"django",
"django-queryset"
] | I was wondering if there was a way to use Django's filter() on query sets using a dynamically generated python property using `property()`. I have `first_name` and `last_name` of every user, and I want to filter based on their concatenated name `first_name last_name`. (The reason behind this is that when I do autocompl... | The accepted answer is not entirely true.
For many cases, you can override `get()` in the model manager to `pop` dynamic properties from the keyword arguments, then add the actual attributes you want to query against into the `kwargs` keyword arguments dictionary. Be sure to return a `super` so any regular `get()` cal... |
How to change metadata on an object in Amazon S3 | 4,754,383 | 30 | 2011-01-21T00:56:57Z | 4,754,439 | 35 | 2011-01-21T01:07:21Z | [
"python",
"amazon-s3",
"boto"
] | If you have already uploaded an object to an Amazon S3 bucket, how do you change the metadata using the API? It is possible to do this in the AWS Management Console, but it is not clear how it could be done programmatically. Specifically, I'm using the boto API in Python and from reading the source it is clear that usi... | It appears you need to overwrite the object with itself, using a "PUT Object (Copy)" with an `x-amz-metadata-directive: REPLACE` header in addition to the metadata. In boto, this can be done like this:
```
k = k.copy(k.bucket.name, k.name, {'myKey':'myValue'}, preserve_acl=True)
```
Note that any metadata you do not ... |
How to change metadata on an object in Amazon S3 | 4,754,383 | 30 | 2011-01-21T00:56:57Z | 16,540,993 | 11 | 2013-05-14T10:37:52Z | [
"python",
"amazon-s3",
"boto"
] | If you have already uploaded an object to an Amazon S3 bucket, how do you change the metadata using the API? It is possible to do this in the AWS Management Console, but it is not clear how it could be done programmatically. Specifically, I'm using the boto API in Python and from reading the source it is clear that usi... | In order to set metadata on S3 files,just don't provide target location as only source information is enough to set metadata.
```
final ObjectMetadata metadata = new ObjectMetadata();
metadata.addUserMetadata(metadataKey, value);
final CopyObjectRequest request = new CopyObjectRequest(bucketName, keyName, bucketName, ... |
DRY way to add created/modified by and time | 4,754,485 | 31 | 2011-01-21T01:14:03Z | 4,754,656 | 7 | 2011-01-21T01:48:04Z | [
"python",
"django"
] | Having something like
* created\_by
* created\_date
* modified\_by
* modified\_date
Would be a very common pattern for a lot of tables.
1) You can set created date automatically (but not others) in model.py with
```
created_date = models.DateTimeField(auto_now_add=True, editable=False)
```
2) You could do created/... | For timestamped models you probably want to look at [django-model-utils](https://github.com/carljm/django-model-utils) or [django-extensions](https://github.com/django-extensions/django-extensions). They each include abstract base classes which automatically handle of a created and last modified timestamp. You can eith... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.