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 |
|---|---|---|---|---|---|---|---|---|---|
Filtering and selecting from pivot tables made with python pandas | 11,973,741 | 4 | 2012-08-15T17:04:17Z | 11,976,153 | 7 | 2012-08-15T19:47:23Z | [
"python",
"indexing",
"pivot",
"pivot-table",
"pandas"
] | I'm struggling with hierarchical indexes in the Python pandas package. Specifically I don't understand how to filter and compare data in rows after it has been pivoted.
Here is the example table from the documentation:
```
import pandas as pd
import numpy as np
In [1027]: df = pd.DataFrame({'A' : ['one', 'one', 'two... | Pivot table returns a DataFrame so you can simply filter by doing:
```
In [15]: pivoted = pivot_table(df, values='D', rows=['A', 'B'], cols=['C'])
In [16]: pivoted[pivoted.foo < 0]
Out[16]:
C bar foo
A B
one A -0.412628 -1.062175
three B NaN -0.562207
two A N... |
How to output a comma delimited list in jinja python template? | 11,974,318 | 47 | 2012-08-15T17:43:18Z | 11,974,399 | 76 | 2012-08-15T17:49:34Z | [
"python",
"jinja2"
] | If I have a list of `users` say `["Sam", "Bob", "Joe"]`, I want to do something where I can output in my jinja template file:
```
{% for user in userlist %}
<a href="/profile/{{ user }}/">{{ user }}</a>
{% if !loop.last %}
,
{% endif %}
{% endfor %}
```
I want to make the output template be:
```... | I believe you want your if check to be:
```
{% if not loop.last %}
,
{% endif %}
``` |
How to output a comma delimited list in jinja python template? | 11,974,318 | 47 | 2012-08-15T17:43:18Z | 22,831,412 | 47 | 2014-04-03T08:04:44Z | [
"python",
"jinja2"
] | If I have a list of `users` say `["Sam", "Bob", "Joe"]`, I want to do something where I can output in my jinja template file:
```
{% for user in userlist %}
<a href="/profile/{{ user }}/">{{ user }}</a>
{% if !loop.last %}
,
{% endif %}
{% endfor %}
```
I want to make the output template be:
```... | you could also use the builtin "join" filter (<http://jinja.pocoo.org/docs/templates/#join> like this:
```
{{ users|join(', ') }}
``` |
How to output a comma delimited list in jinja python template? | 11,974,318 | 47 | 2012-08-15T17:43:18Z | 33,940,873 | 17 | 2015-11-26T14:15:39Z | [
"python",
"jinja2"
] | If I have a list of `users` say `["Sam", "Bob", "Joe"]`, I want to do something where I can output in my jinja template file:
```
{% for user in userlist %}
<a href="/profile/{{ user }}/">{{ user }}</a>
{% if !loop.last %}
,
{% endif %}
{% endfor %}
```
I want to make the output template be:
```... | And using the `joiner` from <http://jinja.pocoo.org/docs/dev/templates/#joiner>
```
{% set comma = joiner(",") %}
{% for user in userlist %}
{{ comma() }}<a href="/profile/{{ user }}/">{{ user }}</a>
{% endfor %}
```
It's made for this exact purpose. |
Dictionary into dictionary in python | 11,975,020 | 2 | 2012-08-15T18:33:49Z | 11,975,046 | 11 | 2012-08-15T18:35:51Z | [
"python",
"dictionary"
] | Ok, this one should be simple. I have 3 dictionaries. They are all made, ordered, and filled to my satisfaction but I would like to put them all in an overarching dictionary so I can reference and manipulate them more easily and efficiently.
```
Layer0 = {}
Layer1 = {}
Layer2 = {}
```
here they are when created, and ... | [Dictionary](http://docs.python.org/tutorial/datastructures.html#dictionaries) items have both a key and a value.
```
Layers = {'Layer0': Layer0, 'Layer1': Layer1, 'Layer2': Layer2}
``` |
Efficient unit basis vector with numpy | 11,975,146 | 9 | 2012-08-15T18:40:50Z | 11,975,241 | 9 | 2012-08-15T18:46:40Z | [
"python",
"numpy"
] | Given an index and a size, is there a more efficient way to produce:
```
import numpy as np
np.array([1.0 if i == index else 0.0 for i in range(size)])
``` | ```
In [2]: import numpy as np
In [9]: size = 5
In [10]: index = 2
In [11]: np.eye(1,size,index)
Out[11]: array([[ 0., 0., 1., 0., 0.]])
```
---
Hm, unfortunately, using np.eye for this is rather slow:
```
In [12]: %timeit np.eye(1,size,index)
100000 loops, best of 3: 7.68 us per loop
In [13]: %timeit a = np... |
Why does `getattr` not support consecutive attribute retrievals? | 11,975,781 | 14 | 2012-08-15T19:22:21Z | 11,975,810 | 15 | 2012-08-15T19:23:59Z | [
"python"
] | ```
class A(): pass
a = A()
b = A()
a.b = b
b.c = 1
a.b # this is b
getattr(a, "b") # so is this
a.b.c # this is 1
getattr(a, "b.c") # this raises an AttributeError
```
It seemed very natural to me to assume the latter. I'm sure there is a good reason for this. What is it? | You can't put a period in the getattr function because getattr is a direct dictionary lookup of the object.
If you use the 'dir' function on a, you'll see the dictionary keys that correspond to your object's attributes. In this case, "b.c" *isn't* in the set of dictionary keys.
The only way to do this with `getattr` ... |
Why does `getattr` not support consecutive attribute retrievals? | 11,975,781 | 14 | 2012-08-15T19:22:21Z | 14,324,459 | 34 | 2013-01-14T18:37:20Z | [
"python"
] | ```
class A(): pass
a = A()
b = A()
a.b = b
b.c = 1
a.b # this is b
getattr(a, "b") # so is this
a.b.c # this is 1
getattr(a, "b.c") # this raises an AttributeError
```
It seemed very natural to me to assume the latter. I'm sure there is a good reason for this. What is it? | [Python's built-in `reduce` function](http://docs.python.org/2/library/functions.html#reduce) enables the functionality you're looking for. Here's a simple little helper function that will get the job done:
```
class NoDefaultProvided(object):
pass
def getattrd(obj, name, default=NoDefaultProvided):
"""
S... |
How to keep index when using pandas merge | 11,976,503 | 25 | 2012-08-15T20:10:04Z | 11,982,843 | 36 | 2012-08-16T07:53:01Z | [
"python",
"pandas"
] | I would like to merge two data frames, and keep the index from the first frame as the index on the merged dataset. However, when I do the merge, the resulting DataFrame has integer index. How can I specify that I want to keep the index from the left data frame?
```
In [441]: a=DataFrame(data={"col1": [1,2,3], 'to_merg... | ```
In [5]: a.reset_index().merge(b, how="left").set_index('index')
Out[5]:
col1 to_merge_on col2
index
a 1 1 1
b 2 3 2
c 3 4 NaN
``` |
Lists as reference types in python | 11,977,060 | 2 | 2012-08-15T20:50:16Z | 11,977,124 | 7 | 2012-08-15T20:54:39Z | [
"python",
"primes"
] | Following is the piece of code that i wrote to calculate the nth prime number.
I initialize arr = [2,3,5]; and prime(arr,n) is supposed to modify arr to contain first n prime numbers. But arr does not reflect changes after prime(arr,n) is executed.
I read that lists are passed as reference types ,so what is the problem... | Change the line:
```
arr = arr + [num];
```
to
```
arr.append(num)
```
The new line actually changes the `arr` array. The original line didn't change it; it created a *new* variable called `arr` (it was a [rebinding operation instead of a mutating one](http://en.wikipedia.org/wiki/Name_binding#Rebinding_and_mutatio... |
Builder pattern equivalent in Python | 11,977,279 | 17 | 2012-08-15T21:05:11Z | 11,977,454 | 42 | 2012-08-15T21:16:45Z | [
"python",
"design-patterns",
"builder-pattern"
] | In Java, you can use the [**builder pattern**](http://stackoverflow.com/questions/5007355/builder-pattern-in-effective-java) to provide a more readable means to instantiating a class with many parameters. In the builder pattern, one constructs a configuration object with methods to set named attributes, and then uses i... | Design patterns can often be replaced with built-in language features.
### Your use case
You say "I wanted to have a more readable "means" to instantiating a class with many parameters.". In Java's case:
> [[A] use case for the builder pattern is when the constructor of the object to be built must take very many par... |
Builder pattern equivalent in Python | 11,977,279 | 17 | 2012-08-15T21:05:11Z | 26,193,004 | 13 | 2014-10-04T12:51:08Z | [
"python",
"design-patterns",
"builder-pattern"
] | In Java, you can use the [**builder pattern**](http://stackoverflow.com/questions/5007355/builder-pattern-in-effective-java) to provide a more readable means to instantiating a class with many parameters. In the builder pattern, one constructs a configuration object with methods to set named attributes, and then uses i... | The OP set themselves up for a fall by casting the Builder pattern as Java specific. It's not. It's in the [Gang of Four's book](http://en.wikipedia.org/wiki/Builder_pattern) and is potentially relevant to any object oriented language.
Unfortunately, even the [Wikipedia article on the Builder pattern](http://en.wikipe... |
Creating a dictionary with same values | 11,977,730 | 2 | 2012-08-15T21:37:01Z | 11,977,757 | 12 | 2012-08-15T21:40:06Z | [
"python",
"dictionary"
] | Suppose I have dictionary `a = {}` and I want to have it a result like this
```
value = 12
a = {'a':value,'b':value,'f':value,'h':value,'p':value}
```
and so on for many `keys:same value`. Now of course I can do it like this
```
a.update({'a':value})
a.update({'b':value})
```
and so on....
but since the value is sa... | You could use [dict comprehensions](http://www.python.org/dev/peps/pep-0274/) (python 2.7+):
```
>>> v = 12
>>> d = {k:v for k in 'abfhp'}
>>> print d
{'a': 12, 'h': 12, 'b': 12, 'p': 12, 'f': 12}
``` |
Reverse the one-to-one mapped dictionary | 11,978,037 | 2 | 2012-08-15T22:07:19Z | 11,978,059 | 11 | 2012-08-15T22:09:26Z | [
"python",
"dictionary"
] | Suppose there is a dictionary
```
a = {'a':122,'b':123,'d':333,'e':'233'}
```
Now I want to revert it as its a one-to-one dictionary so we can do that.
What I have tried:
```
In [67]: ivd=[(v,k) for (k,v) in a.items()]
In [68]: ivd
Out[68]: [(122, 'a'), (123, 'b'), ('233', 'e'), (333, 'd')]
```
Now may be some ho... | You can use dict constructor:
```
ivd = dict((v, k) for (k, v) in a.iteritems())
```
or dict comprehension in python 2.7 or later:
```
ivd = {v: k for (k, v) in a.items()}
``` |
How to make an OR statement in python? | 11,978,463 | 2 | 2012-08-15T22:50:59Z | 11,978,475 | 8 | 2012-08-15T22:52:05Z | [
"python"
] | Why does this not work:
```
file = "v3a2"
if "v1" or "v2" in file:
v1.write(total)
elif "v3" in file:
print "never here?????"
```
How to formulate this? | Try
```
if "v1" in file or "v2" in file:
```
instead of
```
if "v1" or "v2" in file:
```
Perhaps a review of Python [Boolean Operations](http://docs.python.org/reference/expressions.html#boolean-operations) might be helpful. At the bottom of that page in the summary there is also a *table of operator precedence*.... |
How to make an OR statement in python? | 11,978,463 | 2 | 2012-08-15T22:50:59Z | 11,978,498 | 7 | 2012-08-15T22:57:22Z | [
"python"
] | Why does this not work:
```
file = "v3a2"
if "v1" or "v2" in file:
v1.write(total)
elif "v3" in file:
print "never here?????"
```
How to formulate this? | ```
if "v1" or "v2" in file:
```
is equivalent to
```
if ("v1") or ("v2" in file):
```
Which will always be `True` because `bool("v1")==True`
you could say
```
if any(x in file for x in ["v1", "v2"]):
```
or
```
if "v1" in file or "v2" in file:
```
The version with `any` looks ni... |
Django: DecimalField values displaying | 11,978,640 | 3 | 2012-08-15T23:19:09Z | 11,980,742 | 8 | 2012-08-16T04:28:56Z | [
"python",
"django",
"django-models",
"django-templates"
] | I have a model with `DecimalField`:
```
points_player1 = models.DecimalField(max_digits=3, decimal_places=1, blank=True, null=True)
```
When I displaying this field in template, it always shows values like `0.0` or `1.0` etc.
But I want to make this behavior more user-friendly:
1. If user input, for example, is `1` ... | You can do `{{decimal_field|floatformat}}` in the template, which will round off and show ".0" only when necessary.
More reference [template - floatformat](https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#floatformat) |
subclasses of pandas' object work differently from subclass of other object? | 11,979,194 | 5 | 2012-08-16T00:39:34Z | 11,982,602 | 10 | 2012-08-16T07:34:54Z | [
"python",
"subclass",
"pandas",
"series"
] | I am trying to create a subclass of a Panda data structure to substitute, in my code, a subclass of a **dict** with a subclass of a **Series**, I don't understand why this example code doesn't work
```
from pandas import Series
class Support(Series):
def supportMethod1(self):
print 'I am support metho... | # Current Answer (Pandas >= 0.13)
An internal refactor in Pandas 0.13 drastically simplified subclassing. Pandas `Series` can now be subclassed like any other Python object:
```
class MySeries(pd.Series):
def my_method(self):
return "my_method"
```
# Legacy Answer (Pandas <= 0.12)
The problem is that Se... |
Reverse dns lookup with scapy in python | 11,979,250 | 2 | 2012-08-16T00:47:47Z | 11,981,798 | 8 | 2012-08-16T06:30:26Z | [
"python",
"scapy",
"reverse-dns"
] | How can I do reverse DNS lookup using `scapy` in Python? I look for it in Google but I couldn't find related to this topic. | Reverse DNS is already written into Python's Socket module. Simply use the following:
```
>>> import socket
>>> socket.gethostbyaddr("69.59.196.211")
('stackoverflow.com', ['211.196.59.69.in-addr.arpa'], ['69.59.196.211'])
```
Which was originally posted here, [Python lookup hostname from IP with 1 second timeout]... |
Why Python built in "all" function returns True for empty iterables? | 11,979,683 | 19 | 2012-08-16T01:53:18Z | 11,979,706 | 7 | 2012-08-16T01:56:50Z | [
"python"
] | I know it has a good reason, but I want to know what reason?
```
>>> print all([])
True
```
If all() is intended to check if every item on iterable evaluates to "True", and we know empty lists are evaluated to False
```
>>> bool([])
False
```
So why the all() returns True for empty lists?
< edit >
I already read ... | [`all()`](http://docs.python.org/library/functions.html#all) (documented to "*Return True if all elements of the iterable are true (**or if the iterable is empty**).*") is equivalent to the following:
```
def all(iterable):
for element in iterable:
if not element:
return False
return True
`... |
Why Python built in "all" function returns True for empty iterables? | 11,979,683 | 19 | 2012-08-16T01:53:18Z | 11,979,709 | 20 | 2012-08-16T01:57:16Z | [
"python"
] | I know it has a good reason, but I want to know what reason?
```
>>> print all([])
True
```
If all() is intended to check if every item on iterable evaluates to "True", and we know empty lists are evaluated to False
```
>>> bool([])
False
```
So why the all() returns True for empty lists?
< edit >
I already read ... | This is expressed as "For all X in S, X is true". If S is empty, there are no X. However, the truth statement remains True, because for all X, X was true... there just aren't any X!
Here is a explanation [using logic](http://bytes.com/topic/python/answers/474051-any-all-empty-list).
> Consider two sets A and B where ... |
In python, how do you import all classes from another module without keeping the imported module's namespace? | 11,980,062 | 2 | 2012-08-16T02:48:55Z | 11,980,088 | 16 | 2012-08-16T02:52:46Z | [
"python"
] | How do you import classes and methods from another module without retaining the former module namespace?
I am current refactoring some legacy code and am frequently doing imports similar to these.
```
from legacy_module import ClassA as ClassA
from legacy_module import ClassB as ClassB
from legacy_module import Class... | Use `from legacy_module import *` as your entire import. |
Django URL didn't match any of URL config | 11,980,110 | 2 | 2012-08-16T02:55:08Z | 11,980,129 | 8 | 2012-08-16T02:57:54Z | [
"python",
"django",
"design-patterns",
"django-urls"
] | The errors message is:
```
Using the URLconf defined in Blog.urls,
Django tried these URL patterns, in this order:
^admin/doc/
^admin/
^post/ ^post/(?P<post_id>\d+)/$
The current URL, post/1458/, didn't match any of these.
```
Why? I think `post/1485/` match `^post/(?P<post_id>\d+)/$`
My root url config is:
```
u... | Your current setup would match URLs like this:
```
/post/post/1485/
```
Make `posts/urls.py` look like:
```
urlpatterns = patterns('',
...
url(r'^(?P<post_id>\d+)/$', 'post.views.post_page'),
)
``` |
Multiple Columns in PyQt4 (potentially using QTreeWidget) | 11,980,149 | 3 | 2012-08-16T03:01:08Z | 11,980,701 | 14 | 2012-08-16T04:24:57Z | [
"python",
"pyqt4",
"qtreewidget"
] | I'm trying to get QTreeWidget working exactly similar to this one. In python! I don't care about multiple tabs but about multiple columns.

This is what I've got so far. I don't know how to have more than one header though.
```
self.pointListBox = QtGui.QTreeWidget()
x=Qt... | There's a few things you'll want to fix there.
```
from PyQt4 import QtCore, QtGui
import sys
app = QtGui.QApplication(sys.argv)
QtGui.qApp = app
pointListBox = QtGui.QTreeWidget()
header=QtGui.QTreeWidgetItem(["Tree","First","secondo"])
#...
pointListBox.setHeaderItem(header) #Another alternative is setHeaderLab... |
How do you create a Button on a tkinter Canvas? | 11,980,812 | 4 | 2012-08-16T04:39:09Z | 11,981,214 | 8 | 2012-08-16T05:34:34Z | [
"python",
"user-interface",
"button",
"tkinter"
] | I created a Frame and then a Canvas.
What I want to do next is to add a Button on the Canvas.
However, when I packed the Button I cannot see the Canvas!
Here is what I tried:
```
from Tkinter import Tk, Canvas, Frame, Button
from Tkinter import BOTH, W, NW, SUNKEN, TOP, X, FLAT, LEFT
class Example(Frame):
de... | The Tkinter `pack` manager tries to resize the parent widget to the correct size to contain its child widgets, and no larger, by default. So the canvas is there - but it's precisely the same size as the button, and thus invisible.
If you want to place a widget on a canvas *without* causing the canvas to dynamically re... |
What does __init__ method return in python | 11,981,368 | 10 | 2012-08-16T05:50:12Z | 11,981,379 | 26 | 2012-08-16T05:51:26Z | [
"python"
] | ```
class Num:
def __init__(self,num):
self.n = num
```
I read that the `__init__` method returns `None`.When I perform `a=Num(5)`, `Num(5)` will call `__init__` method of the class.But if `__init__` returns `None` then `a` should reference nothing.But instead `a` is referencing the object of `Num` Class.How ... | `__init__()` returns `None`. It is [`__new__()`](http://docs.python.org/reference/datamodel.html#object.__new__) that returns the new instance. |
Python Gtk.Entry placeholder text | 11,982,799 | 4 | 2012-08-16T07:49:55Z | 11,985,546 | 7 | 2012-08-16T10:47:34Z | [
"python",
"gtk",
"entry"
] | i have a login-window with two gtk.Entry objects, one for username, one for password. How can i add some Ghosttext to the Entry, so there is written "Username" in the Entry but if you click inside the text dissapears. | Starting with Gtk+ 3.2 it's possible to [set placeholder text](http://developer.gnome.org/gtk3/3.4/GtkEntry.html#gtk-entry-set-placeholder-text).
```
entry = Gtk.Entry()
entry.set_placeholder_text("I am a placeholder")
``` |
Matplotlib Legends not working | 11,983,024 | 31 | 2012-08-16T08:07:48Z | 11,983,074 | 70 | 2012-08-16T08:12:11Z | [
"python",
"plot",
"matplotlib"
] | Ever since upgrading matplotlib I get the following error whenever trying to create a legend:
```
/usr/lib/pymodules/python2.7/matplotlib/legend.py:610: UserWarning: Legend does not support [<matplotlib.lines.Line2D object at 0x3a30810>]
Use proxy artist instead.
http://matplotlib.sourceforge.net/users/legend_guide.h... | You should add commas:
```
plot1, = plt.plot(a,b)
plot2, = plt.plot(a,c)
```
The reason you need the commas is because plt.plot() returns a tuple of line objects, no matter how many are actually created from the command. Without the comma, "plot1" and "plot2" are tuples instead of line objects, making the later call ... |
How to fix issue with 'datetime.datetime' which has no attribute timedelta? | 11,983,609 | 7 | 2012-08-16T08:49:27Z | 11,983,701 | 12 | 2012-08-16T08:54:40Z | [
"python",
"datetime"
] | How will I fix this problem on Python. Here's my code:
```
import time
import datetime
from time import mktime
from datetime import datetime
date = '20120814174530'
date_to_strp = time.strptime(date, '%Y%m%d%H%M%S') #convert the value of date into strptime
date_final = datetime.fromtimesta... | Either use `datetime.datetime.fromtimestamp` or change the import to `from datetime import datetime as dt` and use `dt.fromtimestamp`. |
python - appending to same file from multiple threads | 11,983,938 | 10 | 2012-08-16T09:08:59Z | 11,984,760 | 18 | 2012-08-16T09:57:49Z | [
"python"
] | I'm writing an app that appends lines to a the same file from multiple threads.
I have a problem in which some lines are appended without a new line.
Any solution for this?
```
class PathThread(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
d... | The solution is to write to the file in one thread only.
```
import Queue # or queue in Python 3
import threading
class PrintThread(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def printfiles(self, p):
for path, dirs, files in os.wa... |
Why does Python return a negative timezone value? | 11,984,618 | 6 | 2012-08-16T09:49:18Z | 11,984,774 | 7 | 2012-08-16T09:58:27Z | [
"python",
"time",
"timezone"
] | For [time.timezone](http://docs.python.org/py3k/library/time.html?highlight=time.timezone#time.timezone), the Python documentation says:
> The offset of the local (non-DST) timezone, in seconds west of UTC (negative in most of Western Europe, positive in the US, zero in the UK).
Does anybody know why it returns a neg... | This is a Unix artefact. Although the standard numeric description for timezones is in hours and minutes east from UTC (UTC+1 for Brussels, UTC-5 for New York, etc.) the Unix `timezone` is measured in seconds *west* from UTC.
From <http://pubs.opengroup.org/onlinepubs/7908799/xsh/tzset.html>:
> The external variable ... |
Python regex - Ignore parenthesis as indexing? | 11,985,628 | 4 | 2012-08-16T10:53:45Z | 11,985,790 | 8 | 2012-08-16T11:03:51Z | [
"python",
"regex",
"findall"
] | I've currently written a nooby regex pattern which involves excessive use of the "(" and ")" characters, but I'm using them for 'or' operators, such as (A|B|C) meaning A or B or C.
I need to find every match of the pattern in a string.
Trying to use the `re.findall(pattern, text)` method is no good, since it interpr... | Yes, add `?:` to a group to make it non-capturing.
```
import re
print re.findall('(.(foo))', "Xfoo") # [('Xfoo', 'foo')]
print re.findall('(.(?:foo))', "Xfoo") # ['Xfoo']
```
See [re syntax](http://docs.python.org/library/re.html#regular-expression-syntax) for more information. |
Is it possible to make this shell script faster? | 11,987,832 | 13 | 2012-08-16T13:07:15Z | 11,988,198 | 7 | 2012-08-16T13:26:28Z | [
"python",
"shell",
"unix"
] | I have a task of creating a script which takes a huge text file as an input. It then needs to find all words and the number of occurrences and create a new file with each line displaying a unique word and its occurrence.
As an example take a file with this content:
```
Lorem ipsum dolor sit amet, consectetur adipisic... | An important point here is probably inter-process I/O. The Python script has all data in memory, so no I/O happens while it processes the data.
Also note that Python isn't slow as such. Most functionality in Python is implemented in C.
The shell script has to start 5 processes and each of them has to read the whole t... |
Which form of connection to use with pika | 11,987,838 | 16 | 2012-08-16T13:07:36Z | 11,989,180 | 7 | 2012-08-16T14:19:11Z | [
"python",
"rabbitmq",
"pika"
] | I've been trying to figure out which form of connection i should use when using pika, I've got two alternatives as far as I understand.
Either the `BlockingConnection` or the `SelectConnection`, however I'm not really sure about the differences between these two (i.e. what is the BlockingConnection blocking? and more)... | The SelectConnection is useful if your application architecture can benefit from an asynchronous design, e.g. doing something else while the RabbitMQ IO completes (e.g. switch to some other IO etc) . This type of connection uses callbacks to indicate when functions return. For example you can declare callbacks for
on\... |
regex for capturing group that is only sometimes present | 11,988,702 | 2 | 2012-08-16T13:52:32Z | 11,988,762 | 7 | 2012-08-16T13:55:37Z | [
"python",
"regex",
"grouping"
] | I have a set of filenames like:
```
PATJVI_RNA_Tumor_8_3_63BJTAAXX.310_BUSTARD-2012-02-19.fq.gz
PATMIF_RNA_Tumor_CGTGAT_2_1_BC0NKBACXX.334_BUSTARD-2012-05-07.fq.gz
```
I would like to have a single regex (in python, fyi) that can capture each of the groups between the "\_" characters. However, note that in the second... | To make a group optional, you can add `?` after the desired group. Like this:
(\w+)?
But your example has an underscore that should be optional as well. To deal with it, you can group it together with optional group.
```
((\w+)_)?
```
However this will add a new group to your match results. To avoid it, use a non-ma... |
How to heapify by field from custom objects | 11,989,178 | 2 | 2012-08-16T14:19:03Z | 11,989,773 | 7 | 2012-08-16T14:46:07Z | [
"python",
"python-2.7"
] | I am receiving on server objects from clients ( every object has same structure and have field self.utc\_time which contains time of creation of that object). I need to store in some structure so I always have sorted in ascending so when I pop I pop the oldest object by utc\_time, not by time when I receive. I thought ... | Add the [magic `__cmp__` comparison method](http://docs.python.org/reference/datamodel.html#object.__cmp__) to your class to avoid needing to do the tuple-decoration that Maksim describes:
```
>>> import heapq
>>> class MyObject(object):
... def __init__(self, val):
... self.val = val
... def __cmp__(s... |
Pyramids route_url with additional query arguments | 11,989,317 | 8 | 2012-08-16T14:25:53Z | 11,989,318 | 25 | 2012-08-16T14:25:53Z | [
"python",
"url-routing",
"pyramid"
] | In Pyramids framework, functions `route_path` and `route_url` are used to generate urls from routes configuration. So, if I have route:
```
config.add_route('idea', 'ideas/{idea}')
```
I am able to generate the url for it using
```
request.route_url('idea', idea="great");
```
However, sometimes I may want to add ad... | You can add additional query arguments to url passing the `_query` dictionary
```
request.route_url('idea', idea='great', _query={'sort':'asc'})
``` |
Replacing "\r\n" with "\n" | 11,989,501 | 6 | 2012-08-16T14:34:09Z | 11,989,578 | 9 | 2012-08-16T14:37:24Z | [
"python"
] | I have some text data that is printing out the actual characters "\r\n" (so four characters total). I'd like to replace those four characters with the single "\n" character, but I can't seem to make Python do it for me. I'm currently trying:
```
mytext.replace("\r\n", "\n")
```
But that just prints out "\n" (two char... | ```
mytext.replace(r"\r\n", r"\n")
```
The 'r' denotes a raw string, which tells python to interpret the backslashes in the text as literal characters and not as escape characters. |
producing all the anagrams from a string python | 11,989,502 | 3 | 2012-08-16T14:34:08Z | 11,989,618 | 11 | 2012-08-16T14:39:27Z | [
"python"
] | I was thinking about this problem today, and I came with the following pseudocode (Python 3.2) :
```
def anagrams( string ):
for c in string:
anagram = c + anagram( string - {c} ) # remove the char from its position in the string
print(anagram)
return
def main():
word = "abcd"
anagrams(... | Why not just use [itertools](http://docs.python.org/library/itertools.html)?
```
>>> import itertools
>>> ["".join(perm) for perm in itertools.permutations("abc")]
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
```
The [documentation](http://docs.python.org/library/itertools.html#itertools.permutations) also contains cod... |
How to create a worldwide unique GUID/UUID system for Mongo with Python? | 11,990,254 | 9 | 2012-08-16T15:09:16Z | 11,996,090 | 7 | 2012-08-16T22:03:27Z | [
"python",
"mongodb",
"guid",
"uuid",
"pymongo"
] | In the Mongo docs, it states the following:
> The \_id field can be of any type; however, it must be unique. Thus you
> can use UUIDs in the \_id field instead of BSON ObjectIds (BSON
> ObjectIds are slightly smaller; they need not be worldwide unique,
> just unique for a single db cluster). When using UUIDs, your
> a... | If you want a unique id, and don't want to use ObjectId, you probably want to use uuid4:
```
>>> import pymongo
>>> import uuid
>>> c = pymongo.Connection()
>>> uu = uuid.uuid4()
>>> uu
UUID('14a2aad7-fa01-40a4-8a80-04242b946ee4')
>>> c.test.uuidtest.insert({'_id': uu})
UUID('14a2aad7-fa01-40a4-8a80-04242b946ee4')
>>>... |
How to fix this script so that it won't peg the CPU? | 11,990,503 | 6 | 2012-08-16T15:22:41Z | 11,990,663 | 12 | 2012-08-16T15:31:41Z | [
"python",
"performance",
"keyboard",
"cpu",
"xlib"
] | On my home Kubuntu machine, I am running a script to beep on every keypress, no matter which window or application has focus, adapted from [this insightful page](http://rants.sayanriju.co.cc/script-to-make-tick-tick-sound-on-keypress)
```
#!/usr/bin/env python
from Xlib.display import Display
import os
import sys
Z... | Use events:
```
import Xlib
from Xlib.display import Display
display = Display()
screen = display.screen()
w = screen.root.create_window(0, 0, 100, 100, 1,
screen.root_depth,
event_mask = Xlib.X.KeyPressMask)
w.map()
while True:
event = display.next_event()
if event.type != Xlib.... |
How to fix this script so that it won't peg the CPU? | 11,990,503 | 6 | 2012-08-16T15:22:41Z | 11,990,679 | 8 | 2012-08-16T15:32:33Z | [
"python",
"performance",
"keyboard",
"cpu",
"xlib"
] | On my home Kubuntu machine, I am running a script to beep on every keypress, no matter which window or application has focus, adapted from [this insightful page](http://rants.sayanriju.co.cc/script-to-make-tick-tick-sound-on-keypress)
```
#!/usr/bin/env python
from Xlib.display import Display
import os
import sys
Z... | Your while loop is consuming all your CPU's cycles since it's executing as fast as possible. You could add a small sleep() delay, but you risk missing out on some key events. Alternatively, consider using the [pyhook](http://sourceforge.net/apps/mediawiki/pyhook/index.php?title=Main_Page) module to monitor key presses. |
Python: how to make global imports from a function | 11,990,556 | 22 | 2012-08-16T15:26:02Z | 11,990,800 | 29 | 2012-08-16T15:39:09Z | [
"python",
"import",
"module",
"python-module"
] | I fear that this is a messy way to approach the problem but...
let's say that I want to make some imports in Python based on some conditions.
For this reason I want to write a function:
```
def conditional_import_modules(test):
if test == 'foo':
import onemodule, anothermodule
elif test == 'bar':
... | Imported modules are just variables - names bound to some values. So all you need is to import them and make them global with `global` keyword.
Example:
```
>>> math
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined
>>> def f():
... global math
... ... |
Django: Display NullBooleanField as Radio and default to None | 11,990,852 | 3 | 2012-08-16T15:42:27Z | 18,249,230 | 7 | 2013-08-15T08:47:51Z | [
"python",
"django",
"forms",
"form-fields"
] | I am successfully implementing `NullBooleanField` as radio buttons in several ways but the problem is that I can not set the default value to None.
Here is the code:
```
models.py:
class ClinicalData(models.Model):
approved = models.NullBooleanField()
...
forms.py:
NA_YES_NO = ((None, 'N/A'), (True,... | I know this has been answered for a while now, but I was also trying to solve this problem and came across this question.
After trying emyller's solution, it seemed to work, however when I looked at the form's `self.cleaned_data`, I saw that the values I got back were all either `True` or `None`, no `False` values wer... |
Selecting a subset of a Pandas DataFrame indexed by DatetimeIndex with a list of TimeStamps | 11,991,627 | 10 | 2012-08-16T16:27:44Z | 11,994,944 | 12 | 2012-08-16T20:26:37Z | [
"python",
"time-series",
"pandas"
] | I have a large Pandas `DataFrame`
```
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 3425100 entries, 2011-12-01 00:00:00 to 2011-12-31 23:59:59
Data columns:
sig_qual 3425100 non-null values
heave 3425100 non-null values
north 3425099 non-null values
west 3425097 non-null values
dtypes... | df.ix[my\_list\_of\_dates] should work just fine.
```
In [193]: df
Out[193]:
A B C D
2012-08-16 2 1 1 7
2012-08-17 6 4 8 6
2012-08-18 8 3 1 1
2012-08-19 7 2 8 9
2012-08-20 6 7 5 8
2012-08-21 1 3 3 3
2012-08-22 8 2 3 8
2012-08-23 7 1 7 4
2012-08-24 2 6 0 6
2012-08-25 ... |
How to fix: W602 deprecated form of raising exception | 11,991,637 | 19 | 2012-08-16T16:29:03Z | 11,991,638 | 22 | 2012-08-16T16:29:03Z | [
"python",
"pylint",
"pep8"
] | If I use pylint (via sublimerlinter) I get following warning message:
`W602 deprecated form of raising exception`
This I how I use exceptions in my code:
```
if CONDITION == True:
raise ValueError, HELPING_EXPLANATION
``` | **Raise your exception like that:**
```
if CONDITION == True:
raise ValueError(HELPING_EXPLANATION)
```
**From [PEP 8 -- Style Guide for Python Code - Programming Recommendations](http://www.python.org/dev/peps/pep-0008/#id39):**
> When raising an exception, use raise `ValueError('message')` instead of the older... |
Python hangs over ssh | 11,992,204 | 3 | 2012-08-16T17:10:05Z | 11,992,595 | 7 | 2012-08-16T17:37:25Z | [
"python",
"linux",
"ssh",
"hang"
] | I'm trying to a run a python script directly over ssh like this:
```
ssh hostname python_script
```
Unfortunately nothing happens after python starts, and in fact the python process that is created remotely stays "alive" even after I disconnect from SSH. The same thing happens if I try to start the python interpreter... | Try `ssh -t hostname python_script`. By default, `ssh` doesn't allocate a pseudo-tty to interact with when it's given a program to run (although it does if you just do `ssh hostname`); `-t` tells it to do so. |
ID of a Python thread as reported by top | 11,992,275 | 6 | 2012-08-16T17:14:55Z | 11,993,054 | 10 | 2012-08-16T18:12:27Z | [
"python",
"linux",
"multithreading",
"ctypes"
] | I am starting a bunch of different threads in my Python script. I want to keep track of the memory and CPU usage of each of these threads. I use `top` and `ps -eLf` for that.
But it turns out that the identifier returned by `thread.start_new_thread()` is different from the thread PID displayed by `top` and other simil... | Thanks to this [post](http://python.6.n6.nabble.com/Get-thread-pid-td1536295.html), I got the Python threads to report their respective thread IDs. First do a `grep -r 'SYS_gettid' /usr/include/'`. I got a line: `#define SYS_gettid __NR_gettid` Upon further grepping by `grep -r '__NR_gettid' /usr/include/`, I got a bun... |
Pragmas in python | 11,992,448 | 17 | 2012-08-16T17:27:06Z | 11,992,491 | 10 | 2012-08-16T17:30:24Z | [
"python",
"pragma"
] | I'm reading bottle.py source code. It's a web framework, with only 3000+ lines python code. So cool.
I found some code like this:
```
class ServerAdapter(object):
quiet = False
def __init__(self, host='127.0.0.1', port=8080, **config):
self.options = config
self.host = host
self.port =... | For Python, it's simply a comment. It might be an annotation targeted at some external tool, which reads and analyzes Python code, similar, for example, to doctest's `#doctest: +ELLIPSIS` annotations or PyLint's `# pylint: disable=W0613` style annotations. |
Pragmas in python | 11,992,448 | 17 | 2012-08-16T17:27:06Z | 11,992,947 | 32 | 2012-08-16T18:04:45Z | [
"python",
"pragma"
] | I'm reading bottle.py source code. It's a web framework, with only 3000+ lines python code. So cool.
I found some code like this:
```
class ServerAdapter(object):
quiet = False
def __init__(self, host='127.0.0.1', port=8080, **config):
self.options = config
self.host = host
self.port =... | It is apparenly related to the [coverage.py](http://nedbatchelder.com/code/coverage/):
> Coverage.py is a tool for measuring code coverage of Python programs. It monitors your program, noting which parts of the code have been executed, then analyzes the source to identify code that could have been executed but was not... |
What would prevent filter from returning 0? | 11,993,112 | 3 | 2012-08-16T18:17:59Z | 11,993,195 | 10 | 2012-08-16T18:23:41Z | [
"python",
"filter",
"boolean"
] | When I try to filter `[1,2,0,3,8]` with `if x < 3: return x` I end up with `[1,2]`. Why is the `0` not included in this list?
```
def TestFilter(x):
if x < 3:
return x
a = [1,2,0,3,8]
b = filter(TestFilter, a)
print b
``` | Every time your function returns `True` [filter()](http://docs.python.org/library/functions.html#filter) will add the current element from the original list to the new list. Python considers `0` to be `False` and any other number to be `True`. Therefore you will want to have the function return `True` instead of the nu... |
Ignore case in string comparison | 11,993,206 | 6 | 2012-08-16T18:24:06Z | 11,993,250 | 12 | 2012-08-16T18:28:15Z | [
"python",
"equals"
] | If I have two variables, a and b and they could be integers, float, or strings.
I want to return `True` if they are equal (in case of string, ignore case).
As Pythonic as possible. | This is the most pythonic I can think of. Better to ask for foregiveness than for permission:
```
>>> def iequal(a, b):
... try:
... return a.upper() == b.upper()
... except AttributeError:
... return a == b
...
>>>
>>> iequal(2, 2)
True
>>> iequal(4, 2)
False
>>> iequal("joe", "Joe")
True
>>> iequ... |
Python: why does my list change when I'm not actually changing it? | 11,993,878 | 4 | 2012-08-16T19:10:11Z | 11,993,900 | 14 | 2012-08-16T19:11:35Z | [
"python",
"list"
] | Newbie with a question, so please be gentle:
```
list = [1, 2, 3, 4, 5]
list2 = list
def fxn(list,list2):
for number in list:
print(number)
print(list)
list2.remove(number)
print("after remove list is ", list, " and list 2 is ", list2)
return list, list2
list, list2 = fxn(li... | The reason this is happening can be found here:
```
mlist = [1,2,3,4,5]
mlist2 = mlist
```
the second statement "points" `mlist2` to `mlist` (i.e., they both refer to the *same* list object) and any changes you make to one is reflected in the other.
To make a copy instead try this (using a slice operation):
```
mli... |
How to divide flask app into multiple py files? | 11,994,325 | 43 | 2012-08-16T19:43:25Z | 11,994,728 | 46 | 2012-08-16T20:09:37Z | [
"python",
"flask"
] | My flask application currently consists of a single `test.py` file with multiple routes and the `main()` route defined. Is there some way I could create a `test2.py` file that contains routes that were not handled in `test.py`?
```
@app.route('/somepath')
def somehandler():
# Handler code here
```
I am concerned ... | You can use the usual Python package structure to divide your App into multiple modules, [see the Flask docs.](http://flask.pocoo.org/docs/patterns/packages/)
However,
> Flask uses a concept of blueprints for making application components and supporting common patterns within an application or across applications.
Y... |
How to divide flask app into multiple py files? | 11,994,325 | 43 | 2012-08-16T19:43:25Z | 11,995,246 | 10 | 2012-08-16T20:52:33Z | [
"python",
"flask"
] | My flask application currently consists of a single `test.py` file with multiple routes and the `main()` route defined. Is there some way I could create a `test2.py` file that contains routes that were not handled in `test.py`?
```
@app.route('/somepath')
def somehandler():
# Handler code here
```
I am concerned ... | I would like to recommend [flask-empty](https://github.com/italomaia/flask-empty/) at GitHub.
It provides an easy way to understand [Blueprints](http://flask.pocoo.org/docs/blueprints/), multiple views and [extensions](http://flask.pocoo.org/docs/extensiondev/). |
pandas DataFrame.to_string() truncating strings from columns | 11,994,765 | 7 | 2012-08-16T20:11:51Z | 12,001,086 | 10 | 2012-08-17T06:54:29Z | [
"python",
"pandas"
] | When I try to use to\_string to output a column from a dataframe, it truncates the output of the column.
```
print gtf_df.ix[:1][['transcript_id','attributes']].to_string(header=False,index=False)
Out: ' CUFF.1.1 gene_id "CUFF.1"; transcript_id "CUFF.1.1"; FPKM '
print gtf_df.ix[:1]['attributes'][0]
Out: 'gene_id ... | Using `__repr__` or `to_string` columns are by default truncated at 50 chars. In versions of Pandas older than 0.13.1, this can be controlled using `pandas.set_printoptions()`:
```
In [64]: df
Out[64]:
A B
a this is a very long string, longer than the defau bar
b... |
Is there a way to get a schema of a database from within python? | 11,996,394 | 8 | 2012-08-16T22:33:27Z | 11,996,423 | 10 | 2012-08-16T22:37:15Z | [
"python",
"sqlite",
"database-schema"
] | I'm trying to find out a way to find the names of tables in a database(if any exist). I find that from a sqlite cli I can use:
```
>.tables
```
Then for the fields:
```
>PRAGMA TABLE_INFO(table_name)
```
This obviously doesn't work within python. Is there even a way to do this with python or should I just be using ... | You should be able access the table names from the `sqlite_master` table.
```
SELECT name FROM sqlite_master WHERE type='table';
```
The names of the columns are not directly accessible. The easiest way to get them is to query the table and get the column names from the query result.
```
SELECT * FROM table_name LIM... |
Is there a way to get a schema of a database from within python? | 11,996,394 | 8 | 2012-08-16T22:33:27Z | 11,996,548 | 15 | 2012-08-16T22:51:01Z | [
"python",
"sqlite",
"database-schema"
] | I'm trying to find out a way to find the names of tables in a database(if any exist). I find that from a sqlite cli I can use:
```
>.tables
```
Then for the fields:
```
>PRAGMA TABLE_INFO(table_name)
```
This obviously doesn't work within python. Is there even a way to do this with python or should I just be using ... | From the [sqlite FAQ](https://www.sqlite.org/faq.html#q7):
> From within a C/C++ program (or a script using Tcl/Ruby/Perl/Python bindings) you can get access to table and index names by doing a `SELECT` on a special table named "SQLITE\_MASTER". Every SQLite database has an `SQLITE_MASTER` table that defines the schem... |
Multiprocessing in Python while limiting the number of running processes | 11,996,632 | 13 | 2012-08-16T22:59:53Z | 11,998,520 | 18 | 2012-08-17T01:02:10Z | [
"python",
"multithreading",
"multiprocessing"
] | I'd like to run multiple instances of program.py simultaneously, while limiting the number of instances running at the same time (e.g. to the number of CPU cores available on my system). For example, if I have 10 cores and have to do 1000 runs of program.py in total, only 10 instances will be created and running at any... | I know you mentioned that the Pool.map approach doesn't make much sense to you. The map is just an easy way to give it a source of work, and a callable to apply to each of the items. The `func` for the map could be any entry point to do the actual work on the given arg.
If that doesn't seem right for you, I have a pre... |
How to automatically capitalize field on form submission in Django? | 11,996,963 | 2 | 2012-08-16T23:40:05Z | 12,001,244 | 9 | 2012-08-17T07:05:36Z | [
"python",
"django",
"sorting",
"django-models",
"django-forms"
] | I have a `ProductForm` where users can add a `Product` to the database with information like `title`, `price`, and `condition`.
How do I make it so that when the user submits the form, the first letter of the `title` field is automatically capitalized?
For example, if a user types "excellent mattress" in the form, dj... | Forms have a built-in hook for cleaning specific fields ([docs](https://docs.djangoproject.com/en/1.4/ref/forms/validation/#cleaning-a-specific-field-attribute)), which would be a cleaner (pun intended) location for this code:
```
class ProductForm(forms.Form):
...
def clean_title(self):
return self.cl... |
SWIG Python Structure Array | 11,998,369 | 7 | 2012-08-17T00:40:11Z | 12,003,647 | 8 | 2012-08-17T10:00:13Z | [
"python",
"c",
"swig"
] | I've been searching for a few days trying to figure out how to turn an array of structures into a Python list. I have a function that returns a pointer to the beginning of the array.
```
struct foo {
int member;
};
struct foo *bar() {
struct foo *t = malloc(sizeof(struct foo) * 4);
... do stuff with the s... | The idea you tried with `[ANY]` won't work for several reasons. Primarily though `ANY` can be used in typemaps to allow the same typemap to work with varying fixed size arrays, which isn't what you've got there.
The syntax for C isn't quire right there either. You can't write:
```
int[4] bar() {
static int data[4];... |
regular expression \Z(?ms) | 11,998,613 | 4 | 2012-08-17T01:18:10Z | 11,998,653 | 11 | 2012-08-17T01:24:48Z | [
"python",
"regex"
] | What does `\Z(?ms)` mean in a regular expression?
`\Z` is end-of-string, but what is the `(?ms)` part?
This is added by `fnmatch.translate("abc")` to the returned regular expression. | From [the docs](http://docs.python.org/library/re.html):
> (?iLmsux)
>
> (One or more letters from the set 'i', 'L', 'm', 's', 'u', 'x'.) The group matches the empty string; the letters set the corresponding flags: re.I (ignore case), re.L (locale dependent), re.M (multi-line), re.S (dot matches all), re.U (Unicode de... |
python adding number to string | 11,999,228 | 2 | 2012-08-17T03:02:40Z | 11,999,258 | 7 | 2012-08-17T03:06:56Z | [
"python"
] | Trying to add a count int to the end of a string *(website url)*:
Code:
```
count = 0
while count < 20:
Url = "http://www.ihiphopmusic.com/music/page/"
Url = (Url) + (count)
#Url = Url.append(count)
print Url
```
I want:
```
http://www.ihiphopmusic.com/music/page/2
http://www.ihiphopmusic.com/m... | The problem is exactly what the traceback states.
Python doesn't know what to do with `"hello" + 12345`
You'll have to convert the integer `count` into a string first.
Additionally, you never increment the `count` variable, so your while loop will go on forever.
Try something like this:
```
count = 0
url = "http://... |
Python argparse: metavar and action=store_true together | 11,999,416 | 6 | 2012-08-17T03:32:49Z | 11,999,588 | 12 | 2012-08-17T04:01:48Z | [
"python",
"argparse"
] | I'm using argparse module in Python to parse parameters typed in a command line interface. I have the following add\_argument call to a subparser object:
```
submit_parser.add_argument('-pv','--provision',metavar='PROVISION', dest='PROVISION',
help='provision system',
... | A metavar only makes sense for positional arguments (think filenames at the end of the command line) or for when an argument takes arguments of its own (like `--input-files foo.txt bar.txt`).
Your `--provision` argument is a flag because you set the `action` to `store_true`. It doesn't take any arguments (i.e., `nargs... |
Does Eclipse have indentation guides? | 12,000,219 | 8 | 2012-08-17T05:25:01Z | 21,578,200 | 9 | 2014-02-05T13:07:42Z | [
"python",
"eclipse-plugin",
"pydev"
] | Recently, I use Eclipse to edit my python code. But lacking indentation guides, I feel not very well. So how to add the auto indentation guides for Eclipse? Is there certain plugin?
What's more, I have tried the EditBox. But, you know, that is not very natural under some themes............... | There is a plugin that does the job nicely called **Indent Guide**
The update site is <http://sschaef.github.io/IndentGuide/> |
How use python on ipad? | 12,002,051 | 10 | 2012-08-17T08:06:56Z | 12,002,165 | 13 | 2012-08-17T08:15:19Z | [
"python",
"ipad"
] | Recently, I've found that the ipad can run python with a special python interpret. But editing the code on ipad is a terrible nightmare. So how can I push the python code which has been edited completely on PC into the ipad and run it? | you may be interesting in <https://www.pythonanywhere.com> project.
I am using it on ipad too. |
Celery task schedule (Ensuring a task is only executed one at a time) | 12,003,221 | 14 | 2012-08-17T09:30:16Z | 12,003,293 | 19 | 2012-08-17T09:34:56Z | [
"python",
"django",
"celery"
] | I have a task, somewhat like this:
```
@task()
def async_work(info):
...
```
At any moment, I may call async\_work with some info. For some reason, I need is ensure that only one async\_work is running at a time, other calling request must wait for.
So I come up with the following code:
```
is_locked = False ... | It is invalid to access local variables since you can have several celery workers running tasks. And those workers might even be on different hosts. So, basically, there is as many `is_locked` variable instances as many Celery workers are running
your `async_work` task. Thus, even though your code won't raise any error... |
Threadsafe and fault-tolerant file writes | 12,003,805 | 7 | 2012-08-17T10:09:55Z | 12,007,885 | 9 | 2012-08-17T14:40:14Z | [
"python",
"file",
"thread-safety"
] | I have a long-running process which writes a lot of stuff in a file. The result should be everything or nothing, so I'm writing to a temporary file and rename it to the real name at the end. Currently, my code is like this:
```
filename = 'whatever'
tmpname = 'whatever' + str(time.time())
with open(tmpname, 'wb') as ... | You can use Python's `tempfile` module to give you a temporary file name. It can create a temporary file in a thread safe manner rather than making one up using `time.time()` which may return the same name if used in multiple threads at the same time.
As suggested in a comment to your question, this can be coupled wit... |
How do I add sheet name for each datasheet in an XLS file generated from "tablib"? | 12,004,536 | 6 | 2012-08-17T11:01:50Z | 12,004,841 | 12 | 2012-08-17T11:23:39Z | [
"python"
] | I want to convert some data in my database to XLS (Excel) format. I used `tablib` to do this and can get the Excel sheets in the proper format.
How do I specify names for individual sheets in my Excel file? | When exporting to Excel, the sheets have names from the `Dataset.title` property ([source code](https://github.com/kennethreitz/tablib/blob/develop/tablib/formats/_xls.py#L53)).
You can set the title in the `Dataset` constructor:
```
dataset = Dataset(title="Sheet name")
``` |
Python - find digits in a string | 12,005,558 | 5 | 2012-08-17T12:12:10Z | 12,005,674 | 12 | 2012-08-17T12:19:00Z | [
"python"
] | ```
def get_digits(str1):
c = ""
for i in str1:
if i.isdigit():
c += i
return c
```
Above is the code that I used and the problem is that it only returns only the first digit of strings. For this, I have to keep both for loop and return statement. Anyone knows how to fix?
Than... | As the others said, you have a semantic problem on your indentation, but you don't have to write such function to do that, a more pythonic way to do that is:
```
def get_digits(text):
return filter(str.isdigit, text)
```
On the interpreter:
```
>>> filter(str.isdigit, "lol123")
'123'
```
## Some advice
Always ... |
Can't assign to operator | 12,006,018 | 3 | 2012-08-17T12:39:58Z | 12,006,065 | 9 | 2012-08-17T12:42:50Z | [
"python",
"python-2.7",
"variable-assignment"
] | ```
i = 0
num = 0
while i <= 1000:
if i % 3 and i % 5 == 0:
num + i = num <--- Adding Up Numbers Divisable by 3 & 5...
i += 1
print num
```
Error:*\** can't assign to operator (line 5) | Are you sure you don't want:
```
num = num + i
```
or equivalently:
```
num += i
```
?
Note that this can be done a little easier using `sum`, `range` and a generator expression:
```
sum( x for x in range(0,1000,5) if x % 3 == 0 )
#^only take every 5th element (0, 5, 10, 15 ...)
... |
How do Django models work? | 12,006,267 | 15 | 2012-08-17T12:54:48Z | 12,006,688 | 14 | 2012-08-17T13:24:01Z | [
"python",
"django",
"django-models"
] | So I can create Django model like this:
```
from django.db import models
class Something(models.Model):
title = models.TextField(max_length=200)
```
and I can work with it like this:
```
thing = Something()
#set title
thing.title = "First thing"
#get title
thing.title
```
All works as it should but I'd like to... | I think its hard to beat what Django documentation has to [say on this](https://code.djangoproject.com/wiki/DevModelCreation).
> The Model class (see base.py) has a **metaclass** attribute that defines ModelBase (also in base.py) as the class to use for creating new classes. So ModelBase.**new** is called to create th... |
Python nosetests skip certain Tests | 12,006,400 | 10 | 2012-08-17T13:04:10Z | 12,671,360 | 10 | 2012-10-01T10:14:25Z | [
"python",
"pylons",
"nosetests"
] | I am working on tests for a web application written in python.
Suppose I have 5 tests in my test\_login.py module.
Every single test is a Class.
There is often one, base test that extends TestFlow class, which is our predefined test class.
And then other tests in this module extend that base test.
For instance :
... | Form nosetests it can be done as below by specifying the attributes
<http://nose.readthedocs.org/en/latest/plugins/attrib.html>
> Oftentimes when testing you will want to select tests based on criteria rather than simply by filename. For example, you might want to run all tests except for the slow ones. You can do thi... |
Python: Pandas Divide DataFrame by first row | 12,007,406 | 4 | 2012-08-17T14:08:18Z | 12,007,574 | 10 | 2012-08-17T14:20:05Z | [
"python",
"pandas"
] | I am absolutely new to Python and Panda and even though I have checked the documentation, I don't seem to understand the right way to index a Pandas DataFrame. I would like to divide a DataFrame full of stock prices by their respective initial values in order to index the different stocks to 100. I want to use this to ... | ```
In [193]: df
Out[193]:
A B C D
a 1 8 9 1
b 5 4 3 6
c 4 6 1 3
d 1 0 2 9
In [194]: df.divide(df.ix[0] / 100)
Out[194]:
A B C D
a 100 100 100.000000 100
b 500 50 33.333333 600
c 400 75 11.111111 300
d 100 0 22.222222 900
``` |
Join a list of strings in python and wrap each string in quotation marks | 12,007,686 | 30 | 2012-08-17T14:26:54Z | 12,007,707 | 50 | 2012-08-17T14:28:10Z | [
"python",
"string",
"list",
"join"
] | I've got:
```
words = ['hello', 'world', 'you', 'look', 'nice']
```
I want to have:
```
'"hello", "world", "you", "look", "nice"'
```
What's the easiest way to do this with Python? | ```
>>> words = ['hello', 'world', 'you', 'look', 'nice']
>>> ', '.join('"{0}"'.format(w) for w in words)
'"hello", "world", "you", "look", "nice"'
``` |
Join a list of strings in python and wrap each string in quotation marks | 12,007,686 | 30 | 2012-08-17T14:26:54Z | 12,008,055 | 28 | 2012-08-17T14:50:13Z | [
"python",
"string",
"list",
"join"
] | I've got:
```
words = ['hello', 'world', 'you', 'look', 'nice']
```
I want to have:
```
'"hello", "world", "you", "look", "nice"'
```
What's the easiest way to do this with Python? | you may also perform a single `format` call
```
>>> words = ['hello', 'world', 'you', 'look', 'nice']
>>> '"{0}"'.format('", "'.join(words))
'"hello", "world", "you", "look", "nice"'
```
Edit : Some benchmarking (performed on a 2009 mbp):
```
>>> timeit.Timer("""words = ['hello', 'world', 'you', 'look', 'nice'] * 10... |
argparse: setting optional argument with value of mandatory argument | 12,007,704 | 8 | 2012-08-17T14:27:33Z | 12,007,789 | 8 | 2012-08-17T14:34:04Z | [
"python",
"default-value",
"argparse"
] | With Python's [argparse](http://docs.python.org/dev/library/argparse.html), I would like to add an optional argument that, if not given, gets the value of another (mandatory) argument.
```
parser.add_argument('filename',
metavar = 'FILE',
type = str,
help ... | As far as I know, there is no way to do this that is more clean than:
```
ns = parser.parse_args()
ns.extra_file = ns.extra_file if ns.extra_file else ns.filename
```
(just like you propose in your question).
You *could* probably do some [custom action gymnastics similar to this](http://stackoverflow.com/a/11455440/... |
How should I name my classes and function and even strings? | 12,007,811 | 8 | 2012-08-17T14:35:46Z | 12,007,830 | 14 | 2012-08-17T14:37:05Z | [
"python"
] | I am new to Python as you might tell. I have read various documents but I still can not figure out if there's a `"naming best practices"` for **strings functions and of course, classes**.
If I want to name a class or a function as a SiteMap, is it ok to use SiteMap? Should it be Site\_map or any other thing, for examp... | [PEP8](http://www.python.org/dev/peps/pep-0008/) specifies recommended naming convention for Python. Among rules discussed there, it mentions `underscore_names` for functions and variables (regardless of their type), and `CamelCase` for classes. |
How should I name my classes and function and even strings? | 12,007,811 | 8 | 2012-08-17T14:35:46Z | 12,007,958 | 11 | 2012-08-17T14:44:58Z | [
"python"
] | I am new to Python as you might tell. I have read various documents but I still can not figure out if there's a `"naming best practices"` for **strings functions and of course, classes**.
If I want to name a class or a function as a SiteMap, is it ok to use SiteMap? Should it be Site\_map or any other thing, for examp... | **Naming Conventions:**
There are various Python naming conventions I use. Consistency here is certainly good as it helps to identify what sort of object names point to. I think the conventions I use basically follow [PEP8](http://www.python.org/dev/peps/pep-0008/).
**1)** Module names should be lowercase with unders... |
Better ways to get nth element from an unsubscriptable iterable | 12,007,820 | 15 | 2012-08-17T14:36:32Z | 12,007,859 | 21 | 2012-08-17T14:38:48Z | [
"python",
"iterator"
] | Sometimes an iterable might be not subscriptable. Say the return from `itertools.permutations`:
```
ps = permutations(range(10), 10)
print ps[1000]
```
Python will complain that `'itertools.permutations' object is not subscriptable`
Of course one can perform `next()` by `n` times to get the nth element. Just wonderi... | Just use `nth` recipe from [`itertools`](http://docs.python.org/library/itertools.html#recipes)
```
>>> from itertools import permutations, islice
>>> def nth(iterable, n, default=None):
"Returns the nth item or a default value"
return next(islice(iterable, n, None), default)
>>> print nth(permutation... |
Create a halo around text in Python using PIL? | 12,008,493 | 4 | 2012-08-17T15:15:42Z | 12,010,040 | 7 | 2012-08-17T17:02:56Z | [
"python",
"text",
"python-imaging-library"
] | I'm watermarking some pictures using PIL and I'm having a hard time reading some of the text (black text on dark background). I can't just change text color since I've got a wide array of background colors. Is there any way to add a halo effect around the text?
For example:
<http://i.imgur.com/WYxSU.jpg>
The bottom te... | If you don't care about speed too much, you can do it using composition:
1. draw text with halo color on a blank `RGBA` image
2. blur it
3. draw it again with text color
4. invert this image to get composition mask
5. "merge" with original image
For example:
```
import sys
import Image, ImageChops, ImageDraw, ImageF... |
Adding widgets to qtablewidget pyqt | 12,009,134 | 5 | 2012-08-17T15:56:59Z | 12,010,007 | 9 | 2012-08-17T17:00:48Z | [
"python",
"pyqt",
"qtablewidget"
] | Is there anyway to add like a button in qtablewidget? But the date within the cell would stil have to be displaying, for example if an user double clicked a cell, could i send a signal like a button? Thanks!
edititem():
```
def editItem(self,clicked):
if clicked.row() == 0:
#go to tab1
if clicked.row(... | You have a couple of questions rolled into one...short answer, yes, you can add a button to a QTableWidget - you can add any widget to the table widget by calling setCellWidget:
```
# initialize a table somehow
table = QTableWidget(parent)
table.setRowCount(1)
table.setColumnCount(1)
# create an cell widget
btn = QPu... |
Testing failure of an assignment with unittest | 12,009,587 | 8 | 2012-08-17T16:27:13Z | 12,009,957 | 10 | 2012-08-17T16:56:57Z | [
"python",
"unit-testing",
"properties",
"variable-assignment",
"assertraises"
] | One of my attributes is a property where the setter calls a validation function that raises an exception if the new value is invalid:
```
pos.offset = 0
# @offset.setter calls validate(offset=0)
# PositionError: Offset may not be 0.
```
I'm trying to add a test to ensure that this fails. However, I can't figure out h... | When you want to use `unittest` to test that an exception occurs in a block of code rather than just a function call, you can use `assertRaises` as a context manager:
```
with self.assertRaises(PositionError):
pos.offset = 0
```
This use can be found in the [unittest docs](http://docs.python.org/dev/library/unitt... |
How to loop over a circular list, while peeking ahead and behind current element? | 12,010,820 | 4 | 2012-08-17T17:56:33Z | 12,010,872 | 7 | 2012-08-17T17:59:06Z | [
"python"
] | With the following example list: `L = ['a','b','c','d']`
I'd like to achieve the following output:
```
>>> a d b
>>> b a c
>>> c b d
>>> d c a
```
Pseudo-code would be:
```
for e in L:
print(e, letter_before_e, letter_after_e
``` | You could just loop over `L` and take the index `i` minus and plus 1 modulo `len(L)` to get the previous and next element. |
Trying to implement python TestSuite | 12,011,091 | 14 | 2012-08-17T18:15:36Z | 12,011,486 | 25 | 2012-08-17T18:46:59Z | [
"python",
"unit-testing",
"regression-testing",
"test-suite",
"pyunit"
] | I have two test cases (two different files) that I want to run together in a Test Suite. I can get the tests to run just by running python "normally" but when I select to run a python-unit test it says 0 tests run. Right now I'm just trying to get at least one test to run correectly.
```
import usertest
import configt... | you want to use a testsuit. So you need not call unittest.main().
Use of testsuit should be like this..
```
#import usertest
#import configtest # first test
import unittest # second test
class ConfigTestCase(unittest.TestCase):
def setUp(self):
print 'stp'
##set up code
def runTest(self):
... |
Force YAML values to be strings | 12,012,774 | 4 | 2012-08-17T20:30:29Z | 12,013,083 | 7 | 2012-08-17T20:57:00Z | [
"python",
"yaml"
] | Look at this code, under Python 2.7:
```
>>> import yaml
>>> yaml.load('string: 01')
{'string': 1}
>>> :(
```
Is it possible to obtain the string `01` without modifying the yaml file? I didn't find anything in the docs. | Try:
```
>> import yaml
>> yaml.load('string: 01', Loader=yaml.loader.BaseLoader)
{u'string': u'01'}
``` |
Django post save signal getting called twice despite uid | 12,012,887 | 5 | 2012-08-17T20:41:21Z | 12,013,253 | 7 | 2012-08-17T21:12:45Z | [
"python",
"mysql",
"django",
"signals"
] | I have registered my signal with the callback using the `@receiver` decorator
```
@receiver(post_save, sender=User, dispatch_uid='ARandomUniqueString')
def do_callback(sender, **kwargs):
```
I have put the `from app.signals import *` code in `__init__.py` and I can see that it gets imported twice and I do not think ... | Ok so I moved the import to `views.py` (or `models.py` and while it was getting imported only once, it was getting called twice.
The problem was that the `post_save` signal was getting called when the object was created as well as saved. I have no idea why so I added a workaround which now works
```
created = False
... |
Most efficient way to generate "ordered subsets" of a sequence | 12,013,035 | 5 | 2012-08-17T20:53:31Z | 12,013,088 | 11 | 2012-08-17T20:57:14Z | [
"python"
] | I need to generate all "ordered subsets" (apologies if I'm not using correct mathematical terminology) of a sequence in Python, with omitted elements replaced with `None`.Given `[1, 2]`, I want `[(1, 2), (1, None), (None, 2), (None, None)]`. Each "ordered subset" should have the property that at each position, it is ei... | ```
from itertools import product, repeat
given = [1, 2]
with_nones = zip(given, repeat(None))
print(list(product(*with_nones)))
``` |
Celery creating a new connection for each task | 12,013,220 | 17 | 2012-08-17T21:09:13Z | 28,123,297 | 7 | 2015-01-24T07:23:01Z | [
"python",
"django",
"heroku",
"redis",
"celery"
] | I'm using Celery with Redis to run some background tasks, but each time a task is called, it creates a new connection to Redis. I'm on Heroku and my Redis to Go plan allows for 10 connections. I'm quickly hitting that limit and getting a "max number of clients reached" error.
How can I ensure that Celery queues the ta... | I wish I was using Redis, because there is a specific option to limit the number of connections: `CELERY_REDIS_MAX_CONNECTIONS`.
* <http://docs.celeryproject.org/en/3.0/configuration.html#celery-redis-max-connections> (for 3.0)
* <http://docs.celeryproject.org/en/latest/configuration.html#celery-redis-max-connections>... |
Python tkinter app adding a right click context menu? | 12,014,210 | 11 | 2012-08-17T23:04:16Z | 12,014,379 | 17 | 2012-08-17T23:29:34Z | [
"python",
"user-interface",
"tkinter",
"contextmenu"
] | I have a python-tkinter gui app that I've been trying to find some way to add in some functionality. I was hoping there would be a way to right-click on an item in the app's listbox area and bring up a context menu. Is tkinter able to accomplish this? Would I be better off looking into gtk or some other gui-toolkit? | Here is an example from [effbot](http://effbot.org/tkinterbook/menu.htm) that uses the Menu widget to create a "popup menu":
```
from Tkinter import * # Tkinter -> tkinter in Python 3
root = Tk()
def hello():
print "hello!"
# create a popup menu
menu = Menu(root, tearoff=0)
menu.add_command(label="Undo", comman... |
Iterating over related objects in Django: loop over query set or use one-liner select_related (or prefetch_related) | 12,014,704 | 9 | 2012-08-18T00:18:56Z | 12,014,898 | 34 | 2012-08-18T00:53:01Z | [
"python",
"django",
"orm"
] | I have a newsletter application where a newsletter has multiple articles within each issue. I want to display a summary page online that lists the newsletter year, volume and label, and then in an unordered list display all the articles in the issue. I am quite new to Django so I am trying to determine the best way to ... | The approach you are doing now will be **heavily** inefficient, because it will result in an 1+N number of queries. That is, 1 for the query of all your Newsletters, and then 1 for every single time you evaluate those `n.article_set.all()` results. So if you have 100 Newletter objects in that first query, you will be d... |
Python Regular Expression: why does this not work? | 12,014,991 | 2 | 2012-08-18T01:11:04Z | 12,015,123 | 8 | 2012-08-18T01:39:03Z | [
"python",
"regex",
"substitution"
] | This does not give me an error nor an answer.
```
re.sub('\\.(\\W|\\.)*[o0](\\W|[o0])*', '*', '..........................................')
```
Why does it behave like so? Also, if I reduce the amount of 'periods', then it works.
Thank you. | You've got [catastrophic backtracking](http://www.regular-expressions.info/catastrophic.html). |
Why can print("string", object) give different results than print(object)? | 12,015,163 | 5 | 2012-08-18T01:49:53Z | 12,015,177 | 12 | 2012-08-18T01:52:03Z | [
"python"
] | I have defined this class:
```
class Point():
def __init__(self,x,y):
self.x = x
self.y = y
def __str__(self):
return "Point x: {0}, Point y: {1}".format(self.x, self.y)
```
What is the difference between the 2 cases `print("Point",p1)` and `print(p1)`:
```
p1 = Point(1,2)
print("Poin... | The former is printing a tuple containing `"Point"` and `p1`; in this case `__repr__()` will be used to generate the string for output instead of `__str__()`. |
Python 3 vs Python 2 map behavior | 12,015,521 | 8 | 2012-08-18T03:13:10Z | 12,015,545 | 11 | 2012-08-18T03:17:58Z | [
"python",
"python-3.x",
"map-function"
] | In Python 2, a common (old, legacy) idiom is to use `map` to join iterators of uneven length using the form `map(None,iter,iter,...)` like so:
```
>>> map(None,xrange(5),xrange(10,12))
[(0, 10), (1, 11), (2, None), (3, None), (4, None)]
```
In Python 2, it is extended so that the *longest* iterator is the length of t... | [`itertools.zip_longest`](http://docs.python.org/py3k/library/itertools.html#itertools.zip_longest) does what you want, with a more comprehensible name. :) |
Add null character to string in python | 12,016,005 | 3 | 2012-08-18T05:05:36Z | 12,016,031 | 16 | 2012-08-18T05:08:19Z | [
"python"
] | I have list as:
```
['t','e','s','t','s','t','r','i','n','g']
```
How to add null character after each string `t`, `e`, `s`, `t`, `s`, `t`, `r`, `i`, `n`, `g`? | List comprehension.
```
[c + '\0' for c in S]
```
But it smells like you want UTF-16LE instead.
```
u'teststring'.encode('utf-16le')
``` |
Assign a list to variables | 12,016,240 | 2 | 2012-08-18T05:58:01Z | 12,016,261 | 11 | 2012-08-18T06:01:19Z | [
"python",
"google-chartwrapper"
] | I have a python list:
```
x = ['aa', 'bb', 'cc']
```
The len() (or list length, which is 3 in this case) of this list can be any number, as it is basically coming from database. My question is: how can I assign each string member of this list into a separate variable automatically? The point over here is: I do not kn... | [You're doing it wrong.](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists)
```
G.label(*x)
``` |
Microsoft Translator API in Python | 12,017,846 | 3 | 2012-08-18T10:35:00Z | 12,149,985 | 7 | 2012-08-27T21:40:29Z | [
"python",
"microsoft-translator"
] | I wrote small script in python to translate words from English to Russian language. It uses the [Microsoft-Translator-Python-API](https://github.com/openlabs/Microsoft-Translator-Python-API/) for connection to Microsoft Translator API. However, there is a problem of delay - it takes up to three seconds to call API and ... | Interestingly enough, you can actually do this:
```
import json
import requests
import urllib
args = {
'client_id': '',#your client id here
'client_secret': '',#your azure secret here
'scope': 'http://api.microsofttranslator.com',
'grant_type': 'client_credentials'
}
oauth_url = 'ht... |
Print Combining Strings and Numbers | 12,018,992 | 17 | 2012-08-18T13:32:47Z | 12,019,007 | 35 | 2012-08-18T13:34:31Z | [
"python"
] | To print strings and numbers in Python, is there any other way than doing something like:
```
first = 10
second = 20
print "First number is %(first)d and second number is %(second)d" % {"first": first, "second":second}
``` | You could do any of these (and there may be other ways):
```
(1) print "First number is {} and second number is {}".format(first, second)
(1b) print "First number is {first} and number is {second}".format(first=first, second=second)
```
or
```
(2) print 'First number is', first, ' second number is', second
```
or
... |
Where to put standalone-django scripts without breaking imports? | 12,019,661 | 4 | 2012-08-18T15:10:47Z | 12,019,708 | 10 | 2012-08-18T15:16:37Z | [
"python",
"django"
] | I'm still pretty new to Python.
I have a Django website with several apps and a `/libs` directory. I need to add a couple cron jobs that will use my Django models. I've already worked all that out, no big deal.
I have a problem with my imports, though.
I would like to include these scripts in the App they generally ... | There is a better way, custom management commands solve this.
<https://docs.djangoproject.com/en/dev/howto/custom-management-commands/>
These let you write stand alone utility scripts. You can run these as a cron or just as utilities. They use the exact same paths as any other module in your django app.
While these s... |
How to get month and year from Date field in sqlalchemy? | 12,019,766 | 8 | 2012-08-18T15:25:20Z | 12,024,611 | 16 | 2012-08-19T06:13:59Z | [
"python",
"sql",
"sqlalchemy"
] | The result should be Date object
Since the day cannot be 'removed', set it to say, 1st day of the month.
Leaving only Month, Year | You can use following constructs to filter the `Date` column using either `year` or `month`:
```
.filter(extract('year', Foo.Date) == 2012)
.filter(extract('month', Foo.Date) == 12)
```
And `group_by` is also possible:
```
.group_by(sqlalchemy.func.year(Foo.Date), sqlalchemy.func.month(Foo.Date))
```
Now I haven't ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.