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 oop polymorphism
6,355,337
3
2011-06-15T09:01:29Z
6,355,411
7
2011-06-15T09:07:00Z
[ "python", "oop", "polymorphism" ]
I can't understand why this code: ``` class A(object): def __init__(self): self.__value = 1 def get_value(self): return self.__value class B(A): def __init__(self): A.__init__( self ) self.__value = 2 b = B() print b.get_value() ``` gives 1, but not 2. Thanks for your he...
Your problem is that double underscores are [special](http://docs.python.org/tutorial/classes.html#tut-private) in python, and create some modicum of privacy (not enforced, but it mangles the names, which is what is affecting you here). You should recreate this without the variable being named with double underscores. ...
Python: Intertwining two lists
6,356,041
11
2011-06-15T10:05:03Z
6,356,099
14
2011-06-15T10:09:39Z
[ "python", "list-comprehension" ]
What is the pythonic way of doing the following: I have two lists `a` and `b` of the same length `n`, and I want to form the list ``` c = [a[0], b[0], a[1], b[1], ..., a[n-1], b[n-1]] ```
``` c = [item for pair in zip(a, b) for item in pair] ``` Read documentation about [zip](http://docs.python.org/library/functions.html#zip). --- For comparison with Ignacio's answer see this question: [How do I convert a tuple of tuples to a one-dimensional list using list comprehension?](http://stackoverflow.com/qu...
Python: Intertwining two lists
6,356,041
11
2011-06-15T10:05:03Z
6,356,128
11
2011-06-15T10:11:33Z
[ "python", "list-comprehension" ]
What is the pythonic way of doing the following: I have two lists `a` and `b` of the same length `n`, and I want to form the list ``` c = [a[0], b[0], a[1], b[1], ..., a[n-1], b[n-1]] ```
``` c = list(itertools.chain.from_iterable(itertools.izip(a, b))) ```
Music Analysis and Visualization
6,356,749
9
2011-06-15T11:05:33Z
6,361,439
9
2011-06-15T17:01:48Z
[ "python", "audio", "visualization", "music" ]
I'm interested in programming a music visualizer in Python. The first problem is how to get the information from the music? Like volume, frequency, rpm, etc. And from where? From the soundcard or the actual music file? My guess is from the soundcard, but how do I access the soundcard and the wanted information? Prefe...
If you are looking for a cross-platform audio library I strongly suggest to use [FMOD](http://www.fmod.org) which just rocks. There is also a [wrapper](http://sourceforge.net/projects/pyfmodex/) to use it in python available (though I've never used it). It will provide features like getting the spectrum out-of-the-bo...
Decorate methods per instance in Python
6,356,858
5
2011-06-15T11:16:33Z
6,356,992
10
2011-06-15T11:26:58Z
[ "python", "decorator" ]
Assume I have some simple class ``` class TestClass: def doSomething(self): print 'Did something' ``` I would like to decorate the `doSomething` method, for example to count the number of calls ``` class SimpleDecorator(object): def __init__(self,func): self.func=func self.count=0 ...
Utilize the fact that `self` (i.e. the object which the method is invoked on) is passed as a parameter to the method: ``` import functools def counted(method): @functools.wraps(method) def wrapped(obj, *args, **kwargs): if hasattr(obj, 'count'): obj.count += 1 else: ob...
Sqlite version for Python 3.x
6,357,074
3
2011-06-15T11:34:27Z
6,357,334
8
2011-06-15T11:59:50Z
[ "python", "sqlite" ]
I want to use sqlite3 with Python 3.1.3 and I need to set enable\_load\_extension to true. To do this I believe I need sqlite version 3.x. From reading posts here it looks like a suitable version of sqlite ought to be bundled with python version 2.6 and up. However, when I do: ``` import sqlite3 sqlite3.version_info `...
Don't confuse the version of SQLite with the version of pysqlite, the Python binding for the SQLite API. The `version` and `version_info` attributes you used refer to the latter. Ever wondered why the module is named `sqlite3`? It only supports version 3.x! To check the SQLite version, use `sqlite_version` instead: ...
Twisted or Celery? Which is right for my application with lots of SOAP calls?
6,357,737
27
2011-06-15T12:34:42Z
6,359,524
14
2011-06-15T14:40:45Z
[ "python", "soap", "concurrency", "twisted", "celery" ]
I'm writing a Python application that needs both concurrency and asynchronicity. I've had a few recommendations each for Twisted and Celery, but I'm having trouble determining which is the better choice for this application (I have no experience with either). The application (which is not a web app) primarily centers ...
> Is either Celery or Twisted a more generally appropriate framework here? Depends on what you mean by "generally appropriate". > If they'll both solve the problem adequately, are there pros/cons to using one vs the other? Not an exhaustive list. Celery Pros: * Ready-made distributed task queue, with rate-limiting...
How do I run some python code in another process?
6,357,850
6
2011-06-15T12:46:10Z
6,357,878
11
2011-06-15T12:48:50Z
[ "python", "multiprocessing" ]
I want to start, from Python, some other Python code, preferably a function, but in **another process**. It is mandatory to run this in another process, because I want to run some concurrency tests, like opening a file that was opened exclusively by the parent process (this has to fail). Requirements: * multiplatfor...
I would seriously take a look at the documentation for [multiprocessing](http://docs.python.org/library/multiprocessing.html) library of Python. From the first sentence of the package's description: > multiprocessing is a package that supports spawning processes using an API similar to the threading module. It then g...
How do I install a DMG file from the command line?
6,357,914
7
2011-06-15T12:51:37Z
6,358,679
12
2011-06-15T13:45:40Z
[ "python", "osx", "bash" ]
I am looking for small bash or python script that will install a `.dmg` file. We'll assume that the dmg contains one or more `.app` directories that have to be copied to `/Applications`, overriding any already existing directories. Files or directories not matching the `*.app` pattern are to be ignored.
You can mount the disk image using ``` hdiutil attach -mountpoint <path-to-desired-mountpoint> <filename.dmg> ``` The disk image will be mounted at the selected path (the argument following `-mountpoint`). Then, search for an `.app` file and copy the file to `/Applications`. Once you have finished installation unmou...
Naming dict keys for fast lookup in python
6,358,335
7
2011-06-15T13:22:30Z
6,358,602
7
2011-06-15T13:40:40Z
[ "python", "django", "performance", "dictionary" ]
I'm going to have 1 small dictionary (between 5 and 20 keys) that will be referenced up to a hundred times or so for one page load in python 2.5. I'm starting to name the keys which it will be looking up and I was wondering if there is a key naming convention I could follow to help dict lookup times.
I had to test ;-) using * f1, integer key `1` * f2 short string, `"one"` * f3 long string `"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"` as one of the keys into a dictionary of length 4. Iterating 10,000,000 times and measuring the times. I get this result: ``` <function f1 at 0xb779187c> f1 3.64 <function f2 at 0x...
Is there an Ant task which can fetch an artifact from Hudson/Jenkins?
6,358,692
5
2011-06-15T13:46:11Z
6,358,733
7
2011-06-15T13:48:25Z
[ "java", "python", "ant", "hudson", "jenkins" ]
I've hand-rolled my project's build-system (mostly in Python + Hudson). One of the things I need to do quite often is fetch artifacts from upstream Hudson / Jenkins. These artifacts could be almost anything - for example a zip-file full of business data to process or even an egg containing a load of python code which ...
The proper solution is to publish the artifacts from Hudson/Jenkins to an artifact manager, such as [Nexus](http://nexus.sonatype.org/) or [Artifactory](http://www.jfrog.com/products.php), and then pull the artifact versions with something like [Ivy](http://ant.apache.org/ivy/) or [Gradle](http://www.gradle.org/).
Gracefully Terminating Python Threads
6,359,597
11
2011-06-15T14:45:26Z
6,359,663
7
2011-06-15T14:49:41Z
[ "python", "multithreading" ]
I am trying to write a unix client program that is listening to a socket, stdin, and reading from file descriptors. I assign each of these tasks to an individual thread and have them successfully communicating with the "main" application using synchronized queues and a semaphore. The problem is that when I want to shut...
There is no good way to work around this, especially when the thread is blocking. I had a similar issue ( [Python: How to terminate a blocking thread](http://stackoverflow.com/questions/5019436/python-how-to-terminate-a-blocking-thread)) and the only way I was able to stop my threads was to close the underlying connec...
Django template question: how to output just the text if the variable has html in it?
6,359,773
4
2011-06-15T14:56:44Z
6,359,799
7
2011-06-15T14:58:47Z
[ "python", "django" ]
I have a lot of variables that has html in them. For example the value of a variable called {{object.name}} is the following: ``` Play this <a href="#">hot</a> game and see how <b>fun</b> it is! ``` Is there a filter that can be applied on the variable that will give me just the text: ``` Play this hot game and see ...
[striptags](https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#striptags) filter removes all html {{object.name|striptags}}
How do you select choices in a form using Python?
6,359,817
10
2011-06-15T15:00:06Z
6,360,556
20
2011-06-15T15:49:41Z
[ "python", "mechanize" ]
I'd like to know how to select options in a form that is formatted like ``` <td align="left"> <select name="FORM1" id="FORM1" multiple="multiple" size="5"> <option value="Value1">Value1</option> <option value="Value2">Value2</option> </s...
Here are some basic usage examples to get you going: ``` >>> import mechanize >>> br = mechanize.Browser() >>> br.open('http://www.w3schools.com/html/html_forms.asp') ``` Forms have a `name` attribute; sometimes it's empty though: ``` >>> [f.name for f in br.forms()] ['searchform', None, None, None, None, 'input0'] ...
Save image created via PIL to django model
6,359,880
8
2011-06-15T15:04:08Z
6,396,532
10
2011-06-18T13:58:02Z
[ "python", "django", "django-models", "python-imaging-library" ]
I have successfully created and rotated an image that was uploaded via email to a directory on my server using the following code: ``` image = ContentFile(b64decode(part.get_payload())) im = Image.open(image) tempfile = im.rotate(90) tempfile.save("/srv/www/mysite.com/public_html/media/images/r...
I solved the issue with the following code: ``` image = ContentFile(b64decode(part.get_payload())) im = Image.open(image) tempfile = im.rotate(270) tempfile_io =StringIO.StringIO() tempfile.save(tempfile_io, format='JPEG') image_file = InMemoryUploadedFile(tempfile_io, None, '...
Python Multiprocessing - Just not getting it
6,360,679
5
2011-06-15T15:57:30Z
6,360,957
10
2011-06-15T16:22:06Z
[ "python", "python-3.x", "multiprocessing", "pool", "python-2.7" ]
I've been spending some time trying to understand multiprocessing, though its finer points evade my untrained mind. I've been able to get a pool to [return a simple integer](http://pastebin.com/MzagGPrb), but if the function doesn't just return a result like all of the examples I can find (even in the [documentation](h...
It took me a while to understand what you want to happen. The problem has to do with the way multiprocessing works. Basically, you need to write your program in a functional style, instead of relying on side-effects as you do now. Right now, you're sending out objects to your pool to be modified and returning nothing ...
What's the get_Text() equivalent in python bindings for Selenium/Webdriver
6,360,939
4
2011-06-15T16:20:49Z
6,361,031
8
2011-06-15T16:27:40Z
[ "python", "selenium-webdriver" ]
I would like to move from Selenium 1 to Selenium 2. I use python binding however I can not find any get\_text() functions. eg. `selenium.find_elements_by_css_selector("locator").get_text()` Is there such function in python bindings for Selenium/Webdriver ?
use the '.text' property. ``` element.text ```
Why do assertions in unittest use TestCase.assertEqual not the assert keyword?
6,361,147
24
2011-06-15T16:37:22Z
6,361,186
16
2011-06-15T16:40:26Z
[ "python", "unit-testing" ]
Python's built-in unittest module makes assertions with `TestCase.assert*` methods: ``` class FooTest(TestCase): def test_foo(self): self.assertEqual(1,1) self.assertNotEqual(1,2) self.assertTrue(True) ``` I have generally used a testrunner such as [nose](http://somethingaboutorange.com/mr...
The problem with the `assert` keyword is that it is optimized out, and thus *ignored*, when Python is run in 'optimized' mode (with the `-O` argument or with the `PYTHONOPTIMIZE` environment variable set.) If tests were to use `assert` then testing with `-O` would be impossible. Additionally, the use of the assert met...
How to check if a name/value pair exists when posting data?
6,362,047
16
2011-06-15T17:53:52Z
6,362,080
12
2011-06-15T17:56:12Z
[ "python", "django" ]
I'm not able to find the proper syntax for doing what I want to do. I want to do something if a name/value pair is not present. Here is the code in my view: ``` if (!request.POST['number']): # do something ``` What is the proper way to accomplish something like the above? I am getting a syntax error when I try th...
Most logically: ``` if not 'number' in request.POST: ``` Python convention: ``` if 'number' not in request.POST: ``` Both work in exactly the same way.
How to check if a name/value pair exists when posting data?
6,362,047
16
2011-06-15T17:53:52Z
6,362,353
23
2011-06-15T18:15:42Z
[ "python", "django" ]
I'm not able to find the proper syntax for doing what I want to do. I want to do something if a name/value pair is not present. Here is the code in my view: ``` if (!request.POST['number']): # do something ``` What is the proper way to accomplish something like the above? I am getting a syntax error when I try th...
@Thomas gave you the generic way, but there is a shortcut for the particular case of getting a default value when a key does not exist. ``` number = request.POST.get('number', 0) ``` This is equivalent to: ``` if 'number' not in request.POST: number = 0 else: number = request.POST['number'] ```
realtime statistical analysis
6,362,335
10
2011-06-15T18:14:17Z
6,566,911
7
2011-07-04T02:56:38Z
[ "python", "numpy" ]
I need to do some real-time data analysis to monitor for operational errors. More specifically, I'm controlling a winch on a buoy which is lowering an instrument package down through the water. I need to detect if it has hit the bottom, and stop it if it has. I've got the following data: depth of sensor, rate at which ...
Your approach (comparing current derivative to mean derivative) is good, but could be improved. Most importantly, you really need to see your data before deciding how to analyze it: ![plot of data, derivatives, and power spectra](http://i.stack.imgur.com/MODU3.png) These plots show: A) Your original data. Note: the r...
Install Python extension to specific location
6,362,466
6
2011-06-15T18:24:42Z
6,444,370
7
2011-06-22T18:00:33Z
[ "python", "distutils" ]
My project mix pure Python code, and Cython extensions for optimization and for linking with C libraries. I have one source tree for my Python project, and one for Cython and C code. My Cython extensions each have a setup.py file to build them. Actually, for each extension, I do the following: ``` python setup.py buil...
I finally found the answer! The option is -b (or --build\_lib) ``` python setup.py build_ext -b ../some/specific/place/ ```
What is the difference between numpy.fft and scipy.fftpack?
6,363,154
34
2011-06-15T19:28:04Z
6,363,572
26
2011-06-15T19:59:09Z
[ "python", "numpy", "scipy", "fft" ]
Is the later just a synonym of the former, or are they two different implementations of FFT? Which one is better?
SciPy does more: * <http://docs.scipy.org/doc/numpy/reference/routines.fft.html> * <http://docs.scipy.org/doc/scipy/reference/fftpack.html#> In addition, SciPy exports some of the NumPy features through its own interface, for example if you execute *scipy.fftpack.helper.fftfreq* and *numpy.fft.helper.fftfreq* you're ...
What is the difference between numpy.fft and scipy.fftpack?
6,363,154
34
2011-06-15T19:28:04Z
8,481,916
15
2011-12-12T22:37:44Z
[ "python", "numpy", "scipy", "fft" ]
Is the later just a synonym of the former, or are they two different implementations of FFT? Which one is better?
I found that numpy's 2D fft was significantly faster than scipy's, but FFTW was faster than both (using the PyFFTW bindings). Performance tests are here: code.google.com/p/agpy/source/browse/trunk/tests/test\_ffts.py And the results (for `n` x `n` arrays): ``` n sp np ...
Understanding resource and context in Pyramid
6,363,273
8
2011-06-15T19:39:05Z
6,368,133
13
2011-06-16T06:54:06Z
[ "python", "resources", "url-routing", "pyramid" ]
Please bear with me, since I am just getting started with Pyramid. I am having trouble understanding context and resource in Pyramid, with regards to **URL Dispatch**. I'm not quite sure what it means from the description in the documentation, context and resource is somewhat circular (to me). * What is a resource in ...
First of all, the main reason that you would want to even care about this stuff when using URL Dispatch is for the purposes of using pyramid's auth system. If you don't care about that, then you can completely ignore contexts and resource trees and go on with dispatch. ## Resource Trees Pyramid has a unique concept o...
How to tell if one regular expression matches a subset of another regular expression?
6,363,397
11
2011-06-15T19:47:41Z
6,364,335
9
2011-06-15T21:03:08Z
[ "python", "regex" ]
I'm just wondering if it's possible to use one regular expression to match another, that is some sort of: ``` ['a-z'].match(['b-x']) True ['m-n'].match(['0-9']) False ``` Is this sort of thing possible with regex at all? I'm doing work in python, so any advice specific to the `re` module's implementation would help,...
I think — in theory — to tell whether regexp `A` matches a subset of what regexp `B` matches, an algorithm could: 1. Compute the minimal Deterministic Finite Automaton of `B` and also of the "union" `A|B`. 2. Check if the two DFAs are identical. This is true if and only if A matches a subset of what B matches. Howeve...
Why can't I get my static dir to work with django 1.3?
6,363,728
6
2011-06-15T20:11:43Z
6,364,477
7
2011-06-15T21:14:30Z
[ "python", "django", "website", "static", "url-pattern" ]
This problem is very simple, but I just can't figure it out added to my urlpatterns ``` url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/home/user/www/site/static'}) ``` where my main.css is : /home/user/www/site/static/css/main.css when I access <http://localhost:8000/static/> I get:...
If you are using the built-in development webserver (i.e. run it with `manage.py runserver`), Django will take care of static files while in development. Please note that `STATIC_ROOT` is the path where Django collects static files in, rather than the path that it serves files from. You should not maintain `STATIC_ROO...
Default sub-command, or handling no sub-command with argparse
6,365,601
11
2011-06-15T23:24:34Z
26,379,693
9
2014-10-15T10:00:51Z
[ "python", "parsing", "command-line-arguments", "argparse", "subcommand" ]
How can I have a default [sub-command](http://docs.python.org/py3k/library/argparse.html#sub-commands), or handle the case where no sub-command is given using [`argparse`](http://docs.python.org/py3k/library/argparse.html)? ``` import argparse a = argparse.ArgumentParser() b = a.add_subparsers() b.add_parser('hi') a....
On Python 3.2 (and 2.7) you will get that error, but not on 3.3 and 3.4 (no response). Therefore on 3.3/3.4 you could test for `parsed_args` to be an empty `Namespace`. A more general solution is to add a method `set_default_subparser()` (taken from the [ruamel.std.argparse](https://bitbucket.org/ruamel/std.argparse) ...
Improving FFT performance in Python
6,365,623
17
2011-06-15T23:28:57Z
6,366,027
13
2011-06-16T00:53:34Z
[ "python", "numpy", "scipy", "fft", "fftw" ]
What is the fastest FFT implementation in Python? It seems numpy.fft and scipy.fftpack both are based on fftpack, and not FFTW. Is fftpack as fast as FFTW? What about using multithreaded FFT, or using distributed (MPI) FFT?
You could certainly wrap whatever FFT implementation that you wanted to test using Cython or other like-minded tools that allow you to access external libraries. If you're going to test FFT implementations, you might also take a look at GPU-based codes (if you have access to the proper hardware). There are several: <h...
Add to locals() in Python 3.2+?
6,365,845
2
2011-06-16T00:13:52Z
6,365,889
7
2011-06-16T00:22:21Z
[ "python", "variables", "python-3.x" ]
I'm trying to programmatically define several variables in the local namespace: ``` for build_step in 'prepare', 'configure', 'make', 'stage', 'package', 'all': p = build_subparsers.add_parser(build_step) p.set_defaults(build_step=build_step) if build_step != 'package': p.add_argument('specfile') ...
The answer is: don't do that. If you want to programmatically store values, use a container: ``` >>> d = dict() >>> d['a'] = 5 ``` Or create a container class, if you really must. ``` >>> class Container(object): ... pass ... >>> c = Container() >>> setattr(c, 'a', 5) >>> c.a 5 ```
How to change the url using django process_request .
6,366,589
4
2011-06-16T02:47:55Z
16,990,633
8
2013-06-07T18:25:37Z
[ "python", "django", "url", "middleware" ]
This is my code : ``` class MobileMiddleware(object): def process_request(self, request): if request.path.startswith('/core/mypage/'): request.path='/core/mypage/?key=value' print request.path,'aaaa' ``` I want to add a param `key` when the page url is `/core/mypage/`, and the ur...
For googlers - I tested with request.path\_info. If you want to change URL in middlware, change request.path\_info in [process\_request](https://docs.djangoproject.com/en/dev/topics/http/middleware/#process_request). ``` request.path_info = <change request.path_info> ``` Please Note that I do not suggest or forbid to...
SSH to machine through a middle host
6,366,652
7
2011-06-16T02:57:57Z
6,366,741
7
2011-06-16T03:17:30Z
[ "python", "ssh" ]
In my work with my professor I have to ssh into our server and from there I ssh into each node to run our programs. I am trying to write a python program that will let me do everything that I need to do on the remote node from my local machine. The commands that I will be running on the nodes are: * cp files from loca...
You don't need Python to do this. Check the [ProxyCommand configuration option for SSH](http://www.openbsd.org/cgi-bin/man.cgi?query=ssh_config). Here is a [tutorial](http://backdrift.org/transparent-proxy-with-ssh) that explains the details.
How to send email via Django?
6,367,014
81
2011-06-16T04:11:12Z
6,367,023
33
2011-06-16T04:12:58Z
[ "python", "django", "email", "website", "smtp" ]
In my `settings.py`, I have the following: ``` EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # Host for sending e-mail. EMAIL_HOST = 'localhost' # Port for sending e-mail. EMAIL_PORT = 1025 # Optional SMTP authentication information for EMAIL_HOST. EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL...
Send the email to a real SMTP server. If you don't want to set up your own then you can find companies that will run one for you, such as Google themselves.
How to send email via Django?
6,367,014
81
2011-06-16T04:11:12Z
6,367,458
123
2011-06-16T05:24:07Z
[ "python", "django", "email", "website", "smtp" ]
In my `settings.py`, I have the following: ``` EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # Host for sending e-mail. EMAIL_HOST = 'localhost' # Port for sending e-mail. EMAIL_PORT = 1025 # Optional SMTP authentication information for EMAIL_HOST. EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL...
I use Gmail as my SMTP server for Django. Much easier than dealing with postfix or whatever other server. I'm not in the business of managing email servers. In settings.py: ``` EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'me@gmail.com' EMAIL_HOST_PASSWORD = 'password' ``` **...
How to send email via Django?
6,367,014
81
2011-06-16T04:11:12Z
27,878,592
10
2015-01-10T16:47:21Z
[ "python", "django", "email", "website", "smtp" ]
In my `settings.py`, I have the following: ``` EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # Host for sending e-mail. EMAIL_HOST = 'localhost' # Port for sending e-mail. EMAIL_PORT = 1025 # Optional SMTP authentication information for EMAIL_HOST. EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL...
My site is hosted on Godaddy and I have private email registered on the same. These are the settings which worked for me: In settings.py: ``` EMAIL_HOST = 'mail.domain.com' EMAIL_HOST_USER = 'abc@domain.com' EMAIL_HOST_PASSWORD = 'abcdef' DEFAULT_FROM_EMAIL = 'abc@domain.com' SERVER_EMAIL = 'abc@domain.com' EMAIL_POR...
How to send email via Django?
6,367,014
81
2011-06-16T04:11:12Z
29,213,958
10
2015-03-23T15:20:52Z
[ "python", "django", "email", "website", "smtp" ]
In my `settings.py`, I have the following: ``` EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # Host for sending e-mail. EMAIL_HOST = 'localhost' # Port for sending e-mail. EMAIL_PORT = 1025 # Optional SMTP authentication information for EMAIL_HOST. EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL...
For Django version 1.7, if above solutions dont work then try the following in **settings.py** add ``` #For email EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'sender@gmail.com' #Must generate specific password for your app in [...
Is there an easy way to tell which line number a file pointer is on?
6,367,051
2
2011-06-16T04:19:35Z
6,367,075
7
2011-06-16T04:24:05Z
[ "python", "text-files", "line-numbers" ]
In Python 2.5, I am reading a structured text data file (~30 MB in size) using a file pointer: ``` fp = open('myfile.txt', 'r') line = fp.readline() # ... many other fp.readline() processing steps, which # are used in different contexts to read the structures ``` But then, while parsing the file, I hit something inte...
A typical solution to this problem is to define a new class that wraps an existing instance of a `file`, which automatically counts the numbers. Something like this (just off the top of my head, I haven't tested this): ``` class FileLineWrapper(object): def __init__(self, f): self.f = f self.line =...
python: creating instance from variable name
6,367,164
2
2011-06-16T04:37:48Z
6,367,198
11
2011-06-16T04:44:35Z
[ "python", "class", "instance" ]
\*\*\*EDIT2: Sorry about the broken code. Here is working code which illustrates the same issue: ``` class bead(): def printmsg(a): print('test message') chain1=bead() x='chain1' eval(x + '.printmsg()') ``` \*\*\*EDIT: Thank you gnibbler for answering the original question. Here's a better worded version...
Instead of the `eval()`, you could say ``` getattr(locals()[x], y) ``` or ``` getattr(locals().get(x), y) ``` Is that what you mean?
Saving numpy array in mongodb
6,367,589
14
2011-06-16T05:43:10Z
6,376,382
17
2011-06-16T17:55:51Z
[ "python", "mongodb", "numpy", "nosql", "datastore" ]
I have a couple of MongoDB documents wherein one my the fields is best represented as a matrix (numpy array). I would like to save this document to MongoDB, how do I do this? ``` { 'name' : 'subject1', 'image_name' : 'blah/foo.png', 'feature1' : np.array(...) } ```
For a 1D numpy array, you can use lists: ``` # serialize 1D array x record['feature1'] = x.tolist() # deserialize 1D array x x = np.fromiter( record['feature1'] ) ``` For multidimensional data, I believe you'll need to use pickle and pymongo.binary.Binary: ``` # serialize 2D array y record['feature2'] = pymongo.bin...
Objects vs instance in python
6,368,432
5
2011-06-16T07:23:40Z
6,380,430
13
2011-06-17T01:18:23Z
[ "c++", "python", "object" ]
In C++ there are just objects and classes, where objects are instances of classes. In Python, a class definition (i.e., the body of a class) is called an object. And, the object in C++ is called instance in python. Check [this](http://docs.python.org/tutorial/classes.html#class-definition-syntax) Am I wrong? **EDIT...
> In Python, a class definition (i.e., the body of a class) is called an object Actually, this is still called a class in Python. That's why you define it like this: ``` class Foo(object): pass ``` The `class` keyword is used because the result is still called a class. The word `object` is in parentheses to sho...
Python list intersection efficiency: generator or filter()?
6,369,527
4
2011-06-16T09:13:56Z
6,369,558
13
2011-06-16T09:16:52Z
[ "python", "list", "intersection", "python-2.7", "intersect" ]
I would like to intersect two lists in Python (2.7). I need the result to be iterable: ``` list1 = [1,2,3,4] list2 = [3,4,5,6] result = (3,4) # any kind of iterable ``` Providing a *full iteration* will be performed first thing after the intersection, which of the following is more efficient? Using a generator: ```...
Neither of these. The best way is to use sets. ``` list1 = [1,2,3,4] list2 = [3,4,5,6] result = set(list1).intersection(list2) ``` Sets are iterable, so no need to convert the result into anything.
Turn the dictionary keys into variable names with same values in Python from .mat Matlab files using scipy.io.loadmat
6,369,535
4
2011-06-16T09:14:59Z
6,370,282
8
2011-06-16T10:16:03Z
[ "python", "matlab", "numpy", "scipy", "mat-file" ]
I am trying to take a basic dictionary temp = {'key':array([1,2])} loaded from a .mat file with scipy.io.loadmat. Turn the keys in the Python dictionary file returned by loadmat() into variable names with values the same as the representing keys. So for example: ``` temp = {'key':array([1,2])} ``` turned into ``` k...
In python, method parameters can be passed as dictionnaries with the `**` magic: ``` def my_func(key=None): print key #do the real stuff temp = {'key':array([1,2])} my_func(**temp) >>> array([1,2]) ```
How do I print out the contents of my settings in a django shell?
6,369,697
15
2011-06-16T09:28:49Z
6,369,749
17
2011-06-16T09:33:12Z
[ "python", "django" ]
When I run `python manage.py shell`, I can print out the python path ``` >>> import sys >>> sys.path ``` What should I type to introspect all my django settings ?
``` from django.conf import settings dir(settings) ``` and then choose attribute from what `dir(settings)` have shown you to say: ``` settings.name ``` where `name` is the attribute that is of your interest Alternatively: ``` settings.__dict__ ``` prints all the settings. But it prints also the module standard at...
How do I print out the contents of my settings in a django shell?
6,369,697
15
2011-06-16T09:28:49Z
11,585,348
13
2012-07-20T18:54:23Z
[ "python", "django" ]
When I run `python manage.py shell`, I can print out the python path ``` >>> import sys >>> sys.path ``` What should I type to introspect all my django settings ?
To show all django settings (including default settings not specified in your local settings file): ``` from django.conf import settings dir(settings) ```
How do I print out the contents of my settings in a django shell?
6,369,697
15
2011-06-16T09:28:49Z
21,198,170
10
2014-01-17T23:57:21Z
[ "python", "django" ]
When I run `python manage.py shell`, I can print out the python path ``` >>> import sys >>> sys.path ``` What should I type to introspect all my django settings ?
In case a newbie stumbles upon this question wanting to be spoon fed the way to print out the values for all settings: ``` def show_settings(): from django.conf import settings for name in dir(settings): print name, getattr(settings, name) ```
How do I print out the contents of my settings in a django shell?
6,369,697
15
2011-06-16T09:28:49Z
26,718,776
14
2014-11-03T16:41:47Z
[ "python", "django" ]
When I run `python manage.py shell`, I can print out the python path ``` >>> import sys >>> sys.path ``` What should I type to introspect all my django settings ?
I know that this is an old question, but with current versions of django (1.6+), you can accomplish this from the command line the following way: ``` python manage.py diffsettings --all ``` The result will show all of the settings including the defautls (denoted by ### in front of the settings name).
What is the most pythonic way to import modules in python
6,372,159
11
2011-06-16T12:52:56Z
6,372,175
13
2011-06-16T12:54:35Z
[ "python", "python-import" ]
Can anyone suggest me what is the most pythonic way to import modules in python? Let me explain - i have read a lot of python code and found several different ways of how to import modules or if to be more precise - when to import: 1. Use one module/several modules which include all the imports(third party modules) wh...
It *really* doesn't matter, so long as you don't `from ... import *`. The rest is all taste and getting around cyclic import issues. [PEP 8](http://www.python.org/dev/peps/pep-0008/) states that you should import at the top of the script, but even that isn't set in stone.
Sort Tuples Python
6,372,198
13
2011-06-16T12:55:45Z
6,372,223
29
2011-06-16T12:57:21Z
[ "python", "sorting", "tuples" ]
I have a list of tuples in my Blender python code ``` scores=[(1489,"Sean"), (2850,"Bob"), (276,"Crap Player"), (78495, "Great Player"), (8473, "Damian"), (4860, "Andy"), (0, "Stephen")] ``` I'm trying to sort them by their score by using this ``` sorted(scores, key=lambda score: score[0], reverse=True) ``` but thi...
Just do: ``` print sorted(scores, reverse=True) [(78495, 'Great Player'), (8473, 'Damian'), (4860, 'Andy'), (2850, 'Bob'), (1489, 'Sean'), (276, 'Crap Player'), (0, 'Stephen')] ``` you can use `scores.sort(reverse=True)` if you want to sort in place, and by the way the sort function in case of list of tuple by defaul...
Sort Tuples Python
6,372,198
13
2011-06-16T12:55:45Z
6,372,241
10
2011-06-16T12:58:25Z
[ "python", "sorting", "tuples" ]
I have a list of tuples in my Blender python code ``` scores=[(1489,"Sean"), (2850,"Bob"), (276,"Crap Player"), (78495, "Great Player"), (8473, "Damian"), (4860, "Andy"), (0, "Stephen")] ``` I'm trying to sort them by their score by using this ``` sorted(scores, key=lambda score: score[0], reverse=True) ``` but thi...
`sorted()` returns the sorted sequence. If you want to sort a list in place then use `list.sort()`.
how to parse a list or string into chunks of fixed length
6,372,228
5
2011-06-16T12:57:35Z
6,372,316
8
2011-06-16T13:02:53Z
[ "python" ]
I'm really stuck on a basic question. I am trying to take a list of one item and divide it into a list of many items each with a charater length of 10. For example give a list with one item, `['111111111122222222223333333333']`, the output would produce: ``` 1111111111 2222222222 3333333333 ``` I feel like this is su...
A related question has been asked: [Slicing a list into a list of sub-lists...](http://stackoverflow.com/questions/2231663/slicing-a-list-into-a-list-of-sub-lists) For example, if your source list is: ``` the_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, ... ] ``` you can split it like: ``` split_list = [the_list[i:i+n] for i...
How to Download a file to a specific path in the server : Python
6,373,094
3
2011-06-16T13:57:16Z
6,373,260
7
2011-06-16T14:08:44Z
[ "python", "jython" ]
How to download a file through http on to a local folder on my server in jython(or python) The below code might work ``` os.chdir("/path/to/change/to") from urllib2 import urlopen f = urlopen("http://some.server/some/directory/some.file") ``` But for this my Current working directory is changed.I want to be in the c...
How about [urllib.urlretrieve](http://docs.python.org/library/urllib.html#urllib.urlretrieve) ``` import urllib urllib.urlretrieve('http://python.org/images/python-logo.gif', '/tmp/foo.gif') ```
Getting the Server URL in Google App Engine using python
6,373,479
13
2011-06-16T14:23:29Z
6,373,608
15
2011-06-16T14:31:04Z
[ "python", "google-app-engine", "url", "web-applications" ]
How do I get App Engine to generate the URL of the server it is currently running on? If the application is running on development server it should return ``` http://localhost:8080/ ``` and if the application is running on Google's servers it should return ``` http://application-name.appspot.com ```
You can get the URL that was used to make the current request from within your webapp handler via `self.request.url` or you could piece it together using the `self.request.environ` dict (which you can read about on the [WebOb docs](http://pythonpaste.org/webob/reference.html#id1) - request inherits from webob) You can...
Getting the Server URL in Google App Engine using python
6,373,479
13
2011-06-16T14:23:29Z
19,369,907
10
2013-10-14T21:53:22Z
[ "python", "google-app-engine", "url", "web-applications" ]
How do I get App Engine to generate the URL of the server it is currently running on? If the application is running on development server it should return ``` http://localhost:8080/ ``` and if the application is running on Google's servers it should return ``` http://application-name.appspot.com ```
Here is an alternative answer. ``` from google.appengine.api import app_identity server_url = app_identity.get_default_version_hostname() ``` On the dev appserver this would show: > localhost:8080 and on appengine > your\_app\_id.appspot.com
Printing { and } with new format syntax
6,374,492
12
2011-06-16T15:35:07Z
6,374,542
20
2011-06-16T15:37:30Z
[ "python" ]
I need to add '{' and/or '}' in a string where I use the format function to format the string. For example: I want my string to be "{3}", but this: ``` "\{{}\}".format(3) ``` gives me the error: ``` ValueError: Single '}' encountered in format string ``` Does anyone know how use '{' and '}' in string formatting? T...
Simply duplicate the braces: ``` >>> "{{{0}}}".format(3) '{3}' ```
Python: Non-blocking socket or Asynchronos I/O
6,374,685
7
2011-06-16T15:46:14Z
6,377,550
7
2011-06-16T19:37:14Z
[ "python", "sockets", "nonblocking" ]
I am new to Python and currently have to write a python socket to be run as a script that communicates with a device over TCP/IP (a weather station). The device acts as the Server Side (listening over IP:PORT, accepting connection, receiving request, transferring data). I only need to send one message, receive the ...
You can try a timeout approach, like Russel code or you can use a non-blocking socket, as shown in the code below. It will never block at `socket.recv` and you can use it inside a loop to retry as many times you want. This way your program will not hang at timeout. This way, you can test if data is available and if not...
Unknown screen output of manually installed Python 2.7
6,375,120
8
2011-06-16T16:14:41Z
6,375,165
10
2011-06-16T16:18:11Z
[ "python" ]
I installed Python 2.7 today using: ``` ./configure --prefix=/home/zhanwu/local --enable-shared --enable-profiling --with-pydebug make install ``` Then I keep getting something like "[37745 refs]" on screen after each function call: ``` [zhanwu@cluster ~]$ ~/local/bin/python Python 2.7.1 (r271:86832, Jun 16 2011, 17...
You get these because you configured the build with `--with-pydebug`. They denote the number of references Python is currently keeping track of. To get rid of them, configure without `--with-pydebug`.
Reading unicode elements into numpy array
6,375,343
8
2011-06-16T16:30:44Z
6,375,576
7
2011-06-16T16:47:32Z
[ "python", "unicode", "numpy" ]
Consider a text file called "new.txt" containing the following elements: ``` μm ∂r ∆λ ``` In Python 2.7, I can read the file by typing: ``` >>> import codecs >>> f = codecs.open('new.txt', encoding='utf-8') >>> lines = [line.strip() for line in f2.readlines()] >>> lines [u'\u03bcm', u'\u2202r', u'\u2206\u03bb'...
In memory, unicode strings are represented as [UCS-2](http://en.wikipedia.org/wiki/UCS-2) or [UCS-4](http://en.wikipedia.org/wiki/UCS-4), depending on how your Python interpreter was compiled. Your file is encoded in [UTF-8](http://en.wikipedia.org/wiki/UTF-8), so you need to recode it before you can map it to the NumP...
What is the best way to deal with import cycle in Python?
6,375,574
3
2011-06-16T16:47:31Z
6,375,593
7
2011-06-16T16:48:46Z
[ "python", "python-import" ]
In our projects we have level 'controls' with the following modules: 'grid', 'gridcell', 'combo' and etc. Grid module imports gridcell module since grid consists of cells, while any cell can contain combo inside it. So initially we starting to use 'from ... import ...' statements inside these classes the following way:...
``` import controls.gridcell as gridcell ``` etc. etc. etc. etc.
How do you base-64 encode a PNG image for use in a data-uri in a CSS file?
6,375,942
18
2011-06-16T17:18:05Z
6,375,973
30
2011-06-16T17:20:40Z
[ "python", "css", "image", "base64", "data-uri" ]
I want to base-64 encode a PNG file, to include it in a data:url in my stylesheet. How can I do that? I’m on a Mac, so something on the Unix command line would work great. A Python-based solution would also be grand.
This should do it in Python: ``` import base64 encoded = base64.b64encode(open("filename.png", "rb").read()) ```
How to display "This many months ago" in Django using Humanize?
6,376,671
5
2011-06-16T18:20:12Z
6,376,735
15
2011-06-16T18:25:11Z
[ "python", "django" ]
I have this variable: ``` {{ video.pub_date }} ``` which outputs: ``` May 16, 2011, 2:03 p.m. ``` How can I get it to show: ``` 1 month ago ``` I have loaded humanize on the page, but the django docs for humanize doesn't really show how to implement it to show what I want: <https://docs.djangoproject.com/en/dev/...
You have to have the development version of Django to use the [**naturaltime** filter](https://docs.djangoproject.com/en/dev/ref/contrib/humanize/#naturaltime) ``` {% load humanize %} {{ video.pub_date|naturaltime }} ``` Humanize isn't a template tag, it's a library of [template filters](https://docs.djangoproject.co...
What is the best way to create a string array in python?
6,376,886
10
2011-06-16T18:38:53Z
6,377,006
8
2011-06-16T18:50:19Z
[ "python", "arrays", "string" ]
I'm relatively new to Python and it's libraries and I was wondering how I might create a string array with a preset size. It's easy in java but I was wondering how I might do this in python. So far all I can think of is ``` strs = ['']*size ``` And some how when I try to call string methods on it, the debugger gives...
In Python, the tendency is usually that one would use a non-fixed size list (that is to say items can be appended/removed to it dynamically). If you followed this, there would be no need to allocate a fixed-size collection ahead of time and fill it in with empty values. Rather, as you get or create strings, you simply ...
What is the best way to create a string array in python?
6,376,886
10
2011-06-16T18:38:53Z
6,377,007
24
2011-06-16T18:50:20Z
[ "python", "arrays", "string" ]
I'm relatively new to Python and it's libraries and I was wondering how I might create a string array with a preset size. It's easy in java but I was wondering how I might do this in python. So far all I can think of is ``` strs = ['']*size ``` And some how when I try to call string methods on it, the debugger gives...
In python, you wouldn't normally do what you are trying to do. But, the below code will do it: ``` strs = ["" for x in range(size)] ```
converting from local to utc timezone
6,377,179
4
2011-06-16T19:05:25Z
6,377,429
8
2011-06-16T19:27:24Z
[ "python", "timezone", "pytz" ]
I'm attempting to craft a function that takes a time object and converts it to UTC time. The code below appears to be off by one hour. When i run noon through the converter, i get back 18:00:00. But when i run the same data through online converters, i get 17:00:00. What am i doing wrong here? Any help would be greatl...
Change ``` src_dt = dt.replace(tzinfo=src_tz) ``` to ``` src_dt = src_tz.localize(dt) ``` Using `localize` adjusts for Daylight Savings Time, while `replace` does not. See the section entitled "Localized times and date arithmetic" [in the docs](http://pypi.python.org/pypi/pytz/).
How to override the default value of a Model Field from an Abstract Base Class
6,377,631
24
2011-06-16T19:43:40Z
6,379,556
27
2011-06-16T22:58:26Z
[ "python", "django", "django-models" ]
I've got some code that looks like this: ``` class BaseMessage(models.Model): is_public = models.BooleanField(default=False) # some more fields... class Meta: abstract = True class Message(BaseMessage): # some fields... ``` and I'd like to override the default value of the `is_public` field ...
You can actually do this as follows: ``` class BaseMessage(models.Model): is_public = models.BooleanField(default=False) # some more fields... class Meta: abstract = True class Message(BaseMessage): # some fields... Message._meta.get_field('is_public').default = True ``` I have done this onc...
executable made with py2exe doesn't run on windows xp 32bit
6,378,673
6
2011-06-16T21:12:15Z
6,378,741
7
2011-06-16T21:18:46Z
[ "python", "windows", "architecture", "py2exe" ]
I created an executable with py2exe on a 64bit windows 7 machine, and distributed the program. On a windows xp 32bit machine the program refuses to run exhibiting the following behavior: > a popup window says: program.exe is > not a valid win32 application. > > The command prompt window says "access > denied" I chec...
I think you just need to install 32-bit python and 32-bit py2exe on your machine.... see [Can 64-bit python create 32-bit Windows executables](http://stackoverflow.com/questions/4935502/can-64-bit-python-create-32-bit-windows-executables)
Python: Binding Socket: "Address already in use"
6,380,057
38
2011-06-17T00:12:11Z
6,380,198
62
2011-06-17T00:35:46Z
[ "python", "sockets", "tcp", "port" ]
I have a question regarding client socket on TCP/IP network. Let's say I use ``` try: comSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) comSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except socket.error, msg: sys.stderr.write("[ERROR] %s\n" % msg[1]) sys.exit(1) try: ...
Try using the `SO_REUSEADDR` socket option before binding the socket. ``` comSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ``` **Edit:** I see you're still having trouble with this. There is a case where `SO_REUSEADDR` won't work. If you try to bind a socket and reconnect to the same destination (with ...
Python: Binding Socket: "Address already in use"
6,380,057
38
2011-06-17T00:12:11Z
18,858,817
16
2013-09-17T19:57:25Z
[ "python", "sockets", "tcp", "port" ]
I have a question regarding client socket on TCP/IP network. Let's say I use ``` try: comSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) comSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except socket.error, msg: sys.stderr.write("[ERROR] %s\n" % msg[1]) sys.exit(1) try: ...
Here is the complete code that I've tested and absolutely does NOT give me a "address already in use" error. You can save this in a file and run the file from within the base directory of the HTML files you want to serve. Additionally, you could programmatically change directories prior to starting the server ``` impo...
Python: Binding Socket: "Address already in use"
6,380,057
38
2011-06-17T00:12:11Z
19,247,688
8
2013-10-08T12:27:55Z
[ "python", "sockets", "tcp", "port" ]
I have a question regarding client socket on TCP/IP network. Let's say I use ``` try: comSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) comSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except socket.error, msg: sys.stderr.write("[ERROR] %s\n" % msg[1]) sys.exit(1) try: ...
Actually, SO\_REUSEADDR flag can lead to much greater consequences: SO\_REUSADDR permits you to use a port that is stuck in TIME\_WAIT, but you still can not use that port to establish a connection to the last place it connected to. What? Suppose I pick local port 1010, and connect to foobar.com port 300, and then clos...
Why does Python not perform type conversion when concatenating strings?
6,380,500
16
2011-06-17T01:32:14Z
6,380,524
7
2011-06-17T01:35:19Z
[ "python", "string", "type-conversion" ]
In Python, the following code produces an error: ``` a = 'abc' b = 1 print(a + b) ``` (The error is "TypeError: cannot concatenate 'str' and 'int' objects"). Why does the Python interpreter not automatically try using the str() function when it encounters concatenation of these types?
There's a very large degree of ambiguity with such operations. Suppose that case instead: ``` a = '4' b = 1 print(a + b) ``` It's not clear if `a` should be coerced to an integer (resulting in `5`), or if `b` should be coerced to a string (resulting in `'41'`). Since type juggling rules are transitive, passing a nume...
Why does Python not perform type conversion when concatenating strings?
6,380,500
16
2011-06-17T01:32:14Z
6,380,529
19
2011-06-17T01:35:44Z
[ "python", "string", "type-conversion" ]
In Python, the following code produces an error: ``` a = 'abc' b = 1 print(a + b) ``` (The error is "TypeError: cannot concatenate 'str' and 'int' objects"). Why does the Python interpreter not automatically try using the str() function when it encounters concatenation of these types?
The problem is that the conversion is ambiguous, because `+` means both *string concatenation* and *numeric addition*. The following question would be equally valid: > Why does the Python interpreter not automatically try using the **int()** function when it encounters **addition** of these types? This is exactly the...
Simple python inheritance
6,381,590
5
2011-06-17T05:10:47Z
6,381,701
8
2011-06-17T05:30:16Z
[ "python", "inheritance", "constructor" ]
``` class Animal(object): def __init__(self, nlegs=4): print '__init__ Animal' self.nlegs = nlegs class Cat(Animal): def __init__(self, talk='meow'): print '__init__ Cat' self.talk = talk class Dog(Animal): def __init__(self, talk='woof'): print '__init__ Dog' ...
To build on what everyone else has said, yes, you'll need to call the parent's `__init__` method. It's generally best to use super. However, in certain cases (particularly when you're inheriting from multiple classes) it can be a big gotcha. I'll avoid going into detail, there are no shortage of [various articles whic...
Add two matrices in python
6,382,705
8
2011-06-17T07:33:38Z
6,382,720
16
2011-06-17T07:34:48Z
[ "python", "nested-lists" ]
I'm trying to write a function that adds two matrices to pass the following doctests: ``` >>> a = [[1, 2], [3, 4]] >>> b = [[2, 2], [2, 2]] >>> add_matrices(a, b) [[3, 4], [5, 6]] >>> c = [[8, 2], [3, 4], [5, 7]] >>> d = [[3, 2], [9, 2], [10, 12]] >>> add_matrices(c, d) [[11, 4], [12, 6], [15, 19]] ```...
## Matrix library You can use the `numpy` module, which has support for this. ``` >>> import numpy as np >>> a = np.matrix([[1, 2], [3, 4]]) >>> b = np.matrix([[2, 2], [2, 2]]) >>> a+b matrix([[3, 4], [5, 6]]) ``` --- ## Home-grown solution: heavyweight Assuming you wanted to implement it yourself, you'd...
How to use getopt/OPTARG in Python? How to shift arguments if too many arguments (9) are given?
6,382,804
13
2011-06-17T07:44:04Z
6,382,852
26
2011-06-17T07:49:01Z
[ "python", "arguments", "getopt" ]
How to use getopt/optarg in Python?
This is an example of how I do it, I usually use the same basic template: ``` import sys import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'm:p:h', ['miner=', 'params=', 'help']) except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ('-h', '--help'): usage()...
Python mysqldb: Library not loaded: libmysqlclient.18.dylib
6,383,310
157
2011-06-17T08:37:41Z
6,967,816
295
2011-08-06T15:28:29Z
[ "python", "mysql-python" ]
I just compiled and installed mysqldb for python 2.7 on my mac os 10.6. I created a simple test file that imports ``` import MySQLdb as mysql ``` Firstly, this command is red underlined and the info tells me "Unresolved import". Then I tried to run the following simple python code ``` import MySQLdb as mysql def ma...
I solved the problem by creating a symbolic link to the library. I.e. The actual library resides in ``` /usr/local/mysql/lib ``` And then I created a symbolic link in ``` /usr/lib ``` Using the command: ``` sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib ``` so that I hav...
Python mysqldb: Library not loaded: libmysqlclient.18.dylib
6,383,310
157
2011-06-17T08:37:41Z
7,005,506
52
2011-08-10T03:18:56Z
[ "python", "mysql-python" ]
I just compiled and installed mysqldb for python 2.7 on my mac os 10.6. I created a simple test file that imports ``` import MySQLdb as mysql ``` Firstly, this command is red underlined and the info tells me "Unresolved import". Then I tried to run the following simple python code ``` import MySQLdb as mysql def ma...
I found there was another solution for this problem rather than creating a symbolic link. You set the path to your directory, where libmysqlclient.18.dylib resides, to DYLD\_LIBRARY\_PATH environment variable. What I did is to put following line in my .bash\_profile: ``` export DYLD_LIBRARY_PATH=/usr/local/mysql-5.5....
Python mysqldb: Library not loaded: libmysqlclient.18.dylib
6,383,310
157
2011-06-17T08:37:41Z
11,265,299
19
2012-06-29T16:09:54Z
[ "python", "mysql-python" ]
I just compiled and installed mysqldb for python 2.7 on my mac os 10.6. I created a simple test file that imports ``` import MySQLdb as mysql ``` Firstly, this command is red underlined and the info tells me "Unresolved import". Then I tried to run the following simple python code ``` import MySQLdb as mysql def ma...
I found putting this in your .profile or .bashrc (whichever you use) is the easiest way to do it, sym links are messy compared to keeping paths in your source files. Also compared to yoshisurfs answer, most of the time when mysql gets installed the mysql directory should be renamed to just mysql, not the whole file na...
Python mysqldb: Library not loaded: libmysqlclient.18.dylib
6,383,310
157
2011-06-17T08:37:41Z
13,421,926
112
2012-11-16T17:56:50Z
[ "python", "mysql-python" ]
I just compiled and installed mysqldb for python 2.7 on my mac os 10.6. I created a simple test file that imports ``` import MySQLdb as mysql ``` Firstly, this command is red underlined and the info tells me "Unresolved import". Then I tried to run the following simple python code ``` import MySQLdb as mysql def ma...
My preferred method is to actually fix the library rather than playing with environment variables that may or may not actually be in scope depending on how the application is run. This is actually a fairly simple process. First, look at the error output to see where the offending python module is located: > ImportErr...
Python mysqldb: Library not loaded: libmysqlclient.18.dylib
6,383,310
157
2011-06-17T08:37:41Z
19,623,171
35
2013-10-27T20:30:50Z
[ "python", "mysql-python" ]
I just compiled and installed mysqldb for python 2.7 on my mac os 10.6. I created a simple test file that imports ``` import MySQLdb as mysql ``` Firstly, this command is red underlined and the info tells me "Unresolved import". Then I tried to run the following simple python code ``` import MySQLdb as mysql def ma...
In my case, I was getting the error with Mac OS X 10.9 Mavericks. I installed MySQL Community Server directly from the Oracle/MySQL Website from DMG. All I needed to do was symlink the lib files to the /usr/local/lib directory. ``` mkdir -p /usr/local/lib ln -s /usr/local/mysql/lib/libmysql* /usr/local/lib ``` Bo...
Add 2 hours and 1 day onto a timestamp in django
6,383,900
5
2011-06-17T09:35:35Z
6,383,935
13
2011-06-17T09:40:03Z
[ "python", "django", "time", "timestamp" ]
i have a model which holds data for a game, how would i add 2 hours and 1 day onto the 'starts' field? ``` class Game(models.Model): starts = models.DateTimeField(auto_now_add=True) ends = models.DateTimeField() ``` does anyone have a solution for this?
``` from datetime import timedelta obj.starts += timedelta(days=1, hours=2) ```
Is there a way to instantiate a class without calling __init__?
6,383,914
33
2011-06-17T09:37:22Z
6,384,228
10
2011-06-17T10:05:33Z
[ "python", "class", "constructor", "instantiation" ]
Is there a way to circumvent the constructor `__init__` of a class in python? Example: ``` class A(object): def __init__(self): print "FAILURE" def Print(self): print "YEHAA" ``` Now I would like to create an instance of `A`. It could look like this, however this syntax is not correct. ...
Use `classmethod` decorator for your `Load` method: ``` class B(object): def __init__(self, name, data): self._Name = name #store data @classmethod def Load(cls, file, newName): f = open(file, "rb") s = pickle.load(f) f.close() return cls(newName, s) ``...
Is there a way to instantiate a class without calling __init__?
6,383,914
33
2011-06-17T09:37:22Z
6,384,982
35
2011-06-17T11:19:14Z
[ "python", "class", "constructor", "instantiation" ]
Is there a way to circumvent the constructor `__init__` of a class in python? Example: ``` class A(object): def __init__(self): print "FAILURE" def Print(self): print "YEHAA" ``` Now I would like to create an instance of `A`. It could look like this, however this syntax is not correct. ...
You *can* circumvent `__init__` by calling `__new__` directly. Then you can create a object of the given type and call an alternative method for `__init__`. This is something that `pickle` would do. However, first I'd like to stress very much that it is something that you ***shouldn't*** do and whatever you're trying ...
Is there a way to instantiate a class without calling __init__?
6,383,914
33
2011-06-17T09:37:22Z
18,653,042
8
2013-09-06T08:16:17Z
[ "python", "class", "constructor", "instantiation" ]
Is there a way to circumvent the constructor `__init__` of a class in python? Example: ``` class A(object): def __init__(self): print "FAILURE" def Print(self): print "YEHAA" ``` Now I would like to create an instance of `A`. It could look like this, however this syntax is not correct. ...
Taking your question literally I would use meta classes : ``` class MetaSkipInit(type): def __call__(cls): return cls.__new__(cls) class B(object): __metaclass__ = MetaSkipInit def __init__(self): print "FAILURE" def Print(self): print "YEHAA" b = B() b.Print() ``` This c...
Polar plot without grid in matplotlib
6,385,458
5
2011-06-17T12:02:02Z
6,386,097
10
2011-06-17T12:59:51Z
[ "python", "matplotlib" ]
Is there a way to turn of the grid for polar plots in matplotlib? I tried `matplotlib.pyplot.rgrids([], [])`, but it doesn't work.
From your `axes` instance, call `grid(False)`. ``` import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111, polar=True) ax.grid(False) r = np.arange(0,1,0.001) theta = 2*2*np.pi*r ax.plot(theta,r) plt.show() ```
griddata runtime error -- Python / SciPy (Interpolation)
6,385,621
3
2011-06-17T12:17:53Z
6,386,769
7
2011-06-17T13:49:25Z
[ "python", "scipy", "interpolation" ]
I use scipy's griddate-function for interpolation. What does the following error message means which appears when python is executing the griddata-function? ``` File "C:\Python25\lib\site-packages\scipy\interpolate\ndgriddata.py", line 182, in griddata ip = LinearNDInterpolator(points, values, fill_value=fill_value) ...
This typically means that the point set you passed in cannot be triangulated. Some common cases when this might occur: * You have 2D data, but all the points lie along a line. In this case there is no triangulation of the data to non-degenerate triangles. * You have 3D data, but all the points lie on a plane, so no de...
Python technique or simple templating system for plain text output
6,385,686
24
2011-06-17T12:25:17Z
6,385,805
8
2011-06-17T12:36:07Z
[ "python", "templates" ]
I am looking for either technique or templating system for Python for formatting output to simple text. What I require is that it will be able to iterate through multiple lists or dicts. It would be nice if I would be able to define template into separate file (like output.templ) instead of hardcoding it into source co...
There are quite a number of template engines for python: [Jinja](http://jinja.pocoo.org/), [Cheetah](http://www.cheetahtemplate.org/), [Genshi](http://genshi.edgewall.org/) [etc](http://www.google.de/search?q=python+template+engine). You won't make a mistake with any of them.
Python technique or simple templating system for plain text output
6,385,686
24
2011-06-17T12:25:17Z
6,385,864
8
2011-06-17T12:40:42Z
[ "python", "templates" ]
I am looking for either technique or templating system for Python for formatting output to simple text. What I require is that it will be able to iterate through multiple lists or dicts. It would be nice if I would be able to define template into separate file (like output.templ) instead of hardcoding it into source co...
If your prefer to use something shipped with the standard library, take a look at the [format string syntax](http://docs.python.org/library/string.html#format-string-syntax). By default it is not able to format lists like in your output example, but you can handle this with a [custom Formatter](http://docs.python.org/l...
Python technique or simple templating system for plain text output
6,385,686
24
2011-06-17T12:25:17Z
6,385,940
79
2011-06-17T12:47:07Z
[ "python", "templates" ]
I am looking for either technique or templating system for Python for formatting output to simple text. What I require is that it will be able to iterate through multiple lists or dicts. It would be nice if I would be able to define template into separate file (like output.templ) instead of hardcoding it into source co...
You can use the standard library [string template](http://docs.python.org/library/string.html#template-strings): So you have a file `foo.txt` with ``` $title ... $subtitle ... $list ``` and a dictionary ``` d={ 'title':title, 'subtitle':subtitle, 'list':'\n'.join(list) } ``` Then it is quite simple ``` from strin...
DateTimeField doesn't show in admin system
6,386,172
35
2011-06-17T13:06:39Z
6,386,240
26
2011-06-17T13:13:22Z
[ "python", "django", "django-admin", "admin" ]
How come my "date" field doesn't come up in the admin system? In my admin.py file i have ``` from django.contrib import admin from glasses.players.models import * admin.site.register(Rating) ``` and the Rating model has a field called "date" which looks like this ``` date = models.DateTimeField(editable=True, auto_...
I believe to reason lies with the `auto_now_add` field. From [this answer](http://stackoverflow.com/questions/1737017/django-auto-now-and-auto-now-add/1737078#1737078): > Any field with the auto\_now attribute > set will also inherit editable=False > and therefore will not show up in the > admin panel. Also mentione...
DateTimeField doesn't show in admin system
6,386,172
35
2011-06-17T13:06:39Z
16,842,174
9
2013-05-30T17:13:41Z
[ "python", "django", "django-admin", "admin" ]
How come my "date" field doesn't come up in the admin system? In my admin.py file i have ``` from django.contrib import admin from glasses.players.models import * admin.site.register(Rating) ``` and the Rating model has a field called "date" which looks like this ``` date = models.DateTimeField(editable=True, auto_...
*Major Hack:* If you really need to do this (as I do) you can always hack around it by immediatley setting the field to be "editable" defining the field as follows: ``` class Point(models.Model): mystamp=models.DateTimeField("When Created",auto_now_add=True) mystamp.editable=True ``` This will make the field edi...
DateTimeField doesn't show in admin system
6,386,172
35
2011-06-17T13:06:39Z
23,660,030
81
2014-05-14T16:18:42Z
[ "python", "django", "django-admin", "admin" ]
How come my "date" field doesn't come up in the admin system? In my admin.py file i have ``` from django.contrib import admin from glasses.players.models import * admin.site.register(Rating) ``` and the Rating model has a field called "date" which looks like this ``` date = models.DateTimeField(editable=True, auto_...
If you really want to see date in the admin panel, you can add `readonly_fields` in **admin.py**: ``` class RatingAdmin(admin.ModelAdmin): readonly_fields = ('date',) admin.site.register(Rating,RatingAdmin) ``` Any field you specify will be added last after the editable fields. To control the order you can use t...
HTTP requests and JSON parsing in Python
6,386,308
47
2011-06-17T13:17:43Z
6,386,363
11
2011-06-17T13:22:02Z
[ "python", "json" ]
I want to dynamically query Google Maps through the Google Directions API. As an example, this request calculates the route from Chicago, IL to Los Angeles, CA via two waypoints in Joplin, MO and Oklahoma City, OK: <http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoi...
``` import urllib import json url = 'http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false' result = json.load(urllib.urlopen(url)) ```
HTTP requests and JSON parsing in Python
6,386,308
47
2011-06-17T13:17:43Z
6,386,366
96
2011-06-17T13:22:20Z
[ "python", "json" ]
I want to dynamically query Google Maps through the Google Directions API. As an example, this request calculates the route from Chicago, IL to Los Angeles, CA via two waypoints in Joplin, MO and Oklahoma City, OK: <http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoi...
I recommend using the awesome [requests](http://docs.python-requests.org/en/latest/index.html) library: ``` import json, requests url = 'http://maps.googleapis.com/maps/api/directions/json' params = dict( origin='Chicago,IL', destination='Los+Angeles,CA', waypoints='Joplin,MO|Oklahoma+City,OK', senso...
HTTP requests and JSON parsing in Python
6,386,308
47
2011-06-17T13:17:43Z
15,561,153
7
2013-03-22T01:23:02Z
[ "python", "json" ]
I want to dynamically query Google Maps through the Google Directions API. As an example, this request calculates the route from Chicago, IL to Los Angeles, CA via two waypoints in Joplin, MO and Oklahoma City, OK: <http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoi...
Use the requests library, pretty print the results so you can better locate the keys/values you want to extract, and then use nested for loops to parse the data. In the example I extract step by step driving directions. ``` import json, requests, pprint url = 'http://maps.googleapis.com/maps/api/directions/json?' pa...
HTTP requests and JSON parsing in Python
6,386,308
47
2011-06-17T13:17:43Z
17,517,598
42
2013-07-08T00:06:39Z
[ "python", "json" ]
I want to dynamically query Google Maps through the Google Directions API. As an example, this request calculates the route from Chicago, IL to Los Angeles, CA via two waypoints in Joplin, MO and Oklahoma City, OK: <http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoi...
The `requests` Python module takes care of both retrieving JSON data and decoding it, due to its builtin JSON decoder. Here is an example taken from [the module's documentation](http://www.python-requests.org/en/latest/user/quickstart/#json-response-content): ``` >>> import requests >>> r = requests.get('https://githu...
HTTP requests and JSON parsing in Python
6,386,308
47
2011-06-17T13:17:43Z
19,785,386
8
2013-11-05T09:19:27Z
[ "python", "json" ]
I want to dynamically query Google Maps through the Google Directions API. As an example, this request calculates the route from Chicago, IL to Los Angeles, CA via two waypoints in Joplin, MO and Oklahoma City, OK: <http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoi...
`requests` has built-in `.json()` method ``` import requests requests.get(url).json() ```
Using the logging python class to write to a file?
6,386,698
29
2011-06-17T13:44:21Z
6,386,764
32
2011-06-17T13:48:59Z
[ "python", "logging" ]
How can I use the logging class in python to write to a file? Every time I try to use it, it just prints out the message.
Taken from the "[logging cookbook](http://docs.python.org/howto/logging-cookbook.html#logging-cookbook)": ``` # create logger with 'spam_application' logger = logging.getLogger('spam_application') # create file handler which logs even debug messages fh = logging.FileHandler('spam.log') fh.setLevel(logging.DEBUG) logge...
Using the logging python class to write to a file?
6,386,698
29
2011-06-17T13:44:21Z
6,386,990
38
2011-06-17T14:03:47Z
[ "python", "logging" ]
How can I use the logging class in python to write to a file? Every time I try to use it, it just prints out the message.
An example using `logging.basicConfig` rather than `logging.fileHandler()` ``` logging.basicConfig(filename=logname, filemode='a', format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s', datefmt='%H:%M:%S', ...
Why is foo(*arg, x) not allowed in Python?
6,387,631
27
2011-06-17T14:52:12Z
6,387,855
11
2011-06-17T15:09:43Z
[ "python", "function", "variableargumentlists" ]
Look at the following example ``` point = (1, 2) size = (2, 3) color = 'red' class Rect(object): def __init__(self, x, y, width, height, color): pass ``` It would be very tempting to call: ``` Rect(*point, *size, color) ``` Possible workarounds would be: ``` Rect(point[0], point[1], size[0], size[1], ...
I'm not going to speak to why multiple tuple unpacking isn't part of Python, but I will point out that you're not matching your class to your data in your example. You have the following code: ``` point = (1, 2) size = (2, 3) color = 'red' class Rect(object): def __init__(self, x, y, width, height, color): ...
Why is foo(*arg, x) not allowed in Python?
6,387,631
27
2011-06-17T14:52:12Z
6,388,053
9
2011-06-17T15:24:37Z
[ "python", "function", "variableargumentlists" ]
Look at the following example ``` point = (1, 2) size = (2, 3) color = 'red' class Rect(object): def __init__(self, x, y, width, height, color): pass ``` It would be very tempting to call: ``` Rect(*point, *size, color) ``` Possible workarounds would be: ``` Rect(point[0], point[1], size[0], size[1], ...
As far as I know, it was a design choice, but there seems to be a logic behind it. **EDIT:** the `*args` notation in a function call was designed so you could pass in a tuple of variables of an arbitrary length that could change between calls. In that case, having something like f(\*a, \*b, c) doesn't make sense as a ...
Generate a heatmap in MatPlotLib using a scatter data set
6,387,819
4
2011-06-17T15:07:08Z
6,390,144
12
2011-06-17T18:28:42Z
[ "python", "matplotlib", "plot", "visualization", "heatmap" ]
My question is almost exactly similar to [this one](http://stackoverflow.com/questions/2369492/generate-a-heatmap-in-matplotlib-using-a-scatter-data-set). **However**, I'm not satisfied with the answers, because I want to generate an actual heatmap, without explicitely binning the data. To be precise, I would like to ...
Convert your time series data into a numeric format with matplotlib.dats.date2num. Lay down a rectangular grid that spans your x and y ranges and do your convolution on that plot. Make a pseudo-color plot of your convolution and then reformat the x labels to be dates. The label formatting is a little messy, but reason...