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 |
|---|---|---|---|---|---|---|---|---|---|
Why do you need to set the WORKON_HOME environment variable? | 13,787,566 | 6 | 2012-12-09T13:01:11Z | 13,787,884 | 7 | 2012-12-09T13:38:33Z | [
"python",
"virtualenv"
] | I haven't used my python/virtual environments in a while, but I do have virtualenvironment wrapper installed also.
My question is, in the doc page it says to do this:
```
export WORKON_HOME=~/Envs
$ mkdir -p $WORKON_HOME
$ source /usr/local/bin/virtualenvwrapper.sh
$ mkvirtualenv env1
```
I simply did this at my pro... | If `WORKON_HOME` is not set, your default virtualenv folder will be set to `~/.virtualenvs`
(see [virtualenvwrapper.sh l.118](https://bitbucket.org/dhellmann/virtualenvwrapper/src/a766226010beb5df341bcb4bceb2befaba8603d4/virtualenvwrapper.sh?at=default#cl-118))
You will also use `WORKON_HOME` to specify to `pip` whi... |
Formatting display of numbers in Python 3 | 13,787,739 | 2 | 2012-12-09T13:20:52Z | 13,787,759 | 9 | 2012-12-09T13:22:41Z | [
"python",
"python-3.x"
] | I am wondering how to truncate numbers in Python 3? For example, `87.28197` to `87.281`
The standard in Python 2 was using `%` but this is no longer used. | The `%` string formatter still is available in Python 3. It is preferred you use the `''.format()` [string formatting syntax](http://docs.python.org/2/library/string.html#format-string-syntax), which also supports specifying float precisions.
Both of these work:
```
>>> yournumber = 87.28197
>>> "{0:.3f}".format(your... |
What are heap queues for? | 13,788,349 | 7 | 2012-12-09T14:33:48Z | 13,788,703 | 8 | 2012-12-09T15:17:44Z | [
"python"
] | Reading Guido's infamous answer to the question [Sorting a million 32-bit integers in 2MB of RAM using Python](http://neopythonic.blogspot.fr/2008/10/sorting-million-32-bit-integers-in-2mb.html), I discovered the module [heapq](http://docs.python.org/2.7/library/heapq.html).
I also discover I didn't understand jack ab... | `heapq` implements [binary heaps](https://en.wikipedia.org/wiki/Binary_heap), which are a partially sorted data structure. In particular, they have three interesting operations:
* `heapify` turns a list into a heap, in-place, in O(*n*) time;
* `heappush` adds an element to the heap in O(lg *n*) time;
* `heappop` retri... |
PyQt: how to handle event without inheritance | 13,788,452 | 4 | 2012-12-09T14:46:57Z | 13,789,535 | 11 | 2012-12-09T16:59:32Z | [
"python",
"events",
"pyqt",
"pyqt4",
"handler"
] | How can I handle mouse event without a inheritance, the usecase can be described as follows:
Suppose that I wanna let the QLabel object to handel `MouseMoveEvent`, the way in the tutorial often goes in the way that we create a new class inherited from QLabel. But can I just use a lambda expression to handel the event ... | The most flexible way to do this is to install an [event filter](https://qt-project.org/doc/qt-4.8/qobject.html#installEventFilter) that can receive events on behalf of the object:
```
from PyQt4 import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
sel... |
How to apply Column defaults before a commit in sqlalchemy | 13,791,487 | 12 | 2012-12-09T20:29:52Z | 13,791,802 | 9 | 2012-12-09T21:03:52Z | [
"python",
"sqlalchemy"
] | I have a declarative-base model:
```
class User(Base):
id = Column(Integer, primary_key=True)
money = Column(Integer, default=100)
```
and then I run
```
>>> u = User()
>>> u.money
None
```
How can I populate the defaults using sqlalchemy *without* writing anything to the database? | The column default only applies to INSERT and UPDATE statements, and thus isn't being applied until you `.flush()` the session.
To see the same value on new instances before you flush, you need to apply the default when a new instance is being created; in the `__init__` method of the `User` object:
```
class User(Bas... |
Usage of the "==" operator for three objects | 13,792,604 | 4 | 2012-12-09T22:36:44Z | 13,792,615 | 12 | 2012-12-09T22:38:10Z | [
"python",
"operators",
"equality"
] | Is there any computational difference between these two methods of checking equality between three objects?
I have two variables: `x` and `y`. Say I do this:
```
>>> x = 5
>>> y = 5
>>> x == y == 5
True
```
Is that different from:
```
>>> x = 5
>>> y = 5
>>> x == y and x == 5
True
```
What about if they are `False... | Python has chained comparisons, so these two forms are equivalent:
```
x == y == z
x == y and y == z
```
except that in the first, y is only evaluated once.
This means you can also write:
```
0 < x < 10
10 >= z >= 2
```
etc. You can also write confusing things like:
```
a < b == c is d # Don't do this
```
Beg... |
Joining Table/DataFrames with common Column in Python | 13,793,321 | 5 | 2012-12-10T00:12:52Z | 13,793,474 | 15 | 2012-12-10T00:35:51Z | [
"python",
"pandas"
] | I have two DataFrames:
```
df1 = ['Date_Time',
'Temp_1',
'Latitude',
'N_S',
'Longitude',
'E_W']
df2 = ['Date_Time',
'Year',
'Month',
'Day',
'Hour',
'Minute',
'Seconds']
```
As You can see both DataFrames have `Date_Time` as a common column. I want to Join these two DataFra... | You are looking for a [`merge`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html?highlight=merge#pandas.DataFrame.merge):
```
df1.merge(df2, on='Date_Time')
```
*The keywords are the same as for `join`, but `join` uses only the index, see ["Database-style DataFrame joining/merging"](h... |
Passing table name as a parameter in psycopg2 | 13,793,399 | 19 | 2012-12-10T00:23:10Z | 13,793,441 | 7 | 2012-12-10T00:29:49Z | [
"python",
"sql",
"postgresql",
"sql-injection",
"psycopg2"
] | I have the following code, using pscyopg2:
```
sql = 'select %s from %s where utctime > %s and utctime < %s order by utctime asc;'
data = (dataItems, voyage, dateRangeLower, dateRangeUpper)
rows = cur.mogrify(sql, data)
```
This outputs:
```
select 'waterTemp, airTemp, utctime' from 'ss2012_t02' where utctime > '201... | The table name cannot be passed as a parameter, but everything else can. Thus, the table name should be hard coded in your app (Don't take inputs or use anything outside of the program as a name). The code you have should work for this.
On the slight chance that you have a legitimate reason to take an outside table na... |
Passing table name as a parameter in psycopg2 | 13,793,399 | 19 | 2012-12-10T00:23:10Z | 28,593,246 | 16 | 2015-02-18T20:26:45Z | [
"python",
"sql",
"postgresql",
"sql-injection",
"psycopg2"
] | I have the following code, using pscyopg2:
```
sql = 'select %s from %s where utctime > %s and utctime < %s order by utctime asc;'
data = (dataItems, voyage, dateRangeLower, dateRangeUpper)
rows = cur.mogrify(sql, data)
```
This outputs:
```
select 'waterTemp, airTemp, utctime' from 'ss2012_t02' where utctime > '201... | Per [this answer](http://stackoverflow.com/a/13891511/1956065) you can do it as so:
```
import psycopg2
from psycopg2.extensions import AsIs
#Create your connection and cursor...
cursor.execute("SELECT * FROM %(table)s", {"table": AsIs("my_awesome_table")})
``` |
Easiest way to remove unicode representations from a string in python 3? | 13,793,973 | 5 | 2012-12-10T01:55:16Z | 13,794,050 | 10 | 2012-12-10T02:06:40Z | [
"python",
"string",
"python-3.x",
"escaping"
] | I have a string in python 3 that has several unicode representations in it, for example:
```
t = 'R\\u00f3is\\u00edn'
```
and I want to convert t so that it has the proper representation when I print it, ie:
```
>>> print(t)
RóisÃn
```
However I just get the original string back. I've tried re.sub and some others... | You want to use the built-in codec `unicode_escape`.
If `t` is already a `bytes` (an 8-bit string), it's as simple as this:
```
>>> print(t.decode('unicode_escape'))
RóisÃn
```
If `t` has already been decoded to Unicode, you can to encode it back to a `bytes` and then `decode` it this way. If you're sure that all ... |
How do I plot 3 subplots in the same display window? python | 13,794,350 | 4 | 2012-12-10T02:52:59Z | 13,794,574 | 12 | 2012-12-10T03:23:03Z | [
"python",
"matplotlib",
"plot",
"subplot"
] | ```
# Import plotting routines
from pylab import *
# 1D ODE that has a pitchfork bifurcation
# x_dot = r * x - x * x * x
def PitchforkODE(r,x):
return r * x - x * x * x
# 1D Euler
def OneDEuler(r,x,f,dt):
return x + dt * f(r,x)
# Improved 1D Euler
def ImprovedOneDEuler(r,x,f,dt):
xtemp = x + dt * f(r,x)
return x... | Well...It looks like you are doing the plotting part correctly. The code below gives you the figure further below.
```
from pylab import *
subplot(3,1,1)
plot(arange(33))
subplot(3,1,2)
plot(arange(44))
subplot(3,1,3)
plot(arange(55),'r')
```

Your c... |
Python regular expression for Beautiful Soup | 13,794,532 | 3 | 2012-12-10T03:18:14Z | 13,794,740 | 10 | 2012-12-10T03:50:00Z | [
"python",
"regex",
"beautifulsoup"
] | I am using Beautiful Soup to pull out specific div tags, and it seems I can't use
simple string matching.
The page has some tags in the form of
```
<div class="comment form new"...>
```
which I want to ignore, and also some tags in the form of
```
<div class="comment comment-xxxx...">
```
where the x's represent a... | I think I've got it:
```
>>> [div['class'] for div in soup.find_all('div')]
[['comment', 'form', 'new'], ['comment', 'comment-xxxx...']]
```
Notice that, unlike the equivalent in BS3, it's not this:
```
['comment form new', 'comment comment-xxxx...']
```
And that's why your regexps won't match.
But you can match, ... |
How do I choose between 3 random numbers in Python 2.7? | 13,795,659 | 3 | 2012-12-10T05:45:33Z | 13,795,677 | 14 | 2012-12-10T05:47:01Z | [
"python",
"random",
"python-2.7"
] | Lets say I want to generate one of the numbers 1, 4, or 7.
How would I do this? I originally thought I could write
```
import random
rand.randint(1,4,7)
```
but that doesn't seem to work. Thanks. | Use random choice
```
print random.choice([1,4,7])
``` |
Numpy error: Singular matrix | 13,795,682 | 3 | 2012-12-10T05:47:45Z | 13,795,874 | 8 | 2012-12-10T06:09:48Z | [
"python",
"numpy"
] | What does the error `Numpy error: Matrix is singular` mean specifically (when using the `linalg.solve` function)? I have looked on Google but couldn't find anything that made it clear when this error occurs. | A singular matrix is one that is not invertible. This means that the system of equations you are trying to solve does not have a unique solution; `linalg.solve` can't handle this.
You may find that `linalg.lstsq` provides a usable solution. |
What is sys.maxint in Python 3? | 13,795,758 | 34 | 2012-12-10T05:56:20Z | 13,795,777 | 44 | 2012-12-10T05:58:00Z | [
"python",
"python-3.x"
] | I've been trying to find out how to represent a maximum integer, and I've read to use `"sys.maxint"`. However, in Python 3 when I call it I get:
```
AttributeError: module 'object' has no attribute 'maxint'
``` | > The sys.maxint constant was removed, since there is no longer a limit
> to the value of integers. However, sys.maxsize can be used as an
> integer larger than any practical list or string index. It conforms to
> the implementationâs ânaturalâ integer size and is typically the same
> as sys.maxint in previous re... |
What is sys.maxint in Python 3? | 13,795,758 | 34 | 2012-12-10T05:56:20Z | 13,796,364 | 8 | 2012-12-10T06:58:00Z | [
"python",
"python-3.x"
] | I've been trying to find out how to represent a maximum integer, and I've read to use `"sys.maxint"`. However, in Python 3 when I call it I get:
```
AttributeError: module 'object' has no attribute 'maxint'
``` | Python 3 ints do not have a maximum.
If your purpose is to determine the maximum size of an int in C when compiled the same way Python was, you can use the struct module to find out:
```
>>> import struct
>>> platform_c_maxint = 2 ** (struct.Struct('i').size * 8 - 1) - 1
```
If you are curious about the internal imp... |
What is sys.maxint in Python 3? | 13,795,758 | 34 | 2012-12-10T05:56:20Z | 22,948,228 | 9 | 2014-04-08T21:09:28Z | [
"python",
"python-3.x"
] | I've been trying to find out how to represent a maximum integer, and I've read to use `"sys.maxint"`. However, in Python 3 when I call it I get:
```
AttributeError: module 'object' has no attribute 'maxint'
``` | As pointed out by others, Python 3's `int` does not have a maximum size, but if you just need something that's guaranteed to be higher than any other `int` value, then you can use the float value for Infinity, which you can get with `float("inf")`. |
How can I call OCaml functions from a Python program? | 13,795,785 | 4 | 2012-12-10T05:59:32Z | 13,795,826 | 7 | 2012-12-10T06:03:42Z | [
"python",
"ocaml"
] | I've got a large legacy program that is written in OCaml, and I'd like to be able to call some OCaml functions from my Python program.
How can I do this the easiest way? | Directly, no. However, if you create a `C` API for your Ocaml library, you can call that API via. Python's `ctypes` module or similar. Likewise, if you expose a network service for your OCaml application, Python can call into that. |
How can I call OCaml functions from a Python program? | 13,795,785 | 4 | 2012-12-10T05:59:32Z | 13,796,668 | 8 | 2012-12-10T07:27:56Z | [
"python",
"ocaml"
] | I've got a large legacy program that is written in OCaml, and I'd like to be able to call some OCaml functions from my Python program.
How can I do this the easiest way? | You might find useful [Pycaml](http://caml.inria.fr/cgi-bin/hump.en.cgi?contrib=792), a Python-OCaml interface allowing to call OCaml functions from Python and vice versa.
Be sure to look for the 2011 or later version, which is based on a 2002 version. |
python bug with __le__, __ge__? | 13,799,386 | 6 | 2012-12-10T10:46:48Z | 13,799,667 | 8 | 2012-12-10T11:02:56Z | [
"python"
] | Is it me or python that is confused with the following code ? I would expect `__le__` to be called by `a <= ab`, not `__ge__`:
```
#!/usr/bin/env python2
class B(object):
def __ge__(self, other):
print("__ge__ unexpectedly called")
class A(object):
def __le__(self, other):
print("__le__ calle... | The short answer is that they wanted to allow `AB` to override the behavior from `A`. Python can't call `AB.__lt__(a, ab)`, because `a` may not be a valid `self` for an `AB` method, so instead, it calls `AB.__gt__(ab, a)`, which is valid.
The long answer is a bit more complicated.
According to the docs for [rich comp... |
Can't load relative config file using ConfigParser from sub-directory | 13,800,515 | 12 | 2012-12-10T11:59:17Z | 13,800,583 | 14 | 2012-12-10T12:04:20Z | [
"python"
] | I have the following directory structure:
```
my_program/
foo.py
__init__.py # empty
conf/
config.cfg
__init__.py
```
In foo.py I have this:
```
import sys
#sys.path.append('conf/')
import ConfigParser
config = ConfigParser.ConfigParser()
config.read( 'conf/config.cfg' )
``... | Paths are relative to the *current working directory*, which is usually the directory from which you run your program (but the current directory can be changed by your program [or a module] and it is in general *not* the directory of your program file).
A solution consists in automatically calculating the path to your... |
Deleting from python heapq in O(logn) | 13,800,947 | 2 | 2012-12-10T12:28:01Z | 13,801,331 | 7 | 2012-12-10T12:50:57Z | [
"python"
] | I have a heap (python, heapq module) like this -
```
>>> h = []
>>> heappush(h, (5, 'write code'))
>>> heappush(h, (7, 'release product'))
>>> heappush(h, (1, 'write spec'))
>>> heappush(h, (3, 'create tests'))
```
How do I remove the tuple with item value as "create tests" in O(logn) and preserve the heap property?
... | If you do need to take an item out of the `heap` but want to preserve the `heap` you could do it lazily and discard it when the item comes out naturally, rather than searching through the list for it.
If you store items you want to remove in a blacklist `set`, then each time you `heapq.heappop` check if that item is i... |
Select all text in a Text widget using Python 3 with tkinter | 13,801,557 | 7 | 2012-12-10T13:05:32Z | 13,803,783 | 9 | 2012-12-10T15:20:32Z | [
"python",
"python-3.x",
"tkinter"
] | I'm working on my first Python program and have little idea what I'm doing. I want to re-bind ctrl-a (control a) to select all text in a Text widget. The current binding is ctrl-/ (control /). The binding part jumps right to the function but the actual text selection doesn't work. Instead, the cursor jumps to the first... | You need to both do the selection and then inhibit the default action by having your function do `return 'break'`.
This is due to how Tkinter processes events. It uses what it calls "bind tags". Even though it looks like you are binding to a widget, you are actually binding to a tag that is the name of the widget. The... |
elements being copied along a list in python | 13,802,572 | 2 | 2012-12-10T14:08:41Z | 13,802,603 | 8 | 2012-12-10T14:10:15Z | [
"python",
"list",
"class"
] | I have a list of lists called `hab` acting as a 2D array. In this list of lists I am storing elements of a class called `loc` which is why I am not using a numpy array (it's not storing numbers).
I want to fill each element with a randomly picked 'loc' by looping through each element. However it seems that whenever I ... | The problem is here:
```
hab=[[0]*xaxis]*yaxis
```
As a result of the above statement, `hab` consists of `yaxis` references *to the same list*:
```
In [6]: map(id, hab)
Out[6]: [18662824, 18662824, 18662824]
```
When you modify `hab[k][j]`, all other `hab[][j]` change too:
```
In [10]: hab
Out[10]: [[0, 0], [0, 0]... |
How to stop same letter appearing twice in list? | 13,803,074 | 4 | 2012-12-10T14:38:10Z | 13,803,096 | 8 | 2012-12-10T14:39:26Z | [
"python"
] | im trying to write a progam where you enter either a vowel or a consonant 8 times and the list of letters you have chosen is then shown. Is there a way to program it so that the same letter cannot come up twice, e.g if you select vowel and get the letter a, then the letter a cannot be randomly chosen again?
This is the... | Create a list of all consonnants and of all vowels, `shuffle` them randomly and then take one element at a time:
```
import random
con = list('bcdfghjklmnpqrstvwxyz') # in some languages "y" is a vowel
vow = list('aeiou')
random.shuffle(con)
random.shuffle(vow)
# con is now: ['p', 'c', 'j', 'b', 'q', 'm', 'r', 'n', '... |
Testing equality of three values | 13,805,939 | 12 | 2012-12-10T17:25:08Z | 13,805,988 | 13 | 2012-12-10T17:27:57Z | [
"python"
] | Does this do what I think it does? It seems to me that yes. I am asking to be sure.
```
if n[i] == n[i+1] == n[i+2]:
return True
```
Are these equal?
```
if n[i] == n[i+1] and n[i+1] == n[i+2]:
return True
``` | It is *equivalent* to but not equal to, since accesses are only performed once. Python chains relational operators naturally (including `in` and `is`).
The easiest way to show the slight difference:
```
>>> print(1) == print(2) == print(3)
1
2
3
True
>>> print(1) == print(2) and print(2) == print(3)
1
2
2
3
True
``` |
python lxml inkscape namespace tags | 13,806,088 | 3 | 2012-12-10T17:33:56Z | 13,806,489 | 7 | 2012-12-10T17:59:54Z | [
"python",
"svg",
"lxml",
"inkscape"
] | I am generating an SVG file that's intended to include Inkscape-specific tags. For example, `inkscape:label` and `inkscape:groupmode`. I am using lxml etree as my parser/generator. I'd like to add the `label` and `groupmode` tags to the following instance:
```
layer = etree.SubElement(svg_instance, 'g', id="layer-id")... | First, remember that `inkscape:` isnt' a namespace, it's just a convenient way of referring to a namespace that is defined in your XML root element. The namespace is `http://www.inkscape.org/namespaces/inkscape`, and depending on your XML, `inkscape:groupmode` might be identical to `foo:groupmode`. And of course, your ... |
when to use utf8 as a header in py files | 13,807,748 | 11 | 2012-12-10T19:27:15Z | 13,807,795 | 7 | 2012-12-10T19:30:41Z | [
"python",
"utf-8"
] | Some source files, from downloaded code, have the following header
```
# -*- coding: utf-8 -*-
```
I have an idea what utf-8 encoding is but why would it be needed as a header in a python source file? | wherever you need to use in your code chars that aren't from ascii, like:
```
Ä
```
interpreter will complain that he doesn't understand that char.
Usually this happens when you define constants.
Example:
Add into x.py
```
print 'Ä'
```
then start a python console
```
import x
Traceback (most recent call last)... |
Python iterate through list and count items of a certain value | 13,808,428 | 2 | 2012-12-10T20:11:43Z | 13,808,522 | 7 | 2012-12-10T20:17:16Z | [
"python"
] | Hi I have a python problem whereby I have to count which list elements contain the value 2, in a list with various levels of nest. E.g.:
```
my_list = [[2,3,2,2], [[2,1,2,1], [2,1,1]], [1,1,1]]
```
this list can have have up to three levels of nesting but could also be two or only one level deep.
I have piece of cod... | I'd use a variant of the `flatten()` generator from <http://stackoverflow.com/a/2158532/367273>
The original yields every elements from an arbitrarily nested and irregularly shaped structure of iterables. My variant (below) yields the innermost iterables instead of yielding the scalars.
```
from collections import It... |
Sum of even integers from a to b in Python | 13,809,159 | 4 | 2012-12-10T21:00:20Z | 13,809,214 | 9 | 2012-12-10T21:04:38Z | [
"python",
"python-3.x"
] | This is my code:
```
def sum_even(a, b):
count = 0
for i in range(a, b, 1):
if(i % 2 == 0):
count += [i]
return count
```
An example I put was print(sum\_even(3,7)) and the output is 0. I cannot figure out what is wrong. | Your indentation is off, it should be:
```
def sum_even(a, b):
count = 0
for i in range(a, b, 1):
if(i % 2 == 0):
count += i
return count
```
so that `return count` doesn't get scoped to your for loop (in which case it would return on the 1st iteration, causing it to return 0)
(And ch... |
Python - find intersection of values in a dict | 13,810,130 | 2 | 2012-12-10T22:09:29Z | 13,810,161 | 8 | 2012-12-10T22:12:35Z | [
"python",
"dictionary",
"intersection"
] | Im writing a function to handle multiple queries in a boolean AND search.
I have a dict of docs where each query occurs= `query_dict`
I want the intersection of all values in the query\_dict.values():
```
query_dict = {'foo': ['doc_one.txt', 'doc_two.txt', 'doc_three.txt'],
'bar': ['doc_one.txt', 'doc_t... | ```
In [36]: query_dict = {'foo': ['doc_one.txt', 'doc_two.txt', 'doc_three.txt'],
'bar': ['doc_one.txt', 'doc_two.txt'],
'foobar': ['doc_two.txt']}
In [37]: reduce(set.intersection, (set(val) for val in query_dict.values()))
Out[37]: set(['doc_two.txt'])
```
In [41]: query\_dict = {'foo':... |
Python summing itertools.count? | 13,810,960 | 2 | 2012-12-10T23:16:05Z | 13,811,079 | 7 | 2012-12-10T23:27:51Z | [
"python",
"count",
"itertools",
"infinite"
] | I'm having some trouble with the itertools.count function, and I don't quite understand what it does. I expect the code below to accomplish [Project Euler problem 2](http://projecteuler.net/problem=2).
I know that I could write this with a simple while loop, but is there a way to do it with a list comprehension? This ... | You could use [`takewhile`](http://docs.python.org/2/library/itertools.html#itertools.takewhile):
```
>>> from itertools import count, takewhile, imap
>>> sum(x for x in takewhile(lambda x: x < 4000000, imap(fib, count())) if x % 2 == 0)
4613732
``` |
How do I validate a JSON Schema schema, in Python? | 13,812,136 | 18 | 2012-12-11T01:18:05Z | 13,826,826 | 16 | 2012-12-11T19:08:15Z | [
"python",
"jsonschema"
] | I am programmatically generating a JSON-Schema schema. I wish to ensure that the schema is valid. Is there a schema I can validate my schema against?
Please note my use of schema twice in that sentence and the title. I don't want to validate data against my schema, I want to validate my schema. | Using [jsonschema](http://pypi.python.org/pypi/jsonschema/0.7), you can validate a schema against the meta-schema. The core meta-schema is [here](http://json-schema.org/), but jsonschema bundles it so downloading it is unnecessary.
```
from jsonschema import Draft3Validator
my_schema = json.loads(my_text_file) #or how... |
Efficient way to calculate grid quadrants a line passes through | 13,812,409 | 6 | 2012-12-11T01:53:17Z | 13,812,888 | 7 | 2012-12-11T02:50:36Z | [
"python",
"pseudocode"
] | I have a 2-dimmensional unit grid, and a bunch of line segments that start and end at any rational number. I need an efficient way to calculate which grid cells the line passes through. For example, the line:
From (2.1, 3.9) to (3.8, 4.8) passes through the grid cells with lower left points (2, 3), (2, 4), and (3, 4).... | Folks who work with spatial data deal with this kind of question all the time, so it may be worth piggy-backing on their efforts. Here's a solution that uses R's **raster** package (and functions from the **sp** package on which it depends):
```
library(raster)
## Create a SpatialLines object
a <- c(2.1, 3.9)
b <- c... |
OAuth2 authentication in GAE accessing Calendar API V3 (domain hosted) | 13,812,813 | 2 | 2012-12-11T02:41:55Z | 13,812,948 | 10 | 2012-12-11T02:57:20Z | [
"python",
"google-app-engine",
"oauth-2.0",
"google-calendar",
"google-api-python-client"
] | I'm developing a Google App Engine app with Python. And I'm using:
* Google Calendar API v3 (to access a calendar in my own domain. So, this is Google Apps installed in my domain)
* Google APIs client library for Python.
* OAuth2 to authenticate users of my domain (name@mydomain.com)
I thought I had to use Service Ac... | You don't need a service account, though using one may be useful. There are some tricky issues with service accounts on App Engine detailed in a [reported issue](http://code.google.com/p/google-api-python-client/issues/detail?id=184) with the library. Try playing around with the [Google APIs explorer](https://developer... |
How to split string array to 2-dimension char array in python | 13,813,015 | 4 | 2012-12-11T03:05:16Z | 13,813,034 | 10 | 2012-12-11T03:08:17Z | [
"python",
"arrays"
] | I have a string array, for example:
```
a = ['123', '456', '789']
```
I want to split it to form a 2-dimension char array:
```
b = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
```
I'm using
```
[[element for element in line] for line in array]
```
to achieve my goal but found it not easy to read, is there ... | Looks like a job for `map`:
```
>>> a = ['123', '456', '789']
>>> map(list, a)
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
```
---
**Relevant documentation:**
* [`map`](http://docs.python.org/2/library/functions.html#map)
* [`list`](http://docs.python.org/2/library/functions.html#list) |
Python "import random" Error | 13,813,164 | 2 | 2012-12-11T03:25:29Z | 13,813,411 | 7 | 2012-12-11T03:59:27Z | [
"python",
"random"
] | As you may know from my previous posts, I'm learning Python. And this time I have a small error which I think is with this build of Python itself. When using the following:
```
import random
number = random.randint(1,10000)
```
Python gives me this error:
```
File "C\Users\name\Documents\Python\random.py", line 5, i... | By naming your script `random.py`, you've created a naming conflict with the `random` standard library module.
When you try to run your script, the directory containing the script will be added to the start of the module import path. So when your script does `import random`, you're effectively running a second copy of... |
Is there good library to do nonnegative matrix factorization (NMF) fast? | 13,814,907 | 3 | 2012-12-11T06:36:51Z | 13,815,046 | 13 | 2012-12-11T06:49:15Z | [
"python",
"c++",
"pca",
"matrix-factorization",
"nmf"
] | I have a sparse matrix whose shape is **570000\*3000**. I tried [nima](http://nimfa.biolab.si/) to do NMF (using the default nmf method, and set `max_iter` to 65). However, I found nimfa very slow. Have anyone used a faster library to do NMF? | I have used [`libNMF`](http://www.univie.ac.at/rlcta/software/) before. It's written in C and is very fast. There is a [paper](http://www.cai.sk/ojs/index.php/cai/article/view/161/136) documenting the algorithm and code.
The paper also lists several alternative packages for NMF (in bunch of different languages (which ... |
Django admin - make all fields readonly | 13,817,525 | 13 | 2012-12-11T09:47:06Z | 13,818,017 | 11 | 2012-12-11T10:13:51Z | [
"python",
"django",
"django-admin"
] | I'm trying to make all fields readonly without listing them explicitly.
Something like:
```
class CustomAdmin(admin.ModelAdmin):
def get_readonly_fields(self, request, obj=None):
if request.user.is_superuser:
return self.readonly_fields
return self.fields
```
The problem is `CustomAd... | Ok, now there's this:
```
class CustomAdmin(admin.ModelAdmin):
def get_readonly_fields(self, request, obj=None):
# ...
return [f.name for f in self.model._meta.fields]
```
Still looking for a less ugly way. |
Django admin - make all fields readonly | 13,817,525 | 13 | 2012-12-11T09:47:06Z | 13,830,140 | 24 | 2012-12-11T23:17:36Z | [
"python",
"django",
"django-admin"
] | I'm trying to make all fields readonly without listing them explicitly.
Something like:
```
class CustomAdmin(admin.ModelAdmin):
def get_readonly_fields(self, request, obj=None):
if request.user.is_superuser:
return self.readonly_fields
return self.fields
```
The problem is `CustomAd... | Careful, self.model.\_meta.fields are not necessarily the same fields that CustomAdmin has!
"All fields of the Admin" would look more like this:
```
from django.contrib import admin
from django.contrib.admin.util import flatten_fieldsets
class CustomAdmin(admin.ModelAdmin):
def get_readonly_fields(self, request,... |
matplotlib and libpng issues with ipython notebook | 13,817,940 | 9 | 2012-12-11T10:10:09Z | 23,917,785 | 7 | 2014-05-28T17:04:50Z | [
"python",
"matplotlib",
"ipython",
"libpng",
"ipython-notebook"
] | I was trying to use ipython notebook . I installed all the dependency libraries. However, I cannot use either the "--pylab=inline" option when launching ipython or "savefig" function in the Ipython console. When I tried to do either of them, an error message was returned "RuntimeError: Could not create write struct" re... | I had this same problem on OS X Mavericks with libpng installed via homebrew and also XQuartz installed. It turned out matplotlib was finding the older XQuartz libpng version when compiling, but finding the more recent homebrew libpng at runtime.
The best solution I've found is from [this comment by jaengelberg on git... |
What is different between makedirs and mkdir of os? | 13,819,496 | 5 | 2012-12-11T11:33:07Z | 13,819,575 | 24 | 2012-12-11T11:38:03Z | [
"python",
"linux",
"python-2.7"
] | I am confused to use about these two `os`methods to create the new directory.
Please give me some example in Python. | `makedirs()` [creates all the intermediate directories](http://docs.python.org/2/library/os.html#os.makedirs) if they don't exist (just like `mkdir -p` in bash).
`mkdir()` can create a single sub-directory, and will throw an exception if intermediate directories that don't exist are specified.
Either can be used to c... |
Pyside Signal and Slots connect New Method | 13,820,954 | 3 | 2012-12-11T12:59:15Z | 13,826,714 | 7 | 2012-12-11T19:01:02Z | [
"python",
"pyside",
"signals-slots"
] | This code:
```
self.buttonOk.clicked(self.accept())
self.buttonCancel.clicked(self.reject())
```
Shows this error:
```
TypeError: native Qt signal is not callable
```
How do I connect buttonOk's clicked() signal to accept() Slot? | There are a couple of things wrong with your code.
Firstly, you need to use the signal's `connect()` method to make the connection; and secondly, you need to pass in a *callable object* (i.e. no parens).
So your code needs to look like this:
```
self.buttonOk.clicked.connect(self.accept)
self.buttonCancel.clicked.co... |
Recommended place for a Django project to live on Linux | 13,821,959 | 14 | 2012-12-11T14:34:44Z | 13,822,122 | 22 | 2012-12-11T14:44:43Z | [
"python",
"django",
"django-settings"
] | I'm uploading my first Django project to a Linux server, where I should put my project in the filesystem?
With a PHP, or ASP project, everything goes into `/var/www`, would it be ok to do the same and add my Django project to the `/var/www` folder? | In the [Django tutorial](https://docs.djangoproject.com/en/dev/intro/tutorial01/#creating-a-project) it states:
> Where should this code live?
> If your background is in PHP, you're probably used to putting code under the Web server's document root (in a place such as /var/www). With Django, you don't do that. It's ... |
How can i use scrapy shell to with parameters on url | 13,822,582 | 5 | 2012-12-11T15:07:41Z | 13,823,225 | 7 | 2012-12-11T15:37:25Z | [
"python",
"django",
"scrapy"
] | I want to scrap the job website. i want to do some testing in scrapy shell.
Hence if i type this
`scrapy shell http://www.seek.com.au`
Then if i type
`from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor`
then it works fine
But if i do this
```
scrapy shell http://www.seek.com.au/JobSearch?DateRange=... | apparently, you need to enclose your url within double quotes:
```
scrapy shell "http://www.seek.com.au/JobSearch?DateRange=31&SearchFrom=quick&Keywords=python&nation=3000"
>>> from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
>>> lx = SgmlLinkExtractor()
```
then everything works smoothly (this above ... |
Django Form Wizard to Edit Model | 13,822,975 | 5 | 2012-12-11T15:25:18Z | 13,824,748 | 10 | 2012-12-11T16:50:59Z | [
"python",
"django"
] | I have a Django form wizard working nicely for creating content of one of my models. I want to use the same Wizard for editing data of existing content but can't find a good example of how to do this.
Here is a simplified version of my project code:
forms.py
```
class ProjectEssentialsForm(forms.ModelForm):
clas... | I've just got this working so will post the answer in case it helps someone else.
You can pass the ID of the item you'd like to edit in urls.py like this:
```
(r'^projects/edit/(?P<project_id>[-\d]+)$', ProjectWizard.as_view(FORMS)),
```
You can then look up the item with following code in
views.py:
```
class Proj... |
python request with authentication (access_token) | 13,825,278 | 12 | 2012-12-11T17:22:02Z | 13,827,087 | 22 | 2012-12-11T19:27:54Z | [
"python",
"authentication",
"curl",
"access-token"
] | I am trying to get an API query into python. The command line
```
curl --header "Authorization:access_token myToken" https://website.com/id
```
gives some json output. myToken is a hexadecimal variable that remains constant throughout. I would like to make this call from python so that I can loop through different id... | The [requests](http://docs.python-requests.org) package has a very nice API for HTTP requests, adding a custom header works like this ([source: official docs](http://docs.python-requests.org/en/latest/user/quickstart/#custom-headers):
```
>>> import requests
>>> response = requests.get(
... 'https://website.com/id', h... |
how to read an outputted fortran binary NxNxN matrix into Python | 13,827,368 | 7 | 2012-12-11T19:46:30Z | 13,828,314 | 7 | 2012-12-11T20:51:54Z | [
"python",
"numpy",
"matrix",
"binary",
"fortran"
] | I wrote out a matrix in Fortran as follows:
```
real(kind=kind(0.0d0)), dimension(256,256,256) :: dense
[...CALCULATION...]
inquire(iolength=reclen)dense
open(unit=8,file=fname,&
form='unformatted',access='direct',recl=reclen)
write(unit=8,rec=1)dense(:,:,:)
close(unit=8)
```
I want to read this back into Python. ... | Using IRO-bot's link I modified/made this for my script (nothing but numpy magic):
```
def readslice(inputfilename,ndim):
shape = (ndim,ndim,ndim)
fd = open(fname, 'rb')
data = np.fromfile(file=fd, dtype=np.double).reshape(shape)
fd.close()
return data
```
I did a mean,max,min & sum on the cube an... |
Matplotlib: text color code in the legend instead of a line | 13,828,246 | 8 | 2012-12-11T20:46:42Z | 13,828,904 | 7 | 2012-12-11T21:35:44Z | [
"python",
"numpy",
"matplotlib",
"plot",
"legend"
] | On certain LCD monitors, the color of the horizontal lines in the legend is hard to tell apart. (See the image attached). So instead of drawing a line in the legend, is it possible to just color code the text itself? so another words, have "y=0x" in blue, "y=1x" in green, etc...
```
import matplotlib.pyplot as plt
imp... | Just set the `linewidth` of the legend handles:
```
In [55]: fig, ax = plt.subplots()
In [56]: x = np.arange(10)
In [57]: for i in xrange(5):
....: ax.plot(x, i * x, label='$y = %ix$' % i)
....:
In [58]: leg = ax.legend(loc='best')
In [59]: for l in leg.legendHandles: ... |
Matplotlib: text color code in the legend instead of a line | 13,828,246 | 8 | 2012-12-11T20:46:42Z | 18,476,999 | 10 | 2013-08-27T23:19:16Z | [
"python",
"numpy",
"matplotlib",
"plot",
"legend"
] | On certain LCD monitors, the color of the horizontal lines in the legend is hard to tell apart. (See the image attached). So instead of drawing a line in the legend, is it possible to just color code the text itself? so another words, have "y=0x" in blue, "y=1x" in green, etc...
```
import matplotlib.pyplot as plt
imp... | I was wondering the same thing. Here is what I came up with to change the color of the font in the legend. I am not totally happy with this method, since it seems a little clumsy, but it seems to get the job done:
```
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
fig = plt.figure()
ax = plt.su... |
generalized cumulative functions in NumPy/SciPy? | 13,828,599 | 15 | 2012-12-11T21:13:25Z | 13,828,611 | 10 | 2012-12-11T21:14:31Z | [
"python",
"numpy",
"scipy",
"cumsum"
] | Is there a function in numpy or scipy (or some other library) that generalizes the idea of cumsum and cumprod to arbitrary function. For example, consider the (theoretical) function
```
cumf( func, array)
```
func is a function that accepts two floats, and returns a float. Particular cases
```
lambda x,y: x+y
```
a... | NumPy's ufuncs have [`accumulate()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.accumulate.html):
```
In [22]: np.multiply.accumulate([[1, 2, 3], [4, 5, 6]], axis=1)
Out[22]:
array([[ 1, 2, 6],
[ 4, 20, 120]])
```
Unfortunately, calling `accumulate()` on a `frompyfunc()`'ed Python ... |
why use str() is better than __str__() | 13,829,869 | 2 | 2012-12-11T22:54:44Z | 13,829,889 | 8 | 2012-12-11T22:55:50Z | [
"python"
] | Some time ago I asked one question, and a lot of people suggested me to change `__str__()` to `str(some object)`.
for example:
```
e_address = f_name+l_name+year.__str__()+day.__str__()
```
Change to :
```
e_address = f_name+l_name+str(year)+str(day)
```
So my question is why it is better? Are there any perfor... | `__str__()` is the hook method that `str()` calls if it is present. The `str()` function will fall back to a sensible default if no such method is defined. Hooks are there to override the default behaviour, and you should not assume they are always implemented.
Moreover, it's more readable to just use the `str()` call... |
List home directory without absolute path | 13,830,175 | 3 | 2012-12-11T23:20:57Z | 13,830,191 | 10 | 2012-12-11T23:22:02Z | [
"python"
] | I'm having problem with listing home directory of current user without knowing absolute path to it. I've tried with the following, but it doesn't work:
```
[root@blackbox source]# python
Python 2.6.6 (r266:84292, Dec 7 2011, 20:38:36)
[GCC 4.4.6 20110731 (Red Hat 4.4.6-3)] on linux2
Type "help", "copyright", "credits... | You need to use the [`os.path.expanduser()` function](http://docs.python.org/2/library/os.path.html#os.path.expanduser):
```
>>> import os.path
>>> os.path.expanduser('~')
'/home/username'
``` |
flask-login: Chrome ignoring cookie expiration? | 13,831,251 | 7 | 2012-12-12T01:16:45Z | 13,839,643 | 14 | 2012-12-12T12:19:18Z | [
"python",
"web-applications",
"python-2.7",
"flask",
"flask-login"
] | I've got the authentication working with flask-login, but it seems like no matter what I use for the cookie duration in flask, the session is still authenticated. Am I setting the config variables properly for flask-login? I've tried
```
app.REMEMBER_COOKIE_DURATION = datetime.timedelta(seconds=30)
app.config["REMEMBE... | `REMEMBER_COOKIE_DURATION` is used for "Remember me" functionality, that is, how long to remember logged in user even if he closed the browser. The separate cookie is used for that, the name of which can be set by `REMEMBER_COOKIE_NAME` (`remember_token` by default). To force login session to expire after some time (ev... |
Get matplotlib color cycle state | 13,831,549 | 51 | 2012-12-12T01:50:07Z | 13,831,816 | 53 | 2012-12-12T02:24:48Z | [
"python",
"matplotlib"
] | Is it possible to query the current state of the matplotlib color cycle? In other words is there a function `get_cycle_state` that will behave in the following way?
```
>>> plot(x1, y1)
>>> plot(x2, y2)
>>> state = get_cycle_state()
>>> print state
2
```
Where I expect the state to be the index of the next color that... | ### Accessing the color cycle iterator
There's no "user-facing" (a.k.a. "public") method to access the underlying iterator, but you can access it through "private" (by convention) methods. However, you'd can't get the state of an `iterator` without changing it.
### Setting the color cycle
Quick aside: You can set th... |
Python: object.__new__() takes no parameters | 13,832,086 | 2 | 2012-12-12T02:58:00Z | 13,832,101 | 9 | 2012-12-12T02:59:58Z | [
"python",
"syntax-error"
] | Right now I'm working on a program that allows people to make tests, save them to databases, and then print them. I keep getting the error:
```
Traceback (most recent call last):
File "C:/Users/Shepard/Desktop/Gradebook.py", line 50, in <module>
qs = QuestionStorage("questions.db")
TypeError: object.__new__() takes no... | The `__init__` method signature is `__init__`, not `_init_` in Python |
Python: object.__new__() takes no parameters | 13,832,086 | 2 | 2012-12-12T02:58:00Z | 13,832,149 | 7 | 2012-12-12T03:06:33Z | [
"python",
"syntax-error"
] | Right now I'm working on a program that allows people to make tests, save them to databases, and then print them. I keep getting the error:
```
Traceback (most recent call last):
File "C:/Users/Shepard/Desktop/Gradebook.py", line 50, in <module>
qs = QuestionStorage("questions.db")
TypeError: object.__new__() takes no... | It's worth learning how to debug this for yourself.
Nothing in your error message indicates that the problem has anything to do with sqlite3. So, what happens if you take out all the sqlite3 calls in `QuestionStorage` and run the program?
```
class QuestionStorage(object):
def _init_(self, path):
self.con... |
How to attach a Scrollbar to a Text widget? | 13,832,720 | 7 | 2012-12-12T04:20:28Z | 13,833,338 | 16 | 2012-12-12T05:24:46Z | [
"python",
"tkinter"
] | I am probably over-thinking this, but for some reason I can't seem to figure this out. I am trying to attach a scrollbar to my Text field and have been unable to do so. Here is the segment of code:
```
self.scroller = Scrollbar(self.root)
self.scroller.place(x=706, y=121)
self.outputArea = Text(self.root, height=26, w... | [Tkinter](http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html) has three *geometry managers*: [pack](http://effbot.org/tkinterbook/pack.htm), [grid](http://effbot.org/tkinterbook/grid.htm), and [place](http://effbot.org/tkinterbook/place.htm).
Pack and grid are usually recommended over place.
You can use th... |
Cannot open ".mp4" video files using OpenCV 2.4.3, Python 2.7 in Windows 7 machine | 13,834,399 | 4 | 2012-12-12T06:54:50Z | 22,806,767 | 8 | 2014-04-02T09:17:31Z | [
"python",
"windows",
"opencv",
"ffmpeg",
"mp4"
] | I am currently working on a project that involves reading mp4 video files.
The problem I encountered is that it using Python 2.7 (32 bit), OpenCV 2.4.3 (cv2.pyd) in a Windows 7 machine.
The code snippet is as follows:
```
try:
video = cv2.VideoCapture("video.mp4")
except:
print "Could not open video f... | I have had the same issue before, solved by this step:
Check your OpenCV python version
```
>>> from cv2 import __version__
>>> __version__
'2.4.0'
```
Then Copy your `opencv_ffmpeg.dll` to `C:\Python27\` and rename it to relevant your OpenCV Python Version. In my case I had to rename it to `opencv_ffmpeg240.dll`.
... |
Python subprocess check_output much slower then call | 13,835,055 | 7 | 2012-12-12T07:43:29Z | 13,837,573 | 8 | 2012-12-12T10:21:25Z | [
"python",
"performance",
"subprocess"
] | I was trying to understand why this is happening. I'm calling a command to restart networking on Ubuntu server 12.04.
**Fast execution**
When I call the command using one of following three ways it takes around 0.1 seconds to execute:
1. directly in terminal
2. python script using `os.system`
3. python script using ... | The code below is based on the excellent comment J.F. Sebastian made. The code below runs in 0.1 seconds as expected and returns the output of the command to a string.
```
from subprocess import check_call, STDOUT
from tempfile import NamedTemporaryFile
with NamedTemporaryFile() as f:
check_call(['/etc/init.d/net... |
Why Python doesn't have a native Linked List implementation? | 13,835,267 | 7 | 2012-12-12T07:59:28Z | 13,835,662 | 8 | 2012-12-12T08:30:03Z | [
"python",
"arrays",
"algorithm",
"linked-list"
] | I have tried some quick experiment comparing the performance of native Python lists with linked lists implementations such as [this](http://stackoverflow.com/questions/280243/python-linked-list).
The native python lists are always faster than the non native linked list in the cases where they should not be (according ... | Python has [collections.deque](http://docs.python.org/2/library/collections.html#collections.deque) which is a native doubly-linked list. |
Is there something in Python similar to quantstrat in R? | 13,836,277 | 9 | 2012-12-12T09:08:35Z | 13,841,532 | 14 | 2012-12-12T14:05:12Z | [
"python",
"quantitative-finance",
"quantstrat"
] | Is there something in Python similar to [quantstrat](http://www.r-bloggers.com/?s=quantstrat) in R? | Yes, [Quantopian](https://www.quantopian.com) uses an open-source Python backtesting engine called [zipline](https://github.com/quantopian/zipline). |
Project Euler 240: number of ways to roll dice | 13,836,932 | 6 | 2012-12-12T09:45:14Z | 13,839,290 | 10 | 2012-12-12T11:59:35Z | [
"python",
"puzzle",
"itertools",
"dice"
] | I 'm trying to solve [Project Euler problem 240](http://projecteuler.net/problem=240):
> **In how many ways can twenty 12-sided dice (sides numbered 1 to 12) be rolled so that the top ten sum to 70?**
I've come up with code to solve this. But it really takes a lot of time to compute. I know this approach is pretty ba... | It's no good iterating over all possibilities, because there are 1220 = 3833759992447475122176 ways to roll 20 twelve-sided dice, and at, say, a million rolls per second, that would take millions of years to complete.
The way to solve this kind of problem is to use [dynamic programming](http://en.wikipedia.org/wiki/Dy... |
Converting byte string in unicode string | 13,837,848 | 12 | 2012-12-12T10:37:35Z | 13,838,041 | 20 | 2012-12-12T10:47:40Z | [
"python",
"string",
"unicode",
"python-3.x",
"type-conversion"
] | I have a code such that:
```
a = "\u0432"
b = u"\u0432"
c = b"\u0432"
d = c.decode('utf8')
print(type(a), a)
print(type(b), b)
print(type(c), c)
print(type(d), d)
```
And output:
```
<class 'str'> в
<class 'str'> в
<class 'bytes'> b'\\u0432'
<class 'str'> \u0432
```
Why in the latter case I see a character code,... | In strings (or Unicode objects in Python 2), `\u` has a special meaning, namely saying, "here comes a Unicode character specified by it's Unicode ID". Hence `u"\u0432"` will result in the character в.
The `b''` prefix tells you this is a sequence of 8-bit bytes, and bytes object has no Unicode characters, so the `\u`... |
Custom sorting in pandas dataframe | 13,838,405 | 18 | 2012-12-12T11:09:42Z | 13,839,029 | 23 | 2012-12-12T11:44:10Z | [
"python",
"pandas"
] | I have python pandas dataframe, in which a column contains month name.
How can I do a custom sort using a dictionary, for example:
```
custom_dict = {'March':0, 'April':1, 'Dec':3}
``` | Pandas 0.15 introduced [Categorical Series](http://pandas.pydata.org/pandas-docs/stable/categorical.html), which allows a much clearer way to do this:
First make the month column a categorical and specify the ordering to use.
```
In [21]: df['m'] = pd.Categorical(df['m'], ["March", "April", "Dec"])
In [22]: df # lo... |
How to change filehandle with Python logging on the fly with different classes and imports | 13,839,554 | 10 | 2012-12-12T12:14:02Z | 13,839,732 | 16 | 2012-12-12T12:25:14Z | [
"python",
"logging",
"configuration"
] | I cannot perform an on-the-fly logging fileHandle change.
For example, I have 3 classes
`one.py`
```
import logging
class One():
def __init__(self,txt="?"):
logging.debug("Hey, I'm the class One and I say: %s" % txt)
```
`two.py`
```
import logging
class Two():
def __init__(self,txt="?"):
l... | Indeed, `logging.basicConfig` does *nothing* if a handler has been set up already:
> This function does nothing if the root logger already has handlers configured for it.
You'll need to *replace* the current handler on the root logger:
```
import logging
fileh = logging.FileHandler('/tmp/logfile', 'a')
formatter = ... |
Python: multiply all items in a list together | 13,840,379 | 57 | 2012-12-12T13:00:14Z | 13,840,436 | 70 | 2012-12-12T13:03:06Z | [
"python",
"list",
"multiplication"
] | I need to write a function that takes
a **list** of numbers and **multiplies** them together. Example:
`[1,2,3,4,5,6]` will give me `1*2*3*4*5*6`. I could really use your help. | You can use:
```
import operator
import functools
functools.reduce(operator.mul, [1,2,3,4,5,6], 1)
```
See [`reduce`](http://docs.python.org/2/library/functions.html#reduce) and [`operator.mul`](http://docs.python.org/2/library/operator.html#operator.mul) documentations for an explanation.
You need the `import funct... |
Python: multiply all items in a list together | 13,840,379 | 57 | 2012-12-12T13:00:14Z | 13,840,441 | 79 | 2012-12-12T13:03:18Z | [
"python",
"list",
"multiplication"
] | I need to write a function that takes
a **list** of numbers and **multiplies** them together. Example:
`[1,2,3,4,5,6]` will give me `1*2*3*4*5*6`. I could really use your help. | use reduce
```
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720
``` |
Python: multiply all items in a list together | 13,840,379 | 57 | 2012-12-12T13:00:14Z | 13,843,424 | 20 | 2012-12-12T15:47:11Z | [
"python",
"list",
"multiplication"
] | I need to write a function that takes
a **list** of numbers and **multiplies** them together. Example:
`[1,2,3,4,5,6]` will give me `1*2*3*4*5*6`. I could really use your help. | If you want to avoid importing anything and avoid more complex areas of Python, you can use a simple for loop
```
product = 1 # Don't use 0 here, otherwise, you'll get zero
# because anything times zero will be zero.
list = [1, 2, 3]
for x in list:
product *= x
``` |
Python: multiply all items in a list together | 13,840,379 | 57 | 2012-12-12T13:00:14Z | 32,426,539 | 11 | 2015-09-06T17:54:16Z | [
"python",
"list",
"multiplication"
] | I need to write a function that takes
a **list** of numbers and **multiplies** them together. Example:
`[1,2,3,4,5,6]` will give me `1*2*3*4*5*6`. I could really use your help. | I would use the `numpy.prod` to perform the task. See below.
```
import numpy as np
mylist = [1, 2, 3, 4, 5, 6]
result = np.prod(np.array(mylist))
``` |
FFT in Numpy (Python) when N is not a power of 2 | 13,841,296 | 4 | 2012-12-12T13:52:20Z | 13,842,414 | 8 | 2012-12-12T14:57:42Z | [
"python",
"numpy",
"fft"
] | My question is about the algorithm which is used in Numpy's FFT function.
The documentation of Numpy says that it uses the Cooley-Tukey algorithm. However, as you may know, this algorithm works only if the number N of points is a power of 2.
Does numpy pad my input vector x[n] in order to calculate its FFT X[k]? (I d... | The docs say numpy's FFT is based on [FFTPACK](http://www.netlib.org/fftpack/).
In the FFTPACK docs I find the following:
> ---
>
> subroutine rffti(n,wsave)
>
> ---
>
> subroutine rffti initializes the array wsave which is used in both
> rfftf and rfftb. the prime factorization of n together with a
> tabulation of t... |
Set value for particular cell in pandas DataFrame | 13,842,088 | 70 | 2012-12-12T14:40:45Z | 13,842,286 | 80 | 2012-12-12T14:51:02Z | [
"python",
"pandas"
] | I've created a pandas DataFrame
```
df=DataFrame(index=['A','B','C'], columns=['x','y'])
```
and got this
```
x y
A NaN NaN
B NaN NaN
C NaN NaN
```
Then I want to assign value to particular cell, for example for row 'C' and column 'x'.
I've expected to get such result:
```
x y
A NaN NaN
B Na... | [RukTech's answer](http://stackoverflow.com/a/24517695/190597), `df.set_value('C', 'x', 10)`, is far and away faster than the options I've suggested below.
---
**Warning**: It is sometimes difficult to predict if an operation returns a copy or a view. For this reason the [docs recommend avoiding using "chained indexi... |
Set value for particular cell in pandas DataFrame | 13,842,088 | 70 | 2012-12-12T14:40:45Z | 21,287,539 | 19 | 2014-01-22T15:48:25Z | [
"python",
"pandas"
] | I've created a pandas DataFrame
```
df=DataFrame(index=['A','B','C'], columns=['x','y'])
```
and got this
```
x y
A NaN NaN
B NaN NaN
C NaN NaN
```
Then I want to assign value to particular cell, for example for row 'C' and column 'x'.
I've expected to get such result:
```
x y
A NaN NaN
B Na... | The recommended way (according to the maintainers) to set a value is:
```
df.ix['x','C']=10
```
Using 'chained indexing' (`df['x']['C']`) may lead to problems.
See:
* <http://stackoverflow.com/a/21287235/1579844>
* <http://pandas.pydata.org/pandas-docs/dev/indexing.html#indexing-view-versus-copy>
* <https://github.... |
Set value for particular cell in pandas DataFrame | 13,842,088 | 70 | 2012-12-12T14:40:45Z | 24,517,695 | 73 | 2014-07-01T19:16:40Z | [
"python",
"pandas"
] | I've created a pandas DataFrame
```
df=DataFrame(index=['A','B','C'], columns=['x','y'])
```
and got this
```
x y
A NaN NaN
B NaN NaN
C NaN NaN
```
Then I want to assign value to particular cell, for example for row 'C' and column 'x'.
I've expected to get such result:
```
x y
A NaN NaN
B Na... | The fastest way to do this is using [set\_value](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_value.html). This method is ~100 times faster than `.ix` method. For example:
`df.set_value('C', 'x', 10)` |
How do we get TXT, CNAME and SOA records from dnspython? | 13,842,116 | 6 | 2012-12-12T14:42:09Z | 14,178,752 | 9 | 2013-01-06T02:41:35Z | [
"python",
"dns",
"dnspython"
] | I have a requirement to have a dns query function to query a server for various records. I figured out how to get the MX record (most of the examples show this), A record and NS record. How do I get the TXT, CNAME and SOA records?
Sample code snippet:
```
import dns.resolver
answer=dns.resolver.query("google.co... | You can get the TXT, CNAME, and SOA records a similar way but you just have to get the correct attributes depending on the DNS response object.
Using the python dir() built-in is your friend and one way to figure out what attributes exist in the DNS response object - handy when API documentation is not available.
To ... |
What is the recommended whitespace for slicing with expression indices in Python? | 13,842,531 | 6 | 2012-12-12T15:03:13Z | 13,842,622 | 7 | 2012-12-12T15:08:34Z | [
"python",
"coding-style",
"whitespace"
] | Examples of slicing in [documentation](http://docs.python.org/2/tutorial/introduction.html#strings) only show integer literals and variables used as indices, not more complex expressions (e.g. `myarray[x/3+2:x/2+3:2]`). PEP-8 also doesn't cover this case. What is the usual usage of whitespace here: `myarray[x/3+2:x/2+3... | I have never seen spaces used in slicing operations, so would err on the side of avoiding them. Then again, unless it's performance critical I'd be inclined to move the expressions outside of the slicing operation altogether. After all, your goal is readability:
```
lower = x / 3 + 2
upper = x / 2 + 3
myarray[lower:up... |
What is the keyboard shortcut to move to the start of a line in iPython? | 13,842,738 | 3 | 2012-12-12T15:13:29Z | 13,843,343 | 7 | 2012-12-12T15:43:25Z | [
"python",
"ipython"
] | Whilst typing in iPython, pressing `CTRL+A` I get taken to the front of the line as expected.
Now, after entering a line and recalling it by pressing the `Up arrow` I want to jump back to the front again, so I press `CTRL+A`:

Why am I now stuck on t... | There are various well-known incompatibilities with the default line editing library included with OSX, called `libedit`. So much so that IPython should start with a warning: "libedit detected, readline will not be well-behaved".
That same warning should show you how to solve it: do `easy_install readline` to install ... |
Receiving multicast data on specific interface | 13,844,893 | 5 | 2012-12-12T17:05:15Z | 13,848,541 | 7 | 2012-12-12T20:59:47Z | [
"python",
"sockets",
"multicast",
"packet",
"tcpdump"
] | tcmpdump can view all the multicast traffic to specific group and port on eth2, but my Python program cannot. The Python program, running on Ubuntu 12.04:
```
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Multicast port is 52122
sock.bind(('', 521... | Finally! Found [this question](http://serverfault.com/questions/163244/linux-kernel-not-passing-through-multicast-udp-packets) on ServerFault that addresses the same thing. Basically the kernel was not forwarding on / was filtering out the packets because it thought the sourced address was spoofed.
Changed the setting... |
Meaning of the backtick character in Python | 13,848,053 | 4 | 2012-12-12T20:29:55Z | 13,848,127 | 9 | 2012-12-12T20:35:21Z | [
"python"
] | I'm just getting started with python. Can somebody interpret line 2 of the following code snippet? I don't understand the `` `num` `` bit. I tried to replace the backtick character with a single tick `'`, but then it broke. Just a detailed explanation of that line would be great.
```
loop_count = 1000000
irn = ''.join... | Backticks are a deprecated alias for the `repr()` builtin function, so the second line is equivalent to the following:
```
irn = ''.join([repr(num) for num in range(loop_count)])
```
This uses a list comprehension to create a list of strings representing numbers, and then uses `''.join()` to combine that list of stri... |
Code in Python, communicate in Node.js and Socket.IO, present in HTML | 13,848,943 | 12 | 2012-12-12T21:26:50Z | 13,849,079 | 7 | 2012-12-12T21:36:22Z | [
"python",
"html",
"node.js",
"socket.io"
] | You have a python script `diagnosis.py` that generates realtime event-based data. Using Node.js, you can launch it as a child process and capture its output and then using Socket.IO emit that to the client and present it using HTML.
**Server**
```
var util = require('util'),
spawn = require('child_process').spaw... | [Apache Thrift](http://thrift.apache.org/) is a pretty awesome way to write RPC code between all of the major languages. You write a generic Thrift spec declaring the types and services, and then the code generator creates bindings for your desired languages. You can have apis for calling methods between your node and ... |
Proper way to comment code. Python | 13,850,049 | 4 | 2012-12-12T22:48:58Z | 13,850,162 | 8 | 2012-12-12T22:58:49Z | [
"python",
"comments"
] | I was reading PEP8 and some questions on stackoverflow, but was wondering about spaces between comments:
lets say I have this code:
```
class MyBrowser(QWebPage):
''' Settings for the browser.'''
def __init__(self):
QWebPage.__init__(self)
# Specifies whether images are automatically loaded i... | I don't know if this represents the "community standard" but here are [Google's Python style guides](https://google.github.io/styleguide/pyguide.html?showone=Comments#Comments) (as they relate to comments). Specifically classes:
```
class SampleClass(object):
"""Summary of class here.
Longer class information... |
Dynamically adding methods with or without metaclass in Python | 13,850,114 | 9 | 2012-12-12T22:55:05Z | 13,860,658 | 7 | 2012-12-13T13:17:23Z | [
"python",
"metaclass"
] | **Update - 2012/12/13**
Just to clarify - I'm not so much interested in ways how to add methods to classes - as you can see below in my question and in people's answers, there is more than one way to do that (tongue in cheek and hat tip to my Perl self).
The thing I am interested in is learning what's the fundamental... | The obvious reason to use metaclasses is because they really provide metadata about the class as soon as the class is known, unrelated to the presence of objects or not. Trivial, right? Well, let us show some commands I executed on your original `Z` and `Y` classes to see what this means:
```
In [287]: hasattr(Y,'foo'... |
How to use sprite groups in pygame | 13,851,051 | 5 | 2012-12-13T00:24:50Z | 13,851,145 | 7 | 2012-12-13T00:35:04Z | [
"python",
"sprite",
"pygame",
"groups"
] | So I've gotten to the point in my program where I need to create a group for some sprites that the player can collide with without dying (like some other sprites I may have on screen).
I've scoured Google but it appears that the official pygame documentation is useless and/or hard to comprehend. I'm looking for just a... | To answer your first question; to create a group you would do something like this:
```
gems = pygame.sprite.Group()
```
Then to add a sprite:
```
gems.add(gem)
```
Regarding the attributes for the group you'd like to edit it depends what they are. For example you could define something like this to indicate the dir... |
What are valid statements inside a python eval()? | 13,851,389 | 4 | 2012-12-13T01:07:33Z | 13,851,402 | 8 | 2012-12-13T01:09:16Z | [
"python",
"eval"
] | I have tried
```
eval('print("hello world")')
eval('return 0')
```
which are both incorrect. Why are they invalid and what rules should I follow when using `eval()` (other than as little as possible)? | In Python, `eval()` evaluates *expressions* (something that results in a value). Both `print` and `return` are defined as *statements* (however in Python 3, `print` is actually a function call, which is an expression). In the case of executing statements, you need to use [the `exec` statement](http://docs.python.org/2/... |
How to delete rows from a pandas DataFrame based on a conditional expression | 13,851,535 | 20 | 2012-12-13T01:28:24Z | 13,851,602 | 26 | 2012-12-13T01:37:01Z | [
"python",
"pandas"
] | I have a pandas DataFrame and I want to delete rows from it where the length of the string in a particular column is greater than 2. I know I can use `df.dropna()` to get rid of rows that contain any `NaN`, but I'm not seeing how to remove rows based on a conditional expression.
The answer for [this question](http://s... | When you do `len(df['column name'])` you are just getting one number, namely the number of rows in the DataFrame (i.e., the length of the column itself). If you want to apply `len` to each element in the column, use `df['column name'].map(len)`. So try
```
df[df['column name'].map(len) < 2]
``` |
How to delete rows from a pandas DataFrame based on a conditional expression | 13,851,535 | 20 | 2012-12-13T01:28:24Z | 27,360,130 | 53 | 2014-12-08T14:26:11Z | [
"python",
"pandas"
] | I have a pandas DataFrame and I want to delete rows from it where the length of the string in a particular column is greater than 2. I know I can use `df.dropna()` to get rid of rows that contain any `NaN`, but I'm not seeing how to remove rows based on a conditional expression.
The answer for [this question](http://s... | To directly answer this question's title (which I understand is not necessarily the OP's problem but could help other users coming across this question) one way to do this is to use the [drop](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.drop.html) method:
`df = df.drop(some labels)`
`df = df.d... |
python - printed a list, three dots appeared inside sublists | 13,851,581 | 6 | 2012-12-13T01:33:23Z | 13,851,619 | 11 | 2012-12-13T01:39:30Z | [
"python"
] | I printed out the contents of a list, and i got the following output:
```
[[...], [...], [...], [...], [...], [...]]
```
What are these strange dots?
I used python 2.7.3 | Probably you accidentally built a list containing a reference to itself (or here, lots of references):
```
>>> a = ['x']
>>> a
['x']
>>> a[0] = a
>>> a
[[...]]
```
The three dots are used so that the string representation doesn't drown in recursion. You can verify this by using `id` and the `is` operator:
```
>>> id... |
Is gevent + gunicorn scalable and stable for production use? | 13,852,752 | 5 | 2012-12-13T04:04:27Z | 13,853,992 | 11 | 2012-12-13T06:10:38Z | [
"python",
"webserver",
"tornado",
"gevent",
"gunicorn"
] | I have been looking at python web servers which offer scalability and decided to go with either Tornado (used by Facebook FriendFeed) or Gevent. Since I am pretty new to this, I relied on the [Benchmark of Python Web Servers](http://nichol.as/benchmark-of-python-web-servers) to shortlist Tornado and Gevent. Moreover, a... | As of this writing, Gunicorn is in **beta** (version 0.16) and Gevent has a **release candidate** for 1.0 ([Announcement on Google Groups](https://groups.google.com/forum/#!topic/gevent/hi2dKM66UHI/discussion)), so it might be reasonable to expect changes in the API (less so for Gevent) That said, as long as you track ... |
pandas' transform doesn't work sorting groupby output | 13,854,476 | 10 | 2012-12-13T06:46:04Z | 13,854,901 | 19 | 2012-12-13T07:19:15Z | [
"python",
"aggregate",
"pandas"
] | Another pandas question.
Reading Wes Mckinney's excellent book about Data Analysis and Pandas, I encountered the following thing that I thought should work:
Suppose I have some info about tips.
```
In [119]:
tips.head()
Out[119]:
total_bill tip sex smoker day time size tip_pct
0 16.99 1.01 ... | `transform` is not that well documented, but it seems that the way it works is that what the transform function is passed is not the entire group as a dataframe, but a single column of a single group. I don't think it's really meant for what you're trying to do, and your solution with `apply` is fine.
So suppose `tips... |
Python Requests - managing cookies | 13,854,735 | 8 | 2012-12-13T07:06:43Z | 19,129,354 | 14 | 2013-10-02T03:04:17Z | [
"python",
"cookies",
"python-requests"
] | I'm trying to get some content automatically from a site using requests (and bs4)
I have a script that gets a cookie:
```
def getCookies(self):
username = 'username'
password = 'password'
URL = 'logonURL'
r = requests.get(URL, auth=('username', 'password'))
cookies = r.cookies
```
dump of the coo... | I had a similar problem and found help in this question. The session jar was empty and to actually get the cookie I needed to use a session.
```
session = requests.session()
p = session.post("http://example.com", {'user':user,'password':password})
print 'headers', p.headers
print 'cookies', requests.utils.dict_from_co... |
How can I convert 24 hour time to 12 hour time? | 13,855,111 | 20 | 2012-12-13T07:35:28Z | 13,855,243 | 34 | 2012-12-13T07:46:02Z | [
"python",
"datetime",
"python-3.x",
"python-2.7",
"string-formatting"
] | I have the following 24-hour times:
```
{'Wed': '10:30 - 21:00', 'Sun': '10:30 - 21:00', 'Thu': '10:30 - 21:00',
'Mon': '10:30 - 21:00', 'Fri': '10:30 - 22:00', 'Tue': '10:30 - 21:00',
'Sat': '10:30 - 22:00'}
```
How can I convert this to 12-hour time?
```
{'Wed': '10:30 AM - 09:00 PM', 'Sun': '10:30 AM - 09:00 ... | ```
>>> from datetime import datetime
>>> d = datetime.strptime("10:30", "%H:%M")
>>> d.strftime("%I:%M %p")
'10:30 AM'
>>> d = datetime.strptime("22:30", "%H:%M")
>>> d.strftime("%I:%M %p")
'10:30 PM'
``` |
How can I convert 24 hour time to 12 hour time? | 13,855,111 | 20 | 2012-12-13T07:35:28Z | 13,855,387 | 7 | 2012-12-13T07:56:31Z | [
"python",
"datetime",
"python-3.x",
"python-2.7",
"string-formatting"
] | I have the following 24-hour times:
```
{'Wed': '10:30 - 21:00', 'Sun': '10:30 - 21:00', 'Thu': '10:30 - 21:00',
'Mon': '10:30 - 21:00', 'Fri': '10:30 - 22:00', 'Tue': '10:30 - 21:00',
'Sat': '10:30 - 22:00'}
```
How can I convert this to 12-hour time?
```
{'Wed': '10:30 AM - 09:00 PM', 'Sun': '10:30 AM - 09:00 ... | The key to this code is to use the [library function `time.strptime()`](http://docs.python.org/2/library/time.html#time.strptime) to parse the 24-hour string representations into a `time.struct_time` object, then use [library function `time.strftime()`](http://docs.python.org/2/library/time.html#time.strftime) to forma... |
bash: mkvirtualenv: command not found | 13,855,463 | 37 | 2012-12-13T08:03:18Z | 13,855,464 | 34 | 2012-12-13T08:03:18Z | [
"python",
"bash",
"centos",
"virtualenv",
"virtualenvwrapper"
] | After following the instructions on [Doug Hellman's `virtualenvwrapper` post](http://www.doughellmann.com/articles/pythonmagazine/completely-different/2008-05-virtualenvwrapper/index.html), I still could not fire up a test environment.
```
[mpenning@tsunami ~]$ mkvirtualenv test
-bash: mkvirtualenv: command not found
... | For some reason, `virtualenvwrapper.sh` installed in `/usr/bin/virtualenvwrapper.sh`, instead of under `/usr/local/bin`.
The following in my `.bash_profile` works...
```
source "/usr/bin/virtualenvwrapper.sh"
export WORKON_HOME="/opt/virtual_env/"
```
My install seems to work fine without sourcing `virtualenvwrapper... |
bash: mkvirtualenv: command not found | 13,855,463 | 37 | 2012-12-13T08:03:18Z | 20,725,914 | 24 | 2013-12-22T03:20:08Z | [
"python",
"bash",
"centos",
"virtualenv",
"virtualenvwrapper"
] | After following the instructions on [Doug Hellman's `virtualenvwrapper` post](http://www.doughellmann.com/articles/pythonmagazine/completely-different/2008-05-virtualenvwrapper/index.html), I still could not fire up a test environment.
```
[mpenning@tsunami ~]$ mkvirtualenv test
-bash: mkvirtualenv: command not found
... | I had the same issue on OS X 10.9.1 with python 2.7.5. No issues with `WORKON_HOME` for me, but I did have to manually add `source "/usr/local/bin/virtualenvwrapper.sh"` to `~/.bash_profile` (or `~/.bashrc` in unix) after I ran `pip install virtualenvwrapper` |
Using Pre_delete Signal in django | 13,857,007 | 8 | 2012-12-13T09:42:04Z | 13,858,075 | 20 | 2012-12-13T10:41:11Z | [
"python",
"django",
"django-models",
"django-signals"
] | In my app I want to keep a track of all the questions that are being deleted. And so I have created a class(table) as such in my models file.
```
class Deleted(models.Model):
question = models.IntegerField(null=True, blank=True)#id of question being deleted
user = models.IntegerField(null=True, blank=True)#id of user ... | You start off by defining the [receiver](https://docs.djangoproject.com/en/dev/topics/signals/#django.dispatch.receiver) you want to use:
```
def log_deleted_question(sender, instance, using, **kwargs):
d = Deleted()
d.question = instance.id
d.dt = datetime.datetime.now() # consider using auto_now=True in ... |
Python logging.DEBUG level doesn't logging | 13,857,788 | 15 | 2012-12-13T10:25:15Z | 13,858,009 | 16 | 2012-12-13T10:37:05Z | [
"python",
"logging",
"syslog-ng"
] | I have a problem with python's `logging` lib. With the code below I create a "logger":
```
logger = logging.getLogger()
def logger_init(level):
try:
syslog = SysLogHandler(address=LOG_DESTINATION)
except Exception, ex:
return
formatter = logging.Formatter('%(module)s[%(process)d]: %(message... | You also have to set the level of the logger, not only the handler.
Add this to your `logger_init`:
```
logger.setLevel(level)
``` |
split byte string into lines | 13,857,856 | 12 | 2012-12-13T10:28:02Z | 13,858,054 | 16 | 2012-12-13T10:40:13Z | [
"python",
"python-3.x"
] | How can I split a byte string into a list of lines?
In python 2 I had:
```
rest = "some\nlines"
for line in rest.split("\n"):
print line
```
The code above is simplified for the sake of brevity, but now after some regex processing, I have a byte array in `rest` and I need to iterate the lines. | Decode the bytes into unicode (str) and then use `str.split`:
```
Python 3.2.3 (default, Oct 19 2012, 19:53:16)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = b'asdf\nasdf'
>>> a.split('\n')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
... |
split byte string into lines | 13,857,856 | 12 | 2012-12-13T10:28:02Z | 15,095,537 | 26 | 2013-02-26T17:33:28Z | [
"python",
"python-3.x"
] | How can I split a byte string into a list of lines?
In python 2 I had:
```
rest = "some\nlines"
for line in rest.split("\n"):
print line
```
The code above is simplified for the sake of brevity, but now after some regex processing, I have a byte array in `rest` and I need to iterate the lines. | There is no reason to convert to string. Just give `split` bytes parameters. Split strings with strings, bytes with bytes.
```
Python 3.2.3 (default, Oct 19 2012, 19:53:57)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = b'asdf\nasdf'
>>> a.split(b'\n')
[b'asdf', b... |
Output sorted python dict within django template | 13,858,069 | 2 | 2012-12-13T10:40:59Z | 13,858,143 | 9 | 2012-12-13T10:45:09Z | [
"python",
"django",
"templates",
"sorting",
"dictionary"
] | I got a python dict, that looks like the following (Important informations were replaced with "xxx" due to privacy reasons).
I would like to display this dict within a django template but it should be ordered, so it should start with "A", then continue with "B" instead of "H"
This is my dict (shortened):
```
{ 'A':... | Dictionaries are unsorted.
You will need to convert your dict to a nested list in the view: the easiest way would be just to call `sorted(bdays_all.items())`. |
update dictionary with dynamic keys and values in python | 13,860,026 | 3 | 2012-12-13T12:36:39Z | 13,860,049 | 7 | 2012-12-13T12:38:06Z | [
"python",
"dictionary",
"python-3.x",
"key"
] | I have a dictionary and I want to insert keys and values dynamically but I didn't manage to do it. The problem is that when I use the update method it doesn't add a pair but it deletes the previous values so I have only the last value when printing the dictionary
here is my code
```
i = 0
for o in iterload(f):
i=i... | Remove the following line:
```
mydic = {i : o["name"]}
```
and add the following before your loop:
```
mydic = {}
```
Otherwise you're creating a brand new one-element dictionary on every iteration.
Also, the following:
```
mydic.update({i : o["name"]})
```
is more concisely written as
```
mydic[i] = o["nam... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.