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
import error: no module named dns.query
15,240,215
4
2013-03-06T06:09:39Z
15,247,011
9
2013-03-06T12:09:03Z
[ "python", "scapy" ]
i am trying to execute a python code in windows... the code containds the following lines: ``` from scapy import * import random import socket import dns.query ``` but wen i compile it from command line it gives the following error: ``` C:\Python25 > attack.py Traceback <most recent call last>: File "C:\Python25\att...
This means that you do not have dnspython install. There are two ways to install dnspython : 1.Good way: To install any module, easiest way is to first install setup tools. Setup tools is something similar to "apt-get" for ubuntu. where you say "easy\_install " and it will get it and install it. To install setuptool...
Handling Variable Number of Columns with Pandas - Python
15,242,746
27
2013-03-06T08:52:55Z
15,252,012
27
2013-03-06T15:55:05Z
[ "python", "pandas" ]
I have a data set that looks like this (at most 5 columns - but can be less) ``` 1,2,3 1,2,3,4 1,2,3,4,5 1,2 1,2,3,4 .... ``` I am trying to use pandas read\_table to read this into a 5 column data frame. I would like to read this in without additional massaging. If I try ``` import pandas as pd my_cols=['A','B','C...
One way which seems to work (at least in 0.10.1 and 0.11.0.dev-fc8de6d): ``` >>> !cat ragged.csv 1,2,3 1,2,3,4 1,2,3,4,5 1,2 1,2,3,4 >>> my_cols = ["A", "B", "C", "D", "E"] >>> pd.read_csv("ragged.csv", names=my_cols, engine='python') A B C D E 0 1 2 3 NaN NaN 1 1 2 3 4 NaN 2 1 2 3 4 5 3 1...
Sort a dict by numeric value of dict.values
15,244,022
4
2013-03-06T09:56:16Z
15,244,093
10
2013-03-06T09:58:49Z
[ "python", "sorting", "dictionary" ]
I have a dict `d = {'a': '1', 'c': '10', 'b': '8', 'e': '11', 'g': '3', 'f': '2'}`. I want to sort the dict with numeric value of `d.values()`. Required ans is `['a','f', 'g', 'b', 'c', 'e']`. I had checked [here](http://stackoverflow.com/questions/613183/python-sort-a-dictionary-by-value) . I couldn't make it to sort ...
``` >>> d = {'a': '1', 'c': '10', 'b': '8', 'e': '11', 'g': '3', 'f': '2'} >>> sorted(d, key=lambda i: int(d[i])) ['a', 'f', 'g', 'b', 'c', 'e'] ```
What does this socket.gaierror mean?
15,246,088
25
2013-03-06T11:26:01Z
15,246,135
13
2013-03-06T11:27:51Z
[ "python", "tcp", "errno" ]
I'm new to python and going through a book, Core Python Applications 3rd Edition. This is the the first example and already I'm stumped with it. Here's the code with the error at the end. #1/usr/bin/env python ``` from socket import * from time import ctime HOST = ' ' PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) t...
The ``` HOST = ' ' ``` should read ``` HOST = '' ``` (i.e. no space between the quotes). The reason you're getting the error is that `' '` is not a valid hostname. In this context, `''` has a special meaning (it basically means "all local addresses").
What does this socket.gaierror mean?
15,246,088
25
2013-03-06T11:26:01Z
15,246,250
24
2013-03-06T11:33:01Z
[ "python", "tcp", "errno" ]
I'm new to python and going through a book, Core Python Applications 3rd Edition. This is the the first example and already I'm stumped with it. Here's the code with the error at the end. #1/usr/bin/env python ``` from socket import * from time import ctime HOST = ' ' PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) t...
It means that your given host name `' '` is invalid (gai stands for `getaddrinfo()`). As NPE already states, maybe an empty string `''` would be more appropriate than a space `' '`.
Is there a way to react to an Exception raising to the top of the program without try/except in Python?
15,246,709
7
2013-03-06T11:55:50Z
15,246,741
12
2013-03-06T11:57:14Z
[ "python", "exception" ]
Can I catch and dump an exception (and the corresponding stacktrace) that would make the program crash without doing something like : ``` try: # whole program except Execption as e: dump(e) raise ``` Sometime a external library crashes, and I'd like to react to Python dying and log the reasons it does so. I ...
Yes, by registering a [`sys.excepthook()` function](http://docs.python.org/2/library/sys.html#sys.excepthook): ``` import sys def myexcepthook(type, value, tb): dump(type, value, tb) sys.excepthook = myexcepthook ``` This *replaces* the default hook, which prints out the traceback to `stderr`. It is called when...
How can I dynamically create derived classes from a base class
15,247,075
38
2013-03-06T12:13:01Z
15,247,202
35
2013-03-06T12:19:39Z
[ "python", "class", "inheritance" ]
For example I have a base class as follows: ``` class BaseClass(object): def __init__(self, classtype): self._type = classtype ``` From this class I derive several other classes, e.g. ``` class TestClass(BaseClass): def __init__(self): super(TestClass, self).__init__('Test') class SpecialCla...
[`type()`](http://docs.python.org/2/library/functions.html#type) is the function that creates classes (and in particular sub-classes): ``` def set_x(self, value): self.x = value SubClass = type('SubClass', (BaseClass,), {'set_x': set_x}) # (More methods can be put in SubClass, including __init__().) obj = SubCla...
How can I dynamically create derived classes from a base class
15,247,075
38
2013-03-06T12:13:01Z
15,247,892
52
2013-03-06T12:55:00Z
[ "python", "class", "inheritance" ]
For example I have a base class as follows: ``` class BaseClass(object): def __init__(self, classtype): self._type = classtype ``` From this class I derive several other classes, e.g. ``` class TestClass(BaseClass): def __init__(self): super(TestClass, self).__init__('Test') class SpecialCla...
This bit of code allows you to create new classes with dynamic names and parameter names. The parameter verification in `__init__` just does not allow unknown parameters, if you need other verifications, like type, or that they are mandatory, just add the logic there: ``` class BaseClass(object): def __init__(self...
How to find duplicate names using pandas?
15,247,628
14
2013-03-06T12:40:38Z
15,248,239
26
2013-03-06T13:10:39Z
[ "python", "group-by", "pandas" ]
I have a `pandas.DataFrame` with a column called `name` containing strings. I would like to get a list of the names which occur more than once in the column. How do I do that? I tried: ``` funcs_groups = funcs.groupby(funcs.name) funcs_groups[(funcs_groups.count().name>1)] ``` But it doesn't filter out the singleton...
If you want to find the rows with duplicated name (except the first time we see that), you can try this ``` In [16]: import pandas as pd In [17]: p1 = {'name': 'willy', 'age': 10} In [18]: p2 = {'name': 'willy', 'age': 11} In [19]: p3 = {'name': 'zoe', 'age': 10} In [20]: df = pd.DataFrame([p1, p2, p3]) In [21]: df O...
python list comprehension with multiple 'if's
15,248,272
11
2013-03-06T13:11:58Z
15,248,309
17
2013-03-06T13:13:35Z
[ "python", "if-statement", "list-comprehension" ]
We all know python's ``` [f(x) for x in y if g(x)] ``` syntax. However the [AST](http://docs.python.org/2/library/ast.html#abstract-grammar) representation of list comprehension has room for more than one 'if' expression: ``` comprehension = (expr target, expr iter, expr* ifs) ``` Can somebody give me an example o...
Just stack them after one another: ``` [i for i in range(100) if i > 10 if i < 50] ``` Produces the integers between 11 and 49, inclusive.
python list comprehension with multiple 'if's
15,248,272
11
2013-03-06T13:11:58Z
15,248,356
22
2013-03-06T13:16:37Z
[ "python", "if-statement", "list-comprehension" ]
We all know python's ``` [f(x) for x in y if g(x)] ``` syntax. However the [AST](http://docs.python.org/2/library/ast.html#abstract-grammar) representation of list comprehension has room for more than one 'if' expression: ``` comprehension = (expr target, expr iter, expr* ifs) ``` Can somebody give me an example o...
The grammar allows for multiple if statements because you can mix them between the for loops: ``` [j for i in range(100) if i > 10 for j in range(i) if j < 20] ``` The comprehension components should be viewed as nested statements, the above translates to: ``` lst = [] for i in range(100): if i > 10: for...
How does python find a module file if the import statement only contains the filename?
15,252,040
16
2013-03-06T15:56:06Z
15,252,107
19
2013-03-06T15:58:30Z
[ "python", "python-import", "python-module", "pythonpath" ]
Everywhere I see Python code importing modules using `import sys` or `import mymodule` How does the interpreter find the correct file if no directory or path is provided?
<http://docs.python.org/2/tutorial/modules.html#the-module-search-path> > When a module named spam is imported, the interpreter first searches > for a built-in module with that name. If not found, it then searches > for a file named spam.py in a list of directories given by the > variable sys.path. sys.path is initial...
How does python find a module file if the import statement only contains the filename?
15,252,040
16
2013-03-06T15:56:06Z
15,252,125
8
2013-03-06T15:59:19Z
[ "python", "python-import", "python-module", "pythonpath" ]
Everywhere I see Python code importing modules using `import sys` or `import mymodule` How does the interpreter find the correct file if no directory or path is provided?
Also, you can see what the current path is by using the `sys` module ``` import sys print sys.path ```
Python extension debugging
15,253,586
8
2013-03-06T17:06:23Z
15,305,483
9
2013-03-09T00:05:47Z
[ "python", "gdb", "debug-symbols", "python-extensions" ]
I'm trying to debug an extension module for python that I wrote in C. I compiled it using the following: ``` python setup.py build -g install --user ``` I then debug with: ``` gdb python ... b py_node_make run test.py ``` It breaks at py\_node\_make (one of the functions I defined), but then I try: ``` (gdb) print...
For source debugging to work, your C extensions must be built with debug info (`gcc -g`). Since you're driving the compilation process with `distutils`, you can specify the compiler flags used through the **CFLAGS** environment variable ([Installing Python Modules: Tweaking compiler/linker flags](http://docs.python.org...
Stop pylab overlaying plots?
15,253,897
4
2013-03-06T17:20:47Z
15,253,984
7
2013-03-06T17:25:42Z
[ "python", "matplotlib", "overlay" ]
In my code, I am trying to periodically create a graph and save the graph to a file. The code looks like this: ``` import pylab as p def simpledist(speclist,totalbugs,a): data = [float(spec.pop)/float(totalbugs) for spec in speclist] p.hist(data) p.savefig('/Home/s1215235/Documents/python/newfolder/' + st...
To clear the plot use [`p.clf`](http://matplotlib.org/api/pyplot_api.html?highlight=clf#matplotlib.pyplot.clf) ``` def simpledist(speclist,totalbugs,a): data = [float(spec.pop)/float(totalbugs) for spec in speclist] p.clf() p.hist(data) p.savefig('/Home/s1215235/Documents/python/newfolder/' + str(a) + ...
standard way to handle user session in tornado
15,254,538
7
2013-03-06T17:55:38Z
15,265,556
8
2013-03-07T07:36:10Z
[ "python", "tornado" ]
So, in order to avoid the "no one best answer" problem, I'm going to ask, not for the best way, but the standard or most common way to handle sessions when using the Tornado framework. That is, if we're not using 3rd party authentication (OAuth, etc.), but rather we have want to have our own Users table with secure coo...
Tornado designed to be stateless and don't have session support out of the box. Use secure cookies to store sensitive information like user\_id. Use standard cookies to store not critical information. For storing large objects - use standard scheme - MySQL + memcache.
standard way to handle user session in tornado
15,254,538
7
2013-03-06T17:55:38Z
16,320,593
10
2013-05-01T14:59:03Z
[ "python", "tornado" ]
So, in order to avoid the "no one best answer" problem, I'm going to ask, not for the best way, but the standard or most common way to handle sessions when using the Tornado framework. That is, if we're not using 3rd party authentication (OAuth, etc.), but rather we have want to have our own Users table with secure coo...
Here's how it seems other micro frameworks handle sessions (CherryPy, Flask for example): 1. Create a table holding `session_id` and whatever other fields you'll want to track on a per session basis. Some frameworks will allow you to just store this info in a file on a per user basis, or will just store things directl...
Passing variable changes between threads in Python functions [Beginner]
15,254,567
4
2013-03-06T17:56:53Z
15,254,607
10
2013-03-06T17:58:40Z
[ "python", "multithreading", "variables", "loops", "multiprocessing" ]
So I have this code: ``` import time import threading bar = False def foo(): while True: if bar == True: print "Success!" else: print "Not yet!" time.sleep(1) def example(): while True: time.sleep(5) bar = True t1 = threading.Thread(target=foo) t1...
`bar` is a global variable. You should put `global bar` inside `example()`: ``` def example(): global bar while True: time.sleep(5) bar = True ``` * When **reading** a variable, it is first searched inside the function and if not found, outside. That's why it's not necessary to put `global bar...
Python MySQLdb execute table variable
15,255,694
7
2013-03-06T18:58:01Z
15,255,803
8
2013-03-06T19:04:33Z
[ "python", "mysql-python" ]
I'm trying to use a variable for a table name. I get the error "... near ''myTable'' at line 1 I must not be escaping this right. The double '' in the error seems to be a clue, but I don't get it. ``` db = MySQLdb.connect("localhost","user","pw","database" ) table = "myTable" def geno_order(db, table): cursor = db...
You can't use a parameter for the table name in the `execute` call. You'll need to use normal Python string interpolation for that: ``` sql = "SELECT * FROM %s" % table cursor.execute(sql) ``` Naturally, you'll need to be extra careful if the table name is coming from user input.
Python convert Excel File (xls or xlsx) to/from ODS
15,257,032
3
2013-03-06T20:11:24Z
15,257,777
7
2013-03-06T20:52:34Z
[ "python", "excel", "xlrd", "openoffice-api", "ods" ]
I've been scouring the net to find a Python library or tool that can converts an Excel file to/from ODS format, but haven't been able to come across anything. I need the ability to input and output data in either format. We don't need to worry about merged cells, formulas or anything non-straightforward.
If you have libreoffice installed, you can do a python execution wrapper around its headless mode: ``` $ /usr/bin/libreoffice --headless --invisible -convert-to ods /home/cwgem/Downloads/QTL_Sample_data.xls convert /home/cwgem/Downloads/QTL_Sample_data.xls -> /home/cwgem/QTL_Sample_data.ods using OpenDocument Spreads...
Django forms.ModelForm, Pylint, and new/old style classes
15,257,534
9
2013-03-06T20:39:54Z
15,257,589
8
2013-03-06T20:43:13Z
[ "python", "django", "pylint" ]
I have a Django 1.5 form that looks like this (simplified): ``` class BidForm(forms.ModelForm): class Meta: fields = ( ) model = Bid def __init__(self, *args, **kwargs): super(BidForm, self).__init__(*args, **kwargs) something() ``` When I run Pylint on this, I get a t...
No. Pylint, great though it is, is far from infallible, and in this case has just got it wrong. ModelForm is a new style class and the super is needed.
"IOError: decoder zip not available" : Ubuntu Python PIL
15,258,335
9
2013-03-06T21:22:43Z
17,180,735
8
2013-06-18T23:39:09Z
[ "python", "python-imaging-library", "imaging" ]
I am trying to get the sample heatmap.py running from: <http://jjguy.com/heatmap/> ``` #image.py import heatmap import random if __name__ == "__main__": pts = [] for x in range(400): pts.append((random.random(), random.random() )) print "Processing %d points..." % len(pts) hm = heatmap.H...
I just encountered a similar issue caused by having both PIL (installed through the python pip installer) and the python-imaging package installed via apt-get. When I removed the extra version from pip that resolved it for me. If you installed PIL from source or using pip then you might have the same problem. When I ...
os.path.islink on windows with python
15,258,506
10
2013-03-06T21:32:33Z
15,259,028
17
2013-03-06T22:05:39Z
[ "python", "windows", "symlink", "pywin32" ]
On Windows 7 with Python 2.7 how can I detect if a path is a symbolic link? This does not work `os.path.islink()`, it says it returns false if false or not supported and the path I'm providing is definitely a symbolic link so I'm assuming it's not supported on windows? What can I do?
The root problem is that you're using too old a version of Python. If you want to stick to 2.x, you will not be able to take advantage of new features added after early 2010. One of those features is handling NTFS symlinks. That functionality was added in 3.2 in late 2010. (See the [3.2](http://hg.python.org/cpython/f...
Python: how to sort array of dicts by two fields?
15,258,559
5
2013-03-06T21:36:24Z
15,258,588
8
2013-03-06T21:38:30Z
[ "python", "arrays", "sorting" ]
I am somewhat new to Python... I have an array of dicts that I got by reading a file containing JSON messages, i.e. using something like this: ``` import json ws = [] with open('messages.txt', 'r') as f: for line in f: data = json.loads(line) ws.append(data) ``` Each JSON message has, among other...
``` ws.sort(key=lambda datum: (datum['date'], datum['type'], datum['location'])) ``` Tuples are sorted naturally first by first element, then by succeeding elements.
Requests -- how to tell if you're getting a 404
15,258,728
32
2013-03-06T21:46:37Z
15,258,759
71
2013-03-06T21:48:50Z
[ "python", "python-requests" ]
I'm using the Requests library and accessing a website to gather data from it with the following code: ``` r = requests.get(url) ``` I want to add error testing for when an improper URL is entered and a 404 error is returned. If I intentionally enter an invalid URL, when I do this: ``` print r ``` I get this: ``` ...
Look at the [`r.status_code` attribute](http://docs.python-requests.org/en/latest/user/quickstart/#response-status-codes): ``` if r.status_code == 404: # A 404 was issued. ``` Demo: ``` >>> import requests >>> r = requests.get('http://httpbin.org/status/404') >>> r.status_code 404 ``` If you want `requests` to ...
conditional sums for pandas aggregate
15,259,547
11
2013-03-06T22:39:42Z
15,262,146
10
2013-03-07T02:45:52Z
[ "python", "pandas", "data.table" ]
I just recently made the switch from R to python and have been having some trouble getting used to data frames again as opposed to using R's data.table. The problem I've been having is that I'd like to take a list of strings, check for a value, then sum the count of that string- broken down by user. So I would like to ...
To complement unutbu's answer, here's an approach using `apply` on the groupby object. ``` >>> df.groupby('A_id').apply(lambda x: pd.Series(dict( sum_up=(x.B == 'up').sum(), sum_down=(x.B == 'down').sum(), over_200_up=((x.B == 'up') & (x.C > 200)).sum() ))) over_200_up sum_down sum_up A_id ...
python TCPServer address already in use but I close the server and I use `allow_reuse_address`
15,260,558
5
2013-03-06T23:55:12Z
15,278,302
9
2013-03-07T17:54:04Z
[ "python", "tcp", "port", "bind" ]
Here is my code to run the server: ``` class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): #.... PORT = 8089 httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler) httpd.allow_reuse_address = True print "Serving forever at port", PORT try: httpd.serve_forever() except: print "Closin...
Thanks to the other answers, I figured it out. `allow_reuse_address` should be on the class, not on the instance: ``` SocketServer.TCPServer.allow_reuse_address = True httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler) ``` I'm still not sure why closing the socket didn't free it up for the next run of the s...
How do I replace multiple spaces with just one character?
15,260,652
3
2013-03-07T00:03:44Z
15,260,673
19
2013-03-07T00:05:29Z
[ "python", "python-3.x" ]
Here's my code so far: ``` input1 = input("Please enter a string: ") newstring = input1.replace(' ','_') print(newstring) ``` So if I put in my input as: ``` I want only one underscore. ``` It currently shows up as: ``` I_want_only_____one______underscore. ``` But I want it to show up like this: ``` I_wan...
This pattern will replace any groups of whitespace with a single underscore ``` newstring = '_'.join(input1.split()) ``` If you only want to replace spaces (not tab/newline/linefeed etc.) it's probably easier to use a regex ``` import re newstring = re.sub(' +', '_', input1) ```
Encrypting the lines in a file
15,260,966
4
2013-03-07T00:34:46Z
15,261,130
7
2013-03-07T00:51:17Z
[ "python" ]
I'm trying to write a program that opens a text file, and shifts each of the characters in the file 5 characters to the right. It should only do this for alphanumeric characters, and leave nonalphanumerics as they are. (ex: C becomes H) I'm supposed to be using the ASCII table to do this, and I'm having an issue when t...
Using [str.translate](http://www.tutorialspoint.com/python/string_translate.htm): ``` In [24]: import string In [25]: string.uppercase Out[25]: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' In [26]: string.uppercase[5:]+string.uppercase[:5] Out[26]: 'FGHIJKLMNOPQRSTUVWXYZABCDE' In [27]: table = string.maketrans(string.uppercase, st...
100x100 image with random pixel colour
15,261,851
4
2013-03-07T02:14:25Z
15,261,887
15
2013-03-07T02:18:11Z
[ "python", "image", "matplotlib", "python-imaging-library", "draw" ]
I'm trying to make a `100x100` image with each pixel being a different random colour, like this example: ![enter image description here](http://i.stack.imgur.com/6CecU.jpg) I've tried to use `matplotlib` but I'm not having much luck. Should I maybe be using PIL?
This is simple with `numpy` and `pylab`. You can set the colormap to be whatever you like, here I use spectral. ``` from pylab import imshow, show, get_cmap from numpy import random Z = random.random((50,50)) # Test data imshow(Z, cmap=get_cmap("Spectral"), interpolation='nearest') show() ``` ![enter image descri...
100x100 image with random pixel colour
15,261,851
4
2013-03-07T02:14:25Z
15,262,028
10
2013-03-07T02:33:26Z
[ "python", "image", "matplotlib", "python-imaging-library", "draw" ]
I'm trying to make a `100x100` image with each pixel being a different random colour, like this example: ![enter image description here](http://i.stack.imgur.com/6CecU.jpg) I've tried to use `matplotlib` but I'm not having much luck. Should I maybe be using PIL?
If you want to create an image file (and display it elsewhere, with or without Matplotlib), you could use Numpy and PIL as follows: ``` import numpy, Image imarray = numpy.random.rand(100,100,3) * 255 im = Image.fromarray(imarray.astype('uint8')).convert('RGBA') im.save('result_image.png') ``` The idea here is to cr...
Apply different functions to different items in group object: Python pandas
15,262,134
8
2013-03-07T02:44:56Z
15,262,876
10
2013-03-07T04:05:53Z
[ "python", "function", "group-by", "pandas", "apply" ]
Suppose I have a dataframe as follows: ``` In [1]: test_dup_df Out[1]: exe_price exe_vol flag 2008-03-13 14:41:07 84.5 200 yes 2008-03-13 14:41:37 85.0 10000 yes 2008-03-13 14:41:38 84.5 69700 yes 2008-03-13 14:41:39 84.5 1200 yes 2008-03-13 14:42:00 84.5 1000 yes ...
Apply your own function: ``` In [12]: def func(x): exe_price = (x['exe_price']*x['exe_vol']).sum() / x['exe_vol'].sum() exe_vol = x['exe_vol'].sum() flag = True return Series([exe_price, exe_vol, flag], index=['exe_price', 'exe_vol', 'flag']) In [13]: test_...
Convert floating point number to certain precision, then copy to String
15,263,597
47
2013-03-07T05:14:46Z
15,263,850
13
2013-03-07T05:33:41Z
[ "python", "string", "floating-point" ]
I have a floating point number, say `135.12345678910`. I want to concatenate that value to a string, but only want `135.123456789`. With print, I can easily do this by doing something like: ``` print "%.9f" % numvar ``` with `numvar` being my original number. Is there an easy way to do this?
Using round: ``` >>> numvar = 135.12345678910 >>> str(round(numvar,9)) '135.123456789' >>> ```
Convert floating point number to certain precision, then copy to String
15,263,597
47
2013-03-07T05:14:46Z
15,263,885
58
2013-03-07T05:36:58Z
[ "python", "string", "floating-point" ]
I have a floating point number, say `135.12345678910`. I want to concatenate that value to a string, but only want `135.123456789`. With print, I can easily do this by doing something like: ``` print "%.9f" % numvar ``` with `numvar` being my original number. Is there an easy way to do this?
With python < 3 (e.g. 2.6 or 2.7), there are two ways to do so. ``` # Option one older_method_string = "%.9f" % numvar # Option two newer_method_string = "{:.9f}".format(numvar) ``` But note that for python versions above 3 (e.g. 3.2 or 3.3), option two is [preferred](http://docs.python.org/2/library/stdtypes.html#...
python gtk webkit display local html data
15,264,383
3
2013-03-07T06:14:30Z
15,264,506
7
2013-03-07T06:22:46Z
[ "python", "webkit" ]
is there any way to use the webkit engine in python, combined with GTK to display html data that is stored within a python file, for example ``` import webkit import gtk html = "<h1>This is HTML content</h1><p>I am displaying this in python</p" gobject.threads_init() win = gtk.Window() view = webkit.WebView() view.o...
Try: ``` view.load_html_string(html, '') ``` Ref: <http://webkitgtk.org/reference/webkit2gtk/unstable/WebKitWebView.html#webkit-web-view-load-html> Or, you can store your HTML in a file: ``` # Option 1 view.open('file:///path/to/file/page.html') # Option 2 uri = 'page.html' uri = os.path.realpath(uri) uri = urlpar...
Does Heroku no longer support Celery?
15,265,319
13
2013-03-07T07:21:38Z
15,280,203
53
2013-03-07T19:39:05Z
[ "python", "heroku", "celery", "amqp" ]
I was finally getting to the point where I had some free time and wanted to add Celery to my Python/Flask project on Heroku. However, almost all mentions of Celery from the Heroku docs are gone. There used to be article with a tutotial in the "Getting started with Django", but it's gone. Will "just doing it" myself wo...
I'm the owner of Python at Heroku. Celery is still fully supported. The documentation at the bottom of the Django guide was removed because it was out of date with the latest release of Celery (v3.0) and was fairly incomplete, in my opinion. I'm currently working on a new [Dev Center article](https://devcenter.heroku...
How to check if entry is file or folder using Python's standard library zipfile?
15,267,661
4
2013-03-07T09:38:53Z
15,267,890
8
2013-03-07T09:48:54Z
[ "python", "python-2.7", "zip", "zipfile" ]
I have a zip file and I need to check if a file is a folder or a file without extracting them. I could check it using `file_size` property of `infolist` if it is 0 but this is the same for a file with 0 size. So it is not useful. I looked on the [ZIP specification](http://www.pkware.com/documents/casestudies/APPNOTE.T...
How about checking if the filename ends with `/`?
Why XGrabKey generates extra focus-out and focus-in events?
15,270,420
35
2013-03-07T11:48:39Z
15,322,809
12
2013-03-10T13:34:37Z
[ "python", "linux", "x11", "xlib" ]
Does anyone know an xlib function to trap a keypress event without losing the original focus? How to get rid of it? (or "to use XGrabKey() without generating Grab-style focusout"?) (or "How to get rid of NotifyGrab and NotifyUngrab focus events at system level?) The XGrabKey will lose focus on key pressed and restor...
I looked at global hotkeys back in the early 90s for Irix, ultrix and solaris, as it had been easy to do on my Acorn BBC computer. Eventually we decided on solving this in a non-portable way on a level below xlib with some proprietary code. Since our software installation needed as superuser priviliges anyway, we were ...
Why XGrabKey generates extra focus-out and focus-in events?
15,270,420
35
2013-03-07T11:48:39Z
15,404,395
12
2013-03-14T08:30:10Z
[ "python", "linux", "x11", "xlib" ]
Does anyone know an xlib function to trap a keypress event without losing the original focus? How to get rid of it? (or "to use XGrabKey() without generating Grab-style focusout"?) (or "How to get rid of NotifyGrab and NotifyUngrab focus events at system level?) The XGrabKey will lose focus on key pressed and restor...
My current code(from <http://diyism-myboard.googlecode.com/files/myboard.py>): ``` disp=Display() screen=disp.screen() root=screen.root def grab_key(key, mod): key_code=string_to_keycode(key) #3rd: bool owner_events, 4th: pointer_mode, 5th: keyboard_mode, X.GrabModeSync, X.GrabModeAsync root.grab_key(key_...
Python mySQL Update, Working but not updating table
15,271,907
22
2013-03-07T13:00:22Z
15,271,977
50
2013-03-07T13:03:34Z
[ "python", "mysql", "sql-update", "mysql-connector-python" ]
I have a python script which needs to update a mysql database, I have so far: ``` dbb = MySQLdb.connect(host="localhost", user="user", passwd="pass", db="database") try: curb = dbb.cursor() curb.execute ("UPDATE RadioGroups SET CurrentState=1 WHERE RadioID=11") print "Row(s) were upda...
use ``` dbb.commit() ``` after `curb.execute ("UPDATE RadioGroups SET CurrentState=1 WHERE RadioID=11")` to commit all the changes that you 'loaded' into the mysql server
Python mySQL Update, Working but not updating table
15,271,907
22
2013-03-07T13:00:22Z
24,216,675
13
2014-06-14T04:48:10Z
[ "python", "mysql", "sql-update", "mysql-connector-python" ]
I have a python script which needs to update a mysql database, I have so far: ``` dbb = MySQLdb.connect(host="localhost", user="user", passwd="pass", db="database") try: curb = dbb.cursor() curb.execute ("UPDATE RadioGroups SET CurrentState=1 WHERE RadioID=11") print "Row(s) were upda...
As the @Lazykiddy pointed out, you have to commit your changes after you load them into the mysql. You could also use this approach to enable the auto commit setting, just after the MySQL connection initialization: ``` dbb.autocommit(True) ``` Then, it will automatically commit the changes you made during your code ...
python json dumps
15,272,421
6
2013-03-07T13:26:03Z
24,800,031
7
2014-07-17T09:42:13Z
[ "python" ]
i have the following string, need to turn it into a list without u'': ``` my_str = "[{u'name': u'squats', u'wrs': [[u'99', 8]], u'id': 2}]" ``` i can get rid of " by using ``` import ast str_w_quotes = ast.literal_eval(my_str) ``` then i do: ``` import json json.dumps(str_w_quotes) ``` and get ``` [{\"id\": 2, \...
This works but doesn't seem too elegant ``` import json json.dumps(json.JSONDecoder().decode(str_w_quotes)) ```
python union of multiple ranges
15,273,693
4
2013-03-07T14:25:23Z
15,273,749
7
2013-03-07T14:28:28Z
[ "python", "range", "union" ]
I have these ranges: ``` 7,10 11,13 11,15 14,20 23,39 ``` I need to perform a union of the overlapping ranges to give ranges that are not overlapping, so in the example: ``` 7,20 23,39 ``` I've done this in Ruby where I have pushed the start and end of the range in array and sorted them and then perform union of th...
Let's say, `(7, 10)` and `(11, 13)` result into `(7, 13)`: ``` a = [(7, 10), (11, 13), (11, 15), (14, 20), (23, 39)] b = [] for begin,end in sorted(a): if b and b[-1][1] >= begin - 1: b[-1] = (b[-1][0], end) else: b.append((begin, end)) ``` `b` is now ``` [(7, 20), (23, 39)] ``` **EDIT**: A...
ImportError in importing from sklearn: cannot import name check_build
15,274,696
31
2013-03-07T15:12:12Z
17,870,134
18
2013-07-25T22:53:14Z
[ "python", "numpy", "scipy", "scikit-learn" ]
I am getting the following error while trying to import from sklearn: ``` >>> from sklearn import svm Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> from sklearn import svm File "C:\Python27\lib\site-packages\sklearn\__init__.py", line 16, in <module> from . import check_build I...
``` >>> from sklearn import preprocessing, metrics, cross_validation Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> from sklearn import preprocessing, metrics, cross_validation File "D:\Python27\lib\site-packages\sklearn\__init__.py", line 31, in <module> from . import __check_b...
ImportError in importing from sklearn: cannot import name check_build
15,274,696
31
2013-03-07T15:12:12Z
26,255,358
42
2014-10-08T11:03:26Z
[ "python", "numpy", "scipy", "scikit-learn" ]
I am getting the following error while trying to import from sklearn: ``` >>> from sklearn import svm Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> from sklearn import svm File "C:\Python27\lib\site-packages\sklearn\__init__.py", line 16, in <module> from . import check_build I...
Worked for me after installing scipy.
Python indentation, allignment of IFs and ELSEs
15,275,628
2
2013-03-07T15:51:32Z
15,275,717
10
2013-03-07T15:55:17Z
[ "python", "syntax", "python-2.7", "indentation" ]
I am new to python and i am still strugling to understand how the sytnax works, how you need to allign your If and else to make it work correctly. How do i really know which else goes with which if? especially when using nested code blocks. In the code below for the else followed by the comment Prime! from what i unde...
The rule is very simple: the `else` clause must have the same indentation as the statement it refers to (most commonly, an `if` statement). Now, here: ``` for div in range(3, n, 2): if (n % div == 0): # not a prime n += 1 break else: ... ``` you are not using `if`-`else`, you are using [`for`-`else`]...
python return lists of continuous integers from list
15,276,156
4
2013-03-07T16:15:00Z
15,276,206
9
2013-03-07T16:17:17Z
[ "python", "lambda", "group-by", "itertools", "continuous" ]
I have a list of integers, and I want to generate a list containing a list of all the continuous integers. ``` #I have: full_list = [0,1,2,3,10,11,12,59] #I want: continuous_integers = [[0,1,2,3], [10,11,12], [59]] ``` I have the following which works, but seems like a poor way to do it: ``` sub_list = [] continuous...
You can use the following recipe: ``` from operator import itemgetter from itertools import groupby full_list = [0,1,2,3,10,11,12,59] cont = [map(itemgetter(1), g) for k, g in groupby(enumerate(full_list), lambda (i,x):i-x)] # [[0, 1, 2, 3], [10, 11, 12], [59]] ```
Django: How to disable ordering in model
15,276,825
4
2013-03-07T16:43:36Z
15,276,914
9
2013-03-07T16:47:32Z
[ "python", "django" ]
Let's say there is a model with default ordering described in Meta class ``` class People(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) middle_name = models.CharField(max_length=100) class Meta: ordering = (last_name, first_name) `...
You can just override by simply adding .order\_by() for example: ``` People.objects.all().order_by() ``` This will make sure that Meta ordering is overridden.
Update a dictionary with another dictionary, but only non-None values
15,277,307
2
2013-03-07T17:03:58Z
15,277,395
8
2013-03-07T17:07:44Z
[ "python" ]
From the python [documentation](http://docs.python.org/2/library/stdtypes.html#mapping-types-dict) I see that `dict` has an `update(...)` method, but it appears it does not take exceptions where I may not want to update the old dictionary with a new value. For instance, when the value is `None`. This is what I current...
You could use something like: ``` old = {1: 'one', 2: 'two'} new = {1: 'newone', 2: None, 3: 'new'} old.update( (k,v) for k,v in new.iteritems() if v is not None) # {1: 'newone', 2: 'two', 3: 'new'} ```
Setting (mocking) request headers for Flask app unit test
15,278,285
12
2013-03-07T17:53:23Z
15,281,179
17
2013-03-07T20:33:22Z
[ "python", "unit-testing", "flask" ]
Does anyone know of a way to set (mock) the User-Agent of the request object provided by FLask (Werkzeug) during unit testing? As it currently stands, when I attempt to obtain details such as the request.headers['User-Agent'] a KeyError is raised as the Flask test\_client() doesn't set these up. (See partial stack tra...
You need to pass in `environ_base` when you call `get()` or `post()`. E.g., ``` client = app.test_client() response = client.get('/your/url/', environ_base={'HTTP_USER_AGENT': 'Chrome, etc'}) ``` Then your `request.user_agent` should be whatever you pass in, and you can access it via `request.h...
What happens when you import a package?
15,280,157
15
2013-03-07T19:35:53Z
15,280,354
9
2013-03-07T19:47:16Z
[ "python", "memory-management", "heap-memory" ]
For efficiency's sake I am trying to figure out how python works with its heap of objects (and system of namespaces, but it is more or less clear). So, basically, I am trying to understand when objects are loaded into the heap, how many of them are there, how long they live etc. And my question is **when I work with a...
You have a few different questions here. . . ### About importing packages When you import a package, the sequence of steps is the same as when you import a module. The only difference is that the packages's code (i.e., the code that creates the "module code object") is the code of the package's `__init__.py`. So yes...
How to chain attribute lookups that might return None in Python?
15,280,511
10
2013-03-07T19:55:39Z
15,281,402
7
2013-03-07T20:47:12Z
[ "python" ]
My problem is a general one, how to chain a series of attribute lookups when one of the intermediate ones might return `None`, but since I ran into this problem trying to use Beautiful Soup, I'm going to ask it in that context. Beautiful Soup parses an HTML document and returns an object that can be used to access the...
The most straightforward way is to wrap in a `try`...`except` block. ``` try: title = soup.head.title.string except AttributeError: print "Title doesn't exist!" ``` There's really no reason to test at each level **when removing each test would raise the same exception in the failure case**. I would consider t...
classifying a series to a new column in pandas
15,281,320
6
2013-03-07T20:43:16Z
15,281,515
8
2013-03-07T20:53:56Z
[ "python", "pandas" ]
I want to be able to take my current set of data, which is filled with ints, and classify them according to certain criteria. The table looks something like this: ``` [in]> df = pd.DataFrame({'A':[0,2,3,2,0,0],'B': [1,0,2,0,0,0],'C': [0,0,1,0,1,0]}) [out]> A B C 0 0 1 0 1 2 0 0 2 3 2 1 3 2 0 0 4 0 0...
I can think of two ways. The first is to write a classifier function and then `.apply` it row-wise: ``` >>> import pandas as pd >>> df = pd.DataFrame({'A':[0,2,3,2,0,0],'B': [1,0,2,0,0,0],'C': [0,0,1,0,1,0]}) >>> >>> def classifier(row): ... if row["A"] > 0 and row["B"] == 0 and row["C"] == 0: ... ...
Custom data structures in Python
15,281,746
3
2013-03-07T21:05:48Z
15,281,895
12
2013-03-07T21:15:25Z
[ "python" ]
I'm quite new to Python and I need to make declare my own data structure, I'm a bit confused on how to do this though. I currently have: ``` class Particle: def __init__(self, mass, position, velocity, force): self.mass = mass self.position, self.velocity, self.force = position, velocity, force ...
First off, you should understand that `__getitem__` is syntactic sugar. It's nice to have, but if you don't need it, don't use it. `__getitem__` and `__setitem__` are basically if you want to be able to access items from your object using bracket notation like: ``` p= Particle(foo) bar = p[0] ``` if you don't need to...
Cannot figure out python selenium webdriver move_to_element functionality
15,281,887
4
2013-03-07T21:14:50Z
15,281,989
8
2013-03-07T21:21:27Z
[ "python", "selenium", "webdriver", "mouseover" ]
I looked at number of examples as well as source code for ActionChains and seemingly am using the code suggested in other examples for hover functionality, but still I cannot get over this exception. The code is as follows: ``` menu = browser.find_element_by_xpath("//nav/ul/li/a[@href='#'][.='Profile']") hover = Actio...
The first argument to `ActionChains` is the driver instance you use to control the browser, ie `browser` in this case. Try the following: ``` menu = browser.find_element_by_xpath("//nav/ul/li/a[@href='#'][.='Profile']") hover = ActionChains(browser).move_to_element(menu) hover.perform() ```
Setting matplotlib colorbar range
15,282,189
16
2013-03-07T21:33:28Z
15,282,215
21
2013-03-07T21:35:22Z
[ "python", "matplotlib" ]
I would like to set the matplotlib colorbar range. Here's what I have so far: ``` import numpy as np import matplotlib.pyplot as plt x = np.arange(20) y = np.arange(20) data = x[:-1,None]+y[None,:-1] fig = plt.gcf() ax = fig.add_subplot(111) X,Y = np.meshgrid(x,y) quadmesh = ax.pcolormesh(X,Y,data) plt.colorbar(quad...
Arg. It's always the last thing you try: ``` quadmesh.set_clim(vmin=0, vmax=15) ``` works.
Bug in Python's documentation?
15,283,821
9
2013-03-07T23:21:29Z
15,283,868
12
2013-03-07T23:25:32Z
[ "python", "import", "module" ]
I am reading <http://docs.python.org/2/tutorial/modules.html#more-on-modules> and wonder if the following is correct: > Modules can import other modules. It is customary but not required to > place all import statements at the beginning of a module (or script, > for that matter). **The imported module names are placed...
Yes, this is a documentation error. The `import` statement imports the names to the *current* namespace. Usually `import` is used outside of functions and classes, but as you've discovered, it does work within them. In your example function, the module is imported into the function's local namespace when the function i...
Python PIL struggles with uncompressed 16-bit TIFF images
15,284,601
8
2013-03-08T00:30:58Z
15,293,007
8
2013-03-08T11:32:31Z
[ "python", "python-imaging-library", "tiff" ]
My system is Mac OS X v10.8.2. I have several 2560x500 uncompressed 16-bit TIFF images (grayscale, unsigned 16-bit integers). I first attempt to load them using PIL (installed via Homebrew, version 1.7.8): ``` from PIL import Image import numpy as np filename = 'Rocks_2ptCal_750KHz_20ms_1ma_120KV_2013-03-06_20-02-12....
It turns out that Matplotlib handles 16-bit uncompressed TIFF images in *two* lines of code: ``` import matplotlib.pyplot as plt img = plt.imread(filename) # >>> img # array([[38948, 41457, 37714, ..., 61511, 61785, 61824], # [39704, 38083, 36690, ..., 61419, 60086, 61910], # [41449, 39169, 38178, ..., 60...
autopep8 with vim
15,285,032
7
2013-03-08T01:12:34Z
23,762,720
10
2014-05-20T14:33:09Z
[ "python", "vim", "pep8" ]
Is there a way to automatically apply [autopep8](https://github.com/hhatto/autopep8) to a file being edited in vim? I have the following [vimrc](https://github.com/mictadlo/vimrc4GO/blob/master/.vimrc). Thank you in advance.
The correct way of using autopep8 is to rely on vim "formatprg" settings. So you add the line below to vimrc: ``` au FileType python setlocal formatprg=autopep8\ - ``` Now when you select lines in python and hit `gq` (the default mapping unless you remapped it). It will filter the lines through `autopep8` and writes ...
Having trouble with my Fahrenheit to Celcius/Kelvin converter
15,285,086
3
2013-03-08T01:17:46Z
15,285,107
8
2013-03-08T01:19:49Z
[ "python", "math", "python-2.7" ]
``` # Fahrenheit to Celcius def f2c(): userInput = tempEntry.get().lower() thisEquation = "Fahrenheit to Celcius" if userInput == "": textWid.insert(END,"-- " + thisEquation + " --") textWid.insert(END,"\n") textWid.insert(END,temp_equations[thisEquation]) textWid.insert(...
`5 / 9` is your problem: ``` >>> 5 / 9 0 ``` In Python 2, dividing an integer by an integer yields an integer. You want to make at least one of the numbers a float: ``` >>> 5.0 / 9 0.5555555555555556 >>> 5.0 / 9.0 0.5555555555555556 ```
Lazy map function in Python
15,285,134
6
2013-03-08T01:22:36Z
15,285,146
24
2013-03-08T01:24:14Z
[ "python", "map", "iterator", "lazy-evaluation" ]
Is there a way of making `map` lazy? Or is there another implementation of it built-in in Python? I want something like this to work: ``` from itertools import count for x in map(lambda x: x**2, count()): print x ``` Of course, the above code won't end, but I'd like just to enter any condition (or more complex ...
use [`itertools.imap`](http://docs.python.org/2/library/itertools.html#itertools.imap) on Python 2.x or upgrade to Python 3.x You can also just use a simple generator expression that is far more pythonic: ``` foo = (x**2 for x in count()) ```
isPrime Function for Python Language
15,285,534
14
2013-03-08T02:12:11Z
15,285,588
32
2013-03-08T02:17:51Z
[ "python", "primes" ]
So I was able to solve this problem with a little bit of help from the internet and this is what I got: ``` def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True ``` But my question really is how to do it, but WHY. I understand that 1 is not considered a "pr...
Of many primality tests floating around the Internet, consider the following prime test: ``` def is_prime(n): if n == 2 or n == 3: return True if n < 2 or n%2 == 0: return False if n < 9: return True if n%3 == 0: return False r = int(n**0.5) f = 5 while f <= r: print '\t',f if n%f == 0: return Fa...
isPrime Function for Python Language
15,285,534
14
2013-03-08T02:12:11Z
15,285,602
16
2013-03-08T02:19:21Z
[ "python", "primes" ]
So I was able to solve this problem with a little bit of help from the internet and this is what I got: ``` def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True ``` But my question really is how to do it, but WHY. I understand that 1 is not considered a "pr...
With `n**.5`, you are not squaring n, but taking the square root. Consider the number 20; the integer factors are 1, 2, 4, 5, 10, and 20. When you divide 20 by 2 and get 10, you know that it is also divisible by 10, without having to check. When you divide it by 4 and get 5, you know it is divisible by both 4 and 5, w...
How to set default Python version in terminal on OS X 10.6.8?
15,285,592
10
2013-03-08T02:18:32Z
15,285,745
10
2013-03-08T02:35:47Z
[ "python", "osx" ]
I just downloaded python 2.7 on my mac which runs OS X 10.6.8. The previous version of python installed was 2.6. When I type `python` in the terminal it opens python version 2.6. I want it to open python 2.7 How do I make Python 2.7 open by default?
The easier solution is to install it via MacPorts: ``` sudo port install python_select port search python # Search for version you are looking for sudo port install python27 sudo port select --set python python27 ```
How to set default Python version in terminal on OS X 10.6.8?
15,285,592
10
2013-03-08T02:18:32Z
15,285,815
11
2013-03-08T02:43:02Z
[ "python", "osx" ]
I just downloaded python 2.7 on my mac which runs OS X 10.6.8. The previous version of python installed was 2.6. When I type `python` in the terminal it opens python version 2.6. I want it to open python 2.7 How do I make Python 2.7 open by default?
The python.org installers for Python 2.x on OS X by default modify shell profiles (for the standard shells like `bash` and `csh`) to add its framework `bin` directory to the front of your shell path. Assuming you did not deselect the option during installation, there should now be the following in your `.bash_profile` ...
Django self-referential foreign key
15,285,626
65
2013-03-08T02:22:10Z
15,285,656
105
2013-03-08T02:25:18Z
[ "python", "django", "django-orm" ]
I'm kind of new to webapps and database stuff in general so this might be a dumb question. I want to make a model ("CategoryModel") with a field that points to the primary id of another instance of the model (its parent). ``` class CategoryModel(models.Model): parentId = models.ForeignKey(CategoryModel) ``` How d...
You can pass in the name of a model as a string to ForeignKey and it will do the right thing. So: ``` parentId = models.ForeignKey("CategoryModel") ``` Or you can use the string "self" ``` parentId = models.ForeignKey("self") ```
Django self-referential foreign key
15,285,626
65
2013-03-08T02:22:10Z
15,285,661
26
2013-03-08T02:25:34Z
[ "python", "django", "django-orm" ]
I'm kind of new to webapps and database stuff in general so this might be a dumb question. I want to make a model ("CategoryModel") with a field that points to the primary id of another instance of the model (its parent). ``` class CategoryModel(models.Model): parentId = models.ForeignKey(CategoryModel) ``` How d...
You can use the string 'self' to indicate a self-reference. ``` class CategoryModel(models.Model): parentId = models.ForeignKey('self') ``` <https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey>
GoogleMaps API -address to coordinates (latitude,longitude)
15,285,691
12
2013-03-08T02:29:28Z
15,347,833
10
2013-03-11T20:20:05Z
[ "python", "google-maps", "google-geocoding-api" ]
This is driving me crazy. I have deleted this key 1000 times so far. Yesterday it worked like a charm, today not anymore Here is the python code: ``` from googlemaps import GoogleMaps gmaps = GoogleMaps("AIzaSyBIdSyB_td3PE-ur-ISjwFUtBf2O0Uo0Jo") exactaddress ="1 Toronto Street Toronto" lat, lng = gmaps.address_to_latl...
Although Google deprecated the V2 calls with googlemaps (which is why you're seeing the broken calls), they just recently announced that they are giving developers a six-month extension (until September 8, 2013) to move from the V2 to V3 API. See [Update on Geocoding API V2](http://googlegeodevelopers.blogspot.com/2013...
GoogleMaps API -address to coordinates (latitude,longitude)
15,285,691
12
2013-03-08T02:29:28Z
22,399,945
9
2014-03-14T08:42:12Z
[ "python", "google-maps", "google-geocoding-api" ]
This is driving me crazy. I have deleted this key 1000 times so far. Yesterday it worked like a charm, today not anymore Here is the python code: ``` from googlemaps import GoogleMaps gmaps = GoogleMaps("AIzaSyBIdSyB_td3PE-ur-ISjwFUtBf2O0Uo0Jo") exactaddress ="1 Toronto Street Toronto" lat, lng = gmaps.address_to_latl...
Since September 2013, Google Maps API v2 [no longer works](https://developers.google.com/maps/articles/geocodingupgrade). Here is the code working for API v3 (based on [this answer](http://stackoverflow.com/a/14582003/304209)): ``` import urllib import simplejson googleGeocodeUrl = 'http://maps.googleapis.com/maps/ap...
python 3 round function approximation
15,286,194
2
2013-03-08T03:26:25Z
15,286,217
9
2013-03-08T03:29:34Z
[ "python", "math", "python-3.x", "decimal", "rounding" ]
I am facing a problem with the round function of python. When I round with 2 digits by executing `round(0.715,2)` the answer is 0.71, similarly when I execute `round(0.615,2)` the result is 0.61. But when I execute `round(0.515,2)` it gives 0.52, similarly for `round(0.915,2)` the result is 0.92. Can someone explain t...
This is due to the [floating point](http://en.wikipedia.org/wiki/Floating_point#Representable_numbers.2C_conversion_and_rounding) approximations of the numbers you are using. There are only ~16 significant decimal digits. As you see the first two are slightly under and the second two are slightly over ``` >>> "%.20f"%...
Print multiple arguments in python
15,286,401
99
2013-03-08T03:51:48Z
15,286,409
183
2013-03-08T03:52:57Z
[ "python", "printing", "python-3.x", "arguments" ]
This is just a snippet of my code: ``` print("Total score for %s is %s ", name, score) ``` but I want it to print out: "Total score for (name) is (score)" where name is a variable in a list and score is an integer. This is python 3.3 if that helps at all.
Pass it as a tuple: ``` print("Total score for %s is %s " % (name, score)) ``` Or use the new-style string formatting: ``` print("Total score for {} is {}".format(name, score)) ``` Or pass the values as parameters and `print` will do it: ``` print("Total score for", name, "is", score) ``` If you don't want space...
Print multiple arguments in python
15,286,401
99
2013-03-08T03:51:48Z
25,029,092
7
2014-07-30T05:00:47Z
[ "python", "printing", "python-3.x", "arguments" ]
This is just a snippet of my code: ``` print("Total score for %s is %s ", name, score) ``` but I want it to print out: "Total score for (name) is (score)" where name is a variable in a list and score is an integer. This is python 3.3 if that helps at all.
just try: ``` print ( "Total score for", name,"is", score ) ```
Is it REALLY true that Python code runs faster in a function?
15,287,488
7
2013-03-08T05:42:51Z
15,288,493
10
2013-03-08T07:00:57Z
[ "python", "performance", "profiling", "benchmarking", "cpython" ]
I saw a comment that lead me to the question [Why does Python code run faster in a function?](http://stackoverflow.com/questions/11241523/why-does-python-code-run-faster-in-a-function). I got to thinking, and figured I would try it myself using the [`timeit`](http://docs.python.org/2/library/timeit.html) library, howe...
The flaw in your test is the way `timeit` compiles the code of your `stmt`. It's actually compiled within the following template: ``` template = """ def inner(_it, _timer): %(setup)s _t0 = _timer() for _i in _it: %(stmt)s _t1 = _timer() return _t1 - _t0 """ ``` Thus `stmt` is actually runn...
Why should Py_INCREF(Py_None) be required before returning Py_None in C?
15,287,590
13
2013-03-08T05:51:29Z
15,288,194
14
2013-03-08T06:38:58Z
[ "python", "c", "reference-counting" ]
Why should Py\_INCREF(Py\_None) be required before returning Py\_None in C as follows? ``` Py_INCREF(Py_None); return Py_None; ``` If Py\_INCREF(Py\_None) is omitted, what will happen?
Missing a `Py_INCREF` will result in an incorrect counting of references for `Py_None`, which may lead the interpreter to deallocate `Py_None`. Since `Py_None` is allocated statically in the `Objects/object.c` file: ``` PyObject _Py_NoneStruct = { _PyObject_EXTRA_INIT 1, &PyNone_Type }; ``` And in `Include/object...
Why should Py_INCREF(Py_None) be required before returning Py_None in C?
15,287,590
13
2013-03-08T05:51:29Z
15,288,314
11
2013-03-08T06:48:12Z
[ "python", "c", "reference-counting" ]
Why should Py\_INCREF(Py\_None) be required before returning Py\_None in C as follows? ``` Py_INCREF(Py_None); return Py_None; ``` If Py\_INCREF(Py\_None) is omitted, what will happen?
`Py_None` is really just another Python object, except without methods. Python will count the references to any `PyObject*`. It doesn't matter if it is a string, integer, or None. If you don't increment the reference count, the Python interpreter will eventually discard the object after its reference count hits `0`, ...
Update database with multiple SQL Statments
15,288,594
5
2013-03-08T07:09:29Z
15,291,171
14
2013-03-08T09:55:02Z
[ "python", "mysql", "database-connection", "mysql-python" ]
I am using mysql connector.Python 1.0.9 downloaded from MySQL site. I have a sample [table here](http://sqlfiddle.com/#!2/7a7cb5/1) ``` DROP TABLE IF EXISTS my_table; CREATE TABLE my_table (id INT NOT NULL AUTO_INCREMENT UNIQUE, Shot VARCHAR(4), sec varchar(5), lay VARCHAR(15) NOT NULL, lay_status VARCHAR(15) NOT NU...
At-last after a long research on docs and help. I could able to solve the issue. Here i am posting the solution so other can be benefited. using a for loop at cursur.execute with ,multi=True worked. i dont know why we need to loop through. ``` for result in cursor.execute(SQL,multi = True): pass ``` without loop...
How can I serve files with UTF-8 encoding using Python SimpleHTTPServer?
15,288,891
6
2013-03-08T07:31:11Z
24,517,632
11
2014-07-01T19:12:05Z
[ "python", "webserver" ]
I often use the following to quickly fire up a web server to serve HTML content from the current folder (for local testing): ``` python -m SimpleHTTPServer 8000 ``` Is there a reasonably simple way I can do this, but have the server serve the files with a UTF-8 encoding rather than the system default?
Had the same problem, the following code worked for me. To start a SimpleHTTPServer with UTF-8 encoding, simply copy/paste the following in terminal. ``` python -c "import SimpleHTTPServer; m = SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map; m[''] = 'text/plain'; m.update(dict([(k, v + ';charset=UTF-8') for...
Printing to stdout in IPython parallel processes
15,289,168
8
2013-03-08T07:51:32Z
15,302,196
8
2013-03-08T19:54:56Z
[ "python", "printing", "parallel-processing", "ipython", "ipython-parallel" ]
I'm new to IPython and would like to print intermediate results to stdout while running IPython parallel cluster functions. (I'm aware that with multiple processes, this might mangle the output, but that's fine--it's just for testing/debugging, and the processes I'd be running are long enough that such a collision is u...
It's actually more similar to `subprocess.Popen( ... , stdout=PIPE)` than you seem to be expecting. Just like the `Popen` object has a `stdout` attribute, which you can read to see the stdout of the subprocess, An AsyncResult has a `stdout` attribute that contains the stdout captured from the engines. It does differ in...
Pandas Dataframe output to JSON
15,291,153
5
2013-03-08T09:54:29Z
15,291,510
8
2013-03-08T10:12:45Z
[ "python", "json", "pandas" ]
I have a Pandas Dataframe with a DateTimeIndex and columns with hourly objects and I would like to transform and output a single column into a JSON file composed of an array of daily arrays of hourly values. A simple example: If I have the Dataframe: ``` In [106]: rng = pd.date_range('1/1/2011 01:00:00', periods=12...
``` import json import pandas as pd import numpy as np rng = pd.date_range('1/1/2011 01:00:00', periods=12, freq='H') df = pd.DataFrame(np.random.randn(12, 1), index=rng, columns=['A']) print json.dumps(df.T.as_matrix().tolist(),indent=4) ``` out: ``` [ [ -0.6916923670267555, 0.230752560080333...
I have 2 versions of python installed, but cmake is using older version. How do I force cmake to use the newer version?
15,291,500
14
2013-03-08T10:12:27Z
15,291,663
11
2013-03-08T10:20:01Z
[ "python", "python-2.7", "cmake" ]
I have 2 versions of python installed, but **cmake** is using older version. How do I force **cmake** to use the newer version?
Try to add `-DPYTHON_EXECUTABLE:FILEPATH=/path/to/python2.7` It might be a path problem? Also could specify the path to your python library,use your version that you want: ``` cmake -DPYTHON_LIBRARIES=/Library/Frameworks/Python.framework/Versions/2.7/lib/libpython2.7.dylib . ```
I have 2 versions of python installed, but cmake is using older version. How do I force cmake to use the newer version?
15,291,500
14
2013-03-08T10:12:27Z
16,045,924
9
2013-04-16T19:55:52Z
[ "python", "python-2.7", "cmake" ]
I have 2 versions of python installed, but **cmake** is using older version. How do I force **cmake** to use the newer version?
I had a similar problem, and resolved it using @Paul's answer as a hint. I needed to use `python2.7` to compile an older library, but `cmake` keeps picking up my `python3.2` libraries (and executable). First, I ran `cmake` with default options, then edited the `CMakeCache.txt` file which it generated. I did it this wa...
Overriding the default type() metaclass before Python runs
15,293,172
9
2013-03-08T11:41:10Z
15,392,133
8
2013-03-13T17:19:07Z
[ "python", "metaclass", "bytecode-manipulation" ]
**Here be dragons. You've been warned.** I'm thinking about creating a new library that will attempt to help write a better test suite. In order to do that one of the features is a feature that verifies that any object that is being used which isn't the test runner and the [system under test](http://xunitpatterns.co...
The following is not advisable, and you'll hit plenty of problems and cornercases implementing your idea, but on Python 3.1 and onwards, you can hook into the *custom* class creation process by overriding the `__build_class__` built-in hook: ``` import builtins _orig_build_class = builtins.__build_class__ class So...
Import constants from .h file into python
15,293,604
13
2013-03-08T12:04:12Z
15,293,726
11
2013-03-08T12:11:01Z
[ "python", "c", "header", "constants", "ctypes" ]
I've been looking for a simple answer to this question, but it seems that I can't find one. I would prefer to stay away from any external libraries that aren't already included in Python 2.6/2.7. I have 2 c header files that resemble the following: ``` //constants_a.h const double constant1 = 2.25; const double const...
I recommend using regular expressions (`re` module) to parse the information you want out of the files. Building a full C parser would be huge, but if you only use the variables and the file is reasonably simple/predictable/under control, then what you need to write is straightforward. Just watch out for 'gotcha' art...
Import constants from .h file into python
15,293,604
13
2013-03-08T12:04:12Z
15,504,090
9
2013-03-19T15:47:37Z
[ "python", "c", "header", "constants", "ctypes" ]
I've been looking for a simple answer to this question, but it seems that I can't find one. I would prefer to stay away from any external libraries that aren't already included in Python 2.6/2.7. I have 2 c header files that resemble the following: ``` //constants_a.h const double constant1 = 2.25; const double const...
In general, *defining* variables in C header file is poor style. The header file should only *declare* objects, leaving their definition for the appropriate ".c" source code file. One thing you may want to do is to declare the library-global constants like `extern const whatever_type_t foo;` and define (or "implement"...
Supervisor not working with Gunicorn + Flask
15,293,801
5
2013-03-08T12:15:21Z
15,293,953
8
2013-03-08T12:24:40Z
[ "python", "flask", "gunicorn", "supervisord" ]
I am trying to run Gunicorn from Supervisor in an Ubuntu 12.04 system. Gunicorn runs a Flask app (simple REST web service tested with Flask's embedded server). I have installed Gunicorn by clonning GIT repo, trying to avoid 'apt-get install' because it runs Gunicorn server when installs it. I do not want it running, it...
I don't see you setting the environment in your supervisor config file: ``` [program:gunicorn] environment=PYTHONPATH=/usr/local/bin:/usr/local/lib/project command=/usr/local/bin/gunicorn my_app:app -c /path/to/.gu_setup ... ``` If that doesn't work, try starting gunicorn in debug mode: ``` command=/usr/local/bin/gu...
Sort a list of tuples alphabetically (case-sensitive)
15,294,473
4
2013-03-08T12:54:37Z
15,294,530
9
2013-03-08T12:57:19Z
[ "python", "list", "sorting", "tuples" ]
I have a list of tuples ``` alist = [(u'First', 23), (u'Second', 64),(u'last', 19)] ``` I want to sort alphabetically (and case-sensitive) to get this: ``` (u'last', 19), (u'First', 23), (u'Second', 64) ``` I tried this: ``` sorted(alist, key=lambda x: x[0], reverse= True) ``` Unfortunately I get this: ``` (u'la...
Include a key that indicates if the first character is uppercase or not: ``` >>> sorted([(u'First', 23), (u'Second', 64),(u'last', 19)], key=lambda t: (t[0][0].isupper(), t[0])) [(u'last', 19), (u'First', 23), (u'Second', 64)] ``` `False` sorts before `True` so words with a lowercase initial will be sorted before wor...
How to calculate rolling cumulative product on Pandas DataFrame
15,295,434
7
2013-03-08T13:48:36Z
15,296,415
9
2013-03-08T14:34:55Z
[ "python", "pandas", "time-series", "finance" ]
I have a time series of returns, rolling beta, and rolling alpha in a pandas DataFrame. How can I calculate a rolling annualized alpha for the alpha column of the DataFrame? (I want to do the equivalent to =PRODUCT(1+[trailing 12 months])-1 in excel) ``` SPX Index BBOEGEUS Index Beta Alpha 2006-07-...
will this do? ``` import pandas as pd import numpy as np # your DataFrame; df = ... pd.rolling_apply(df, 12, lambda x: np.prod(1 + x) - 1) ```
django-registration app and Django 1.5 custom user model
15,296,295
11
2013-03-08T14:29:27Z
15,297,944
9
2013-03-08T15:51:34Z
[ "python", "django", "django-registration" ]
I use django-registration app and Django 1.5. How to create (new in django) custom user model and save also this data during registration (Please note that I am using django-registration): ``` class CustomProfile(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=255) bank = m...
django-registration's main fork is not compatible with django 1.5 for now. Check [this pull request](https://bitbucket.org/ubernostrum/django-registration/pull-request/36/fixes-for-15-use-templateview-and-the-new/diff). You have three options: * Patch django-registration's code. You can get the changes needed from t...
Computing where the overlap is
15,296,507
2
2013-03-08T14:40:05Z
15,296,578
7
2013-03-08T14:43:46Z
[ "python", "algorithm" ]
If you have two pairs of values, start and end- how do you compute where their overlap is? I.e if the pairs of start and end values are > [10, 20], [15, 20] In this case `compute_overlap((15,20),(10,20))` should return `(15,20)` because that is where the overlap is. What is the best way to do this?
If your intervals are `a, b` and `c, d`, i.e. ``` (a, b), (c, d) = [10, 20], [15, 20] ``` then the overlapping interval is ``` x, y = max(a, c), min(b, d) if x > y: # no overlap x, y = None, None ``` and the amount of overlap is `y - x` or `y - x + 1`, depending on whether your intervals are closed or [half-cl...
Python regex extract vimeo id from url
15,296,719
5
2013-03-08T14:51:16Z
15,296,847
10
2013-03-08T14:57:10Z
[ "python", "regex", "url", "vimeo" ]
``` embed_url = 'http://www.vimeo.com/52422837' response = re.search(r'^(http://)?(www\.)?(vimeo\.com/)?([\/\d+])', embed_url) return response.group(4) ``` The response is: ``` 5 ``` I was hoping for ``` 52422837 ``` Anybody an idea? I'm really bad with regexes :S
Don't reinvent the wheel! ``` >>> import urlparse >>> urlparse.urlparse('http://www.vimeo.com/52422837') ParseResult(scheme='http', netloc='www.vimeo.com', path='/52422837', params='', query='', fragment='') >>> urlparse.urlparse('http://www.vimeo.com/52422837').path.lstrip("/") '52422837' ```
improve in coding saving how to check if two line segments are crossing in Python
15,297,590
2
2013-03-08T15:33:46Z
15,307,103
13
2013-03-09T04:20:23Z
[ "python", "coding-style", "geometry", "line" ]
Consider the following example of crossing lines: ``` l1 = ((20,5),(40,20)) l2 = ((20,20),(40,5)) l3 = ((30,30),(30,5)) # vertical line ``` I developed the following code to compute the x,y of the crossing point (see theoretical details) ``` def gradient(l): """Returns gradient 'm' of a line""" m = None ...
Any code that returns the right answer is pretty awesome in my book. Well done. Here are a few suggestions: ``` def parallel(l1,l2): if gradient(l1) != gradient(l2): return False return True ``` can be written as ``` def parallel(l1,l2): return gradient(l1) == gradient(l2) ``` Similarly, ``` i...
Sending Mailgun Inline Images in HTML using Python Requests library
15,299,693
5
2013-03-08T17:18:48Z
15,302,750
7
2013-03-08T20:29:32Z
[ "python", "html", "email", "python-requests", "mailgun" ]
I am having trouble working out how I can send multiple inline messages using the Mailgun api, from a Python app using the requests library. Currently I have (using jinja2 for templates and flask as the webframework, hosted on Heroku): ``` def EmailFunction(UserEmail): Sender = 'testing@test.co.uk' Subject = '...
Sending Inline Images is documented [here](http://documentation.mailgun.net/user_manual.html?highlight=image#sending-inline-images). In the HTML, you'll reference the image like this: ``` <html>Inline image here: <img src="cid:test.jpg"></html> ``` Then, define a Multidict, to post the files to the API: ``` files=M...
How to use Python decorators to check function arguments?
15,299,878
18
2013-03-08T17:29:50Z
15,299,927
12
2013-03-08T17:32:41Z
[ "python", "python-decorators" ]
I would like to define some generic decorators to check arguments before calling some functions. Something like: ``` @checkArguments(types = ['int', 'float']) def myFunction(thisVarIsAnInt, thisVarIsAFloat) ''' Here my code ''' pass ``` Side notes: 1. Type checking is just here to show an example 2. I'm usi...
On Python 3.3, you can use function annotations and inspect: ``` import inspect def validate(f): def wrapper(*args): fname = f.__name__ fsig = inspect.signature(f) vars = ', '.join('{}={}'.format(*pair) for pair in zip(fsig.parameters, args)) params={k:v for k,v in zip(fsig.paramet...
How to use Python decorators to check function arguments?
15,299,878
18
2013-03-08T17:29:50Z
15,300,191
22
2013-03-08T17:49:24Z
[ "python", "python-decorators" ]
I would like to define some generic decorators to check arguments before calling some functions. Something like: ``` @checkArguments(types = ['int', 'float']) def myFunction(thisVarIsAnInt, thisVarIsAFloat) ''' Here my code ''' pass ``` Side notes: 1. Type checking is just here to show an example 2. I'm usi...
From the [Decorators for Functions and Methods](http://www.python.org/dev/peps/pep-0318/): ``` def accepts(*types): def check_accepts(f): assert len(types) == f.func_code.co_argcount def new_f(*args, **kwds): for (a, t) in zip(args, types): assert isinstance(a, t), \ ...
Difference between ManyToOneRel and ForeignKey?
15,300,422
12
2013-03-08T18:04:28Z
15,300,763
12
2013-03-08T18:24:52Z
[ "python", "database", "django" ]
In django, what's the difference between a ManyToOneRel and a ForeignKey field?
`ManyToOneRel` is not a `django.db.models.fields.Field`, it is a class that is used inside Django but not in the user code.
Difference between ManyToOneRel and ForeignKey?
15,300,422
12
2013-03-08T18:04:28Z
17,047,519
12
2013-06-11T15:07:41Z
[ "python", "database", "django" ]
In django, what's the difference between a ManyToOneRel and a ForeignKey field?
Django relations model exposes (and documents) only *OneToOneField*, *ForeignKey* and *ManyToManyField*, which corresponds to the inner * **OneToOneField** -> **OneToOneRel** * **ForeignKey** -> **ManyToOneRel** * **ManyToManyField** -> **ManyToManyRel** See source of *django.db.models.fields.related* for further det...
Python -- return, return None, and no return at all
15,300,550
126
2013-03-08T18:12:15Z
15,300,582
10
2013-03-08T18:13:33Z
[ "python", null, "return" ]
Consider three functions: ``` def my_func1(): print "Hello World" return None def my_func2(): print "Hello World" return def my_func3(): print "Hello World" ``` They all appear to return None. Are there any differences between how the returned value of these functions behave? Are there any reasons to pref...
They each return the same singleton `None` -- There is no functional difference. I think that it is reasonably idiomatic to leave off the `return` statement unless you need it to break out of the function early (in which case a bare `return` is more common), or return something other than `None`. It also makes sense a...
Python -- return, return None, and no return at all
15,300,550
126
2013-03-08T18:12:15Z
15,300,671
165
2013-03-08T18:19:21Z
[ "python", null, "return" ]
Consider three functions: ``` def my_func1(): print "Hello World" return None def my_func2(): print "Hello World" return def my_func3(): print "Hello World" ``` They all appear to return None. Are there any differences between how the returned value of these functions behave? Are there any reasons to pref...
On the actual behavior, there is no difference. They all return `None` and that's it. However, there is a time and place for all of these. The following instructions are basically how the different methods should be used (or atleast how I was taught they should be used), but they are not absolute rules so you can mix t...
Python -- return, return None, and no return at all
15,300,550
126
2013-03-08T18:12:15Z
15,300,733
12
2013-03-08T18:23:10Z
[ "python", null, "return" ]
Consider three functions: ``` def my_func1(): print "Hello World" return None def my_func2(): print "Hello World" return def my_func3(): print "Hello World" ``` They all appear to return None. Are there any differences between how the returned value of these functions behave? Are there any reasons to pref...
Yes, they are all the same. We can review the interpreted machine code to confirm that that they're all doing the exact same thing. ``` import dis def f1(): print "Hello World" return None def f2(): print "Hello World" return def f3(): print "Hello World" dis.dis(f1) 4 0 LOAD_CONST 1 ('Hello Wo...
Python argparse: default value or specified value
15,301,147
50
2013-03-08T18:49:46Z
15,301,183
74
2013-03-08T18:52:43Z
[ "python", "default-value", "argparse" ]
I would like to have a optional argument that will default to a value if only the flag is present with no value specified, but store a user-specified value instead of the default if the user specifies a value. Is there already an action available for this? An example: ``` python script.py --example # args.example wou...
``` import argparse parser = argparse.ArgumentParser() parser.add_argument('--example', nargs='?', const=1, type=int) args = parser.parse_args() print(args) ``` --- ``` % test.py Namespace(example=None) % test.py --example Namespace(example=1) % test.py --example 2 Namespace(example=2) ``` --- * `nargs='?'` means ...