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
Apply automatic pep8 fixes from QuickFix window
10,943,987
13
2012-06-08T06:26:08Z
10,988,909
7
2012-06-11T23:50:18Z
[ "python", "vim", "pep8", "python-mode" ]
### Background: I'm using the (fantastic) Vim plugin [python-mode](https://github.com/klen/python-mode), which includes the pep8 linter. The `:PyLint` command runs all linters and opens errors in a QuickFix window. ### Problem: Now, let's assume I'm only using the pep8 linter, and I have a QuickFix window full of er...
## Options There are two simple answers that won't wipe out your undo history. ### 1. Diff with the saved file in Vim I found this `DiffWithSaved` function online quite a while ago and it has been very useful. In this case, you can just run autopep8 in the terminal, and when `Gvim` asks to reload the file, choose no...
remove pytz timezone
10,944,047
42
2012-06-08T06:32:37Z
10,944,136
77
2012-06-08T06:39:17Z
[ "python", "timezone", "pytz" ]
Is there a simple way to remove the timezone from a pytz datetime object? e.g. reconstructing `dt` from `dt_tz` in this example: ``` >>> import datetime >>> import pytz >>> dt = datetime.datetime.now() >>> dt datetime.datetime(2012, 6, 8, 9, 27, 32, 601000) >>> dt_tz = pytz.utc.localize(dt) >>> dt_tz datetime.dateti...
To remove a timezone (tzinfo) from a datetime object: ``` # dt_tz is a datetime.datetime object dt = dt_tz.replace(tzinfo=None) ``` If you are using a library like [arrow](http://crsmithdev.com/arrow/), then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thin...
How do I check if a string only contains alphanumeric characters and dashes?
10,944,438
14
2012-06-08T07:06:33Z
10,944,484
17
2012-06-08T07:10:39Z
[ "python", "regex", "string", "alphanumeric" ]
The string I'm testing can be matched with `[\w-]+`. Can I test if a string conforms to this in Python, instead of having a list of the disallowed characters and testing for that?
If you want to test a string against a regular expression, use the [re](http://docs.python.org/library/re.html) library ``` import re valid = re.match('^[\w-]+$', str) is not None ```
Dynamically updating plot in matplotlib
10,944,621
53
2012-06-08T07:22:07Z
10,944,967
56
2012-06-08T07:49:21Z
[ "python", "matplotlib", "tkinter" ]
I am making an application in Python which collects data from a serial port and plots a graph of the collected data against arrival time. The time of arrival for the data is uncertain. I want the plot to be updated when data is received. I searched on how to do this and found two methods: 1. Clear the plot and re-draw...
> *Is there a way in which I can update the plot just by adding more point[s] to it...* There are a number of ways of animating data in matplotlib, depending on the version you have. Have you seen the [matplotlib cookbook](http://www.scipy.org/Cookbook/Matplotlib/Animations) examples? Also, check out the more modern [...
Dynamically updating plot in matplotlib
10,944,621
53
2012-06-08T07:22:07Z
24,272,092
14
2014-06-17T19:44:34Z
[ "python", "matplotlib", "tkinter" ]
I am making an application in Python which collects data from a serial port and plots a graph of the collected data against arrival time. The time of arrival for the data is uncertain. I want the plot to be updated when data is received. I searched on how to do this and found two methods: 1. Clear the plot and re-draw...
In order to do this without FuncAnimation (eg you want to execute other parts of the code while the plot is been produced or you want to be updating several plots at the same time), calling `draw` alone does not produce the plot (at least with the qt backend). The following works for me: ``` import matplotlib.pyplot ...
Python: unescape "\xXX"
10,944,907
13
2012-06-08T07:44:31Z
10,944,959
7
2012-06-08T07:48:29Z
[ "python" ]
I have a string with *escaped data* like ``` escaped_data = '\\x50\\x51' print escaped_data # gives '\x50\x51' ``` What Python function would unescape it so I would get ``` raw_data = unescape( escaped_data) print raw_data # would print "PQ" ```
You could use the 'unicode\_escape' codec: ``` >>> '\\x50\\x51'.decode('unicode_escape') u'PQ' ``` Alternatively, 'string-escape' will give you a classic Python 2 string (bytes in Python 3): ``` >>> '\\x50\\x51'.decode('string_escape') 'PQ' ```
Python: unescape "\xXX"
10,944,907
13
2012-06-08T07:44:31Z
10,944,965
16
2012-06-08T07:49:07Z
[ "python" ]
I have a string with *escaped data* like ``` escaped_data = '\\x50\\x51' print escaped_data # gives '\x50\x51' ``` What Python function would unescape it so I would get ``` raw_data = unescape( escaped_data) print raw_data # would print "PQ" ```
You can decode with `string-escape`. ``` >>> escaped_data = '\\x50\\x51' >>> escaped_data.decode('string-escape') 'PQ' ``` In [Python 3.0](http://en.wikipedia.org/wiki/History_of_Python#Version_3.0) there's no `string-escape`, but you can use `unicode_escape`. From a `bytes` object: ``` >>> escaped_data = b'\\x50\\...
gcc : Unable to find Python.h, When its there in /usr/includes/python2.7?
10,945,675
4
2012-06-08T08:47:16Z
10,945,719
10
2012-06-08T08:50:30Z
[ "python", "c", "gcc", "include", "include-path" ]
My C code: ``` #include<stdio.h> #include "Python.h" int main() { printf("Hello World"); return 0; } ``` I have `python-dev` installed for python2.7. Moreover, `Python.h` is available in `/usr/include/python2.7`. `gcc myfile.c` # Python.h: No such file or directory I even tried : `gcc -L/usr/include/python...
It should be `-I`, not `-L`: ``` gcc -I/usr/include/python2.7 myfile.c ```
In Python, how can I open a file and read it on one line, and still be able to close the file afterwards?
10,946,134
5
2012-06-08T09:20:28Z
10,946,193
14
2012-06-08T09:24:09Z
[ "python" ]
While working through this exercise I ran into a problem. ``` from sys import argv from os.path import exists script, from_file, to_file = argv print "Copying from %s to %s" % (from_file, to_file) # we could do these two on one line too, how? input = open(from_file) indata = input.read() print "The input file is %d...
The preferred way to work with resources in python is to use [context managers](http://docs.python.org/whatsnew/2.6.html#pep-343-the-with-statement): ``` with open(infile) as fp: indata = fp.read() ``` The `with` statement takes care of closing the resource and cleaning up. You *could* write that on one line if...
Python try except finally: Invalid syntax error (what's wrong with this code?)
10,946,339
2
2012-06-08T09:34:39Z
10,946,408
11
2012-06-08T09:38:53Z
[ "python", "sqlalchemy" ]
I am trying to use finally in the following function, however, Python reports a Syntax error. I'm sure I'm doing something silly, but I can't seem to spot it ... Snippet follows below: ``` # Store ids with key # Returns GUID (used to clear table after words) def storeIdsInTemporaryTable(dbinfo, id_list): conn = d...
Are you using a Python < 2.5? try except finally was only added in 2.5 and before you had to wrap try except in a try finally.
pytz: getting all timezones, where now specific time
10,947,115
2
2012-06-08T10:26:24Z
10,947,203
9
2012-06-08T10:32:49Z
[ "python", "timezone", "pytz" ]
In DB I have table (User), which store timezone (as a string value, for ex.: "Europe/Oslo") for that user. Now, I need to get all Users, where local time now is for ex.: 9AM. Is there any good way of doing this, w/o making loop over all Users? If pytz is able to return list of timezones, where for now time is 9AM, I c...
``` import datetime import pytz now = datetime.now(pytz.utc) # datetime.datetime(2012, 6, 8, 10, 31, 58, 493905, tzinfo=<UTC>) [tz for tz in pytz.common_timezones_set if now.astimezone(pytz.timezone(tz)).hour == 9] # ['Atlantic/Cape_Verde'] [tz for tz in pytz.common_timezones_set if now.astimezone(pytz.timezone(tz))...
Database errors in Django when using threading
10,948,537
7
2012-06-08T12:06:30Z
10,949,616
7
2012-06-08T13:16:35Z
[ "python", "django", "multithreading", "postgresql" ]
I am working in a Django web application which needs to query a PostgreSQL database. When implementing concurrency using Python [threading](http://docs.python.org/library/threading.html) interface, I am getting `DoesNotExist` errors for the queried items. Of course, these errors do not occur when performing the queries...
Try using TransactionTestCase: ``` class ThreadingTest(TransactionTestCase): ``` TestCase keeps data in memory and doesn't issue a COMMIT to database. Probably the threads are trying to connect directly to DB, while the data is not commited there yet. Seedescription here: <https://docs.djangoproject.com/en/dev/topics...
Sum one column of a list(follow up)
10,950,057
2
2012-06-08T13:45:13Z
10,950,090
7
2012-06-08T13:47:25Z
[ "python" ]
I have a list that that looks like this: ``` ('string ', 'time', 'SPY', 0, 0, 131.63, 100), ('sting ', 'time', 'SPY', 0, 0, 131.63, 700) ``` what I want to do is add the last column of data What I though to do is unzip the list and then sum the absolute value of the date in the last column but I cant get it to work ...
Generator expressions are your friend: ``` sum(l[-1] for l in list) ``` (although I do hope your list isn't literally called 'list', since that would shadow the builtin). For the followup, it does depend on exactly what you mean by 'add all the sums that are outputted'. This could mean have some number of lists like...
python Socket.IO client for sending broadcast messages to TornadIO2 server
10,950,365
19
2012-06-08T14:03:36Z
10,950,702
16
2012-06-08T14:23:06Z
[ "python", "django", "websocket", "socket.io", "tornado" ]
I am building a realtime web application. **I want to be able to send broadcast messages from the server-side implementation of my python application.** Here is the setup: * **[socketio.js](http://socket.io/)** on the client-side * **[TornadIO2](https://github.com/mrjoes/tornadio2)** server as Socket.IO server * **py...
I've recently written a very similar application on a similar setup, so I do have several insights. The proper way of doing what you need is to have a pub-sub backend. There's only so much you can do with simple `ConnectionHandler`s. Eventually, handling class-level sets of connections starts to get ugly (not to menti...
Pandas DataFrame aggregate function using multiple columns
10,951,341
37
2012-06-08T15:01:32Z
10,964,938
55
2012-06-09T22:07:32Z
[ "python", "pandas" ]
Is there a way to write an aggregation function as is used in `DataFrame.agg` method, that would have access to more than one column of the data that is being aggregated? Typical use cases would be weighted average, weighted standard deviation funcs. I would like to be able to write something like ``` def wAvg(c, w):...
Yes; use the `.apply(...)` function, which will be called on each sub-DataFrame. For example: ``` grouped = df.groupby(keys) def wavg(group): d = group['data'] w = group['weights'] return (d * w).sum() / w.sum() grouped.apply(wavg) ```
Python - reference object in memory by address
10,951,416
3
2012-06-08T15:06:28Z
10,951,462
7
2012-06-08T15:08:27Z
[ "python" ]
This is kind of a silly question, but I'm just curious about it. Suppose I'm at the Python shell and I have some database object that I query. I do: `db.query(queryString)` The query returns a response `<QueryResult object at 0xffdf842c>` or something like that. But then I say "Oh! I forgot to put `result = db.quer...
You can do: ``` >>> result=_ ``` at the shell. `_` represents the last calculated object. Example: ``` >>> iter(range(10)) <listiterator object at 0x10ebcccd0> >>> result=_ >>> result <listiterator object at 0x10ebcccd0> >>> list(result) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ``` You can also see the string representation...
resource file in PyQt4
10,951,608
6
2012-06-08T15:19:12Z
10,951,766
12
2012-06-08T15:30:13Z
[ "python", "pyqt4", "embedded-resource" ]
I'm trying to understand an example in PyQt4 (simpletreemodel.pyw) I see the code ``` import simpletreemodel_rc ``` But I can't see where the module is used in the example code When I examine the module simpletreemodel, I see: ``` from PyQt4 import QtCore qt_resource_data = b"\ \x00\x00\x07\xb9\ \x47\ \x65\x74\...
What you see is the byte-by-byte dump of the resources the `.qrc` file contains. You don't explicitly access the objects inside the module. Just import it, and you will be able to access those resources by their original names(and paths) but preceded by a colon. ``` pixmap = QPixMap(':/images/filename.jpg') ``` **UPD...
Plot Ellipse with matplotlib.pyplot (Python)
10,952,060
6
2012-06-08T15:47:18Z
10,952,180
7
2012-06-08T15:55:24Z
[ "python", "matplotlib", "ellipse" ]
Sorry if this is a stupid question, but is there an easy way to plot an ellipse with matplotlib.pyplot in Python? I was hoping there would be something similar to matplotlib.pyplot.arrow, but I can't find anything. Is the only way to do it using matplotlib.patches with draw\_artist or something similar? I would hope t...
Have you seen the [matplotlib ellipse demo](http://matplotlib.sourceforge.net/examples/pylab_examples/ellipse_demo.html)? Here they use [`matplotlib.patches.Ellipse`](http://matplotlib.sourceforge.net/api/artist_api.html#matplotlib.patches.Ellipse).
When would os.environ['foo'] not match os.getenv('foo')?
10,952,507
24
2012-06-08T16:17:47Z
10,953,127
12
2012-06-08T17:06:50Z
[ "python", "windows", "environment-variables", "freebsd" ]
I have a small Python application, launched via `subprocess.Popen`, that takes some parameters in the form of environment variables. I do this by passing the environment structure into the `Popen` call. The program then reads the variables via `os.getenv`. Or rather, it used to read them that way. On Windows, it worke...
`os.environ` is created on import of the `os` module, and doesn't reflect changes to the environment that occur afterwards unless modified directly. Interestingly enough, however, `os.getenv()` doesn't actually get the most recent environment variables either, at least not in CPython. You see, in CPython, `os.getenv()`...
Count lower case characters in a string
10,953,189
6
2012-06-08T17:12:01Z
10,953,236
10
2012-06-08T17:15:00Z
[ "python" ]
What is the most pythonic and/or efficient way to count the number of characters in a string that are lowercase? Here's the first thing that came to mind: ``` def n_lower_chars(string): return sum([int(c.islower()) for c in string]) ```
Clever trick of yours! However, I find it more readable to filter the lower chars, adding 1 for each one. ``` def n_lower_chars(string): return sum(1 for c in string if c.islower()) ```
Update new Django and Python 2.7.* with virtualenv on Dreamhost (with passenger)
10,953,695
29
2012-06-08T17:52:23Z
10,953,696
47
2012-06-08T17:52:24Z
[ "python", "django", "passenger", "dreamhost" ]
Dreamhost is a great host for small project. And it's also Django friendly hosting. Everything good except python and Django version is a little bit out of date. Well it's a whole day of work to figure out how to update Python 2.7.3, Django 1.4 on dreamhost and I really want to share with whoever finding it
I currently have private server, a shell account and a bit of luck. So here is what I do: 1. SSH to your host to upgrade python ``` cd ~ mkdir tmp cd tmp wget http://www.python.org/ftp/python/2.7.3/Python-2.7.3.tgz tar zxvf Python-2.7.3.tgz cd Python-2.7.3 ./configure --enable-shared --...
Recursive module import and reload
10,955,057
16
2012-06-08T19:35:48Z
10,955,181
12
2012-06-08T19:47:34Z
[ "python", "reload", "python-import" ]
Can someone explain why executing the following code: file "**hello.py**": ``` import hello print "hello" hello = reload(hello) ``` executing as `python hello.py` prints the following? ``` hello hello hello hello ``` Why 4 times? I know that when a module is already imported it's not imported again, but reload for...
`python hello.py` (A) runs the code once, when (A) calls `import hello` the code is run again (B), when (A) and (B) call `reload(hello)`, the code is run twice more, for four times total. In general, for the lifetime of a program a module's code will be executed at the following times: * Once if it is the main module...
Recursive module import and reload
10,955,057
16
2012-06-08T19:35:48Z
10,955,314
8
2012-06-08T19:56:58Z
[ "python", "reload", "python-import" ]
Can someone explain why executing the following code: file "**hello.py**": ``` import hello print "hello" hello = reload(hello) ``` executing as `python hello.py` prints the following? ``` hello hello hello hello ``` Why 4 times? I know that when a module is already imported it's not imported again, but reload for...
`reload` keeps a list (actually a dict) of modules it is currently reloading to avoid reloading modules recursively. See <http://hg.python.org/cpython/file/e6b8202443b6/Lib/imp.py#l236> This isn't documented, as such, but I think you can probably rely on it remaining the case.
Encrypt File using AES and PyCrypto in Python 3
10,956,274
4
2012-06-08T21:32:25Z
10,959,695
7
2012-06-09T08:59:48Z
[ "python", "python-3.x", "pycrypto" ]
I'm using PyCrypto to encrypt a binary file using AES in CBC mode (Python 3.2.3 64-bit and PyCrypto 2.6). Using the code from this: <http://eli.thegreenplace.net/2010/06/25/aes-encryption-of-files-in-python-with-pycrypto/> But running into the following error: ValueError: IV must be 16 bytes long. Here's the code: `...
As the PyCrypto API says, the IV [must be a byte string](https://www.dlitz.net/software/pycrypto/api/current/Crypto.Cipher.AES-module.html#new), not a *text* string. Your piece of code will work fine in Python 2, because they are the same thing (that is, they all are class `str`, unless you deal with Unicode text). In...
How to solve this Python puzzle in a much more elegant manner?
10,956,286
2
2012-06-08T21:33:23Z
10,956,381
9
2012-06-08T21:44:21Z
[ "coding-style", "python" ]
I was working through CoderByte 'Python' questions. Time is of essence, so the code may not be really readable but pretty straight forward. I will be interested in your approach. My code works for some words but testing with 'sentence' is giving me a different result, debugging as we speak. Please comment on my thinkin...
I would use [`str.translate()`](http://docs.python.org/library/stdtypes.html#str.translate) for this, it might look something like this: ``` import string def LetterChanges(s): orig = string.letters new = string.ascii_lowercase[1:] + 'a' + string.ascii_uppercase[1:] + 'A' for vowel in 'aeiou': new...
Python: How to access tuple values inside a dictionary of a dictionary
10,956,645
4
2012-06-08T22:15:37Z
10,956,669
7
2012-06-08T22:19:32Z
[ "python" ]
I have a dict of dict setup as follows: ``` from collections import namedtuple Point = namedtuple('Point', 'r w') mydict= { 'user1': {'item1': Point(2.5,0.1),'item2': Point(3.5,0.6)}, 'user2': {'item1': Point(3.0,0.3), 'item3': Point(3.5,0.8)}, 'user3': {'item1': Point(2.0,0.4),'item3': Point(0.5,0.1), 'i...
You can do it like this: ``` r_vals = [u['item3'].r for u in mydict.itervalues() if 'item3' in u] if r_vals: r_avg = sum(r_vals)/len(r_vals) else: r_avg = 0 # ??? ```
how to make hollow square marks with matplotlib in python
10,956,903
5
2012-06-08T22:53:40Z
10,957,084
14
2012-06-08T23:20:00Z
[ "python", "matplotlib" ]
Black line in the following graph is plotting using the below command for matplotlib python ``` pylab.semilogy(xaxis, pq_averages, 'ks-',color='black', label='DCTCP-PQ47.5') ``` So 'ks-' part indicates solid line with square black marks. So it had solid squares for the plotted points. Can these squares be made hollow...
Try adding `markerfacecolor` like so: ``` pylab.semilogy(xaxis, pq_averages, 'ks-', markerfacecolor='white', label='DCTCP-PQ47.5') ```
Python naming conventions in decorators
10,957,409
16
2012-06-09T00:19:37Z
10,957,424
16
2012-06-09T00:22:03Z
[ "coding-style", "python" ]
Are there any "accepted" naming conventions for the innards of Python decorators? The [style guide](http://www.python.org/dev/peps/pep-0008/) doesn't mention it, and [this awesome entry about decorators](http://stackoverflow.com/questions/739654/understanding-python-decorators) is pretty consistent in using variants o...
There are no standardized conventions (such as PEPs) for those names. If you check the python stdlib you'll find lots of different names for those functions. However, `decorator` is a rather common name for the decorator function `inner`. It is also common to call your `wrapped` function `wrapper` and decorate it wi...
How to for loop in reverse?
10,957,812
2
2012-06-09T02:02:20Z
10,957,836
7
2012-06-09T02:08:17Z
[ "python", "algorithm", "loops", "for-loop", "simulation" ]
I'm making a water simulation program, and I need it to do a for loop through y, x. But I need it to check the most bottom y first, then up. This is my lvl: ``` lvl = [[0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] ``` I need it to check lvl[4] and the...
You can use the [`reversed`](http://docs.python.org/library/functions.html?highlight=reversed#reversed) built-in method to reverse the ordering of your list of lists: ``` for li in reversed(lvl): print li ``` Output: ``` [0, 0, 0, 0, 0] [0, 0, 0, 0, 0] [0, 0, 1, 0, 0] [0, 0, 1, 0, 0] [0, 0, 1, 0, 0] ```
When is it appropriate to use a database , in Python
10,957,877
13
2012-06-09T02:16:44Z
10,957,977
8
2012-06-09T02:49:43Z
[ "python", "database", "flat-file" ]
I am making a little add-on for a game, and it needs to store information on a player: * username * ip-address * location in game * a list of alternate user names that have came from that ip or alternate ip addresses that come from that user name I read an article a while ago that said that unless I am storing a larg...
Most importantly, unless you specifically need performance or high reliability, do whatever will make your code simplest/easiest to write. --- If your data is extremely structured (and you know SQL or are willing to learn) then using a database like `sqlite3` might be appropriate. (You should ignore the comment about...
Why do I get the error "TypeError: coercing to Unicode: need string or buffer, int found"?
10,958,466
9
2012-06-09T04:54:59Z
10,958,477
26
2012-06-09T04:56:15Z
[ "python", "unicode" ]
After running this small program: ``` #!/usr/bin/env python2.7 # -*-coding:utf-8 -* a = 1 b = 2 c = 3 title = u"""a=""" + a + u""", b=""" + str(b) + \ u""", c=""" + str(c) print(title) ``` I get the following error: ``` u""", c=""" + str(c) TypeError: coercing to Unicode: need string or buffer, int found ``` Bu...
You didn't wrap `a` in a `str` call. You need to do `str(a)` where you have `a`, just like you did for b and c.
Generator Expression vs yield: Why isn't 'next()' working?
10,958,771
5
2012-06-09T05:55:50Z
10,958,785
19
2012-06-09T05:58:14Z
[ "python" ]
I know I must be missing something simple, but I am not seeing it. If I have a generator expression like this: ``` >>> serializer=(sn for sn in xrange(0,sys.maxint)) ``` I can generate, easily, individual integers like this: ``` >>> serializer.next() 0 >>> serializer.next() 1 >>> serializer.next() 2 ``` If I write...
`ser()` creates the generator. So each time you call `ser()` it is sending you a new generator instance. You need to use it just like the expression: ``` serializer = ser() serializer.next() ``` Consider that, if it *didn't* work this way, you could only ever use the `ser()` function once and you could never reset it...
"exists" keyword in Python?
10,958,874
8
2012-06-09T06:14:31Z
10,958,885
21
2012-06-09T06:17:46Z
[ "python" ]
I've recently made the following example for Pythons for ... else: ``` def isPrime(element): """ just a helper function! don't get religious about it! """ if element == 2: return True elif element <= 1 or element % 2 == 0: return False else: for i in xrange(3, element, 2): ...
``` myList = [4, 4, 9, 12] if not any(isPrime(x) for x in myList): print("The list did not contain a prime") ``` Python also has `all()` which cranks through any sequence and returns `True` if all elements evaluate true. `any()` and `all()` both have short-circuit evaluation: if `any()` finds any element that ev...
printing \78 gives beep-tone in console
10,959,410
2
2012-06-09T08:03:08Z
10,959,421
8
2012-06-09T08:04:50Z
[ "python", "windows" ]
Why does the following code make my machine do a beep-tone? ``` print '\78' ``` I have tested it in the interactive interpreter and running a script in the command-line. I have also tested it in an embedded environment and it does not invoke a beep there.
It interprets `\7` as the *octal* escape, so it's BEL with ASCII code 7. This is a character that, when printed on a terminal, rings a bell. Yes, a literal bell in ancient times with teletypes (and even some terminals). Since we pride ourselves in not letting 1960s technology go to waste every terminal emulator has the...
Building a DSL query language
10,959,489
6
2012-06-09T08:21:12Z
14,780,697
8
2013-02-08T20:20:12Z
[ "python", "django", "dsl" ]
i'm working on a project (written in Django) which has only a few entities, but many rows for each entity. In my application i have several static "reports", directly written in plain SQL. The users can also search the database via a generic filter form. Since the target audience is really tech-savvy and at some point...
Writing such a DSL is actually surprisingly easy with [PLY](http://www.dabeaz.com/ply/), and what ho—there's already an example available for doing just what you want, in Django. You see, Django has this fancy thing called a [`Q` object](https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-...
Tkinter Canvas move item to top level
10,959,858
4
2012-06-09T09:27:56Z
10,959,968
8
2012-06-09T09:46:01Z
[ "python", "tkinter", "widget", "tkinter-canvas" ]
I have a Tkinter Canvas widget (Python 2.7, not 3), and on this Canvas I have different items. If I create a new item that overlaps an old item, It will be in front. How can I now move the old item in front of the newly created one, or even in front of all other items on the Canvas? Example code so far: ``` from Tkin...
Use the `tag_lower()` and `tag_raise()` methods for the `Canvas` object: ``` canvas.tag_raise(firstRect) ``` Or: ``` canvas.tag_lower(secondRect) ```
Non-ASCII characters in Matplotlib
10,960,463
27
2012-06-09T11:07:24Z
10,960,464
46
2012-06-09T11:07:25Z
[ "python", "unicode", "matplotlib", "ascii" ]
I have a problem displaying non-[ASCII](http://en.wikipedia.org/wiki/ASCII) characters in Matplotlib, these characters are rendered as small boxes instead of a proper font, it looks like (I filled these boxes with red paint to hightlight them): ![Here is the image showing the problem](http://i.stack.imgur.com/HSN1f.pn...
This problem may actually have a couple of different causes: **The default font does not include these glyphs** You may change the default font using the following (before any plotting is done!) ``` matplotlib.rc('font', family='Arial') ``` In some versions of matplotlib you'll have te set family: ``` matplotl...
How to read file attributes in directory?
10,960,477
3
2012-06-09T11:08:13Z
10,960,485
19
2012-06-09T11:09:50Z
[ "python" ]
For example, ``` import os print os.listdir() ``` list files in directory. How to get file modification time fo all files in directory ?
Use the [`os.stat`](http://docs.python.org/library/os.html#os.stat) call for obtaining file properties like the modification time. ``` import os for filename in os.listdir(): info = os.stat(filename) print info.st_mtime ``` `st_mtime` is a float value on python 2.5 and up, representing seconds since the epoch...
apt-get install for different python versions
10,960,805
9
2012-06-09T11:59:06Z
10,961,173
8
2012-06-09T12:51:28Z
[ "python", "linux", "ubuntu", "installation" ]
I have ubuntu 10.04 with python2.6 by default. I have installed python2.7. When I want to install python packages with ``` apt-get python-<package> ``` it gets installed to python2.6. How can I make it to install to python2.7, is there any option? I have looked at [this](http://superuser.com/a/236249/133546), but I...
Python has got its own package managing facilities, in parallel to the one sets by the Linux distributions (including Ubuntu). The repository is the Pypi - Python Package Index, and packages are installed with [`pip`](https://pypi.python.org/pypi/pip) or the easy\_install script, which is part of Python's setuptools pa...
How to generate an html directory list using Python
10,961,378
11
2012-06-09T13:18:40Z
10,961,991
26
2012-06-09T14:54:49Z
[ "python", "html", "flask", "jinja2" ]
I am having some problems using Python to generate an html document. I am attempting to create an HTML list of a directory tree. This is what I have so far: ``` def list_files(startpath): for root, dirs, files in os.walk(startpath): level = root.replace(startpath, '').count(os.sep) if level <= 1: ...
You could separate the directory tree generation and its rendering as html. To generate the tree you could use a simple recursive function: ``` def make_tree(path): tree = dict(name=os.path.basename(path), children=[]) try: lst = os.listdir(path) except OSError: pass #ignore errors else: ...
Is there a 'man' for python?
10,962,160
6
2012-06-09T15:19:34Z
10,962,176
9
2012-06-09T15:21:36Z
[ "python" ]
I am wondering if there is a CLI like 'man.py' dedicated to Python? ex, ``` man.py os.system > system(command) -> exit_status > > Execute the command (a string) in a subshell. ```
The easiest way is using `pydoc function` on the shell, with `function` being either the name of a builtin or the qualified name (`module.function`) of a function in a module: ``` > PAGER=cat pydoc urllib.urlencode [adrian@hades:~]> PAGER=cat pydoc urllib.urlencode Help on function urlencode in urllib: urllib.urlenco...
Is there a 'man' for python?
10,962,160
6
2012-06-09T15:19:34Z
10,962,184
13
2012-06-09T15:22:13Z
[ "python" ]
I am wondering if there is a CLI like 'man.py' dedicated to Python? ex, ``` man.py os.system > system(command) -> exit_status > > Execute the command (a string) in a subshell. ```
The pydoc module provides it: ``` $ python -m pydoc os.system Help on built-in function system in os: os.system = system(...) system(command) -> exit_status Execute the command (a string) in a subshell. $ ```
How does Python's Garbage Collector Detect Circular References?
10,962,393
24
2012-06-09T15:52:16Z
10,962,484
21
2012-06-09T16:05:59Z
[ "python", "garbage-collection", "cpython" ]
I'm trying to understand how Python's garbage collector detects circular references. When I look at the documentation, all I see is a statement that circular references are detected, except when the objects involved have a `__del__` method. If this happens, my understanding (possibly faulty) is that the gc module acts...
> How does Python detect & free circular memory references before making use of the gc module? It doesn't. The gc exists only *to* detect and free circular references. Non-circular references are handled through refcounting. Now, to see *how* gc determines the set of objects referenced by any given object, take a loo...
Overload [] python operator and chaining methods using a memory reference
10,962,448
7
2012-06-09T16:00:28Z
10,962,531
9
2012-06-09T16:12:44Z
[ "python", "operator-overloading" ]
Is it possible to overload `[] (__getitem__)` Python operator and chain methods using the initial memory reference. Imagine I have a class `Math` that accepts a list of integer numbers, like this: ``` class Math(object): def __init__(self, *args, **kwargs): assert(all([isinstance(item, int) for item in li...
As Winston mentions, you need to implement an auxiliary object: ``` class Math(object): def __init__(self, *args, **kwargs): self.list = list(args) def __getitem__(self, i): return MathSlice(self, i) class MathSlice(object): def __init__(self, math, slice): self.math = math ...
how to combine django plus gevent the basics?
10,964,571
15
2012-06-09T21:04:44Z
10,991,862
19
2012-06-12T07:02:45Z
[ "python", "django", "comet", "gevent" ]
After much searching and googling I am coming back to the well. I have Django 1.4 and am looking for a decent *working* example to figure out getting Django to work with gevent. I like the Django framwork but I need it to handle long polling. I already have a working server using gevent on it's own that handles long po...
Here's how I run Django with gevent + monkey patching: 1. I've modified `manage.py` so the first line (after the shebang) is `from gevent import monkey; monkey.patch_all()` 2. I've added a new `run_production_server` script (see below). Finally, I've configured my front-end webserver to proxy requests to port `1234` ...
python error: no module named pylab
10,965,336
48
2012-06-09T23:30:52Z
10,965,351
86
2012-06-09T23:34:28Z
[ "python", "python-2.7", "ubuntu-12.04", "matplotlib" ]
I am new to Python and want to use its `plot` functionality to create graphs. I am using ubuntu 12.04. I followed the Python installation steps from <http://eli.thegreenplace.net/2011/10/10/installing-python-2-7-on-ubuntu/> but when I do ``` from pylab import * ``` I am getting this error ``` >>> from pylab import *...
You'll need to install numpy, scipy and matplotlib to get pylab. In ubuntu you can install them with this command: ``` sudo apt-get install python-numpy python-scipy python-matplotlib ``` If you installed python from source you will need to install these packages through pip. Note that you may have to install other d...
python error: no module named pylab
10,965,336
48
2012-06-09T23:30:52Z
13,275,617
18
2012-11-07T18:12:32Z
[ "python", "python-2.7", "ubuntu-12.04", "matplotlib" ]
I am new to Python and want to use its `plot` functionality to create graphs. I am using ubuntu 12.04. I followed the Python installation steps from <http://eli.thegreenplace.net/2011/10/10/installing-python-2-7-on-ubuntu/> but when I do ``` from pylab import * ``` I am getting this error ``` >>> from pylab import *...
I solved the same problem by installing "matplotlib".
How to convert Numpy array to PIL image applying matplotlib colormap
10,965,417
28
2012-06-09T23:48:26Z
10,967,471
58
2012-06-10T08:55:47Z
[ "python", "numpy", "matplotlib", "python-imaging-library", "color-mapping" ]
I have a simple problem but cannot find a good solution to it. I want to take a numpy 2D array which represents a grayscale image, and convert it to an RGB PIL image while applying some of the matplotlib colormaps. I can get a reasonable PNG output by using the `pyplot.figure.figimage` command: ``` dpi = 100.0 w, h ...
Quite a busy one liner, but here it is: 1. First ensure your numpy array, `myarray`, is normalised with the max value at `1.0`. 2. Apply the colormap directly to `myarray`. 3. Rescale to the `0-255` range. 4. Convert to integers, using `np.uint8()`. 5. Use `Image.fromarray()`. And you're done: ``` import Image im = ...
How do you manage a temporary directory such that it is guaranteed to be deleted on program close?
10,965,479
6
2012-06-10T00:03:52Z
10,965,572
16
2012-06-10T00:28:47Z
[ "garbage-collection", "python" ]
I'm working with a temporary directory and I want to make sure that it gets deleted on program close (regardless of whether the program was successful). I'm using `tempfile.mkdtemp`to create the directory and putting the string that's created into a subclass of `str` that deletes the directory on its `__del__` command:...
I wouldn't use a `__del__` method, the semantics are unreliable, and could interfere with garbage collection. Use a context manager: define a `__enter__` and `__exit__` method, and put your use of the object in a `with` statement. It's clear, it's explicit, and it will work without worry. Or, another way to make a con...
How do you manage a temporary directory such that it is guaranteed to be deleted on program close?
10,965,479
6
2012-06-10T00:03:52Z
13,906,631
7
2012-12-16T23:42:49Z
[ "garbage-collection", "python" ]
I'm working with a temporary directory and I want to make sure that it gets deleted on program close (regardless of whether the program was successful). I'm using `tempfile.mkdtemp`to create the directory and putting the string that's created into a subclass of `str` that deletes the directory on its `__del__` command:...
I needed something similar for a package test suite that depended on the existence of a specific (semi-mocked) file structure. With many test modules I don't always know which tests will be run and in what order, or how the test run will exit. Using `__del__` at application exit is unreliable in my experience. And usi...
How to have an alias of URL on Python Flask?
10,965,899
4
2012-06-10T02:05:32Z
10,965,916
9
2012-06-10T02:08:56Z
[ "python", "flask", "jinja2", "werkzeug" ]
I'm using Flask 0.8. How to have an alias of a URL like this: ``` @app.route('/') def index(): # I want to display as http://localhost/index, BUT, I DON'T WANT TO REDIRECT. # KEEP URL with only '/' @app.route('/index') def index(): # Real processing to display /index view ``` So, why my hope to use an a...
This should work. But why do you want two URL's to display the same thing? ``` @app.route('/') @app.route('/index') def index(): ... ```
Can subprocess.call be invoked without waiting for process to finish?
10,965,949
13
2012-06-10T02:19:50Z
10,965,965
21
2012-06-10T02:23:40Z
[ "python" ]
I'm currently using subprocess.call() to invoke another program, but it blocks the executing thread until that program finishes. Is there a way to simply launch that program without waiting for return?
Use `subprocess.Popen` instead of `subprocess.call`: ``` process = subprocess.Popen(['foo', '-b', 'bar']) ```
What happens to a immutable object in python when its value is changed?
10,966,884
5
2012-06-10T06:52:23Z
10,966,910
8
2012-06-10T06:58:49Z
[ "python", "object", "immutability" ]
Does an immutable object in python mean that its value cannot be changed after its conception? If that is the case what will happen when we try to change its value. Let me try to explain my doubt with an example. For instance I initialized a String object `S` with value `"Hello World"`. ``` S = 'Hello World' ``` Th...
Python stopped `S` pointing to the the old string object and made it point to a new one ``` >>> S="Hello World" >>> id(S) 32386960 >>> S="Hello Human" >>> id(S) 32387008 >>> ``` You can't change immutable objects, so even when you think you muight be (eg with the `+=` operator) you aren't ``` >>> S="Hello" >>> id(S)...
Do Python Inline if statements execute a function twice?
10,967,326
7
2012-06-10T08:31:02Z
10,967,336
20
2012-06-10T08:32:19Z
[ "python" ]
When I do something like (totally random example dont read into variable names): ``` variable = read_file() if read_file() else "File was empty" ``` In this case does read\_file() get excuted twice? If so is there a way to do it to only execute once but keep it within one line?
In that case `read_file()` would get executed twice. You can do this instead: ``` variable = read_file() or "File was empty" ```
Python Selenium: Save Web Page
10,967,408
8
2012-06-10T08:46:03Z
10,970,124
10
2012-06-10T15:56:17Z
[ "python", "selenium" ]
I am using selenium webdriver for Python 2.7: 1. Start a browser: `browser = webdriver.Firefox()`. 2. Go to some URL: `browser.get('http://www.google.com')`. At this point, how can I send a 'Save Page As' command to the browser? Note: It is not the web-page source that I am interested in. I would like to save the pa...
Unfortunately you can't do what you would like to do with Selenium. You can use page\_source to get the html but that is all that you would get. Selenium unfortunately can't interact with the Dialog that is given to you when you do save as. You can do the following to get the dialog up but then you will need somethin...
How do I dynamically create properties in Python?
10,967,551
11
2012-06-10T09:13:03Z
10,967,617
21
2012-06-10T09:26:05Z
[ "python" ]
Suppose I have a class like this: ``` class Alphabet(object): __init__(self): self.__dict = {'a': 1, 'b': 2, ... 'z': 26} @property def a(self): return self.__dict['a'] @property def b(self): return self.__dict['b'] ... @property def z(self) ...
Don't use properties but implement the following methods: * `__getattr__(self, name)` * `__setattr__(self, name, value)` * `__delattr__(self, name)` See <http://docs.python.org/reference/datamodel.html#customizing-attribute-access> Your `__getattr__` method could look like this: ``` def __getattr__(self, name): ...
How to make HTTP request through a (tor) socks proxy using python?
10,967,631
10
2012-06-10T09:30:13Z
10,968,171
13
2012-06-10T11:06:35Z
[ "python", "http", "proxy", "socks", "tor" ]
I'm trying to make a HTTP request using python. I tried changing my windows system proxy (using `inetcpl.cpl` ) ``` url = 'http://www.whatismyip.com' request = urllib2.Request(url) request.add_header('Cache-Control','max-age=0') request.set_proxy('127.0.0.1:9050', 'socks') response = urllib2.urlopen(request) response....
I'm the OP. According to the answer given by Tisho, this worked for me: ``` import urllib, urllib2 ##Download SocksiPy - A Python SOCKS client module. ( http://code.google.com/p/socksipy-branch/downloads/list ) ##Simply copy the file "socks.py" to your Python's lib/site-packages directory, and initiate a socks socket...
python: when can I unpack a generator?
10,967,819
6
2012-06-10T10:04:08Z
10,967,834
8
2012-06-10T10:06:42Z
[ "python", "args", "iterable-unpacking" ]
How does it work under the hood? I don't understand the reason for the errors below: ``` >>> def f(): ... yield 1,2 ... yield 3,4 ... >>> *f() File "<stdin>", line 1 *f() ^ SyntaxError: invalid syntax >>> zip(*f()) [(1, 3), (2, 4)] >>> zip(f()) [((1, 2),), ((3, 4),)] >>> *args = *f() File "<stdin>", ...
The `*iterable` syntax is only supported in an argument list of a function call (and in function definitions). In Python 3.x, you can also use it on the left-hand side of an assignment, like this: ``` [*args] = [1, 2, 3] ``` **Edit**: Note that there are [plans to support the remaining generalisations](http://bugs.p...
When to use attributes vs. when to use properties in python?
10,967,849
7
2012-06-10T10:08:24Z
10,967,855
15
2012-06-10T10:10:10Z
[ "python" ]
Just a quick question, I'm having a little difficulty understanding where to use properties vs. where use to plain old attributes. The distinction to me is a bit blurry. Any resources on the subject would be superb, thank you!
Properties are more flexible than attributes, since you can define functions that describe what is supposed to happen when setting, getting or deleting them. If you don't need this additional flexibility, use attributes – they are easier to declare and faster. In languages like Java, it is usually recommended to *al...
When to use attributes vs. when to use properties in python?
10,967,849
7
2012-06-10T10:08:24Z
10,967,861
13
2012-06-10T10:11:24Z
[ "python" ]
Just a quick question, I'm having a little difficulty understanding where to use properties vs. where use to plain old attributes. The distinction to me is a bit blurry. Any resources on the subject would be superb, thank you!
The point is that the syntax is interchangeable. Always start with attributes. If you find you need additional calculations when accessing an attribute, replace it with a property.
How to import python module from .so file?
10,968,309
10
2012-06-10T11:32:20Z
13,466,708
9
2012-11-20T04:42:29Z
[ "c++", "python", "boost-python" ]
``` [me@hostname python]$ cat hello_world.cc #include <string> #include <Python.h> #include <boost/python.hpp> namespace { std::string greet() { return "Helloworld"; } } using namespace boost::python; BOOST_PYTHON_MODULE(hello_world) { def("greet",greet); } [me@hostnmae python]$ g++ -c -fPIC hello_world.cc -I/p...
take that 'hello\_world.so' file and and make new python file (in the same dir) named as 'hello\_world.py'. Put the below code in it.. . ``` def __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__,'hello_world.so') _...
What is the Google Appengine Ndb GQL query max limit?
10,968,439
4
2012-06-10T11:51:59Z
10,969,575
7
2012-06-10T14:39:09Z
[ "python", "google-app-engine", "gql", "app-engine-ndb" ]
I am looking around in order to get an answer what is the max limit of results I can have from a GQL query on Ndb on Google AppEngine. I am using an implementation with cursors but it will be much faster if I retrieve them all at once.
Basically you don't have the old limit of 1000 entities per query anymore, but consider using a reasonable limit, because you can hit the time out error and it's better to get them in batches so users won't wait during load time.
What is the Google Appengine Ndb GQL query max limit?
10,968,439
4
2012-06-10T11:51:59Z
10,974,037
8
2012-06-11T02:42:53Z
[ "python", "google-app-engine", "gql", "app-engine-ndb" ]
I am looking around in order to get an answer what is the max limit of results I can have from a GQL query on Ndb on Google AppEngine. I am using an implementation with cursors but it will be much faster if I retrieve them all at once.
This depends on lots of things like the size of the entities and the number of values that need to look up in the index, so it's best to benchmark it for your specific application. Also beware that if you find that on a sunny day it takes e.g. 10 seconds to load all your items, that probably means that some small fract...
pymongo connection pooling and client requests
10,968,489
13
2012-06-10T12:01:37Z
11,009,036
7
2012-06-13T06:01:35Z
[ "python", "pymongo" ]
I know `pymongo` is thread safe and has an inbuilt connection pool. In a web app that I am working on, I am creating a new connection instance on every request. My understanding is that since `pymongo` manages the connection pool, it isn't wrong approach to create a new connection on each request, as at the end of th...
The "wrong approach" depends upon the architecture of your application. With pymongo being thread-safe and automatic connection pooling, the actual use of a single shared connection, or multiple connections, is going to "work". But the results will depend on what you expect the behavior to be. The documentation comment...
How do I change the scale of imshow in matplotlib without stretching the image?
10,969,113
5
2012-06-10T13:31:09Z
10,970,122
8
2012-06-10T15:56:09Z
[ "python", "matplotlib" ]
I wanted to plot using imshow in a manner similar to the second example here <http://www.scipy.org/Plotting_Tutorial> but to redefine the scale for the axis. I'd also like the image to stay still while I do this! The code from the example: ``` from scipy import * from pylab import * # Creating the grid of coordinate...
A `help(imshow)` will find the `aspect` argument, which after a bit of experimentation seems to give what you want (a square image of the spiral but with x scale from -4 to 4 and y from -1 to 1) when used like this: ``` imshow(z, origin='lower', extent=[-4,4,-1,1], aspect=4) ``` But now your `plot` is still from -1 t...
OpenCV - Reading a 16 bit grayscale image
10,969,585
6
2012-06-10T14:41:03Z
10,970,461
9
2012-06-10T16:50:19Z
[ "python", "opencv" ]
I'm trying to read a 16 bit grayscale image using OpenCV 2.4 in Python, but it seems to be loading it as 8 bit. I'm doing: ``` im = cv2.imread(path,0) print im [[25 25 28 ..., 0 0 0] [ 0 0 0 ..., 0 0 0] [ 0 0 0 ..., 0 0 0] ..., ``` How do I get it as 16 bit?
Figured it out. In case anyone else runs into this problem: ``` im = cv2.imread(path,-1) ``` Setting the flag to 0, to load as grayscale seems to default to 8 bit. Setting to -1 loads the image "as is".
MongoDB: Why does update() return null even when successful?
10,970,149
2
2012-06-10T15:59:31Z
10,970,233
10
2012-06-10T16:14:50Z
[ "python", "database", "mongodb", "pymongo" ]
I'm using this code to insert (or update if already existing) a new user to the databse: ``` emailAddress = self.request.params.get('emailaddress') googleRefreshToken = self.request.params.get('googlerefreshtoken') # upsert new user postData = {"emailAddress" : emailAddress, "googleRefreshToken...
As described in the [docs](http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update), if you include `safe=True` in your parameters to `update`, the response to `lastError` is returned, otherwise it returns `None`. If you want the `_id` of the document updated, you'll eithe...
Matplotlib: no effect of set_data in imshow for the plot
10,970,492
6
2012-06-10T16:54:41Z
12,470,959
9
2012-09-18T05:36:39Z
[ "python", "matplotlib" ]
I have a strange error which I can't fix without your help. After I set an image with `imshow` in matplotlib it stays the same all the time even if I change it with the method `set_data`. Just take a look on this example: ``` import numpy as np from matplotlib import pyplot as plt def newevent(event): haha[1,1] ...
The problem is because you have not updated the pixel scaling after the first call. When you instantiate `imshow`, it sets `vmin` and `vmax` from the initial data, and never touches it again. In your code, it sets both `vmin` and `vmax` to 0, since your data, `haha = zeros((2,2))`, is zero everywhere. Your new event ...
Using tweepy to access Twitter's Streaming API
10,970,550
4
2012-06-10T17:02:37Z
11,075,678
9
2012-06-17T23:43:46Z
[ "python", "twitter", "tweepy" ]
I'm currently having trouble getting example code for using tweepy to access Twitter's Streaming API to run correctly (err...or at least how I expect it to run). I'm using a recent clone of tweepy from GitHub (labeled version 1.9) and Python 2.7.1. I've tried example code from three sources, in each case using "twitte...
I ran into this as well and fixed it on my local checkout by changing line 160 in streaming.py to ``` if delimited_string.strip().isdigit(): ``` This seems to be a known issue/bug in Tweepy - should have checked the issues list before doing all that debugging :) - <https://github.com/tweepy/tweepy/pull/173> <https:/...
Backporting Python 3 open(encoding="utf-8") to Python 2
10,971,033
58
2012-06-10T18:03:29Z
10,971,047
30
2012-06-10T18:04:28Z
[ "python", "python-3.x", "py2to3" ]
I have a Python codebase, built for Python 3, which uses Python 3 style open() with encoding parameter: <https://github.com/miohtama/vvv/blob/master/vvv/textlineplugin.py#L47> ``` with open(fname, "rt", encoding="utf-8") as f: ``` Now I'd like to backport this code to Python 2.x, so that I would have a codebase ...
I think ``` from io import open ``` should do.
Backporting Python 3 open(encoding="utf-8") to Python 2
10,971,033
58
2012-06-10T18:03:29Z
10,975,371
74
2012-06-11T06:32:41Z
[ "python", "python-3.x", "py2to3" ]
I have a Python codebase, built for Python 3, which uses Python 3 style open() with encoding parameter: <https://github.com/miohtama/vvv/blob/master/vvv/textlineplugin.py#L47> ``` with open(fname, "rt", encoding="utf-8") as f: ``` Now I'd like to backport this code to Python 2.x, so that I would have a codebase ...
### 1. To get an encoding parameter in Python 2: If you only need to support Python 2.6 and 2.7 you can use [`io.open`](https://docs.python.org/2/library/io.html#io.open) instead of `open`. `io` is the new io subsystem for Python 3, and it exists in Python 2,6 ans 2.7 as well. Please be aware that in Python 2.6 (as we...
shape-preserving piecewise cubic interpolation for 3D curve in python
10,971,359
5
2012-06-10T18:43:21Z
10,972,865
9
2012-06-10T22:31:55Z
[ "python", "numpy", "scipy", "curve-fitting" ]
I have a curve in 3D space. I want to use a shape-preserving piecewise cubic interpolation on it similar to pchip in matlab. I researched functions provided in scipy.interpolate, e.g. interp2d, but the functions work for some curve structures and not the data points I have. Any ideas of how to do it? Here are the data...
You probably want to use [splprep() and splev()](http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.splev.html#scipy.interpolate.splev), like this (basic explaination in comments): ``` import scipy from scipy import interpolate import numpy as np #This is your data, but we're 'zooming' into just 5 ...
python cat (echo) equivalent for stdin
10,971,404
2
2012-06-10T18:47:41Z
10,971,516
8
2012-06-10T19:02:53Z
[ "python", "stdin" ]
I thought this program will echo my console input line by line: ``` import os, sys for line in sys.stdin: print line ``` Unfortunately it waits for EOF (ctrl + D) and then it produces output. How should I modify my program to get output line by line?
Python 2.x: ``` for line in iter(sys.stdin.readline, ''): print line, ``` Python 3.x: ``` for line in iter(sys.stdin.readline, ''): print(line, end='') ``` See the documentation on [`iter()`](http://docs.python.org/library/functions.html#iter) with two arguments, it actually has reading from a file like thi...
SQLAlchemy declarative extension vs. elixir
10,971,454
5
2012-06-10T18:54:08Z
15,299,015
11
2013-03-08T16:42:31Z
[ "python", "sqlalchemy", "python-elixir" ]
I am planning to use SQLAlchemy in one of my projects and i am very interested in declarative syntax of tables. I was told to use the [Elixir Declarative Layer](http://elixir.ematia.de/trac/wiki) for that, at the same time SQLAlchemy has its built-in [declarative extension](http://docs.sqlalchemy.org/en/latest/orm/ext...
Elixir exists because SQLA Declarative didn't. Now that we have SQLAlchemy declarative, you probably don't need Elixir unless there's a specific way it does things that you prefer. Just be aware that Elixir is a dead project, and you will be stuck with an older version of SQLAlchemy.
pandas: combine two columns in a DataFrame
10,972,410
14
2012-06-10T21:12:43Z
10,972,557
14
2012-06-10T21:38:40Z
[ "python", "dataframe", "pandas" ]
I have a pandas DataFrame that has multiple columns in it: ``` Index: 239897 entries, 2012-05-11 15:20:00 to 2012-06-02 23:44:51 Data columns: foo 11516 non-null values bar 228381 non-null values Time_UTC 239897 non-null values dtstamp 239897 non-null ...
Try this: ``` pandas.concat([df['foo'].dropna(), df['bar'].dropna()]).reindex_like(df) ``` If you want that data to become the new column `bar`, just assign the result to `df['bar']`.
pandas: combine two columns in a DataFrame
10,972,410
14
2012-06-10T21:12:43Z
23,787,861
12
2014-05-21T15:38:41Z
[ "python", "dataframe", "pandas" ]
I have a pandas DataFrame that has multiple columns in it: ``` Index: 239897 entries, 2012-05-11 15:20:00 to 2012-06-02 23:44:51 Data columns: foo 11516 non-null values bar 228381 non-null values Time_UTC 239897 non-null values dtstamp 239897 non-null ...
you can use directly fillna and assigning the result to the column 'bar' ``` df['bar'].fillna(df['foo'], inplace=True) del df['foo'] ``` general example: ``` import pandas as pd #creating the table with two missing values df1 = pd.DataFrame({'a':[1,2],'b':[3,4]}, index = [1,2]) df2 = pd.DataFrame({'b':[5,6]}, index ...
How can I access BPY in standard python console? BPY is the Blender-python -thing
10,972,637
7
2012-06-10T21:53:56Z
11,102,681
10
2012-06-19T14:03:49Z
[ "python", "blender" ]
The author [here](http://blip.tv/pycon-us-videos-2009-2010-2011/pycon-2011-using-blender-s-new-bpy-python-api-4898905) in point 17.20-17.50 mentions that you can access BPY with the standard Python interpreter in the future. It is already 1 year old so how can I access the BPY with the standard python console? > **Tri...
Based on [these instructions](http://wiki.blender.org/index.php/User%3aIdeasman42/BlenderAsPyModule): Obtain the blender source code: ``` cd ~/src # or what you prefer git clone http://git.blender.org/blender.git cd blender git submodule update --init --recursive git submodule foreach git checkout master git submodu...
How do I read one and only one byte from a binary file at a specified position?
10,972,827
3
2012-06-10T22:26:00Z
10,972,846
7
2012-06-10T22:28:56Z
[ "python", "byte", "binary-data", "binaryfiles" ]
I am wondering if it is possibly to read one byte at one given position at a time in python. I know about `file.read(`*`any number`*`)`, but I want something that returns the byte I specify and ONLY the byte I specify. If I write: `file.read(10)`, it reads the first 10 bytes of the file. How do I say *read byte 10 and...
Using seek and read, as show below should allow you to read one byte at a given position: ``` f.seek(10) f.read(1) ```
Python Logging (function name, file name, line number) using a single file
10,973,362
37
2012-06-11T00:07:12Z
10,974,508
16
2012-06-11T04:29:29Z
[ "python", "logging" ]
I am trying to learn how an application works. And for this I am inserting debug commands as the first line of each function's body with the goal of logging the function's name as well as the line number (within the code) where I send a message to the log output. Finally, since this application comprises of many files,...
You have a few marginally related questions here. I'll start with the easiest: (3). Using `logging` you can aggregate all calls to a single log file or other output target: they will be in the order they occurred in the process. Next up: (2). `locals()` provides a dict of the current scope. Thus, in a method that has...
Python Logging (function name, file name, line number) using a single file
10,973,362
37
2012-06-11T00:07:12Z
20,112,491
135
2013-11-21T04:28:35Z
[ "python", "logging" ]
I am trying to learn how an application works. And for this I am inserting debug commands as the first line of each function's body with the goal of logging the function's name as well as the line number (within the code) where I send a message to the log output. Finally, since this application comprises of many files,...
The correct answer for this is to use the already provided [`funcName`](https://docs.python.org/2/library/logging.html#logrecord-attributes) variable ``` import logging logger = logging.getLogger('root') FORMAT = "[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s" logging.basicConfig(format=FORMAT) logger.setL...
A more "pythonic" approach to "check for None and deal with it"
10,973,427
3
2012-06-11T00:20:01Z
10,973,462
7
2012-06-11T00:26:19Z
[ "string", "coding-style", "python" ]
I have a `list` of `dict` with keys `['name','content','summary',...]`. All the values are strings. But some values are `None`. I need to remove all the new lines in `content`, `summary` and some other keys. So, I do this: ``` ... ... for item in item_list: name = item['name'] content = item['content'] if ...
The code feels unwieldy to you, but part of the reason is because you are repeating yourself. This is better: ``` def remove_newlines(text): if text is not None: return text.replace('\n', '') for item in item_list: name = item['name'] content = remove_newlines(item['content']) summary = remove...
Convert JSON array to Python list
10,973,614
24
2012-06-11T01:03:22Z
10,973,638
40
2012-06-11T01:09:18Z
[ "python", "json", "list" ]
``` import json array = '{"fruits": ["apple", "banana", "orange"]}' data = json.loads(array) ``` That is my JSON array, but I would want to convert all the values in the fruits string to a Python list. What would be the correct way of doing this?
``` import json array = '{"fruits": ["apple", "banana", "orange"]}' data = json.loads(array) print data['fruits'] # the print displays: # [u'apple', u'banana', u'orange'] ``` You had everything you needed. `data` will be a dict, and `data['fruits']` will be a list
Convert JSON array to Python list
10,973,614
24
2012-06-11T01:03:22Z
10,973,648
7
2012-06-11T01:10:56Z
[ "python", "json", "list" ]
``` import json array = '{"fruits": ["apple", "banana", "orange"]}' data = json.loads(array) ``` That is my JSON array, but I would want to convert all the values in the fruits string to a Python list. What would be the correct way of doing this?
[Tested on Ideone.](http://ideone.com/8qE6N) ``` import json array = '{"fruits": ["apple", "banana", "orange"]}' data = json.loads(array) fruits_list = data['fruits'] print fruits_list ```
Python initialization
10,973,764
5
2012-06-11T01:38:52Z
10,973,815
9
2012-06-11T01:51:36Z
[ "python", "class", "init" ]
I have this code: ``` def __init__(self, a, b, c, d...): self.a = a self.b = b etc ``` I'm thinking of replacing it with: ``` def __init__(self, a, b, c, d...): args=locals() for key in args: self.__dict__[key] = args[key] ``` Is this a bad idea? Are there any better ways to do this?
From the [Zen of Python](http://www.python.org/dev/peps/pep-0020/): **Simple is better than complex.** and **Readability counts.** The explicit assignments are much more readable and simpler than using magic to set the values.
Understanding the map function
10,973,766
91
2012-06-11T01:39:42Z
10,973,804
38
2012-06-11T01:49:50Z
[ "python", "map-function" ]
``` map(function, iterable, ...) ``` Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be ex...
`map` doesn't relate to a Cartesian product at all, although I imagine someone well versed in functional programming could come up with some impossible to understand way of generating a one using `map`. `map` in Python 3 is equivalent to this: ``` def map(func, iterable): for i in iterable: yield func(i) ...
Understanding the map function
10,973,766
91
2012-06-11T01:39:42Z
10,973,806
12
2012-06-11T01:50:01Z
[ "python", "map-function" ]
``` map(function, iterable, ...) ``` Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be ex...
`map` creates a new list by applying a function to every element of the source: ``` xs = [1, 2, 3] # all of those are equivalent — the output is [2, 4, 6] # 1. map ys = map(lambda x: x * 2, xs) # 2. list comprehension ys = [x * 2 for x in xs] # 3. explicit loop ys = [] for x in xs: ys.append(x * 2) ``` n-ary `...
Understanding the map function
10,973,766
91
2012-06-11T01:39:42Z
10,973,817
130
2012-06-11T01:51:42Z
[ "python", "map-function" ]
``` map(function, iterable, ...) ``` Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be ex...
`map` isn't particularly pythonic. I would recommend using list comprehensions instead: ``` map(f, iterable) ``` is basically equivalent to: ``` [f(x) for x in iterable] ``` `map` on its own can't do a Cartesian product, because the length of its output list is always the same as its input list. You can trivially d...
Understanding the map function
10,973,766
91
2012-06-11T01:39:42Z
10,973,829
12
2012-06-11T01:55:14Z
[ "python", "map-function" ]
``` map(function, iterable, ...) ``` Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be ex...
Simplifying a bit, you can imagine `map()` doing something like this: ``` def mymap(func, lst): result = [] for e in lst: result.append(func(e)) return result ``` As you can see, it takes a function and a list, and returns a new list with the result of applying the function to each of the elements...
Does a library for prime-related functions exist for Python?
10,974,805
9
2012-06-11T05:22:29Z
10,974,890
8
2012-06-11T05:34:33Z
[ "python", "primes" ]
I've just implemented the [Miller-Rabin-Test](http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test) and a simple function for factorizing numbers. Both could be done better and at least the Miller-Rabin-Test is well-known. So could you please tell me if a Python-Library, that implements such common prime f...
[gmpy2](http://code.google.com/p/gmpy/) supports a variety of pseudoprime tests. The Miller-Rabin test is available as gmpy2.is\_strong\_prp(). gmpy2 does not have any factorization code yet. Disclaimer: I'm the maintainer of gmpy2. The primality tests are based on code from <http://sourceforge.net/projects/mpzprp/fi...
python split string based on regular expression
10,974,932
51
2012-06-11T05:40:39Z
10,974,956
11
2012-06-11T05:44:17Z
[ "python", "regex" ]
I have output of a command in tabular form. I'm parsing this output from result file and storing it in a string. Each element in 1 row is seperated by one or more space. So I'm using regular expression to match 1 or more spaces and split it, but python is inserting a space between every element: ``` >>> str1="a b ...
The `str.split` method will automatically remove all white space between items: ``` >>> str1 = "a b c d" >>> str1.split() ['a', 'b', 'c', 'd'] ``` Docs are here: <http://docs.python.org/library/stdtypes.html#str.split>
python split string based on regular expression
10,974,932
51
2012-06-11T05:40:39Z
10,974,957
58
2012-06-11T05:44:21Z
[ "python", "regex" ]
I have output of a command in tabular form. I'm parsing this output from result file and storing it in a string. Each element in 1 row is seperated by one or more space. So I'm using regular expression to match 1 or more spaces and split it, but python is inserting a space between every element: ``` >>> str1="a b ...
By using `(`,`)`, you are capturing the group, if you simply remove them you will not have this problem. ``` >>> str1 = "a b c d" >>> re.split(" +", str1) ['a', 'b', 'c', 'd'] ``` However there is no need for regex, `str.split` without any delimiter specified will split this by whitespace for you. This wo...
Is there an easy way to find the runtime environment in Pyramid
10,975,156
5
2012-06-11T06:10:13Z
10,975,487
14
2012-06-11T06:43:52Z
[ "python", "pyramid" ]
In pyramid, I need to render my templates according to different runtime environments -- enable google analytics, use minified code, etc. (when in production). Is there an easy way to find out the current environment -- perhaps an existing flag to find out which ini file was used?
Pyramid INI files can hold [arbitrary configuration entries](http://docs.pylonsproject.org/projects/pyramid/en/1.3-branch/narr/environment.html#adding-a-custom-setting), so why not include a flag in your files that distinguishes between production and development deployments? I'd do it like this; in your production .i...
Make reverse diagonals white in heatmap
10,975,402
9
2012-06-11T06:35:44Z
10,976,306
8
2012-06-11T07:57:56Z
[ "python", "matplotlib", "pyqt", "pyqt4" ]
I'm trying to do something as seen on the image is given below, ![enter image description here](http://i.stack.imgur.com/fmMC6.png) Just setting reverse diagonals white color is left. I couldn't set them as white. The chart takes integer values and I don't know what integer value is corresponding of white color. Than...
You can make your own colormap, or adjust an existing one :) ![enter image description here](http://i.stack.imgur.com/EPAN5.png) Here's the code for the above plot, with explainations in the comments: ``` import matplotlib from pylab import * import numpy as np #Create test data with zero valued diagonal: data = np...
Why Logging is not working on django website?
10,975,798
4
2012-06-11T07:11:12Z
10,976,225
9
2012-06-11T07:50:30Z
[ "python", "django" ]
This is what i tried . In my view.py file , ``` import logging logger = logging.getLogger("mylog") logging.basicConfig(format='%(name)s:%(levelname)s:%(message)s',level=logging.INFO,datefmt='%d/%m/%y %I:%M:%S') ``` Then inside a function , ``` logger.debug("this is an error") logger.warning("This is a warning") prin...
Try adding this to handlers: ``` 'console':{ 'level':'DEBUG', 'class':'logging.StreamHandler', 'formatter': 'simple' } ``` and in loggers: ``` 'django': { 'handlers':['console'], 'propagate': True, 'level':'INFO', }, ``` The log level co...
More pythonic way to find first two greatest value in a list in python
10,976,081
6
2012-06-11T07:37:06Z
10,976,110
16
2012-06-11T07:39:56Z
[ "python" ]
These days I design some algorithms in python, but find first two greatest value in python is too ugly and inefficient. How to implement it in a efficient or a pythonic way?
Most Pythonic way is to use [`nlargest`](http://docs.python.org/library/heapq.html#heapq.nlargest): ``` import heapq values = heapq.nlargest(2, my_list) ```
Concurrent requests in Appengine Python
10,977,143
6
2012-06-11T09:08:22Z
11,006,155
8
2012-06-12T23:12:10Z
[ "python", "performance", "google-app-engine", "concurrency", "python-2.7" ]
Official appengine documentation says that if we set threadsafe property to true in app.yaml then appengine will server concurrent requests. Official link: <https://developers.google.com/appengine/docs/python/python27/newin27#Concurrent_Requests> * Does it mean application will be faster (than 2.5) if we have threads...
You still only have one thread per request - you can't spawn. With threadsafe off, Appengine will only route one request to an instance. So if the number of requests per second times the time to handle a request approaches one, Appengine will spin up a new instance to handle them. This cost money. With threadsafe on, ...
Change matplotlib.pyplot text() object properties
10,978,440
3
2012-06-11T10:31:32Z
10,979,853
7
2012-06-11T12:10:54Z
[ "python", "animation", "plot", "matplotlib" ]
I have a `matplotlib.pyplot` graph that updates in a loop to create an animation, using this kind of code that I got from [another answer](http://stackoverflow.com/a/10896688/711017): ``` import matplotlib.pyplot as plt fig, ax = plt.subplots() x = [1, 2, 3, 4] #x-coordinates y = [5, 6, 7, 8] #y-coordinates f...
Similar as `set_data` you can use `set_text` (see here for the documentation: <http://matplotlib.sourceforge.net/api/artist_api.html#matplotlib.text.Text.set_text>). So first ``` text = plt.text(x, y, "Some text") ``` and then in the loop: ``` text.set_text("Some other text") ``` In your example it could look like...
Django Haystack - Show results without needing a search query?
10,978,695
8
2012-06-11T10:49:35Z
24,200,522
10
2014-06-13T08:04:40Z
[ "python", "django", "search", "solr", "django-haystack" ]
I would like to display all results which match selected facets even though a search query has not been inserted. Similar to how some shop applications work e.g. Amazon `e.g. Show all products which are "blue" and between $10-$100.` Haystack does not return any values if a search query is not specified. Any ideas ho...
If anyone is still looking, there's a simple solution suggested in haystack code: <https://github.com/toastdriven/django-haystack/blob/master/haystack/forms.py#L34> ``` class SearchForm(forms.Form): def no_query_found(self): """ Determines the behavior when no query was found. By default, no results ...
no access to GetCaptureProperty or any similar function in python opencv
10,978,768
5
2012-06-11T10:55:33Z
10,979,030
7
2012-06-11T11:15:28Z
[ "python", "opencv" ]
I tried lot of combinations in opencv 2.3 and 2.4 to get frame count of a video, but without any result. It seems it simply isn't there. ``` stream = cv.VideoCapture(avsfilename) #stream.isOpened() returns True, everything's ok framecount = cv.GetCaptureProperty(stream, CV_CAP_PROP_FRAME_COUNT) #no framecount = cv.Get...
You've got to be a little careful of your `cv2` and `cv` imports, both of these work: ``` import cv2 import cv2.cv as cv #Using cv2: stream = cv2.VideoCapture(filename) print stream.get(cv.CV_CAP_PROP_FRAME_COUNT) #using cv: stream = cv.CaptureFromFile(filename) print cv.GetCaptureProperty(stream, cv.CV_CAP_PROP_FRA...
Safely create a file if and only if it does not exist with python
10,978,869
51
2012-06-11T11:03:11Z
10,979,569
54
2012-06-11T11:53:15Z
[ "python" ]
I wish to write to a file based on whether that file already exists or not, only writing if it doesn't already exist (in practice, I wish to keep trying files until I find one that doesn't exist). The following code shows a way in which a potentially attacker could insert a symlink, as suggested in [this post](http://...
**Edit**: See also [Dave Jones' answer](http://stackoverflow.com/a/18474773/220155): from Python 3.3, you can use the `x` flag to `open()` to provide this function. **Original answer below** Yes, but not using Python's standard `open()` call. You'll need to use [`os.open()`](http://docs.python.org/library/os.html#os....