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
How to test with Python's unittest that a warning has been thrown?
3,892,218
26
2010-10-08T15:51:35Z
12,935,176
17
2012-10-17T13:15:29Z
[ "python", "unit-testing", "exception-handling", "warnings" ]
I have a following function in Python and I want to test with unittest that if the function gets 0 as argument, it throws a warning. I already tried assertRaises, but since I don't raise the warning, that doesn't work. ``` def isZero( i): if i != 0: print "OK" else: warning = Warning...
You can write your own assertWarns function to incapsulate catch\_warnings context. I've just implemented it the following way, with a mixin: ``` class WarningTestMixin(object): 'A test which checks if the specified warning was raised' def assertWarns(self, warning, callable, *args, **kwds): with warn...
How to adapt my current splash screen to allow other pieces of my code to run in the background?
3,892,327
6
2010-10-08T16:08:18Z
3,892,669
12
2010-10-08T16:53:25Z
[ "python", "multithreading", "wxpython", "initialization", "splash-screen" ]
Currently I have a splash screen in place. However, it does not work as a real splash screen - as it halts the execution of the rest of the code (instead of allowing them to run in the background). This is the current (reduced) arquitecture of my program, with the important bits displayed in full. How can I adapt the ...
Your code is pretty messy/complicated. There's no need to override wx.SplashScreen and no reason your splash screen close event should be creating the main application window. Here's how I do splash screens. ``` import wx def show_splash(): # create, show and return the splash screen bitmap = wx.Bitmap('image...
subprocess replacement of popen2 with Python
3,892,556
5
2010-10-08T16:38:09Z
3,892,595
8
2010-10-08T16:45:21Z
[ "python", "subprocess" ]
I tried to run this code from the book 'Python Standard Library' of 'Fred Lunde'. ``` import popen2, string fin, fout = popen2.popen2("sort") fout.write("foo\n") fout.write("bar\n") fout.close() print fin.readline(), print fin.readline(), fin.close() ``` It runs well with a warning of ``` ~/python_standard_librar...
``` import subprocess proc=subprocess.Popen(['sort'],stdin=subprocess.PIPE,stdout=subprocess.PIPE) proc.stdin.write('foo\n') proc.stdin.write('bar\n') out,err=proc.communicate() print(out) ```
Python - unhashable type error in urllib2
3,893,292
14
2010-10-08T18:29:30Z
3,893,338
27
2010-10-08T18:35:41Z
[ "python", "exception", "urllib2" ]
``` >> url = 'https://test.authorize.net/gateway/transact.dll' >> data = {'x_login': 'abc123', 'x_type': 'AUTH_CAPTURE', 'x_card_num': '4444333322221103', 'x_amount': '50.75', 'x_tran_key ': 'abc123', 'x_version': '3.1', 'x_delim_char': '|', 'x_exp_date': '022012', 'x_delim_data': 'TRUE'} >> >> urllib2.urlopen(url, da...
`data` is suppossed to be a "a buffer in the standard application/x-www-form-urlencoded format.", not a dict. Before you pass the data dict in do `data = urllib.urlencode(data)`, so you get the correct format from your dict.
Cheap way to search a large text file for a string
3,893,885
21
2010-10-08T19:56:37Z
3,893,901
11
2010-10-08T19:58:58Z
[ "python" ]
I need to search a pretty large text file for a particular string. Its a build log with about 5000 lines of text. Whats the best way to go about doing that? Using regex shouldn't cause any problems should it? I'll go ahead and read blocks of lines, and use the simple find.
You could do a simple find: ``` f = open('file.txt', 'r') lines = f.read() answer = lines.find('string') ``` A simple find will be quite a bit quicker than regex if you can get away with it.
Cheap way to search a large text file for a string
3,893,885
21
2010-10-08T19:56:37Z
3,893,931
34
2010-10-08T20:03:36Z
[ "python" ]
I need to search a pretty large text file for a particular string. Its a build log with about 5000 lines of text. Whats the best way to go about doing that? Using regex shouldn't cause any problems should it? I'll go ahead and read blocks of lines, and use the simple find.
If it is "pretty large" file, then access the lines sequentially and don't read the whole file into memory: ``` with open('largeFile', 'r') as inF: for line in inF: if 'myString' in line: # do_something ```
Cheap way to search a large text file for a string
3,893,885
21
2010-10-08T19:56:37Z
4,937,035
9
2011-02-08T18:50:27Z
[ "python" ]
I need to search a pretty large text file for a particular string. Its a build log with about 5000 lines of text. Whats the best way to go about doing that? Using regex shouldn't cause any problems should it? I'll go ahead and read blocks of lines, and use the simple find.
The following function works for textfiles and binary files (returns only position in byte-count though), it does have the benefit to **find strings even if they would overlap a line or buffer** and would not be found when searching line- or buffer-wise. ``` def fnd(fname, s, start=0): with open(fname, 'rb') as f:...
Django ManyToManyField ordering using through?
3,893,955
13
2010-10-08T20:07:37Z
10,911,820
14
2012-06-06T09:47:52Z
[ "python", "django", "many-to-many", "order" ]
Here is a snippet of how my models are setup: ``` class Profile(models.Model): name = models.CharField(max_length=32) accout = models.ManyToManyField( 'project.Account', through='project.ProfileAccount' ) def __unicode__(self) return self.name class Accounts(models.Model...
I just came through this. ``` class Profile(models.Model): accounts = models.ManyToManyField('project.Account', through='project.ProfileAccount') def get_accounts(self): return self.accounts.order_by('link_to_profile') class Account(models.Model): name ...
python - strtotime equivalent?
3,894,010
13
2010-10-08T20:17:18Z
3,894,047
27
2010-10-08T20:24:39Z
[ "python" ]
I'm using this to convert date time strings to a unix timestamp: ``` str(int(time.mktime(time.strptime(date,"%d %b %Y %H:%M:%S %Z")))) ``` However often the date structure isn't the same so I keep getting the following error message: > time data did not match format: data=Tue, 26 May 2009 19:58:20 -0500 fmt=%d %b %Y...
``` from dateutil.parser import parse parse('Tue, 26 May 2009 19:58:20 -0500').strftime('%s') # returns '1243364300' ```
Twisted Deferred.addCallBack() vs. yield and @inlineDeferred
3,894,278
9
2010-10-08T21:00:20Z
3,954,427
14
2010-10-17T17:40:44Z
[ "python", "twisted" ]
Is there any reason to use one over the other? Do they have the same performance?
I tend to use `inlineCallbacks` for multistep initialization (such as auth) to some service where each subsequent step depends on a result from the previous step, for example. Other than these situations, I tend to find that `inlineCallbacks` could lead to lazy programming that could *slow down* your app. Here's an ex...
What icons are available to use when displaying a notification with libnotify?
3,894,763
4
2010-10-08T22:32:51Z
3,894,929
7
2010-10-08T23:17:43Z
[ "python", "pygtk", "libnotify" ]
I'm using the [libnotify](http://roscidus.com/desktop/node/336) library to display a notification in Ubuntu. I would ideally like to display a battery of some sort (since my app is a battery meter). The types of icons I can use are: 1. a URI specifying the icon file name (e.g. file://path/to/my-icon.png) 2. a 'stock'...
You can easily find out using [pygtk](http://www.pygtk.org/) itself: ``` >>> import gtk >>> print "\n".join(name for name in dir(gtk) if name.startswith("STOCK_")) ``` On my machine, this prints: ``` STOCK_ABOUT STOCK_ADD STOCK_APPLY STOCK_BOLD STOCK_CANCEL STOCK_CAPS_LOCK_WARNING STOCK_CDROM STOCK_CLEAR STOCK_CLOSE...
How importing works. Why imported modules not inheriting other imported modules
3,895,346
6
2010-10-09T01:39:02Z
3,895,510
10
2010-10-09T02:48:20Z
[ "python", "module", "import" ]
I just "thought" I understood how importing and modules work but obviously I need more schooling. Here is an example program (just a test case of somerthing I'm doing that is much bigger in scope and scale) and a module: quick.py ``` import gtk from quick_window import * w.show_all() gtk.main() ``` quick\_window.p...
The details of importing get very complicated, but conceptually it is very simple. When you write: ``` import some_module ``` It is equivalent to this: ``` some_module = import_module("some_module") ``` where import\_module is kind of like: ``` def import_module(modname): if modname in sys.modules: mo...
what is a quick way to delete all elements from a list that do not satisfy a constraint?
3,895,424
6
2010-10-09T02:15:14Z
3,895,431
7
2010-10-09T02:17:42Z
[ "python" ]
I have a list of strings. I have a function that given a string returns 0 or 1. How can I delete all strings in the list for which the function returns 0?
``` [x for x in lst if fn(x) != 0] ``` This is a "list comprehension", one of Python's nicest pieces of syntactical sugar that often takes lines of code in other languages and additional variable declarations, etc. See: <http://docs.python.org/tutorial/datastructures.html#list-comprehensions>
pymongo (python+mongodb) drop collection/gridfs?
3,895,572
5
2010-10-09T03:23:43Z
3,901,808
8
2010-10-10T19:19:41Z
[ "python", "mongodb", "pymongo" ]
Anyone know the commands to drop a collection of documents and also drop a gridfs database?
To delete a collection, you can either call the [`drop()`](http://api.mongodb.org/python/1.9%2B/api/pymongo/collection.html#pymongo.collection.Collection.drop) method on it, or use the [`drop_collection()`](http://api.mongodb.org/python/1.9%2B/api/pymongo/database.html#pymongo.database.Database.drop_collection) method ...
Number of regex matches
3,895,646
25
2010-10-09T03:57:11Z
3,895,658
35
2010-10-09T04:02:02Z
[ "python" ]
I'm using the finditer-function in the re module to match some things and everything is working. Now I need to find out how many matches I've got, is it possible without looping through the iterator twice? (one to find out the count and then the real iteration) Edit: As requested, some code: ``` imageMatches = re.fi...
If you know you will want all the matches, you could use the `re.findall` function. It will return a list of all the matches. Then you can just do `len(result)` for the number of matches.
Installed python3, getting command not found error in terminal
3,895,756
5
2010-10-09T04:56:56Z
3,895,851
7
2010-10-09T05:38:59Z
[ "python", "osx", "path" ]
I installed python3, I can open idle and it says it is running python3.0.1, but when I enter python3 in the terminal (on OSX) I get an error saying 'command not found'. Entering python gets me the 2.x version that came on the computer. Any advice on how I can access python3 from the terminal? Thanks
First, don't use Python 3.0.1. It has many problems and was officially retired upon the release of Python 3.1 (currently 3.1.2). You can find the python.org Mac OS X installer for 3.1.2 [here](http://www.python.org/download/releases/3.1.2/). Once it is installed, then you need to ensure that the `bin` directory from th...
Regex to match 'lol' to 'lolllll' and 'omg' to 'omggg', etc
3,895,874
4
2010-10-09T05:56:32Z
3,895,901
7
2010-10-09T06:10:18Z
[ "python", "regex", "string-matching" ]
Hey there, I love regular expressions, but I'm just not good at them at all. I have a list of some 400 shortened words such as lol, omg, lmao...etc. Whenever someone types one of these shortened words, it is replaced with its English counterpart ([laughter], or something to that effect). Anyway, people are annoying an...
**FIRST APPROACH -** Well, using regular expression(s) you could do like so - ``` import re re.sub('g+', 'g', 'omgggg') re.sub('l+', 'l', 'lollll') ``` etc. Let me point out that using regular expressions is a very fragile & basic approach to dealing with this problem. You could so easily get strings from users whi...
Image library for Python 3
3,896,286
113
2010-10-09T15:56:23Z
10,376,944
18
2012-04-29T23:34:54Z
[ "python", "image", "python-3.x", "python-imaging-library" ]
What is python-3 using instead of PIL for manipulating Images?
Christoph Gohlke managed to build PIL (for Windows only) for python versions up to 3.3: <http://www.lfd.uci.edu/~gohlke/pythonlibs/> I tried his version of PIL with Python 3.2, and image open/create/pixel manipulation/save all work.
Image library for Python 3
3,896,286
113
2010-10-09T15:56:23Z
12,197,361
10
2012-08-30T12:56:02Z
[ "python", "image", "python-3.x", "python-imaging-library" ]
What is python-3 using instead of PIL for manipulating Images?
Qt works very well with graphics. In my opinion it is more versatile than PIL. You get all the features you want for graphics manipulation, but there's also vector graphics and even support for real printers. And all of that in one uniform API, [**`QPainter`**](http://qt-project.org/doc/qt-4.8/qpainter.html). To use ...
Image library for Python 3
3,896,286
113
2010-10-09T15:56:23Z
13,011,542
62
2012-10-22T12:32:09Z
[ "python", "image", "python-3.x", "python-imaging-library" ]
What is python-3 using instead of PIL for manipulating Images?
The "friendly PIL fork" **[Pillow](http://python-pillow.github.io/) works on Python 2 and 3**. Check out the [Github project](https://github.com/python-imaging/Pillow) for support matrix and so on.
Python - Fastest way to find the average value over entire dict each time it gets modified?
3,897,040
4
2010-10-09T17:07:25Z
3,897,106
11
2010-10-09T17:23:03Z
[ "python", "dictionary", "iteration", "average" ]
I'm trying to find the fastest/most efficient way to extract the average value from a dict. The task I'm working on requires that it do this thousands of times, so simply iterating over all the values in the dict each time to find the average would be entirely inefficient. Hundreds and hundreds of new key,value pairs g...
Create your own dict subclass that tracks the count and total, and then can quickly return the average: ``` class AvgDict(dict): def __init__(self): self._total = 0.0 self._count = 0 def __setitem__(self, k, v): if k in self: self._total -= self[k] self._count -...
Django/Celery can't find importlib
3,897,436
3
2010-10-09T18:55:08Z
3,898,093
8
2010-10-09T22:17:43Z
[ "python", "django", "celery" ]
So I just updated django to 1.2.3 and now when I try to run 'python manage.py shell' to work in the django environment, I'm getting the following error. ``` Traceback (most recent call last): File "manage.py", line 11, in <module> execute_manager(settings) File "/opt/local/Library/Frameworks/Python.framework/V...
importlib which was added in Python 2.7/3.1, I believe. You can download a port for pyton 2.5 here: * [importlib 1.0.1 - Backport of importlib.import\_module() from Python 2.7](http://pypi.python.org/pypi/importlib/1.0.1) Also check the [`setup.cfg`](http://github.com/ask/celery/blob/master/setup.cfg) for celery near...
Check if value already exists within list of dictionaries?
3,897,499
35
2010-10-09T19:12:03Z
3,897,516
83
2010-10-09T19:16:11Z
[ "python", "list", "dictionary" ]
I've got a Python list of dictionaries, as follows: ``` a = [ {'main_color': 'red', 'second_color':'blue'}, {'main_color': 'yellow', 'second_color':'green'}, {'main_color': 'yellow', 'second_color':'blue'}, ] ``` I'd like to check whether a dictionary with a particular key/value already exists in the list...
Here's one way to do it: ``` if not any(d['main_color'] == 'red' for d in a): # does not exist ``` The part in parentheses is a generator expression that returns `True` for each dictionary that has the key-value pair you are looking for, otherwise `False`. --- If the key could also be missing the above code can...
Python: how can I get rid of the second element of each sublist?
3,898,065
3
2010-10-09T22:07:15Z
3,898,071
7
2010-10-09T22:09:37Z
[ "python" ]
I have a list of sublists, such as: [[501, 4], [501, 4], [501, 4], [501, 4]] How can I get rid of the second element for each sublist ? (i.e. 4) [501, 501, 501, 501] Should I iterate the list or is there a faster way ? thanks
You can use a list comprehension to take the first element of each sublist: ``` xs = [[501, 4], [501, 4], [501, 4], [501, 4]] [x[0] for x in xs] # [501, 501, 501, 501] ```
What is this cProfile result telling me I need to fix?
3,898,266
10
2010-10-09T23:04:43Z
3,898,993
23
2010-10-10T04:13:46Z
[ "python", "performance", "profiling", "profile", "cprofile" ]
I would like to improve the performance of a Python script and have been using `cProfile` to generate a performance report: ``` python -m cProfile -o chrX.prof ./bgchr.py ...args... ``` I opened this `chrX.prof` file with Python's `pstats` and printed out the statistics: ``` Python 2.7 (r27:82500, Oct 5 2010, 00:24...
`ncalls` is relevant only to the extent that comparing the numbers against other counts such as number of chars/fields/lines in a file may highligh anomalies; `tottime` and `cumtime` is what really matters. `cumtime` is the time spent in the function/method *including* the time spent in the functions/methods that it ca...
Set specific DNS server using dns.resolver (pythondns)
3,898,363
17
2010-10-09T23:46:03Z
6,947,181
40
2011-08-04T19:08:45Z
[ "python", "dns" ]
I am using `dns.resolver` from [dnspython](http://www.dnspython.org/). Is it possible to set the IP address of the server to use for queries ?
Although this is somewhat of an old thread, I will jump in. I've bumped against the same challenge and I thought I would share the solution. So, basically the config file would populate the 'nameservers' instance variable of the dns.resolver.Resolver you are using. Hence, if you want to coerce your Resolver to use a pa...
What is the standard Python docstring format?
3,898,572
327
2010-10-10T01:10:44Z
3,898,661
11
2010-10-10T01:48:11Z
[ "python", "coding-style", "documentation", "docstring" ]
I have seen a few different styles of writing docstrings in Python, is there an official or "agreed-upon" style?
[PEP-8](http://python.org/dev/peps/pep-0008/) is the official python coding standard. It contains a section on docstrings, which refers to [PEP-257](http://www.python.org/dev/peps/pep-0257/) -- a complete specification for docstrings.
What is the standard Python docstring format?
3,898,572
327
2010-10-10T01:10:44Z
3,899,154
178
2010-10-10T05:36:16Z
[ "python", "coding-style", "documentation", "docstring" ]
I have seen a few different styles of writing docstrings in Python, is there an official or "agreed-upon" style?
Docstring conventions are in [PEP-257](http://www.python.org/dev/peps/pep-0257/) with much more detail than PEP-8. However, docstrings seem to be far more personal than other areas of code. Different projects will have their own standard. I tend to always include docstrings, because they tend to demonstrate how to us...
What is the standard Python docstring format?
3,898,572
327
2010-10-10T01:10:44Z
8,109,339
260
2011-11-13T03:14:39Z
[ "python", "coding-style", "documentation", "docstring" ]
I have seen a few different styles of writing docstrings in Python, is there an official or "agreed-upon" style?
The [Google style guide](https://github.com/google/styleguide) contains an excellent Python style guide. It includes [conventions for readable docstring syntax](https://google.github.io/styleguide/pyguide.html#Comments) that offers better guidance than PEP-257. For example: ``` def square_root(n): """Calculate the...
What is the standard Python docstring format?
3,898,572
327
2010-10-10T01:10:44Z
23,188,939
34
2014-04-21T00:01:27Z
[ "python", "coding-style", "documentation", "docstring" ]
I have seen a few different styles of writing docstrings in Python, is there an official or "agreed-upon" style?
As apparantly no one mentioned it: you can also use the **Numpy Docstring Standard**. It is widely used in the scientific community. * The [specification of the format](https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt) from numpy together with an [example](https://github.com/numpy/numpy/blob/maste...
What is the standard Python docstring format?
3,898,572
327
2010-10-10T01:10:44Z
24,385,103
247
2014-06-24T11:10:21Z
[ "python", "coding-style", "documentation", "docstring" ]
I have seen a few different styles of writing docstrings in Python, is there an official or "agreed-upon" style?
# Formats Python docstrings can be written following several formats as the other posts showed. However the default Sphinx docstring format was not mentioned and is based on **reStructuredText (reST)**. You can get some information about the main formats in [that tuto](http://daouzli.com/blog/docstring.html). Note th...
Google search using python script
3,898,574
16
2010-10-10T01:11:59Z
3,898,955
15
2010-10-10T03:55:46Z
[ "python" ]
Could anyone help me on how to write a python script that searches google and prints the links of top results.
Maybe, something like this? ``` import urllib import json as m_json query = raw_input ( 'Query: ' ) query = urllib.urlencode ( { 'q' : query } ) response = urllib.urlopen ( 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&' + query ).read() json = m_json.loads ( response ) results = json [ 'responseData' ] [...
list.extend and list comprehension
3,899,645
16
2010-10-10T08:49:37Z
3,899,658
16
2010-10-10T08:51:52Z
[ "python", "list", "list-comprehension" ]
When I need to add several identical items to the list I use list.extend: ``` a = ['a', 'b', 'c'] a.extend(['d']*3) ``` Result ``` ['a', 'b', 'c', 'd', 'd', 'd'] ``` But, how to do the similar with list comprehension? ``` a = [['a',2], ['b',2], ['c',1]] [[x[0]]*x[1] for x in a] ``` Result ``` [['a', 'a'], ['b', ...
Stacked LCs. ``` [y for x in a for y in [x[0]] * x[1]] ```
Will the real path.py please stand up?
3,899,761
18
2010-10-10T09:30:16Z
7,923,330
10
2011-10-27T22:47:39Z
[ "python", "path", "module" ]
There was a good module, `path.py`, written by Jason Orendorff. If I recall correctly, there was some discussion about adding it to the standard library then it faded away. It looks now that there are multiple outgrowths of the original one. I can find so far [unipath](http://pypi.python.org/pypi/Unipath/0.2.1), what ...
I've also been a fan of this module for quite some time. [This one](https://pypi.python.org/pypi/path.py) seems to have the most recent commits, and also to be true to the original form -- which really, I like best of the different versions I've tried. Installable using `pip install path.py` **edit**: Looks like as of...
How to change the font size on a matplotlib plot
3,899,980
163
2010-10-10T10:43:27Z
3,900,167
185
2010-10-10T11:49:11Z
[ "python", "matplotlib", "font-size" ]
How does one change the font size for all elements (ticks, labels, title) on a matplotlib plot? I know how to change the tick label sizes, this is done with: ``` import matplotlib matplotlib.rc('xtick', labelsize=20) matplotlib.rc('ytick', labelsize=20) ``` But how does one change the rest?
From the [matplotlib documentation](http://matplotlib.sourceforge.net/api/matplotlib_configuration_api.html#matplotlib.rc), ``` font = {'family' : 'normal', 'weight' : 'bold', 'size' : 22} matplotlib.rc('font', **font) ``` This sets the font of all items to the font specified by the kwargs object, ...
How to change the font size on a matplotlib plot
3,899,980
163
2010-10-10T10:43:27Z
6,441,839
103
2011-06-22T14:46:44Z
[ "python", "matplotlib", "font-size" ]
How does one change the font size for all elements (ticks, labels, title) on a matplotlib plot? I know how to change the tick label sizes, this is done with: ``` import matplotlib matplotlib.rc('xtick', labelsize=20) matplotlib.rc('ytick', labelsize=20) ``` But how does one change the rest?
``` matplotlib.rcParams.update({'font.size': 22}) ```
How to change the font size on a matplotlib plot
3,899,980
163
2010-10-10T10:43:27Z
14,971,193
83
2013-02-20T02:13:32Z
[ "python", "matplotlib", "font-size" ]
How does one change the font size for all elements (ticks, labels, title) on a matplotlib plot? I know how to change the tick label sizes, this is done with: ``` import matplotlib matplotlib.rc('xtick', labelsize=20) matplotlib.rc('ytick', labelsize=20) ``` But how does one change the rest?
If you want to change the fontsize for just a specific plot that has already been created, try this: ``` import matplotlib.pyplot as plt ax = plt.subplot(111, xlabel='x', ylabel='y', title='title') for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()): ...
How to change the font size on a matplotlib plot
3,899,980
163
2010-10-10T10:43:27Z
23,572,192
32
2014-05-09T19:08:00Z
[ "python", "matplotlib", "font-size" ]
How does one change the font size for all elements (ticks, labels, title) on a matplotlib plot? I know how to change the tick label sizes, this is done with: ``` import matplotlib matplotlib.rc('xtick', labelsize=20) matplotlib.rc('ytick', labelsize=20) ``` But how does one change the rest?
**Update:** See the bottom of the answer for a slightly better way of doing it **Update #2:** I've figured out changing legend title fonts too This answer is for anyone trying to change all the fonts, including for the legend, and for anyone trying to use different fonts and sizes for each thing. It does not use rc ...
Python strip() multiple characters?
3,900,054
32
2010-10-10T11:09:16Z
3,900,077
17
2010-10-10T11:17:10Z
[ "python" ]
I want to remove any brackets from a string. Why doesn't this work properly? ``` >>> name = "Barack (of Washington)" >>> name = name.strip("(){}<>") >>> print name Barack (of Washington ```
I did a time test here, using each method 100000 times in a loop. The results surprised me. (The results still surprise me after editing them in response to valid criticism in the comments.) Here's the script: ``` import timeit bad_chars = '(){}<>' setup = """import re import string s = 'Barack (of Washington)' bad...
Python strip() multiple characters?
3,900,054
32
2010-10-10T11:09:16Z
3,900,078
33
2010-10-10T11:17:15Z
[ "python" ]
I want to remove any brackets from a string. Why doesn't this work properly? ``` >>> name = "Barack (of Washington)" >>> name = name.strip("(){}<>") >>> print name Barack (of Washington ```
Because that's not what `strip()` does. It removes leading and trailing characters that are present in the argument, but not those characters in the middle of the string. You could do: ``` name= name.replace('(', '').replace(')', '').replace ... ``` or: ``` name= ''.join(c for c in name if c not in '(){}<>') ``` o...
Python strip() multiple characters?
3,900,054
32
2010-10-10T11:09:16Z
3,900,089
7
2010-10-10T11:20:07Z
[ "python" ]
I want to remove any brackets from a string. Why doesn't this work properly? ``` >>> name = "Barack (of Washington)" >>> name = name.strip("(){}<>") >>> print name Barack (of Washington ```
Because `strip()` only strips trailing and leading characters, based on what you provided. I suggest: ``` >>> import re >>> name = "Barack (of Washington)" >>> name = re.sub('[\(\)\{\}<>]', '', name) >>> print(name) Barack of Washington ```
Python strip() multiple characters?
3,900,054
32
2010-10-10T11:09:16Z
23,514,434
10
2014-05-07T09:52:38Z
[ "python" ]
I want to remove any brackets from a string. Why doesn't this work properly? ``` >>> name = "Barack (of Washington)" >>> name = name.strip("(){}<>") >>> print name Barack (of Washington ```
[string.translate](https://docs.python.org/2/library/string.html#string.translate) with table=None works fine. ``` >>> name = "Barack (of Washington)" >>> name = name.translate(None, "(){}<>") >>> print name Barack of Washington ```
Ignore an element while building list in python
3,900,215
7
2010-10-10T12:02:56Z
3,900,224
18
2010-10-10T12:06:53Z
[ "python", "list", "syntactic-sugar" ]
I need to build a list from a string in python using the [f(char) for char in string] syntax and I would like to be able to ignore (not insert in the list) the values of f(x) which are equal no None. How can I do that ?
We could create a "subquery". ``` [r for r in (f(char) for char in string) if r is not None] ``` If you allow all False values (0, False, None, etc.) to be ignored as well, `filter` could be used: ``` filter(None, (f(char) for char in string) ) # or, using itertools.imap, filter(None, imap(f, string)) ```
access to google with python
3,900,610
2
2010-10-10T14:07:20Z
3,900,666
10
2010-10-10T14:19:22Z
[ "python" ]
how i can access to google !! i had try that code ``` urllib.urlopen('http://www.google.com') ``` but it's show message `prove you are human` or some think like dat some people say try user agent !! i dunno !
You should use the [Google API](http://code.google.com/apis/ajaxsearch/) for accessing the search. [Here's an example for python](http://dcortesi.com/2008/05/28/google-ajax-search-api-example-python-code/). Unutbu provided a link to an [older SO answer](http://stackoverflow.com/questions/1657570/google-search-from-a-py...
Python+Celery: Chaining jobs?
3,901,101
28
2010-10-10T16:24:24Z
12,034,239
25
2012-08-20T08:12:48Z
[ "python", "celery" ]
The [Celery documentation](http://celery.readthedocs.org/en/latest/userguide/tasks.html#avoid-launching-synchronous-subtasks) suggests that it's a bad idea to have tasks wait on the results of other tasks… But the suggested solution (see “good” heading) leaves a something to be desired. Specifically, there's no c...
You can do it with a celery chain. See <https://celery.readthedocs.org/en/latest/userguide/canvas.html#chains> ``` @task() def add(a, b): time.sleep(5) # simulate long time processing return a + b ``` Chaining job: ``` # import chain from celery import chain # the result of the first add job will be # the f...
Difference between "if x" and "if x is not None"
3,901,144
18
2010-10-10T16:33:35Z
3,901,151
31
2010-10-10T16:35:25Z
[ "python", "boolean" ]
It appears that "if x" is almost like short-hand for the longer "if x is not None" syntax. Are they functionally identical or are there cases where for a given value of x the two would evaluate differently? I would assume the behavior should also be identical across Python implementations - but if there are subtle dif...
The former tests trueness, whereas the latter tests for identity with `None`. Lots of values are false, such as `False`, `0`, `''`, and `None`, but only `None` is `None`.
Difference between "if x" and "if x is not None"
3,901,144
18
2010-10-10T16:33:35Z
3,901,191
35
2010-10-10T16:44:23Z
[ "python", "boolean" ]
It appears that "if x" is almost like short-hand for the longer "if x is not None" syntax. Are they functionally identical or are there cases where for a given value of x the two would evaluate differently? I would assume the behavior should also be identical across Python implementations - but if there are subtle dif...
In the following cases: ``` test = False test = "" test = 0 test = 0.0 test = [] test = () test = {} test = set() ``` the `if` test will differ: ``` if test: #False if test is not None: #True ```
How do I count words in an nltk plaintextcorpus faster?
3,902,044
4
2010-10-10T20:25:37Z
3,902,368
8
2010-10-10T21:54:20Z
[ "python", "nlp", "nltk", "corpus" ]
I have a set of documents, and I want to return a list of tuples where each tuple has the date of a given document and the number of times a given search term appears in that document. My code (below) works, but is slow, and I'm a n00b. Are there obvious ways to make this faster? Any help would be much appreciated, mos...
If you just want a frequency of word counts, then you don't need to create `nltk.Text` objects, or even use `nltk.PlainTextReader`. Instead, just go straight to `nltk.FreqDist`. ``` files = list_of_files fd = nltk.FreqDist() for file in files: with open(file) as f: for sent in nltk.sent_tokenize(f.lower())...
Apply opencv threshold to a numpy array
3,903,432
6
2010-10-11T03:59:52Z
5,652,830
10
2011-04-13T16:55:05Z
[ "python", "opencv", "numpy" ]
I'm trying to apply opencv's `Threshold` function to a numpy array. I'm using the python bindings for opencv 2.1. It goes like this: ``` import cv import numpy as np a = np.random.rand(1024,768) cv.Threshold(a,a,0.5,1,cv.CV_THRESH_BINARY) ``` and this throws an error: ``` OpenCV Error: Unsupported format or combinat...
Apparently the `Threshold` method is more fussy than Smooth - it only works on 8 bit integer / 32 bit floating point arrays (see [here](http://opencv.willowgarage.com/documentation/python/miscellaneous_image_transformations.html#index-919)) so your code snippet above won’t work because numpy arrays default to float64...
Taking list's tail in a Pythonic way?
3,903,467
6
2010-10-11T04:12:09Z
3,903,483
7
2010-10-11T04:17:04Z
[ "python" ]
``` from random import randrange data = [(randrange(8), randrange(8)) for x in range(8)] ``` And we have to test if the first item equals to one of a tail. I am curious, how we would do it in most simple way without copying tail items to the new list? Please take into account this piece of code gets executed many time...
## **Nick D's Answer is better** use `islice`. It doesn't make a copy of the list and essentially embeds your second (elegant but verbose) solution in a C module. ``` import itertools head = data[0] result = head in itertools.islice(data, 1, None) ``` for a demo: ``` >>> a = [1, 2, 3, 1] >>> head = a[0] >>> tail =...
How to convert hex string to hex number?
3,904,135
11
2010-10-11T07:08:19Z
3,904,171
15
2010-10-11T07:14:22Z
[ "python" ]
I have integer number in ex. 16 and i am trying to convert this number to a hex number. I tried to achieve this by using hex function but whenever you provide a integer number to the hex function it returns string representation of hex number, ``` my_number = 16 hex_no = hex(my_number) print type(hex_no) // It wil...
``` >>> print int('0x10', 16) 16 ```
zlib module missing
3,905,615
13
2010-10-11T11:06:12Z
3,905,660
23
2010-10-11T11:12:49Z
[ "python", "ubuntu", "python-2.7", "ubuntu-10.04" ]
I have compiled and installed python 2.7 on my ubuntu lucid. But I am unable to install setuptools for python 2.7 because the data decompression module zlib is not present. This is the exact error: ``` Traceback (most recent call last): File "setup.py", line 94, in <module> scripts = scripts, File "/usr/loc...
You forgot to install `zlib1g-dev` before building Python.
Why can't I call read() twice on an open file?
3,906,137
36
2010-10-11T12:25:38Z
3,906,148
55
2010-10-11T12:27:19Z
[ "python", "io" ]
For an exercise I'm doing, I'm trying to read the contents of a given file twice using the `read()` method. Strangely, when I call it the second time, it doesn't seem to return the file content as a string? Here's the code ``` f = f.open() # get the year match = re.search(r'Popularity in (\d+)', f.read()) if match:...
Calling `read()` reads through the entire file and leaves the read cursor at the end of the file (with nothing more to read). If you are looking to read a certain number of lines at a time you could use `readline()`, `readlines()` or iterate through lines with `for line in handle:`. To answer your question directly, o...
Why can't I call read() twice on an open file?
3,906,137
36
2010-10-11T12:25:38Z
3,906,149
11
2010-10-11T12:27:23Z
[ "python", "io" ]
For an exercise I'm doing, I'm trying to read the contents of a given file twice using the `read()` method. Strangely, when I call it the second time, it doesn't seem to return the file content as a string? Here's the code ``` f = f.open() # get the year match = re.search(r'Popularity in (\d+)', f.read()) if match:...
The read pointer moves to after the last read byte/character. Use the `seek()` method to rewind the read pointer to the beginning.
Why can't I call read() twice on an open file?
3,906,137
36
2010-10-11T12:25:38Z
3,906,205
11
2010-10-11T12:34:41Z
[ "python", "io" ]
For an exercise I'm doing, I'm trying to read the contents of a given file twice using the `read()` method. Strangely, when I call it the second time, it doesn't seem to return the file content as a string? Here's the code ``` f = f.open() # get the year match = re.search(r'Popularity in (\d+)', f.read()) if match:...
Everyone who has answered this question so far is absolutely right - `read()` moves through the file, so after you've called it, you can't call it again. What I'll add is that in your particular case, you don't need to seek back to the start or reopen the file, you can just store the text that you've read in a local v...
Why can't I call read() twice on an open file?
3,906,137
36
2010-10-11T12:25:38Z
3,906,563
7
2010-10-11T13:20:04Z
[ "python", "io" ]
For an exercise I'm doing, I'm trying to read the contents of a given file twice using the `read()` method. Strangely, when I call it the second time, it doesn't seem to return the file content as a string? Here's the code ``` f = f.open() # get the year match = re.search(r'Popularity in (\d+)', f.read()) if match:...
yeah, as above... i'll write just an example: ``` >>> a = open('file.txt') >>> a.read() #output >>> a.seek(0) >>> a.read() #same output ```
python : get the print output in an exec statement
3,906,232
15
2010-10-11T12:38:16Z
3,906,390
24
2010-10-11T12:58:26Z
[ "python", "printing", "exec" ]
i've got a little problem here is my code : ``` code = """ i = [0,1,2] for j in i : print j """ result = exec(code) ``` how could i get the things that print outputed ? bref here how can i get in something : ``` 0 1 2 ``` regards and thanks Bussiere
I had the same idea as Frédéric, but i wrote a context manager to handle replacing stdout: ``` import sys import StringIO import contextlib @contextlib.contextmanager def stdoutIO(stdout=None): old = sys.stdout if stdout is None: stdout = StringIO.StringIO() sys.stdout = stdout yield stdout ...
Image classification in python
3,906,682
12
2010-10-11T13:31:39Z
3,907,297
9
2010-10-11T14:49:18Z
[ "python", "image-processing", "opencv", "machine-learning", "barcode-scanner" ]
I'm looking for a method of classifying scanned pages that consist largely of text. Here are the particulars of my problem. I have a large collection of scanned documents and need to detect the presence of certain kinds of pages within these documents. I plan to "burst" the documents into their component pages (each o...
I will answer in 3 parts since your problem is clearly a large one and I would highly recommend manual method with cheap labour if the collection of pages does not exceed a 1000. **Part 1:** Feature Extraction - You have a very large array of features to choose from in the object detection field. Since one of your req...
Python function local name binding from an outer scope
3,908,335
12
2010-10-11T17:01:33Z
3,913,185
11
2010-10-12T09:26:03Z
[ "python", "scope", "decorator" ]
I need a way to "inject" names into a function from an outer code block, so they are accessible locally **and** they don't need to be specifically handled by the function's code (defined as function parameters, loaded from `*args` etc.) The simplified scenario: providing a framework within which the users are able to ...
The more I mess around with the stack, the more I wish I hadn't. Don't hack globals to do what you want. Hack bytecode instead. There's two ways that I can think of to do this. 1) Add cells wrapping the references that you want into `f.func_closure`. You have to reassemble the bytecode of the function to use `LOAD_DER...
Check if Session Key is Set in Django
3,908,761
9
2010-10-11T18:01:04Z
3,908,770
29
2010-10-11T18:02:42Z
[ "python", "django" ]
I am attempting to create a relatively simple shopping cart in Django. I am storing the cart in request.session['cart']. Therefore, I'll need to access the data in this session when anything is added to it. However, if the session is not already set, I cannot access it without receiving an error. Is there anyway to che...
I assume that you want to check if a *key* is set in session, not if a *session* is set (don't know what the latter means). If so: You can do: ``` if key not in request.session: # Set it. ``` In your case: ``` if 'cart' not in request.session: # Set it. ``` **EDIT**: changed the code snippet to use `key no...
Check if Session Key is Set in Django
3,908,761
9
2010-10-11T18:01:04Z
3,908,866
10
2010-10-11T18:16:52Z
[ "python", "django" ]
I am attempting to create a relatively simple shopping cart in Django. I am storing the cart in request.session['cart']. Therefore, I'll need to access the data in this session when anything is added to it. However, if the session is not already set, I cannot access it without receiving an error. Is there anyway to che...
You can use the `get`-method on the session dictionary, it will not throw an error if the key doesn't exist, but return none as a default value or your custom default value: ``` cart = request.session.get('cart') cart = request.session.get('cart', 'no cart') ```
Is there a B-Tree Database or framework in Python?
3,909,602
13
2010-10-11T20:14:00Z
3,911,263
18
2010-10-12T02:24:58Z
[ "python", "b-tree" ]
I heard that B-Tree datbases are faster than Hash tables, so I thought of using a B-Tree Db for my project. Is there any existing framework in python which allows us to use such Data structure or will I have to code from scratch?
The only reason to choose a B-Tree over a hash table, either in memory or with block storage (as in a database) is to support queries other than equal. A b-tree permits you perform range queries with good performance. Many key-value stores (such as berkley db) don't make this externally visible, though, because they st...
Plotting mplot3d / axes3D xyz surface plot with log scale?
3,909,794
8
2010-10-11T20:42:07Z
17,363,073
8
2013-06-28T10:54:21Z
[ "python", "numpy", "matplotlib" ]
I've been looking high and low for a solution to this simple problem but I can't find it anywhere! There are a loads of posts detailing semilog / loglog plotting of data in 2D e.g. plt.setxscale('log') however I'm interested in using log scales on a 3d plot(mplot3d). I don't have the exact code to hand and so can't po...
Since I encountered the same question and Alejandros answer did not produced the desired Results here is what i found out so far. The log scaling for Axes in 3D is an ongoing issue in matplotlib. Currently you can only relabel the axes with: ``` ax.yaxis.set_scale('log') ``` This will however not cause the axes to b...
How to stub Python methods without Mock
3,909,942
6
2010-10-11T21:02:43Z
3,910,476
18
2010-10-11T22:47:00Z
[ "python", "unit-testing", "mocking", "stub" ]
I'm a C# dev moving into some Python stuff, so I don't know what I'm doing just yet. I've read that you don't really need Dependency Injection with Python. I've been told you can instantiate objects in your code and have them run the way you want, however, you can point methods on those objects to my own stubs defined ...
Here's a basic example. Note that the production getData() method is never called. It has been mocked out with a stub. ``` import unittest class ClassIWantToTest(object): def getData(self): print "PRODUCTION getData called" return "Production code that gets data from server or data file" def ...
ndarray field names for both row and column?
3,910,301
7
2010-10-11T22:08:34Z
3,910,931
7
2010-10-12T00:32:21Z
[ "python", "numpy" ]
I'm a computer science teacher trying to create a little gradebook for myself using NumPy. But I think it would make my code easier to write if I could create an ndarray that uses field names for both the rows and columns. Here's what I've got so far: ``` import numpy as np num_stud = 23 num_assign = 2 grades = np.zer...
For entering and storing the data, I would use a relational database (like sqlite, MySQL or Postgresql). If you do it this way, you can easily write multiple programs which analyze the data in different ways. The sqlite database itself can be accessed from a variety of programming languages, GUI/CLI interfaces. Your da...
ndarray field names for both row and column?
3,910,301
7
2010-10-11T22:08:34Z
3,910,961
10
2010-10-12T00:41:38Z
[ "python", "numpy" ]
I'm a computer science teacher trying to create a little gradebook for myself using NumPy. But I think it would make my code easier to write if I could create an ndarray that uses field names for both the rows and columns. Here's what I've got so far: ``` import numpy as np num_stud = 23 num_assign = 2 grades = np.zer...
From you description, you'd be better off using a different data structure than a standard numpy array. `ndarray`s aren't well suited to this... They're not spreadsheets. However, there has been extensive recent work on a type of numpy array that *is* well suited to this use. [Here's a description](http://projects.sci...
python SocketServer.BaseRequestHandler knowing the port and use the port already opened
3,911,009
2
2010-10-12T01:01:09Z
6,260,204
9
2011-06-07T02:55:29Z
[ "python", "sockets", "port", "socketserver" ]
This is the code which i played, but each time i make a mistake i can't relaunch it. It says to me that the port / socket is already used That's the first question The second one is in my MyTCPHandler how can i kno the port used ? here is my code : ``` # MetaProject v 0.2 # -*- coding: utf-8 -*- """ Thanks to : People...
It's actually easier than that -- you can just set it as a class variable, rather than overriding **init**. E.g., ``` class MyServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): allow_reuse_address = True ```
Python slice how-to, I know the Python slice but how can I use built-in slice object for it?
3,911,483
37
2010-10-12T03:27:10Z
3,911,763
45
2010-10-12T04:43:17Z
[ "python", "slice" ]
What's the use of built-in function `slice` and how can I use it? The direct way of Pythonic slicing I know - `l1[start:stop:step]`. I want to know if I have a slice object, then how do I use it?
You create a slice by calling slice with the same fields you would use if doing [start:end:step] notation: ``` sl = slice(0,4) ``` To use the slice, just pass it as if it were the index into a list or string: ``` >>> s = "ABCDEFGHIJKL" >>> sl = slice(0,4) >>> print s[sl] 'ABCD' ``` Let's say you have a file of fixe...
Python slice how-to, I know the Python slice but how can I use built-in slice object for it?
3,911,483
37
2010-10-12T03:27:10Z
3,912,107
16
2010-10-12T06:16:45Z
[ "python", "slice" ]
What's the use of built-in function `slice` and how can I use it? The direct way of Pythonic slicing I know - `l1[start:stop:step]`. I want to know if I have a slice object, then how do I use it?
Square brackets following a sequence denote either indexing or slicing depending on what's inside the brackets: ``` >>> "Python rocks"[1] # index 'y' >>> "Python rocks"[1:10:2] # slice 'yhnrc' ``` Both of these cases are handled by the `__getitem__()` method of the sequence (or `__setitem__()` if on the left of...
"Pythonic" multithreaded (Concurrent) language
3,911,897
3
2010-10-12T05:26:55Z
3,912,215
7
2010-10-12T06:43:56Z
[ "python", "multithreading", "multiprocessing", "concurrency" ]
I now primarily write in python, however I am looking for a language that is more thread friendly (not JAVA,C#,C or C++). Python's threads are good when they are IO bound but it's coming up short when I am doing something CPU intensive. Any ideas? Thanks, James
Clojure is pretty fun, if you're into that sort of thing. It's a lisp that runs on the JVM. Apparently it's as fast as Java for a lot of things, despite being dynamically typed \*. Java interop is about as convenient as I could imagine possible, though the native clojure libraries are already decent enough that you don...
What are Python namespaces all about
3,913,217
21
2010-10-12T09:30:05Z
3,913,488
27
2010-10-12T10:05:36Z
[ "python", "programming-languages", "namespaces" ]
I have just started learning Python & have come across **"namespaces"** concept in Python. While I got the jist of what it is, but am unable to appreciate the gravity of this concept. Some browsing on the net revealed that one of the reasons going against PHP is that it has no native support for namespaces. **Could s...
Namespace is a way to implement scope. In Java (or C) the compiler determines where a variable is visible through static scope analysis. * In C, scope is either the body of a function or it's global or it's external. The compiler reasons this out for you and resolves each variable name based on scope rules. External ...
Django - ManyToManyField in a model, setting it to null?
3,913,499
5
2010-10-12T10:07:49Z
3,913,508
9
2010-10-12T10:09:15Z
[ "python", "django", "django-models", "manytomanyfield" ]
I have a django model (A) which has a ManyToManyField (types) to another model (B). Conceptually the field in A is an 'optionally limit this object to these values'. I have set `blank=null` and `null=True` on the ManyToManyField. I have created an object from this model, and set types to some values. All is good. I wa...
That's what `clear()` is for. <http://docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.related.RelatedManager.clear> Perhaps you're looking for `remove()`? <http://docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.related.RelatedManager.remove>
False or None vs. None or False
3,914,667
16
2010-10-12T12:29:54Z
3,914,686
36
2010-10-12T12:31:47Z
[ "python", "boolean-logic" ]
``` In [20]: print None or False -------> print(None or False) False In [21]: print False or None -------> print(False or None) None ``` This behaviour confuses me. Could someone explain to me why is this happening like this? I expected them to both behave the same.
The expression `x or y` evaluates to `x` if `x` is true, or `y` if `x` is false. Note that "true" and "false" in the above sentence are talking about "truthiness", not the fixed values `True` and `False`. Something that is "true" makes an `if` statement succeed; something that's "false" makes it fail. "false" values i...
How to turn a float number like 293.4662543 into 293.47 in python?
3,914,725
3
2010-10-12T12:35:38Z
3,914,795
10
2010-10-12T12:43:37Z
[ "python", "number-formatting" ]
How to shorten the float result I got? I only need 2 digits after the dot. Sorry I really don't know how to explain this better in English... Thanks
From The Floating-Point Guide's [Python cheat sheet](http://floating-point-gui.de/languages/python/): ``` "%.2f" % 1.2399 # returns "1.24" "%.3f" % 1.2399 # returns "1.240" "%.2f" % 1.2 # returns "1.20" ``` Using round() is the wrong thing to do, because floats are [binary fractions](http://floating-point-gui.de/form...
Dynamically creating classes - Python
3,915,024
18
2010-10-12T13:10:07Z
3,915,082
31
2010-10-12T13:16:55Z
[ "python", "django", "class", "forms", "dynamic" ]
**I need to dynamically create a class. To go in futher detail I need to dynamically create a subclass of Django's Form class.** By dynamically I intend to create a class based on configuration provided by a user. --- e.g. > I want a **class named CommentForm** which should **subclass the Form class** > > The class...
You can create classes on the fly by calling the `type` built-in, passing appropriate arguments along, like: ``` CommentForm = type("CommentForm", (Form,), { 'name': forms.CharField(), ... }) ``` It works with new-style classes. I am not sure, whether this would also work with old-style classes.
Dynamically creating classes - Python
3,915,024
18
2010-10-12T13:10:07Z
3,915,110
11
2010-10-12T13:19:58Z
[ "python", "django", "class", "forms", "dynamic" ]
**I need to dynamically create a class. To go in futher detail I need to dynamically create a subclass of Django's Form class.** By dynamically I intend to create a class based on configuration provided by a user. --- e.g. > I want a **class named CommentForm** which should **subclass the Form class** > > The class...
Classes can be defined almost anywhere. ``` def newclass(val): class C(object): def __str__(self): return str(val) return C MyClass = newclass(5) m = MyClass() print str(m) ```
How to test same assertion for large amount of data
3,915,232
10
2010-10-12T13:32:00Z
3,923,268
8
2010-10-13T11:48:35Z
[ "python", "unit-testing", "pyunit" ]
I am using python unittest module to do a number of tests; however, it is very repetitive. I have a lot of data that I want to run through the same test over and over, checking if correct. However, I have to define a test for every one. For instance I want to do something similar to this. I know I could do it using a...
Sample code for solution suggested by Bill Gribble could look like this: ``` import unittest class DataTestCase(unittest.TestCase): def __init__(self, number): unittest.TestCase.__init__(self, methodName='testOneNumber') self.number = number def testOneNumber(self): self.assertEqual(s...
Generic Python metaclass to keep track of subclasses
3,915,315
8
2010-10-12T13:40:47Z
3,915,441
8
2010-10-12T13:53:47Z
[ "python", "metaclass" ]
I'm trying to writing a generic metaclass for tracking subclasses Since I want this to be generic, I didn't want to hardcode any class name within this metaclass, therefore I came up with a function that generates the proper metaclass, something like: ``` def make_subtracker(root): class SubclassTracker(type): ...
I think you want something like this (untested): ``` class SubclassTracker(type): def __init__(cls, name, bases, dct): if not hasattr(cls, '_registry'): cls._registry = [] print('registering %s' % (name,)) cls._registry.append(cls) super(SubclassTracker, cls).__init__(na...
Generic Python metaclass to keep track of subclasses
3,915,315
8
2010-10-12T13:40:47Z
3,918,389
8
2010-10-12T19:44:06Z
[ "python", "metaclass" ]
I'm trying to writing a generic metaclass for tracking subclasses Since I want this to be generic, I didn't want to hardcode any class name within this metaclass, therefore I came up with a function that generates the proper metaclass, something like: ``` def make_subtracker(root): class SubclassTracker(type): ...
Python does this automatically for new-style classes, as mentioned in this [answer](http://stackoverflow.com/questions/3862310/how-can-i-find-all-subclasses-of-a-given-class-in-python/3862957#3862957) to the similar queston [How can I find all subclasses of a given class in Python?](http://stackoverflow.com/questions/3...
How do I properly format a StringIO object(python and django) to be inserted into an database?
3,915,888
4
2010-10-12T14:48:28Z
3,927,989
13
2010-10-13T21:04:03Z
[ "python", "django", "django-models" ]
I have a requeriment to store images in the database using django, and for that I created a custom field : ``` from django.db import models class BlobField(models.Field): __metaclass__ = models.SubfieldBase def db_type(self, connection): #TODO handle other db engines backend = connection.set...
There is no constraint requiring `get_db_prep_value` to return "printable" characters, or ASCII ones, or otherwise-constrained sets of characters: return any byte string that catches your fancy. You'll get a string in `to_python` and can make a file-like `StringIO` instance reading its data with `the_instance = StringI...
gtk minimum size
3,916,762
5
2010-10-12T16:12:25Z
3,916,901
8
2010-10-12T16:29:00Z
[ "c++", "python", "c", "gtk", "pygtk" ]
Is there an easy way to request that a GTK widget have a minimum width/height? I know you can do it on the column of a `TreeView`, but is it available for general widgets?
For C/C++: [gtk\_widget\_set\_size\_request()](http://library.gnome.org/devel/gtk/unstable/GtkWidget.html#gtk-widget-set-size-request) > Sets the minimum size of a widget; that is, the widget's size request will be width by height. PyGTK: [def set\_size\_request(width, height)](http://www.pygtk.org/docs/pygtk/class-g...
Iron Python vs Razor
3,916,787
2
2010-10-12T16:15:36Z
3,917,668
7
2010-10-12T18:08:31Z
[ "python", "ironpython", "razor" ]
I have a little bit of experience with the new Razor syntax, but none with Iron Python. I was wondering do both meet the same needs? Is one favored by Microsoft over the other (or will be)? Appreciate your thoughts, as I'm toying with the idea of learning Iron Python, but if Razor can meet the same need, I probably won...
To expand on the answer given by PaulStack: Razor is a templating engine (with a slant towards templating XML-style documents, e.g. HTML web pages) that is available as a View Engine in MVC 3 as well as the default page syntax in ASP.NET Web Pages (which is part of the WebMatrix stack). The Razor parser uses assumptio...
How is Python's List Implemented?
3,917,574
74
2010-10-12T17:56:33Z
3,917,591
19
2010-10-12T17:59:29Z
[ "python", "arrays", "list", "linked-list", "python-internals" ]
Is it a linked list, an array? I searched around and only found people guessing. My C knowledge isn't good enough to look at the source code.
This is implementation dependent, but IIRC: * CPython uses an array of pointers * Jython uses an `ArrayList` * IronPython apparently also uses an array. You can browse the [source code](http://ironpython.codeplex.com/SourceControl/BrowseLatest) to find out. Thus they all have O(1) random access.
How is Python's List Implemented?
3,917,574
74
2010-10-12T17:56:33Z
3,917,596
24
2010-10-12T18:00:23Z
[ "python", "arrays", "list", "linked-list", "python-internals" ]
Is it a linked list, an array? I searched around and only found people guessing. My C knowledge isn't good enough to look at the source code.
In CPython, lists are arrays of pointers. Other implementations of Python may choose to store them in different ways.
How is Python's List Implemented?
3,917,574
74
2010-10-12T17:56:33Z
3,917,632
32
2010-10-12T18:04:10Z
[ "python", "arrays", "list", "linked-list", "python-internals" ]
Is it a linked list, an array? I searched around and only found people guessing. My C knowledge isn't good enough to look at the source code.
It's an array. Practical proof: Indexing takes (of course with extremely small differences (0.0013 µsecs!)) the same time regardless of index: ``` ...>python -m timeit --setup="x = [None]*1000" "x[500]" 10000000 loops, best of 3: 0.0579 usec per loop ...>python -m timeit --setup="x = [None]*1000" "x[0]" 10000000 loo...
How is Python's List Implemented?
3,917,574
74
2010-10-12T17:56:33Z
3,958,322
130
2010-10-18T10:39:40Z
[ "python", "arrays", "list", "linked-list", "python-internals" ]
Is it a linked list, an array? I searched around and only found people guessing. My C knowledge isn't good enough to look at the source code.
The C code is pretty simple, actually. Expanding one macro and pruning some irrelevant comments, the basic structure is in [`listobject.h`](http://hg.python.org/cpython/file/tip/Include/listobject.h#l22), which defines a list as: ``` typedef struct { PyObject_HEAD Py_ssize_t ob_size; /* Vector of pointers...
How is Python's List Implemented?
3,917,574
74
2010-10-12T17:56:33Z
10,852,811
16
2012-06-01T15:07:33Z
[ "python", "arrays", "list", "linked-list", "python-internals" ]
Is it a linked list, an array? I searched around and only found people guessing. My C knowledge isn't good enough to look at the source code.
According to the [documentation](http://docs.python.org/faq/design.html#how-are-lists-implemented), > Python’s lists are really variable-length arrays, not Lisp-style linked lists.
How do I plot multiple X or Y axes in matplotlib?
3,918,028
21
2010-10-12T18:54:47Z
3,919,443
19
2010-10-12T22:06:33Z
[ "python", "matplotlib" ]
I'm currently using matplotlib to plot a measurement against 2 or 3 other measurements (sometimes categorical) on the x-axis. Currently, I am grouping the data on the x-axis into tuples and sorting them before plotting... the result looks something like the left image below. What I would like to do is to plot the data ...
First off, cool question! It's definitely possible with matplotlib >= 1.0.0. (The new spines functionality allows it) It requires a fair bit of voodoo, though... My example is far from perfect, but hopefully it makes some sense: ``` import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl def main...
How do I plot multiple X or Y axes in matplotlib?
3,918,028
21
2010-10-12T18:54:47Z
3,919,530
9
2010-10-12T22:23:43Z
[ "python", "matplotlib" ]
I'm currently using matplotlib to plot a measurement against 2 or 3 other measurements (sometimes categorical) on the x-axis. Currently, I am grouping the data on the x-axis into tuples and sorting them before plotting... the result looks something like the left image below. What I would like to do is to plot the data ...
Joe's example is good. I'll throw mine in too. I was working on it a few hours ago, but then had to run off to a meeting. It steals from [here](http://matplotlib.sourceforge.net/examples/pylab_examples/multiple_yaxis_with_spines.html). ``` import matplotlib.pyplot as plt import matplotlib.ticker as ticker ## the foll...
How to make sure a file exists or can be created before writing to it in Python?
3,918,433
3
2010-10-12T19:48:45Z
3,918,457
12
2010-10-12T19:51:05Z
[ "python", "file-io", "filesystems" ]
I'm writing a function and I want it to `touch` a file so that I can write to that file. If the file doesn't exist, I will get an error. How can I say that?
Just open the file for writing and it will be created if it doesn't exist (assuming you have proper permission to write to that location). ``` f = open('some_file_that_might_not_exist.txt', 'w') f.write(data) ``` You will get an `IOError` if you can't open the file for writing.
How to make sure a file exists or can be created before writing to it in Python?
3,918,433
3
2010-10-12T19:48:45Z
3,918,908
7
2010-10-12T20:49:13Z
[ "python", "file-io", "filesystems" ]
I'm writing a function and I want it to `touch` a file so that I can write to that file. If the file doesn't exist, I will get an error. How can I say that?
Per [the docs, os.utime()](http://docs.python.org/library/os.html#os.utime) will function similar to touch if you give it None as the time argument, for example: ``` os.utime("test_file", None) ``` When I tested this (on Linux and later Windows), I found that test\_file had to already exist. YMMV on other OS's. Of c...
splitting the bill algorithmically & fair, afterwards :)
3,918,567
3
2010-10-12T20:07:30Z
3,918,592
9
2010-10-12T20:10:54Z
[ "python", "algorithm", "math", "floating-accuracy" ]
I'm trying to solve the following real-life problem you might have encountered yourselves: You had dinner with some friends and you all agreed to split the bill evenly. Except that when the bill finally arrives, you find out not everyone has enough cash on them (if any, cheap bastards). So, some of you pays more than...
<http://www.billmonk.com/> Amongst others. The problem has already been solved. Many times over. --- > "Theoratically, the sum of the differences should be zero, right?" Yes. Since you've used `float`, however, you have representation issues when the number of people is not a power of two. Never. Use. `float` For....
Parse a map of int -> list from a string
3,918,797
3
2010-10-12T20:34:16Z
3,918,829
8
2010-10-12T20:38:42Z
[ "python" ]
This should be a fairly straight forward python question, but I'm getting stuck getting the syntax right. Let's say I have a string: ``` "1:a,b,c::2:e,f,g::3:h,i,j" ``` and I want to convert this to a map like so: ``` {'1': ['a', 'b', 'c'], '2': ['e', 'f', 'g'], '3': ['h', 'i', 'j']} ``` How would this be done? I...
Here's one approach: ``` dict((k, v.split(',')) for k,v in (x.split(':') for x in s.split('::'))) ```
How to continuously monitor rhythmbox for track change using python
3,919,735
4
2010-10-12T23:07:10Z
4,111,731
12
2010-11-06T03:20:39Z
[ "python", "monitor", "dbus", "rhythmbox" ]
I want to monitor the change of track in Rhythmbox using python. I want to continuously check for change of track and execute a set of functions if the track is changed. I have written a piece of code which gets hold of the Rhythmbox interfaces from the dbus and gets the current track details. But this program has to b...
The Rhythmbox player object (`/org/gnome/Rhythmbox/Player`) sends a `playingUriChanged` signal whenever the current song changes. Connect a function to the signal to have it run whenever the signal is received. Here's an example that prints the title of the song whenever a new song starts, using the GLib main loop to p...
Python - Flipping Binary 1's and 0's in a String
3,920,494
3
2010-10-13T03:04:40Z
3,920,499
19
2010-10-13T03:06:53Z
[ "python" ]
I'm trying to take a binary number in string form and flip the 1's and 0's, that is, change all of the 1's in the string to 0's, and all of the 0's to 1's. I'm new to Python and have been racking my brain for several hours now trying to figure it out.
``` >>> ''.join('1' if x == '0' else '0' for x in '1000110') '0111001' ``` The `a for b in c` pattern is a *generator expression*, which produces a series of items based on a different series. In this case, the original series is the characters (since you can iterate over strings in Python, which gives you the charact...
Python - Flipping Binary 1's and 0's in a String
3,920,494
3
2010-10-13T03:04:40Z
3,920,534
11
2010-10-13T03:16:05Z
[ "python" ]
I'm trying to take a binary number in string form and flip the 1's and 0's, that is, change all of the 1's in the string to 0's, and all of the 0's to 1's. I'm new to Python and have been racking my brain for several hours now trying to figure it out.
Another way to do it is with [`string.translate()`](http://docs.python.org/library/stdtypes.html#str.translate) and [`string.maketrans()`](http://docs.python.org/library/string.html#string.maketrans) ``` from string import maketrans bitString = "10101010100011010" flippedString = bitString.translate(maketrans("10","01...
How to suppress a third-party warning using warnings.filterwarnings
3,920,502
15
2010-10-13T03:08:02Z
3,920,894
24
2010-10-13T04:59:48Z
[ "python", "suppress-warnings", "paramiko", "pycrypto" ]
I am using Paramiko in my python code (for sftp). Everything works fine except that everytime I import or call a paramiko function. This warning would show up: ``` C:\Python26\lib\site-packages\Crypto\Util\randpool.py:40: RandomPool_Deprecation Warning: This application uses RandomPool, which is BROKEN in older releas...
Easiest way would be as the warnings module suggests [here](http://docs.python.org/library/warnings.html#temporarily-suppressing-warnings): ``` with warnings.catch_warnings(): warnings.simplefilter("ignore") import paramiko ```
Linear Regression with Python numpy
3,920,571
6
2010-10-13T03:25:35Z
3,920,660
7
2010-10-13T03:57:15Z
[ "python", "numpy", "linear-regression" ]
I'm trying to make a simple linear regression function but continue to encounter a numpy.linalg.linalg.LinAlgError: Singular matrix error Existing function (with debug): ``` def makeLLS(inputData, targetData): print "In makeLLS:" print " Shape inputData:",inputData.shape print " Shape targetData:",...
A singular matrix is one for which the determinant is zero. This indicates that your matrix has rows that aren't linearly independent. For instance, if one of the rows is not linearly independent of the others, then it can be constructed by a linear combination of the other rows. I'll use numpy's linalg.solve example t...
Linear Regression with Python numpy
3,920,571
6
2010-10-13T03:25:35Z
3,921,663
14
2010-10-13T07:44:46Z
[ "python", "numpy", "linear-regression" ]
I'm trying to make a simple linear regression function but continue to encounter a numpy.linalg.linalg.LinAlgError: Singular matrix error Existing function (with debug): ``` def makeLLS(inputData, targetData): print "In makeLLS:" print " Shape inputData:",inputData.shape print " Shape targetData:",...
As explained in the other answer `linalg.solve` expects a full rank matrix. This is because it tries to solve a matrix equation rather than do linear regression which should work for all ranks. There are a few methods for linear regression. The simplest one I would suggest is the standard least squares method. Just us...
IndentationError: unexpected indent error
3,920,628
12
2010-10-13T03:44:18Z
3,920,674
25
2010-10-13T04:00:49Z
[ "python", "syntax", "indentation" ]
I am new to Python and am getting this error: ``` Traceback (most recent call last): File "/usr/local/bin/scrapy", line 4, in <module> execute() File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scrapy/cmdline.py", line 130, in execute _run_print_help(parser, _ru...
While the indentation errors are obvious in the StackOverflow page, they may not be in your editor. You have a mix of different indentation types here, 1, 4 and 8 spaces. You should always use four spaces for indentation, as per [PEP8](http://www.python.org/dev/peps/pep-0008/). You should also [avoid mixing tabs and sp...