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 |
|---|---|---|---|---|---|---|---|---|---|
Python socket bind without port | 11,059,228 | 3 | 2012-06-15T23:06:40Z | 11,059,254 | 7 | 2012-06-15T23:10:44Z | [
"python",
"sockets",
"bind"
] | I need to bind my socket to specific local IP before connecting as a client.
```
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("192.168.1.2", 33333))
s.connect(("google.com", 80))
s.send("test")
```
The probles is: I know how to bind to specific local ip, but I don't know what to specify in port. I ca... | Yes, you should use 0 as the port. The operating system will then choose the port for you, the same way it would do if you had not called `bind`. |
Google App Engine Projection Query | 11,059,339 | 3 | 2012-06-15T23:22:47Z | 11,059,380 | 7 | 2012-06-15T23:29:44Z | [
"python",
"google-app-engine",
"gae-datastore",
"datastore"
] | I have a model like this:
```
class Users(db.Model):
email = db.EmailProperty(required=True, indexed=True)
user_name = db.StringProperty(required=True, indexed=True)
api_key = db.StringProperty(required=False, indexed=False)
active = db.BooleanProperty(required=True, indexed=False)
real_name = db.String... | You cannot project unindexed properties. As stated in the [documentation](https://developers.google.com/appengine/docs/python/datastore/queries#Query_Projection)
> There are some limitations on what properties can be projected:
> You can only project indexed properties. This means that projecting Text, Blob or other p... |
parsing a tab-separated file in Python | 11,059,390 | 16 | 2012-06-15T23:31:49Z | 11,059,449 | 35 | 2012-06-15T23:39:36Z | [
"python",
"tabs",
"io"
] | I'm trying to parse a tab-separated file in Python where a number placed k tabs apart from the beginning of a row, should be placed into the k-th array.
Is there a built-in function to do this, or a better way, other than reading line by line and do all the obvious processing a naive solution would perform? | You can use [the `csv` module](http://docs.python.org/library/csv.html) to parse tab seperated value files easily.
```
import csv
with open("tab-separated-values") as tsv:
for line in csv.reader(tsv, dialect="excel-tab"): #You can also use delimiter="\t" rather than giving a dialect.
...
```
Where `line`... |
Does python mako template support connitue/break in loop context? | 11,060,327 | 5 | 2012-06-16T02:33:37Z | 11,060,493 | 11 | 2012-06-16T03:18:07Z | [
"python",
"templates",
"loops",
"mako"
] | Is it possible to use continue/break in a %control structure loop.
For example:
```
% for x in range(1):
% continue
% endfor
```
Thanks, | ```
from mako.template import Template
t = Template(
"""
% for i in xrange(5):
% if i == 3:
<% break %>
% endif
${i}
% endfor
% for i in xrange(5):
% if i == 3:
<% continue %>
% endif
${i}
% endfor
""")
print t.render()
output:
0
1
2
0
1
2
4
``` |
Is there a "not equal" operator in Python? | 11,060,506 | 134 | 2012-06-16T03:19:57Z | 11,060,508 | 275 | 2012-06-16T03:21:41Z | [
"python",
"operators"
] | How would you say does not equal?
Like
```
if hi == hi:
print "hi"
elif hi (does not equal) bye:
print "no hi"
```
Is there a replacement for `==` that means "not equal"? | Use `!=` (preferred) or `<>` (deprecated). See [comparison operators](http://docs.python.org/release/2.5.2/lib/comparisons.html). For comparing object identities, you can use the keyword `is` and its negation `is not`.
e.g.
```
1 == 1 # true
1 != 1 # false
1 <> 1 # false
[] is [] # false (distinct objects)
a = b = []... |
Is there a "not equal" operator in Python? | 11,060,506 | 134 | 2012-06-16T03:19:57Z | 11,060,512 | 28 | 2012-06-16T03:22:40Z | [
"python",
"operators"
] | How would you say does not equal?
Like
```
if hi == hi:
print "hi"
elif hi (does not equal) bye:
print "no hi"
```
Is there a replacement for `==` that means "not equal"? | Not equal `!=` (vs equal `==`)
Are you asking about something like this?
```
answer = 'hi'
if answer == 'hi': # equal
print "hi"
elif answer != 'hi': # not equal
print "no hi"
```
This [Python - Basic Operators](http://www.tutorialspoint.com/python/python_basic_operators.htm) chart might be helpful. |
Is there a "not equal" operator in Python? | 11,060,506 | 134 | 2012-06-16T03:19:57Z | 11,060,620 | 12 | 2012-06-16T03:45:38Z | [
"python",
"operators"
] | How would you say does not equal?
Like
```
if hi == hi:
print "hi"
elif hi (does not equal) bye:
print "no hi"
```
Is there a replacement for `==` that means "not equal"? | There's the `!=` (not equal) operator that returns `True` when two values differ, though be careful with the types cause `"1" != 1` this will always return True and `"1" == 1` will always return False, since the types differ, python is dynamically but strongly typed, other statically typed languages would complain abou... |
Python method lookup rules | 11,060,600 | 4 | 2012-06-16T03:40:53Z | 11,060,628 | 10 | 2012-06-16T03:47:36Z | [
"python",
"python-3.x"
] | I find the following example mildly surprising:
```
>>> class Foo:
def blah(self):
pass
>>> f = Foo()
>>> def bar(self):
pass
>>> Foo.bar = bar
>>> f.bar
<bound method Foo.bar of <__main__.Foo object at 0x02D18FB0>>
```
I expected the bound method to be associated with each particular i... | You want to blow your mind, try this:
```
f.blah is f.blah
```
That's right, the instance method wrapper is *different* each time you access it.
In fact an instance method is a descriptor. In other words, `f.blah` is actually:
```
Foo.blah.__get__(f, type(f))
```
Methods are not actually stored on the instance; th... |
Python method lookup rules | 11,060,600 | 4 | 2012-06-16T03:40:53Z | 11,060,633 | 7 | 2012-06-16T03:48:32Z | [
"python",
"python-3.x"
] | I find the following example mildly surprising:
```
>>> class Foo:
def blah(self):
pass
>>> f = Foo()
>>> def bar(self):
pass
>>> Foo.bar = bar
>>> f.bar
<bound method Foo.bar of <__main__.Foo object at 0x02D18FB0>>
```
I expected the bound method to be associated with each particular i... | The instances do not "contain" the method. The lookup process happens dynamically at the time you access `foo.bar`. It checks to see if the instance has an attribute of that name. Since it doesn't, it looks on the class, whereupon it finds whatever attribute the class has at that time. Note that methods are not special... |
python conversion between color spaces | 11,062,773 | 2 | 2012-06-16T10:52:25Z | 11,062,786 | 8 | 2012-06-16T10:54:42Z | [
"python",
"color-space"
] | I wanted to convert from rgb to hsv but the results seem to be unexpected
Following is the code
```
import colorsys
print colorsys.rgb_to_hsv(144, 190, 255)
```
and it prints following
```
(0.5, 0, 255)
```
where I was expecting it to be
```
(215,44,100)
```
or
```
(215,0.44,1.0)
```
any ide... | The [documentation of `colorsys`](http://docs.python.org/library/colorsys.html) explains that all colour space coordinates are floating point numbers between `0.0` and `1.0` â rescale your values accordingly to get the desired results:
```
>>> h, s, v = colorsys.rgb_to_hsv(144/255., 190/255., 255/255.)
>>> 360 * h, ... |
Python script to copy text to clipboard | 11,063,458 | 24 | 2012-06-16T12:32:47Z | 11,063,483 | 30 | 2012-06-16T12:35:47Z | [
"python",
"clipboard",
"pyperclip"
] | I just need a python script that copies text to the clipboard.
After the script gets executed i need the output of the text to be pasted to another source.
Is it possible to write a python script that does this job? | See [Pyperclip](http://coffeeghost.net/2010/10/09/pyperclip-a-cross-platform-clipboard-module-for-python/). Example (taken from Pyperclip site):
```
import pyperclip
pyperclip.copy('The text to be copied to the clipboard.')
spam = pyperclip.paste()
```
Also, see [Xerox](https://github.com/kennethreitz/xerox). But it ... |
Python script to copy text to clipboard | 11,063,458 | 24 | 2012-06-16T12:32:47Z | 17,371,323 | 21 | 2013-06-28T18:27:58Z | [
"python",
"clipboard",
"pyperclip"
] | I just need a python script that copies text to the clipboard.
After the script gets executed i need the output of the text to be pasted to another source.
Is it possible to write a python script that does this job? | On mac i use this function.
```
import os
data = "hello world"
os.system("echo '%s' | pbcopy" % data)
```
It will copy "hello world" to the clipboard. |
Python script to copy text to clipboard | 11,063,458 | 24 | 2012-06-16T12:32:47Z | 25,476,462 | 7 | 2014-08-24T21:25:37Z | [
"python",
"clipboard",
"pyperclip"
] | I just need a python script that copies text to the clipboard.
After the script gets executed i need the output of the text to be pasted to another source.
Is it possible to write a python script that does this job? | Use Tkinter:
<http://stackoverflow.com/a/4203897/2804197>
```
try:
from Tkinter import Tk
except ImportError:
from tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('i can has clipboardz?')
r.destroy()
```
(Original author: <http://stackoverflow.com/users/449571/atomizer>) |
Read delay in App Engine Datastore after put() | 11,063,597 | 14 | 2012-06-16T12:50:57Z | 11,064,675 | 21 | 2012-06-16T15:17:23Z | [
"python",
"google-app-engine",
"gae-datastore"
] | I write a code for a blog/news site. Main page has 10 most recent articles and also there is an archive section with all articles sorted by modification time descending. In archive section I use pagination based on cursors and I cache results starting from the second page as pages are changed only when new article is p... | You're most likely being hit by "eventually consistent queries". When using the HR datastore, queries may use slightly old data, and it takes a while for data written by put() to be visible to queries (there is no such delay for get() by key or id). The delay is typically measured in seconds but I don't think we guaran... |
assigning two variables to one list slice | 11,064,075 | 7 | 2012-06-16T14:02:01Z | 11,064,103 | 11 | 2012-06-16T14:05:47Z | [
"python",
"list",
"pattern-matching",
"slice"
] | Is it possible to assign to a list slice in one go, that would achieve the following as:
```
mylist = [1,2,3,4,5,6,7]
xs = mylist[:-1]
x = mylist[-1]
xs == [1,2,3,4,5,6]
x == 7
```
I know I can write it like this:
```
xs,x = mylist[:-1], mylist[-1]
```
but I was wondering if it is possible to this any other way... | You can in Python 3:
```
>>> *xs, x = [1, 2, 3, 4, 5, 6, 7]
>>> xs
[1, 2, 3, 4, 5, 6]
>>> x
7
``` |
Flask - custom decorator breaks the routing | 11,064,263 | 7 | 2012-06-16T14:29:21Z | 11,686,329 | 9 | 2012-07-27T10:50:08Z | [
"python",
"json",
"decorator",
"flask"
] | I have the following Flask routes and a custom helper:
```
from spots import app, db
from flask import Response
import simplejson as json
def json_response(action_func):
def create_json_response(*args, **kwargs):
ret = action_func(*args, **kwargs)
code = 200
if len(ret) == 2:
... | As ÐидÑл ÐеÑÑов said the solution is to use [functools.wraps](http://docs.python.org/library/functools.html#functools.wraps):
```
import functools
def json_response(action_func):
@functools.wraps(action_func)
def create_json_response(*args, **kwargs):
...
return create_json_response
```
The... |
passing one list of values instead of mutiple arguments to a function? | 11,064,406 | 5 | 2012-06-16T14:47:16Z | 11,064,421 | 7 | 2012-06-16T14:48:49Z | [
"python",
"list",
"function",
"arguments"
] | Lets say there's a function `func()` which takes two arguments, `a` and `b`. Is there some kind of technique in Python to pass a single list `mylist` which has both values to the function instead?
```
def myfunc(a, b):
return a+b
myfunc([1, 2])
```
If one was completely sure that he was always calling the same f... | You can use `*` to [unpack the list into arguments](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists):
```
myfunc(*mylist)
``` |
Adobe Photoshop-style posterization and OpenCV | 11,064,454 | 8 | 2012-06-16T14:52:06Z | 11,065,161 | 7 | 2012-06-16T16:25:45Z | [
"python",
"opencv",
"numpy"
] | It seems Adobe Photoshop does posterization by quantizing each color channel separately, based on the number of levels specified. So for example, if you specify 2 levels, then it will take the R value, and set it to 0 if your R value is less than 128 or 255 if your value is >= 128. It will do the same for G and B.
Is ... | We can do this quite neatly using numpy, without having to worry about the channels at all!
```
import cv2
im = cv2.imread('1_tree_small.jpg')
im[im >= 128]= 255
im[im < 128] = 0
cv2.imwrite('out.jpg', im)
```
output:

input:
![enter image descript... |
Adobe Photoshop-style posterization and OpenCV | 11,064,454 | 8 | 2012-06-16T14:52:06Z | 11,072,667 | 7 | 2012-06-17T15:49:18Z | [
"python",
"opencv",
"numpy"
] | It seems Adobe Photoshop does posterization by quantizing each color channel separately, based on the number of levels specified. So for example, if you specify 2 levels, then it will take the R value, and set it to 0 if your R value is less than 128 or 255 if your value is >= 128. It will do the same for G and B.
Is ... | Your question specifically seems to be asking about a level of 2. But what about levels more than 2. So i have added a code below which can posterize for any level of color.
```
import numpy as np
import cv2
im = cv2.imread('messi5.jpg')
n = 2 # Number of levels of quantization
indices = np.arange(0,256) # Lis... |
Get pixel's RGB using PIL | 11,064,786 | 39 | 2012-06-16T15:32:25Z | 11,064,935 | 56 | 2012-06-16T15:52:09Z | [
"python",
"image",
"python-imaging-library",
"rgb",
"pixel"
] | Is it possible to get the RGB color of a pixel using PIL?
I'm using this code:
```
im = Image.open("image.gif")
pix = im.load()
print(pix[1,1])
```
However, it only outputs a number (e.g. `0` or `1`) and not three numbers (e.g. `60,60,60` for R,G,B). I guess I'm not understanding something about the function. I'd lov... | Yes, this way:
```
im = Image.open('image.gif')
rgb_im = im.convert('RGB')
r, g, b = rgb_im.getpixel((1, 1))
print r, g, b
(65, 100, 137)
```
The reason you were getting a single value before with `pix[1, 1]` is because GIF pixels refer to one of the 256 values in the GIF color palette.
See also this SO post: [Pyth... |
Generate a sequence of numbers in Python | 11,064,917 | 18 | 2012-06-16T15:50:26Z | 11,064,945 | 17 | 2012-06-16T15:53:04Z | [
"python",
"sequence"
] | How can I generate the sequence of numbers "1,2,5,6,9,10......" and so until 100 in Python?
I even need the comma (',') included, but this is not the main problem.
The sequence: every number from 1..100, divisible by 4 with remainder 1 or 2. | Every number from 1,2,5,6,9,10... is divisible by 4 with remainder 1 or 2.
```
>>> ','.join(str(i) for i in xrange(100) if i % 4 in (1,2))
'1,2,5,6,9,10,13,14,...'
``` |
Generate a sequence of numbers in Python | 11,064,917 | 18 | 2012-06-16T15:50:26Z | 11,064,967 | 9 | 2012-06-16T15:56:29Z | [
"python",
"sequence"
] | How can I generate the sequence of numbers "1,2,5,6,9,10......" and so until 100 in Python?
I even need the comma (',') included, but this is not the main problem.
The sequence: every number from 1..100, divisible by 4 with remainder 1 or 2. | ```
>>> ','.join('{},{}'.format(i, i + 1) for i in range(1, 100, 4))
'1,2,5,6,9,10,13,14,17,18,21,22,25,26,29,30,33,34,37,38,41,42,45,46,49,50,53,54,57,58,61,62,65,66,69,70,73,74,77,78,81,82,85,86,89,90,93,94,97,98'
```
That was a quick and quite dirty solution.
Now, for a solution that is suitable for different kind... |
Unpacking keyword arguments, but only the ones that match the function | 11,065,419 | 11 | 2012-06-16T17:04:29Z | 11,065,434 | 21 | 2012-06-16T17:06:39Z | [
"python"
] | Let's say I have a function:
```
def foo(a = None, b=None, c=None):
return "a:%s, b:%s, c:%s" % (a,b,c)
```
I have a dictionary with some (or none) of the arguments above, but also with keys that are not named arguments in the function, e.g.:
```
d = {'a':1, 'x':4, 'b':2, 'y':5}
```
If I call the following I will... | ```
def foo(a = None, b=None, c=None,**extras):
return "a:%s, b:%s, c:%s" % (a, b, c)
```
here the `**extras` will collect all the extra named/keyword arguments. |
using django-allauth | 11,065,610 | 5 | 2012-06-16T17:32:22Z | 11,075,511 | 8 | 2012-06-17T23:11:13Z | [
"python",
"django",
"django-admin",
"django-allauth"
] | i am having trouble using django-allauth. I am getting this error.
NoReverseMatch at /accounts/login/
Reverse for 'facebook\_channel' with arguments '()' and keyword arguments '{}' not found.
So far I have followed everything to the letter.
here is my settings.py
```
INSTALLED_APPS = (
'django.contrib.auth',
... | Just faced and solved the same problem. You need to install the Facebook SDK egg, which django-allauth relies on, i.e.:
```
pip install -e git://github.com/pythonforfacebook/facebook-sdk.git#egg=facebook-sdk
```
(By the way, if you are using Django 1.4, you will run into a runtime error when confirming email addresse... |
How do I get linux to automatically run my python script in the Python interpreter? | 11,065,863 | 6 | 2012-06-16T18:07:18Z | 11,065,879 | 9 | 2012-06-16T18:09:27Z | [
"python",
"linux"
] | I've decided that it would be good for me to move outside of my .NET bubble and start experimenting with other technologies. I have Ubuntu12 running and python2.7 and 3.2 are installed. I can run code directly in the interpreters.
I have a basic script on the filesystem called Standalone.py:
```
#!/usr/bin/env python... | 1. You need to make the script executable using
```
chmod +x Standalone.py
```
2. Usually, the current directory is not searched for executable files, so you need to use
```
./Standalone.py
```
to tell the shell that the script is in the current directory. |
Remove punctuation from Unicode formatted strings | 11,066,400 | 23 | 2012-06-16T19:28:05Z | 11,066,687 | 47 | 2012-06-16T20:11:54Z | [
"python",
"unicode"
] | I have a function that removes punctuation from a list of strings:
```
def strip_punctuation(input):
x = 0
for word in input:
input[x] = re.sub(r'[^A-Za-z0-9 ]', "", input[x])
x += 1
return input
```
I recently modified my script to use Unicode strings so I could handle other non-Western c... | You could use `unicode.translate()` method:
```
import unicodedata
import sys
tbl = dict.fromkeys(i for i in xrange(sys.maxunicode)
if unicodedata.category(unichr(i)).startswith('P'))
def remove_punctuation(text):
return text.translate(tbl)
```
You could also use `r'\p{P}'` that is supporte... |
mysql error : ERROR 1018 (HY000): Can't read dir of '.' (errno: 13) | 11,066,411 | 15 | 2012-06-16T19:29:35Z | 11,066,467 | 28 | 2012-06-16T19:38:12Z | [
"python",
"mysql",
"database",
"django",
"permissions"
] | when i try to view the databases in mysql i get this error:
```
ERROR 1018 (HY000): Can't read dir of '.' (errno: 13)
```
And that stops my app from displaying...
My django debugger says:
```
(2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/my_database' (13)")
```
Here is my settings file... | You need to set ownership and permissions for directory:
```
chown -R mysql:mysql /var/lib/mysql/ #your mysql user may have different name
chmod -R 755 /var/lib/mysql/
```
Note: `-R` makes commands recursive - you may omit it, if there is no subdirs in `/var/lib/mysql/`. |
mysql error : ERROR 1018 (HY000): Can't read dir of '.' (errno: 13) | 11,066,411 | 15 | 2012-06-16T19:29:35Z | 34,185,550 | 15 | 2015-12-09T17:47:30Z | [
"python",
"mysql",
"database",
"django",
"permissions"
] | when i try to view the databases in mysql i get this error:
```
ERROR 1018 (HY000): Can't read dir of '.' (errno: 13)
```
And that stops my app from displaying...
My django debugger says:
```
(2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/my_database' (13)")
```
Here is my settings file... | For Us OS X Users, this should work:
```
sudo chown -R mysql:mysql /usr/local/mysql/
sudo chmod -R 755 /usr/local/mysql/
```
Edit: Depending on how you installed mysql your mileage my vary. I installed using the mysql community server dmg installer on mysql.com |
beautifulsoup can't find href in file using regular expression | 11,066,874 | 3 | 2012-06-16T20:40:27Z | 11,066,890 | 9 | 2012-06-16T20:42:25Z | [
"python",
"beautifulsoup"
] | I have a html file like following:
```
<form action="/2811457/follow?gsid=3_5bce9b871484d3af90c89f37" method="post">
<div>
<a href="/2811457/follow?page=2&gsid=3_5bce9b871484d3af90c89f37">next_page</a>
<input name="mp" type="hidden" value="3" />
<input type="text" name="page" size="2" style='-wap-input-forma... | You need to escape the question mark. The regular expression `w?` means `zero or one w`. Try this:
```
print soup.find('a', href = re.compile(r'.*follow\?page.*'))
``` |
Python Pandas - Re-ordering columns in a dataframe based on column name | 11,067,027 | 71 | 2012-06-16T21:05:01Z | 11,067,072 | 93 | 2012-06-16T21:12:21Z | [
"python",
"pandas",
"order"
] | I have a dataframe with over 200 columns (don't ask why). The issue is as they were generated the order is
```
['Q1.3','Q6.1','Q1.2','Q1.1',......]
```
I need to re-order the columns as follows:
```
['Q1.1','Q1.2','Q1.3',.....'Q6.1',......]
```
Is there some way for me to do this within python? | ```
df.reindex_axis(sorted(df.columns), axis=1)
```
This assumes that sorting the column names will give the order you want. If your column names won't sort lexicographically (e.g., if you want column Q10.3 to appear after Q9.1), you'll need to sort differently, but that has nothing to do with pandas. |
Python Pandas - Re-ordering columns in a dataframe based on column name | 11,067,027 | 71 | 2012-06-16T21:05:01Z | 11,385,780 | 94 | 2012-07-08T18:56:47Z | [
"python",
"pandas",
"order"
] | I have a dataframe with over 200 columns (don't ask why). The issue is as they were generated the order is
```
['Q1.3','Q6.1','Q1.2','Q1.1',......]
```
I need to re-order the columns as follows:
```
['Q1.1','Q1.2','Q1.3',.....'Q6.1',......]
```
Is there some way for me to do this within python? | You can also do more succinctly:
`df.sort_index(axis=1)` |
Python Pandas - Re-ordering columns in a dataframe based on column name | 11,067,027 | 71 | 2012-06-16T21:05:01Z | 19,238,029 | 11 | 2013-10-08T02:22:08Z | [
"python",
"pandas",
"order"
] | I have a dataframe with over 200 columns (don't ask why). The issue is as they were generated the order is
```
['Q1.3','Q6.1','Q1.2','Q1.1',......]
```
I need to re-order the columns as follows:
```
['Q1.1','Q1.2','Q1.3',.....'Q6.1',......]
```
Is there some way for me to do this within python? | [Tweet's answer](http://stackoverflow.com/a/11067079/841830) can be passed to BrenBarn's answer above with
```
data.reindex_axis(sorted(data.columns, key=lambda x: float(x[1:])), axis=1)
```
So for your example, say:
```
vals = randint(low=16, high=80, size=25).reshape(5,5)
cols = ['Q1.3', 'Q6.1', 'Q1.2', 'Q9.1', 'Q... |
Python Pandas - Re-ordering columns in a dataframe based on column name | 11,067,027 | 71 | 2012-06-16T21:05:01Z | 24,396,554 | 13 | 2014-06-24T21:22:45Z | [
"python",
"pandas",
"order"
] | I have a dataframe with over 200 columns (don't ask why). The issue is as they were generated the order is
```
['Q1.3','Q6.1','Q1.2','Q1.1',......]
```
I need to re-order the columns as follows:
```
['Q1.1','Q1.2','Q1.3',.....'Q6.1',......]
```
Is there some way for me to do this within python? | You can just do:
```
df[sorted(df.columns)]
``` |
Python Pandas - Re-ordering columns in a dataframe based on column name | 11,067,027 | 71 | 2012-06-16T21:05:01Z | 27,361,326 | 10 | 2014-12-08T15:33:31Z | [
"python",
"pandas",
"order"
] | I have a dataframe with over 200 columns (don't ask why). The issue is as they were generated the order is
```
['Q1.3','Q6.1','Q1.2','Q1.1',......]
```
I need to re-order the columns as follows:
```
['Q1.1','Q1.2','Q1.3',.....'Q6.1',......]
```
Is there some way for me to do this within python? | Don't forget to add "inplace=True" to Wes' answer or set the result to a new DataFrame.
```
df.sort_index(axis=1, inplace=True)
``` |
Annotate Time Series plot in Matplotlib | 11,067,368 | 16 | 2012-06-16T22:01:39Z | 11,068,038 | 25 | 2012-06-17T00:30:01Z | [
"python",
"numpy",
"matplotlib"
] | I have an index array (x) of dates (datetime objects) and an array of actual values (y: bond prices). Doing (in iPython):
```
plot(x,y)
```
Produces a perfectly fine time series graph with the x axis labeled with the dates. No problem so far. But I want to add text on certain dates. For example, at 2009-10-31 I wish ... | Matplotlib uses an internal floating point format for dates.
You just need to convert your date to that format (using `matplotlib.dates.date2num` or `matplotlib.dates.datestr2num`) and then use `annotate` as usual.
As a somewhat excessively fancy example:
```
import datetime as dt
import matplotlib.pyplot as plt
imp... |
In Javascript a dictionary comprehension, or an Object `map` | 11,068,247 | 17 | 2012-06-17T01:22:41Z | 11,068,265 | 20 | 2012-06-17T01:29:00Z | [
"javascript",
"jquery",
"python"
] | I need to generate a couple of objects from lists in Javascript. In Python, I'd write this:
```
{key_maker(x): val_maker(x) for x in a_list}
```
Another way to ask is does there exist something like `jQuery.map()` which aggregates objects? Here's my guess (doesn't work):
```
var result = {}
$.map(a_list, function(x)... | Assuming `a_list` is an Array, the closest would probably be to use `.reduce()`.
```
var result = a_list.reduce(function(obj, x) {
obj[key_maker(x)] = val_maker(x);
return obj;
}, {});
```
Array comprehensions are likely coming in a future version of JavaScript.
---
You can patch non ES5 compliant implement... |
What's meaning of these formats in twisted's docstring? | 11,068,385 | 6 | 2012-06-17T01:56:34Z | 11,069,862 | 9 | 2012-06-17T08:09:09Z | [
"python",
"format",
"twisted",
"docstring"
] | In twisted's sourcecode, many docstrings contain formats like this: L{xxx} or C{xxx} or a line begin with an '@', what's their meanings?
for example, in twisted/internet/interfaces.py:
```
def registerProducer(producer, streaming):
"""
Register to receive data from a producer.
...
For L{IPullProducer}... | The documentation format used by Twisted is [Epytext, which is documented on `epydoc.sourceforge.net`](http://epydoc.sourceforge.net/manual-epytext.html).
`L{}` means "link" (i.e. "this is a Python identifier, please link to it") `C{}` means "code" (i.e. `hello C{foo} bar` should be formatted like "hello `foo` bar"). ... |
Check if file is symlink in python | 11,068,419 | 42 | 2012-06-17T02:03:57Z | 11,068,434 | 72 | 2012-06-17T02:08:25Z | [
"python",
"operating-system"
] | In python, is there a function to check if a given file/directory is a symlink ? For example, for the below files, my wrapper function should return `True`.
```
# ls -l
total 0
lrwxrwxrwx 1 root root 8 2012-06-16 18:58 dir -> ../temp/
lrwxrwxrwx 1 root root 6 2012-06-16 18:55 link -> ../log
``` | To determine if a directory entry is a symlink use this:
> [os.path.islink(path)](http://docs.python.org/library/os.path.html?highlight=islink#os.path.islink)
>
> Return True if path refers to a directory entry that is a symbolic
> link. Always False if symbolic links are not supported.
For instance, given:
```
drwx... |
running python executable in linux | 11,068,477 | 3 | 2012-06-17T02:21:41Z | 11,068,481 | 12 | 2012-06-17T02:23:03Z | [
"python",
"ubuntu"
] | I've found a few other people asking this question, but the answers for their problem are not helping me. I trying to learn python and trying to make a file executable.
The practice script runs when I type `python ./userPrompt.py`.
But when I try to run it as an executable (just `./userPrompt.py`).
I've successful ch... | The path is `/usr`, not `/user`. |
python raw_input odd behavior with accents containing strings | 11,068,581 | 3 | 2012-06-17T02:51:13Z | 11,068,845 | 9 | 2012-06-17T04:06:36Z | [
"python",
"unicode",
"diacritics",
"raw-input"
] | I'm writing a program that asks the user for input that contains accents. The user input string is tested to see if it matches a string declared in the program. As you can see below, my code is not working:
---
## code
```
# -*- coding: utf-8 -*-
testList = ['má']
myInput = raw_input('enter something here: ')
pri... | What you're running into is that `raw_input` gives you a byte string, but the string you're comparing against is a Unicode string. Python 2 tries to convert them to a common type to compare, but this fails because it can't guess the encoding of the byte string - so, your solution is to do the conversion explicitly.
As... |
How to generate a new map for jvectormap jquery plugin? | 11,068,645 | 14 | 2012-06-17T03:08:54Z | 13,520,307 | 14 | 2012-11-22T21:37:01Z | [
"javascript",
"jquery",
"python",
"jvectormap"
] | I want to know how to create or generate a map for jquery plugin jvectormap <http://jvectormap.com/>
The project has several maps:
<http://jvectormap.com/maps/>
but I need I map with Australia and new Zeland divided by states. In the documentation in github <https://github.com/bjornd/jvectormap>, it says that anyone ... | Just in case anyone will need the same.
To run converter, you need (this instruction is valid for Windows environment):
* download and install [OSGeo4W](http://trac.osgeo.org/osgeo4w/) (use Express Desktop Install)
* download desired shape file ([this](http://www.naturalearthdata.com/downloads/10m-cultural-vectors/10m... |
how to process all kinds of exception in a scrapy project, in errback and callback? | 11,069,128 | 9 | 2012-06-17T05:28:31Z | 11,079,181 | 7 | 2012-06-18T08:21:57Z | [
"python",
"scrapy"
] | I am currently working on a scraper project which is much important to ensure EVERY request got properly handled, i.e., either to log an error or to save a successful result. I've already implemented the basic spider, and I can now process 99% of the requests successfully, but I could get errors like captcha, 50x, 30x,... | EDIT 16 nov 2012: Scrapy >=0.16 uses a different method to attach methods to signals, extra example added
The most simple solution would be to write an extension in which you capture failures, using Scrapy signals.
For example; the following extension will catch all errors and print a traceback.
You could do anything... |
Python, How to efficiently make a nested dictionary from a list of lists | 11,069,623 | 2 | 2012-06-17T07:25:05Z | 11,069,701 | 9 | 2012-06-17T07:39:25Z | [
"python"
] | I have a list of lists that looks like this
```
[['ip1',404],
['ip1',200],
['ip1',200],
['ip2',200],
['ip2',200],
['ip2',504]]
```
I need to make a dictionary that has counts of the status codes by ip address.
```
results = {'ip1':{404:1,200:2},'ip2':{200:2,504:1}}
``` | The tools in collections make short work of this problem:
```
>>> from collections import defaultdict, Counter
>>> d = defaultdict(Counter)
>>> for ip, code in [['ip1',404], ['ip1',200], ['ip1',200],
['ip2',200], ['ip2',200], ['ip2',504]]:
d[ip][code] += 1
>>> dict(d)
{'ip2': Counter({200... |
Argparse python, remove subparser list in help menu | 11,070,268 | 12 | 2012-06-17T09:29:25Z | 11,809,651 | 11 | 2012-08-04T15:11:46Z | [
"python",
"argparse"
] | I'm writing a command-line utility using Argparse and have added a bunch of sub\_parsers (sub commands). In the help menu they appear under a group called "commands" and I get a nice list of all the possible options. However before this list appears, all the same commands appear under the group title in braces like so:... | The "{foo,bar}" part is the argument 'metavar'. A metavar is how argparse refers to expected argument values in the usage and help strings. argparse treats subcommands like an argument with multiple choices so if you don't specify a metavar, the default is the list of choices (subcommands) in curly braces. It lets the ... |
How to add a new column to a CSV file using Python? | 11,070,527 | 23 | 2012-06-17T10:10:50Z | 11,070,638 | 30 | 2012-06-17T10:32:50Z | [
"python",
"csv",
"python-3.x"
] | I have several [CSV](http://en.wikipedia.org/wiki/Comma-separated_values) files that look like this:
```
Input
Name Code
blackberry 1
wineberry 2
rasberry 1
blueberry 1
mulberry 2
```
I would like to add a new column to all CSV files so that it would look like this:
```
Output ... | This should give you an idea of what to do:
```
>>> v = open('C:/test/test.csv')
>>> r = csv.reader(v)
>>> row0 = r.next()
>>> row0.append('berry')
>>> print row0
['Name', 'Code', 'berry']
>>> for item in r:
... item.append(item[0])
... print item
...
['blackberry', '1', 'blackberry']
['wineberry', '2', '... |
How to use 2to3 tool in windows? | 11,071,037 | 15 | 2012-06-17T11:42:06Z | 11,071,056 | 31 | 2012-06-17T11:45:32Z | [
"python",
"2to3"
] | I tried to modify the sintax using 2to3 tool by running command
```
python C:\Python32\Tools\scripts\2to3.py neo4j.py
```
and got the output

When opening neo4j.py however I noticed there hasn't been anything changed. Below is the block of code wher... | You have to use the `-w` flag to actually write the changes:
```
python C:\Python32\Tools\scripts\2to3.py -w neo4j.py
```
See the [2to3.py documentation](http://docs.python.org/release/3.0.1/library/2to3.html). |
python 3 in emacs | 11,071,701 | 7 | 2012-06-17T13:38:34Z | 11,072,062 | 10 | 2012-06-17T14:31:55Z | [
"python",
"emacs",
"python-3.x",
"emacs23"
] | I changed two days ago to Emacs 23, which lately gave me a lot of headache, especially, as I have two Python versions installed, the older 2.7 and 3. As I generally want to start the python 3 interpreter, it would be nice if I could tell Emacs in some way to use python 3 instead of 2.7.
Besides, I could not find a mod... | If you're using `python-mode.el`, you can specify the binary to be executed as an inferior process by setting the `py-python-command` variable, i.e.:
```
(setq py-python-command "python3")
```
Naturally, you'll need to provide the name of the binary as it exists on your system in place of `"python3"`, if it differs. ... |
Install python modules with Visual Studio 2008 on Windows x64 | 11,072,521 | 4 | 2012-06-17T15:31:38Z | 11,072,924 | 10 | 2012-06-17T16:27:13Z | [
"python",
"visual-studio"
] | I try installing python modules (this time `flask-bcrypt` or `py-bcrypt`) and I can't get it to work because compilation failed.
I learned that I needed Visual Studio 2008 (I do own 2010 Professional, but it seems thats not enough). So I downloaded the Express Edition and ran again. This time it failed with some Value... | The command line VS 2008 compilers are included with "[Microsoft Windows SDK for Windows 7 and .NET Framework 3.5 Service Pack 1](http://www.microsoft.com/en-us/download/details.aspx?id=3138)". During on the download and installation, make sure you select the x64 compiler.
Once you have the SDK installed, Python can b... |
open() function python default directory | 11,073,553 | 3 | 2012-06-17T17:56:59Z | 11,073,565 | 8 | 2012-06-17T17:58:56Z | [
"python"
] | I'm new and I have no idea where the default directory for the `open()` function is.
For example `open('whereisthisdirectory.txt','r')`
Can someone advise me? I've tried googling it (and looking on stackoverflow) and even putting a random txt file in so many folders but I still can't figure it out. Since I'm beginnin... | `os.getcwd()`
Shows the current working directory, that's what `open` uses for for relative paths.
You can change it with `os.chdir`. |
How to group DataFrame by a period of time? | 11,073,609 | 19 | 2012-06-17T18:07:39Z | 11,073,962 | 19 | 2012-06-17T18:56:19Z | [
"python",
"pandas"
] | I have some data from log files and would like to group entries by a minute:
> ```
> def gen(date, count=10):
> while count > 0:
> yield date, "event{}".format(randint(1,9)), "source{}".format(randint(1,3))
> count -= 1
> date += DateOffset(seconds=randint(40))
>
> df = DataFrame.from_recor... | You can group on any array/Series of the same length as your DataFrame --- even a computed factor that's not actually a column of the DataFrame. So to group by minute you can do:
```
df.groupby(df.index.map(lambda t: t.minute))
```
If you want to group by minute and something else, just mix the above with the column ... |
Why does installing numpy require python-dev in Kubuntu 12.04 | 11,073,695 | 6 | 2012-06-17T18:18:38Z | 11,073,758 | 8 | 2012-06-17T18:27:24Z | [
"python",
"ubuntu",
"debian",
"pip"
] | Just starting out in python on a pendrive 12.04 Kubuntu environment. I had to install GCC (understand that), but I also had to install python-dev before I could use PIP to install numpy. Why do I need python-dev?
```
sudo apt-get install gcc
sudo apt-get install pip
cd /usr/lib/python2.7/
sudo apt-get install python-d... | When you use `pip` to install numpy, the packages is compiled from source. The `pythonx.x-dev` packages contain the necessary header files for linking against python. |
Identifying If the OS is (Open)SUSE in Python? | 11,073,998 | 6 | 2012-06-17T19:01:21Z | 11,074,198 | 7 | 2012-06-17T19:32:32Z | [
"python",
"opensuse",
"suse",
"identification",
"uname"
] | I'm developing a script that *needs* the package managers of a System. I've identified Fedora, Gentoo, and Arch Linux using the `os.uname()` function.
However, the (open)SUSE `uname` results is the same as other Linux Distros. I found the `uname` results of many distros on [Wikipedia](http://en.wikipedia.org/wiki/Unam... | If the distribution follows the [Linux Standard Base](http://www.linuxbase.org/), you could read the output of [lsb\_release -i](http://refspecs.linuxbase.org/LSB_4.1.0/LSB-Core-generic/LSB-Core-generic/lsbrelease.html).
Something like this:
```
import os
try:
distro = os.popen('lsb_release -i').read().split(':'... |
Set random seed temporarily, like "new Random()" | 11,074,523 | 11 | 2012-06-17T20:25:07Z | 11,074,556 | 21 | 2012-06-17T20:30:42Z | [
"python",
"random"
] | In Python, what is the best way to generate some random number using a certain seed but without reseeding the global state? In Java, you could write simply:
```
Random r = new Random(seed);
r.nextDouble();
```
and the standard `Math.random()` would not be affected. In Python, the best solution that I can see is:
```... | You can instantiate your own [`Random`](http://hg.python.org/cpython/file/2.7/Lib/random.py#l72) object.
```
myrandom = random.Random(myseed)
```
The `random` module manages its own instance of `Random`, which will be unaffected by changes made to `myrandom`. |
Unstring Python? | 11,075,583 | 2 | 2012-06-17T23:23:48Z | 11,075,589 | 11 | 2012-06-17T23:26:07Z | [
"python"
] | I am a noob,
How do I remove quotations and commas from my list? Or how do I "unstring"?
Without showing the dictionary (dic), the code I am using looks like this:
```
>>>import itertools
>>>list(itertools.product(dic[2], dic[3])
```
my results looks like this:
```
[('A', 'D'), ('A', 'E'), ('A', 'F'), ('B', 'D'), (... | You want to produce a string, so you can use string manipulation (in particular, the [`join`](http://docs.python.org/library/stdtypes.html#str.join) method):
```
>>> import itertools
>>> a = ['A', 'B']
>>> b = ['D', 'E', 'F']
>>> print ', '.join(''.join(x) for x in itertools.product(a, b))
AD, AE, AF, BD, BE, BF
```
... |
No module named query on haystack | 11,076,253 | 3 | 2012-06-18T02:08:01Z | 11,077,916 | 9 | 2012-06-18T06:33:50Z | [
"python",
"django",
"django-haystack",
"pythonpath"
] | I was using haystack on my Windows computer, but I realized I needed other modules for my django app that are easier to install on Linux, so I moved to my VirtualBox with Ubuntu. I installed everything with virtualenv in a venv folder. Basically my app uses haystack with a Whoosh backend.
On view.py, on the import line... | So I did a very dumb mistake.
I used `pip install haystack` instead of `pip install django-haystack`. |
Is it possible to iterate through all nodes with py2neo | 11,076,260 | 8 | 2012-06-18T02:09:32Z | 11,085,368 | 11 | 2012-06-18T14:51:05Z | [
"python",
"neo4j",
"py2neo"
] | Is there a way to iterate through every node in a neo4j database using py2neo?
My first thought was iterating through `GraphDatabaseService`, but that didn't work. If there isn't a way to do it with py2neo, is there another python interface that would let me?
**Edit:** I'm accepting @Nicholas's answer for now, but I'... | I would suggest doing that with asynchronous Cypher, something like:
```
from py2neo import neo4j, cypher
graph_db = neo4j.GraphDatabaseService()
def handle_row(row):
node = row[0]
# do something with `node` here
cypher.execute(graph_db, "START z=node(*) RETURN z", row_handler=handle... |
Efficient comparison of all elements of python dict | 11,076,438 | 4 | 2012-06-18T02:50:49Z | 11,076,475 | 9 | 2012-06-18T02:58:10Z | [
"python",
"dictionary",
"compare"
] | I am looking for a more efficient way to do comparisons between all elements of a python dict.
Here is psuedocode of what I am doing:
```
for key1 in dict:
for key2 in dict:
if not key1 == key2:
compare(key1,key2)
```
if the length of the dict is N, this is N^2 - N. Is there any way of not re... | Maybe something like
```
>>> import itertools
>>>
>>> d = {1:2, 2:3, 3:4}
>>>
>>> for k0, k1 in itertools.combinations(d,2):
... print 'compare', k0, k1
...
compare 1 2
compare 1 3
compare 2 3
```
if you don't care about whether you get (1,2) or (2,1). [Of course you could iterate over `sorted(d)` or some vari... |
Finding matching submatrices inside a matrix | 11,078,122 | 5 | 2012-06-18T06:52:49Z | 11,079,590 | 8 | 2012-06-18T08:54:16Z | [
"python",
"numpy"
] | I have a 100x200 2D array expressed as a numpy array consisting of black (0) and white (255) cells. It is a bitmap file. I then have 2D shapes (it's easiest to think of them as letters) that are also 2D black and white cells.
I know I can naively iterate through the matrix but this is going to be a 'hot' portion of my... | You *can* use correlate. You'll need to set your black values to -1 and your white values to 1 (or vice-versa) so that you know the value of the peak of the correlation, and that it only occurs with the correct letter.
The following code does what I think you want.
```
import numpy
from scipy import signal
# Set up ... |
Finding matching submatrices inside a matrix | 11,078,122 | 5 | 2012-06-18T06:52:49Z | 11,079,691 | 7 | 2012-06-18T09:02:11Z | [
"python",
"numpy"
] | I have a 100x200 2D array expressed as a numpy array consisting of black (0) and white (255) cells. It is a bitmap file. I then have 2D shapes (it's easiest to think of them as letters) that are also 2D black and white cells.
I know I can naively iterate through the matrix but this is going to be a 'hot' portion of my... | Here is a method you may be able to use, or adapt, depending upon the details of your requirements. It uses [`ndimage.label` and `ndimage.find_objects`:](http://docs.scipy.org/doc/scipy/reference/ndimage.html)
1. label the image using `ndimage.label` this finds all blobs in the array and labels them to integers.
2. Ge... |
Django signals for new entry only | 11,079,644 | 10 | 2012-06-18T08:58:28Z | 11,080,062 | 22 | 2012-06-18T09:24:35Z | [
"python",
"django",
"django-signals"
] | I'm using Django's post\_save signal to send emails to users whenever a *new* article is added to the site. However, users still receive new emails whenever I use `save()` method for already created articles. How is it possible to receive emails only when NEW entry was added?
Thanks in advance | The `post_save` signal receives a boolean `created` argument which indicates if the saved `instance` was created.
```
def my_callback(sender, **kwargs):
if kwargs['created']:
print('Instance is new')
``` |
Break items into columns evenly in Jinja2 template | 11,079,690 | 2 | 2012-06-18T09:02:10Z | 11,094,294 | 7 | 2012-06-19T04:19:31Z | [
"python",
"flask",
"jinja2"
] | I have a list of cities names that is variable and I want to break it into 4 columns evenly. I have some solution but it looks overwhelmed and dirty. What's the best and simplest way to do it?
My solution is here:
```
{% set cities_in_column = cities|length/4|int %}
{% set step=0 %}
<div class="four columns">
{% ... | You are looking for the [`slices`](http://jinja.pocoo.org/docs/templates/#slice) filter:
```
{% for column in cities | sort | slice(4) -%}
<div class="four columns">
{%- for city in column -%}
<h5><a href="/city/{{ city.url}}">{{ city.name }}</a>
<span style="float:right;">({{ city.users_count }})</span></... |
Python decorators theory | 11,079,734 | 4 | 2012-06-18T09:05:13Z | 11,079,772 | 8 | 2012-06-18T09:07:31Z | [
"python",
"decorator",
"theory"
] | I have question about clean thory in Python. When:
```
@decorator_func
def func(bla, alba):
pass
```
Is equivalent to:
```
def func(bla, alba):
pass
func = decorator_func(func)
```
So:
```
@decorator_func(aaa, bar)
def func(bla, alba):
pass
```
Is equvalent to...? | It's equivalent to:
```
def func(bla, alba):
pass
func = decorator_func(aaa, bar)(func)
```
Or:
```
def func(bla, alba):
pass
decorator = decorator_func(aaa, bar)
func = decorator(func)
```
So in your second example, `decorator_func` should be a callable that returns a callable.
Here's an example of such a... |
Google App Engine: Determine whether Current Request is a Taskqueue | 11,081,767 | 4 | 2012-06-18T11:23:38Z | 11,082,412 | 7 | 2012-06-18T12:01:36Z | [
"python",
"google-app-engine",
"task-queue"
] | Is there a way to dynamically determine whether the currently executing task is a standard http request or a TaskQueue?
In some parts of my request handler, I make a few urlfetches. I would like the timeout delay of the url fetch to be short if the request is a standard http request and long if it is a TaskQueue. | Pick any one of the following HTTP headers:
1. `X-AppEngine-QueueName`, the name of the queue (possibly default)
2. `X-AppEngine-TaskName`, the name of the task, or a system-generated unique ID if no name was specified
3. `X-AppEngine-TaskRetryCount`, the number of times this task has been retried; for the first attem... |
matplotlib.pyplot How to name different lines in the same plot? | 11,082,831 | 4 | 2012-06-18T12:25:42Z | 11,082,907 | 8 | 2012-06-18T12:29:24Z | [
"python",
"plot",
"matplotlib",
"diagram"
] | Think about doing this:
```
import matplotlib.pyplot as plt
plt.plot(x_A,y_A,'g--')
plt.plot(x_B,y_B,'r-o')
plt.show()
```
How would you go about giving both lines different names, i.e. like Microsoft Excel would do it? | ```
import matplotlib.pyplot as plt
plt.plot(x_A,y_A,'g--', label="plot A")
plt.plot(x_B,y_B,'r-o', label="plot A")
plt.legend()
plt.show()
``` |
pyMySQL set connection character set | 11,082,909 | 8 | 2012-06-18T12:29:29Z | 11,083,221 | 28 | 2012-06-18T12:47:28Z | [
"python",
"mysql",
"unicode",
"pymysql"
] | I'm developing a fairly straightforward web app using Flask and MySQL.
I'm struggling with unicode. Users sometimes paste stuff that they copied from Word and it's falling over with the old smart quotes `u'\u201c'`.
A little bit of investigation shows that the connection I have to MySQL is using the `Latin1` charset ... | I worked it out by poking around in the [pyMySQL source](https://github.com/PyMySQL/PyMySQL) (I had tried, but couldn't find the right place!).
You can specify it when you create the connection:
```
conn = pymysql.connect(host='localhost',
user='username',
passwd='passwor... |
How to get the first sentence from the following paragraph? | 11,083,036 | 4 | 2012-06-18T12:36:05Z | 11,084,569 | 7 | 2012-06-18T14:05:07Z | [
"python",
"nlp",
"text-segmentation"
] | I know this might sound easy. I thought about using the first dot(.) which comes as the benchmark, but when abbreviations and short forms come, I am rendered helpless.
e.g. -
> Sir Winston Leonard Spencer-Churchill, KG, OM, CH, TD, PC, DL, FRS,
> Hon. RA (30 November 1874 â 24 January 1965) was a British politician... | If you use `nltk` you can add abbreviations, like this:
```
>>> import nltk
>>> sent_detector = nltk.data.load('tokenizers/punkt/english.pickle')
>>> sent_detector._params.abbrev_types.add('hon')
>>> sent_detector.tokenize(your_text)
['Sir Winston Leonard Spencer-Churchill, KG, OM, CH, TD, PC, DL, FRS, Hon. RA
(30 No... |
How do I instantiate a module in Python | 11,083,315 | 2 | 2012-06-18T12:53:15Z | 11,083,372 | 7 | 2012-06-18T12:56:09Z | [
"python",
"python-2.7"
] | I've heard before that "modules are just classes too". I have a few situations, mostly unit testing and interactive interpreter experimentation, where I would like to create a module in a variable without having to create any external files. I imagine something like:
```
>>> import sys
>>>
>>> m = sys.Module() # <- Th... | ```
>>> import types
>>> help(types.ModuleType)
>>> mymod = types.ModuleType("MyMod")
>>> mymod
<module 'MyMod' (built-in)>
>>>
``` |
Python - threading.Timer stays alive after calling cancel() method | 11,083,349 | 9 | 2012-06-18T12:55:14Z | 11,083,919 | 10 | 2012-06-18T13:27:22Z | [
"python",
"multithreading"
] | I noticed the following behavior in the following code (using threading.Timer class):
```
import threading
def ontimer():
print threading.current_thread()
def main():
timer = threading.Timer(2, ontimer)
timer.start()
print threading.current_thread()
timer.cancel()
if timer.isAlive():
... | A `Timer` is a subclass of a `Thread` and its [implementation](https://hg.python.org/cpython/file/0792a0ad7f22/Lib/threading.py#l1049) is really simple. It waits the provided time by subscribing to the event `finished`.
So when you set the event by `Timer.cancel` it is guaranteed that the function does not get called.... |
Python - threading.Timer stays alive after calling cancel() method | 11,083,349 | 9 | 2012-06-18T12:55:14Z | 11,083,983 | 10 | 2012-06-18T13:31:11Z | [
"python",
"multithreading"
] | I noticed the following behavior in the following code (using threading.Timer class):
```
import threading
def ontimer():
print threading.current_thread()
def main():
timer = threading.Timer(2, ontimer)
timer.start()
print threading.current_thread()
timer.cancel()
if timer.isAlive():
... | You should use the [thread.join()](http://docs.python.org/library/threading.html#threading.Thread.join) to wait until your timer's thread is really finished and cleaned.
```
import threading
def ontimer():
print threading.current_thread()
def main():
timer = threading.Timer(2, ontimer)
timer.start()
... |
Python eigenvectors: differences among numpy.linalg, scipy.linalg and scipy.sparse.linalg | 11,083,660 | 14 | 2012-06-18T13:12:30Z | 11,084,192 | 11 | 2012-06-18T13:43:20Z | [
"python",
"numpy",
"scipy"
] | Scipy and Numpy have between them three different functions for finding eigenvectors for a given square matrix, these are:
1. [`numpy.linalg.eig(a)`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eig.html#numpy.linalg.eig)
2. [`scipy.linalg.eig(a)`](http://docs.scipy.org/doc/scipy/reference/generate... | The special behaviour of the third one has to do with the [Lanczos algorithm](http://en.wikipedia.org/wiki/Lanczos_algorithm), which works very well with sparse matrices. The documentation of `scipy.sparse.linalg.eig` says it uses a wrapper for ARPACK, which in turn uses "the Implicitly Restarted Arnoldi Method (IRAM) ... |
Generating users accounts inside Google App Engine | 11,083,776 | 11 | 2012-06-18T13:19:03Z | 11,087,970 | 8 | 2012-06-18T17:28:12Z | [
"python",
"google-app-engine",
"openid"
] | For a project, I'm going to create an application on Google App Engine where:
* Discussion Leaders can register with their e-mail address (or OpenID or Google Account) on the website itself to use it.
* In the application admin page they can create a group discussion for which they can add users based on their e-mail ... | # **[EngineAuth](https://github.com/scotch/engineauth)**
A few months ago I developed a python package called [EngineAuth](https://github.com/scotch/engineauth). It uses a middleware to intercept request intended for authentication.
Here's an example app:
<http://engineauth.scotchmedia.com/>
And the source:
<https... |
Numpy mean with condition | 11,084,710 | 3 | 2012-06-18T14:13:13Z | 11,085,270 | 11 | 2012-06-18T14:45:41Z | [
"python",
"numpy"
] | I have algorithm of calculating average speed in pure python:
```
speed = [...]
avg_speed = 0.0
speed_count = 0
for i in speed:
if i > 0: # I dont need zeros
avg_speed += i
speed_count += 1
if speed_count == 0:
return 0.0
return avg_speed / speed_count
... | The function `numpy.average` can receive a `weights` argument, where you can put a boolean array generated from some condition applied to the array itself - in this case, an element being greater than 0:
```
average_speed = numpy.average(speeds, weights=(speeds > 0))
```
Hope this helps |
matplotlib linked x axes with autoscaled y axes on zoom | 11,086,724 | 16 | 2012-06-18T16:06:08Z | 11,103,301 | 20 | 2012-06-19T14:37:11Z | [
"python",
"matplotlib"
] | How can I create a stack of plots with linked (shared) x axes that autoscale the y axes of all "slave" plots during zoom? For example:
```
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212, sharex=ax1)
ax1.plot([0,1])
ax2.plot([2,1])
plt.show()
```
When I zoom in ... | After studying the gory details of matplotlib's axes.py, it appears that there are no provisions to autoscale an axes based on a view of the data, so there is no high-level way to achieve what I wanted.
However, there are 'xlim\_changed' events, to which one can attach a callback:
```
import numpy as np
def on_xlim_... |
Read a text file with non-ASCII characters in an unknown encoding | 11,086,752 | 5 | 2012-06-18T16:08:07Z | 11,087,170 | 10 | 2012-06-18T16:33:32Z | [
"python",
"encoding"
] | I want to read a file that contains also **German and not only characters**. I found that i can do like this
```
>>> import codecs
>>> file = codecs.open('file.txt','r', encoding='UTF-8')
>>> lines= file.readlines()
```
This is working when i try to run my job in Python IDLE but when i try to run it from somewh... | You need to know which character encoding the text is encoded in. If you don't know that beforehand, you can try guessing it with the [chardet](http://pypi.python.org/pypi/chardet) module. First install it:
```
$ pip install chardet
```
Then, for example reading the file in binary mode:
```
>>> import chardet
>>> ch... |
Deferred evaluation with lambda in Python | 11,087,047 | 5 | 2012-06-18T16:26:49Z | 11,087,133 | 11 | 2012-06-18T16:31:36Z | [
"python",
"lambda",
"deferred-execution"
] | In a loop, I am trying to defer the comparison the two value()s of two Nodes to a later time.
```
class Node():
def __init__(self, v):
self.v = v
def value(self):
return self.v
nodes = [Node(0), Node(1), Node(2), Node(3), Node(4), Node(2)]
results = []
for i in [0, 1, 2]:
j = i + 3
res... | To bind the current values of `i` and `j` to the function instead of having it look in the outer scope, you can use either a closure or default argument values. The easiest way to do this is to use default argument values in your lambda:
```
for i in [0, 1, 2]:
j = i + 3
results.append(lambda i=i, j=j: nodes[i... |
Does Gunicorn run on Windows | 11,087,682 | 22 | 2012-06-18T17:08:03Z | 11,087,777 | 22 | 2012-06-18T17:15:30Z | [
"python",
"gunicorn"
] | I have looked around for a while, and I was surprised not finding any information whether Gunicorn runs on Windows or not.
Does anyone know if that is the case, and if so, where can I find some documentation about it? | Gunicorn is for a UNIX environment and is incompatible with Windows. |
Does Gunicorn run on Windows | 11,087,682 | 22 | 2012-06-18T17:08:03Z | 13,868,338 | 14 | 2012-12-13T20:53:33Z | [
"python",
"gunicorn"
] | I have looked around for a while, and I was surprised not finding any information whether Gunicorn runs on Windows or not.
Does anyone know if that is the case, and if so, where can I find some documentation about it? | Edit: there's now a plan to add Windows support. <https://github.com/benoitc/gunicorn/issues/524>
---
No. Gunicorn doesn't run on Windows. It's very design is to take 'advantage of features in Unix/Unix-like kernels'. |
How to use a common ini configuration (between development and production) in pyramid? | 11,089,479 | 7 | 2012-06-18T19:11:59Z | 11,093,895 | 16 | 2012-06-19T03:13:08Z | [
"python",
"configuration",
"pyramid"
] | I want to have a common configuration with settings that do not change across different environments (development and production). I know I could set up a global settings.py file (e.g., sql limits), but as far as I know, pyramid requires certain settings to be found in the ini file at startup (e.g., template directory ... | There are a couple possible options without going outside the INI-confines of PasteDeploy. However, up front, realize the beauty of the INI file model is an underlying ability to create multiple files with different settings/configurations. Yes, you have to keep them in sync, but they are just settings (no logic) so th... |
sorting dictionary python 3 | 11,089,655 | 6 | 2012-06-18T19:25:44Z | 11,089,708 | 15 | 2012-06-18T19:29:58Z | [
"python",
"dictionary"
] | I'm working on python 3.2.2.
Breaking my head more than 3 hours to sort a dictionary by it's keys.
I managed to make it a sorted list with 2 argument members, but can not make it a sorted dictionary in the end.
This is what I've figured:
```
myDic={10: 'b', 3:'a', 5:'c'}
sorted_list=sorted(myDic.items(), key=lambda x... | `dict` does not keep its elements' order. What you need is an OrderedDict: <http://docs.python.org/library/collections.html#collections.OrderedDict>
**edit**
Usage example:
```
>>> from collections import OrderedDict
>>> a = {'foo': 1, 'bar': 2}
>>> a
{'foo': 1, 'bar': 2}
>>> b = OrderedDict(sorted(a.items()))
>>> b... |
Find longest repetitive sequence in a string | 11,090,289 | 31 | 2012-06-18T20:09:24Z | 11,090,397 | 27 | 2012-06-18T20:17:32Z | [
"python",
"regex",
"string",
"algorithm"
] | I need to find the longest sequence in a string with the caveat that the sequence must be repeated three or more times. So, for example, if my string is:
**fdwaw4helloworldvcdv1c3xcv3xcz1sda21f2sd1ahelloworldgafgfa4564534321fadghelloworld**
then I would like the value "**helloworld**" to be returned.
I know of a few... | This problem is a variant of the [longest repeated substring problem](http://en.wikipedia.org/wiki/Longest_repeated_substring_problem) and there is an O(n)-time algorithm for solving it that uses [suffix trees](http://en.wikipedia.org/wiki/Suffix_tree). The idea (as suggested by Wikipedia) is to construct a suffix tree... |
Find longest repetitive sequence in a string | 11,090,289 | 31 | 2012-06-18T20:09:24Z | 11,091,454 | 7 | 2012-06-18T21:36:26Z | [
"python",
"regex",
"string",
"algorithm"
] | I need to find the longest sequence in a string with the caveat that the sequence must be repeated three or more times. So, for example, if my string is:
**fdwaw4helloworldvcdv1c3xcv3xcz1sda21f2sd1ahelloworldgafgfa4564534321fadghelloworld**
then I would like the value "**helloworld**" to be returned.
I know of a few... | Use defaultdict to tally each substring beginning with each position in the input string. The OP wasn't clear whether overlapping matches should or shouldn't be included, this brute force method includes them.
```
from collections import defaultdict
def getsubs(loc, s):
substr = s[loc:]
i = -1
while(subst... |
Is there a way to read 10000 lines from a file in python? | 11,091,029 | 13 | 2012-06-18T21:05:02Z | 11,091,136 | 21 | 2012-06-18T21:12:31Z | [
"python"
] | I am relatively new in python, was working on C a lot. Since I was seeing so many new functions in python that I do not know, I was wondering if there is a function that can request 10000 lines from a file in python.
Something like this is what I expect if that kind of function exist:
```
lines = get_10000_lines(file... | > f.readlines() returns a list containing all the lines of data in the file. If given an optional parameter sizehint, it reads that many bytes from the file and enough more to complete a line, and returns the lines from that. This is often used to allow efficient reading of a large file by lines, but without having to ... |
Is there a way to read 10000 lines from a file in python? | 11,091,029 | 13 | 2012-06-18T21:05:02Z | 11,091,142 | 20 | 2012-06-18T21:12:55Z | [
"python"
] | I am relatively new in python, was working on C a lot. Since I was seeing so many new functions in python that I do not know, I was wondering if there is a function that can request 10000 lines from a file in python.
Something like this is what I expect if that kind of function exist:
```
lines = get_10000_lines(file... | ```
from itertools import islice
with open(filename) as f:
first10000 = islice(f, 10000)
```
This sets `first10000` to an iterable object, i.e. you can loop over it with
```
for x in first10000:
do_something_with(x)
```
If you need a list, do `list(islice(f, 10000))` instead.
When the file contains less th... |
KeyError when adding objects to SQLAlchemy association object | 11,091,491 | 5 | 2012-06-18T21:39:55Z | 11,116,291 | 8 | 2012-06-20T09:12:49Z | [
"python",
"sqlalchemy"
] | I have two tables, `tablet` and `correspondent`:
```
class Correspondent(db.Model, GlyphMixin):
# PK column and tablename etc. come from the mixin
name = db.Column(db.String(100), nullable=False, unique=True)
# association proxy
tablets = association_proxy('correspondent_tablets', 'tablet')
def __init... | The **problem** with your code is in the `.__init__` method. If you are to `debug-watch/print()` the parameters, you will notice that the parameter `tablet` is actually an instance of `Correspondent`:
```
class Tablet_Correspondent(db.Model):
def __init__(self, tablet=None, correspondent=None):
print "in _... |
Python Packages Offline Installation | 11,091,623 | 50 | 2012-06-18T21:51:46Z | 11,092,043 | 30 | 2012-06-18T22:32:55Z | [
"python",
"pip",
"freebsd",
"easy-install",
"python-requests"
] | What's the best way to download a python package and it's dependencies from pypi for offline installation on another machine? Is there any easy way to do this with pip or easy\_install? I'm trying to install the requests library on a FreeBSD box that is not connected to the internet. | If the package is on PYPI, download it and its dependencies to some local directory.
E.g.
```
$ mkdir /pypi && cd /pypi
$ ls -la
-rw-r--r-- 1 pavel staff 237954 Apr 19 11:31 Flask-WTF-0.6.tar.gz
-rw-r--r-- 1 pavel staff 389741 Feb 22 17:10 Jinja2-2.6.tar.gz
-rw-r--r-- 1 pavel staff 70305 Apr 11 0... |
Python Packages Offline Installation | 11,091,623 | 50 | 2012-06-18T21:51:46Z | 14,447,068 | 108 | 2013-01-21T20:55:53Z | [
"python",
"pip",
"freebsd",
"easy-install",
"python-requests"
] | What's the best way to download a python package and it's dependencies from pypi for offline installation on another machine? Is there any easy way to do this with pip or easy\_install? I'm trying to install the requests library on a FreeBSD box that is not connected to the internet. | I use the `-d` (or `--download`) option to `pip install`, which makes the process of downloading sdist tarballs from PyPI much simpler. For instance, `pip install --download /path/to/some/dir celery` will download the sdist tarballs for celery and all its dependencies to `/path/to/some/dir` (but will not install them).... |
matplotlib with dates | 11,092,214 | 4 | 2012-06-18T22:52:52Z | 11,092,292 | 11 | 2012-06-18T23:01:53Z | [
"python",
"date",
"matplotlib"
] | I'm trying to plot values as a function of the date (only hh:mm:ss, without dd/mm/yy). The code looks like this
```
dates = matplotlib.dates.date2num(x_values)
plt.plot_date(dates, y_values)
```
but I get the following error
> 'numpy.string\_' object has no attribute 'toordinal'. | `date2num` expects `datetime` objects. If you have strings, use `matplotlib.dates.datestr2num`. |
Python - List of unique dictionaries | 11,092,511 | 45 | 2012-06-18T23:30:38Z | 11,092,590 | 79 | 2012-06-18T23:42:23Z | [
"python",
"dictionary"
] | Let's say I got a list of dictionaries:
```
[
{'id': 1, 'name': 'john', 'age': 34},
{'id': 1, 'name': 'john', 'age': 34},
{'id': 2, 'name': 'hanna', 'age': 30},
]
```
and I need to obtain a list of unique dictionaries (removing the duplicates):
```
[
{'id': 1, 'name': 'john', 'age': 34},
{'id': 2... | So make a temporary dict with the key being the `id`. This filters out the duplicates.
The `values()` of the dict will be the list
In Python2.7
```
>>> L=[
... {'id':1,'name':'john', 'age':34},
... {'id':1,'name':'john', 'age':34},
... {'id':2,'name':'hanna', 'age':30},
... ]
>>> {v['id']:v for v in L}.values()
[{'ag... |
Python - List of unique dictionaries | 11,092,511 | 45 | 2012-06-18T23:30:38Z | 11,092,607 | 24 | 2012-06-18T23:44:27Z | [
"python",
"dictionary"
] | Let's say I got a list of dictionaries:
```
[
{'id': 1, 'name': 'john', 'age': 34},
{'id': 1, 'name': 'john', 'age': 34},
{'id': 2, 'name': 'hanna', 'age': 30},
]
```
and I need to obtain a list of unique dictionaries (removing the duplicates):
```
[
{'id': 1, 'name': 'john', 'age': 34},
{'id': 2... | The usual way to find just the common elements in a set is to use Python's `set` class. Just add all the elements to the set, then convert the set to a `list`, and bam the duplicates are gone.
The problem, of course, is that a `set()` can only contain hashable entries, and a `dict` is not hashable.
If I had this prob... |
Python - List of unique dictionaries | 11,092,511 | 45 | 2012-06-18T23:30:38Z | 19,804,098 | 11 | 2013-11-06T04:25:08Z | [
"python",
"dictionary"
] | Let's say I got a list of dictionaries:
```
[
{'id': 1, 'name': 'john', 'age': 34},
{'id': 1, 'name': 'john', 'age': 34},
{'id': 2, 'name': 'hanna', 'age': 30},
]
```
and I need to obtain a list of unique dictionaries (removing the duplicates):
```
[
{'id': 1, 'name': 'john', 'age': 34},
{'id': 2... | You can use numpy library:
```
import numpy as np
list_of_unique_dicts=list(np.unique(np.array(list_of_dicts)))
``` |
large scale clustering library possibly with python bindings | 11,092,589 | 6 | 2012-06-18T23:42:17Z | 11,095,284 | 8 | 2012-06-19T06:06:18Z | [
"python",
"data-mining",
"cluster-analysis"
] | I've been trying to cluster some larger dataset. consisting of 50000 measurement vectors with dimension 7. I'm trying to generate about 30 to 300 clusters for further processing.
I've been trying the following clustering implementations with no luck:
* Pycluster.kcluster (gives only 1-2 non-empty clusters on my datas... | 50000 instances and 7 dimensions isn't really big, and should not kill an implementation.
Although it doesn't have python binding, give [ELKI](http://elki.dbs.ifi.lmu.de/) a try. The benchmark set they use on their homepage is 110250 instances in 8 dimensions, and they run k-means on it in 60 seconds apparently, and t... |
How to mouseover in python Webdriver | 11,092,748 | 21 | 2012-06-19T00:06:23Z | 11,108,430 | 28 | 2012-06-19T19:57:43Z | [
"python",
"selenium",
"webdriver",
"selenium-webdriver"
] | It seems this is the way to do hover / mouseover in webdriver, at least in the java api:
```
Actions action = new Actions(driver);
action.moveToElement(element).build().perform();
action.moveByOffset(1, 1).build().perform();
```
Is this possible in the Python api?
The webdriver api docs for python don't seem to menti... | ```
from selenium.webdriver.common.action_chains import ActionChains
def hover(self):
wd = webdriver_connection.connection
element = wd.find_element_by_link_text(self.locator)
hov = ActionChains(wd).move_to_element(element)
hov.perform()
``` |
Python Decimal to String | 11,093,021 | 16 | 2012-06-19T00:50:06Z | 11,093,031 | 31 | 2012-06-19T00:51:32Z | [
"python",
"string",
"decimal"
] | There are tons of topics on here that explain how to convert a string to a decimal, but how do I convert a decimal back to a string?
Like if I did this:
```
import decimal
dec = decimal.Decimal('10.0')
```
How would I take `dec` and get `'10.0'` (a string) out? | Use [the `str()` builtin](http://docs.python.org/library/functions.html#str), which:
> Returns a string containing a nicely printable representation of an object.
E.g:
```
>>> import decimal
>>> dec = decimal.Decimal('10.0')
>>> str(dec)
'10.0'
``` |
Python Decimal to String | 11,093,021 | 16 | 2012-06-19T00:50:06Z | 27,053,722 | 7 | 2014-11-21T03:41:55Z | [
"python",
"string",
"decimal"
] | There are tons of topics on here that explain how to convert a string to a decimal, but how do I convert a decimal back to a string?
Like if I did this:
```
import decimal
dec = decimal.Decimal('10.0')
```
How would I take `dec` and get `'10.0'` (a string) out? | Use the string format function:
```
>>> from decimal import Decimal
>>> d = Decimal("0.0000000000000123123")
>>> s = '{0:f}'.format(d)
>>> print(s)
0.0000000000000123123
```
If you just type cast the number to a string it won't work for exponents:
```
>>> str(d)
'1.23123E-14'
``` |
Use logging print the output of pprint | 11,093,236 | 25 | 2012-06-19T01:25:13Z | 11,093,247 | 53 | 2012-06-19T01:27:03Z | [
"python",
"logging",
"pprint"
] | I want to use pprint's output to show a complex data structure, but I would like to output it using the logging module rather than stdout.
```
ds = [{'hello': 'there'}]
logging.debug( pprint.pprint(ds) ) # outputs as STDOUT
``` | Use [`pprint.pformat`](http://docs.python.org/library/pprint.html#pprint.pformat) to get a string, and then send it to your logging framework.
```
ds = [{'hello': 'there'}]
logging.debug(pprint.pformat(ds))
``` |
Use logging print the output of pprint | 11,093,236 | 25 | 2012-06-19T01:25:13Z | 21,024,454 | 8 | 2014-01-09T15:33:53Z | [
"python",
"logging",
"pprint"
] | I want to use pprint's output to show a complex data structure, but I would like to output it using the logging module rather than stdout.
```
ds = [{'hello': 'there'}]
logging.debug( pprint.pprint(ds) ) # outputs as STDOUT
``` | The solution above didn't *quite* cut it for me because I'm also using a formatter to add name and levelname when logging. It looks a little untidy:
```
__main__ : DEBUG : ['aaaaaaaaaaaaaaaaaaaa',
'bbbbbbbbbbbbbbbbbbbb',
'cccccccccccccccccccc',
'dddddddddddddddddddd']
__main__ : DEBUG : Some other logging te... |
Create list of object attributes in python | 11,093,421 | 6 | 2012-06-19T01:57:05Z | 11,093,436 | 19 | 2012-06-19T01:59:14Z | [
"python"
] | I have a list of objects:
```
[Object_1, Object_2, Object_3]
```
Each object has an attribute: time:
```
Object_1.time = 20
Object_2.time = 30
Object_3.time = 40
```
I want to create a list of the time attributes:
```
[20, 30, 40]
```
What is the most efficient way to get this output? It can't be to iterate over ... | List comprehension is what you're after:
```
list_of_objects = [Object_1, Object_2, Object_3]
[x.time for x in list_of_objects]
``` |
Python Unicode string stored as '\u84b8\u6c7d\u5730' in file, how to convert it back to Unicode? | 11,094,380 | 6 | 2012-06-19T04:30:43Z | 11,094,432 | 27 | 2012-06-19T04:35:27Z | [
"python",
"unicode"
] | Some Unicode data is stored in file as '\u84b8\u6c7d\u5730' without any encoding.
Is there a way to covert them back in Python? | ```
>>> print '\u84b8\u6c7d\u5730'.decode('unicode-escape')
è¸æ±½å°
``` |
Capturing a single image from my webcam in Java or Python | 11,094,481 | 21 | 2012-06-19T04:40:52Z | 11,094,696 | 10 | 2012-06-19T05:08:17Z | [
"java",
"python",
"webcam",
"image-capture",
"javacv"
] | I want to capture a single image from my webcam and save it to disk. I want to do this in Java or Python (preferably Java). I want something that will work on both 64-bit Win7 and 32-bit Linux.
EDIT: I use Python 3.x, not 2.x
Because everywhere else I see this question asked people manage to get confused, I'm going t... | On windows it is easy to interact with your webcam with pygame:
```
from VideoCapture import Device
cam = Device()
cam.saveSnapshot('image.jpg')
```
I haven't tried using pygame on linux (all my linux boxen are servers without X), but this link might be helpful <http://www.jperla.com/blog/post/capturing-frames-from-a... |
Capturing a single image from my webcam in Java or Python | 11,094,481 | 21 | 2012-06-19T04:40:52Z | 11,094,891 | 34 | 2012-06-19T05:29:54Z | [
"java",
"python",
"webcam",
"image-capture",
"javacv"
] | I want to capture a single image from my webcam and save it to disk. I want to do this in Java or Python (preferably Java). I want something that will work on both 64-bit Win7 and 32-bit Linux.
EDIT: I use Python 3.x, not 2.x
Because everywhere else I see this question asked people manage to get confused, I'm going t... | @thebjorn has given a good answer. But if you want more options, you can try OpenCV, SimpleCV.
using **SimpleCV**:
```
from SimpleCV import Image, Camera
cam = Camera()
img = cam.getImage()
img.save("filename.jpg")
```
using **OpenCV**:
```
from cv2 import *
# initialize the camera
cam = VideoCapture(0) # 0 -> i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.