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 |
|---|---|---|---|---|---|---|---|---|---|
Matplotlib subplots_adjust hspace so titles and xlabels don't overlap? | 2,418,125 | 22 | 2010-03-10T15:32:03Z | 2,516,508 | 7 | 2010-03-25T14:51:30Z | [
"python",
"matplotlib"
] | With, say, 3 rows of subplots in matplotlib, `xlabels` of one row can overlap the title of the next. One has to fiddle with `pl.subplots_adjust(hspace)`, which is annoying.
Is there a recipe for `hspace` that prevents overlaps and works for any nrow?
```
""" matplotlib xlabels overlap titles ? """
import sys
import n... | I find this quite tricky, but there is some information on it [here at the MatPlotLib FAQ](http://matplotlib.sourceforge.net/faq/howto_faq.html#automatically-make-room-for-tick-labels). It is rather cumbersome, and requires finding out about what space individual elements (ticklabels) take up...
**Update:**
The page s... |
Matplotlib subplots_adjust hspace so titles and xlabels don't overlap? | 2,418,125 | 22 | 2010-03-10T15:32:03Z | 6,541,482 | 28 | 2011-06-30T21:48:17Z | [
"python",
"matplotlib"
] | With, say, 3 rows of subplots in matplotlib, `xlabels` of one row can overlap the title of the next. One has to fiddle with `pl.subplots_adjust(hspace)`, which is annoying.
Is there a recipe for `hspace` that prevents overlaps and works for any nrow?
```
""" matplotlib xlabels overlap titles ? """
import sys
import n... | You can use plt.subplots\_adjust to change the spacing between the subplots Link
```
subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
left = 0.125 # the left side of the subplots of the figure
right = 0.9 # the right side of the subplots of the figure
bottom = 0.1 # the b... |
Matplotlib subplots_adjust hspace so titles and xlabels don't overlap? | 2,418,125 | 22 | 2010-03-10T15:32:03Z | 8,729,186 | 26 | 2012-01-04T15:16:41Z | [
"python",
"matplotlib"
] | With, say, 3 rows of subplots in matplotlib, `xlabels` of one row can overlap the title of the next. One has to fiddle with `pl.subplots_adjust(hspace)`, which is annoying.
Is there a recipe for `hspace` that prevents overlaps and works for any nrow?
```
""" matplotlib xlabels overlap titles ? """
import sys
import n... | The link posted by Jose has been updated and pylab now has a `tight_layout()` function that does this automatically (in matplotlib version 1.1.0).
<http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.tight_layout>
<http://matplotlib.org/users/tight_layout_guide.html#plotting-guide-tight-layout> |
Problem importing pylab in Ubuntu 8.1 | 2,418,583 | 2 | 2010-03-10T16:26:12Z | 2,418,650 | 8 | 2010-03-10T16:35:42Z | [
"python"
] | I have installed numpy1.3,scipy 0.7.1,matplotlib 0.99.1.1 and python 2.5
when I import pylab I get the following error. Someone please help.
```
/var/lib/python-support/python2.5/gtk-2.0/gtk/__init__.py:72: GtkWarning: could not open display
warnings.warn(str(e), _gtk.Warning)
/usr/lib/python2.5/site-packag... | try using a different backend for plotting than Gtk.
Open the python console and type:
```
>>> import matplotlib
>>> matplotlib.matplotlib_fname()
```
This will print a file name. Edit this file and modify the section 'Backend' and change Gtk or GtkAgg with any other (see the documentation in the same file), until y... |
Extracting code from photograph of T-shirt via OCR | 2,418,722 | 36 | 2010-03-10T16:43:36Z | 2,418,817 | 7 | 2010-03-10T16:58:53Z | [
"python",
"ocr",
"tesseract"
] | I recently saw someone with a T-shirt with some Perl code on the back. I took a photograph of it and cropped out the code:

Next I tried to extract the code from the image via OCR, so I installed [Tesseract OCR](http://code.google.com/p/tesseract-ocr/) and the Python bindings ... | If I were you I'd start by cleaning up the image as much as possible, using a picture-manipulation program (GIMP, for example) so that the input for the OCR would be more easily understandable.
If possible, aim for creating a black-and-white only image. |
Extracting code from photograph of T-shirt via OCR | 2,418,722 | 36 | 2010-03-10T16:43:36Z | 2,418,837 | 35 | 2010-03-10T17:00:10Z | [
"python",
"ocr",
"tesseract"
] | I recently saw someone with a T-shirt with some Perl code on the back. I took a photograph of it and cropped out the code:

Next I tried to extract the code from the image via OCR, so I installed [Tesseract OCR](http://code.google.com/p/tesseract-ocr/) and the Python bindings ... | You can probably type faster than you can clean up images and install OCR engines:
```
#!/usr/bin/perl
(my$d=q[AA GTCAGTTCCT
CGCTATGTA ACACACACCA
TTTGTGAGT ATGTAACATA
CTCGCTGGC TATGTCAGAC
AGATTGATC GATCGATAGA
ATGATAGATC ... |
Extracting code from photograph of T-shirt via OCR | 2,418,722 | 36 | 2010-03-10T16:43:36Z | 2,418,850 | 15 | 2010-03-10T17:01:29Z | [
"python",
"ocr",
"tesseract"
] | I recently saw someone with a T-shirt with some Perl code on the back. I took a photograph of it and cropped out the code:

Next I tried to extract the code from the image via OCR, so I installed [Tesseract OCR](http://code.google.com/p/tesseract-ocr/) and the Python bindings ... | pre-processing will definitely yield a more workable image.
For example, here is the result of Gimp "Levels", "Difference-of-Gaussians", and "Levels" filters on the image.
 |
Extracting code from photograph of T-shirt via OCR | 2,418,722 | 36 | 2010-03-10T16:43:36Z | 2,418,975 | 8 | 2010-03-10T17:17:13Z | [
"python",
"ocr",
"tesseract"
] | I recently saw someone with a T-shirt with some Perl code on the back. I took a photograph of it and cropped out the code:

Next I tried to extract the code from the image via OCR, so I installed [Tesseract OCR](http://code.google.com/p/tesseract-ocr/) and the Python bindings ... | Just a few small typos in RedDwight code.
```
#!/usr/bin/perl
(my $d=q[AA GTCAGTTCCT
CGCTATGTA ACACACACCA
TTTGTGAGT ATGTAACATA
CTCGCTGGC TATGTCAGAC
AGATTGATC GATCGATAGA
ATGATAGATC GAACGAGTGA
TAGATAGAGT GAT... |
OSX : Defining a new URL handler that points straight at a Python script | 2,418,910 | 10 | 2010-03-10T17:09:33Z | 2,499,107 | 11 | 2010-03-23T10:35:10Z | [
"python",
"osx",
"url",
"handler"
] | I'm trying to define a new URL handler under OSX that will point at a python script.
I've wrapped the Python script up into an applet (right-clicked on the .py, and gone Open With -> Build Applet)
I've added the following into the applet's Info.plist:
```
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>C... | After a lot of messing around, I've managed to get this working under OSX...
This is how I'm doing it:
in the AppleScript Script Editor, write the following script:
```
on open location this_URL
do shell script "/scripts/runLocalCommand.py '" & this_URL & "'"
end open location
```
If you want to make sure you'r... |
Get function import path | 2,419,416 | 6 | 2010-03-10T18:17:51Z | 2,419,541 | 8 | 2010-03-10T18:34:35Z | [
"python",
"function",
"import",
"path"
] | ```
from pack.mod import f
```
How to get from object f information about import - `'pack.mod'`
I can get it using `f.__module__`
but if function def in module where i get this attribute (`f.__module__`) it return `'__main__'`. But i need real path here - `'pack.mod'`
I found this way to get this information:
```
i... | What `inspect.getmodule(f)` does internally, per [inspect.py's sources](http://svn.python.org/view/python/trunk/Lib/inspect.py?revision=75433&view=markup), is essentially `sys.modules.get(object.__module__)` -- I wouldn't call using that code directly "more convenient", though (beyond the "essentially" part, `inspect` ... |
How to get one value from a generator in Python? | 2,419,770 | 40 | 2010-03-10T19:11:28Z | 2,419,780 | 7 | 2010-03-10T19:13:00Z | [
"python",
"generator"
] | Very basic question - how to get one value from a generator in Python?
So far I found I can get one by writing `gen.next()`. I just want to make sure this is the right way? | This is the correct way to do it.
You can also use `next(gen)`.
<http://docs.python.org/library/functions.html#next> |
How to get one value from a generator in Python? | 2,419,770 | 40 | 2010-03-10T19:11:28Z | 2,419,782 | 50 | 2010-03-10T19:13:03Z | [
"python",
"generator"
] | Very basic question - how to get one value from a generator in Python?
So far I found I can get one by writing `gen.next()`. I just want to make sure this is the right way? | Yes, or `next(gen)` in 2.6+. |
How to get one value from a generator in Python? | 2,419,770 | 40 | 2010-03-10T19:11:28Z | 2,421,288 | 29 | 2010-03-10T22:54:12Z | [
"python",
"generator"
] | Very basic question - how to get one value from a generator in Python?
So far I found I can get one by writing `gen.next()`. I just want to make sure this is the right way? | In Python <= 2.5, use `gen.next()`. This will work for all Python 2.x versions, but not Python 3.x
In Python >= 2.6, use `next(gen)`. This is a built in function, and is clearer. It will also work in Python 3.
Both of these end up calling a specially named function, `next()`, which can be overridden by subclassing. I... |
Search for string allowing for one mismatch in any location of the string | 2,420,412 | 19 | 2010-03-10T20:42:30Z | 2,421,378 | 18 | 2010-03-10T23:09:45Z | [
"python",
"string",
"pattern-matching",
"string-matching",
"dna-sequence"
] | I am working with DNA sequences of length 25 (see examples below). I have a list of 230,000 and need to look for each sequence in the entire genome (toxoplasma gondii parasite). I am not sure how large the genome is, but much longer than 230,000 sequences.
I need to look for each of my sequences of 25 characters, for ... | **Before you read on**, have you looked at [biopython](http://biopython.org/wiki/Main_Page)?
It appears that you want to find approximate matches with one substitution error, and zero insertion/deletion errors i.e. a Hamming distance of 1.
If you have a Hamming distance match function (see e.g. the link provided by I... |
Search for string allowing for one mismatch in any location of the string | 2,420,412 | 19 | 2010-03-10T20:42:30Z | 10,986,521 | 13 | 2012-06-11T19:44:02Z | [
"python",
"string",
"pattern-matching",
"string-matching",
"dna-sequence"
] | I am working with DNA sequences of length 25 (see examples below). I have a list of 230,000 and need to look for each sequence in the entire genome (toxoplasma gondii parasite). I am not sure how large the genome is, but much longer than 230,000 sequences.
I need to look for each of my sequences of 25 characters, for ... | Python [regex](http://pypi.python.org/pypi/regex/) library supports fuzzy regular expression matching. One advantage over [TRE](http://laurikari.net/tre/) is that it allows to find all matches of regular expression in the text (supports overlapping matches as well).
```
import regex
m=regex.findall("AA", "CAG")
>>> []... |
Apache2: mod_wsgi or mod_python, which one is better? | 2,421,007 | 5 | 2010-03-10T22:10:07Z | 2,421,036 | 14 | 2010-03-10T22:14:10Z | [
"python",
"rest",
"web-services",
"apache2"
] | I am planning to write web service in python. But, I found wsgi also does the similar thing. Which one can be preferred?
Thank you
Bala
> Update
I am still confused. Please help.
Better in my sense means:
1. Bug will be fixed periodically.
2. Chosen by most developers.
3. Additional features like authentica... | `mod_wsgi` is more actively maintained and (I hear -- haven't benchmarked them myself!) better performing than `mod_python`. So unless you need exclusive features of `mod_python`, just to use a web app framework (or non-framework, like [werkzeug](http://werkzeug.pocoo.org/);-), you're probably better off with `mod_wsgi... |
How to filter a query by property of user profile in Django? | 2,421,221 | 9 | 2010-03-10T22:43:14Z | 2,421,247 | 8 | 2010-03-10T22:47:41Z | [
"python",
"django"
] | I have two models,`Design` and `Profile`. Profile is hooked up in settings.py as the profile to be used with the User model. So I can access it via `user.get_profile()`.
And each `Design` instance has an `author` property that is a ForeignKey to User.
So, when I'm any view, I can get the screenname (a property of Pro... | If your profile class is named Profile, and you haven't customized the User <-> Profile relation using the related\_name property of the ForeignKey, then shouldn't you be accessing via:
```
designs = Design.objects.filter(author__user__profile__screenname__icontains=w)
```
The User -> Profile spans a relation so you ... |
How to correctly call base class methods (and constructor) from inherited classes in Python? | 2,421,307 | 24 | 2010-03-10T22:57:34Z | 2,421,325 | 30 | 2010-03-10T23:01:15Z | [
"python"
] | Suppose I have a `Base` class and a `Child` class that inherits from `Base`. What is the right way to call the constructor of base class from a child class in Python? Do I use `super`?
Here is an example of what I have so far:
```
class Base(object):
def __init__(self, value):
self.value = value
...
cla... | That is correct. Note that you can also call the `__init__` method directly on the `Base` class, like so:
```
class Child(Base):
def __init__(self, something_else):
Base.__init__(self, value = 20)
self.something_else = something_else
```
That's the way I generally do it. But it's discouraged, beca... |
How to correctly call base class methods (and constructor) from inherited classes in Python? | 2,421,307 | 24 | 2010-03-10T22:57:34Z | 2,421,333 | 8 | 2010-03-10T23:02:25Z | [
"python"
] | Suppose I have a `Base` class and a `Child` class that inherits from `Base`. What is the right way to call the constructor of base class from a child class in Python? Do I use `super`?
Here is an example of what I have so far:
```
class Base(object):
def __init__(self, value):
self.value = value
...
cla... | Yes, that's correct. If you wanted to be able to pass `value` into the `Child` class you could do it this way
```
class Child(Base):
def __init__(self, value, something_else):
super(Child, self).__init__(value)
self.something_else = something_else
...
``` |
How to correctly call base class methods (and constructor) from inherited classes in Python? | 2,421,307 | 24 | 2010-03-10T22:57:34Z | 2,421,428 | 14 | 2010-03-10T23:20:40Z | [
"python"
] | Suppose I have a `Base` class and a `Child` class that inherits from `Base`. What is the right way to call the constructor of base class from a child class in Python? Do I use `super`?
Here is an example of what I have so far:
```
class Base(object):
def __init__(self, value):
self.value = value
...
cla... | If you're using Python 3.1, super is new and improved. It figures out the class and instance arguments for you. So you should call super without arguments:
```
class Child(Base):
def __init__(self, value, something_else):
super().__init__(value)
self.something_else = something_else
...
``` |
How to determine if the value is ONE-BUT-LAST in a Python generator? | 2,421,368 | 2 | 2010-03-10T23:08:04Z | 2,421,465 | 10 | 2010-03-10T23:29:28Z | [
"python",
"generator"
] | Since generator returns values lazily, how do I determine if the value returned from a generator is one-but-last? I spent like an hour on this and can't figure it out.
Any help appreciated. Is it even possible??
Thanks, Boda Cydo! | You can wrap the generator in a generator that generates a sequence of pairs whose first element is a boolean telling you whether the element is the last-but-one:
```
def ending(generator):
z2 = generator.next()
z1 = generator.next()
for x in generator:
yield (False, z2)
z2, z1 = z1, x
... |
What is the Bash equivalent of Python's pass statement | 2,421,586 | 53 | 2010-03-10T23:54:34Z | 2,421,592 | 71 | 2010-03-10T23:55:25Z | [
"python",
"bash",
"language-comparisons"
] | Is there a Bash equivalent to the Python's `pass` statement? | You can use `:` for this. |
What is the Bash equivalent of Python's pass statement | 2,421,586 | 53 | 2010-03-10T23:54:34Z | 2,421,637 | 15 | 2010-03-11T00:07:07Z | [
"python",
"bash",
"language-comparisons"
] | Is there a Bash equivalent to the Python's `pass` statement? | `true` is a command that successfully does nothing.
(`false` would, in a way, be the opposite: it doesn't do anything, but claims that a failure occurred.) |
How to Check if request.GET var is None? | 2,422,055 | 16 | 2010-03-11T02:00:29Z | 2,422,422 | 24 | 2010-03-11T03:54:42Z | [
"python",
"django"
] | Hey, I'm getting into django and this is getting me a headache.
I'm trying to get a simple GET variable. URL is site.com/search/?q=search-term
My view is:
```
def search(request):
if request.method == 'GET' and 'q' in request.GET:
q = request.GET.get('q', None)
if q is not None:
results = Task.objects... | First, check if the `request.GET` dict contains a parameter named `q`. You're doing this properly already:
```
if request.method == 'GET' and 'q' in request.GET:
```
Next, check if the value of `q` is either `None` or the empty string. To do that, you can write this:
```
q = request.GET['q']
if q is not None and q !... |
Python: How can I replace full-width characters with half-width characters? | 2,422,177 | 3 | 2010-03-11T02:42:08Z | 2,422,245 | 7 | 2010-03-11T03:03:34Z | [
"python",
"unicode",
"translation"
] | If this was PHP, I would probably do something like this:
```
function no_more_half_widths($string){
$foo = array('ï¼','ï¼','ï¼','ï¼','ï¼','ï¼','ï¼','ï¼','ï¼','ï¼ï¼')
$bar = array('1','2','3','4','5','6','7','8','9','10')
return str_replace($foo, $bar, $string)
}
```
I have tried the .translate funct... | The built-in `unicodedata` module can do it:
```
>>> import unicodedata
>>> foo = u'ï¼ï¼ï¼ï¼ï¼ï¼ï¼ï¼ï¼ï¼'
>>> unicodedata.normalize('NFKC', foo)
u'1234567890'
```
The âNFKCâ stands for â[Normalization Form](http://unicode.org/reports/tr15/) KC [Compatibility Decomposition, followed by Canonical Compos... |
How do I create a list with 256 elements? | 2,422,461 | 2 | 2010-03-11T04:05:42Z | 2,422,501 | 7 | 2010-03-11T04:16:23Z | [
"python"
] | I've started teaching myself Python, and as an exercise I've set myself the task of generating lookup tables I need for another project.
I need to generate a list of 256 elements in which each element is the value of `math.sin(2*i*pi/256)`. The problem is, I don't know how to generate a list initialized to "dummy" val... | Two answers have already shown you how to build your list at a single stroke, using the "list comprehension" (AKA "listcomp") construct.
To answer your specific question, though,
```
mylist = [None] * 256
```
is the simplest way to make a list with 256 items, all `None`, in case you want to fill it in later.
If you... |
Python os.path.join on Windows | 2,422,798 | 45 | 2010-03-11T05:38:19Z | 2,422,847 | 7 | 2010-03-11T05:47:30Z | [
"python",
"windows",
"path-manipulation"
] | I am trying to learn python and am making a program that will output a script. I want to use os.path.join, but am pretty confused. According to the [docs](http://docs.python.org/library/os.path.html) if I say:
```
os.path.join('c:', 'sourcedir')
```
I get `"C:sourcedir"`. According to the docs, this is normal, right?... | The reason `os.path.join('C:', 'src')` is not working as you expect is because of something in the documentation that you linked to:
> Note that on Windows, since there is a
> current directory for each drive,
> os.path.join("c:", "foo") represents a
> path relative to the current directory
> on drive C: (c:foo), not ... |
Python os.path.join on Windows | 2,422,798 | 45 | 2010-03-11T05:38:19Z | 2,422,864 | 20 | 2010-03-11T05:52:34Z | [
"python",
"windows",
"path-manipulation"
] | I am trying to learn python and am making a program that will output a script. I want to use os.path.join, but am pretty confused. According to the [docs](http://docs.python.org/library/os.path.html) if I say:
```
os.path.join('c:', 'sourcedir')
```
I get `"C:sourcedir"`. According to the docs, this is normal, right?... | Windows has a concept of current directory for each drive. Because of that, `"c:sourcedir"` means "sourcedir" inside the current C: directory, and you'll need to specify an absolute directory.
Any of these should work and give the same result, but I don't have a Windows VM fired up at the moment to double check:
```
... |
Python os.path.join on Windows | 2,422,798 | 45 | 2010-03-11T05:38:19Z | 7,435,335 | 8 | 2011-09-15T17:56:29Z | [
"python",
"windows",
"path-manipulation"
] | I am trying to learn python and am making a program that will output a script. I want to use os.path.join, but am pretty confused. According to the [docs](http://docs.python.org/library/os.path.html) if I say:
```
os.path.join('c:', 'sourcedir')
```
I get `"C:sourcedir"`. According to the docs, this is normal, right?... | To be pedantic, it's probably not good to hardcode either / or \ as the path separator. Maybe this would be best?
```
mypath = os.path.join('c:%s' % os.sep, 'sourcedir')
```
or
```
mypath = os.path.join('c:' + os.sep, 'sourcedir')
``` |
Python os.path.join on Windows | 2,422,798 | 45 | 2010-03-11T05:38:19Z | 7,767,925 | 45 | 2011-10-14T12:56:25Z | [
"python",
"windows",
"path-manipulation"
] | I am trying to learn python and am making a program that will output a script. I want to use os.path.join, but am pretty confused. According to the [docs](http://docs.python.org/library/os.path.html) if I say:
```
os.path.join('c:', 'sourcedir')
```
I get `"C:sourcedir"`. According to the docs, this is normal, right?... | To be even more pedantic, the most python doc consistent answer would be:
```
mypath = os.path.join('c:', os.sep, 'sourcedir')
```
Since you also need os.sep for the posix root path:
```
mypath = os.path.join(os.sep, 'usr', 'lib')
``` |
Python: avoiding if condition? | 2,422,905 | 4 | 2010-03-11T06:00:17Z | 2,422,919 | 7 | 2010-03-11T06:02:35Z | [
"python",
"variable-assignment",
"condition"
] | Which is better?
```
if not var:
var = get_var()
```
(or)
> var = var or get\_var()
Also, How do I know the better of the two?
**edit:**
One more option from steve,
```
var = var if var else get_var()
``` | The better is the one you like better. I would use first version with `if` but this is very personal. |
Python: avoiding if condition? | 2,422,905 | 4 | 2010-03-11T06:00:17Z | 2,422,952 | 7 | 2010-03-11T06:12:22Z | [
"python",
"variable-assignment",
"condition"
] | Which is better?
```
if not var:
var = get_var()
```
(or)
> var = var or get\_var()
Also, How do I know the better of the two?
**edit:**
One more option from steve,
```
var = var if var else get_var()
``` | When two style variations are so close stylistically, I use `timeit` as the tie-breaker: faster must mean closer to Python's mainstream, i.e., better. Hey, it's better than endless debate, y?-) So:
```
$ python -mtimeit -s'var=0; getvar=lambda:0' 'var = var or getvar()'
1000000 loops, best of 3: 0.359 usec per loop
$ ... |
Python urllib3 and how to handle cookie support? | 2,422,922 | 6 | 2010-03-11T06:03:10Z | 2,423,176 | 8 | 2010-03-11T07:07:21Z | [
"python",
"urllib3"
] | So I'm looking into [urllib3](http://code.google.com/p/urllib3/) because it has connection pooling and is thread safe (so performance is better, especially for crawling), but the documentation is... minimal to say the least. urllib2 has build\_opener so something like:
```
#!/usr/bin/python
import cookielib, urllib2
c... | You're correct, there's no immediately better way to do this right now. I would be more than happy to accept a patch if you have a congruent improvement.
One thing to keep in mind, urllib3's HTTPConnectionPool is intended to be a "pool of connections" to a specific host, as opposed to a stateful client. In that contex... |
In Python, is this a good practice? | 2,423,145 | 2 | 2010-03-11T06:59:34Z | 2,423,164 | 12 | 2010-03-11T07:05:04Z | [
"python"
] | ```
try:
spam.foo
except AttributeError:
do_somthing()
```
(Is it wise to check an attribute like that without using it?) | **Update**:
If you are really only interested in whether the attribute `foo` exists (and not doing something with the attribute) than of course `hasattr()` might be better way to check for the attribute.
From a *developer/user* point of view I have to confess that, for me, the use of `hasattr()` better reflects your... |
Python decompressing gzip chunk-by-chunk | 2,423,866 | 26 | 2010-03-11T09:35:35Z | 2,424,549 | 34 | 2010-03-11T11:40:57Z | [
"python",
"gzip",
"zlib"
] | I've a memory- and disk-limited environment where I need to decompress the contents of a gzip file sent to me in string-based chunks (over xmlrpc binary transfer). However, using the zlib.decompress() or zlib.decompressobj()/decompress() both barf over the gzip header. I've tried offsetting past the gzip header (docume... | gzip and zlib use slightly different headers.
See <http://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib>
Try `d = zlib.decompressobj(16+zlib.MAX_WBITS)`.
And you might try changing your chunk size to a power of 2 (say `CHUNKSIZE=1024`) for possible performance reasons. |
Read and overwrite a file in Python | 2,424,000 | 51 | 2010-03-11T10:01:43Z | 2,424,018 | 10 | 2010-03-11T10:04:09Z | [
"python",
"file",
"overwrite"
] | Currently I'm using this:
```
f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.close()
```
But the problem is that the old file is larger than the new file. So I end up with a new file that has a part of the old file on the end of it. | Probably it would be easier and neater to close the file after `text = re.sub('foobar', 'bar', text)`, re-open it for writing (thus clearing old contents), and write your updated text to it. |
Read and overwrite a file in Python | 2,424,000 | 51 | 2010-03-11T10:01:43Z | 2,424,044 | 7 | 2010-03-11T10:08:38Z | [
"python",
"file",
"overwrite"
] | Currently I'm using this:
```
f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.close()
```
But the problem is that the old file is larger than the new file. So I end up with a new file that has a part of the old file on the end of it. | The [`fileinput`](https://docs.python.org/2/library/fileinput.html) module has an `inline` mode for writing changes to the file you are processing without using temporary files etc. The module nicely encapsulates the common operation of looping over the lines in a list of files, via an object which transparently keeps ... |
Read and overwrite a file in Python | 2,424,000 | 51 | 2010-03-11T10:01:43Z | 2,424,410 | 96 | 2010-03-11T11:16:18Z | [
"python",
"file",
"overwrite"
] | Currently I'm using this:
```
f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.close()
```
But the problem is that the old file is larger than the new file. So I end up with a new file that has a part of the old file on the end of it. | If you don't want to close and reopen the file, to avoid race conditions, you could [`truncate`](https://docs.python.org/3/library/io.html#io.IOBase.truncate) it:
```
f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()
f.close()
```
The functionality may ... |
What is the easiest way to convert list with str into list with int? | 2,424,412 | 10 | 2010-03-11T11:16:55Z | 2,424,425 | 16 | 2010-03-11T11:18:49Z | [
"python",
"string",
"integer"
] | What is the easiest way to convert list with `str` into list with `int` in Python?
For example, we have to convert `['1', '2', '3']` to `[1, 2, 3]`. Of course, we can use a `for` loop, but it's too easy. | Python 2.x:
```
map(int, ["1", "2", "3"])
```
Python 3.x (in 3.x, `map` returns an iterator, not a list as in 2.x):
```
list(map(int, ["1", "2", "3"]))
```
`map` documentation: [2.6](http://docs.python.org/library/functions.html#map), [3.1](http://docs.python.org/3.1/library/functions.html#map) |
What is the easiest way to convert list with str into list with int? | 2,424,412 | 10 | 2010-03-11T11:16:55Z | 2,424,434 | 17 | 2010-03-11T11:19:35Z | [
"python",
"string",
"integer"
] | What is the easiest way to convert list with `str` into list with `int` in Python?
For example, we have to convert `['1', '2', '3']` to `[1, 2, 3]`. Of course, we can use a `for` loop, but it's too easy. | ```
[int(i) for i in str_list]
``` |
How to get a list with elements that are contained in two other lists? | 2,424,700 | 2 | 2010-03-11T12:03:33Z | 2,424,712 | 8 | 2010-03-11T12:06:03Z | [
"python"
] | We have two lists:
```
a=['1','2','3','4']
b=['2','3','4','5']
```
How to get a list with elements that are contained in both lists:
```
a_and_b=['2','3','4']
```
and a list with elements that are contained only in one list, but not the other:
```
only_a=['1']
only_b=['5']
```
Yes, I can use cycles, but it's lame... | if order is not important
```
>>> a=['1','2','3','4']
>>> b=['2','3','4','5']
>>> set(a) & set(b)
set(['3', '2', '4'])
```
only a
```
>>> set(a).difference(b) # or set(a) - set(b)
set(['1'])
```
only b
```
>>> set(b).difference(a) # or set(b) - set(a)
set(['5'])
``` |
Python vs Bash - In which kind of tasks each one outruns the other performance-wise? | 2,424,921 | 42 | 2010-03-11T12:42:52Z | 2,424,971 | 19 | 2010-03-11T12:50:50Z | [
"python",
"performance",
"bash"
] | Obviously Python is more user friendly, a quick search on google shows many results that say that, as Python is byte-compiled is usually faster. I even found [this](http://www.murga-linux.com/puppy/viewtopic.php?mode=attach&id=16212&sid=9ec56d74e859eb32ab750e74981181a7) that claims that you can see an improvement of ov... | **Developer efficiency** matters much more to me in scenarios where both bash and Python are sensible choices.
Some tasks lend themselves well to bash, and others to Python. It also isn't unusual for me to start something as a bash script and change it to Python as it evolves over several weeks.
A big advantage Pytho... |
Python vs Bash - In which kind of tasks each one outruns the other performance-wise? | 2,424,921 | 42 | 2010-03-11T12:42:52Z | 2,426,281 | 10 | 2010-03-11T15:37:06Z | [
"python",
"performance",
"bash"
] | Obviously Python is more user friendly, a quick search on google shows many results that say that, as Python is byte-compiled is usually faster. I even found [this](http://www.murga-linux.com/puppy/viewtopic.php?mode=attach&id=16212&sid=9ec56d74e859eb32ab750e74981181a7) that claims that you can see an improvement of ov... | Bash is primarily a batch / shell scripting language with far less support for various data types and all sorts of quirks around control structures -- not to mention compatibility issues.
Which is faster? Neither, because you are not comparing apples to apples here. If you had to sort an ascii text file and you were u... |
Python vs Bash - In which kind of tasks each one outruns the other performance-wise? | 2,424,921 | 42 | 2010-03-11T12:42:52Z | 2,441,363 | 48 | 2010-03-14T06:09:42Z | [
"python",
"performance",
"bash"
] | Obviously Python is more user friendly, a quick search on google shows many results that say that, as Python is byte-compiled is usually faster. I even found [this](http://www.murga-linux.com/puppy/viewtopic.php?mode=attach&id=16212&sid=9ec56d74e859eb32ab750e74981181a7) that claims that you can see an improvement of ov... | Generally, bash works better than python only in those environments where python is not available. :)
Seriously, I have to deal with both languages daily, and will take python instantly over bash if given the choice. Alas, I am forced to use bash on certain "small" platforms because someone has (mistakenly, IMHO) deci... |
Python vs Bash - In which kind of tasks each one outruns the other performance-wise? | 2,424,921 | 42 | 2010-03-11T12:42:52Z | 10,562,652 | 7 | 2012-05-12T09:49:21Z | [
"python",
"performance",
"bash"
] | Obviously Python is more user friendly, a quick search on google shows many results that say that, as Python is byte-compiled is usually faster. I even found [this](http://www.murga-linux.com/puppy/viewtopic.php?mode=attach&id=16212&sid=9ec56d74e859eb32ab750e74981181a7) that claims that you can see an improvement of ov... | If you are looking to cobble together a quick utility with minimal effort, bash is good. For a wrapper round an application, bash is invaluable.
Anything that may have you coming back over and over to add improvements is probably (though not always) better suited to a language like Python as Bash code comprising over ... |
Python vs Bash - In which kind of tasks each one outruns the other performance-wise? | 2,424,921 | 42 | 2010-03-11T12:42:52Z | 14,476,979 | 26 | 2013-01-23T10:05:05Z | [
"python",
"performance",
"bash"
] | Obviously Python is more user friendly, a quick search on google shows many results that say that, as Python is byte-compiled is usually faster. I even found [this](http://www.murga-linux.com/puppy/viewtopic.php?mode=attach&id=16212&sid=9ec56d74e859eb32ab750e74981181a7) that claims that you can see an improvement of ov... | **Typical mainframe flow...**
```
Input Disk/Tape/User (runtime) --> Job Control Language (JCL) --> Output Disk/Tape/Screen/Printer
| ^
v |
--> COBOL Program ----
```
**Typ... |
Python vs Bash - In which kind of tasks each one outruns the other performance-wise? | 2,424,921 | 42 | 2010-03-11T12:42:52Z | 25,171,738 | 8 | 2014-08-06T23:05:54Z | [
"python",
"performance",
"bash"
] | Obviously Python is more user friendly, a quick search on google shows many results that say that, as Python is byte-compiled is usually faster. I even found [this](http://www.murga-linux.com/puppy/viewtopic.php?mode=attach&id=16212&sid=9ec56d74e859eb32ab750e74981181a7) that claims that you can see an improvement of ov... | Performance-wise bash outperforms python in the process startup time.
Here are some measurements from my core i7 laptop running Linux Mint:
```
Starting process Startup time
empty /bin/sh script 1.7 ms
empty /bin/bash script 2.8 ms
empty python script ... |
Are zlib.compress on Python and Deflater.deflate on Java (Android) compatible? | 2,424,945 | 6 | 2010-03-11T12:45:52Z | 2,426,740 | 7 | 2010-03-11T16:28:29Z | [
"java",
"python",
"android",
"zlib",
"deflate"
] | I am porting a Python application to Android and, at some point, this application has to communicate with a Web Service, sending it compressed data.
In order to do that it uses the next method:
```
def stuff(self, data):
"Convert into UTF-8 and compress."
return zlib.compress(simplejson.dumps(data))
```
I am... | compress and deflate are different compression algorithms so the answer is they will not be compatible. As an example of the difference here is 'a' compressed using the two algorithms via Tcl:
```
% binary encode hex [zlib compress a]
789c4b040000620062
% binary encode hex [zlib deflate a]
4b0400
```
Your python code... |
How to write a generator that returns ALL-BUT-LAST items in the iterable in Python? | 2,425,096 | 4 | 2010-03-11T13:11:18Z | 2,425,143 | 10 | 2010-03-11T13:18:01Z | [
"python"
] | I asked some similar questions [1, 2] yesterday and got great answers, but I am not yet technically skilled enough to write a generator of such sophistication myself.
How could I write a generator that would raise StopIteration if it's the last item, instead of yielding it?
I am thinking I should somehow ask two valu... | This should do the trick:
```
def allbutlast(iterable):
it = iter(iterable)
current = it.next()
for i in it:
yield current
current = i
>>> list(allbutlast([1,2,3]))
[1, 2]
```
This will iterate through the entire list, and return the previous item so the last item is never returned.
No... |
How to look ahead one element in a Python generator? | 2,425,270 | 33 | 2010-03-11T13:34:58Z | 2,425,347 | 31 | 2010-03-11T13:46:09Z | [
"python",
"generator"
] | I can't figure out how to look ahead one element in a Python generator. As soon as I look it's gone.
Here is what I mean:
```
gen = iter([1,2,3])
next_value = gen.next() # okay, I looked forward and see that next_value = 1
# but now:
list(gen) # is [2, 3] -- the first value is gone!
```
Here is a more real exampl... | The Python generator API is one way: You can't push back elements you've read. But you can create a new iterator using the [itertools module](http://docs.python.org/library/itertools.html) and prepend the element:
```
import itertools
gen = iter([1,2,3])
peek = gen.next()
print list(itertools.chain([peek], gen))
``` |
How to look ahead one element in a Python generator? | 2,425,270 | 33 | 2010-03-11T13:34:58Z | 10,576,559 | 18 | 2012-05-14T01:18:25Z | [
"python",
"generator"
] | I can't figure out how to look ahead one element in a Python generator. As soon as I look it's gone.
Here is what I mean:
```
gen = iter([1,2,3])
next_value = gen.next() # okay, I looked forward and see that next_value = 1
# but now:
list(gen) # is [2, 3] -- the first value is gone!
```
Here is a more real exampl... | Ok - two years too late - but I came across this question, and did not find any of the answers to my satisfaction. Came up with this meta generator:
```
class Peekorator(object):
def __init__(self, generator):
self.empty = False
self.peek = None
self.generator = generator
try:
... |
How to look ahead one element in a Python generator? | 2,425,270 | 33 | 2010-03-11T13:34:58Z | 12,059,829 | 14 | 2012-08-21T17:13:24Z | [
"python",
"generator"
] | I can't figure out how to look ahead one element in a Python generator. As soon as I look it's gone.
Here is what I mean:
```
gen = iter([1,2,3])
next_value = gen.next() # okay, I looked forward and see that next_value = 1
# but now:
list(gen) # is [2, 3] -- the first value is gone!
```
Here is a more real exampl... | You can use itertools.tee to produce a lightweight copy of the generator. Then peeking ahead at one copy will not affect the second copy:
```
import itertools
copy1, copy2 = itertools.tee(original_generator)
if copy1.next() == "STOP":
stop_application()
process_items(copy2)
```
The 'copy2' generator is unaffected... |
How to look ahead one element in a Python generator? | 2,425,270 | 33 | 2010-03-11T13:34:58Z | 27,698,681 | 28 | 2014-12-30T01:59:05Z | [
"python",
"generator"
] | I can't figure out how to look ahead one element in a Python generator. As soon as I look it's gone.
Here is what I mean:
```
gen = iter([1,2,3])
next_value = gen.next() # okay, I looked forward and see that next_value = 1
# but now:
list(gen) # is [2, 3] -- the first value is gone!
```
Here is a more real exampl... | For sake of completeness, the [`more-itertools` package](https://pypi.python.org/pypi/more-itertools) (which should probably be part of any Python programmer's toolbox) includes a `peekable` wrapper that implements this behavior. As the code example in [the documentation](https://pythonhosted.org/more-itertools/api.htm... |
How to dynamically access class properties in Python? | 2,425,272 | 11 | 2010-03-11T13:35:10Z | 2,425,281 | 27 | 2010-03-11T13:36:50Z | [
"python",
"class"
] | Let's say I create an instance of a class and want to assign some values to its public properties. Usually, this would be done like this:
```
class MyClass:
def __init__(self):
self.name = None
self.text = None
myclass = MyClass()
myclass.name = 'My name'
```
But, what if a write a function that ... | ```
setattr(my_class_instance, 'attr_name', attr_value)
``` |
How do I select from multiple tables in one query with Django? | 2,425,603 | 6 | 2010-03-11T14:17:04Z | 2,425,642 | 19 | 2010-03-11T14:21:50Z | [
"python",
"django",
"join",
"django-queryset"
] | I have two tables, one "Company" and one "Employee":
```
class Company(models.Model):
name = models.CharField(max_length=60)
class Employee(models.Model):
name = models.CharField(max_length=60)
company = models.ForeignField(Company)
```
And I want to list every Employee in a table, with the Company next ... | Using [`select_related()`](http://docs.djangoproject.com/en/dev/ref/models/querysets/#id4) will pre-populate the appropriate attributes:
```
Employee.objects.select_related()
``` |
How to prevent a function from being overridden in python | 2,425,656 | 20 | 2010-03-11T14:24:32Z | 2,425,785 | 24 | 2010-03-11T14:39:01Z | [
"python",
"override",
"final"
] | Is there a way to make a class function unoverriddable? something like java's `final` keyword. i.e, any overriding class cannot override that method. | The issue is you are trying to write in Python using Java philosophies. Some thing carry over, but not all of them. In Python you can do the following and it is perfectly fine, but completely goes against how Java thinks of objects.
```
class Thing(object):
x = 1
something = Thing()
something.y = something.x
```
... |
How to prevent a function from being overridden in python | 2,425,656 | 20 | 2010-03-11T14:24:32Z | 2,425,818 | 47 | 2010-03-11T14:42:08Z | [
"python",
"override",
"final"
] | Is there a way to make a class function unoverriddable? something like java's `final` keyword. i.e, any overriding class cannot override that method. | You could put a comment in there to the effect of:
```
# We'll fire you if you override this method.
```
It's surprising how well low-tech solutions like this work in practice. |
Timeout for xmlrpclib client requests | 2,425,799 | 3 | 2010-03-11T14:40:35Z | 2,426,293 | 9 | 2010-03-11T15:37:48Z | [
"python",
"xmlrpclib"
] | I am using Python's xmlrpclib to make requests to an xml-rpc service.
Is there a way to set a client timeout, so my requests don't hang forever when the server is not available?
I know I can globally set a socket timeout with `socket.setdefaulttimeout()`, but that is not preferable. | The clean approach is to define and use a custom transport, e.g.:
! this will work only for python2.7 !
```
import xmlrpclib, httplib
class TimeoutTransport(xmlrpclib.Transport):
timeout = 10.0
def set_timeout(self, timeout):
self.timeout = timeout
def make_connection(self, host):
h = http... |
Timeout for xmlrpclib client requests | 2,425,799 | 3 | 2010-03-11T14:40:35Z | 6,014,897 | 8 | 2011-05-16T08:42:05Z | [
"python",
"xmlrpclib"
] | I am using Python's xmlrpclib to make requests to an xml-rpc service.
Is there a way to set a client timeout, so my requests don't hang forever when the server is not available?
I know I can globally set a socket timeout with `socket.setdefaulttimeout()`, but that is not preferable. | doh, to make this work in python2.6+ do this:
```
class HTTP_with_timeout(httplib.HTTP):
def __init__(self, host='', port=None, strict=None, timeout=5.0):
if port == 0: port = None
self._setup(self._connection_class(host, port, strict, timeout=timeout))
def getresponse(self, *args, **kw):
... |
How to join list of strings? | 2,426,988 | 5 | 2010-03-11T16:58:48Z | 2,427,007 | 13 | 2010-03-11T17:01:03Z | [
"python",
"string"
] | This is probably seriously easy to solve for most of you but I cannot solve this simply putting `str()` around it can I?
I would like to convert this list: `['A','B','C']` into `'A B C'`.
Thanks in advance!! | ```
In [1]: L = ['A', 'B', 'C']
In [2]: " ".join(L)
Out[2]: 'A B C'
``` |
How to do Python's zip in C#? | 2,427,015 | 10 | 2010-03-11T17:02:04Z | 2,427,055 | 7 | 2010-03-11T17:06:16Z | [
"c#",
".net",
"python",
"linq",
"zip"
] | Python's `zip` function does the following:
```
a = [1, 2, 3]
b = [6, 7, 8]
zipped = zip(a, b)
```
result
```
[[1, 6], [2, 7], [3, 8]]
``` | How about [this](http://bartdesmet.net/blogs/bart/archive/2008/11/03/c-4-0-feature-focus-part-3-intermezzo-linq-s-new-zip-operator.aspx)?
C# 4.0 LINQ'S NEW ZIP OPERATOR
```
public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(
this IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
... |
Thread-safe equivalent to python's time.strptime()? | 2,427,240 | 15 | 2010-03-11T17:33:30Z | 2,427,308 | 21 | 2010-03-11T17:46:01Z | [
"python"
] | Something I wrote throws a lot of `AttributeError` exceptions when using time.strptime() inside a thread. This only seems to happen on Windows (not on Linux) but whatever- upon a'Googling, it seems that time.strptime() isn't considered thread-safe.
Is there a better way to create a datetime object from a string? Curre... | According to the [bug report](http://bugs.python.org/issue7980), this doesn't happen if you call `strptime` once before creating your threads. I've done a little testing which seems to confirm this. So just make any call to `strptime` during initialization as a workaround. |
Thread-safe equivalent to python's time.strptime()? | 2,427,240 | 15 | 2010-03-11T17:33:30Z | 22,476,843 | 9 | 2014-03-18T10:38:54Z | [
"python"
] | Something I wrote throws a lot of `AttributeError` exceptions when using time.strptime() inside a thread. This only seems to happen on Windows (not on Linux) but whatever- upon a'Googling, it seems that time.strptime() isn't considered thread-safe.
Is there a better way to create a datetime object from a string? Curre... | Just another workaround for this bug, you can simply import `_strptime` manually, along with datetime
```
import _strptime
from datetime import datetime
# then, in threaded block
datetime.strptime(date, format)
``` |
Python Question: Year and Day of Year to date? | 2,427,555 | 27 | 2010-03-11T18:21:43Z | 2,427,578 | 15 | 2010-03-11T18:25:30Z | [
"python",
"date",
"julian-date"
] | I have a year value and a day of year and would like to convert to a date (day/month/year).
Thanks in advance. :) | ```
>>> import datetime
>>> datetime.datetime.strptime('2010 120', '%Y %j')
datetime.datetime(2010, 4, 30, 0, 0)
>>> _.strftime('%d/%m/%Y')
'30/04/2010'
``` |
Python Question: Year and Day of Year to date? | 2,427,555 | 27 | 2010-03-11T18:21:43Z | 2,427,581 | 40 | 2010-03-11T18:26:01Z | [
"python",
"date",
"julian-date"
] | I have a year value and a day of year and would like to convert to a date (day/month/year).
Thanks in advance. :) | ```
datetime.datetime(year, 1, 1) + datetime.timedelta(days - 1)
``` |
Creating a JSON response using Django and Python | 2,428,092 | 249 | 2010-03-11T19:40:35Z | 2,428,119 | 559 | 2010-03-11T19:44:55Z | [
"python",
"django",
"json"
] | I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working.
This is the server-side script:
```
/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];
/* RETURN VALUE */
$arrayToJs... | I usually use a dictionary, not a list to return JSON content.
```
import json
from django.http import HttpResponse
response_data = {}
response_data['result'] = 'error'
response_data['message'] = 'Some error message'
```
Pre-Django 1.7 you'd return it like this:
```
return HttpResponse(json.dumps(response_data), c... |
Creating a JSON response using Django and Python | 2,428,092 | 249 | 2010-03-11T19:40:35Z | 2,428,192 | 121 | 2010-03-11T19:55:29Z | [
"python",
"django",
"json"
] | I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working.
This is the server-side script:
```
/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];
/* RETURN VALUE */
$arrayToJs... | I use this, it works fine.
```
from django.utils import simplejson
from django.http import HttpResponse
def some_view(request):
to_json = {
"key1": "value1",
"key2": "value2"
}
return HttpResponse(simplejson.dumps(to_json), mimetype='application/json')
```
Alternative:
```
from django.ut... |
Creating a JSON response using Django and Python | 2,428,092 | 249 | 2010-03-11T19:40:35Z | 11,470,298 | 9 | 2012-07-13T12:14:10Z | [
"python",
"django",
"json"
] | I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working.
This is the server-side script:
```
/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];
/* RETURN VALUE */
$arrayToJs... | You'll want to use the django serializer to help with unicode stuff:
```
from django.core import serializers
json_serializer = serializers.get_serializer("json")()
response = json_serializer.serialize(list, ensure_ascii=False, indent=2, use_natural_keys=True)
return HttpResponse(response, mimetype="applicati... |
Creating a JSON response using Django and Python | 2,428,092 | 249 | 2010-03-11T19:40:35Z | 16,360,219 | 13 | 2013-05-03T13:35:45Z | [
"python",
"django",
"json"
] | I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working.
This is the server-side script:
```
/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];
/* RETURN VALUE */
$arrayToJs... | ```
from django.http import HttpResponse
import json
class JsonResponse(HttpResponse):
def __init__(self, content={}, mimetype=None, status=None,
content_type='application/json'):
super(JsonResponse, self).__init__(json.dumps(content), mimetype=mimetype,
... |
Creating a JSON response using Django and Python | 2,428,092 | 249 | 2010-03-11T19:40:35Z | 24,411,716 | 110 | 2014-06-25T14:41:22Z | [
"python",
"django",
"json"
] | I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working.
This is the server-side script:
```
/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];
/* RETURN VALUE */
$arrayToJs... | New in django 1.7
you could use [JsonResponse](https://docs.djangoproject.com/en/dev/ref/request-response/#jsonresponse-objects) objects.
from the docs:
```
from django.http import JsonResponse
return JsonResponse({'foo':'bar'})
``` |
Creating a JSON response using Django and Python | 2,428,092 | 249 | 2010-03-11T19:40:35Z | 26,653,011 | 16 | 2014-10-30T12:29:12Z | [
"python",
"django",
"json"
] | I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working.
This is the server-side script:
```
/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];
/* RETURN VALUE */
$arrayToJs... | Since Django 1.7 you have a standard [JsonResponse](https://docs.djangoproject.com/en/1.7/ref/request-response/#jsonresponse-objects) that's exactly what you need:
```
from django.http import JsonResponse
...
return JsonResponse(array_to_js, safe=False)
```
You don't even need to json.dump your array. |
Creating a JSON response using Django and Python | 2,428,092 | 249 | 2010-03-11T19:40:35Z | 32,466,453 | 10 | 2015-09-08T20:12:30Z | [
"python",
"django",
"json"
] | I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working.
This is the server-side script:
```
/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];
/* RETURN VALUE */
$arrayToJs... | For those who use Django 1.7+
```
from django.http import JsonResponse
def your_view(request):
json_object = {'key': "value"}
return JsonResponse(json_object)
```
[official docs](https://docs.djangoproject.com/en/1.8/ref/request-response/#jsonresponse-objects) |
casting raw strings python | 2,428,117 | 26 | 2010-03-11T19:44:30Z | 2,428,132 | 54 | 2010-03-11T19:46:50Z | [
"python",
"string",
"python-2.x"
] | in python, given a variable which holds a string is there a quick way to cast that into another raw string variable?
the following code should illustrate what im after...
```
def checkEqual(x, y):
print True if x==y else False
line1 = "hurr..\n..durr"
line2 = r"hurr..\n..durr"
line3 = "%r"%line1
print "%s \n\n%... | ```
"hurr..\n..durr".encode('string-escape')
``` |
Should I worry about circular references in Python? | 2,428,301 | 27 | 2010-03-11T20:11:28Z | 2,428,360 | 9 | 2010-03-11T20:17:49Z | [
"python"
] | Suppose I have code that maintains a parent/children structure. In such a structure I get circular references, where a child points to a parent and a parent points to a child. Should I worry about them? I'm using Python 2.5.
I am concerned that they will not be garbage collected and the application will eventually con... | Python will detect the cycle and release the memory when there are no outside references. |
Should I worry about circular references in Python? | 2,428,301 | 27 | 2010-03-11T20:11:28Z | 2,428,361 | 13 | 2010-03-11T20:18:00Z | [
"python"
] | Suppose I have code that maintains a parent/children structure. In such a structure I get circular references, where a child points to a parent and a parent points to a child. Should I worry about them? I'm using Python 2.5.
I am concerned that they will not be garbage collected and the application will eventually con... | Experimentally: you're fine:
```
import itertools
for i in itertools.count():
a = {}
b = {"a":a}
a["b"] = b
```
It consistently stays at using 3.6 MB of RAM. |
Should I worry about circular references in Python? | 2,428,301 | 27 | 2010-03-11T20:11:28Z | 2,428,888 | 22 | 2010-03-11T21:37:46Z | [
"python"
] | Suppose I have code that maintains a parent/children structure. In such a structure I get circular references, where a child points to a parent and a parent points to a child. Should I worry about them? I'm using Python 2.5.
I am concerned that they will not be garbage collected and the application will eventually con... | "Worry" is misplaced, but if your program turns out to be slow, consume more memory than expected, or have strange inexplicable pauses, the cause is indeed likely to be in those garbage reference loops -- they need to be garbage collected by a different procedure than "normal" (acyclic) reference graphs, and that colle... |
Concise way to getattr() and use it if not None in Python | 2,428,557 | 18 | 2010-03-11T20:50:42Z | 2,428,876 | 22 | 2010-03-11T21:36:00Z | [
"python"
] | I am finding myself doing the following a bit too often:
```
attr = getattr(obj, 'attr', None)
if attr is not None:
attr()
# Do something, either attr(), or func(attr), or whatever
else:
# Do something else
```
Is there a more pythonic way of writing that? Is this better? (At least not in performance, IMO... | Since you are calling the `attr`, you could just do:
```
def default_action():
# do something else
action = getattr(obj, 'attr', default_action)
action()
``` |
datetime command line argument in python 2.4 | 2,428,746 | 7 | 2010-03-11T21:16:13Z | 2,428,785 | 14 | 2010-03-11T21:23:10Z | [
"python",
"datetime"
] | I want to pass a datetime value into my python script on the command line. My first idea was to use optparse and pass the value in as a string, then use datetime.strptime to convert it to a datetime. This works fine on my machine (python 2.6), but I also need to run this script on machines that are running python 2.4, ... | Go by way of the `time` module, which did already have `strptime` in 2.4:
```
>>> import time
>>> t = time.strptime("2010-02-02 7:31", "%Y-%m-%d %H:%M")
>>> t
(2010, 2, 2, 7, 31, 0, 1, 33, -1)
>>> import datetime
>>> datetime.datetime(*t[:6])
datetime.datetime(2010, 2, 2, 7, 31)
``` |
How to treat the last element in list differently in Python? | 2,429,098 | 28 | 2010-03-11T22:15:02Z | 2,429,118 | 32 | 2010-03-11T22:17:48Z | [
"python"
] | I need to do some special operation for the last element in a list.
Is there any better way than this?
```
array = [1,2,3,4,5]
for i, val in enumerate(array):
if (i+1) == len(array):
// Process for the last element
else:
// Process for the other element
``` | ```
for item in list[:-1]:
print "Not last: ", item
print "Last: ", list[-1]
```
If you don't want to make a copy of list, you can make a simple generator:
```
# itr is short for "iterable" and can be any sequence, iterator, or generator
def notlast(itr):
itr = iter(itr) # ensure we have an iterator
pre... |
How to treat the last element in list differently in Python? | 2,429,098 | 28 | 2010-03-11T22:15:02Z | 2,429,129 | 20 | 2010-03-11T22:18:41Z | [
"python"
] | I need to do some special operation for the last element in a list.
Is there any better way than this?
```
array = [1,2,3,4,5]
for i, val in enumerate(array):
if (i+1) == len(array):
// Process for the last element
else:
// Process for the other element
``` | If your sequence isn't terribly long then you can just slice it:
```
for val in array[:-1]:
do_something(val)
else:
do_something_else(array[-1])
``` |
How to determine if the given object is of given type in Python? | 2,429,164 | 4 | 2010-03-11T22:23:55Z | 2,429,175 | 7 | 2010-03-11T22:25:06Z | [
"python",
"types"
] | I always thought operator `is` determined if the given variable is of the given type. But I just determined it was not true:
```
>>> class A():
pass
...
>>> a = A()
>>> a is A
False
```
How do I test if `a` is of type `class A`?
Please advise.
Thanks, Boda Cydo. | You want `isinstance(a, A)`.
Keep in mind, it might be better to avoid the `isinstance` check by adding methods to `A` that make it do what you want without explicitly determining that it is an `A`.
`is` determines if two objects are the same object. |
Why is Decimal('0') > 9999.0 True in Python? | 2,429,475 | 5 | 2010-03-11T23:40:06Z | 2,429,536 | 12 | 2010-03-11T23:55:26Z | [
"python",
"comparison",
"types",
"operators",
"logic"
] | This is somehow related to my question [Why is ''>0 True in Python?](http://stackoverflow.com/questions/2384078/why-is-0-true-in-python)
In Python 2.6.4:
```
>> Decimal('0') > 9999.0
True
```
From the [answer](http://stackoverflow.com/questions/2384078/why-is-0-true-in-python/2384090#2384090) to my original question... | Because the decimal module does not compare against any type except long, int, and Decimal. In all other cases, decimal silently returns the "not something it knows about object" as greater. You can see this behavior in the \_convert\_other() function of decimal.py
Silly, silly Decimal class.
*Oh, see <http://bugs.py... |
Why do people write #!/usr/bin/env python on the first line of a Python script? | 2,429,511 | 564 | 2010-03-11T23:50:54Z | 2,429,515 | 169 | 2010-03-11T23:52:37Z | [
"python",
"shell",
"shebang"
] | It seems to me like the files run the same without that line. | That is called the [shebang line](http://www.in-ulm.de/~mascheck/various/shebang/). As the [Wikipedia entry explains](http://en.wikipedia.org/wiki/Shebang_%28Unix%29):
> In computing, a shebang (also called a hashbang, hashpling, pound bang, or crunchbang) refers to the characters "#!" when they are the first two char... |
Why do people write #!/usr/bin/env python on the first line of a Python script? | 2,429,511 | 564 | 2010-03-11T23:50:54Z | 2,429,517 | 683 | 2010-03-11T23:52:41Z | [
"python",
"shell",
"shebang"
] | It seems to me like the files run the same without that line. | If you have several versions of Python installed, `/usr/bin/env` will ensure the interpreter used is the first one on your environment's `$PATH`. The alternative would be to hardcode something like `#!/usr/bin/python`; that's ok, but less flexible.
In Unix, an *executable* file that's meant to be interpreted can indic... |
Why do people write #!/usr/bin/env python on the first line of a Python script? | 2,429,511 | 564 | 2010-03-11T23:50:54Z | 2,429,524 | 8 | 2010-03-11T23:53:22Z | [
"python",
"shell",
"shebang"
] | It seems to me like the files run the same without that line. | This is a shell convention that tells the shell which program can execute the script.
```
#!/usr/bin/env python
```
resolves to a path to the Python binary. |
Why do people write #!/usr/bin/env python on the first line of a Python script? | 2,429,511 | 564 | 2010-03-11T23:50:54Z | 2,429,552 | 31 | 2010-03-11T23:58:43Z | [
"python",
"shell",
"shebang"
] | It seems to me like the files run the same without that line. | Technically, in Python, this is just a comment line.
This line is only used if you run the py script *from the shell* (from the command line). This is know as the ["*Shebang*!"](https://en.wikipedia.org/wiki/Shebang_(Unix)), and it is used in various situations, not just with Python scripts.
Here, it instructs the sh... |
Why do people write #!/usr/bin/env python on the first line of a Python script? | 2,429,511 | 564 | 2010-03-11T23:50:54Z | 2,429,730 | 107 | 2010-03-12T00:35:46Z | [
"python",
"shell",
"shebang"
] | It seems to me like the files run the same without that line. | Expanding a bit on the other answers, here's a little example of how your command line scripts can get into trouble by incautious use of `/usr/bin/env` shebang lines:
```
$ /usr/local/bin/python -V
Python 2.6.4
$ /usr/bin/python -V
Python 2.5.1
$ cat my_script.py
#!/usr/bin/env python
import json
print "hello, json"
... |
Why do people write #!/usr/bin/env python on the first line of a Python script? | 2,429,511 | 564 | 2010-03-11T23:50:54Z | 6,769,343 | 31 | 2011-07-20T22:34:10Z | [
"python",
"shell",
"shebang"
] | It seems to me like the files run the same without that line. | The main reason to do this is to make the script portable across operating system environments.
For example under mingw, python scripts use :
```
#!/c/python3k/python
```
and under GNU/Linux distribution it is either:
```
#!/usr/local/bin/python
```
or
```
#!/usr/bin/python
```
and under the best commercial Unix... |
Why do people write #!/usr/bin/env python on the first line of a Python script? | 2,429,511 | 564 | 2010-03-11T23:50:54Z | 8,463,033 | 11 | 2011-12-11T09:34:30Z | [
"python",
"shell",
"shebang"
] | It seems to me like the files run the same without that line. | It's recommended way, proposed in documentation:
> 2.2.2. Executable Python Scripts
>
> On BSDâish Unix systems, Python scripts can be made directly
> executable, like shell scripts, by putting the line
>
> ```
> #! /usr/bin/env python3.2
> ```
from <http://docs.python.org/py3k/tutorial/interpreter.html#executable-... |
Why do people write #!/usr/bin/env python on the first line of a Python script? | 2,429,511 | 564 | 2010-03-11T23:50:54Z | 9,865,189 | 65 | 2012-03-26T00:07:27Z | [
"python",
"shell",
"shebang"
] | It seems to me like the files run the same without that line. | In order to run the python script, we need to tell the shell three things:
1. That the file is a script
2. Which interpreter we want to execute the script
3. The path of said interpreter
The shebang `#!` accomplishes (1.). The shebang begins with a `#` because the `#` character is a comment marker in many scripting l... |
Why do people write #!/usr/bin/env python on the first line of a Python script? | 2,429,511 | 564 | 2010-03-11T23:50:54Z | 13,992,280 | 8 | 2012-12-21T14:52:58Z | [
"python",
"shell",
"shebang"
] | It seems to me like the files run the same without that line. | You can try this issue using virtualenv
Here is test.py
```
#! /usr/bin/env python
import sys
print(sys.version)
```
Create virtual environments
```
virtualenv test2.6 -p /usr/bin/python2.6
virtualenv test2.7 -p /usr/bin/python2.7
```
activate each environment then check the differences
```
echo $PATH
./test.py
`... |
Why do people write #!/usr/bin/env python on the first line of a Python script? | 2,429,511 | 564 | 2010-03-11T23:50:54Z | 22,475,174 | 15 | 2014-03-18T09:31:10Z | [
"python",
"shell",
"shebang"
] | It seems to me like the files run the same without that line. | It probably makes sense to emphasize one thing that the most have missed, which may prevent immediate understanding. When you type `python` in terminal you don't normally provide a full path. Instead, the executable is up looked in `PATH` environment variable. In turn, when you want to execute a Python program directly... |
Why do people write #!/usr/bin/env python on the first line of a Python script? | 2,429,511 | 564 | 2010-03-11T23:50:54Z | 27,998,855 | 23 | 2015-01-17T11:13:25Z | [
"python",
"shell",
"shebang"
] | It seems to me like the files run the same without that line. | Perhaps your question is in this sense:
If you want to use: `$python myscript.py`
You don't need that line at all. The system will call python and then python interpreter will run your script.
But if you intend to use: `$./myscript.py`
Calling it directly like a normal program or bash script, you need write that li... |
Python for loop question | 2,429,560 | 14 | 2010-03-12T00:00:39Z | 2,429,584 | 8 | 2010-03-12T00:04:13Z | [
"python",
"loops",
"for-loop"
] | I was wondering how to achieve the following in python:
```
for( int i = 0; cond...; i++)
if cond...
i++; //to skip an run-through
```
I tried this with no luck.
```
for i in range(whatever):
if cond... :
i += 1
``` | There is a `continue` keyword which skips the current iteration and advances to the next one (and a `break` keyword which skips all loop iterations and exits the loop):
```
for i in range(10):
if i % 2 == 0:
# skip even numbers
continue
print i
``` |
Python for loop question | 2,429,560 | 14 | 2010-03-12T00:00:39Z | 2,429,600 | 21 | 2010-03-12T00:07:36Z | [
"python",
"loops",
"for-loop"
] | I was wondering how to achieve the following in python:
```
for( int i = 0; cond...; i++)
if cond...
i++; //to skip an run-through
```
I tried this with no luck.
```
for i in range(whatever):
if cond... :
i += 1
``` | Python's for loops are different. `i` gets reassigned to the next value every time through the loop.
The following will do what you want, because it is taking the literal version of what C++ is doing:
```
i = 0
while i < some_value:
if cond...:
i+=1
...code...
i+=1
```
Here's why:
in C++, the fo... |
Add Keyboard Binding To Existing Emacs Mode | 2,429,603 | 6 | 2010-03-12T00:08:12Z | 2,430,474 | 14 | 2010-03-12T04:14:42Z | [
"python",
"emacs",
"keyboard-shortcuts",
"elisp"
] | I'm attempting my first modification of Emacs. I recorded a little keyboard macro and had Emacs spit it out as elisp, resulting in:
```
(setq add-docstring
"\C-rdef\C-n\C-a\C-m\C-p\C-i\C-u6\"\C-u3\C-b")
(global-set-key "\C-c\C-d" 'add-docstring)
```
Searching the Emacs reference, though, revealed that `C-c C-d` i... | It turns out, `C-c C-d` is already bound in `python-mode` (to `'python-pdbtrack-toggle-stack-tracking`), so you may want to revisit your choice of key binding.
*Note:* if you just want to cut/paste a solution, jump to the end of the answer. Read on for an explanation of how to get there - in case you want to do it aga... |
What is the purpose of a zip function (as in Python or C# 4.0)? | 2,429,692 | 7 | 2010-03-12T00:26:32Z | 2,429,712 | 7 | 2010-03-12T00:29:33Z | [
"c#",
"python",
"zip"
] | Someone asked [How to do Pythonâs zip in C#?](http://stackoverflow.com/questions/2427015)...
...which leads me to ask, what good is zip? In what scenarios do I need this? Is it really so foundational that I need this in the base class library? | It allows you to process sequences in parallel instead of sequentially or nested. There's... so many uses for it that they currently escape me. |
What is the purpose of a zip function (as in Python or C# 4.0)? | 2,429,692 | 7 | 2010-03-12T00:26:32Z | 2,429,725 | 7 | 2010-03-12T00:35:07Z | [
"c#",
"python",
"zip"
] | Someone asked [How to do Pythonâs zip in C#?](http://stackoverflow.com/questions/2427015)...
...which leads me to ask, what good is zip? In what scenarios do I need this? Is it really so foundational that I need this in the base class library? | Here's a common use case for zip:
```
x = [1,2,3,4,5]
y = [6,7,8,9,0]
for a,b in zip(x,y):
print a, b
```
Which would output:
```
1 6
2 7
3 8
4 9
5 0
``` |
What is the purpose of a zip function (as in Python or C# 4.0)? | 2,429,692 | 7 | 2010-03-12T00:26:32Z | 2,429,737 | 11 | 2010-03-12T00:37:46Z | [
"c#",
"python",
"zip"
] | Someone asked [How to do Pythonâs zip in C#?](http://stackoverflow.com/questions/2427015)...
...which leads me to ask, what good is zip? In what scenarios do I need this? Is it really so foundational that I need this in the base class library? | zip is useful if you'd like to iterate over multiple iterables simultaneously, which is a reasonably common scenario in Python.
One real-world scenario where zip has come in handy for me is if you have an M by N array, and you want to look at columns instead of rows. For example:
```
>>> five_by_two = ((0, 1), (1, 2)... |
Need help understanding "TypeError: default __new__ takes no parameters" error in python | 2,429,899 | 3 | 2010-03-12T01:24:19Z | 2,429,957 | 7 | 2010-03-12T01:40:03Z | [
"python",
"init",
"typeerror"
] | For some reason I am having trouble getting my head around `__init__` and `__new__`. I have a bunch of code that runs fine from the terminal, but when I load it as a plugin for Google Quick Search Box, I get the error `TypeError: default __new__ takes no parameters`.
I have been reading about the error, and it's kind ... | Simplest way to reproduce your problem:
```
>>> class Bah(object): pass
...
>>> x = Bah(23)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: default __new__ takes no parameters
```
So it looks like there's a class in your code (not when run from the terminal, but then you do very differen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.