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 |
|---|---|---|---|---|---|---|---|---|---|
Equivalent of 'in' for comparing two Numpy arrays | 4,313,986 | 3 | 2010-11-30T12:55:43Z | 4,314,205 | 8 | 2010-11-30T13:21:19Z | [
"python",
"numpy"
] | In pure, unvectorised, Python I can use,
```
>>> a = 9
>>> b = [5, 7, 12]
>>> a in b
False
```
I would like to do something similar for arrays in Numpy i.e.
```
>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> b = np.array([5, 7, 12])
>>> a in b
np.array([False, False, False, False, True, False, True, False, Fa... | You are looking for [in1d](http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html):
```
>>> import numpy as np
>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> b = np.array([5, 7, 12])
>>> np.in1d( a, b)
array([False, False, False, False, True, False, True, False, False, False], dtype=bool)
``` |
A quickie: python, terminal "print command not found" | 4,315,131 | 3 | 2010-11-30T15:03:30Z | 4,315,158 | 15 | 2010-11-30T15:05:52Z | [
"python",
"osx",
"terminal",
"bbedit",
"textwrangler"
] | Been using terminal to run python scripts written in textwrangler for about 18 months. Decided to look at possibility of moving to an IDE so downloaded a couple of trial versions. Just downloaded BBEedit and suddenly having problems executing script, either from BBedit or Textwrangler. The following code:
```
print "P... | Try putting
```
#!/usr/bin/env python
```
at the top of the script. The program is trying to execute it like a shell script instead of running it through python. |
load csv into 2D matrix with numpy for plotting | 4,315,506 | 33 | 2010-11-30T15:40:22Z | 4,315,914 | 78 | 2010-11-30T16:20:18Z | [
"python",
"arrays",
"csv",
"numpy",
"reshape"
] | Given this CSV file:
```
"A","B","C","D","E","F","timestamp"
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291111964948E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291113113366E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291120650486E12
```
I simply want to load it ... | Pure numpy
```
numpy.loadtxt(open("test.csv","rb"),delimiter=",",skiprows=1)
```
Check out the [loadtxt](http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html#numpy.loadtxt) documentation.
You can also use python's csv module:
```
import csv
import numpy
reader=csv.reader(open("test.csv","rb"),deli... |
How to run the same test-case for different classes? | 4,316,294 | 8 | 2010-11-30T16:55:10Z | 4,316,515 | 8 | 2010-11-30T17:20:00Z | [
"python",
"unit-testing"
] | I have several classes that share some invariants and have a common interface, and I would like to check that for each of them automatically. As an example, suppose I have several classes that implement different approaches for partitioning a data-set. The common invariant here would be, that for all of these classes t... | You could use multiple inheritance.
```
class PartitionerInvariantsFixture(object):
def setUp(self):
self.testDataSet = range(100) # create test-data-set
super(PartitionInvariantsFixture, self).setUp()
def test_partitioner(self):
TestCase.assertEqual(self.testDataSet,
... |
Python: How to resolve URLs containing '..' | 4,317,242 | 5 | 2010-11-30T18:41:19Z | 4,317,446 | 8 | 2010-11-30T19:04:28Z | [
"python",
"url"
] | I need to uniquely identify and store some URLs. The problem is that sometimes they come containing ".." like `http://somedomain.com/foo/bar/../../some/url` which basically is `http://somedomain.com/some/url` if I'm not wrong.
Is there a Python function or a tricky way to resolve this URLs ? | Thereâs a simple solution using [urlparse](http://docs.python.org/library/urlparse.html).urljoin:
```
>>> import urlparse
>>> urlparse.urljoin('http://www.example.com/foo/bar/../../baz/bux/', '.')
'http://www.example.com/baz/bux/'
```
However, if there is no trailing slash (the last component is a file, not a direc... |
Python/Numpy MemoryError | 4,318,615 | 10 | 2010-11-30T21:03:54Z | 4,319,312 | 23 | 2010-11-30T22:22:44Z | [
"python",
"memory",
"numpy",
"scipy"
] | Basically, I am getting a memory error in python when trying to perform an algebraic operation on a numpy matrix. The variable `u`, is a large matrix of double (in the failing case its a 288x288x156 matrix of doubles. I only get this error in this huge case, but I am able to do this on other large matrices, just not th... | Rewrite to
```
p *= alpha
u += p
```
and this will use much less memory. Whereas `p = p*alpha` allocates a whole new matrix for the result of `p*alpha` and then discards the old `p`; `p*= alpha` does the same thing in place.
In general, with big matrices, try to use `op=` assignment. |
Iterating through a scipy.sparse vector (or matrix) | 4,319,014 | 25 | 2010-11-30T21:46:36Z | 4,319,087 | 36 | 2010-11-30T21:57:09Z | [
"python",
"scipy",
"sparse-matrix"
] | I'm wondering what the best way is to iterate nonzero entries of sparse matrices with scipy.sparse. For example, if I do the following:
```
from scipy.sparse import lil_matrix
x = lil_matrix( (20,1) )
x[13,0] = 1
x[15,0] = 2
c = 0
for i in x:
print c, i
c = c+1
```
the output is
```
0
1
2
3
4
5
6
7
8
... | Edit: [bbtrb's method](http://stackoverflow.com/questions/4319014/iterating-through-a-scipy-sparse-vector-or-matrix/4319159#4319159) (using [coo\_matrix](http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.coo_matrix.html#scipy.sparse.coo_matrix)) is much faster than my original suggestion, using [nonzero]... |
Iterating through a scipy.sparse vector (or matrix) | 4,319,014 | 25 | 2010-11-30T21:46:36Z | 4,319,159 | 20 | 2010-11-30T22:05:22Z | [
"python",
"scipy",
"sparse-matrix"
] | I'm wondering what the best way is to iterate nonzero entries of sparse matrices with scipy.sparse. For example, if I do the following:
```
from scipy.sparse import lil_matrix
x = lil_matrix( (20,1) )
x[13,0] = 1
x[15,0] = 2
c = 0
for i in x:
print c, i
c = c+1
```
the output is
```
0
1
2
3
4
5
6
7
8
... | The fastest way should be by converting to a `coo_matrix`:
```
cx = scipy.sparse.coo_matrix(x)
for i,j,v in zip(cx.row, cx.col, cx.data):
print "(%d, %d), %s" % (i,j,v)
``` |
Remove the newline character in a list read from a file | 4,319,236 | 20 | 2010-11-30T22:14:11Z | 4,319,261 | 12 | 2010-11-30T22:17:18Z | [
"python",
"list",
"newline"
] | I have a simple program that takes an ID number and prints information for the person matching the ID. The information is stored in a .dat file, with one ID number per line.
The problem is that my program is also reading the newline character \n from the file. I have tried the 'name'.split() method, but this doesn't s... | You can use the `strip()` function to remove trailing (and leading) whitespace; passing it an argument will let you specify which whitespace:
```
for i in range(len(lists)):
grades.append(lists[i].strip('\n'))
```
---
It looks like you can just simplify the whole block though, since if your file stores one ID pe... |
Remove the newline character in a list read from a file | 4,319,236 | 20 | 2010-11-30T22:14:11Z | 4,319,271 | 45 | 2010-11-30T22:18:39Z | [
"python",
"list",
"newline"
] | I have a simple program that takes an ID number and prints information for the person matching the ID. The information is stored in a .dat file, with one ID number per line.
The problem is that my program is also reading the newline character \n from the file. I have tried the 'name'.split() method, but this doesn't s... | `str.strip()` returns a string with leading+trailing whitespace removed, `.lstrip` and `.rstrip` for only leading and trailing respectively.
```
grades.append(lists[i].rstrip('\n').split(','))
``` |
Python unittest - opposite of assertRaises? | 4,319,825 | 170 | 2010-11-30T23:34:52Z | 4,319,836 | 52 | 2010-11-30T23:37:08Z | [
"python",
"unit-testing"
] | I want to write a test to establish that an Exception is not raised in a given circumstance.
It's straightforward to test if an Exception **is** raised ...
```
sInvalidPath=AlwaysSuppliesAnInvalidPath()
self.assertRaises(PathIsNotAValidOne, MyObject, sInvalidPath)
```
... but how can you do the **opposite**.
Someth... | Just call the function. If it raises an exception, the unit test framework will flag this as an error. You might like to add a comment, e.g.:
```
sValidPath=AlwaysSuppliesAValidPath()
# Check PathIsNotAValidOne not thrown
MyObject(sValidPath)
``` |
Python unittest - opposite of assertRaises? | 4,319,825 | 170 | 2010-11-30T23:34:52Z | 4,319,870 | 159 | 2010-11-30T23:42:55Z | [
"python",
"unit-testing"
] | I want to write a test to establish that an Exception is not raised in a given circumstance.
It's straightforward to test if an Exception **is** raised ...
```
sInvalidPath=AlwaysSuppliesAnInvalidPath()
self.assertRaises(PathIsNotAValidOne, MyObject, sInvalidPath)
```
... but how can you do the **opposite**.
Someth... | ```
try:
myFunc()
except ExceptionType:
self.fail("myFunc() raised ExceptionType unexpectedly!")
``` |
Python unittest - opposite of assertRaises? | 4,319,825 | 170 | 2010-11-30T23:34:52Z | 4,319,998 | 35 | 2010-12-01T00:02:50Z | [
"python",
"unit-testing"
] | I want to write a test to establish that an Exception is not raised in a given circumstance.
It's straightforward to test if an Exception **is** raised ...
```
sInvalidPath=AlwaysSuppliesAnInvalidPath()
self.assertRaises(PathIsNotAValidOne, MyObject, sInvalidPath)
```
... but how can you do the **opposite**.
Someth... | > Hi - I want to write a test to establish that an Exception is not raised in a given circumstance.
That's the default assumption -- exceptions are not raised.
If you say nothing else, that's assumed in every single test.
You don't have to actually write an any assertion for that. |
Python unittest - opposite of assertRaises? | 4,319,825 | 170 | 2010-11-30T23:34:52Z | 4,363,064 | 8 | 2010-12-06T03:55:56Z | [
"python",
"unit-testing"
] | I want to write a test to establish that an Exception is not raised in a given circumstance.
It's straightforward to test if an Exception **is** raised ...
```
sInvalidPath=AlwaysSuppliesAnInvalidPath()
self.assertRaises(PathIsNotAValidOne, MyObject, sInvalidPath)
```
... but how can you do the **opposite**.
Someth... | I am the original poster and I accepted the above answer by DGH without having first used it in the code.
Once I did use I realised that it needed a little tweaking to actually do what I needed it to do (to be fair to DGH he/she did say "or something similar" !).
I thought it was worth posting the tweak here for the ... |
Matplotlib transparent line plots | 4,320,021 | 49 | 2010-12-01T00:05:16Z | 4,320,275 | 10 | 2010-12-01T00:53:01Z | [
"python",
"matplotlib",
"scientific-computing"
] | I am plotting two similar trajectories in matplotlib and I'd like to plot each of the lines with partial transparency so that the red (plotted second) doesn't obscure the blue.

**EDIT**: Here's the image with transparent lines.
.lines:
l.set_alpha(.7)
```
**EDIT:** please see Joe's answer in the comments. |
Matplotlib transparent line plots | 4,320,021 | 49 | 2010-12-01T00:05:16Z | 22,412,921 | 61 | 2014-03-14T18:24:21Z | [
"python",
"matplotlib",
"scientific-computing"
] | I am plotting two similar trajectories in matplotlib and I'd like to plot each of the lines with partial transparency so that the red (plotted second) doesn't obscure the blue.

**EDIT**: Here's the image with transparent lines.

```
(I know I add nothing new, but the straightforward answer should be visible). |
Extending Numpy with C function | 4,320,133 | 2 | 2010-12-01T00:25:40Z | 4,320,706 | 7 | 2010-12-01T02:31:53Z | [
"python",
"c",
"numpy",
"swig",
"cython"
] | I am trying to speed up my Numpy code and decided that I wanted to implement one particular function where my code spent most of the time in C.
I'm actually a rookie in C, but I managed to write the function which normalizes every row in a matrix to sum to 1. I can compile it and I tested it with some data (in C) and ... | Unless you have a really good reason not to, you should use cython to interface C and python. (We are starting to use cython instead of raw C inside numpy/scipy themselves).
You can see a simple example in my scikits [talkbox](https://github.com/cournape/talkbox) (since cython has improved quite a bit since then, I th... |
Django: Display Choice Value | 4,320,679 | 105 | 2010-12-01T02:25:39Z | 4,321,512 | 234 | 2010-12-01T05:36:25Z | [
"python",
"django"
] | Model:
```
class Person(models.Model):
name = models.CharField(max_length=200)
CATEGORY_CHOICES = (
('M','Male'),
('F','Female'),
)
gender = models.CharField(max_length=200, choices = CATEGORY_CHOICES)
to_be_listed = models.BooleanField(default=True)
description ... | It looks like you were on the right track - [get\_FOO\_display()](http://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.get_FOO_display) is most certainly what you want:
In templates, you don't include () in the name of a method. Do the following:
```
{{ person.get_gender_display }}
``` |
How do I write a decorator for my Django/Python view? | 4,320,703 | 3 | 2010-12-01T02:31:16Z | 4,320,739 | 11 | 2010-12-01T02:40:33Z | [
"python",
"django",
"http",
"request",
"decorator"
] | Here's my view. Basically, it returns different Responses based on whether it's logged in or not.
```
@check_login()
def home(request):
if is_logged_in(request):
return x
else:
return y
```
Here's my decorator code. I just want to check if the request has headers, and if so, log him in.
```
... | Use only `@check_login` instead of `check_login()` - otherwise your decorator has to return a decorate as you are doing `home = check_login()(home)`
Here's an example decorator:
```
def check_login(method):
@functools.wraps(method)
def wrapper(request, *args, **kwargs):
if request.META['username'] == ... |
How to set border color of certain Tkinter widgets? | 4,320,725 | 11 | 2010-12-01T02:38:36Z | 4,321,115 | 23 | 2010-12-01T04:10:29Z | [
"python",
"colors",
"tkinter",
"tcl",
"border"
] | I'm trying to change the background color of my Tkinter app, but for certain widgets it leaves a white border around the edges.
For example, this:
```
from tkinter import *
COLOR = "black"
root = Tk()
root.config(bg=COLOR)
button = Button(text="button", bg=COLOR)
button.pack(padx=5, pady=5)
entry = Entry(bg=COLOR,... | Turns out that wasn't nearly as hard as defining a custom style.
Just use: `widget.config(highlightbackground=COLOR)` |
importError: no module named _winreg python3 | 4,320,761 | 7 | 2010-12-01T02:47:41Z | 4,320,793 | 15 | 2010-12-01T02:53:27Z | [
"python",
"cx-freeze",
"winreg"
] | Where can I download \_winreg for python3 if I can at all. I have my 'windir' on E:\Windows. I do not know if cx\_Freeze did not notice that. I am using cx\_Freeze to create an msi installer. | As it says in the [\_winreg documentation](http://docs.python.org/library/_winreg.html), it has been renamed to `winreg` in Python 3.0. You should run the [2to3](http://docs.python.org/glossary.html#term-to3) tool if you're converting code that was written for Python 2.x. |
Split a list into nested lists on a value | 4,322,705 | 19 | 2010-12-01T09:06:42Z | 4,322,780 | 27 | 2010-12-01T09:16:16Z | [
"python",
"list-comprehension",
"nested-lists"
] | Say I have a list like so:
```
[1, 4, None, 6, 9, None, 3, 9, 4 ]
```
I decide to split this into nested lists on `None`, to get this:
```
[ [ 1, 4 ], [ 6, 9 ], [ 3, 9, 4 ] ]
```
Of course, I could have wanted to do this on `(9, None)` in which case, we would have got:
```
[ [ 1, 4 ], [ 6 ], [ 3 ], [ 4 ] ]
```
Th... | ```
>>> def isplit(iterable,splitters):
return [list(g) for k,g in itertools.groupby(iterable,lambda x:x in splitters) if not k]
>>> isplit(L,(None,))
[[1, 4], [6, 9], [3, 9, 4]]
>>> isplit(L,(None,9))
[[1, 4], [6], [3], [4]]
```
benchmark code:
```
import timeit
kabie=("isplit_kabie",
"""
import itertools
... |
Set timezone to EST in Google App Engine (Python) | 4,323,908 | 2 | 2010-12-01T11:36:38Z | 4,324,529 | 7 | 2010-12-01T12:50:39Z | [
"python",
"google-app-engine"
] | Can anyone advise how I change the timezone for my google app engine application? It's running python, I need to set the timezone so all datetime.now() etc work on EST timezone instead of the default?
Thanks! | Have a look at <http://timezones.appspot.com/>
You can not make `datetime.now()` to use your custom time zone but you can convert time as per your requirements. |
Loop with conditions in python | 4,323,946 | 7 | 2010-12-01T11:40:34Z | 4,323,992 | 7 | 2010-12-01T11:46:01Z | [
"coding-style",
"python",
"idioms",
"idiomatic"
] | Consider the following code in C:
```
for(int i=0; i<10 && some_condition; ++i){
do_something();
}
```
I would like to write something similar in Python. The best version I can think of is:
```
i = 0
while some_condition and i<10:
do_something()
i+=1
```
Frankly, I don't like `while` loops that imitate ... | In general, the "`range` + `break`" style is preferred - but in Python 2.x, use `xrange` instead of `range` for iteration (this creates the values on-demand instead of actually making a list of numbers).
But it always depends. What's special about the number 10 in this context? What exactly is `some_condition`? Etc.
... |
Loop with conditions in python | 4,323,946 | 7 | 2010-12-01T11:40:34Z | 4,324,061 | 7 | 2010-12-01T11:55:09Z | [
"coding-style",
"python",
"idioms",
"idiomatic"
] | Consider the following code in C:
```
for(int i=0; i<10 && some_condition; ++i){
do_something();
}
```
I would like to write something similar in Python. The best version I can think of is:
```
i = 0
while some_condition and i<10:
do_something()
i+=1
```
Frankly, I don't like `while` loops that imitate ... | This might not be related, but there's what I'm used to do... If `some_condition` is simple enough, put it in a function and `filter` items you iterate over:
```
def some_condition(element):
return True#False
for i in filter(some_condition, xrange(10)):
pass
```
You can use this approach also when you iterat... |
How to integrate Redis with SQLAlchemy | 4,324,407 | 7 | 2010-12-01T12:36:41Z | 4,331,070 | 11 | 2010-12-02T02:16:04Z | [
"python",
"sqlalchemy",
"nosql",
"redis"
] | I'm learning to use SQLAlchemy connected to a SQL database for 12 standard relational tables (e.g. SQLite or PostgreSQL). But then I'd like to use Redis with Python for a couple of tables, particularly for Redis's fast set manipulation. I realise that Redis is NoSQL, but can I integrate this with SQLAlchemy for the ben... | While it is possible to set up an ORM that puts data in redis, it isn't a particularly good idea. ORMs are designed to expose standard SQL features. Many things that are standard in SQL such as querying on arbitrary columns are not available in redis unless you do a lot of extra work. At the same time redis has feature... |
How to integrate Redis with SQLAlchemy | 4,324,407 | 7 | 2010-12-01T12:36:41Z | 4,332,791 | 8 | 2010-12-02T07:44:39Z | [
"python",
"sqlalchemy",
"nosql",
"redis"
] | I'm learning to use SQLAlchemy connected to a SQL database for 12 standard relational tables (e.g. SQLite or PostgreSQL). But then I'd like to use Redis with Python for a couple of tables, particularly for Redis's fast set manipulation. I realise that Redis is NoSQL, but can I integrate this with SQLAlchemy for the ben... | Redis is a very good at what he does, storing key values and making simple atomic
operations, but if you want to use it as a relational database you really are gonna SUFFER!, as I had... and here is my story...
I've do something like that, making several objects to abstracting all the redis internals exposing primitiv... |
What's the proper way to install pip, virtualenv, and distribute for Python? | 4,324,558 | 217 | 2010-12-01T12:54:48Z | 4,325,047 | 19 | 2010-12-01T13:55:07Z | [
"python",
"virtualenv",
"setuptools",
"distribute"
] | ## Short Question
* What is the proper way to install [`pip`](http://pip.readthedocs.org), [`virtualenv`](http://virtualenv.openplans.org/), and [`distribute`](http://packages.python.org/distribute/)?
## Background
In [my answer](http://stackoverflow.com/questions/4314376/python-egg-file/4314446#4314446) to [SO ques... | I think Glyph means do something like this:
1. Create a directory `~/.local`, if it doesn't already exist.
2. In your `~/.bashrc`, ensure that `~/.local/bin` is on `PATH` and that `~/.local` is on `PYTHONPATH`.
3. Create a file `~/.pydistutils.cfg` which contains
```
[install]
prefix=~/.local
```
It's... |
What's the proper way to install pip, virtualenv, and distribute for Python? | 4,324,558 | 217 | 2010-12-01T12:54:48Z | 5,177,027 | 157 | 2011-03-03T05:30:49Z | [
"python",
"virtualenv",
"setuptools",
"distribute"
] | ## Short Question
* What is the proper way to install [`pip`](http://pip.readthedocs.org), [`virtualenv`](http://virtualenv.openplans.org/), and [`distribute`](http://packages.python.org/distribute/)?
## Background
In [my answer](http://stackoverflow.com/questions/4314376/python-egg-file/4314446#4314446) to [SO ques... | You can do this without installing **anything** into python itself.
You don't need sudo or any privileges.
You don't need to edit any files.
Install virtualenv into a bootstrap virtual environment. Use the that virtual environment to create more. Since virtualenv ships with pip and distribute, you get everything fro... |
What's the proper way to install pip, virtualenv, and distribute for Python? | 4,324,558 | 217 | 2010-12-01T12:54:48Z | 14,718,550 | 15 | 2013-02-05T22:56:02Z | [
"python",
"virtualenv",
"setuptools",
"distribute"
] | ## Short Question
* What is the proper way to install [`pip`](http://pip.readthedocs.org), [`virtualenv`](http://virtualenv.openplans.org/), and [`distribute`](http://packages.python.org/distribute/)?
## Background
In [my answer](http://stackoverflow.com/questions/4314376/python-egg-file/4314446#4314446) to [SO ques... | If you follow the steps advised in several tutorials I linked in [this answer](http://stackoverflow.com/a/14717552/544059), you
can get the desired effect without the somewhat complicated "manual" steps in Walker's and Vinay's answers. If you're on Ubuntu:
```
sudo apt-get install python-pip python-dev
```
The equiva... |
What's the proper way to install pip, virtualenv, and distribute for Python? | 4,324,558 | 217 | 2010-12-01T12:54:48Z | 17,339,129 | 8 | 2013-06-27T09:11:03Z | [
"python",
"virtualenv",
"setuptools",
"distribute"
] | ## Short Question
* What is the proper way to install [`pip`](http://pip.readthedocs.org), [`virtualenv`](http://virtualenv.openplans.org/), and [`distribute`](http://packages.python.org/distribute/)?
## Background
In [my answer](http://stackoverflow.com/questions/4314376/python-egg-file/4314446#4314446) to [SO ques... | On Ubuntu:
`sudo apt-get install python-virtualenv`
The package `python-pip` is a dependency, so it will be installed as well. |
What's the proper way to install pip, virtualenv, and distribute for Python? | 4,324,558 | 217 | 2010-12-01T12:54:48Z | 21,456,786 | 11 | 2014-01-30T12:38:57Z | [
"python",
"virtualenv",
"setuptools",
"distribute"
] | ## Short Question
* What is the proper way to install [`pip`](http://pip.readthedocs.org), [`virtualenv`](http://virtualenv.openplans.org/), and [`distribute`](http://packages.python.org/distribute/)?
## Background
In [my answer](http://stackoverflow.com/questions/4314376/python-egg-file/4314446#4314446) to [SO ques... | ## Python 3.4 onward
Python 3.3 adds the [venv module](http://docs.python.org/3.4/library/venv.html), and Python 3.4 adds the [ensurepip module](http://docs.python.org/3.4/library/ensurepip.html). This makes bootstrapping pip as easy as:
> python -m ensurepip
Perhaps preceded by a call to `venv` to do so inside a vi... |
Removing control characters from a string in python | 4,324,790 | 17 | 2010-12-01T13:25:52Z | 4,324,823 | 15 | 2010-12-01T13:30:31Z | [
"python",
"string",
"python-3.x"
] | I currently have the following code
```
def removeControlCharacters(line):
i = 0
for c in line:
if (c < chr(32)):
line = line[:i - 1] + line[i+1:]
i += 1
return line
```
This is just does not work if there are more than one character to be deleted. | You could use [`str.translate`](http://docs.python.org/library/stdtypes.html#str.translate) with the appropriate map, for example like this:
```
>>> mpa = dict.fromkeys(range(32))
>>> 'abc\02de'.translate(mpa)
'abcde'
``` |
Removing control characters from a string in python | 4,324,790 | 17 | 2010-12-01T13:25:52Z | 19,016,117 | 39 | 2013-09-25T22:17:35Z | [
"python",
"string",
"python-3.x"
] | I currently have the following code
```
def removeControlCharacters(line):
i = 0
for c in line:
if (c < chr(32)):
line = line[:i - 1] + line[i+1:]
i += 1
return line
```
This is just does not work if there are more than one character to be deleted. | There are *hundreds* of control characters in unicode. If you are sanitizing data from the web or some other source that might contain non-ascii characters, you will need Python's [unicodedata module](http://docs.python.org/2/library/unicodedata.html). The `unicodedata.category(â¦)` function returns the [unicode categ... |
Save a subplot in matplotlib | 4,325,733 | 17 | 2010-12-01T15:09:38Z | 4,328,608 | 35 | 2010-12-01T20:10:19Z | [
"python",
"matplotlib"
] | is it possible to save (to a png) an individual subplot in a matplotlib figure? Lets say I have
```
import pylab as p
ax1 = subplot(121)
ax2 = subplot(122)
ax.plot([1,2,3],[4,5,6])
ax.plot([3,4,5],[7,8,9])
```
Is it possible to save each of the two subplots to different files or at least copy them separately to a new... | While @Eli is quite correct that there usually isn't much of a need to do it, it is possible. `savefig` takes a `bbox_inches` argument that can be used to selectively save only a portion of a figure to an image.
Here's a quick example:
```
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
#... |
Save a subplot in matplotlib | 4,325,733 | 17 | 2010-12-01T15:09:38Z | 26,432,947 | 8 | 2014-10-17T20:26:10Z | [
"python",
"matplotlib"
] | is it possible to save (to a png) an individual subplot in a matplotlib figure? Lets say I have
```
import pylab as p
ax1 = subplot(121)
ax2 = subplot(122)
ax.plot([1,2,3],[4,5,6])
ax.plot([3,4,5],[7,8,9])
```
Is it possible to save each of the two subplots to different files or at least copy them separately to a new... | Applying the `full_extent()` function in an answer by @Joe 3 years later from [here](http://stackoverflow.com/a/14720600), you can get exactly what the OP was looking for. Alternatively, you can use `Axes.get_tightbbox()` which gives a little tighter bounding box
```
import matplotlib.pyplot as plt
import matplotlib a... |
Create default values for dictionary in python | 4,326,119 | 12 | 2010-12-01T15:46:03Z | 4,326,140 | 22 | 2010-12-01T15:49:11Z | [
"python",
"coding-style",
"performance"
] | Let's have a method that would cache results it calculates.
**"If" approach**:
```
def calculate1(input_values):
if input_values not in calculate1.cache.keys():
# do some calculation
result = input_values
calculate1.cache[input_values] = result
return calculate1.cache[input_values]
cal... | Use a [collections.defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict). It's designed precisely for this purpose. |
Solve this equation with fixed point iteration | 4,326,419 | 5 | 2010-12-01T16:17:56Z | 4,326,491 | 8 | 2010-12-01T16:24:33Z | [
"python",
"equation",
"fixed-point",
"nonlinear-functions",
"numerical-analysis"
] | How can I solve this equation
> x3 + x - 1 = 0
using fixed point iteration?
Is there any *fixed-point iteration* code (especially in Python) I can find online? | Using [scipy.optimize.fixed\_point](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fixed_point.html#scipy-optimize-fixed-point):
```
import scipy.optimize as optimize
def func(x):
return -x**3+1
# This finds the value of x such that func(x) = x, that is, where
# -x**3 + 1 = x
print(optimize.f... |
Can I count on order being preserved in a Python tuple? | 4,326,553 | 10 | 2010-12-01T16:30:22Z | 4,326,606 | 11 | 2010-12-01T16:35:25Z | [
"python",
"list",
"tuples"
] | I've got a list of datetimes from which I want to construct time segments. In other words, turn `[t0, t1, ... tn]` into `[(t0,t1),(t1,t2),...,(tn-1, tn)]`. I've done it this way:
```
# start by sorting list of datetimes
mdtimes.sort()
# construct tuples which represent possible start and end dates
# left edges
dtg0 =... | 1. Tuple order is as you insert values into the tuple. They're not going to be sorted as I think you're asking. `zip` will again, retain the order you inserted the values in.
2. It's an acceptable method, but I have 2 alternate suggestions: Use the [copy](http://docs.python.org/library/copy.html) module, or use `dtg1 =... |
Can I count on order being preserved in a Python tuple? | 4,326,553 | 10 | 2010-12-01T16:30:22Z | 4,326,624 | 12 | 2010-12-01T16:36:28Z | [
"python",
"list",
"tuples"
] | I've got a list of datetimes from which I want to construct time segments. In other words, turn `[t0, t1, ... tn]` into `[(t0,t1),(t1,t2),...,(tn-1, tn)]`. I've done it this way:
```
# start by sorting list of datetimes
mdtimes.sort()
# construct tuples which represent possible start and end dates
# left edges
dtg0 =... | Both `list` and `tuple` are ordered.
```
dtg0, dtg1 = itertools.tee(mdtimes)
next(dtg0)
dtsegs = zip(dtg0, dtg1)
``` |
Python: Index a Dictionary? | 4,326,658 | 24 | 2010-12-01T16:40:16Z | 4,326,729 | 43 | 2010-12-01T16:46:56Z | [
"python",
"dictionary",
"indexing"
] | I have a Dictionary below:
```
dict = {
"blue" : "5"
"red" : "6"
"yellow" : "8"
}
```
How do I index the first entry in the dictionary?
`dict[0]` will return a `KeyError` for obvious reasons. | Dictionaries are unordered in Python. If you do not care about the order of the entries and want to access the keys or values by index anyway, you can use `d.keys()[i]` and `d.values()[i]` or `d.items()[i]`. (Note that these methods create a list of all keys, values or items, respectively. So if you need them more then... |
Solving equation using bisection method | 4,326,667 | 7 | 2010-12-01T16:40:51Z | 4,326,752 | 11 | 2010-12-01T16:48:41Z | [
"python",
"numerical-analysis",
"bisection"
] | Is there a bisection method I can find online, specifically for python?
For example, given these equations how can I solve them using the bisection method?
```
x^3 = 9
3 * x^3 + x^2 = x + 5
cos^2x + 6 = x
``` | Using [scipy.optimize.bisect](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.bisect.html#scipy.optimize.bisect):
```
import scipy.optimize as optimize
import numpy as np
def func(x):
return np.cos(x)**2 + 6 - x
# 0<=cos(x)**2<=1, so the root has to be between x=6 and x=7
print(optimize.bisect... |
Best way for a beginner to learn screen scraping by Python | 4,328,271 | 27 | 2010-12-01T19:31:56Z | 4,328,400 | 10 | 2010-12-01T19:46:15Z | [
"python",
"screen-scraping",
"beautifulsoup",
"lxml",
"scrapy"
] | This might be one of those questions that are difficult to answer, but here goes:
I don't consider my self programmer - but I would like to :-) I've learned R, because I was sick and tired of spss, and because a friend introduced me to the language - so I am not a complete stranger to programming logic.
Now I would l... | Looks like Scrappy is using XPATH for DOM traversal, which is a language itself and may feel somewhat cryptic for some time. I think BeautifulSoup will give you a faster start. With lxml you'll have to invest more time learning, but it generally considered (not only by me) a better alternative to BeautifulSoup.
For da... |
Best way for a beginner to learn screen scraping by Python | 4,328,271 | 27 | 2010-12-01T19:31:56Z | 4,328,504 | 42 | 2010-12-01T19:58:48Z | [
"python",
"screen-scraping",
"beautifulsoup",
"lxml",
"scrapy"
] | This might be one of those questions that are difficult to answer, but here goes:
I don't consider my self programmer - but I would like to :-) I've learned R, because I was sick and tired of spss, and because a friend introduced me to the language - so I am not a complete stranger to programming logic.
Now I would l... | I agree that the Scrapy docs give off that impression. But, I believe, as I found for myself, that if you are patient with Scrapy, and go through the tutorials first, and then bury yourself into the rest of the documentation, you will not only start to understand the different parts to Scrapy better, but you will appre... |
Generating a graph with certain degree distribution? | 4,328,837 | 6 | 2010-12-01T20:33:53Z | 4,329,371 | 7 | 2010-12-01T21:32:11Z | [
"python",
"algorithm",
"graph",
"networkx"
] | I am trying to generate a random graph that has small-world properties (exhibits a power law distribution). I just started using the networkx package and discovered that it offers a variety of random graph generation. Can someone tell me if it possible to generate a graph where a given node's degree follows a gamma dis... | If you want to use the configuration model something like this should work in NetworkX:
```
import random
import networkx as nx
z=[int(random.gammavariate(alpha=9.0,beta=2.0)) for i in range(100)]
G=nx.configuration_model(z)
```
You might need to adjust the mean of the sequence z depending on parameters in the gamma... |
What's the fastest way to loop through a list and create a single string? | 4,329,022 | 2 | 2010-12-01T20:53:22Z | 4,329,059 | 8 | 2010-12-01T20:57:18Z | [
"python",
"nested-lists"
] | For example:
```
list = [{"title_url": "joe_white", "id": 1, "title": "Joe White"},
{"title_url": "peter_black", "id": 2, "title": "Peter Black"}]
```
How can I efficiently loop through this to create:
```
Joe White, Peter Black
<a href="/u/joe_white">Joe White</a>,<a href="/u/peter_black">Peter Black</a>
``... | The first is pretty simple:
```
', '.join(item['title'] for item in list)
```
The second requires something more complicated, but is essentially the same:
```
','.join('<a href="/u/%(title_url)s">%(title)s</a>' % item for item in list)
```
Both use [generator expressions](http://www.python.org/dev/peps/pep-0289/), ... |
Handle specific exception type in python | 4,329,453 | 11 | 2010-12-01T21:42:29Z | 4,329,501 | 17 | 2010-12-01T21:47:52Z | [
"python",
"exception",
"exception-handling"
] | I have some code that handles an exception, and I want to do something specific only if it's a specific exception, and only in debug mode. So for example:
```
try:
stuff()
except Exception as e:
if _debug and e is KeyboardInterrupt:
sys.exit()
logging.exception("Normal handling")
```
As such, I do... | This is pretty much the way it's done.
```
try:
stuff()
except KeyboardInterrupt:
if _debug:
sys.exit()
logging.exception("Normal handling")
except Exception as e:
logging.exception("Normal handling")
```
There's minimal repetition. Not zero, however, but minimal.
If the "normal handling" is ... |
Handle specific exception type in python | 4,329,453 | 11 | 2010-12-01T21:42:29Z | 4,329,513 | 12 | 2010-12-01T21:49:29Z | [
"python",
"exception",
"exception-handling"
] | I have some code that handles an exception, and I want to do something specific only if it's a specific exception, and only in debug mode. So for example:
```
try:
stuff()
except Exception as e:
if _debug and e is KeyboardInterrupt:
sys.exit()
logging.exception("Normal handling")
```
As such, I do... | Well, really, you probably should keep the handler for `KeyboardInterrupt` separated. Why would you only want to handle keyboard interrupts in debug mode, but swallow them otherwise?
That said, you can use `isinstance` to check the type of an object:
```
try:
stuff()
except Exception as e:
if _debug and isins... |
Python thread daemon property | 4,330,111 | 17 | 2010-12-01T23:13:47Z | 4,330,156 | 18 | 2010-12-01T23:19:19Z | [
"python",
"multithreading",
"daemon"
] | I'm a little confused about what setting a thread to be a daemon means. The documentation says this:
> A thread can be flagged as a âdaemon
> threadâ. The significance of this flag
> is that the entire Python program
> exits when only daemon threads are
> left. The initial value is inherited
> from the creating th... | > Is this saying that this program won't ever finish?
Yes, that program won't finish, just try it out.
> I ask because I have a situation where
> in my main thread I'm calling
> sys.exit(), and the process just hangs
> and my other threads are running as I
> can see the log. Does this have
> anything to do with sys.e... |
Python thread daemon property | 4,330,111 | 17 | 2010-12-01T23:13:47Z | 4,330,186 | 9 | 2010-12-01T23:24:41Z | [
"python",
"multithreading",
"daemon"
] | I'm a little confused about what setting a thread to be a daemon means. The documentation says this:
> A thread can be flagged as a âdaemon
> threadâ. The significance of this flag
> is that the entire Python program
> exits when only daemon threads are
> left. The initial value is inherited
> from the creating th... | Setting `thread.daemon = True` will allow the main program to exit. Apps normally wait till all child threads are finished before completing. |
how do I clear a stringio object? | 4,330,812 | 29 | 2010-12-02T01:16:44Z | 4,330,829 | 51 | 2010-12-02T01:20:15Z | [
"python",
"stringio"
] | I have a stringio object created and it has some text in it. I'd like to clear its existing values and reuse it instead of recalling it. Is there anyway of doing this? | # TL;DR
Don't bother clearing it, just create a new oneâitâs faster.
# The method
## Python 2
Here's how I would find such things out:
```
>>> from StringIO import StringIO
>>> dir(StringIO)
['__doc__', '__init__', '__iter__', '__module__', 'close', 'flush', 'getvalue', 'isatty', 'next', 'read', 'readline', 'r... |
Persistent objects in recursive python functions | 4,331,006 | 2 | 2010-12-02T02:03:53Z | 4,331,045 | 9 | 2010-12-02T02:11:26Z | [
"python",
"recursion",
"persistent"
] | I am trying to write a recursive function that needs to store and modify an object (say a set) as it recurses. Should I use a global name inside the function? Another option is to modify or inherit the class of the parameter of the function so that it can keep this persistent object but I don't find it elegant. I could... | Just pass through your persistent object through the recursive method.
```
def recursivemethod(obj_to_act_on, persistent_obj=None):
if persistent_obj == None:
persistent_obj = set()
# Act on your object
return recursivemethod(newobj, persistent_obj)
``` |
Calling Python functions from C++ | 4,331,599 | 12 | 2010-12-02T04:13:15Z | 4,337,552 | 12 | 2010-12-02T16:52:01Z | [
"c++",
"python",
"callback",
"boost-python"
] | I am trying to achieve call Python functions from C++. I thought it could be achieved through function pointers, but it does not seem to be possible. I have been using `boost.python` to accomplish this.
Say there is a function defined in Python:
```
def callback(arg1, arg2):
#do something
return something
```... | If it might have any name:
Pass it to a function that takes a `boost::python::object`.
```
bp::object pycb; //global variable. could also store it in a map, etc
void register_callback(bp::object cb)
{
pycb = cb;
}
```
If it is in a single known namespace with a consistent name:
```
bp::object pycb = bp::scope... |
Python: sort this dictionary (dict in dict) | 4,331,892 | 11 | 2010-12-02T05:11:39Z | 4,331,932 | 15 | 2010-12-02T05:18:39Z | [
"python",
"sorting",
"dictionary"
] | ```
d = { 'a':{'k':1, 'b':'whatever'}, 'b':{'k':2, 'b':'sort by k'} }
```
Want to sort this dictionary by k as descending order, in python.
Little tricky, please help. | `dict`s are unordered. So there is no way to sort them directly, but if you are
willing to convert the `dict` into a list of (key,value)-tuples, then you could do this:
```
In [9]: d
Out[9]: {'a': {'b': 'whatever', 'k': 1}, 'b': {'b': 'sort by k', 'k': 2}}
In [15]: sorted(d.items(),key=lambda x: x[1]['k'],reverse=Tru... |
Read the current text color in a xterm | 4,332,478 | 14 | 2010-12-02T06:59:39Z | 4,332,530 | 53 | 2010-12-02T07:07:19Z | [
"python",
"bash",
"xterm"
] | I'm writing various utilities, and I'm really liking colorized text. Nothing fancy, just using escape sequences. I've created a simple class that has a pprint(msg, color) function. I've got it working rather easily after finding the codes [here](http://www.pixelbeat.org/docs/terminal_colours/).
The problem that I'm ha... | Rather than using obfuscated escape sequences, use the `tput` facility instead. Here is an excerpt from my `~/.bashrc` that I use for my PS1 prompt:
```
BLACK=$(tput setaf 0)
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW=$(tput setaf 3)
LIME_YELLOW=$(tput setaf 190)
POWDER_BLUE=$(tput setaf 153)
BLUE=$(tput setaf 4... |
R as a general purpose programming language | 4,333,094 | 14 | 2010-12-02T08:37:00Z | 4,333,674 | 20 | 2010-12-02T10:00:44Z | [
"python",
"wiki",
"language-features"
] | I liked Python before because Python has rich built-in types like sets, dicts, lists, tuples. These structures help write short scripts to process data.
On the other side, R is like Matlab, and has scalar, vector, data frame, array and list as its data types. But it lacks sets, dicts, tuples, etc. I know that list typ... | I think that R's data pre-processing capability--i.e., everything from extracting data from its source and just before the analytics steps--has improved substantially in the past three years (the length of time i have been using R). I use python daily and have for the past seven years or so--its text-processing capabil... |
python sort list of lists with casting | 4,333,373 | 14 | 2010-12-02T09:18:45Z | 4,333,405 | 18 | 2010-12-02T09:22:55Z | [
"python",
"sorting"
] | I know tat similar questions has been asked already several times. And i do now how to use the search function, but it still does not work.
So here is the problem setup. I have a list of lists containing strings. One column contains strings which actually represent float values. And it is also the column i want to sor... | ```
l = [["blaa", "0.3", "bli"], ["bla", "0.1", "blub"], ["bla", "-0.2", "blub"]]
l.sort(key=lambda x: float(x[1]))
>>> [['bla', '-0.2', 'blub'], ['bla', '0.1', 'blub'], ['blaa', '0.3', 'bli']]
``` |
How to serialize/deserialized pybrain networks? | 4,334,941 | 8 | 2010-12-02T12:25:35Z | 4,336,001 | 10 | 2010-12-02T14:24:15Z | [
"python",
"serialization",
"neural-network",
"pickle"
] | [PyBrain](http://www.pybrain.org/) is a python library that provides (among other things) easy to use Artificial Neural Networks.
I fail to properly serialize/deserialize PyBrain networks using either pickle or cPickle.
See the following example:
```
from pybrain.datasets import SupervisedDataSet
from pyb... | **Cause**
The mechanism that causes this behavior is the handling of parameters (`.params`) and derivatives (`.derivs`) in PyBrain modules: in fact, all network parameters are stored in one array, but the individual `Module` or `Connection` objects have access to "their own" `.params`, which, however are just a view o... |
How can I create a numpy .npy file in place on disk? | 4,335,289 | 10 | 2010-12-02T13:03:47Z | 4,620,395 | 9 | 2011-01-06T22:02:02Z | [
"python",
"numpy"
] | Is it possible to create an .npy file without allocating the corresponding array in memory first?
I need to create and work with a large numpy array, too big to create in memory. Numpy supports memory mapping, but as far as I can see my options are either:
1. Create a memmapped file using numpy.memmap. This creates t... | I had the same question and was disappointed when I read Sven's reply. Seems as though numpy would be missing out on some key functionality if you couldn't have a huge array on file and work on little pieces of it at a time. Your case seems to be close to one of the use cases in the origional rational for making the .n... |
Wrap subprocess' stdout/stderr | 4,335,587 | 4 | 2010-12-02T13:37:46Z | 4,335,903 | 11 | 2010-12-02T14:15:13Z | [
"python",
"subprocess",
"stdout",
"iostream",
"stderr"
] | I'd like to both capture and display the output of a process that I invoke through Python's subprocess.
I thought I could just pass my file-like object as named parameter stdout and stderr
I can see that it accesses the `fileno`attribute - so it is doing something with the object.
However, the `write()` method is nev... | Stdin, stdout and stderr of a process need to be real file descriptors. (That is actually not a restriction imposed by Python, but rather how pipes work on the OS level.) So you will need a different solution.
If you want to track both `stdout` an `stderr` in real time, you will need asynchronous I/O or threads.
* **... |
MX Record lookup and check | 4,336,849 | 6 | 2010-12-02T15:48:57Z | 4,336,990 | 10 | 2010-12-02T16:01:50Z | [
"python",
"mx-record"
] | I need to create a tool that will check a domains live mx records against what should be expected (we have had issues with some of our staff fiddling with them and causing all incoming mail to redirected into the void)
Now I won't lie, I'm not a competent programmer in the slightest! I'm about 40 pages into "dive into... | Take a look at [dnspython](http://www.dnspython.org/), a module that should do the lookups for you just fine without needing to resort to system calls. |
MX Record lookup and check | 4,336,849 | 6 | 2010-12-02T15:48:57Z | 4,339,305 | 16 | 2010-12-02T20:03:02Z | [
"python",
"mx-record"
] | I need to create a tool that will check a domains live mx records against what should be expected (we have had issues with some of our staff fiddling with them and causing all incoming mail to redirected into the void)
Now I won't lie, I'm not a competent programmer in the slightest! I'm about 40 pages into "dive into... | With [dnspython](http://www.dnspython.org/) module (not built-in, you must `pip install` it):
```
>>> import dns.resolver
>>> domain = 'hotmail.com'
>>> for x in dns.resolver.query(domain, 'MX'):
... print x.to_text()
...
5 mx3.hotmail.com.
5 mx4.hotmail.com.
5 mx1.hotmail.com.
5 mx2.hotmail.com.
``` |
replacing all regex matches in single line | 4,338,032 | 8 | 2010-12-02T17:41:48Z | 4,338,791 | 13 | 2010-12-02T19:07:38Z | [
"python",
"regex"
] | I have dynamic regexp in which I don't know in advance how many groups it has
I would like to replace all matches with xml tags
example
```
re.sub("(this).*(string)","this is my string",'<markup>\anygroup</markup>')
>> "<markup>this</markup> is my <markup>string</markup>"
```
is that even possible in single line? | For a constant regexp like in your example, do
```
re.sub("(this)(.*)(string)",
r'<markup>\1</markup>\2<markup>\3</markup>',
text)
```
Note that you need to enclose .\* in parentheses as well if you don't want do lose it.
Now if you don't know what the regexp looks like, it's more difficult, but should... |
How do I detect Xen in a Python script? | 4,338,768 | 4 | 2010-12-02T19:04:47Z | 4,351,426 | 7 | 2010-12-04T01:35:06Z | [
"python",
"xen"
] | I need to determine when my Python script is running in a Xen virtual machine. The VM will be running Linux.
I can't find anything obvious in the platform module. The closest I can get is the appearance of 'xen' in platform.platform()
```
>>> platform.platform()
'Linux-2.6.18-194.el5xen-x86_64-with-redhat-5.5-Final'
... | FYI, if its a paravirtual VM, there should be a /proc/xen/capabilities file. If its contents is "control\_d" then, you are running under dom0 else , you are running on a domU.
DONT rely on the kernel version. If the VM is compiled with a custom kernel or a different kernel version or even a modern day PV-ops kernel (... |
How Awful is My Decorator? | 4,339,099 | 4 | 2010-12-02T19:41:37Z | 4,339,202 | 8 | 2010-12-02T19:52:10Z | [
"python"
] | I recently created a @sequenceable decorator, that can be applied to any function that takes one argument, and causes it to automatically be applicable to any sequence. This is the code (Python 2.5):
```
def sequenceable(func):
def newfunc(arg):
if hasattr(arg, '__iter__'):
if isinstance(arg, d... | This *is* a terrible idea. This is essentially loose typing. Duck-typing is as far as this
stuff should be taken, IMO.
Consider this:
```
def pluralize(f):
def on_seq(seq):
return [f(x) for x in seq]
def on_dict(d):
return dict((k, f(v)) for k, v in d.iteritems())
f.on_dict = on_dict
... |
Can I cleanse a numpy array without a loop? | 4,339,273 | 6 | 2010-12-02T19:59:20Z | 4,339,327 | 9 | 2010-12-02T20:05:27Z | [
"python",
"numpy"
] | Perhaps not such a big deal, but it breaks my heart to follow this:
`deltas = data[1:] - data[:-1]`
with this:
```
for i in range(len(deltas)):
if deltas[i] < 0: deltas[i] = 0
if deltas[i] > 100: deltas[i] = 0
```
For this particular example...is there a better way to do the cleansing part?
Questio... | ```
import numpy as np
deltas=np.diff(data)
deltas[deltas<0]=0
deltas[deltas>100]=0
```
Also possible, and a bit quicker is
```
deltas[(deltas<0) | (deltas>100)]=0
``` |
Create a dovecot SHA1 digest using bash or python or some other linux command-line tool | 4,339,736 | 4 | 2010-12-02T20:53:32Z | 4,339,875 | 7 | 2010-12-02T21:06:17Z | [
"python",
"bash",
"sha1"
] | Our dovecot and email server authenticate users using SHA1 digests. We can't really change the current digest because we have so many users and don't want to have to have them re-create all their passwords.
We would like an easier way to create a digest to put into the database for our users (and eventually create a w... | You need to base64 encode the binary digest to get it into their format.
```
>>> import hashlib
>>> import base64
>>> p = hashlib.sha1('password')
>>> base64.b64encode(p.digest())
'W6ph5Mm5Pz8GgiULbPgzG37mj9g='
```
EDIT: By the way if you'd prefer to do this from a terminal/bash script, you can do
```
$ echo -n 'pa... |
Fastest Way to Round to the Nearest 5/100ths | 4,340,322 | 6 | 2010-12-02T21:49:15Z | 4,340,355 | 11 | 2010-12-02T21:53:12Z | [
"python"
] | I have numbers that I want to go from:
```
1.215145156155 => 1.2
1.368161685161 => 1.35
1.578414616868 => 1.6
```
(\*Note: the hundredths place should not be marked if it is zero.)
What's the ***fastest*** way to do this?
This is what I have right now, and it is not fast enough:
```
def rounder(v):
v = str(rou... | Scale, round, unscale.
```
round(20*v)/20
```
I should warn you that the behaviour might surprise you:
```
>>> round(20*1.368161685161)/20
1.3500000000000001
```
The rounding is working correctly, but IEEE numbers can't represent 1.35 exactly. Python 2.7 is smarter about this and will choose the simplest representa... |
Setting values of an array to -inf in Python with scipy/numpy | 4,340,787 | 3 | 2010-12-02T22:45:31Z | 4,340,827 | 10 | 2010-12-02T22:49:15Z | [
"python",
"numpy",
"scipy"
] | I have an array that looks like this:
```
a = [ -22 347 4448 294 835 4439 587 326]
```
I want to set its 0 or smaller values to -inf. I tried the following:
```
a[where(a <= 0)] = -inf
```
when I do this, I get the error:
```
OverflowError: cannot convert float infinity to integer
```
Any idea why this is an... | Your array `a` is an array of integers. Integers can't represent infinity -- only floating point numbers can. So there are to fixes:
1. Use an array of floating point numbers instead.
2. Use a large negative integer value, e.g. `-2147483648` if you are using 32-bit integers. Of course that's not the same as -infinity,... |
How do you switch between python 2 and 3, and vice versa? | 4,340,873 | 12 | 2010-12-02T22:55:23Z | 4,341,037 | 10 | 2010-12-02T23:21:38Z | [
"python",
"python-3.x",
"python-2.6"
] | I am reading How To Learn Python The Hard Way, which uses 2. Recently discovered Invent With Python, which uses 3.
Can I download python 3, and use it when I read Invent With Python, then switch back to python 2 when I want to read How To Learn Python The Hard Way. If so, how would I choose which version I use? | depends on your system/platform...
I'm currently on Ubuntu 10.10 and have both 2.6 and 3.1 installed. The default system python is 2.6, and python3 is installed as an additional package.
```
corey@studio17:~$ python
Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56)
[GCC 4.4.5] on linux2
Type "help", "copyright", "cre... |
Convert a list of 2D numpy arrays to one 3D numpy array? | 4,341,359 | 3 | 2010-12-03T00:15:05Z | 4,341,378 | 10 | 2010-12-03T00:20:51Z | [
"python",
"numpy"
] | I have a list of several hundred 10x10 arrays that I want to stack together into a single Nx10x10 array. At first I tried a simple
`newarray = np.array(mylist)`
But that returned with "ValueError: setting an array element with a sequence."
Then I found the online documentation for dstack(), which looked perfect: "..... | ```
newarray = np.dstack(mylist)
```
should work. For example:
```
import numpy as np
# Here is a list of five 10x10 arrays:
x=[np.random.random((10,10)) for _ in range(5)]
y=np.dstack(x)
print(y.shape)
# (10, 10, 5)
# To get the shape to be Nx10x10, you could use rollaxis:
y=np.rollaxis(y,-1)
print(y.shape)
# (5... |
python -m SimpleHTTPServer - Listening on 0.0.0.0:8000 but http://0.0.0.0:8000/test.html gives "Page Not Found" | 4,341,638 | 12 | 2010-12-03T01:15:02Z | 4,341,656 | 8 | 2010-12-03T01:19:13Z | [
"python",
"osx",
"terminal",
"webserver"
] | After cding to my folder I enter
```
python -m SimpleHTTPServer
```
and get
```
Serving HTTP on 0.0.0.0 port 8000 ...
```
in reply. But when I hit `http://0.0.0.0:8000/test.html` I get a page not found error.
I've also tried
```
pushd /path/you/want/to/serve; python -m SimpleHTTPServer; popd
```
taken from [this... | Have you tried <http://127.0.0.1:8000/> ?
:) |
python -m SimpleHTTPServer - Listening on 0.0.0.0:8000 but http://0.0.0.0:8000/test.html gives "Page Not Found" | 4,341,638 | 12 | 2010-12-03T01:15:02Z | 4,341,808 | 16 | 2010-12-03T01:56:03Z | [
"python",
"osx",
"terminal",
"webserver"
] | After cding to my folder I enter
```
python -m SimpleHTTPServer
```
and get
```
Serving HTTP on 0.0.0.0 port 8000 ...
```
in reply. But when I hit `http://0.0.0.0:8000/test.html` I get a page not found error.
I've also tried
```
pushd /path/you/want/to/serve; python -m SimpleHTTPServer; popd
```
taken from [this... | I think the other two answers are trying to make it clear that 0.0.0.0 is not the URL you should be visiting. When a Python web server (like cherrypy for instance) says it is serving on 0.0.0.0 it means it is listening for all TCP traffic that ends up at that machine no matter the hostname or IP that was requested. But... |
How do I disable a Pylint warning? | 4,341,746 | 83 | 2010-12-03T01:41:04Z | 4,341,833 | 48 | 2010-12-03T02:00:52Z | [
"python",
"pylint"
] | I'm trying to disable warning C0321 ("more than one statement on a single line" -- I often put `if` statements with short single-line results on the same line), in Pylint 0.21.1 (if it matters: astng 0.20.1, common 0.50.3, Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56)).
I've tried adding `disable=C0321` in the Pyli... | `pylint --generate-rcfile` shows it like this:
```
[MESSAGES CONTROL]
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time.
#enable=
# Disable the message, report, category or checker with the given... |
How do I disable a Pylint warning? | 4,341,746 | 83 | 2010-12-03T01:41:04Z | 6,719,693 | 61 | 2011-07-16T19:25:41Z | [
"python",
"pylint"
] | I'm trying to disable warning C0321 ("more than one statement on a single line" -- I often put `if` statements with short single-line results on the same line), in Pylint 0.21.1 (if it matters: astng 0.20.1, common 0.50.3, Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56)).
I've tried adding `disable=C0321` in the Pyli... | I had this problem using **Eclipse** and solved it as follows:
in the pylint folder (e.g. C:\Python26\Lib\site-packages\pylint), hold shift, right-click and choose to open the windows command in that folder. Type:
```
lint.py --generate-rcfile > standard.rc
```
This creates the 'standard.rc' configuration file. Open... |
How do I disable a Pylint warning? | 4,341,746 | 83 | 2010-12-03T01:41:04Z | 20,789,397 | 30 | 2013-12-26T18:28:22Z | [
"python",
"pylint"
] | I'm trying to disable warning C0321 ("more than one statement on a single line" -- I often put `if` statements with short single-line results on the same line), in Pylint 0.21.1 (if it matters: astng 0.20.1, common 0.50.3, Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56)).
I've tried adding `disable=C0321` in the Pyli... | To disable a warning locally in a block, add
```
# pylint: disable=C0321
```
to that block. |
How do I disable a Pylint warning? | 4,341,746 | 83 | 2010-12-03T01:41:04Z | 23,542,817 | 39 | 2014-05-08T13:13:46Z | [
"python",
"pylint"
] | I'm trying to disable warning C0321 ("more than one statement on a single line" -- I often put `if` statements with short single-line results on the same line), in Pylint 0.21.1 (if it matters: astng 0.20.1, common 0.50.3, Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56)).
I've tried adding `disable=C0321` in the Pyli... | Starting from Pylint v. 0.25.3, you can use the symbolic names for messages [instead of remembering all those code numbers](https://docs.pylint.org/en/latest/faq.html#do-i-have-to-remember-all-these-numbers). E.g.:
```
# pylint: disable=locally-disabled, multiple-statements, fixme, line-too-long
```
The above comment... |
How do I disable a Pylint warning? | 4,341,746 | 83 | 2010-12-03T01:41:04Z | 32,672,068 | 22 | 2015-09-19T18:57:13Z | [
"python",
"pylint"
] | I'm trying to disable warning C0321 ("more than one statement on a single line" -- I often put `if` statements with short single-line results on the same line), in Pylint 0.21.1 (if it matters: astng 0.20.1, common 0.50.3, Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56)).
I've tried adding `disable=C0321` in the Pyli... | There are several ways to disable warnings & errors from Pylint. Which one to use has to do with how globally or locally you want to apply the disablement -- an important design decision.
**Multiple Approaches**
1. In one or more `pylintrc` files.
This involves more than the `~/.pylintrc` file (in your $HOME directo... |
How can I get a list of references of an object in Python? | 4,341,942 | 6 | 2010-12-03T02:29:27Z | 4,342,276 | 8 | 2010-12-03T03:43:07Z | [
"python",
"variables",
"reference"
] | All:
```
a = 1
b = a
c = b
```
Now I want to get a list of object `1` tagged, which is `[a, b, c]`. How could I do this?
BTW, how to call variable "a" here officially? I know so far it is a "object tag" for the object, but I have no idea what is the term of it.
Thanks!
why do I need this:
```
a = b = c = 1
print... | As you can see, it's impossible to find them all.
```
>>> sys.getrefcount(1)
791
>>> sys.getrefcount(2)
267
>>> sys.getrefcount(3)
98
``` |
How do I serialize a Python dictionary into a string, and then back to a dictionary? | 4,342,176 | 30 | 2010-12-03T03:24:40Z | 4,342,192 | 9 | 2010-12-03T03:27:22Z | [
"python",
"string",
"list",
"serialization",
"dictionary"
] | How do I serialize a Python dictionary into a string, and then back to a dictionary? The dictionary will have lists and other dictionaries inside it. | Use Python's [json](http://docs.python.org/library/json.html) module, or [simplejson](http://pypi.python.org/pypi/simplejson/) if you don't have python 2.6 or higher. |
How do I serialize a Python dictionary into a string, and then back to a dictionary? | 4,342,176 | 30 | 2010-12-03T03:24:40Z | 4,342,219 | 62 | 2010-12-03T03:31:38Z | [
"python",
"string",
"list",
"serialization",
"dictionary"
] | How do I serialize a Python dictionary into a string, and then back to a dictionary? The dictionary will have lists and other dictionaries inside it. | It depends on what you're wanting to use it for. If you're just trying to save it, you should use [`pickle`](http://docs.python.org/library/pickle.html) (or [`cPickle`](http://docs.python.org/library/pickle.html#module-cPickle), which is faster, if using CPython as you probably are).
```
>>> import cPickle
>>> cPickle... |
TCP port using python - how to forward command output to tcp port? | 4,342,697 | 4 | 2010-12-03T05:20:01Z | 4,342,768 | 8 | 2010-12-03T05:34:07Z | [
"python",
"command-line",
"tcp",
"send"
] | I want to develop a code in python which will open a port in the localhost and will send the logs to that port. Logs will be nothing but the command output of a python file.
like :
```
hello.py
i = 0
while True:
print "hello printed %s times." % i
i+=1
```
this will continuously print the statement.
I... | Here is what i came up with.
to use with your script you do :
```
hello.py | thisscript.py
```
Hope it is was you wanted.
```
import socket
import sys
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
while True:
line = sys.stdin.readline()
... |
Python: jQuery-like function chaining? | 4,342,977 | 7 | 2010-12-03T06:17:13Z | 4,343,127 | 10 | 2010-12-03T06:42:15Z | [
"python",
"function",
"chaining"
] | I couldn't find anything on this subject on Google, so I think I should ask it here:
Is it possible to chain functions with Python, like jQuery does?
```
['my', 'list'].foo1(arg1, arg2).foo2(arg1, arg2).foo3(arg1, arg2) #etc...
```
I am losing a lot of space and readability when I write this code:
```
foo3(foo2(foo... | As long as the function returns a value, you can chain it. In jQuery, a selector method usually returns the selector itself, which is what allows you to do the chaining. If you want to implement chaining in python, you could do something like this:
```
class RoboPuppy:
def bark(self):
print "Yip!"
return se... |
Python: jQuery-like function chaining? | 4,342,977 | 7 | 2010-12-03T06:17:13Z | 4,343,534 | 9 | 2010-12-03T08:02:48Z | [
"python",
"function",
"chaining"
] | I couldn't find anything on this subject on Google, so I think I should ask it here:
Is it possible to chain functions with Python, like jQuery does?
```
['my', 'list'].foo1(arg1, arg2).foo2(arg1, arg2).foo3(arg1, arg2) #etc...
```
I am losing a lot of space and readability when I write this code:
```
foo3(foo2(foo... | Here's an expansion of Simon's `ListMutator` suggestion:
```
class ListMutator(object):
def __init__(self, seq):
self.data = seq
def foo1(self, arg1, arg2):
self.data = [x + arg1 for x in self.data]
# This allows chaining:
return self
def foo2(self, arg1, arg2):
s... |
Difference between Systems programming language and Application programming languages | 4,343,014 | 7 | 2010-12-03T06:23:29Z | 4,343,035 | 8 | 2010-12-03T06:28:12Z | [
"c#",
"java",
"python",
"perl",
"programming-languages"
] | What are the differences between a `systems programming language` and `Application programming language`? | As with a great many things in IT, the line is blurry. For example, C started its life as a systems programming language (and was used to implement Unix), but was and is used for applications development too.
Having said that, there are clearly some languages better suited to systems programming than others (eg. C/C++... |
Difference between Systems programming language and Application programming languages | 4,343,014 | 7 | 2010-12-03T06:23:29Z | 4,343,639 | 13 | 2010-12-03T08:18:18Z | [
"c#",
"java",
"python",
"perl",
"programming-languages"
] | What are the differences between a `systems programming language` and `Application programming language`? | A few factors should in my opinon come into consideration
1. In a system programming language you must be able to reach low-level stuff, getting close to the real hardware world. In an application language instead there is a sort of "virtual world" (hopefully nicer and easier to interact with) that has been designed w... |
Using Mongo Find() with $in and Regex | 4,345,361 | 7 | 2010-12-03T12:08:53Z | 4,828,452 | 9 | 2011-01-28T12:56:52Z | [
"python",
"regex",
"mongodb"
] | I've come across a problem. I have an array of words, and I use these words to search the database and match any documents with matching fields using:
```
collection.find({"word":{"$in":words}})
```
The above works very well, but I want to be able to use Regex. The problem I have now is that say one of the words in t... | Sorry for late answer, just googled your question. You should use one regex, not an array of them, like:
```
'^[work|accus*|planet]'
``` |
How to use python urllib2 to send json data for login | 4,348,061 | 16 | 2010-12-03T17:15:46Z | 4,348,122 | 20 | 2010-12-03T17:25:34Z | [
"python",
"json",
"urllib2"
] | I want to use python urllib2 to simulate a login action, I use Fiddler to catch the packets and got that the login action is just an ajax request and the username and password is sent as json data, but I have no idea how to use urllib2 to send json data, help... | ```
import urllib2
import json
# Whatever structure you need to send goes here:
jdata = json.dumps({"username":"...", "password":"..."})
urllib2.urlopen("http://www.example.com/", jdata)
```
This assumes you're using HTTP POST to send a simple json object with username and password. |
How to use python urllib2 to send json data for login | 4,348,061 | 16 | 2010-12-03T17:15:46Z | 7,469,725 | 18 | 2011-09-19T10:47:46Z | [
"python",
"json",
"urllib2"
] | I want to use python urllib2 to simulate a login action, I use Fiddler to catch the packets and got that the login action is just an ajax request and the username and password is sent as json data, but I have no idea how to use urllib2 to send json data, help... | ## For Python 3.x
***Note the following***
* In Python 3.x the `urllib` and `urllib2` modules have been **combined**. The module is named `urllib`. So, remember that `urllib` in Python 2.x and `urllib` in Python 3.x are DIFFERENT modules.
* The POST data for `urllib.request.Request` in Python 3 does NOT accept a stri... |
Django ORM: Filter by extra attribute | 4,348,124 | 8 | 2010-12-03T17:25:52Z | 4,348,728 | 15 | 2010-12-03T18:40:36Z | [
"python",
"django",
"database",
"orm"
] | I want to filter some database objects by a concatenated string.
The normal SQL query would be:
```
SELECT concat(firstName, ' ', name) FROM person WHERE CONCAT(firstName, ' ', name) LIKE "a%";
```
In the model, I have created a manager called PersonObjects:
```
class PersonObjects(Manager):
attrs = {
... | It's not a bug. `filter()` only inspects model definitions, so it doesn't recognize `fullName` as a declared field (because it's not - it's an extra argument in a query).
You can add the `fullName` to `WHERE` using `extra()`:
```
Person.objects.extra(where=["fullName LIKE %s"], params=["Alexei%"])
``` |
Python dictionary keys besides strings and integers? | 4,348,232 | 13 | 2010-12-03T17:36:30Z | 4,348,396 | 17 | 2010-12-03T17:58:18Z | [
"python",
"dictionary"
] | Anyone have some neat examples of dictionaries with some interesting keys (besides the canonical string or integer), and how you used these in your program?
I understand all we need for a key is something `hashable`, meaning it must be immutable and comparable (has an `__eq__()` or `__cmp__()` method).
A related ques... | Let's go for something a bit more esoteric. Suppose you wanted to execute a list of functions and store the result of each. For each function that raised an exception, you want to record the exception, and you also want to keep a count of how many times each kind of exception is raised. Functions and exceptions can be ... |
python packaging for relative imports | 4,348,452 | 64 | 2010-12-03T18:05:40Z | 4,351,737 | 38 | 2010-12-04T03:15:48Z | [
"python",
"python-import"
] | First off all: I'm sorry, I know there has been lots of question about relative imports, but I just didn't find a solution. If possible I would like to use the following directory layout:
```
myClass/
__init__.py
test/
demo.py
benchmark.py
specs.py
src/
__init__.py
m... | > `ValueError: Attempted relative import in non-package`
Means you attempt to use relative import in the module which is not package. Its problem with the file which has this `from ... import` statement, and not the file which you are trying to import.
So if you are doing relative imports in your tests, for example, ... |
python packaging for relative imports | 4,348,452 | 64 | 2010-12-03T18:05:40Z | 10,713,254 | 21 | 2012-05-23T03:59:34Z | [
"python",
"python-import"
] | First off all: I'm sorry, I know there has been lots of question about relative imports, but I just didn't find a solution. If possible I would like to use the following directory layout:
```
myClass/
__init__.py
test/
demo.py
benchmark.py
specs.py
src/
__init__.py
m... | After hours of searching last night I found the answer to relative imports in python!! Or an easy solution at the very least. The best way to fix this it to have the modules called from another module. So say you want demo.py to import myClass.py
in the MyClass folder at the root of the sub-packages toy need to have a ... |
Subprocess Variables | 4,348,524 | 10 | 2010-12-03T18:16:45Z | 4,348,612 | 23 | 2010-12-03T18:26:20Z | [
"python",
"subprocess",
"tcpdump"
] | ```
1 import subprocess
2 raw = raw_input("Filename:").lower()
3 ip = raw_input("Host:").lower()
4 cmd = subprocess.call("tcpdump -c5 -vvv -w" + " raw " + " ip ",shell=True)
```
So this is my script. I everything works besides one key objective, using the raw input.
It allows me to input anything i want, but w... | Don't use `shell=True`. That should be `False`.
You are making subtle mistakes with the input. Specifically, if you have two strings:
```
>>> s1 = 'Hello'
>>> s2 = 'Hi'
>>> s1 + s2
'HelloHi'
```
Notice, there is no space between `Hello` and `Hi`. So don't do this. (Your line 4)
You should do (the good way):
```
>>... |
Subprocess Variables | 4,348,524 | 10 | 2010-12-03T18:16:45Z | 4,348,795 | 20 | 2010-12-03T18:48:21Z | [
"python",
"subprocess",
"tcpdump"
] | ```
1 import subprocess
2 raw = raw_input("Filename:").lower()
3 ip = raw_input("Host:").lower()
4 cmd = subprocess.call("tcpdump -c5 -vvv -w" + " raw " + " ip ",shell=True)
```
So this is my script. I everything works besides one key objective, using the raw input.
It allows me to input anything i want, but w... | You should not use the string form ob the `subprocess` functions. Try:
```
subprocess.check_call(["tcpdump", "-c5", "-vvv", "-w", raw, "host", ip])
``` |
How to do "if-for" statement in python? | 4,348,678 | 11 | 2010-12-03T18:33:20Z | 4,348,687 | 25 | 2010-12-03T18:35:15Z | [
"python"
] | With python, I would like to run a test over an entire list, and, if all the statements are true for each item in the list, take a certain action.
Pseudo-code: If "test involving x" is true for every x in "list", then do "this".
It seems like there should be a simple way to do this.
What syntax should I use in pytho... | Use `all()`. It takes an iterable as an argument and return `True` if all entries evaluate to `True`. Example:
```
if all((3, True, "abc")):
print "Yes!"
```
You will probably need some kind of generator expression, like
```
if all(x > 3 for x in lst):
do_stuff()
``` |
Saving interactive Matplotlib figures | 4,348,733 | 61 | 2010-12-03T18:41:11Z | 4,348,932 | 17 | 2010-12-03T19:03:25Z | [
"python",
"matplotlib"
] | Is there a way to save a Matplotlib figure such that it can be re-opened and have typical interaction restored? (Like the .fig format in MATLAB?)
I find myself running the same scripts many times to generate these interactive figures. Or I'm sending my colleagues multiple static PNG files to show different aspects of ... | This would be a great feature, but AFAIK it isn't implemented in Matplotlib and likely would be difficult to implement yourself due to the way figures are stored.
I'd suggest either (a) separate processing the data from generating the figure (which saves data with a unique name) and write a figure generating script (l... |
Saving interactive Matplotlib figures | 4,348,733 | 61 | 2010-12-03T18:41:11Z | 12,734,765 | 26 | 2012-10-04T19:47:46Z | [
"python",
"matplotlib"
] | Is there a way to save a Matplotlib figure such that it can be re-opened and have typical interaction restored? (Like the .fig format in MATLAB?)
I find myself running the same scripts many times to generate these interactive figures. Or I'm sending my colleagues multiple static PNG files to show different aspects of ... | As of Matplotlib 1.2, we now have experimental [pickle](https://en.wikipedia.org/wiki/Pickle_%28Python%29) support. Give that a go and see if it works well for your case. If you have any issues, please let us know on the [Matplotlib mailing list](https://sourceforge.net/p/matplotlib/mailman/) or by opening an issue on ... |
Saving interactive Matplotlib figures | 4,348,733 | 61 | 2010-12-03T18:41:11Z | 35,100,106 | 9 | 2016-01-30T09:29:10Z | [
"python",
"matplotlib"
] | Is there a way to save a Matplotlib figure such that it can be re-opened and have typical interaction restored? (Like the .fig format in MATLAB?)
I find myself running the same scripts many times to generate these interactive figures. Or I'm sending my colleagues multiple static PNG files to show different aspects of ... | I just found out how to do this. The "experimental pickle support" mentioned by @pelson works quite well.
Try this:
```
# Plot something
import matplotlib.pyplot as plt
fig,ax = plt.subplots()
ax.plot([1,2,3],[10,-10,30])
```
After your interactive tweaking, save the figure object as a binary file:
```
import pickl... |
Python create cookies and then load a page with the cookies | 4,349,147 | 2 | 2010-12-03T19:27:47Z | 4,349,200 | 10 | 2010-12-03T19:34:06Z | [
"python",
"cookies",
"python-3.x",
"httplib2"
] | I would like to access a web page from a python program.
I have to set up cookies to load the page.
I used the httplib2 library, but I didn't find how add my own cookie
```
resp_headers, content = h.request("http://www.theURL.com", "GET")
```
How can I create cookies with the right name and value, add it to the fun... | From <http://code.google.com/p/httplib2/wiki/Examples> hope will help )
Cookies
When automating something, you often need to "login" to maintain some sort of session/state with the server. Sometimes this is achieved with form-based authentication and cookies. You post a form to the server, and it responds with a cook... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.