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
Convert string into integer
8,143,363
2
2011-11-15T21:27:54Z
8,143,380
9
2011-11-15T21:29:18Z
[ "python", "string" ]
How can I convert string into integer and remove every character from that change. Example: `S = "--r10-"` I want to have this: `S = 10` This not work: ``` S = "--10-" int(S) ```
You can use `filter(str.isdigit, s)` to keep only those characters of `s` that are digits: ``` >>> s = "--10-" >>> int(filter(str.isdigit, s)) 10 ``` Note that this might lead to unexpected results for strings that contain multiple numbers ``` >>> int(filter(str.isdigit, "12 abc 34")) 1234 ``` or negative numbers ...
Use binary COPY table FROM with psycopg2
8,144,002
21
2011-11-15T22:21:19Z
8,150,329
23
2011-11-16T10:42:12Z
[ "python", "postgresql", "bulkinsert", "binary-data", "psycopg2" ]
I have tens of millions of rows to transfer from multidimensional array files into a PostgreSQL database. My tools are Python and psycopg2. The most efficient way to bulk instert data is using [`copy_from`](http://initd.org/psycopg/docs/cursor.html#cursor.copy_from). However, my data are mostly 32-bit floating point nu...
Here is the binary equivalent of COPY FROM for Python 3: ``` from io import BytesIO from struct import pack import psycopg2 # Two rows of data; "id" is not in the upstream data source # Columns: node, ts, val1, val2 data = [(23253, 342, -15.336734, 2494627.949375), (23256, 348, 43.23524, 2494827.949375)] con...
How to define a __str__ method for a class?
8,144,026
16
2011-11-15T22:23:41Z
8,144,039
24
2011-11-15T22:26:39Z
[ "python" ]
In Python, the `object` class serves as the root superclass for all the (new-style) classes. By default at least, applying `str` and `repr` to the "class instance" of any subclass of `object` produces the same result: ``` >>> class spam(object): pass ... >>> str(spam) "<class '__main__.spam'>" >>> str(spam) == repr(s...
Actually the same mechanism as for object instances applies for types. Types are just objects themselves, so they are converted to strings by calling the `__str__()` method on *their* type, which is called the "metaclass". So you have to overwrite the `__str__()` method on the metaclass: ``` class fancytype(type): ...
Turning off logging in Paramiko
8,144,545
14
2011-11-15T23:18:22Z
12,960,530
30
2012-10-18T17:42:04Z
[ "python", "logging", "paramiko" ]
I am using the ssh client provided by Paramiko to create a function call 'remoteSSH' (the file name is remoteConnect.py): ``` import paramiko import logging logger = paramiko.util.logging.getLogger() logger.setLevel(logging.WARN) def remoteSSH(username,userpasswd): .... ``` Now I am calling the remoteSSH functio...
Paramiko names its logggers. It seems to function as the logging modules in other languages (JDK logging comes to mind) do. I've found that `logging.getLogger("paramiko").setLevel(logging.WARNING)` helps. (You can put this inside the module that's importing paramiko - just make sure the 'logging' module is enabled a...
Django: How do I use a string as the keyword in a Q() statement?
8,144,582
5
2011-11-15T23:22:52Z
8,144,600
7
2011-11-15T23:25:29Z
[ "python", "django", "django-queryset" ]
I'm writing a simple search form for a certain model. Let's call the model `Orchard` and give it the attributes `apples`, `oranges`, and `pears`, just for the sake of demonstration. So, the form does not require all fields to be filled. So you can search on `apples` and `oranges` but not pears. I them need to filter l...
this is a general issue with using a variable as the key in a keyword arg. the solution is to wrap things in a dict and unpack it: ``` queries &= Q(**{key: options[key]}) ``` or in your case ``` for option in options: if options[option] is None: del(options[option]) # or otherwise only add the ones you a...
Modeling a linear system with Python
8,144,910
5
2011-11-15T22:17:08Z
8,856,101
12
2012-01-13T19:27:49Z
[ "simulation", "python", "modeling" ]
I would like to simulate/model a closed-loop, linear, time-invariant system (specifically a locked PLL approximation) with python. Each sub-block within the model has a known transfer function which is given in terms of complex frequency `H(s) = K / ( s * tau + 1 )`. Using the model, I would like to see how the system...
I know this is a bit old, but a search brought me to this question. I put this together when I couldn't find a good module for it. It's not much, but it's a good start if somebody else finds themselves here. ``` import matplotlib.pylab as plt import numpy as np import scipy.signal def bode(G,f=np.arange(.01,100,.01))...
Python - Conditionally Catching Exceptions
8,146,386
8
2011-11-16T03:41:48Z
8,146,401
15
2011-11-16T03:44:35Z
[ "exception", "exception-handling", "python" ]
Is it possible to conditionally catch exceptions in python? I would like to be able to write a function so that the caller can decide who handles the exception. Basically, I would like something like this: ``` def my_func(my_arg, handle_exceptions): try: do_something(my_arg) except Exception, e if han...
You can re-raise the exception if you don't want to handle it: ``` def my_func(my_arg, handle_exceptions): try: do_something(my_arg) except Exception, e: if not handle_exceptions: # preserve prior stack trace raise # Or, if you dont care about the stack prio...
How do I include Stripe library with Google App Engine
8,146,641
11
2011-11-16T04:15:25Z
8,146,837
12
2011-11-16T04:42:00Z
[ "python", "google-app-engine", "stripe-payments" ]
I am trying to implement Stripe payment <https://stripe.com/> in my app. I need to include this library <https://stripe.com/docs/libraries>. I downloaded and installed it on Lib/site-packages. I checked in IDLE and `import stripe` works. How do I include this in my app's folder?
Just place the `stripe` directory from the library in your app's root directory.
How to obtain better results using NLTK pos tag
8,146,748
7
2011-11-16T04:30:02Z
8,150,864
8
2011-11-16T11:24:17Z
[ "python", "nltk", "pos-tagger" ]
I am just learning nltk using Python. I tried doing pos\_tag on various sentences. But the results obtained are not accurate. How can I improvise the results ? ``` broke = NN flimsy = NN crap = NN ``` Also I am getting lot of extra words being categorized as NN. How can I filter these out to get better results.?
Give the context, there you obtained these results. Just as example, I'm obtaining other results with pos\_tag on the context phrase "They broke climsy crap": ``` import nltk text=nltk.word_tokenize("They broke flimsy crap") nltk.pos_tag(text) ``` > > > [('They', 'PRP'), ('broke', 'VBP'), ('flimsy', 'JJ'), ('crap', '...
How can i get query for .save() in django?
8,148,005
4
2011-11-16T07:15:39Z
8,148,116
7
2011-11-16T07:30:30Z
[ "python", "mysql", "django", "django-models" ]
I am updating a django model object. After setting value for each attribute when i call `obj.save()` it gaves me `OperationalError: (2006, 'MySQL server has gone away')`. I am desperate to know what is causing the following error. How can i get the the query?? As when save method fail because of above error it does not...
You can try ``` from django.db import connection connection.queries ``` it will give you list of all the queries that executed through Django (including .save()). To get your query you can do, ``` try: modelObj.save() except OperationalError: from django.db import connection print connection.queries[-1] ...
Regular expression: how to match a string containing "\n" (newline)?
8,150,745
3
2011-11-16T11:13:42Z
8,150,798
13
2011-11-16T11:19:36Z
[ "python", "regex", "escaping", "line-breaks" ]
I'm trying to dump data from a SQL export file with regular expression. To match the field of post content, I use '`(?P<content>.*?)`'. It works fine most of the time, but if the field contains the string of '\n' the regular expression wouldn't match. How can I modify the regular expression to match them? Thanks! Exam...
You should use `DOTALL` option: ``` >>> re.findall("'(?P<content>.*?)'","'<p>something, \n something else</p>'", re.DOTALL) ['<p>something, \n something else</p>'] ``` See [this](http://docs.python.org/release/3.1.3/library/re.html#re.DOTALL).
pybrain: how to print a network (nodes and weights)
8,150,772
9
2011-11-16T11:16:11Z
8,161,274
19
2011-11-17T02:12:47Z
[ "python", "neural-network", "pybrain" ]
finally I managed to train a network from a file :) Now I want to print the nodes and the weights, especially the weights, because I want to train the network with pybrain and then implement a NN somewhere else that will use it. I need a way to print the layers, the nodes and the weight between nodes, so that I can ea...
There are many ways to access the internals of a network, namely through its "modules" list or its "connections" dictionary. Parameters are stored within those connections or modules. For example, the following should print all this information for an arbitrary network: ``` for mod in net.modules: print("Module:",...
pybrain: how to print a network (nodes and weights)
8,150,772
9
2011-11-16T11:16:11Z
12,829,063
9
2012-10-10T21:57:31Z
[ "python", "neural-network", "pybrain" ]
finally I managed to train a network from a file :) Now I want to print the nodes and the weights, especially the weights, because I want to train the network with pybrain and then implement a NN somewhere else that will use it. I need a way to print the layers, the nodes and the weight between nodes, so that I can ea...
Try this, it worked for me: ``` def pesos_conexiones(n): for mod in n.modules: for conn in n.connections[mod]: print conn for cc in range(len(conn.params)): print conn.whichBuffers(cc), conn.params[cc] ``` The result should be like: ``` <FullConnection 'co1': 'hidd...
For loop with multiple conditions in Python
8,150,846
3
2011-11-16T11:22:50Z
8,150,880
8
2011-11-16T11:25:14Z
[ "python", "for-loop", "python-2.x" ]
I have 3 lists of equal sizes (List1,2 and 3). I want to iterate through the list and and perform operations on each of the items. Like ``` for x in List1, y in List2, z in List3: if(x == "X" or x =="x"): //Do operations on y elif(y=="Y" or y=="y"): //Do operations on x,z ``` So I want to tr...
``` import itertools for x, y, z in itertools.izip(List1, List2, List3): # ... ``` Or just `zip` in Python 3.
Ignore case in glob() on Linux
8,151,300
23
2011-11-16T11:59:04Z
8,151,371
15
2011-11-16T12:04:23Z
[ "python", "linux" ]
I'm writing a script which will have to work on directories which are modified by hand by Windows and Linux users alike. The Windows users tend to not care at all about case in assigning filenames. Is there a way to handle this on the Linux side in Python, i.e. can I get a case-insensitive, glob-like behaviour?
Use case-insensitive regexes instead of glob patterns. [`fnmatch.translate`](http://docs.python.org/library/fnmatch.html#fnmatch.translate) generates a regex from a glob pattern, so ``` re.compile(fnmatch.translate(pattern), re.IGNORECASE) ``` gives you a case-insensitive version of a glob pattern as a compiled RE. ...
Ignore case in glob() on Linux
8,151,300
23
2011-11-16T11:59:04Z
10,886,685
25
2012-06-04T18:57:06Z
[ "python", "linux" ]
I'm writing a script which will have to work on directories which are modified by hand by Windows and Linux users alike. The Windows users tend to not care at all about case in assigning filenames. Is there a way to handle this on the Linux side in Python, i.e. can I get a case-insensitive, glob-like behaviour?
You can replace each alphabetic character c with [cC], via ``` import glob def insensitive_glob(pattern): def either(c): return '[%s%s]'%(c.lower(),c.upper()) if c.isalpha() else c return glob.glob(''.join(map(either,pattern))) ```
Why can't I access a list by its key in Python?
8,151,469
2
2011-11-16T12:12:49Z
8,151,492
9
2011-11-16T12:14:19Z
[ "python", "list" ]
I am creating a list, and then accessing an element like this: ``` list = [] list.insert(42, "foo") list.insert(43, "bar") list.insert(44, "baz") print(list[43]) ``` And I have the folowing error: > print(list[43]) IndexError: list index out of range What is wrong ? Do I have to use a [dictionary](http://docs.py...
There are no "keys" in a list, there are just indices. The reason your code doesn't work the way you expect is that `list.insert(index, obj)` does not pad the list with "blank" entries when `index` is past the end of the list; it simply appends `obj` to the list. You could use a dictionary for this: ``` In [14]: d =...
How to read lines from mmap file in python?
8,151,684
14
2011-11-16T12:27:09Z
8,151,752
11
2011-11-16T12:32:21Z
[ "python", "file", "text", "mmap" ]
Is seems that the mmap interface only supports readline(). If I try to iterate over the object I get character instead of complete lines. What would be the "pythonic" method of reading a mmap'ed file line by line? ``` import sys import mmap import os if (len(sys.argv) > 1): STAT_FILE=sys.argv[1] print STAT_FILE...
I modified your example like this: ``` with open(STAT_FILE, "r+b") as f: m=mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ) while True: line=m.readline() if line == '': break print line.rstrip() ``` **Suggestions:** * do not call a variable `map`, this is ...
How to read lines from mmap file in python?
8,151,684
14
2011-11-16T12:27:09Z
8,152,106
13
2011-11-16T13:01:55Z
[ "python", "file", "text", "mmap" ]
Is seems that the mmap interface only supports readline(). If I try to iterate over the object I get character instead of complete lines. What would be the "pythonic" method of reading a mmap'ed file line by line? ``` import sys import mmap import os if (len(sys.argv) > 1): STAT_FILE=sys.argv[1] print STAT_FILE...
The most concise way to iterate of the lines of a `mmap` is ``` with open(STAT_FILE, "r+b") as f: map = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ) for line in iter(map.readline, ""): # whatever ```
open persian url domains with urllib2
8,152,161
4
2011-11-16T13:06:49Z
8,152,700
8
2011-11-16T13:49:44Z
[ "python", "url", "utf-8" ]
i'm trying to open an url http://الاعلي-للاتصالات.قطر/ar/news-events/event/future-internet-privacy with the urllib2.urlopen but it reports always an error. The similar occurs to http://الاعلي-للاتصالات.قطر/ar ... other pages (chinese ones) are opened ok. Any ideas to point me to th...
As @Donal says, the URL has to be [punycoded](http://en.wikipedia.org/wiki/Punycode). Luckily Python includes this already. Here is a sample Python code ``` domain = "الاعلي-للاتصالات.قطر" domain_unicode = unicode(domain, "utf8") domain_idna = domain_unicode.encode("idna") urllib2.urlopen("http://" +...
How to do string formatting with unicode emdash?
8,152,820
3
2011-11-16T13:58:26Z
8,152,840
7
2011-11-16T14:00:15Z
[ "python", "unicode", "string-formatting" ]
I am trying do string formatting with a unicode variable. For example: ``` >>> x = u"Some text—with an emdash." >>> x u'Some text\u2014with an emdash.' >>> print(x) Some text—with an emdash. >>> s = "{}".format(x) Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'ascii' ...
The new `format()` is not as forgiving when you mix ASCII and unicode strings ... so try this: ``` s = u"{}".format(x) ```
Js Date object to python datetime
8,153,631
9
2011-11-16T14:53:31Z
8,154,033
10
2011-11-16T15:20:31Z
[ "javascript", "python", "parsing", "datetime", "date" ]
I am working with dhtmlxscheduler and I am sending dates to the django server for processing. Dhtmlxscheduler provides me with the following date object, the methods provided start from the second line below: ``` end_date: Sat Nov 19 2011 01:00:00 GMT-0500 (EST) __proto__: Invalid Date constructor: function Date() { ...
toUTCString() gives: ``` "Tue, 22 Nov 2011 06:00:00 GMT" ``` And that's parsible with: ``` datetime.strptime("Tue, 22 Nov 2011 06:00:00 GMT", "%a, %d %b %Y %H:%M:%S %Z") ```
How to fix this AttributeError?
8,153,823
6
2011-11-16T15:06:35Z
8,154,127
16
2011-11-16T15:27:26Z
[ "python", "html", "google-app-engine", "html-parsing", "attributeerror" ]
I installed a stripe package yesterday and now my app is not running. I am trying to understand where the problem is. Is it something to do with `PyShell` or `HTLParser` or something else. I am posting with GAE tag as well hoping that the trace from logs may give a clue about the problem: ``` MLStripper instance has n...
There are one or two issues with the code you posted (mainly to do with initializing the `HTMLParser` properly). Try running this amended version of your script: ``` from HTMLParser import HTMLParser class MLStripper(HTMLParser): def __init__(self): # initialize the base class HTMLParser.__init__...
Drawing a correlation graph in matplotlib
8,154,511
8
2011-11-16T15:51:05Z
8,156,383
14
2011-11-16T17:58:41Z
[ "python", "graph", "matplotlib", "data-visualization" ]
Suppose I have a data set of discrete vectors with `n=2`: ``` DATA = [ ('a', 4), ('b', 5), ('c', 5), ('d', 4), ('e', 2), ('f', 5), ] ``` How can I plot that data set with matplotlib so as to visualize any correlation between the two variables? Any simple code examples would be great.
Joe Kington has the correct answer, but your `DATA` probably is more complicated that is represented. It might have multiple values at 'a'. The way Joe builds the x axis values is quick but would only work for a list of unique values. There may be a faster way to do this, but this how I accomplished it: ``` import mat...
How can I write text over an image, and overlay another image on it, in Python?
8,154,825
4
2011-11-16T16:10:42Z
8,154,867
9
2011-11-16T16:13:20Z
[ "python", "png", "python-imaging-library" ]
I need to put some text over a PNG image in Python, I need to put another image too over the first one. So I'll have a base image (the same for every image created), a logo to put over it in the upper left corner, and a text all over the image (non-specific font, I just need to set the font size). Could I use PIL, or...
PIL can do it: ``` import PIL from PIL import ImageFont from PIL import Image from PIL import ImageDraw font = ImageFont.truetype("/usr/share/fonts/dejavu/DejaVuSans.ttf", 25) img = Image.new("RGBA", (200,200), (120,20,20)) draw = ImageDraw.Draw(img) draw.text((0,0), "This is a test", (255,255,0), font=font) draw = Im...
Can't resolve WindowsError: [Error 2] The system cannot find the file specified
8,155,945
9
2011-11-16T17:26:06Z
8,155,985
13
2011-11-16T17:28:47Z
[ "python" ]
I'm trying to rename all the pictures in a directory. I need to add a couple of pre-pending zero's to the filename. I'm new to Python and I have written the following script. ``` import os path = "c:\\tmp" dirList = os.listdir(path) for fname in dirList: fileName = os.path.splitext(fname)[0] fileName = "00" ...
You should pass the absolute path to `os.rename`. Right now your only passing the filename itself. It isn't looking in the correct place. Use [`os.path.join`](http://docs.python.org/library/os.path.html). Try this: ``` import os path = "c:\\tmp" dirList = os.listdir(path) for fname in dirList: fileName = os.pat...
How to run own daemon processes with Django?
8,156,470
10
2011-11-16T18:05:09Z
8,156,560
12
2011-11-16T18:12:00Z
[ "python", "django", "cron", "command", "daemon" ]
In my Django project I have to do repeatedly some processing in the background. This processing needs access to Django stuff, so I put it into Django's commands and run it as cronjob. Right now I realize, that I have to do some of them more frequently (cronjob has limitation to invoke command at most every 1 minute). A...
We do a lot of background processing for django using Celery <http://celeryproject.org/>. It requires some effort to set up and there is a bit of a learning curve, but once it's up and running it's just awesome.
gzip a file in Python
8,156,707
14
2011-11-16T18:25:41Z
8,156,724
9
2011-11-16T18:27:38Z
[ "python", "gzip", "subprocess" ]
I want to gzip a file in Python. I am trying to use the subprocss.check\_call(), but it keeps failing with the error 'OSError: [Errno 2] No such file or directory'. Is there a problem with what I am trying here? Is there a better way to gzip a file than using subprocess.check\_call? ``` from subprocess import check_ca...
Try this: ``` check_call(['gzip', fullFilePath]) ``` Depending on what you're doing with the data of these files, Skirmantas's link to <http://docs.python.org/library/gzip.html> may also be helpful. Note the examples near the bottom of the page. If you aren't needing to access the data, or don't have the data already...
gzip a file in Python
8,156,707
14
2011-11-16T18:25:41Z
8,156,730
34
2011-11-16T18:28:00Z
[ "python", "gzip", "subprocess" ]
I want to gzip a file in Python. I am trying to use the subprocss.check\_call(), but it keeps failing with the error 'OSError: [Errno 2] No such file or directory'. Is there a problem with what I am trying here? Is there a better way to gzip a file than using subprocess.check\_call? ``` from subprocess import check_ca...
There is a module [gzip](http://docs.python.org/library/gzip.html). Usage: Example of how to create a compressed GZIP file: ``` import gzip content = "Lots of content here" f = gzip.open('/home/joe/file.txt.gz', 'wb') f.write(content) f.close() ``` Example of how to GZIP compress an existing file: ``` import gzip f...
gzip a file in Python
8,156,707
14
2011-11-16T18:25:41Z
11,524,322
23
2012-07-17T14:10:04Z
[ "python", "gzip", "subprocess" ]
I want to gzip a file in Python. I am trying to use the subprocss.check\_call(), but it keeps failing with the error 'OSError: [Errno 2] No such file or directory'. Is there a problem with what I am trying here? Is there a better way to gzip a file than using subprocess.check\_call? ``` from subprocess import check_ca...
In Python 2.7 format: ``` import gzip with open("path/to/file", 'rb') as orig_file: with gzip.open("path/to/file.gz", 'wb') as zipped_file: zipped_file.writelines(orig_file) ``` --- Even shorter (Tested on python 2.7.6) ``` with open('path/to/file') as src, gzip.open('path/to/file.gz', 'wb') as dst: ...
Tail -f log on server, process data, then serve to client via twisted
8,157,197
9
2011-11-16T19:04:50Z
8,159,506
7
2011-11-16T22:15:12Z
[ "python", "twisted" ]
Goal: Show data from server in wxPython GUI on client Newcomer to Twisted. I have a wxPython GUI running on a Windows 7 client, and I have a program running on an Ubuntu server that produces a log. My current attempt is to tail -f the log, pipe the output to a twisted server, then serve any data that meets my regex co...
You've got a few different easily separated goals you're trying to achieve here. First, I'll talk about watching the log file. Your generator has a couple problems. One of them is big - it calls `time.sleep(0.1)`. The `sleep` function blocks for the amount of time passed to it. While it is blocking, the thread which c...
Handling capturing groups in re.sub?
8,157,267
28
2011-11-16T19:10:35Z
8,157,317
36
2011-11-16T19:14:26Z
[ "python", "regex" ]
I want to take the string `0.71331, 52.25378` and return `0.71331,52.25378` - i.e. just look for a digit, a comma, a space and a digit, and strip out the space. This is my current code: ``` coords = '0.71331, 52.25378' coord_re = re.sub("(\d), (\d)", "\1,\2", coords) print coord_re ``` But this gives me `0.7133,2.25...
You should be using raw strings for regex, try the following: ``` coord_re = re.sub(r"(\d), (\d)", r"\1,\2", coords) ``` With your current code, the backslashes in your replacement string are escaping the digits, so you are replacing all matches the equivalent of `chr(1) + "," + chr(2)`: ``` >>> '\1,\2' '\x01,\x02' ...
Handling capturing groups in re.sub?
8,157,267
28
2011-11-16T19:10:35Z
8,157,333
7
2011-11-16T19:15:28Z
[ "python", "regex" ]
I want to take the string `0.71331, 52.25378` and return `0.71331,52.25378` - i.e. just look for a digit, a comma, a space and a digit, and strip out the space. This is my current code: ``` coords = '0.71331, 52.25378' coord_re = re.sub("(\d), (\d)", "\1,\2", coords) print coord_re ``` But this gives me `0.7133,2.25...
Python interprets the `\1` as a character with ASCII value 1, and passes that to `sub`. Use raw strings, in which Python doesn't interpret the `\`. ``` coord_re = re.sub(r"(\d), (\d)", r"\1,\2", coords) ``` This is covered right in the beginning of the [`re` documentation](http://docs.python.org/library/re.html), sh...
Alternative to TCP/IP for local program-to-program data streaming?
8,157,348
2
2011-11-16T19:16:55Z
8,157,428
8
2011-11-16T19:22:26Z
[ "c++", "python", "linux", "networking", "gcc" ]
I have a GNU C++ program and a python script that need to pass strings to each other quite frequently (~70-80 messages a minute). They will run local to each other in CentOS (hosted in the same environment). It feels that although TCP/IP can and will get the job done, what other options do I have? Keep in mind that I ...
If you already have a TCP or UDP server, the easiest way will probably be to switch to UNIX domain sockets. They come in "stream" and "datagram" modes, just like TCP/UDP sockets, and they're always local, as they use the filesystem namespace (instead of port numbers like TCP/UDP).
How to render django form field in template
8,157,509
11
2011-11-16T19:30:21Z
8,158,847
11
2011-11-16T21:17:58Z
[ "python", "django", "django-forms", "django-templates", "django-template-filters" ]
I want to make a page with a list of users and checkboxes that signal if a user is selected, which will apply some action to selected users. I created a form class which looks like this: ``` #in forms.py class UserSelectionForm(forms.Form): """form for selecting users""" def __init__(self, userlist, *args, **k...
You're making the template far too complicated. Add a label to each field when you create it in the form's `__init__` method. ``` for f in userlist: self.fields[str(f.id)] = forms.BooleanField(label=f.username, initial=False) ``` Then just loop over the fields in the form and don't worry about the `userlist` anym...
Can I iterate over several dicts in succession without merging them?
8,158,298
4
2011-11-16T20:36:28Z
8,158,335
10
2011-11-16T20:38:42Z
[ "python", "dictionary", "for-loop" ]
In python, let's say I have three dicts: ``` d1, d2, d3 = {...}, {...}, {...} ``` I need to iterate over each of them and perform the same operation: ``` for k, v in d1.iteritems(): do_some_stuff(k, v) for k, v in d3.iteritems(): do_some_stuff(k, v) for k, v in d3.iteritems(): do_some_stuff(k, v) ``` Is...
You want [`chain`](http://docs.python.org/2/library/itertools.html#itertools.chain): ``` from itertools import chain for k,v in chain(d1.iteritems(), d2.iteritems(), d3.iteritems()): do_some_stuff(k, v) ``` or more general ``` ds = d1,d2,d3 for k,v in chain.from_iterable(d.iteritems() for d in ds): do_some_...
Python: Return tuple or list?
8,159,107
6
2011-11-16T21:38:07Z
8,159,151
22
2011-11-16T21:42:27Z
[ "python" ]
I have a method that returns either a list or a tuple. What is the most pythonic way of denoting the return type in the argument? ``` def names(self, section, as_type=()): return type(as_type)(([m[0] for m in self.items(section)])) ```
The pythonic way would be not to care about the type at all. Return a tuple, and if the calling function needs a list, then let it call `list()` on the result. Or vice versa, whichever makes more sense as a default type. Even better, have it return a generator expression: ``` def names(self, section): return (m[0...
datetime to Unix timestamp with millisecond precision
8,160,246
14
2011-11-16T23:32:34Z
8,160,307
28
2011-11-16T23:39:19Z
[ "python", "datetime" ]
I'm trying to do something really simple, convert a `datetime` object three days into the future into a Unix UTC timestamp: ``` import datetime, time then = datetime.datetime.now() + datetime.timedelta(days=3) # Method 1 print then.strftime("%s") # Method 2 print time.mktime(then.timetuple()) # Method 3 print time.mk...
Datetime objects have a field named `microsecond`. So one way to achieve what you need is: ``` time.mktime(then.timetuple())*1e3 + then.microsecond/1e3 ``` This returns milliseconds since UNIX epoch with the required precision.
Drawing ellipses on matplotlib basemap projections
8,161,144
12
2011-11-17T01:50:41Z
8,177,559
18
2011-11-18T03:52:27Z
[ "python", "matplotlib" ]
I am trying to draw ellipses on a basemap projection. To draw a circle like polygon there is the `tissot` function used to draw [Tissot's indicatrix'](http://en.wikipedia.org/wiki/Tissot%27s_indicatrix) as illustrates the following example. ``` from mpl_toolkits.basemap import Basemap x0, y0 = 35, -50 R = 5 m = Base...
After hours analyzing the source code of basemap's `tissot` function, learning some properties of [ellipses](http://en.wikipedia.org/wiki/Ellipse) and lot's of debugging, I came with a solution to my problem. I've extended the basemap class with a new function called `ellipse` as follows, ``` from __future__ import di...
How can I specify library versions in setup.py?
8,161,617
23
2011-11-17T03:06:06Z
8,161,816
27
2011-11-17T03:40:43Z
[ "python", "buildout" ]
In my `setup.py` file, I've specified a few libraries needed to run my project: ``` setup( # ... install_requires = [ 'django-pipeline', 'south' ] ) ``` How can I specify required versions of these libraries?
I'm not sure about buildout, however, for setuptools/distribute, you specify version info with the comparison operators (like `==`, `>=`, or `<=`). For example: ``` install_requires = ['django-pipeline==1.1.22', 'south>=0.7'] ```
What are the mature CMSs and Blogs built on web2py?
8,161,644
11
2011-11-17T03:11:02Z
8,162,554
7
2011-11-17T05:30:58Z
[ "python", "web2py", "django-cms" ]
In search of technologies for developing web applications and portals, I recently dabbled into Ruby and Python (from a non-sysadmin point of view .. ie, towards web application development) and immediately fell in love with python. I have since wanted to only spend time on python based technology for everything (LOL). ...
Make sure you've got the current version, [Instant Press 2.0](https://bitbucket.org/mulonemartin/instantpress/overview). Here's a recent [video](http://www.youtube.com/watch?v=vGkR246URRk). Unfortunately, I don't think there's much documentation, though I believe Martin (the creator) is working on that. Note, IP 2.0 is...
Analyzing string input until it reaches a certain letter on Python
8,162,021
7
2011-11-17T04:12:42Z
8,162,059
12
2011-11-17T04:18:31Z
[ "python", "string", "input", "edit" ]
I need help in trying to write a certain part of a program. The idea is that a person would input a bunch of gibberish and the program will read it till it reaches an "!" (exclamation mark) so for example: ``` input("Type something: ") ``` *Person types: wolfdo65gtornado!salmontiger223* If I ask the program to print...
The built-in [`str.partition()`](https://docs.python.org/2/library/stdtypes.html#str.partition) method will do this for you. Unlike [`str.split()`](https://docs.python.org/2/library/stdtypes.html#str.split) it won't bother to cut the rest of the `str` into different `str`s. ``` text = raw_input("Type something:") left...
Python - Locating the closest timestamp
8,162,379
8
2011-11-17T05:05:15Z
8,162,408
20
2011-11-17T05:10:10Z
[ "python", "algorithm", "search", "timestamp" ]
I have a Python datetime timestamp and a large dict (index) where keys are timestamps and the values are some other information I'm interested in. I need to find the datetime (the key) in index that is closest to timestamp, as efficiently as possible. At the moment I'm doing something like: ``` for timestamp in time...
Dictionaries aren't organized for efficient near miss searches. They are designed for exact matches (using a [hash table](http://en.wikipedia.org/wiki/Hash_table)). You may be better-off maintaining a separate, fast-searchable ordered structure. A simple way to start off is to use the [bisect module](http://docs.pyth...
python logging specific level only
8,162,419
14
2011-11-17T05:11:18Z
8,163,115
26
2011-11-17T06:41:40Z
[ "python" ]
I'm logging events in my python code uing the python logging module. I have 2 logging files I wish to log too, one to contain user information and the other a more detailed log file for devs. I've set the the two logging files to the levels I want (usr.log = INFO and dev.log = ERROR) but cant work out how to restrict t...
I am in general agreement with David, but I think more needs to be said. To paraphrase [The Princess Bride](http://www.imdb.com/title/tt0093779/quotes) - I do not think this code means what you think it means. Your code has: ``` logger1 = logging.getLogger('') ... logger2 = logging.getLogger('') ``` which means that ...
How can I use Python 2.6 in Ubuntu 11.10?
8,163,018
9
2011-11-17T06:30:40Z
8,163,211
7
2011-11-17T06:53:19Z
[ "python", "ubuntu", "pydev" ]
The default version of Python on Ubuntu 11.10 is 2.7, but I'm looking for 2.6. How do I make it default and where is the executable located? I type `which python2.6` but it returns nothing, yet I did have a python2.6 folder under `/usr/lib/python2.6`. But it doesn't look like the python2.7 which is at the same path `/...
You can install the package `python2.6` (`apt-get install python2.6`). At this point, the default version of Python will still be 2.7. You can change this via ``` ln -s /usr/bin/python2.6 /usr/bin/python ``` Note that there's a decent chance this could cause problems with your system. Several scripts assume the defau...
Running Fabric with Python script together
8,165,470
9
2011-11-17T10:17:42Z
8,166,050
18
2011-11-17T11:05:06Z
[ "python", "ssh", "fabric" ]
I see most of the Fabric API are use together with function. Example of file (sample.py): ``` from fabric.api import * print "Hello" def deploy(): with settings(hosts_string="Remote", user = "ubuntu", key_filename="/home/ubuntu/key.pem"): put('/home/localuser/sample.sh', '/home/ubuntu/') run('bas...
To answer your question directly, you can add this snippet to your file: ``` from fabric.api import * print "Hello" def deploy(): with settings(host_string="Remote", user = "ubuntu", key_filename="/home/ubuntu/key.pem"): put('/home/localuser/sample.sh', '/home/ubuntu/') run('bash /home/ubuntu/samp...
How to pass a function and its arguments through a wrapper function in R? Similar to *args and *kwargs in python
8,165,837
7
2011-11-17T10:47:17Z
8,165,894
10
2011-11-17T10:52:19Z
[ "python", "argument-passing" ]
I want to write a wrapper function in R. I should take a function and its arguments. Do something, and then call the function with the supplied arguments. I know how to do it in python, but I search for an implementation in R. In python I would write: ``` def wrapper(func, *args, **kwargs): #do something here ...
``` wrapper <- function(func, ...) { func(...) } ```
Mocking file objects or iterables in python
8,166,633
9
2011-11-17T11:51:12Z
8,168,742
10
2011-11-17T14:27:55Z
[ "python", "tdd", "mocking", "python-mock" ]
Which way is proper for mocking and testing code that iters object returned by [open()](http://docs.python.org/library/functions.html#open), using [mock](http://www.voidspace.org.uk/python/mock/) library? `whitelist_data.py`: ``` WHITELIST_FILE = "testdata.txt" format_str = lambda s: s.rstrip().lstrip('www.') whitel...
You're looking for a `MagicMock`. This supports iteration. In mock 0.80beta4, `patch` returns a `MagicMock`. So this simple example works: ``` import mock def foo(): for line in open('myfile'): print line @mock.patch('__builtin__.open') def test_foo(open_mock): foo() assert open_mock.called ``` ...
Why is bool a subclass of int?
8,169,001
52
2011-11-17T14:43:36Z
8,169,049
60
2011-11-17T14:46:31Z
[ "python", "boolean" ]
When storing a bool in memcached through python-memcached I noticed that it's returned as an integer. Checking the code of the library showed me that there is a place where `isinstance(val, int)` is checked to flag the value as an integer. So I tested it in the python shell and noticed the following: ``` >>> isinstan...
From a comment on <http://www.peterbe.com/plog/bool-is-int> > It is perfectly logical, if you were around when the bool type was > added to python (sometime around 2.2 or 2.3). > > Prior to introduction of an actual bool type, 0 and 1 were the > official representation for truth value, similar to C89. To avoid > unnec...
Why is bool a subclass of int?
8,169,001
52
2011-11-17T14:43:36Z
8,169,072
22
2011-11-17T14:47:52Z
[ "python", "boolean" ]
When storing a bool in memcached through python-memcached I noticed that it's returned as an integer. Checking the code of the library showed me that there is a place where `isinstance(val, int)` is checked to flag the value as an integer. So I tested it in the python shell and noticed the following: ``` >>> isinstan...
See [PEP 285 -- Adding a bool type](http://www.python.org/dev/peps/pep-0285/). Relevent passage: > 6) Should bool inherit from int? > > => Yes. > > In an ideal world, bool might be better implemented as a > separate integer type that knows how to perform mixed-mode > arithmetic. However, inheriting bool from int eases...
Pythonic way of checking if several elements are in a list
8,169,074
5
2011-11-17T14:48:00Z
8,169,105
13
2011-11-17T14:49:53Z
[ "list", "python" ]
I have this piece of code in Python: ``` if 'a' in my_list and 'b' in my_list and 'c' in my_list: # do something print my_list ``` Is there a more pythonic way of doing this? Something like (invalid python code follows): ``` if ('a', 'b', 'c') individual_in my_list: # do something print my_list ```
``` if set("abc").issubset(my_list): # whatever ```
Pythonic way of checking if several elements are in a list
8,169,074
5
2011-11-17T14:48:00Z
8,169,106
10
2011-11-17T14:50:00Z
[ "list", "python" ]
I have this piece of code in Python: ``` if 'a' in my_list and 'b' in my_list and 'c' in my_list: # do something print my_list ``` Is there a more pythonic way of doing this? Something like (invalid python code follows): ``` if ('a', 'b', 'c') individual_in my_list: # do something print my_list ```
The simplest form: ``` if all(x in mylist for x in 'abc'): pass ``` Often when you have a lot of items in those lists it is better to use a data structure that can look up items without having to compare each of them, like a `set`.
SQLAlchemy expects an object, but finds a Table
8,170,333
12
2011-11-17T16:05:20Z
9,558,936
28
2012-03-04T21:23:23Z
[ "python", "sqlalchemy" ]
I'm currently starting with sqlalchemy. In my current project I have to do some part with Flask and some other part from the command line. The part about flask is running fine, interfacing with sqlalchemy and all, but the commandline part is not. The error I'm getting is ``` ArgumentError("Class object expected, got ...
I have seen that error before if I forget that `ForeignKey()` takes the name of a database table-and-field but that `relationship()` takes the name of an ORM class instead. That is, I sometimes write: ``` movie_id = Column(Integer, ForeignKey('movie.id')) movie = relationship('movie') # WRONG! # Exception: "SQLAlchem...
Get a list of python packages used by a Django Project
8,170,914
7
2011-11-17T16:42:23Z
8,172,441
7
2011-11-17T18:38:54Z
[ "python", "django" ]
Is there any easy way to get a list of python packages used by a Django project? I've looked at snakefood and [this question](http://stackoverflow.com/questions/5219711/list-python-packages-consumed-by-an-application), but neither seem to play nicely within the django environment. Ideally I'm looking for a command I ...
This isn't a complete answer but hopefully it'll make a sensible starting point. From what I can tell, the dependencies of a django project (apart from django itself and its dependencies`*`) consists of: 1. Modules imported by your django project 2. Apps loaded by your project via `settings.INSTALLED_APPS` (and their...
Python LDAP Search
8,170,924
4
2011-11-17T16:43:15Z
8,182,267
8
2011-11-18T12:16:16Z
[ "python", "search", "ldap" ]
I've been reading on how to search LDAP servers using Python, but Ive been stuck for hours and Im not sure why. This is my first time trying to use this sort of API. Heres how I open the connection and try to search: ``` aims_server = '#####.com' base_dn = 'cn=EMPLOYEES,cn=portal,cn=Groups,dc=Company,dc=com' ...
I finally did it and it only took me over 5 hours. Every time I messed around with a configuration I learnt a bit more but I basically had to try every combination to get it to work. It turns out that I was probably being too specific with the base\_dn, so I changed that to a higher level ``` base_dn = 'cn=users,dc=...
Understanding global object persistence in Python WSGI apps
8,170,973
9
2011-11-17T16:46:20Z
8,176,843
14
2011-11-18T01:50:22Z
[ "python", "google-app-engine", "wsgi", "webapp2" ]
Consider the following code in my WebApp2 application in Google App Engine: ``` count = 0 class MyHandler(webapp2.RequestHandler): def get(self): global count count = count + 1 print count ``` With each refresh of the page, the count increments higher. I'm coming from the PHP world whe...
Your understanding is correct. If you want variables that persist for the duration of the request, you shouldn't make them globals at all - make them instance variables on your RequestHandler class, accessed as `self.var`. Since a new RequestHandler is instantiated for each request, your variables will stick around exa...
Strip string after third occurrence of character python
8,170,982
4
2011-11-17T16:46:39Z
8,171,258
19
2011-11-17T17:05:29Z
[ "python" ]
I want to strip all characters after a third character, say - for instance. I found this code online and it works but I'm having trouble learning how it works and wanted to ask so I can understand it fully. ``` def indexList(s, item, i=0): """ Return an index list of all occurrances of 'item' in string/list ...
Here is a way: ``` def trunc_at(s, d, n=3): "Returns s truncated at the n'th (3rd by default) occurrence of the delimiter, d." return d.join(s.split(d)[:n]) print trunc_at("115Z2113-3-777-55789ABC7777", "-") ``` How it works: 1. The string `s` is split into a list at each occurrence of the delimiter `d` usi...
python lxml - modify attributes
8,171,146
10
2011-11-17T16:57:32Z
8,171,456
11
2011-11-17T17:19:14Z
[ "python", "xml", "lxml" ]
``` from lxml import objectify, etree root = etree.fromstring('''<?xml version="1.0" encoding="ISO-8859-1" ?> <scenario> <init> <send channel="channel-Gy"> <command name="CER"> <avp name="Origin-Host" value="router1dev"></avp> <avp name="Origin-Realm" value="realm.dev"></avp> ...
``` import lxml.etree as et tree = et.fromstring(''' ... your xml ... ''') for host_ip in tree.xpath("/scenario/init/send/command[@name='CER']/avp[@name='Host-IP-Address']"): host_ip.attrib['value'] = 'foo' print et.tostring(tree) ```
How do you accept any URL in a Python Bottle server?
8,171,618
11
2011-11-17T17:31:26Z
8,189,597
15
2011-11-18T21:48:46Z
[ "python", "bottle" ]
Using a Bottle Sehttp://bottlepy.org/docs/dev/routing.html#wildcard-filters I'd like to accept any url, and then do something with the url. e.g. ``` @bottle.route("/<url:path>") def index(url): return "Your url is " + url ``` This is tricky because URLs have slashes in them, and Bottle splits by slashes.
Based on new Bottle (v0.10), use a re filter: ``` @bottle.route("/<url:re:.+>") ``` You can do that with old parameters too: ``` @bottle.route("/:url#.+#") ```
How do I convert tuple of tuples to list in one line (pythonic)?
8,171,751
5
2011-11-17T17:40:54Z
8,171,994
7
2011-11-17T17:59:13Z
[ "list", "cursor", "tuples", "python" ]
``` query = 'select mydata from mytable' cursor.execute(query) myoutput = cursor.fetchall() print myoutput (('aa',), ('bb',), ('cc',)) ``` Why is it (cursor.fetchall) returning a tuple of tuples instead of a tuple since my query is asking for only one column of data? What is the best way of converting it to `['aa',...
This works as well: ``` >>> tu = (('aa',), ('bb',), ('cc',)) >>> import itertools >>> list(itertools.chain(*tu)) ['aa', 'bb', 'cc'] ``` **Edit** `Could you please comment on the cost tradeoff? (for loop and itertools)` Itertools is significantly faster: ``` >>> t = timeit.Timer(stmt="itertools.chain(*(('aa',), ('bb...
MIMEText UTF-8 encode problems when sending email
8,171,856
10
2011-11-17T17:49:24Z
8,173,543
25
2011-11-17T20:05:50Z
[ "python", "email", "python-3.x", "unicode", "utf-8" ]
Here is a part of my code which sends an email: ``` servidor = smtplib.SMTP() servidor.connect(HOST, PORT) servidor.login(user, usenha) assunto = str(self.lineEdit.text()) para = str(globe_email) texto = self.textEdit.toPlainText() textos = str(texto) corpo = MIMEText(textos.encode('utf-8'), _charset='utf...
It seems that, in python3, a [`Header`](http://docs.python.org/py3k/library/email.header.html#email.header.Header) object is needed to encode a `Subject` as "utf-8": ``` >>> from email.mime.text import MIMEText >>> from email.header import Header >>> s = 'ação' >>> m = MIMEText(s.encode('utf-8'), 'plain', 'utf-8') >...
How do you make the linewidth of a single line change as a function of x in matplotlib?
8,172,312
6
2011-11-17T18:25:54Z
8,173,469
8
2011-11-17T20:00:13Z
[ "python", "matplotlib" ]
Does anyone know how to make the linewidth of a single line change as a function of x in matplotlib? For example, how would you make a line thin for small values of x, and thick for large values of x?
Basically, you need to use a polygon instead of a line. As a quick example: ``` import numpy as np import matplotlib.pyplot as plt # Make the original line... x = np.linspace(0, 10, 100) y = 2 * x thickness = 0.5 * np.abs(np.sin(x) * np.cos(x)) plt.fill_between(x, y - thickness, y + thickness, color='blue') plt.show...
Python Regex replace
8,172,861
23
2011-11-17T19:11:03Z
8,172,930
26
2011-11-17T19:16:09Z
[ "python", "regex" ]
Hey I'm trying to figure out a regular expression to do the following. Here is my string ``` Place,08/09/2010,"15,531","2,909",650 ``` I need to split this string by the comma's. Though due to the comma's used in the numerical data fields the split doesn't work correctly. So I want to remove the comma's in the numbe...
``` >>> from StringIO import StringIO >>> import csv >>> r = csv.reader(StringIO('Place,08/09/2010,"15,531","2,909",650')) >>> r.next() ['Place', '08/09/2010', '15,531', '2,909', '650'] ```
Python Regex replace
8,172,861
23
2011-11-17T19:11:03Z
8,173,098
47
2011-11-17T19:29:27Z
[ "python", "regex" ]
Hey I'm trying to figure out a regular expression to do the following. Here is my string ``` Place,08/09/2010,"15,531","2,909",650 ``` I need to split this string by the comma's. Though due to the comma's used in the numerical data fields the split doesn't work correctly. So I want to remove the comma's in the numbe...
``` new_string = re.sub(r'"(\d+),(\d+)"', r'\1.\2', original_string) ``` This will substitute the `,` inside the quotes with a `.` and you can now just use the strings split method.
Data from a MATLAB .fig file using Python?
8,172,931
6
2011-11-17T19:16:19Z
8,175,713
8
2011-11-17T23:12:29Z
[ "python", "matlab" ]
Does anyone know of any methods of extracting the data from a MATLAB fig file using Python? I know these are binary files but the methods in the Python Cookbook for .mat files <http://www.scipy.org/Cookbook/Reading_mat_files> don't seem to work for .fig files... Thanks in advance for any help, Dan
.fig files are .mat files (containing a struct), see <http://undocumentedmatlab.com/blog/fig-files-format/> As the reference you give states, structs are only supported up to v7.1: <http://www.scipy.org/Cookbook/Reading_mat_files> So, in MATLAB I save using -v7: ``` plot([1 2],[3 4]) hgsave(gcf,'c','-v7'); ``` Then...
Determine if JSON parsing was successful in python
8,173,514
2
2011-11-17T20:03:36Z
8,173,546
7
2011-11-17T20:05:55Z
[ "python", "json" ]
What kind of exceptions can I expect to be thrown if I try to parse invalid JSON with `json.load`? I couldn't find this in the documentation anywhere.
Why not try it ;) ``` >>> json.loads('ewrwerw') ValueError: No JSON object could be decoded ``` Grepping for `raise` in the sourcecode of the `json` module will also show that nothing but `ValueError` is raised. --- In case you use `simplejson`: ``` class JSONDecodeError(ValueError): ``` So catching `ValueError` ...
Does realloc actually shrink buffers in common implementations?
8,174,278
10
2011-11-17T21:04:43Z
8,174,535
15
2011-11-17T21:26:07Z
[ "python", "c", "memory-management", "numpy", "malloc" ]
In common implementations such as Linux/Glibc, Windows/MSVC and BSD/Mac OS X, will ``` void *p = malloc(N + M); // assume this doesn't fail p = realloc(p, N); // nor this ``` for `N`, `M > 0`, actually shrink the buffer returned by `malloc` in the `realloc` call, in the sense that up to `M` bytes may return t...
I can say about Linux/glibc. In the source code it contains comments like this: > if `n` is for fewer bytes than already held by `p`, the newly unused > space is lopped off and freed if possible. if you look at code of glibc, it contains lines like this: ``` remainder_size = newsize - nb; if (remainder_size < MIN...
How to combine callLater and addCallback?
8,174,437
8
2011-11-17T21:17:22Z
8,175,796
18
2011-11-17T23:22:36Z
[ "python", "twisted" ]
This is so broken, I hope you are merciful with me: ``` reactor.callLater(0, myFunction, parameter1).addCallback(reactor.stop) reactor.run() ``` `myFunction` returns a deferred. I hope it is clear what I want to do: * as soon as the reactor is running, I want to call `myFunction`. That is why I am using 0 as the de...
`IReactorTime.callLater` and `Deferred` are mixed together by `twisted.internet.task.deferLater`. ``` from twisted.internet import reactor, task d = task.deferLater(reactor, 0, myFunction, parameter1) d.addCallback(lambda _: reactor.stop()) reactor.run() ```
Dictionary creation with fromkeys and mutable objects. A surprise
8,174,723
14
2011-11-17T21:39:59Z
8,174,807
14
2011-11-17T21:47:28Z
[ "python" ]
I came to this behavior that surprised me: Python 2.6 and 3.2 ``` >>> xs = dict.fromkeys(range(2), []) >>> xs {0: [], 1: []} >>> xs[0].append(1) >>> xs {0: [1], 1: [1]} ``` However, dict comprehensions in 3.2 show a more polite demeanor: ``` >>> xs = {i:[] for i in range(2)} >>> xs {0: [], 1: []} >>> xs[0].append(1...
Your Python 2.6 example is equivalent to the following, which may help to clarify: ``` >>> a = [] >>> xs = dict.fromkeys(range(2), a) ``` If the default value in `fromkeys()` is a mutable object, each entry in the resulting dictionary will have a reference to the same object, as you've seen. ``` >>> xs[0] is a and x...
QTreeView Checkboxes
8,175,122
11
2011-11-17T22:12:54Z
8,178,567
17
2011-11-18T06:24:12Z
[ "c++", "python", "qt", "checkbox", "pyqt" ]
I know this has been asked a bunch of times, but I cant seem to find anything relevant. Using [the simpletreemodel tutorial](http://doc.qt.io/qt-4.8/qt-itemviews-simpletreemodel-example.html) that comes packaged with Qt, how would I add checkboxes?
Firstly, you'll need to modify TreeItem to keep track of the checked state: ``` private: ... bool checked; ``` and a setter and getter: ``` bool isChecked() const { return checked; } void setChecked( bool set ) { checked = set; } ``` Now the model will need to be modified so that the view knows about the ch...
QTreeView Checkboxes
8,175,122
11
2011-11-17T22:12:54Z
15,592,362
11
2013-03-23T21:37:06Z
[ "c++", "python", "qt", "checkbox", "pyqt" ]
I know this has been asked a bunch of times, but I cant seem to find anything relevant. Using [the simpletreemodel tutorial](http://doc.qt.io/qt-4.8/qt-itemviews-simpletreemodel-example.html) that comes packaged with Qt, how would I add checkboxes?
I converted the above to PyQt for my own purposes and figured I'd share. ``` def data(self, index, role): if not index.isValid(): return None item = index.internalPointer(); if role == Qt.CheckStateRole and index.column() == self.check_col: return int( Qt.Checked if item.isChecked() else ...
Get cookie from CookieJar by name
8,175,928
9
2011-11-17T23:37:38Z
27,523,891
9
2014-12-17T10:52:41Z
[ "python", "cookies", "cookiejar", "cookielib" ]
I know that I can iterate through the cookies in a cookiejar, and this would allow me to find a cookie with a particular name - but does the CookieJar object itself have any methods I can call to get a certain cookie by name? It just saves me having to write a helper method that already exists.
Yes, the `__iter__` method will go through each cookie in `CookieJar`. ``` for cookie in cj: print cookie.name, cookie.value, cookie.domain #etc etc ``` A cookie is not just a name and value pair. In its long list (17) of properties, there is `domain` and `path`. A domain value of `.ibm.com` would be applicable to...
How can I handle a boto exception in python?
8,176,002
7
2011-11-17T23:45:31Z
12,064,611
27
2012-08-21T23:47:07Z
[ "python", "boto" ]
How can I wrap a `boto.storage_uri()` call in python so I can handle possible exceptions?
Your question about Boto is a good one, not not easy to answer. The Boto exception hierarchy is poorly designed, and ultimately the only way to determine what the exception you want to trap is requires looking at the boto source code. For example if you look at (on Ubuntu) /usr/share/pyshared/boto/exception.py you wil...
Tornado Restful Handler Classes
8,176,185
8
2011-11-18T00:09:58Z
12,389,016
14
2012-09-12T13:13:04Z
[ "python", "rest", "tornado", "handlers" ]
I've read around and found [this answered question](http://stackoverflow.com/questions/5560638/what-is-the-best-rest-implemenation-when-using-tornado-requesthandlers) about a problem relating to this but what I really want to know is how to implement this structure and how many handler classes I need: ``` 1 GET /i...
Well, it is largely stylistic. Each request handler in this situation represents the removal of an if statement from one of your methods. I think it can be clearer to limit the number of RequestHandlers. The clearest results I think can be achieved with one handler and three routes. I've also thrown away your item 3. ...
OrderedDict performance (compared to deque)
8,176,513
14
2011-11-18T00:55:52Z
8,177,061
22
2011-11-18T02:26:51Z
[ "python", "performance", "algorithm", "optimization" ]
I've been trying to performance optimize a BFS implementation in Python and my original implementation was using deque to store the queue of nodes to expand and a dict to store the same nodes so that I would have efficient lookup to see if it is already open. I attempted to optimize (simplicity and efficiency) by movi...
Both *deque* and *dict* are implemented in C and will run faster than *OrderedDict* which is implemented in pure Python. The advantage of the *OrderedDict* is that it has O(1) getitem, setitem, and delitem just like regular dicts. This means that it scales very well, despite the slower pure python implementation. Com...
Python: Creating a filter function
8,176,862
2
2011-11-18T01:53:17Z
8,176,897
8
2011-11-18T01:58:29Z
[ "python", "list", "function" ]
I'm trying to create a function: ``` filter(delete,lst) ``` When someone inputs: ``` filter(1,[1,2,1]) ``` returns `[2]` What I have come up with was to use the list.remove function but it only deletes the first instance of delete. ``` def filter(delete, lst): """ Removes the value or string of delete from the ...
Try with list comprehensions: ``` def filt(delete, lst): return [x for x in lst if x != delete] ``` Or alternatively, with the built-in filter function: ``` def filt(delete, lst): return filter(lambda x: x != delete, lst) ``` And it's better *not* to use the name `filter` for your function, since that's the...
Python ZipFile path separators
8,176,953
5
2011-11-18T02:09:36Z
8,177,003
13
2011-11-18T02:17:52Z
[ "python", "zip", "zipfile" ]
If I am unzipping a Zip file with the Python ZipFile library, where the file was created on Windows, but my code is running on Unix-like, will the path separators always be Unix-style?
Internally, ZipFile stores forward slashes as required by the [zip file specification](http://www.pkware.com/documents/casestudies/APPNOTE.TXT). Externally, they get translated using [os.sep](https://docs.python.org/2.7/library/os.html#os.sep) so it will match what is normally expected on a given platform. Code refer...
Python: Maximum recursion depth exceeded
8,177,073
50
2011-11-18T02:30:05Z
8,177,274
101
2011-11-18T03:10:40Z
[ "python", "recursion", "max", "depth", "tree-traversal" ]
I have the following recursion code, at each node I call sql query to get the nodes belong to the parent node. here is the error: ``` Exception RuntimeError: 'maximum recursion depth exceeded' in <bound method DictCursor.__del__ of <MySQLdb.cursors.DictCursor object at 0x879768c>> ignored RuntimeError: maximum recur...
You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this: ``` import sys sys.setrecursionlimit(10000) # 10000 is an example, try with different values ``` ... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.
Python: take the content of a list and append it to another list
8,177,079
64
2011-11-18T02:31:23Z
8,177,090
133
2011-11-18T02:33:34Z
[ "python", "list" ]
I am trying to understand if it makes sense to take the content of a list and append it to another list. I have the first list created trough a loop function, that will get specific lines out of a file and will save them in a list. Then a second list is used to save these lines, and start a new cycle over another fil...
You probably want ``` list2.extend(list1) ``` instead of ``` list2.append(list1) ``` Here's the difference: ``` >>> a = range(5) >>> b = range(3) >>> c = range(2) >>> b.append(a) >>> b [0, 1, 2, [0, 1, 2, 3, 4]] >>> c.extend(a) >>> c [0, 1, 0, 1, 2, 3, 4] ``` Since `list.extend()` accepts an arbitrary iterable, y...
How to subclass Python list without type problems?
8,180,014
18
2011-11-18T09:05:43Z
8,180,073
14
2011-11-18T09:10:53Z
[ "python", "list", "subclass" ]
I want to implement a custom list class in Python as a subclass of `list`. What is the minimal set of methods I need to override from the base `list` class in order to get full type compatibility for all list operations? [This question](http://stackoverflow.com/questions/2235556/python-subclass-builtin-list) suggest t...
You should probably read these two sections from the documentation: * [Emulating container types](http://docs.python.org/reference/datamodel.html#emulating-container-types) * [Additional methods for emulating sequence types](https://docs.python.org/2.7/reference/datamodel.html#additional-methods-for-emulation-of-seque...
How to subclass Python list without type problems?
8,180,014
18
2011-11-18T09:05:43Z
8,180,577
13
2011-11-18T09:54:26Z
[ "python", "list", "subclass" ]
I want to implement a custom list class in Python as a subclass of `list`. What is the minimal set of methods I need to override from the base `list` class in order to get full type compatibility for all list operations? [This question](http://stackoverflow.com/questions/2235556/python-subclass-builtin-list) suggest t...
Firstly, I recommend you follow [Björn Pollex's advice](http://stackoverflow.com/questions/8180014/how-to-subclass-python-list-without-type-problems/8180073#8180073) (+1). To get past this particular problem (`type(l2 + l3) == CustomList`), you need to implement a custom [`__add__()`](http://docs.python.org/reference...
Set Timeout for Pika ioloop async (RabbitMQ)
8,180,596
3
2011-11-18T09:56:09Z
8,181,008
9
2011-11-18T10:32:52Z
[ "python", "rabbitmq", "pika" ]
I need to be able to gracefully stop a consumer (worker) who works in a Pika ioloop. The worker should stop after 60 seconds. Currently processed messages should be finished. I tried to put a `connection.close()` inside the callback function but that only stopped the current thread and not the complete ioloop. And it ...
You can attach a timeout call-back function on the opened connection. Here is the extra code for your example. ``` timeout = 60 def on_timeout(): global connection connection.close() connection.add_timeout(timeout, on_timeout) ```
Mocking a class: Mock() or patch()?
8,180,769
50
2011-11-18T10:11:28Z
8,182,480
74
2011-11-18T12:32:36Z
[ "python", "unit-testing", "mocking" ]
I am using [mock](http://www.voidspace.org.uk/python/mock/index.html) with Python and was wondering which of those two approaches is better (read: more pythonic). **Method one**: Just create a mock object and use that. The code looks like: ``` def test_one (self): mock = Mock() mock.method.return_value = True...
[`mock.patch`](http://www.voidspace.org.uk/python/mock/patch.html) is a very very different critter than `mock.Mock`. `patch` **replaces** the class with a mock object and lets you work with the mock instance. Take a look at this snippet: ``` >>> class MyClass(object): ... def __init__(self): ... print 'Created ...
Java abstract/interface design in Python
8,181,576
14
2011-11-18T11:21:06Z
8,181,859
34
2011-11-18T11:42:03Z
[ "java", "python", "interface", "abstract-class" ]
I have a number of classes which all share the same methods, only with different implementations. In Java, it would make sense to have each of these classes implement an interface or extend an abstract class. Does Python have anything similar to this, or should I be taking an alternative approach?
There's a bit of a story behind interfaces in Python. The original attitude, which held sway for many years, is that you don't need them: Python works on the EAFP (easier to ask forgiveness than permission) principle. That is, instead of specifying that you accept an, I dunno, ICloseable object, you simply try to `clos...
How do I autosize text in matplotlib python?
8,182,124
8
2011-11-18T12:04:30Z
8,188,287
11
2011-11-18T19:50:58Z
[ "python", "matplotlib" ]
I have a plot in matplotlib,and my problem is that because the x axe has strings as values when the plot window gets resized they overlap and they can't be read clearly. A similar thing happens with the legend it doesn't get resized if the windows is resized. Is there a setting for that ?
Not exactly. (Have a look at [the new `matplotlib.pyplot.tight_layout()` function](http://matplotlib.sourceforge.net/users/tight_layout_guide.html) for something vaguely similar, though...) However, the usual trick with long x-tick labels is just to rotate them. For example, if we have something with overlapping xtic...
Resizable divider line in wxpython?
8,182,621
5
2011-11-18T12:45:01Z
8,186,199
7
2011-11-18T17:13:14Z
[ "python", "wxpython" ]
I am not sure what they are called, but I would like a resizable divider line, to separate widgets. I would like something like this (except horizontal): <http://imm.io/bKgf> If you do not know what i am talking about please comment, thanks and sorry for my ignorance.
You need, maybe, a splitterwindow: ``` import wx class MyFrame(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent) self.splitter = wx.SplitterWindow(self) pan1 = wx.Window(self.splitter, style=wx.BORDER_SUNKEN) pan1.SetBackgroundColour("yellow") wx.Stat...
Two dimensional array in python
8,183,146
18
2011-11-18T13:28:33Z
8,183,168
30
2011-11-18T13:30:58Z
[ "python", "multidimensional-array" ]
I want to know how to declare a two dimensional array in Python. ``` arr = [[]] arr[0].append("aa1") arr[0].append("aa2") arr[1].append("bb1") arr[1].append("bb2") arr[1].append("bb3") ``` The first two assignments work fine. But when I try to do, arr[1].append("bb1"), I get the following error, IndexError: list in...
You do not "declare" arrays or anything else in python. You simply assign to a (new) variable. If you want a multidimensional array, simply add a new array as an array element. ``` arr = [] arr.append([]) arr[0].append('aa1') arr[0].append('aa2') ``` or ``` arr = [] arr.append(['aa1', 'aa2']) ```
Two dimensional array in python
8,183,146
18
2011-11-18T13:28:33Z
8,183,201
34
2011-11-18T13:33:08Z
[ "python", "multidimensional-array" ]
I want to know how to declare a two dimensional array in Python. ``` arr = [[]] arr[0].append("aa1") arr[0].append("aa2") arr[1].append("bb1") arr[1].append("bb2") arr[1].append("bb3") ``` The first two assignments work fine. But when I try to do, arr[1].append("bb1"), I get the following error, IndexError: list in...
There aren't multidimensional arrays as such in Python, what you have is a list containing other lists. ``` >>> arr = [[]] >>> len(arr) 1 ``` What you have done is declare a list containing a single list. So `arr[0]` contains a list but `arr[1]` is not defined. You can define a list containing two lists as follows: ...
Two dimensional array in python
8,183,146
18
2011-11-18T13:28:33Z
8,183,308
11
2011-11-18T13:40:45Z
[ "python", "multidimensional-array" ]
I want to know how to declare a two dimensional array in Python. ``` arr = [[]] arr[0].append("aa1") arr[0].append("aa2") arr[1].append("bb1") arr[1].append("bb2") arr[1].append("bb3") ``` The first two assignments work fine. But when I try to do, arr[1].append("bb1"), I get the following error, IndexError: list in...
What you're using here are not arrays, but lists (of lists). If you want multidimensional arrays in Python, you can use Numpy arrays. You'd need to know the shape in advance. For example: ``` import numpy as np arr = np.empty((3, 2), dtype=object) arr[0, 1] = 'abc' ```
Django, Postgresql & IntegrityErrors
8,183,700
3
2011-11-18T14:08:10Z
8,184,680
7
2011-11-18T15:20:01Z
[ "python", "django", "postgresql" ]
I come from a mysql background where if I want to insert a record I can use an INSERT IGNORE command so that I can just bung rows in and if there's a conflict just ignore it. Now, with a Django project I'm working on I'm using postgresql, and issue multiple saves in a loop. However, I *think* if I get an IntegrityErro...
It will depend on how you manage your transaction. On Postgres if one of query in transaction fails all subsequent query will also fail with error "current transaction is aborted, queries ignored until end of transaction block". To deal with it you should use transaction.savepoint\_rollback in an except block. Pleas...
I thought Python passed everything by reference?
8,184,244
6
2011-11-18T14:47:51Z
8,184,272
13
2011-11-18T14:49:48Z
[ "python", "scope" ]
Take the following code ``` #module functions.py def foo(input, new_val): input = new_val #module main.py input = 5 functions.foo(input, 10) print input ``` I thought input would now be 10. Why is this not the case?
Everything is passed by value, but that value is a reference to the original object. If you modify the object, the changes are visible for the caller, but you can't reassign names. Moreover, many objects are immutable (ints, floats, strings, tuples).
I thought Python passed everything by reference?
8,184,244
6
2011-11-18T14:47:51Z
8,184,281
8
2011-11-18T14:50:31Z
[ "python", "scope" ]
Take the following code ``` #module functions.py def foo(input, new_val): input = new_val #module main.py input = 5 functions.foo(input, 10) print input ``` I thought input would now be 10. Why is this not the case?
Inside foo, you're binding the local name `input` to a different object (`10`). In the calling context, the name `input` still refers to the `5` object.
reportlab: add background image by using platypus
8,185,438
3
2011-11-18T16:15:26Z
8,185,816
9
2011-11-18T16:44:26Z
[ "python", "image", "reportlab", "platypus" ]
this is a bit related to this [post](http://stackoverflow.com/questions/5138301/background-image-using-report-lab) I am trying to place an image on the background, and I want to be able to write text over it. using `canvas.drawImage` helps, but that's too low level approach for me. My program uses platypus, but `ca...
When you create a page template in Platypus you have the ability to pass a function via the named argument `onPage`. In that function you can place all your basic page formatting (headers, footers, watermark, background image). Here's an example: ``` def AllPageSetup(canvas, doc): canvas.saveState() #header...
compare object to empty tuple with the 'is' operator in Python 2.x
8,185,776
7
2011-11-18T16:40:58Z
8,186,110
9
2011-11-18T17:05:09Z
[ "python" ]
I'm used to seeing `if obj is None:` in Python, and I've recently come across `if obj is ():`. Since tuples are not mutable, it sounds like a reasonable internal optimization in the Python interpreter to have the empty tuple be a singleton, therefore allowing the use of `is` rather than requiring `==`. But is this guar...
From the Python 2 [docs](http://docs.python.org/reference/expressions.html#parenthesized-forms) and Python 3 [docs](http://docs.python.org/release/3.1.3/reference/expressions.html#parenthesized-forms): > ... two occurrences of the empty tuple may or may not yield the same object. In other words, you can't count on `(...
Styling the popup of a QCompleter in PyQt
8,186,828
6
2011-11-18T17:58:22Z
8,891,759
10
2012-01-17T08:44:09Z
[ "python", "qt4", "pyqt", "styling" ]
Is is possible to apply a stylesheet to the popup portion of a QCompleter tied to a QCombobox? If not, does it require delegate magic? If so, how might that even work as they do tend to confuse the hell out of me. Here is my widget code: ``` class autoFillField(QComboBox): def __init__(self, parent=None): ...
Set the stylesheet of the [popup of the completer](http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qcompleter.html#popup), which will be a QListView object. Here is a runnable example (the background of the popup should be yellow): ``` #!/usr/bin/python import sys from PyQt4 import QtGui, QtCore app = QtG...
How can you set class attributes from variable arguments (kwargs) in python
8,187,082
35
2011-11-18T18:18:24Z
8,187,203
64
2011-11-18T18:27:04Z
[ "python" ]
Suppose have a class with a constructor (or other function) that takes a variable number of arguments and then sets them as class attributes conditionally. I could set them manually, but it seems that variable parameters are common enough in python that there should be a common idiom for doing this. But I'm not sure h...
You can use the `setattr` method: ``` class Foo: def setAllWithKwArgs(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) ``` There is an analogous `getattr` method for retrieving attributes.
How can you set class attributes from variable arguments (kwargs) in python
8,187,082
35
2011-11-18T18:18:24Z
8,187,408
45
2011-11-18T18:39:58Z
[ "python" ]
Suppose have a class with a constructor (or other function) that takes a variable number of arguments and then sets them as class attributes conditionally. I could set them manually, but it seems that variable parameters are common enough in python that there should be a common idiom for doing this. But I'm not sure h...
Isn't this even easier? ``` class Bar(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) ``` then you can: ``` >>> bar = Bar(a=1, b=2) >>> bar.a 1 ``` and with something like: ``` allowed_keys = ['a', 'b', 'c'] self.__dict__.update((k, v) for k, v in kwargs.iteritems() if k in allowed_...
Counting points inside an ellipse
8,187,996
9
2011-11-18T19:27:35Z
8,188,643
8
2011-11-18T20:22:55Z
[ "python", "matplotlib", "ellipse" ]
I'm trying to count given data points inside each ring of ellipse: ![enter image description here](http://i.stack.imgur.com/wwNOB.png) The problem is that I have a function to check that: so for each ellipse, to make sure whether a point is in it, three inputs have to be calculated: ``` def get_focal_point(r1,r2,cen...
This may be something similar to what you are doing. I'm just looking to see if f(x,y) = x^2/r1^2 + y^2/r2^2 = 1. When f(x,y) is larger than 1, the point x,y is outside the ellipse. When it is smaller, then it is inside the ellipse. I loop through each ellipse to find the one when f(x,y) is smaller than 1. The code a...
Django ModelMultipleChoiceField object has no attribute to_field_name
8,188,048
2
2011-11-18T19:31:31Z
8,188,617
9
2011-11-18T20:21:06Z
[ "python", "django", "model", "modelform" ]
I'm trying to create a custom field for a ModelForm. I'm extending from ModelMultipleChoiceField and then overriding render and render\_options, however, I keep getting this exception when just trying to import my form: `AttributeError: 'ModelMultipleChoiceField' object has no attribute 'to_field_name'` I'm not sure ...
You seem to have got confused between fields and widgets. You inherit from `ModelMultipleChoiceField`, which (as the name implies) is a field, not a widget. But `render` and `render_options` are methods on widgets, not fields. And you've used your class in the `widgets` dictionary. I suspect you do mean to create a wi...
How do I do this array lookup/replace with numpy?
8,188,726
4
2011-11-18T20:30:14Z
8,188,858
8
2011-11-18T20:44:19Z
[ "python", "numpy" ]
I've got a 2D numpy array, `A` containing an index into another array, `B`. **What is a good way to get `C` from `A` and `B` using numpy?** ``` A = array([[1, 1, 0, 2], [1, 0, 0, 2], [1, 1, 0, 2]]) B = array([0, 5, 3]) C = array([[5, 5, 0, 3], [5, 0, 0, 3], [5, 5, 0, 3]]) ...
How about this `C = B[A]`. That's the beauty of numpy: ``` In [1]: import numpy as np In [2]: A = np.array([[1, 1, 0, 2], ...: [1, 0, 0, 2], ...: [1, 1, 0, 2]]) In [3]: B = np.array([0, 5, 3]) In [4]: B[A] Out[4]: array([[5, 5, 0, 3], [5, 0, 0, 3], [5, 5, 0, 3]]) ```