title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
python-mode documentation for Emacs
8,993,463
6
2012-01-24T20:14:33Z
8,993,774
8
2012-01-24T20:38:06Z
[ "python", "emacs" ]
I just installed the python-mode in Emacs and it seems to be working well. However, I could not find documentation for the package on [the official site](https://launchpad.net/python-mode). The package comes with a `doc` folder where I can see two files: ``` commands-python-mode.org commands-python-mode.rst ``` Both...
Start off with `M-x describe-mode`. This gives you an overview over the available key bindings. For each command use `C-f name RET` to see the built-in documentation. The `.org` file should be an `org-mode` file and easily readable with Emacs. See also [here](https://web.archive.org/web/20140126011914/http://www.pytho...
Is there InnerText equivalent in BeautifulSoup / python?
8,993,854
20
2012-01-24T20:43:22Z
8,994,150
23
2012-01-24T21:05:57Z
[ "python", "beautifulsoup" ]
With the code below ``` soup = BeautifulSoup(page.read(), fromEncoding="utf-8") result = soup.find('div', {'class' :'flagPageTitle'}) ``` I get the following html: ``` <div id="ctl00_ContentPlaceHolder1_Item65404" class="flagPageTitle" style=" "> <span></span><p>Some text here</p> </div> ``` How can I get `Some...
All you need is: ``` result = soup.find('div', {'class' :'flagPageTitle'}).text ```
Python regex split case insensitive in 2.6
8,993,904
5
2012-01-24T20:46:51Z
8,994,008
11
2012-01-24T20:54:46Z
[ "python", "regex" ]
I have the following code that works in Python 2.7: ``` entry_regex = '(' + search_string + ')' entry_split = re.split(entry_regex, row, 1, re.IGNORECASE) ``` I need to make it work in Python 2.6 as well as in Python 2.7 and 2.6 re.split doesn't accept a flag (re.IGNORECASE) as forth parameter. Any help? Thanks
You can just add (?i) to the regular expression to make it case insensitive: ``` >>> import re >>> reg = "(foo)(?i)" >>> re.split(reg, "fOO1foo2FOO3") ['', 'fOO', '1', 'foo', '2', 'FOO', '3'] ```
Django-haystack returns results with "simple" backend, but not with "whoosh"
8,994,241
4
2012-01-24T21:13:00Z
9,044,659
7
2012-01-28T10:45:17Z
[ "python", "django", "django-haystack", "whoosh" ]
I'm trying to integrate a search with django-haystack, While it works well with the "sample" backend, when replacing the backend with whoosh it always returns 0 results. settings.py: ``` HAYSTACK_DEFAULT_OPERATOR = 'AND' HAYSTACK_SITECONF = 'search_sites' HAYSTACK_SEARCH_ENGINE = 'whoosh' HAYSTACK_SEARCH_RESULTS_PE...
Ok, found it, and it was even more stupid then I though... `templates/search/indexes/profiles/profile_text.txt` should be: ``` {{ object.name }} {{ object.description }} ``` And not: ``` {{ profile.name }} {{ profile.description }} ``` What confused me was that the "simple" backend that matches against the databas...
itertools.ifilter Vs. filter Vs. list comprehensions
8,994,319
15
2012-01-24T21:19:33Z
8,995,857
16
2012-01-24T23:31:51Z
[ "python", "function", "module", "functionality", "builtins" ]
I am trying to become more familiar with the `itertools` module and have found a function called `ifilter`. From what I understand, it filters and iterable based on the given function and returns an iterator over a list containing the elements of the iterable on which the function evaluates to `True`. **Question 1**:...
Your understanding is corret: the only difference is that `ifilter` returns an iterator, while using `filter` is like calling: ``` list(ifilter(...)) ``` You may also be interested in what [PEP 289](http://www.python.org/dev/peps/pep-0289/) says about filter and ifilter: > List comprehensions greatly reduced the nee...
Want to make static SVG plot (from matplotlib) interactive via the browser
8,994,357
10
2012-01-24T21:22:15Z
10,542,968
11
2012-05-10T22:19:57Z
[ "javascript", "python", "svg", "matplotlib" ]
My goal is to make a plot that you can interact with in the browser. Ideally, I would like a well-documented and mature JavaScript plotting library that supports SVG. As far as I can tell, this doesn't exist, though please correct me if I'm wrong. I've identified a couple alternatives. 1. **Use a JavaScript graphics ...
One way to this can be seen in the [matplotlib gallery](http://matplotlib.sourceforge.net/examples/user_interfaces/svg_histogram.html). Basically: 1. In matplotlib, use element.set\_gid("youridhere") on the matplotlib element you wish to make interactive. That is, use set\_gid() on the output from plot()/hist()/whate...
When are Python threads fast?
8,994,438
8
2012-01-24T21:28:18Z
8,994,504
11
2012-01-24T21:32:46Z
[ "python", "multithreading", "gil" ]
We're all aware of the horrors of the [GIL](http://en.wikipedia.org/wiki/Global_Interpreter_Lock), and I've seen a lot of discussion about the right time to use the `multiprocessing` module, but I still don't feel that I have a good intuition about when threading in Python (focusing mainly on CPython) is the right answ...
Threading really only makes sense if you have a lot of blocking I/O going on. If that's the case, then some threads can sleep while other threads work. If threads are CPU-bound, you're not likely to see much benefit from multithreading. Note that the [multiprocessing](http://docs.python.org/library/multiprocessing.htm...
When are Python threads fast?
8,994,438
8
2012-01-24T21:28:18Z
8,994,790
8
2012-01-24T21:55:00Z
[ "python", "multithreading", "gil" ]
We're all aware of the horrors of the [GIL](http://en.wikipedia.org/wiki/Global_Interpreter_Lock), and I've seen a lot of discussion about the right time to use the `multiprocessing` module, but I still don't feel that I have a good intuition about when threading in Python (focusing mainly on CPython) is the right answ...
Since you seem to be looking for examples, here are some off the top of my head and grabbed from searching for CPU-bound and I/O-bound examples (I can't seem to find many). I am no expert, so please feel free to correct anything I've miscategorized. It's also worth noting that advancing technology could move a problem ...
Removing multiple keys from a dictionary safely
8,995,611
46
2012-01-24T23:05:51Z
8,995,760
16
2012-01-24T23:20:23Z
[ "python", "dictionary" ]
I know to remove an entry, 'key' from my dictionary `d`, safely, you do: ``` if d.has_key('key'): del d['key'] ``` However, I need to remove multiple entries from dictionary safely. I was thinking of defining the entries in a tuple as I will need to do this more than once. ``` entitiesToREmove = ('a', 'b', 'c') ...
Why not like this: ``` entries = ('a', 'b', 'c') the_dict = {'b': 'foo'} def entries_to_remove(entries, the_dict): for key in entries: if key in the_dict: del the_dict[key] ```
Removing multiple keys from a dictionary safely
8,995,611
46
2012-01-24T23:05:51Z
8,995,774
66
2012-01-24T23:22:05Z
[ "python", "dictionary" ]
I know to remove an entry, 'key' from my dictionary `d`, safely, you do: ``` if d.has_key('key'): del d['key'] ``` However, I need to remove multiple entries from dictionary safely. I was thinking of defining the entries in a tuple as I will need to do this more than once. ``` entitiesToREmove = ('a', 'b', 'c') ...
``` d = {'some':'data'} entriesToRemove = ('any', 'iterable') for k in entriesToRemove: d.pop(k, None) ```
Removing multiple keys from a dictionary safely
8,995,611
46
2012-01-24T23:05:51Z
8,995,801
33
2012-01-24T23:25:09Z
[ "python", "dictionary" ]
I know to remove an entry, 'key' from my dictionary `d`, safely, you do: ``` if d.has_key('key'): del d['key'] ``` However, I need to remove multiple entries from dictionary safely. I was thinking of defining the entries in a tuple as I will need to do this more than once. ``` entitiesToREmove = ('a', 'b', 'c') ...
Using **Dict Comprehensions** ``` final_dict = {key: t[key] for key in t if key not in [key1, key2]} ``` where **key1** and **key2** are to be removed. In the example below, keys "b" and "c" are to be removed & it's kept in a keys list. ``` >>> a {'a': 1, 'c': 3, 'b': 2, 'd': 4} >>> keys = ["b", "c"] >>> print {key...
Removing multiple keys from a dictionary safely
8,995,611
46
2012-01-24T23:05:51Z
8,995,828
12
2012-01-24T23:27:52Z
[ "python", "dictionary" ]
I know to remove an entry, 'key' from my dictionary `d`, safely, you do: ``` if d.has_key('key'): del d['key'] ``` However, I need to remove multiple entries from dictionary safely. I was thinking of defining the entries in a tuple as I will need to do this more than once. ``` entitiesToREmove = ('a', 'b', 'c') ...
If you also needed to retrieve the values for the keys you are removing, this would be a pretty good way to do it: ``` valuesRemoved = [d.pop(k, None) for k in entitiesToRemove] ``` You could of course still do this just for the removal of the keys from `d`, but you would be unnecessarily creating the list of values ...
Removing multiple keys from a dictionary safely
8,995,611
46
2012-01-24T23:05:51Z
30,351,294
7
2015-05-20T13:35:13Z
[ "python", "dictionary" ]
I know to remove an entry, 'key' from my dictionary `d`, safely, you do: ``` if d.has_key('key'): del d['key'] ``` However, I need to remove multiple entries from dictionary safely. I was thinking of defining the entries in a tuple as I will need to do this more than once. ``` entitiesToREmove = ('a', 'b', 'c') ...
a solution is using `map` and `filter` functions ``` d={"a":1,"b":2,"c":3} l=("a","b","d") map(d.__delitem__, filter(d.__contains__,l)) #list(map(...)) in python 3.X print(d) ``` you get: ``` {'c': 3} ```
Admin Site: TemplateDoesNotExist at /admin/
8,996,549
8
2012-01-25T00:51:38Z
31,952,997
15
2015-08-11T22:21:45Z
[ "python", "django", "django-admin" ]
I'm following Django's official [Tutorial 2](https://docs.djangoproject.com/en/1.3/intro/tutorial02/) but for some reason cannot create an admin site despite following all the steps correctly to my understanding. This is the error I get: ``` TemplateDoesNotExist at /admin/ admin/login.html Request Method: GET Request...
I ran into the same problem, and I had to force pip to re-download django. ``` pip install -r requirements.txt --ignore-installed --force-reinstall --upgrade --no-cache-dir ``` Note: I know that the `--no-cache-dir` option is necessary, I'm not certain that the other options are all required.
Is there any way to access nested or re-raised exceptions in python?
8,997,431
8
2012-01-25T03:18:04Z
9,000,152
9
2012-01-25T09:14:43Z
[ "python", "traceback" ]
A common pattern in python is to catch an error in an upstream module and re-raise that error as something more useful. ``` try: config_file = open('config.ini', 'r') except IOError: raise ConfigError('Give me my config, user!') ``` This will generate a stack trace of the form ``` Traceback (most recent call...
This is known as *Exception Chaining* and is suported in Python 3. PEP 3134: <http://www.python.org/dev/peps/pep-3134/> In Python 2, the old exception is lost when you raise a new one, unless you save it in the `except` block.
Google Appspot and Wordpress
8,997,486
2
2012-01-25T03:29:02Z
9,000,554
8
2012-01-25T09:46:08Z
[ "php", "python", "wordpress", "google-app-engine" ]
Well, I'm currently attempting to build a website using the hosting from [Google Appspot.](http://www.appspot.com) I would like to make a blog portion of my website using Wordpress. How can I host Wordpress on Google Appspot, despite that one uses Python and the other uses PHP (If I remember correctly)?
Wordpress [requires the hosting service to be able to support PHP and MySQL](http://wordpress.org/about/requirements/), both of which are not directly supported by Google App Engine, the underlying "hosting engine" behind what you called Google Appspot. [Google App Engine](http://code.google.com/appengine/) is more ak...
What controls automated window resizing in Tkinter?
8,997,497
8
2012-01-25T03:30:55Z
9,002,361
11
2012-01-25T12:00:32Z
[ "python", "tkinter" ]
Tkinter top level windows seem to have two "modes": where the size is being determined by the application, and where the user controls the size. Consider this code: ``` from tkinter import * class Test(Frame): def __init__(self,parent): Frame.__init__(self,parent) self.b1 = Button(self, text="Butt...
The rule is pretty simple - a toplevel window has a fixed size whenever it has been given a fixed size, otherwise it "shrinks to fit". There are two ways to give the top level window a fixed size: the user can resize it manually, or your application code can call [`wm_geometry`](http://effbot.org/tkinterbook/wm.htm#Tk...
What hash algorithm does Python's dictionary mapping use?
8,997,894
11
2012-01-25T04:40:47Z
8,998,010
17
2012-01-25T04:56:28Z
[ "python", "hashmap" ]
I was messing around with making a command line parser and was wondering what kind of hash algorithm python dict's use? The way I have it set up, I have a pattern match algorithm which matches tokenized input sequences with a dictionary key. Some of the keys are relatively long (length 5 or 6 tuples of 6-7 character s...
The hash that it uses depends on the object being used as a key -- each class can define its own \_\_hash\_\_() method, and the value that it returns for a particular instance is what is used for the dictionary. Python itself provides the hash implementation for str and tuple types. A quick look at the source should r...
why superclass attributes are not available in the current class' namespace?
8,998,608
2
2012-01-25T06:13:59Z
8,998,854
7
2012-01-25T06:48:35Z
[ "python", "class", "namespaces", "python-3.x", "class-attributes" ]
Example: ``` class A: a = 1 class B(A): b = 2 y = b # works fine x = a # NameError: name 'a' is not defined x = A.a # works fine z = B() z.a # works fine B.a # works fine ``` Why is `x = a` not allowed? In every other context (access through an instance, access through the subclass name) it work...
When you write this: ``` class B(A): b = 2 y = b # works fine x = a # NameError: name 'a' is not defined x = A.a # works fine ``` What Python does is create a new scope (stored in a dictionary), execute all your definitions, then at the end of the class block it passes the dictionary to the `type` cla...
How to check blas/lapack linkage in numpy/scipy?
9,000,164
75
2012-01-25T09:15:34Z
9,001,951
9
2012-01-25T11:29:48Z
[ "python", "numpy", "scipy", "lapack", "blas" ]
I am builing my numpy/scipy environment based on blas and lapack more or less based on [this](http://www.tfinley.net/notes/blas-lapack/) walk through. When I am done, how can I check, that my numpy/scipy functions really do use the previously built blas/lapack functionalities?
As it uses the dynamically loaded versions, you can just do this: ``` $ ldd anyoftheCmodules.so ``` where `anyoftheCmodules.so` could be, for example, `numpy/core/_dotblas.so`, which links to `libblas.so`.
How to check blas/lapack linkage in numpy/scipy?
9,000,164
75
2012-01-25T09:15:34Z
9,002,083
7
2012-01-25T11:39:17Z
[ "python", "numpy", "scipy", "lapack", "blas" ]
I am builing my numpy/scipy environment based on blas and lapack more or less based on [this](http://www.tfinley.net/notes/blas-lapack/) walk through. When I am done, how can I check, that my numpy/scipy functions really do use the previously built blas/lapack functionalities?
You can use the link loader dependency tool to look at the C level hook components of your build and see whether they have external dependencies on your blas and lapack of choice. I am not near a linux box right now, but on an OS X machine you can do this inside the site-packages directory which holds the installations...
How to check blas/lapack linkage in numpy/scipy?
9,000,164
75
2012-01-25T09:15:34Z
9,002,656
23
2012-01-25T12:24:16Z
[ "python", "numpy", "scipy", "lapack", "blas" ]
I am builing my numpy/scipy environment based on blas and lapack more or less based on [this](http://www.tfinley.net/notes/blas-lapack/) walk through. When I am done, how can I check, that my numpy/scipy functions really do use the previously built blas/lapack functionalities?
What you are searching for is this: [system info](https://github.com/numpy/numpy/blob/master/numpy/distutils/system_info.py) I compiled numpy/scipy with atlas and i can check this with: ``` import numpy.distutils.system_info as sysinfo sysinfo.get_info('atlas') ``` Check the documentation for more commands.
How to check blas/lapack linkage in numpy/scipy?
9,000,164
75
2012-01-25T09:15:34Z
19,350,234
135
2013-10-13T21:01:24Z
[ "python", "numpy", "scipy", "lapack", "blas" ]
I am builing my numpy/scipy environment based on blas and lapack more or less based on [this](http://www.tfinley.net/notes/blas-lapack/) walk through. When I am done, how can I check, that my numpy/scipy functions really do use the previously built blas/lapack functionalities?
The method `numpy.__config__.show()` outputs information about linkage gathered at build time. My output looks like this. I think it means I am using the BLAS/LAPACK that ships with Mac OS. ``` >>>import numpy as np >>>np.__config__.show() lapack_opt_info: extra_link_args = ['-Wl,-framework', '-Wl,Accelerate'] ...
Python regular expressions - re.search() vs re.findall()
9,000,960
9
2012-01-25T10:16:56Z
9,001,064
10
2012-01-25T10:24:23Z
[ "python", "regex" ]
For school I'm supposed to write a Python RE script that extracts IP addresses. The regular expression I'm using seems to work with `re.search()` but not with `re.findall()`. ``` exp = "(\d{1,3}\.){3}\d{1,3}" ip = "blah blah 192.168.0.185 blah blah" match = re.search(exp, ip) print match.group() ``` The match for tha...
`findall` returns a list of matches, and from the documentation: > If one or more groups are present in the pattern, return a > list of groups; this will be a list of tuples if the pattern > has more than one group. So, your previous expression had one group that matched 3 times in the string where the last match was...
Python - Install OpenSSL
9,001,316
17
2012-01-25T10:42:01Z
9,001,468
30
2012-01-25T10:51:44Z
[ "python", "ssl", "openssl", "install", "python-2.7" ]
I need to install OpenSSL on my python2.7. I tried ``` $ sudo pip install pyopenssl ``` And I got the following ``` /usr/local/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'zip_safe' warnings.warn(msg) running build running build_py running build_ext building 'OpenSSL.crypto' ext...
SSL development libraries have to be installed CentOS: ``` $ yum install openssl-devel ``` Ubuntu: ``` $ apt-get install libssl-dev ``` OS X (with [Homebrew](http://brew.sh/) installed): ``` $ brew install openssl ```
How can I sort a dictionary by key?
9,001,509
367
2012-01-25T10:54:29Z
9,001,529
424
2012-01-25T10:56:30Z
[ "python", "sorting", "dictionary" ]
What would be a nice way to go from `{2:3, 1:89, 4:5, 3:0}` to `{1:89, 2:3, 3:0, 4:5}`? I checked some posts but they all use the "sorted" operator that returns tuples.
Standard Python dictionaries are unordered. Even if you sorted the (key,value) pairs, you wouldn't be able to store them in a `dict` in a way that would preserve the ordering. The easiest way is to use [`OrderedDict`](http://docs.python.org/library/collections.html#collections.OrderedDict), which remembers the order i...
How can I sort a dictionary by key?
9,001,509
367
2012-01-25T10:54:29Z
9,002,555
14
2012-01-25T12:16:27Z
[ "python", "sorting", "dictionary" ]
What would be a nice way to go from `{2:3, 1:89, 4:5, 3:0}` to `{1:89, 2:3, 3:0, 4:5}`? I checked some posts but they all use the "sorted" operator that returns tuples.
As others have mentioned, dictionaries are inherently unordered. However, if the issue is merely **displaying** dictionaries in an ordered fashion, you can override the `__str__` method in a dictionary subclass, and use this dictionary class rather than the builtin `dict`. Eg. ``` class SortedDisplayDict(dict): def...
How can I sort a dictionary by key?
9,001,509
367
2012-01-25T10:54:29Z
13,990,710
234
2012-12-21T13:01:36Z
[ "python", "sorting", "dictionary" ]
What would be a nice way to go from `{2:3, 1:89, 4:5, 3:0}` to `{1:89, 2:3, 3:0, 4:5}`? I checked some posts but they all use the "sorted" operator that returns tuples.
Dictionaries themselves do not have ordered items as such, should you want to print them etc to some order, here are some examples: **In Python 2.4 and above:** ``` mydict = {'carl':40, 'alan':2, 'bob':1, 'danny':3} for key in sorted(mydict): print "%s: %s" % (key, mydict[key]) ``` ...
How can I sort a dictionary by key?
9,001,509
367
2012-01-25T10:54:29Z
15,179,418
104
2013-03-02T21:04:10Z
[ "python", "sorting", "dictionary" ]
What would be a nice way to go from `{2:3, 1:89, 4:5, 3:0}` to `{1:89, 2:3, 3:0, 4:5}`? I checked some posts but they all use the "sorted" operator that returns tuples.
From [Python's `collections` library documentation](http://docs.python.org/2/library/collections.html?highlight=ordereddict#ordereddict-examples-and-recipes): ``` >>> from collections import OrderedDict >>> # regular unsorted dictionary >>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2} >>> # dictionary sorted...
How can I sort a dictionary by key?
9,001,509
367
2012-01-25T10:54:29Z
20,624,774
10
2013-12-17T02:22:36Z
[ "python", "sorting", "dictionary" ]
What would be a nice way to go from `{2:3, 1:89, 4:5, 3:0}` to `{1:89, 2:3, 3:0, 4:5}`? I checked some posts but they all use the "sorted" operator that returns tuples.
In Python 3. ``` >>> D1 = {2:3, 1:89, 4:5, 3:0} >>> for key in sorted(D1): print (key, D1[key]) ``` gives ``` 1 89 2 3 3 0 4 5 ```
How can I sort a dictionary by key?
9,001,509
367
2012-01-25T10:54:29Z
22,364,504
7
2014-03-12T21:43:42Z
[ "python", "sorting", "dictionary" ]
What would be a nice way to go from `{2:3, 1:89, 4:5, 3:0}` to `{1:89, 2:3, 3:0, 4:5}`? I checked some posts but they all use the "sorted" operator that returns tuples.
Found another way: ``` import json print json.dumps(d, sort_keys = True) ``` **upd:** 1. this also sorts nested objects (thanks @DanielF). 2. python dictionaries are unordered therefore this is sutable for print or assign to str only.
How can I sort a dictionary by key?
9,001,509
367
2012-01-25T10:54:29Z
22,718,254
21
2014-03-28T16:27:02Z
[ "python", "sorting", "dictionary" ]
What would be a nice way to go from `{2:3, 1:89, 4:5, 3:0}` to `{1:89, 2:3, 3:0, 4:5}`? I checked some posts but they all use the "sorted" operator that returns tuples.
There are a number of Python modules that provide dictionary implementations which automatically maintain the keys in sorted order. Consider the [sortedcontainers](http://www.grantjenks.com/docs/sortedcontainers/) module which is pure-Python and fast-as-C implementations. There is also a [performance comparison](http:/...
How can I sort a dictionary by key?
9,001,509
367
2012-01-25T10:54:29Z
24,129,524
9
2014-06-09T21:39:39Z
[ "python", "sorting", "dictionary" ]
What would be a nice way to go from `{2:3, 1:89, 4:5, 3:0}` to `{1:89, 2:3, 3:0, 4:5}`? I checked some posts but they all use the "sorted" operator that returns tuples.
I'm not sure that this complete reliability but is working for my cases ``` x = {2:3, 1:89, 4:5, 3:0} dict(sorted(x.iteritems())) ``` {1: 89, 2: 3, 3: 0, 4: 5} sorted(x.iteritems()) , returns a list sorted : [(1, 89), (2, 3), (3, 0), (4, 5)] Applying dict again seems that works (temporarily), but keep in mind dict...
How can I sort a dictionary by key?
9,001,509
367
2012-01-25T10:54:29Z
33,681,720
9
2015-11-12T21:28:37Z
[ "python", "sorting", "dictionary" ]
What would be a nice way to go from `{2:3, 1:89, 4:5, 3:0}` to `{1:89, 2:3, 3:0, 4:5}`? I checked some posts but they all use the "sorted" operator that returns tuples.
Simply: ``` d = {2:3, 1:89, 4:5, 3:0} sd = sorted(d.items()) for k,v in sd: print k, v ``` Output: ``` 1 89 2 3 3 0 4 5 ```
How to build a single python file from multiple scripts
9,002,275
11
2012-01-25T11:54:20Z
24,152,545
13
2014-06-10T23:40:39Z
[ "python" ]
I have a simple python script, which imports various other modules I've written (and so on). Due to my environment, my PYTHONPATH is quite long. I'm also using Python 2.4. What I need to do is somehow package up my script and all the dependencies that aren't part of the standard python, so that I can email a single fi...
I found this useful: <http://blog.ablepear.com/2012/10/bundling-python-files-into-stand-alone.html> In short, you can .zip your modules and include a `__main__.py` file inside, which will enable you to run it like so: ``` python app.zip ``` Since my app is small I made a link from my main script to `__main__.py`.
Using Django's templating engine without the rest of Django
9,002,826
5
2012-01-25T12:36:03Z
9,002,878
8
2012-01-25T12:39:50Z
[ "python", "django", "templates" ]
I'm building an application, that uses the Django templating engine / language to "compile" some HTML. However, the app doesn't run on Django, and doesn't have all the config and stuff. When I try to use it, I get the following error: ``` Traceback (most recent call last): File "Send.py", line 33, in <module> te...
I'd recommend using [Jinja2](http://jinja.pocoo.org/docs/) instead of Django templates as a standalone solution.
Creating a RDF file using a txt file as input
9,002,873
5
2012-01-25T12:39:43Z
9,003,264
9
2012-01-25T13:09:54Z
[ "python", "parsing", "rdf", "text-files" ]
How can I convert a simple tab-delimited txt file (containing the headers subject, predicate, object) into a RDF N-triple format using the python module RDFlib?
It's not very complicated. First, some necessary imports: ``` from StringIO import StringIO from rdflib import Graph, URIRef ``` I'm using `StringIO` here to avoid creating a file. Instead, I'll just list some contents and a file-like object with these contents: ``` contents = '''\ subject1\tpredicate1\tobject1 subj...
writing command line output to file
9,003,522
4
2012-01-25T13:30:06Z
9,003,615
12
2012-01-25T13:37:22Z
[ "python", "osx", "file", "unix", "ls" ]
I am writing a script to clean up my desktop, moving files based on file type. The first step, it would seem, is to `ls -1 /Users/user/Desktop` (I'm on Mac OSX). So, using Python, how would I run a command, then write the output to a file in a specific directory? Since this will be undocumented, and I'll be the only us...
You can redirect standard output to any file using `>` in command. ``` $ ls /Users/user/Desktop > out.txt ``` Using python, ``` os.system('ls /Users/user/Desktop > out.txt') ``` However, if you are using python then instead of using `ls` command you can use `os.listdir` to list all the files in the directory. ``` ...
1000 digits of pi in python
9,004,789
9
2012-01-25T14:59:47Z
9,005,163
10
2012-01-25T15:22:38Z
[ "python", "pi" ]
I have been thinking about this issue and I can't figure it out. Perhaps you can assist me. The problem is my code isn't working to output 1000 digits of pi in the python coding language. Here's my code: ``` def make_pi(): q, r, t, k, m, x = 1, 0, 1, 1, 3, 3 while True: if 4 * q + r - t < m * t: ...
Run this ``` def make_pi(): q, r, t, k, m, x = 1, 0, 1, 1, 3, 3 for j in range(1000): if 4 * q + r - t < m * t: yield m q, r, t, k, m, x = 10*q, 10*(r-m*t), t, k, (10*(3*q+r))//t - 10*m, x else: q, r, t, k, m, x = q*k, (2*q+r)*x, t*x, k+1, (q*(7*k+2)+r*x)//(t...
1000 digits of pi in python
9,004,789
9
2012-01-25T14:59:47Z
13,316,984
19
2012-11-09T22:30:52Z
[ "python", "pi" ]
I have been thinking about this issue and I can't figure it out. Perhaps you can assist me. The problem is my code isn't working to output 1000 digits of pi in the python coding language. Here's my code: ``` def make_pi(): q, r, t, k, m, x = 1, 0, 1, 1, 3, 3 while True: if 4 * q + r - t < m * t: ...
If you don't want to implement your own algorithm, you can use [SymPy](http://sympy.org/). ``` from sympy.mpmath import mp mp.dps = 1000 # number of digits print(mp.pi) # print pi to a thousand places ``` [*Reference*](https://pythonadventures.wordpress.com/2012/04/13/digits-of-pi-part-2/)
Compute eigenvectors of image in python
9,005,659
4
2012-01-25T15:51:40Z
9,007,249
15
2012-01-25T17:31:55Z
[ "python", "image-processing", "numpy", "eigenvector" ]
I'm trying to fit a 2D Gaussian to an image. Noise is very low, so my attempt was to rotate the image such that the two principal axes do not co-vary, figure out the maximum and just compute the standard deviation in both dimensions. Weapon of choice is python. ![2d more-or-less gaussian distribution](http://i.stack.i...
Just a quick note, there are several tools to fit a gaussian to an image. The only thing I can think of off the top of my head is [scikits.learn](http://scikit-learn.org/stable/), which isn't completely image-oriented, but I know there are others. To calculate the eigenvectors of the covariance matrix exactly as you h...
Jinja template renders double quotes or single quotes as &#39; &#34;
9,005,823
6
2012-01-25T16:01:55Z
9,006,024
10
2012-01-25T16:14:26Z
[ "python", "jinja2" ]
Hi i was trying to populate Google Visualization api in jinja template . I took the sample parameters and passed it to the API but it is converting single and double quotes to ' and & Here is the script : ``` <script type="text/javascript"> //load the Google Visualization API and the chart ...
Use the [safe](http://jinja.pocoo.org/docs/templates/#safe) template filter: ``` dataTable.addRows( {{ answerjson1 | safe }} ); ```
Python: Exception decorator. How to preserve stacktrace
9,005,941
14
2012-01-25T16:09:19Z
9,006,442
31
2012-01-25T16:40:50Z
[ "python", "exception", "wrapper", "decorator" ]
I am writing a decorator to apply to a function. It should catch any exception, and then raise a custom exception based on the original exception message. (This is because suds throws a generic WebFault exception, from whose message I parse the exception thrown by the web service and raise a Python exception to mirror ...
In Python 2.x, a little-known feature of `raise` is that it can be used with more than just one argument: the three-argument form of `raise` takes the exception type, the exception instance and the traceback. You can get at the traceback with `sys.exc_info()`, which returns (not coincidentally) the exception type, the ...
Two variations of Python's main function
9,006,054
5
2012-01-25T16:16:42Z
9,006,102
17
2012-01-25T16:19:34Z
[ "python" ]
When writing scripts for personal use, I am used to doing this: ``` def do_something(): # Do something. if __name__ == '__main__': do_something() ``` Or, we can also do this: ``` def do_something(): # Do something. do_something() # No if __name__ thingy. ``` I know the first form is useful whe...
Even if the script is only meant to be executed, it might sometimes be useful to import it anyway -- in an interactive shell, by documentation generation tools, in unit tests or to perform timings. So routinely using the more general form will never hurt.
How to make virtual organisms learn using neural networks?
9,006,993
34
2012-01-25T17:15:44Z
9,007,435
9
2012-01-25T17:44:19Z
[ "python", "artificial-intelligence", "machine-learning", "neural-network", "simulation" ]
I'm making a simple learning simulation, where there are multiple organisms on screen. They're supposed to learn how to eat, using their simple neural networks. They have 4 neurons, and each neuron activates movement in one direction (it's a 2D plane viewed from the bird's perspective, so there are only four directions...
As mentioned by Mika Fischer, this sounds similar to artificial life problems, so that's one avenue you could look at. It also sounds a bit like you're trying to reinvent [Reinforcement Learning](http://en.wikipedia.org/wiki/Reinforcement_learning). I would recommend reading through [Reinforcement Learning: An Introdu...
How to make virtual organisms learn using neural networks?
9,006,993
34
2012-01-25T17:15:44Z
9,007,587
10
2012-01-25T17:53:04Z
[ "python", "artificial-intelligence", "machine-learning", "neural-network", "simulation" ]
I'm making a simple learning simulation, where there are multiple organisms on screen. They're supposed to learn how to eat, using their simple neural networks. They have 4 neurons, and each neuron activates movement in one direction (it's a 2D plane viewed from the bird's perspective, so there are only four directions...
This is similar to issues with trying to find a **global minimum**, where it's easy to get stuck in a local minimum. Consider trying to find the global minimum for the profile below: you place the ball in different places and follow it as it rolls down the hill to the minimum, but depending on where you place it, you m...
What is the pythonic way to read CSV file data as rows of namedtuples?
9,007,174
25
2012-01-25T17:27:59Z
9,007,207
27
2012-01-25T17:30:05Z
[ "python", "csv", "namedtuple" ]
What is the best way to take a data file that contains a header row and read this row into a named tuple so that the data rows can be accessed by header name? I was attempting something like this: ``` import csv from collections import namedtuple with open('data_file.txt', mode="r") as infile: reader = csv.reade...
Use: ``` Data = namedtuple("Data", next(reader)) ``` and omit the line: ``` next(reader) ``` Combining this with an iterative version based on martineau's comment below, the example becomes: ``` import csv from collections import namedtuple try: from itertools import imap except ImportError: # Python 3 im...
What is the pythonic way to read CSV file data as rows of namedtuples?
9,007,174
25
2012-01-25T17:27:59Z
9,007,761
16
2012-01-25T18:05:18Z
[ "python", "csv", "namedtuple" ]
What is the best way to take a data file that contains a header row and read this row into a named tuple so that the data rows can be accessed by header name? I was attempting something like this: ``` import csv from collections import namedtuple with open('data_file.txt', mode="r") as infile: reader = csv.reade...
Please have a look at [`csv.DictReader`](http://docs.python.org/library/csv.html#csv.DictReader). Basically, it provides the ability to get the column names from the first row as you're looking for and, after that, lets you access to each column in a row by name using a dictionary. If for some reason you still need to...
Parallel fetching of files
9,007,456
5
2012-01-25T17:45:36Z
9,010,299
20
2012-01-25T21:05:57Z
[ "python", "http", "asynchronous", "urllib2", "urllib" ]
In order to download files, I'm creating a urlopen object (urllib2 class) and reading it in chunks. I would like to connect to the server several times and download the file in six different sessions. Doing that, the download speed should get faster. Many download managers have this feature. I thought about specifyin...
As to running parallel requests you might want to use [urllib3](http://urllib3.readthedocs.org) or [requests](http://docs.python-requests.org/). I took some time to make a list of similar questions: Looking for `[python] +download +concurrent` gives these interesting ones: * [Concurrent downloads - Python](http://st...
How to find tag with particular text with Beautiful Soup?
9,007,653
16
2012-01-25T17:57:42Z
9,007,749
16
2012-01-25T18:04:17Z
[ "python", "beautifulsoup" ]
I have the following html (line breaks marked with \n): ``` ... <tr> <td class="pos">\n "Some text:"\n <br>\n <strong>some value</strong>\n </td> </tr> <tr> <td class="pos">\n "Fixed text:"\n <br>\n <strong>text I am looking for</strong>\n </td> </tr> <tr> <td class="pos">...
You can pass a regular expression to the text parameter of `findAll`, like so: ``` import BeautifulSoup import re columns = soup.findAll('td', text = re.compile('your regex here'), attrs = {'class' : 'pos'}) ```
How to find tag with particular text with Beautiful Soup?
9,007,653
16
2012-01-25T17:57:42Z
13,348,425
15
2012-11-12T17:27:19Z
[ "python", "beautifulsoup" ]
I have the following html (line breaks marked with \n): ``` ... <tr> <td class="pos">\n "Some text:"\n <br>\n <strong>some value</strong>\n </td> </tr> <tr> <td class="pos">\n "Fixed text:"\n <br>\n <strong>text I am looking for</strong>\n </td> </tr> <tr> <td class="pos">...
This post got me to my answer even though the answer is missing from this post. I felt I should give back. The challenge here is in the inconsistent behavior of `BeautifulSoup.find` when searching with and without text. **Note:** If you have BeautifulSoup, you can test this locally via: ``` curl https://gist.githubu...
Sort Array rows by another array in python
9,007,877
8
2012-01-25T18:12:26Z
9,008,147
8
2012-01-25T18:28:46Z
[ "python", "numpy", "sorting" ]
I'm trying to sort the rows of one array by the values of another. For example: ``` import numpy as np arr1 = np.random.normal(1, 1, 80) arr2 = np.random.normal(1,1, (80,100)) ``` I want to sort arr1 in descending order, and to have the current relationship between arr1 and arr2 to be maintained (ie, after sorting bo...
Use argsort: ``` arr1inds = arr1.argsort() sorted_arr1 = arr1[arr1inds[::-1]] sorted_arr2 = arr2[arr1inds[::-1]] ``` EDIT: changed to descending order
Getting the request IP address with Pyramid
9,007,887
12
2012-01-25T18:12:57Z
9,007,960
19
2012-01-25T18:17:29Z
[ "python", "pyramid" ]
I'm using Pyramid framework and I want to access the IP address from which the request originated. I assume it's in the request object (passed to every view function) somewhere, but I can't find documentation which tells me where it is.
It's in `request.remote_addr`. You can find it in the [`pyramid.request`](http://readthedocs.org/docs/pyramid/en/1.0-branch/api/request.html#pyramid.request.Request.remote_addr) documentation.
Python : 2d contour plot from 3 lists : x, y and rho?
9,008,370
14
2012-01-25T18:45:00Z
9,008,576
31
2012-01-25T19:01:32Z
[ "python", "matplotlib", "contour" ]
I have a simple problem in python and matplotlib. I have 3 lists : x, y and rho with rho[i] a density at the point x[i], y[i]. All values of x and y are between -1. and 1. but they are not in a specific order. How to make a contour plot (like with imshow) of the density rho (interpolated at the points x, y). Thank yo...
You need to interpolate your `rho` values. There's no one way to do this, and the "best" method depends entirely on the a-priori information you should be incorporating into the interpolation. Before I go into a rant on "black-box" interpolation methods, though, a radial basis function (e.g. a "thin-plate-spline" is a...
How to warn about class (name) deprecation
9,008,444
25
2012-01-25T18:51:11Z
9,008,488
9
2012-01-25T18:54:21Z
[ "python", "class", "backwards-compatibility" ]
I have renamed a python class being a part of a library. I am willing to leave a possibility to use its previous name for some time but would like to warn user that it's deprecated and will be removed somewhere in the future. I think that to provide backward compatibility it will be enough to use an alias like that: ...
Please have a look at [`warnings.warn`](http://docs.python.org/library/warnings.html#warnings.warn). As you'll see, the example in the documentation is a deprecation warning: ``` def deprecation(message): warnings.warn(message, DeprecationWarning, stacklevel=2) ```
How to warn about class (name) deprecation
9,008,444
25
2012-01-25T18:51:11Z
9,008,509
17
2012-01-25T18:55:58Z
[ "python", "class", "backwards-compatibility" ]
I have renamed a python class being a part of a library. I am willing to leave a possibility to use its previous name for some time but would like to warn user that it's deprecated and will be removed somewhere in the future. I think that to provide backward compatibility it will be enough to use an alias like that: ...
> Maybe I could make OldClsName a function which emits a warning (to > logs) and constructs the NewClsName object from its parameters (using > \*args and \*\*kvargs) but it doesn't seem elegant enough (or maybe it is?). Yup, I think that's pretty standard practice: ``` def OldClsName(*args, **kwargs): from warnin...
Python easy way to read all import statements from py module
9,008,451
3
2012-01-25T18:51:56Z
9,049,549
7
2012-01-28T23:30:47Z
[ "python", "python-2.7", "mox" ]
I am trying to create a helper function to read a file and mock out all imports for a unit test. I have to read the file vs import since i dont have those things on python path. Example code: --- ``` #module.py import com.stackoverflow.question from com.stackoverflow.util import test_func from com.stackoverflow.util...
Using the [AST](http://docs.python.org/library/ast.html) module, it is pretty easy: ``` import ast from collections import namedtuple Import = namedtuple("Import", ["module", "name", "alias"]) def get_imports(path): with open(path) as fh: root = ast.parse(fh.read(), path) for node in ast.iter...
Using Enthought Python instead of the system Python
9,008,793
9
2012-01-25T19:16:13Z
11,039,465
12
2012-06-14T18:47:15Z
[ "python", "linux", "installation", "enthought" ]
I've installed the [Enthought Python Distribution](http://enthought.com/products/epd.php), which is basically a glorified Python distribution with added libraries for numerical and scientific computing. Now, since I use Debian, there is Python installed already. If I wish to use the Enthought Python for all work, how w...
I think this is the official way of doing it, as recommended by Enthought: ``` export PATH=/usr/local/EPD/bin:$PATH ``` if you installed to `/usr/local/EPD`. Otherwise, the general form is ``` export PATH=/path/to/EPD/bin:$PATH ``` This prepends the path to the EPD binary directory to your system PATH variable. The...
Optimising multiplication modulo a small prime
9,009,139
15
2012-01-25T19:38:55Z
9,041,507
9
2012-01-27T23:36:34Z
[ "python", "math", "cryptography" ]
I need to do the following operation *many* times: 1. Take two integers `a, b` 2. Compute `a * b mod p`, where `p = 1000000007` and `a, b` are of the same order of magnitude as `p` My gut feeling is the naive ``` result = a * b result %= p ``` is inefficient. Can I optimise multiplication modulo `p` much like expon...
You mention that *"`a, b` are of the same order of magnitude as p."* Often in cryptography this means that `a,b` are large numbers near `p`, but strictly less-than `p`. If this is the case, then you could use the simple identity ![a-p \equiv a \pmod{p}](http://i.stack.imgur.com/kKN7m.png) to turn your calculation in...
How does python's random.Random.seed work?
9,009,572
9
2012-01-25T20:11:23Z
9,009,624
13
2012-01-25T20:14:31Z
[ "python" ]
I'm used to typing `random.randrange`. I'll do a `from random import Random` to spot the error from now on. For a game involving procedural generation (nope, not a Minecraft clone :p) I'd like to keep several distinct pseudo-random number generators: * one for the generation of the world (landscape, quests, etc.), * ...
It works almost exactly as you tried but the rnd.seed() applies to the rnd **object** just use ``` rnd = random.Random(0) # <<-- or set it here rnd.seed(7) print [rnd.randrange(5) for i in range(10)] ``` or by setting the global seed, like this: ``` random.seed(7) print [random.randrange(5) for i in range(10)] ```
How can Python dict have multiple keys with same hash?
9,010,222
38
2012-01-25T20:59:46Z
9,010,277
16
2012-01-25T21:04:13Z
[ "python", "hash", "dictionary", "set", "equality" ]
I am trying to understand python hash function under the hood. I created a custom class where all instances return the same hash value. ``` class C(object): def __hash__(self): return 42 ``` I just assumed that only one instance of the above class can be in a set at any time, but in fact a set can have mu...
**Edit**: the answer below is one of possible ways to deal with hash collisions, it is however **not** how Python does it. Python's wiki referenced below is also incorrect. The best source given by @Duncan below is the implementation itself: <http://svn.python.org/projects/python/trunk/Objects/dictobject.c> I apologize...
How can Python dict have multiple keys with same hash?
9,010,222
38
2012-01-25T20:59:46Z
9,010,557
20
2012-01-25T21:26:53Z
[ "python", "hash", "dictionary", "set", "equality" ]
I am trying to understand python hash function under the hood. I created a custom class where all instances return the same hash value. ``` class C(object): def __hash__(self): return 42 ``` I just assumed that only one instance of the above class can be in a set at any time, but in fact a set can have mu...
For a detailed description of how Python's hashing works see my answer to [Why is early return slower than else?](http://stackoverflow.com/questions/8271139) Basically it uses the hash to pick a slot in the table. If there is a value in the slot and the hash matches, it compares the items to see if they are equal. If...
How can Python dict have multiple keys with same hash?
9,010,222
38
2012-01-25T20:59:46Z
9,022,664
44
2012-01-26T17:40:17Z
[ "python", "hash", "dictionary", "set", "equality" ]
I am trying to understand python hash function under the hood. I created a custom class where all instances return the same hash value. ``` class C(object): def __hash__(self): return 42 ``` I just assumed that only one instance of the above class can be in a set at any time, but in fact a set can have mu...
Here is everything about Python dicts that I was able to put together (probably more than anyone would like to know; but the answer is comprehensive). A shout out to [Duncan](http://stackoverflow.com/users/107660/duncan) for pointing out that Python dicts use slots and leading me down this rabbit hole. * Python dictio...
How do I "pickle" instances of Django models in a database into sample python code I can use to load sample data?
9,011,474
4
2012-01-25T22:40:17Z
9,011,993
9
2012-01-25T23:30:11Z
[ "python", "django", "pickle", "sample-data" ]
How do I "pickle" instances of Django models in a database into sample python code I can use to load sample data? I want to: 1) Take a snapshot of several hundred records that I have stored in a MySQL database for a Django project 2) Take this snapshot and modify the data in it (blanking out names) 3) Transform ...
An easy way to do that would be to convert the model to a dict. Then, you can trivially pickle that and then re-inflate it to create new model instances. To store the model as a dict, you can use a built-in Django function: ``` from django.forms.models import model_to_dict my_dict = model_to_dict(my_instance,fields=[...
python's re: return True if regex contains in the string
9,012,008
25
2012-01-25T23:32:05Z
9,012,040
7
2012-01-25T23:36:18Z
[ "python", "regex" ]
I have a regular expression like this: ``` regexp = u'ba[r|z|d]' ``` Function must return True if word contains **bar**, **baz** or **bad**. In short, I need regexp analog for Python's ``` 'any-string' in 'text' ``` How can I realize it? Thanks!
`Match` objects are always true, and `None` is returned if there is no match. Just test for trueness. Code: ``` >>> st = 'bar' >>> m = re.match(r"ba[r|z|d]",st) >>> if m: ... m.group(0) ... 'bar' ``` Output = `bar` If you want `search` functionality ``` >>> st = "bar" >>> m = re.search(r"ba[r|z|d]",st) >>> if ...
python's re: return True if regex contains in the string
9,012,008
25
2012-01-25T23:32:05Z
9,012,064
49
2012-01-25T23:39:33Z
[ "python", "regex" ]
I have a regular expression like this: ``` regexp = u'ba[r|z|d]' ``` Function must return True if word contains **bar**, **baz** or **bad**. In short, I need regexp analog for Python's ``` 'any-string' in 'text' ``` How can I realize it? Thanks!
``` import re word = 'fubar' regexp = re.compile(r'ba[r|z|d]') if regexp.search(word) is not None: print 'matched' ```
python's re: return True if regex contains in the string
9,012,008
25
2012-01-25T23:32:05Z
15,742,632
19
2013-04-01T11:31:01Z
[ "python", "regex" ]
I have a regular expression like this: ``` regexp = u'ba[r|z|d]' ``` Function must return True if word contains **bar**, **baz** or **bad**. In short, I need regexp analog for Python's ``` 'any-string' in 'text' ``` How can I realize it? Thanks!
The best one by far is ``` bool(re.search('ba[rzd]', 'foobarrrr')) ``` Returns True
Django ModelForm has no model class specified
9,012,033
9
2012-01-25T23:35:32Z
9,012,132
17
2012-01-25T23:45:48Z
[ "python", "django", "modelform" ]
I am trying to use ModelForm: ``` from django.db import models from django.forms import ModelForm class Car(models.Model): carnumber = models.CharField(max_length=5) def __unicode__(self): return self.carnumber class PickForm(ModelForm): class Meta: Model = Car` ``` I have checked this ...
It should be `model` instead of `Model` (and without the trailing `, but I guess that's a typo): ``` class PickForm(ModelForm): class Meta: model = Car ```
Move an entire element in with lxml.etree
9,012,363
6
2012-01-26T00:13:59Z
9,013,273
11
2012-01-26T02:23:41Z
[ "python", "xml", "lxml" ]
Within lxml, is it possible, given an element, to move the entire thing elsewhere in the xml document without having to read all of it's children and recreate it? My best example would be changing parents. I've rummaged around the docs a bit but haven't had much luck. Thanks in advance!
`.append`, `.insert` and other operations do that by default ``` >>> from lxml import etree >>> tree = etree.XML('<a><b><c/></b><d><e><f/></e></d></a>') >>> node_b = tree.xpath('/a/b')[0] >>> node_d = tree.xpath('/a/d')[0] >>> node_d.append(node_b) >>> etree.tostring(tree) # complete 'b'-branch is now under 'd', after...
Matplotlib (pyplot) savefig outputs blank image
9,012,487
21
2012-01-26T00:30:33Z
9,012,749
41
2012-01-26T01:05:28Z
[ "python", "image", "matplotlib", "figure" ]
I am trying to save plots I make using matplotlib; however, the images are saving blank. Here is my code: ``` plt.subplot(121) plt.imshow(dataStack, cmap=mpl.cm.bone) plt.subplot(122) y = copy.deepcopy(tumorStack) y = np.ma.masked_where(y == 0, y) plt.imshow(dataStack, cmap=mpl.cm.bone) plt.imshow(y, cmap=mpl.cm.je...
First, what happens when `T0 is not None`? I would test that, then I would adjust the values I pass to `plt.subplot()`; maybe try values 131, 132, and 133, or values that depend whether or not `T0` exists. Second, after `plt.show()` is called, a new figure is created. To deal with this, you can 1. Call `plt.savefig('...
What's the most concise way in Python to group and sum a list of objects by the same property
9,012,864
10
2012-01-26T01:22:02Z
9,012,923
7
2012-01-26T01:30:38Z
[ "python" ]
I have a list of objects of type C, where type C consists of properties X,Y,Z, e.g., c.X, c.Y, c.Z Now I want to perform the following task: * Sum on the property Z of those objects that has the same value for property Y * Output a list of tuples (Y, sum of Zs with this Y) What's the most concise way?
``` from collections import defaultdict totals = defaultdict(int) for c in cs: totals[c.Y] += c.Z tuples = totals.items() ```
What's the most concise way in Python to group and sum a list of objects by the same property
9,012,864
10
2012-01-26T01:22:02Z
9,012,979
8
2012-01-26T01:40:19Z
[ "python" ]
I have a list of objects of type C, where type C consists of properties X,Y,Z, e.g., c.X, c.Y, c.Z Now I want to perform the following task: * Sum on the property Z of those objects that has the same value for property Y * Output a list of tuples (Y, sum of Zs with this Y) What's the most concise way?
The `defaultdict` approach is probably better, assuming `c.Y` is hashable, but here's another way: ``` from itertools import groupby from operator import attrgetter get_y = attrgetter('Y') tuples = [(y, sum(c.Z for c in cs_with_y) for y, cs_with_y in groupby(sorted(cs, key=get_y), get_y)] ``` To be a litt...
debug a big loop in eclipse
9,013,521
5
2012-01-26T03:09:25Z
9,013,542
8
2012-01-26T03:13:58Z
[ "python", "eclipse", "debugging", "pydev" ]
I am debugging a Python program in Eclipse. I have a breakpoint in a big loop and I expect the problem to occur in the (1000+)th round. How can I reach that ASAP instead of clicking `resume` 1000 times?
You want to set a [conditional breakpoint](http://pydev.org/manual_adv_debugger.html). Read through the link I provided for an explanation and example in python.
pdb.set_trace() causing frozen nosetests, does not drop into debugger
9,013,728
40
2012-01-26T03:52:35Z
9,013,748
25
2012-01-26T03:54:47Z
[ "python", "pdb", "nosetests" ]
I'm running a suite of tests (.py files) using nosetests. Using a classic ``` import pdb; pdb.set_trace() ``` the nosetests run just never completes. It just hangs right where the breakpoint has been set, but never drops into the pdb debugger. Any ideas why this would be? I've tried moving the breakpoint to a number...
Nose is capturing the output and redirecting it. So, the breakpoint is hit, but you just don't see it. You need to turn off the output redirection so that the debug output shows up on the screen. Nose can do this for you, if you use: ``` from nose.tools import set_trace; set_trace() ``` instead of: ``` import pdb;p...
pdb.set_trace() causing frozen nosetests, does not drop into debugger
9,013,728
40
2012-01-26T03:52:35Z
9,013,867
46
2012-01-26T04:13:53Z
[ "python", "pdb", "nosetests" ]
I'm running a suite of tests (.py files) using nosetests. Using a classic ``` import pdb; pdb.set_trace() ``` the nosetests run just never completes. It just hangs right where the breakpoint has been set, but never drops into the pdb debugger. Any ideas why this would be? I've tried moving the breakpoint to a number...
Run nose with the `-s` / `--nocapture` option and you'll be able to see the pdb prompt and interact with the debugger normally. If using the commandline that means:- ``` python manage.py test -s [other-opts-and-args] ```
The model FlatPage is already registered
9,013,767
3
2012-01-26T03:57:08Z
9,013,810
7
2012-01-26T04:04:17Z
[ "python", "django" ]
I'm attempting to work my way through Practical Django Projects. It seems to be a bit old, but I've manage to convert the code up to this point. At this point the book would like me to change my models.py to be this: ``` class SearchKeyword(models.Model) keyword = models.CharField(maxlength=50, core=True) pag...
You have to unregister it first as the app itself ships with an `admin.py` ``` admin.site.unregister(FlatPage) admin.site.register(FlatPage, FlatPageAdmin) ```
Creating a Python list comprehension with an if and break
9,014,058
10
2012-01-26T04:47:23Z
9,014,075
32
2012-01-26T04:50:18Z
[ "python", "if-statement", "for-loop", "list-comprehension" ]
Is it possible to turn this code into a list comprehension? ``` for i in userInput: if i in wordsTask: a = i break ``` I know how to convert part of it: ``` [i for i in userInput if i in wordsTask] ``` But I don't know how to add the break, and the documentation hasn't been much help. Any help ...
``` a = next(i for i in userInput if i in wordsTask) ``` To break it down somewhat: ``` [i for i in userInput if i in wordsTask] ``` Will produce a list. What you want is the first item in the list. One way to do this is with the next function: ``` next([i for i in userInput if i in wordsTask]) ``` Next returns th...
How do I check if an insert was successful with MySQLdb in Python?
9,014,233
5
2012-01-26T05:20:04Z
9,014,540
15
2012-01-26T06:11:44Z
[ "python", "mysql-python" ]
I have this code: ``` cursor = conn.cursor() cursor.execute(("insert into new_files (videos_id, filename, " "is_processing) values (%s,%s,1)"), (id, filename)) logging.warn("%d", cursor.rowcount) if (cursor.rowcount == 1): logging.info("inserted values %d, %s", id, filename) else: logging.warn(...
Your code does not commit after the modifications (your modifications are rolled back). That is you should add the following line after `cursor.execute`: ``` conn.commit() ``` Failed insert will throw `MySQLdb.IntegrityError`, so you should be ready to catch it. Thus, your code should look something like: ``` sql_i...
Trying to write my own Neural Network in Python
9,014,416
10
2012-01-26T05:52:16Z
9,031,510
7
2012-01-27T09:54:34Z
[ "python", "machine-learning", "neural-network" ]
Last semester I took an online machine learning course from Standford taught by Professor Ng. <http://www.ml-class.org/course/auth/welcome> I thought it was pretty informative. To brush up/understand neural networks better I tried to write my own in python. Here it is: ``` import numpy class NN: def __init__(sel...
(Sorry, I don't have enough rep to add comments, so I'll just keep posting answers instead.) Yes, it does seem strange. If, however, after training you generate a new matrix B: ``` B = numpy.random.rand(5, 4)/5 Targets = B*X print n.predict(B) print B*X ``` it will work fine (most of the times - sometimes it will st...
Python SEM_OPEN Error
9,015,010
4
2012-01-26T07:26:53Z
10,830,594
9
2012-05-31T09:12:15Z
[ "python", "django", "celery", "django-celery" ]
I am trying to use Celery running with RabbitMQ and Django. So far i have RabbitMQ 2.7 installed on my server, along with python 2.7 , Django 1.3, celery 2.4.6 and django-celery 2.4.2 i followed the simple instructions here <http://django-celery.readthedocs.org/en/latest/introduction.html> and then i tried to start c...
I ran into the same problem on CentOS 6 running under OpenVZ. I had to mount `/dev/shm` because it was missing. Add the following to `/etc/fstab`: ``` tmpfs /dev/shm tmpfs defaults 0 0 ``` And then run `sudo mount /dev/shm` and see if it works. I had my own custom built Python 2.7.3 and this device *n...
Python not replacing % symbol
9,015,340
3
2012-01-26T08:13:16Z
9,015,355
7
2012-01-26T08:15:09Z
[ "python", "replace", "symbol" ]
Hey guys I'm having a bit of an issue, I have to replace the symbols in a string one of them is the % sign now I'm using this as an example ``` li = "this is () stuff %" li.replace('()%', ' ') ``` but it doesnt replace anything at all if instead I do ``` li = "this is () stuff %" li.replace('%', ' ') ``` then the %...
`replace` matches and replaces the *entire* first argument with the second argument. ``` >>> 'abc'.replace('ab', '!') '!c' >>> 'abc'.replace('abd', '!') 'abc' ```
Python not replacing % symbol
9,015,340
3
2012-01-26T08:13:16Z
9,015,399
7
2012-01-26T08:20:11Z
[ "python", "replace", "symbol" ]
Hey guys I'm having a bit of an issue, I have to replace the symbols in a string one of them is the % sign now I'm using this as an example ``` li = "this is () stuff %" li.replace('()%', ' ') ``` but it doesnt replace anything at all if instead I do ``` li = "this is () stuff %" li.replace('%', ' ') ``` then the %...
BTW, it's easy to solve your problem with `string.translate` ``` import string table = string.maketrans('()%', ' ') li = string.translate(li, table) ```
Weird Python behavior
9,015,421
3
2012-01-26T08:22:15Z
9,015,433
12
2012-01-26T08:23:37Z
[ "python" ]
I wrote a code in python which looks like: ``` maplist=[{}]*11 mylist=[0]*11 maplist[0]['this']=1 print maplist ``` When I print maplist the output is : ``` [{'this': 1}, {'this': 1}, {'this': 1}, {'this': 1}, {'this': 1}, {'this': 1}, {'this': 1}, {'this': 1}, {'this': 1}, {'this': 1}, {'this': 1}] ``` Expected is...
When you do the following: ``` maplist=[{}]*11 ``` you end up with eleven references to the same dictionary. This means that when you modify one dictionary, they all appear to change. To fix, replace that line with: ``` maplist=[{} for in xrange(11)] ``` Note that, since `0` is a scalar, the next line is fine as i...
Apache SetEnv not working as expected with mod_wsgi
9,016,504
19
2012-01-26T10:07:58Z
9,017,610
13
2012-01-26T11:39:38Z
[ "python", "apache", "mod-wsgi", "flask" ]
In a flask application I wrote, I make use of an external library which can be configured using environment variables. Note: I wrote this external library myself. So I *could* make changes if necessary. When running from the command line an running the flask server with: ``` # env = python virtual environment ENV_VAR=...
Note that the WSGI environment is passed upon each request to the application in the `environ` argument of the application object. This environment is totally unrelated to the process environment which is kept in `os.environ`. The `SetEnv` directive has no effect on `os.environ` and there is no way through Apache confi...
CMake build of LLVM clang fails with "Unexpected failure executing llvm-build: Traceback (...) import llvmbuild"
9,017,376
14
2012-01-26T11:18:37Z
9,017,890
19
2012-01-26T12:07:52Z
[ "python", "build", "llvm", "clang" ]
I want to build LLVM clang compiler, but CMake ends up with the following error message: ``` CMake Error at CMakeLists.txt:256 (message): Unexpected failure executing llvm-build: Traceback (most recent call last): File "C:/.../llvm/utils/llvm-build/llvm-build", line 3, in <module> import llvmbuild Fil...
I've found the solution. I've just installed another version of **Python: 2.x** (2.72), (still x86-64)
Is it ok to remove the equal signs from a base64 string?
9,020,409
15
2012-01-26T15:21:40Z
9,020,541
16
2012-01-26T15:31:18Z
[ "python", "base64", "md5" ]
I have a string that I'm encoding into base64 to conserve space. Is it a big deal if I remove the equal sign at the end? Would this significantly decrease entropy? What can I do to ensure the length of the resulting string is fixed? ``` >>> base64.b64encode(combined.digest(), altchars="AB") 'PeFC3irNFx8fuzwjAzAfEAup9c...
Every 3 bytes you need to encode as Base64 are converted to 4 ASCII characters and the '=' character is used to pad the result so that there are always a multiple of 4 encoded characters. If you have an exact multiple of 3 bytes then you will get no equal sign. One spare byte means you get two '=' characters at the end...
Is it ok to remove the equal signs from a base64 string?
9,020,409
15
2012-01-26T15:21:40Z
9,020,716
11
2012-01-26T15:41:47Z
[ "python", "base64", "md5" ]
I have a string that I'm encoding into base64 to conserve space. Is it a big deal if I remove the equal sign at the end? Would this significantly decrease entropy? What can I do to ensure the length of the resulting string is fixed? ``` >>> base64.b64encode(combined.digest(), altchars="AB") 'PeFC3irNFx8fuzwjAzAfEAup9c...
Looking at your code: ``` >>> base64.b64encode(combined.digest(), altchars="AB") 'PeFC3irNFx8fuzwjAzAfEAup9cz6xujsf2gAIH2GdUM=' ``` The string that's being encoded in base64 is the result of a function called `digest()`. If your digest function is producing fixed length values (e.g. if it's calculating MD5 or SHA1 di...
PySNMP Errors when working with MIB files
9,020,732
2
2012-01-26T15:42:37Z
9,044,365
7
2012-01-28T09:53:57Z
[ "python", "mib", "pysnmp" ]
I'm attempting to use MIB files in PySNMP. The code is fairly straightforward. Nothing complex. Just trying to get the information under an OID. The code I'm using is as follows: ``` #!/usr/local/bin/python2.7 from pysnmp.smi import builder, view, error from pysnmp.entity.rfc3413.oneliner import cmdgen cmdGen = cmdg...
The `getMibPath()`/`setMibPath()` methods are obsolete. They don't work unless you .egg pysnmp or its MIB modules. You should always use the `getMibSources()`/`setMibSources()` methods instead. These work for both .egg and file-based setup. ``` mibPath = mibBuilder.getMibSources() + (builder.DirMibSource('/path/to/co...
How to convert a MAC number to MAC string?
9,020,843
2
2012-01-26T15:49:34Z
9,020,930
7
2012-01-26T15:54:53Z
[ "python" ]
I want to convert a MAC address 00163e2fbab7 (stored as a string) to its string representation 00:16:3e:2f:ba:b7. What is the easiest way to do this?
Using the [grouper idiom](http://docs.python.org/library/itertools.html#itertools.izip) `zip(*[iter(s)]*n)`: ``` In [32]: addr = '00163e2fbab7' In [33]: ':'.join(''.join(pair) for pair in zip(*[iter(addr)]*2)) Out[33]: '00:16:3e:2f:ba:b7' ``` Also possible, (and, in fact, a bit quicker): ``` In [36]: ':'.join(addr[...
How to convert a MAC number to MAC string?
9,020,843
2
2012-01-26T15:49:34Z
9,021,003
17
2012-01-26T15:59:45Z
[ "python" ]
I want to convert a MAC address 00163e2fbab7 (stored as a string) to its string representation 00:16:3e:2f:ba:b7. What is the easiest way to do this?
Use a completely circuitous method to take advantage of an existing function that groups two hex characters at a time: ``` >>> ':'.join(s.encode('hex') for s in '00163e2fbab7'.decode('hex')) '00:16:3e:2f:ba:b7' ```
TypeError: unhashable type: 'numpy.ndarray'
9,022,656
10
2012-01-26T17:39:55Z
9,022,915
7
2012-01-26T17:59:35Z
[ "python", "numpy" ]
From a text file containing three columns of data I want to be able to just take a `slice` of data from all three columns where the values in the first column are equal to the values defined in `above`. I then want to put the slice of data into a new array called `slice` (I am using **Python 2.7**) ``` above = range(1...
Your variable `energies` probably has the wrong shape: ``` >>> from numpy import array >>> set([1,2,3]) & set(range(2, 10)) set([2, 3]) >>> set(array([1,2,3])) & set(range(2,10)) set([2, 3]) >>> set(array([[1,2,3],])) & set(range(2,10)) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError...
custom dict that allows delete during iteration
9,023,078
21
2012-01-26T18:12:10Z
9,024,499
13
2012-01-26T20:02:59Z
[ "python", "design", "dictionary", "iterator", "python-3.x" ]
UPDATED based on Lennart Regebro's answer Suppose you iterate through a dictionary, and sometimes need to delete an element. The following is very efficient: ``` remove = [] for k, v in dict_.items(): if condition(k, v): remove.append(k) continue # do other things you need to do in this loop for k in remo...
As you note, you can store the items to delete somewhere and defer the deletion of them until later. The problem then becomes *when* to purge them and *how* to make sure that the purge method eventually gets called. The answer to this is a context manager which is also a subclass of `dict`. ``` class dd_dict(dict): ...
Build error with variables and url_for in Flask
9,023,488
11
2012-01-26T18:41:11Z
15,838,522
20
2013-04-05T16:04:55Z
[ "python", "flask", "werkzeug", "build-error", "url-for" ]
Have found one or two people on the interwebs with similar problems, but haven't seen a solution posted anywhere. I'm getting a build error from the code/template below, but can't figure out where the issue is or why it's occurring. It appears that the template isn't recognizing the function, but don't know why this wo...
url\_for looks for a function, you pass it the name of the function you are wanting to call. So you should use : ``` {{ url_for('viewproj', proj=xxx) }} ``` I got the same problem. And I solved it accoring:[Flask error: werkzeug.routing.BuildError](http://stackoverflow.com/questions/3683108/flask-error-werkzeug-rou...
Build error with variables and url_for in Flask
9,023,488
11
2012-01-26T18:41:11Z
25,496,041
16
2014-08-25T23:57:57Z
[ "python", "flask", "werkzeug", "build-error", "url-for" ]
Have found one or two people on the interwebs with similar problems, but haven't seen a solution posted anywhere. I'm getting a build error from the code/template below, but can't figure out where the issue is or why it's occurring. It appears that the template isn't recognizing the function, but don't know why this wo...
Just solved the same problem, the solution is really funny. Just add a '.' in front of your method name in url\_for. Like this: ``` <a href="{{ url_for('.viewproj', proj=project.project_name) }}"> ``` And it should work now. The document for this solution from Flask is <http://flask.pocoo.org/docs/0.10/api/>, and ...
How to generate a repeatable random number sequence?
9,023,660
9
2012-01-26T18:56:12Z
9,023,677
7
2012-01-26T18:58:10Z
[ "python", "random", "cpython" ]
I would like a function that can generate a pseudo-random sequence of values, but for that sequence to be repeatable every run. The data I want has to be reasonably well randomly distributed over a given range, it doesn't have to be perfect. I want to write some code which will have performance tests run on it, based ...
Specify a seed to the random number generator. If you provide the same seed, your random numbers should also be the same. <http://docs.python.org/library/random.html#random.seed>
How to generate a repeatable random number sequence?
9,023,660
9
2012-01-26T18:56:12Z
18,992,474
15
2013-09-24T21:35:18Z
[ "python", "random", "cpython" ]
I would like a function that can generate a pseudo-random sequence of values, but for that sequence to be repeatable every run. The data I want has to be reasonably well randomly distributed over a given range, it doesn't have to be perfect. I want to write some code which will have performance tests run on it, based ...
For this purpose, I've used a repeating MD5 hash, since the intention of a hashing function is a cross-platform one-to-one transformation, so it will always be the same on different platforms. ``` import md5 def repeatable_random(seed): hash = seed while True: hash = md5.md5(hash).digest() for...
Printing at different levels in Python
9,024,767
4
2012-01-26T20:21:39Z
9,024,786
10
2012-01-26T20:23:22Z
[ "python", "logging" ]
I am from a Java background. In Java you can print at different levels in most frameworks. For example in log4J, you have log levels which can be set to Debug, Info, warn etc. Does python have anything similar out of the box? i.e. without having to import another lbrary. Thanks.
Yep! Have a look at the [logging](http://docs.python.org/library/logging.html) module. [Here](http://docs.python.org/howto/logging.html#logging-basic-tutorial)'s a tutorial.
Data Hiding in Python Class
9,025,027
5
2012-01-26T20:41:38Z
9,025,258
12
2012-01-26T20:59:39Z
[ "python" ]
I know that the attributes of class which are declared by double underscore `__` prefix may or may not visible outside the class definition. As we can still access those attributes by `object._className__attrName`. ``` class A: def __init__(self): self.a = 1 self.b = 2 ---- ---- ...
Yes, it is possible to hide private data in a closure -- at least, if there is a way to access `private` from outside `make_A`, I haven't found it: ``` def make_A(): private = { 'a' : 1, 'b' : 2, 'z' : 26, } class A: def __init__(self): self.catch = 100 ...
Python Argparse: Issue with optional arguments which are negative numbers
9,025,204
16
2012-01-26T20:55:56Z
9,031,331
10
2012-01-27T09:37:00Z
[ "python", "argparse", "negative-number" ]
I'm having a small issue with argparse. I have an option xlim which is the xrange of a plot. I want to be able to pass numbers like -2e-5. However this does not work - argparse interprets this is a positional argument. If I do -0.00002 it works - argparse reads it as a negative number. Is it possible to have able to re...
As already pointed out by the comments, the problem is that a `-` prefix is parsed as an option instead of as an argument. One way to workaround this is change the prefix used for options with [`prefix_chars`](http://docs.python.org/dev/library/argparse.html#prefix-chars) argument: ``` #!/usr/bin/python import argpars...
Python Argparse: Issue with optional arguments which are negative numbers
9,025,204
16
2012-01-26T20:55:56Z
17,236,161
11
2013-06-21T13:13:45Z
[ "python", "argparse", "negative-number" ]
I'm having a small issue with argparse. I have an option xlim which is the xrange of a plot. I want to be able to pass numbers like -2e-5. However this does not work - argparse interprets this is a positional argument. If I do -0.00002 it works - argparse reads it as a negative number. Is it possible to have able to re...
One workaround I've found is to quote the value, but adding a space. That is, ``` ./blaa.py --xlim " -2.e-3" 1e4 ``` This way argparse won't think -2.e-3 is an option name because the first character is not a hyphen-dash, but it will still be converted properly to a float because float(string) ignores spaces on the l...