title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
How to set file name in response
9,991,292
4
2012-04-03T10:18:22Z
9,992,943
14
2012-04-03T12:08:27Z
[ "python", "response", "pyramid" ]
I know about content-disposition but I read what it uses for email messages. And I want to know how I can set file name with content-type. ps I use Pyramid framework edit: Web site has button 'download' how to perform Response object for file name too, like ``` return Response(body=f.read(), content_type='application...
You need to set the filename parameter of the Content-Disposition header like so: ``` response.content_disposition = 'attachment; filename="my_filename.txt"' ```
django south migration, doesnt set default
9,991,708
8
2012-04-03T10:48:29Z
9,992,069
11
2012-04-03T11:10:43Z
[ "python", "django", "django-south" ]
I use south to migrate my django models. There is however a nasty bug in south. It doesn't set default values in Postgres Databases. Example: ``` created_at = models.DateTimeField(default = datetime.now) tag_id = models.PositiveIntegerField(default = 0) ``` South will add these 2 fields to database, but fail to set t...
This is not a bug, in South or elsewhere. I think you are confused about how default values work in Django generally. Django does not set default values in the database schema. It applies them directly in Python, when a new instance is created. You can verify this by doing `manage.py sqlall` and see that the generated...
django south migration, doesnt set default
9,991,708
8
2012-04-03T10:48:29Z
12,731,863
20
2012-10-04T16:40:35Z
[ "python", "django", "django-south" ]
I use south to migrate my django models. There is however a nasty bug in south. It doesn't set default values in Postgres Databases. Example: ``` created_at = models.DateTimeField(default = datetime.now) tag_id = models.PositiveIntegerField(default = 0) ``` South will add these 2 fields to database, but fail to set t...
If you are auto-generating your migrations using: ``` ./manage.py schemamigration app_name --auto ``` Then you need to make a small edit to the migration before you actually apply it. Go into the generated migration (should be called something like app\_name/migrations/000X\_\_auto\_add\_field\_foo.py) and look for t...
Linux - Linebreak in IPython
9,991,838
4
2012-04-03T10:56:17Z
17,945,103
13
2013-07-30T10:55:50Z
[ "python", "linux", "shell", "ipython", "line-breaks" ]
Hi I'm new to Linux and I really like the idea of writing and testing python code in a shell. But my problem is how can I do line breaks in IPython. Every time I use the (I think) "normal" shortcut shift+enter the code gets executed. Function keys are disabled and keyboard layout works fine on my laptop, what could be ...
I just came across a solution, posted by Kenneth Falck: [IPython newlines with ^V^J](https://coderwall.com/p/2bdenw) While editing a multiline code block use `Ctrl+V CTRL+J`
Match single quotes from python re
9,991,933
3
2012-04-03T11:02:06Z
9,992,022
7
2012-04-03T11:08:00Z
[ "python" ]
How to match the following i want all the names with in the single quotes ``` This hasn't been much that much of a twist and turn's to 'Tom','Harry' and u know who..yes its 'rock' ``` How to extract the name within the single quotes only ``` name = re.compile(r'^\'+\w+\'') ```
The following regex finds all single words enclosed in quotes: ``` In [6]: re.findall(r"'(\w+)'", s) Out[6]: ['Tom', 'Harry', 'rock'] ``` Here: * the `'` matches a single quote; * the `\w+` matches one or more word characters; * the `'` matches a single quote; * the parentheses form a *capture group*: they define th...
Python Literal r'\' Not Accepted
9,993,390
19
2012-04-03T12:35:21Z
9,993,458
12
2012-04-03T12:39:26Z
[ "python", "syntax", "syntax-error", "literals" ]
`r'\'` in Python does not work as expected. Instead of returning a string with one character (a backslash) in it, it raises a SyntaxError. `r"\"` does the same. This is rather cumbersome if you have a list of Windows paths like these: ``` paths = [ r'\bla\foo\bar', r'\bla\foo\bloh', r'\buff', ...
The backslash can be used to make a following quote not terminate the string: ``` >>> r'\'' "\\'" ``` So `r'foo\'` or `r'\'` are unterminated literals. ### Rationale Because you specifically asked for the reasoning behind this design decision, relevant aspects could be the following (although this is all based on s...
Python Literal r'\' Not Accepted
9,993,390
19
2012-04-03T12:35:21Z
9,993,474
27
2012-04-03T12:39:55Z
[ "python", "syntax", "syntax-error", "literals" ]
`r'\'` in Python does not work as expected. Instead of returning a string with one character (a backslash) in it, it raises a SyntaxError. `r"\"` does the same. This is rather cumbersome if you have a list of Windows paths like these: ``` paths = [ r'\bla\foo\bar', r'\bla\foo\bloh', r'\buff', ...
This is in accordance with the [documentation](http://docs.python.org/reference/lexical_analysis.html#string-literals): > When an `'r'` or `'R'` prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string. For example, the string literal `r"...
Django templates: overriding blocks of included children templates through an extended template
9,996,428
18
2012-04-03T15:23:22Z
20,220,005
18
2013-11-26T14:36:57Z
[ "python", "django", "django-templates", "django-inheritance" ]
I'm wondering if anyone knows how to deal with the following quirky template structure: ``` ### base.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> <head> <title> {% block title %} Title of the page {% endblock %} </title> </head> <body> <header> {% block header %} {% include ...
It seems to be little known that you can use the `with` keyword with the [`include`](https://docs.djangoproject.com/en/dev/ref/templates/builtins/#include) to pass variables into the context of an included template - you can use it to specify includes in the included template: ``` # base.html <html> <body> ...
Python subprocess wildcard usage
9,997,048
26
2012-04-03T15:58:43Z
9,997,093
28
2012-04-03T16:01:08Z
[ "python", "subprocess", "wildcard" ]
``` import os import subprocess proc = subprocess.Popen(['ls','*.bc'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out,err = proc.communicate() print out ``` This script should print all the files with .bc suffix however it returns an empty list. If I do ls \*.bc manually in the command line it works. Doing ['...
You need to supply `shell=True` to execute the command through a shell interpreter. If you do that however, you can no longer supply a list as the first argument, because the arguments will get quoted then. Instead, specify the raw commandline as you want it to be passed to the shell: ``` proc = subprocess.Popen('ls ...
Python subprocess wildcard usage
9,997,048
26
2012-04-03T15:58:43Z
9,997,339
24
2012-04-03T16:17:24Z
[ "python", "subprocess", "wildcard" ]
``` import os import subprocess proc = subprocess.Popen(['ls','*.bc'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out,err = proc.communicate() print out ``` This script should print all the files with .bc suffix however it returns an empty list. If I do ls \*.bc manually in the command line it works. Doing ['...
Expanding the `*` glob is part of the shell, but by default `subprocess` does *not* send your commands via a shell, so the command (first argument, `ls`) is executed, then a literal `*` is used as an argument. This is a good thing, see [the warning block in the "Frequently Used Arguments" section](https://docs.python....
Immutable dictionary, only use as a key for another dictionary
9,997,176
17
2012-04-03T16:06:17Z
9,997,296
32
2012-04-03T16:13:54Z
[ "python" ]
I had the need to implement a hashable dict so I could use a dictionary as a key for another dictionary. A few months ago I used this implementation: [Python hashable dicts](http://stackoverflow.com/questions/1151658/python-hashable-dicts) However I got a notice from a colleague saying 'it is not really immutable, th...
If you are only using it as a key for another `dict`, you could go for `frozenset(mutabledict.items())`. If you need to access the underlying mappings, you could then use that as the parameter to `dict`. ``` mutabledict = dict(zip('abc', range(3))) immutable = frozenset(mutabledict.items()) read_frozen = dict(immutabl...
Immutable dictionary, only use as a key for another dictionary
9,997,176
17
2012-04-03T16:06:17Z
9,997,519
19
2012-04-03T16:30:08Z
[ "python" ]
I had the need to implement a hashable dict so I could use a dictionary as a key for another dictionary. A few months ago I used this implementation: [Python hashable dicts](http://stackoverflow.com/questions/1151658/python-hashable-dicts) However I got a notice from a colleague saying 'it is not really immutable, th...
The *Mapping* abstract base class makes this easy to implement: ``` import collections class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __le...
Unexpected performance curve from CPython merge sort
9,997,692
12
2012-04-03T16:41:06Z
9,999,124
7
2012-04-03T18:24:25Z
[ "python", "sorting", "merge", "garbage-collection" ]
I have implemented a naive merge sorting algorithm in Python. Algorithm and test code is below: ``` import time import random import matplotlib.pyplot as plt import math from collections import deque def sort(unsorted): if len(unsorted) <= 1: return unsorted to_merge = deque(deque([elem]) for elem in ...
You are simply picking up the impact of other processes on your machine. You run your sort function 100 times for input size 1 and record the total time spent on this. Then you run it 100 times for input size 2, and record the total time spent. You continue doing so until you reach input size 1000. Let's say once in ...
How to create broken vertical bar graphs in matpltolib?
9,997,905
5
2012-04-03T16:58:02Z
9,998,811
7
2012-04-03T18:03:31Z
[ "python", "graph", "charts", "matplotlib" ]
I'd like to create a broken vertical bar graph in matplotlib. To give a better idea of the result I'm after, I put an example together with [Balsamiq](http://www.balsamiq.com/): ![enter image description here](http://i.stack.imgur.com/1P6K2.png) I've had a look at the matpltolib [docs](http://matplotlib.sourceforge....
It sounds like you have a few series of start datetimes and stop datetimes. In that case, just use `bar` to plot things, and tell matplotlib that the axes are dates. To get the times, you can exploit the fact that matplotlib's internal date format is a float where each integer corresponds to 0:00 of that day. Therefo...
Python leading underscore _variables
9,998,348
8
2012-04-03T17:28:38Z
9,998,375
13
2012-04-03T17:30:45Z
[ "python" ]
We know that in a class, functions starting with `__function__` do not get imported while using: ``` from module import * ``` Someone asked what is an `_variable`? I have never one. Do they exist? Is this a concept of variable which cannot be accessed using class object or something?
It is a naming convention for private variables. See 9.6, private variables: <http://docs.python.org/tutorial/classes.html#private-variables>
What happens when a connection pool is exhausted?
9,998,805
6
2012-04-03T18:03:07Z
9,999,411
8
2012-04-03T18:44:23Z
[ "python", "sqlalchemy" ]
I'm reading about SQLAlchemy's connection pooling, which has a default of 5 connections and will by default overflow to 10. If the number of cached connections is exceeded, what happens? Are subsequent requests queued until a free connection becomes available or will a new connection that doesn't enter the pool be cre...
You are reading about the QueuePool, which manages database connections for better performance. It does this by holding open idle connections, in case you want to reuse them later. The number of connections it will hold open is pool\_size=5 (default). If you open a sixth connection, one of the connections in the queue ...
Can i put a color changer in a loop?
9,999,010
2
2012-04-03T18:16:52Z
9,999,405
9
2012-04-03T18:44:05Z
[ "python", "colors", "numpy", "matplotlib" ]
So basically what i'm wondering, is at the bottom of my code when i plot the graph of my trials, is there a way to run a color generator through there? Or more explicitly put, could i make a list of warm colors, and put that into my plot function, where it runs through each color in a list as the loop runs through, and...
It sounds like you just want something like this? ``` import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np # Generate data... nx, nsteps = 100, 20 x = np.linspace(0, 1, nx) data = np.random.random((nx, nsteps)) - 0.5 data = data.cumsum(axis=0) data = data.cumsum(axis=1) # Plot cmap = mpl.cm.au...
if command in python
9,999,420
3
2012-04-03T18:45:05Z
9,999,449
15
2012-04-03T18:46:46Z
[ "python" ]
``` if "aa" or "bb" or "cc" or "dd" or "ee" or "ff" in attrs["show"]: self.xx = xxxx ``` I have a code like this, to check if attrs["show"] contains either of these strings, then assign some value to self.xx But is this "IF" command is correct? Because from my results, it seems like this if command is always true...
Try the following: ``` if any(s in attrs["show"] for s in ("aa", "bb", "cc", "dd", "ee", "ff")): self.xx = xxxx ``` Your current if statement will always evaluate to `True`, because instead of checking if each string is in `attrs["show"]` you are checking if `"aa"` is True, or if `"bb"` is True, and on and on. Si...
Project structure for python projects
9,999,618
8
2012-04-03T18:59:19Z
9,999,984
7
2012-04-03T19:24:38Z
[ "python", "maven" ]
Are there any tools which generate a project layout for python specific projects, much similar to what maven accomplishes with `mvn archetype:generate` for java projects.
It is the good news: you do not need any tool. You can organise your source code in any way you want. Let recap why we need tools in the java world: In java you want to generate directories upfront because the namespace system dictates that each class must live in one file in a directory structure that reflects that ...
How to specify multiple author(s) / email(s) in setup.py
9,999,829
33
2012-04-03T19:13:34Z
10,005,265
27
2012-04-04T05:10:01Z
[ "python", "pypi" ]
We wrote a small wrapper to a twitter app and published this information to <http://pypi.python.org>. But setup.py just contained a single field for specifying email / name of the author. How do I specify multiple contributors / email list, to the following fields since we would like this package to be listed under our...
As far as I know, `setuptools` doesn't support using a list of strings in order to specify multiple authors. Your best bet is to list the authors in a single string: ``` author='Foo Bar, Spam Eggs', author_email='foobar@baz.com, spameggs@joe.org', ``` I'm not sure if PyPI validates the `author_email` field, so you ma...
How does one include the server hostname in a django error email?
10,000,428
2
2012-04-03T19:58:36Z
10,001,744
7
2012-04-03T21:33:55Z
[ "python", "django" ]
The title pretty much sums up the question. I have a django based site load balanced across multiple servers. As much as all the servers should be identical, $#%& happens... It would be really useful if the error emails django sends included the hostname of the server. How would this be achieved? p.s. It's django 1.3 ...
You can use the [`SERVER_EMAIL`](https://docs.djangoproject.com/en/dev/ref/settings/#server-email) or [`EMAIL_SUBJECT_PREFIX`](https://docs.djangoproject.com/en/dev/ref/settings/#email-subject-prefix) setting. In your settings.py: ``` import socket SERVER_ADMIN = 'alerts+{0}@mydomain.com'.format(socket.gethostname(...
Type(3,) returns an integer instead of a tuple in python, why?
10,001,816
5
2012-04-03T21:39:28Z
10,001,861
13
2012-04-03T21:43:27Z
[ "python", "types", "tuples" ]
`type(3,)` returns the int type, while ``` t = 3, type(t) ``` returns the tuple type. Why?
Inside the parentheses that form the function call operator, the comma is *not* for building tuples, but for separating arguments. Thus, `type(3, )` is equivalent to `type(3)`. An additional comma at the end of the argument list is allowed by the grammar. You need an extra pair of parens to build a tuple: ``` >>> def ...
How to run a Python script portably without specifying its full path
10,002,291
4
2012-04-03T22:21:49Z
10,002,375
9
2012-04-03T22:28:56Z
[ "python", "windows", "shell", "posix" ]
Is there a portable way to run a python script from a shell without writing its full path? For example in Linux, I would like while in my home directory ``` cd ~ ``` to be able to run a python script called run.py that is in say, ~/long/path/to/run.py, but I want to run it by simply typing ``` python run.py ``` in...
If the directory containing `run.py` is on the module search path (for example, `PYTHONPATH` environment variable), you should be able to run it like this: ``` python -m run ``` Here is the documentation on the `-m` command line option: > **-m** `module-name` > Searches `sys.path` for the named module and runs the...
Python procedure to populate dictionary from data in 2 separate lists
10,003,751
5
2012-04-04T01:21:31Z
10,003,769
13
2012-04-04T01:24:13Z
[ "python", "dictionary" ]
I am trying to create an automated python procedure that uses two separate lists to create a dictionary and so far I am failing. I have two sorted lists where the nth item in the fist list corresponds to the nth item in the second list and I want to combine them into a dictionary. For example, a subset of the 2 lists ...
Use the `zip` and `dict` functions to construct a dictionary out of a list of tuples: ``` birth_years = dict(zip(name, year)) ``` And if you're curious, this would be how I would try to do it with a `for` loop: ``` birth_years = {} for index, n in enumerate(name): birth_years[n] = years[index] ``` I think I like...
How does Python distinguish callback function which is a member of a class?
10,003,833
20
2012-04-04T01:31:28Z
10,003,857
16
2012-04-04T01:34:33Z
[ "python" ]
Please look at the simple example: ``` class A: def __init__(self, flag): self.flag = flag def func(self): print self.flag a = A(1) b = A(2) callback_a = a.func callback_b = b.func callback_a() callback_b() ``` The result is: ``` 1 2 ``` It runs as expected. But I have a question. In C, the callback ...
In Python, the callback is not simply a reference to a member function. Instead, it is "bound" to the object that it refers to when it was created. So `a.func` creates a callable that is bound to `a`, and `b.func` creates a callable that is bound to `b`. Python only needs one implementation of `func()` in memory, but ...
How does Python distinguish callback function which is a member of a class?
10,003,833
20
2012-04-04T01:31:28Z
10,003,918
12
2012-04-04T01:42:59Z
[ "python" ]
Please look at the simple example: ``` class A: def __init__(self, flag): self.flag = flag def func(self): print self.flag a = A(1) b = A(2) callback_a = a.func callback_b = b.func callback_a() callback_b() ``` The result is: ``` 1 2 ``` It runs as expected. But I have a question. In C, the callback ...
Specific to CPython, there is only one copy of the function object. During instance creation, the class wraps the unbound functions in its namespace as bound methods. But they all wrap the same function. Here's your example expanded to show what's going on. ``` class A(object): def __init__(self, flag): self.fl...
HTTP server hangs while accepting packets
10,003,866
4
2012-04-04T01:35:27Z
10,259,265
8
2012-04-21T13:18:41Z
[ "python", "http" ]
I have written a simple http server to handle POST requests: ``` class MyHandler( BaseHTTPServer.BaseHTTPRequestHandler): def do_POST( self ): ctype, pdict = cgi.parse_header(self.headers.getheader('content-type')) postvars = {} try: if ctype == 'application/x-www-form-urlencoded'...
I completely rewrote my solution in order to fix two disadvantages: * It can treat timeout even if client has opened only a connection but did not start communicate. * If the client opens a connection, a new server process is forked. A slow client can not block other. It is based on your code as most as possible. It ...
What's the proper way to run some Python code asynchronously?
10,003,933
10
2012-04-04T01:44:07Z
10,003,949
9
2012-04-04T01:46:18Z
[ "python", "flask", "upstart" ]
I needed to send mail from my plain Flask app, so I thought the simplest way would be to send it using smtplib. But I had to do it asynchronously - you can't just insert a 3 second delay into the request - right? So I add the email to a queue (psql table), and send it from another program that reads this table and uses...
You should consider using [Celery](http://www.celeryproject.org/). It is very widely used in web frameworks for asynchronous processing and supports a lot of different backends like AMQP, databases etc.
What's the proper way to run some Python code asynchronously?
10,003,933
10
2012-04-04T01:44:07Z
10,004,192
9
2012-04-04T02:29:19Z
[ "python", "flask", "upstart" ]
I needed to send mail from my plain Flask app, so I thought the simplest way would be to send it using smtplib. But I had to do it asynchronously - you can't just insert a 3 second delay into the request - right? So I add the email to a queue (psql table), and send it from another program that reads this table and uses...
Try [Gevent](http://gevent.org). You can create Greenlet object for your long task. This greenlet is [green thread](http://en.wikipedia.org/wiki/Green_threads). ``` from gevent import monkey monkey.patch_all() import gevent from gevent import Greenlet class Task(Greenlet): def __init__(self, name): Gr...
How do I use my own loop with pyhook instead of pumpMessages()?
10,004,658
5
2012-04-04T03:47:33Z
14,249,096
10
2013-01-10T00:51:01Z
[ "python", "pyhook" ]
I'm trying to use pyhooks to detect mouse clicks anywhere on screen. The problem is that I can only get it to work with PumpMessages(). I'd like it operate inside of a while loop that I've constructed. Is there a way to accomplish this/why does it need pumpMessages? ``` def onclick(event): print 'Mouse click!' ...
Just for future reference, you can use pythoncom.PumpWaitingMessages() inside the while loop, since it does not lock the execution. Something like this: ``` while True: # your code here pythoncom.PumpWaitingMessages() ```
Python - Classes and OOP Basics
10,004,850
8
2012-04-04T04:16:44Z
10,005,173
29
2012-04-04T04:58:34Z
[ "python", "oop" ]
I do not fully understand classes. I have read the python documentation and several other tutorials. I get the basic gist of it but don't understand the nuance. For instance in my code here: ``` class whiteroom(): """ Pick a door: red, blue, green, or black. """ do = raw_input("> ") if "red" in do: ...
Functions are very different from classes. It looks like you took a function and just changed the `def` to `class`. I guess that *mostly* works in your case, but it's not how classes are supposed to go. Classes contain functions (methods) and data. For example, you have a ball: ``` class Ball(object): # __init__ ...
The Python "is" statement and tuples
10,004,987
11
2012-04-04T04:34:41Z
10,005,123
11
2012-04-04T04:52:03Z
[ "python", "comparison", "tuples" ]
Why is `() is ()` true, yet `(0,) is (0,)` is false? I thought they would be the same object. However, I'm apparently missing something.
`is` tests to see if both sides of the statement share the same memory address. It's basically a shorthand for `id(a) == id(b)` ``` >>> print id(()), id(()) 30085168 30085168 >>> print id((0,)), id((0,)) 38560624 38676432 >>> ``` As `()` happens fairly frequently, it is actually treated as a singleton by the Python I...
Counter variable for class
10,005,343
3
2012-04-04T05:22:46Z
10,005,420
7
2012-04-04T05:31:52Z
[ "python", "class-variables" ]
I am having problem getting this piece of code to run. The class is Student which has a IdCounter, and it is where the problem seems to be. (at line 8) ``` class Student: idCounter = 0 def __init__(self): self.gpa = 0 self.record = {} # Each time I create a new student, the idCounter in...
``` class Student: # A student ID counter idCounter = 0 def __init__(self): self.gpa = 0 self.record = {} # Each time I create a new student, the idCounter increment Student.idCounter += 1 self.name = 'Student {0}'.format(Student.idCounter) classRoster = [] # List of...
Retaining order while using Python's set difference
10,005,367
10
2012-04-04T05:25:20Z
10,005,465
9
2012-04-04T05:36:06Z
[ "python", "set", "order" ]
I'm doing a set difference operation in Python: ``` from sets import Set from mongokit import ObjectId x = [ObjectId("4f7aba8a43f1e51544000006"), ObjectId("4f7abaa043f1e51544000007"), ObjectId("4f7ac02543f1e51a44000001")] y = [ObjectId("4f7acde943f1e51fb6000003")] print list(Set(x).difference(Set(y))) ``` I'm getting...
Sets are unordered, so you will need to put the results back in the correct order after doing your set difference. Fortunately you already have the elements in the order you want, so this is easy. ``` diff = set(x) - set(y) result = [o for o in x if o in diff] ``` But this can be streamlined; you can do the differenc...
Retaining order while using Python's set difference
10,005,367
10
2012-04-04T05:25:20Z
10,006,674
15
2012-04-04T07:27:33Z
[ "python", "set", "order" ]
I'm doing a set difference operation in Python: ``` from sets import Set from mongokit import ObjectId x = [ObjectId("4f7aba8a43f1e51544000006"), ObjectId("4f7abaa043f1e51544000007"), ObjectId("4f7ac02543f1e51a44000001")] y = [ObjectId("4f7acde943f1e51fb6000003")] print list(Set(x).difference(Set(y))) ``` I'm getting...
It looks like you need an ordered set instead of a regular set. ``` >>> x = [ObjectId("4f7aba8a43f1e51544000006"), ObjectId("4f7abaa043f1e51544000007"), ObjectId("4f7ac02543f1e51a44000001")] >>> y = [ObjectId("4f7acde943f1e51fb6000003")] >>> print list(OrderedSet(x) - OrderedSet(y)) [ObjectId("4f7aba8a43f1e51544000006...
Python MySQL: Not showing inserted records
10,006,420
6
2012-04-04T07:07:23Z
10,006,473
15
2012-04-04T07:11:26Z
[ "python", "mysql", "insert" ]
I am using Python 2.7 with MySQLdb 32bit, alongside with MySQL 5.5.8 running local. I am driving myself crazy over this, I have never seen anything like it. Basically, I am inserting records into MySQL from Python via: ``` db=MySQLdb.connect(host="localhost",user="root", passwd="mypassword",db="python",port=3307) cu...
If your code works in the console but not otherwise, I believe you need to add the line ``` db.autocommit(True) ``` After you connect or you need to do `db.commit()` after your inserts.
Python string comparison similarity
10,006,938
3
2012-04-04T07:48:55Z
10,006,999
7
2012-04-04T07:54:38Z
[ "python" ]
I am trying to compare two lists of data which has some free text denoting the same object. example ``` List 1 ['abc LLC','xyz, LLC'] List 2 ['abc , LLC','xyz LLC'] ``` It is a simple example but the problem is there can be many changes like changes in case or adding some "." in between. Is there any python package t...
You could use an implementation of the [Levenshtein Distance](http://en.wikipedia.org/wiki/Levenshtein_distance) algorithm for non-precise string matching, for instance [this one from Wikibooks](http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Levenshtein_distance#Python). Another option would be to, for ...
matplotlib: Creating two (stacked) subplots with SHARED X axis but SEPARATE Y axis values
10,007,016
9
2012-04-04T07:55:44Z
10,011,077
9
2012-04-04T12:27:12Z
[ "python", "matplotlib" ]
I am using matplotlib 1.2.x and Python 2.6.5 on Ubuntu 10.0.4. I am trying to create a SINGLE plot that consists of a top plot and a bottom plot. The X axis is the date of the time series. The top plot contains a candlestick plot of the data, and the bottom plot should consist of a bar type plot - with its own Y axis ...
There seem to be a couple of problems with your code: 1. If you were using `figure.add_subplots` with the full signature of `subplot(nrows, ncols, plotNum)` it may have been more apparent that your first plot asking for 1 row and 1 column and the second plot was asking for 2 rows and 1 column. Hence your f...
Python - dealing with mixed-encoding files
10,009,753
13
2012-04-04T10:59:33Z
10,010,006
20
2012-04-04T11:16:44Z
[ "python", "unicode", "encoding", "utf-8", "windows-1252" ]
I have a file which is mostly UTF-8, but some Windows-1252 characters have also found there way in. I created a table to map from the Windows-1252 (cp1252) characters to their Unicode counterparts, and would like to use it to fix the mis-encoded characters, e.g. ``` cp1252_to_unicode = { "\x85": u'\u2026', # … ...
If you try to decode this sring as utf-8, as you already know, you will get an "UnicodeDecode" error, as these spurious cp1252 characters are invalid utf-8 - However, Python codecs allow you to register a [callback to handle encoding/decodin](http://docs.python.org/library/codecs.html#codecs.register_error)g errors, w...
Understanding parameter handling in a python memoization decorator
10,011,035
7
2012-04-04T12:24:15Z
10,011,128
9
2012-04-04T12:30:44Z
[ "python", "decorator", "memoization" ]
I have been using this excellent decorator for memoization, which I found on the web (shown here with the Fibonacci sequence as an example): ``` def memoize(f): cache= {} def memf(*x): if x not in cache: cache[x] = f(*x) return cache[x] return memf @memoize def fib(n): if n...
The decorator is called only once, immediately after the decorated function is first defined. Thus, these two techniques(using @wrap and bar = wrap(bar)) are the same: ``` >>> def wrap(f): ... print 'making arr' ... arr = [] ... def inner(): ... arr.append(2) ... print arr ... f() ....
python numpy arange unexpected results
10,011,302
12
2012-04-04T12:40:59Z
10,011,517
14
2012-04-04T12:52:47Z
[ "python", "numpy" ]
I am using the arange function to define my for loop iterations and getting unexpected results. ``` i = arange(7.8,8.4,0.05) print i ``` yeilds the following: ``` [ 7.8 7.85 7.9 7.95 8. 8.05 8.1 8.15 8.2 8.25 8.3 8.35 8.4 ] ``` yet using the stop value of 8.35 as follows ``` i = arange(7.8,8.35,0...
I'm guessing that you're seeing the effects of floating point rounding. `numpy.arange` does the same thing as python's `range`: It doesn't include the "endpoint". (e.g. `range(0, 4, 2)` will yield `[0,2]` instead of `[0,2,4]`) However, for floating point steps, the rounding errors are accumulate, and occasionally the...
python numpy arange unexpected results
10,011,302
12
2012-04-04T12:40:59Z
10,011,589
7
2012-04-04T12:57:30Z
[ "python", "numpy" ]
I am using the arange function to define my for loop iterations and getting unexpected results. ``` i = arange(7.8,8.4,0.05) print i ``` yeilds the following: ``` [ 7.8 7.85 7.9 7.95 8. 8.05 8.1 8.15 8.2 8.25 8.3 8.35 8.4 ] ``` yet using the stop value of 8.35 as follows ``` i = arange(7.8,8.35,0...
Perhaps it has to do with limitations on floating point numbers. Due to machine precision, it is not possible to store every conceivable value perfectly as a floating point. For example: ``` >>> 8.4 8.4000000000000004 >>> 8.35 8.3499999999999996 ``` So, 8.4 as a floating point is slightly greater than the actual valu...
How to get NaN when I divide by zero
10,011,707
27
2012-04-04T13:05:00Z
10,011,773
33
2012-04-04T13:09:33Z
[ "python" ]
When I do floating point division in Python, if I divide by zero, I get an exception: ``` >>> 1.0/0.0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: float division ``` I'd really like to get `NaN` or `Inf` instead (because the `NaN` or `Inf` will propagate through the rest...
The easiest way to get this behaviour is to use `numpy.float64` instead of Python default `float` type: ``` >>> import numpy >>> numpy.float64(1.0) / 0.0 inf ``` Of course this requires NumPy. You can use [`numpy.seterr()`](http://docs.scipy.org/doc/numpy-1.6.0/reference/generated/numpy.seterr.html) to fine-tune the ...
How to get NaN when I divide by zero
10,011,707
27
2012-04-04T13:05:00Z
10,011,830
13
2012-04-04T13:12:21Z
[ "python" ]
When I do floating point division in Python, if I divide by zero, I get an exception: ``` >>> 1.0/0.0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: float division ``` I'd really like to get `NaN` or `Inf` instead (because the `NaN` or `Inf` will propagate through the rest...
**Method 1:** ``` try: value = a/b except ZeroDivisionError: value = float('Inf') ``` **Method 2:** ``` if b != 0: value = a / b else: value = float('Inf') ``` But be aware that the value could as well be `-Inf`, so you should make a more distinctive test. Nevertheless, this above should give you th...
How to generate a "big" random number in Python?
10,012,534
9
2012-04-04T13:53:01Z
10,012,574
24
2012-04-04T13:55:05Z
[ "python", "random", "biginteger" ]
How can I generate a big (more than 64 bits) random integer in Python?
You can use [`random.getrandbits()`](http://docs.python.org//library/random.html?highlight=random.getrandbits#random.getrandbits): ``` >>> random.getrandbits(128) 117169677822943856980673695456521126221L ``` As states in the linked documentation, `random.randrange()` will also do the trick if `random.getrandbits()` i...
Python find min & max of two lists
10,012,788
6
2012-04-04T14:07:00Z
10,012,819
19
2012-04-04T14:08:48Z
[ "python", "list" ]
I have two lists such as: ``` l_one = [2,5,7,9,3] l_two = [4,6,9,11,4] ``` ...and I need to find the min and max value from both lists combined. That is, I want to generate a single min and a single max value. My question is - what is the most pythonic way to achieve this? Any help much appreciated.
Arguably the most readable way is ``` max(l_one + l_two) ``` or ``` min(l_one + l_two) ``` It will copy the lists, though, since `l_one + l_two` creates a new list. To avoid copying, you could do ``` max(max(l_one), max(l_two)) min(min(l_one), min(l_two)) ```
Python find min & max of two lists
10,012,788
6
2012-04-04T14:07:00Z
10,012,886
9
2012-04-04T14:12:23Z
[ "python", "list" ]
I have two lists such as: ``` l_one = [2,5,7,9,3] l_two = [4,6,9,11,4] ``` ...and I need to find the min and max value from both lists combined. That is, I want to generate a single min and a single max value. My question is - what is the most pythonic way to achieve this? Any help much appreciated.
Another way that avoids copying the lists ``` >>> l_one = [2,5,7,9,3] >>> l_two = [4,6,9,11,4] >>> >>> from itertools import chain >>> max(chain(l_one, l_two)) 11 >>> min(chain(l_one, l_two)) 2 ```
How you create a datetime index in pandas
10,015,284
2
2012-04-04T16:22:28Z
10,057,962
7
2012-04-07T20:11:27Z
[ "python", "numpy", "pandas" ]
How do I create an datetime index "foo" to use with raw data series. (Example would "as of" every 15 seconds 'foo' and and every 30 seconds 'foo2'.) If raw series can be inserted into a 'base' dataframe, I would like to use 'foo' to recast the dataframe. If wanted series to combine combine df "foo" and df "foo2", what...
It's very hard for me to understand what you're asking; an illustration of exactly what you're looking for, with example data, would help make things more clear. I think what you should do: `rng = DateRange(start, end, offset=datetools.Second(15)` to create the date range. To put data in a DataFrame indexed by that,...
Convert numpy array to tuple
10,016,352
42
2012-04-04T17:33:55Z
10,016,379
44
2012-04-04T17:35:41Z
[ "python", "numpy" ]
**Note:** This is asking for the reverse of the usual tuple-to-array conversion. I have to pass an argument to a (wrapped c++) function as a nested tuple. For example, the following works ``` X = MyFunction( ((2,2),(2,-2)) ) ``` whereas the following *do not* ``` X = MyFunction( numpy.array(((2,2),(2,-2))) ) X = My...
``` >>> arr = numpy.array(((2,2),(2,-2))) >>> tuple(map(tuple, arr)) ((2, 2), (2, -2)) ```
Convert numpy array to tuple
10,016,352
42
2012-04-04T17:33:55Z
10,016,613
12
2012-04-04T17:52:23Z
[ "python", "numpy" ]
**Note:** This is asking for the reverse of the usual tuple-to-array conversion. I have to pass an argument to a (wrapped c++) function as a nested tuple. For example, the following works ``` X = MyFunction( ((2,2),(2,-2)) ) ``` whereas the following *do not* ``` X = MyFunction( numpy.array(((2,2),(2,-2))) ) X = My...
Here's a function that'll do it: ``` def totuple(a): try: return tuple(totuple(i) for i in a) except TypeError: return a ``` And an example: ``` >>> array = numpy.array(((2,2),(2,-2))) >>> totuple(array) ((2, 2), (2, -2)) ```
Save Naive Bayes Trained Classifier in NLTK
10,017,086
32
2012-04-04T18:24:06Z
10,019,929
63
2012-04-04T22:05:23Z
[ "python", "machine-learning", "classification", "nltk", "bayesian" ]
I'm slightly confused in regard to how I save a trained classifier. As in, re-training a classifier each time I want to use it is obviously really bad and slow, how do I save it and the load it again when I need it? Code is below, thanks in advance for your help. I'm using Python with NLTK Naive Bayes Classifier. ``` ...
To save: ``` import pickle f = open('my_classifier.pickle', 'wb') pickle.dump(classifier, f) f.close() ``` To load later: ``` import pickle f = open('my_classifier.pickle', 'rb') classifier = pickle.load(f) f.close() ```
Removing a list of characters in string
10,017,147
188
2012-04-04T18:28:04Z
10,017,169
227
2012-04-04T18:29:58Z
[ "python", "string", "list", "replace" ]
I want to remove characters in a string in python: ``` string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')... ``` But I have many characters I have to remove. I thought about a list ``` list = [',', '!', '.', ';'...] ``` But how can I use the `list` to replace the characters in the `string`?
If you're using python2 and your inputs are strings (not unicodes), the absolutely best method is [`str.translate`](https://docs.python.org/2/library/stdtypes.html#str.translate): ``` >>> chars_to_remove = ['.', '!', '?'] >>> subj = 'A.B!C?' >>> subj.translate(None, ''.join(chars_to_remove)) 'ABC' ``` Otherwise, ther...
Removing a list of characters in string
10,017,147
188
2012-04-04T18:28:04Z
10,017,196
99
2012-04-04T18:31:22Z
[ "python", "string", "list", "replace" ]
I want to remove characters in a string in python: ``` string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')... ``` But I have many characters I have to remove. I thought about a list ``` list = [',', '!', '.', ';'...] ``` But how can I use the `list` to replace the characters in the `string`?
You can use [`str.translate()`](http://docs.python.org/2/library/stdtypes.html#str.translate): ``` s.translate(None, ",!.;") ``` Example: ``` >>> s = "asjo,fdjk;djaso,oio!kod.kjods;dkps" >>> s.translate(None, ",!.;") 'asjofdjkdjasooiokodkjodsdkps' ```
Removing a list of characters in string
10,017,147
188
2012-04-04T18:28:04Z
10,017,200
31
2012-04-04T18:31:32Z
[ "python", "string", "list", "replace" ]
I want to remove characters in a string in python: ``` string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')... ``` But I have many characters I have to remove. I thought about a list ``` list = [',', '!', '.', ';'...] ``` But how can I use the `list` to replace the characters in the `string`?
You can use the [translate](http://docs.python.org/library/string.html#string.translate) method. ``` s.translate(None, '!.;,') ```
Removing a list of characters in string
10,017,147
188
2012-04-04T18:28:04Z
10,017,460
8
2012-04-04T18:51:41Z
[ "python", "string", "list", "replace" ]
I want to remove characters in a string in python: ``` string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')... ``` But I have many characters I have to remove. I thought about a list ``` list = [',', '!', '.', ';'...] ``` But how can I use the `list` to replace the characters in the `string`?
Another approach using regex: ``` ''.join(re.split(r'[.;!?,]', s)) ```
Removing a list of characters in string
10,017,147
188
2012-04-04T18:28:04Z
10,017,485
13
2012-04-04T18:53:30Z
[ "python", "string", "list", "replace" ]
I want to remove characters in a string in python: ``` string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')... ``` But I have many characters I have to remove. I thought about a list ``` list = [',', '!', '.', ';'...] ``` But how can I use the `list` to replace the characters in the `string`?
``` ''.join(c for c in myString if not c in badTokens) ```
Matplotlib markers disappear when edgecolor = 'none'
10,017,876
14
2012-04-04T19:22:32Z
10,021,837
11
2012-04-05T02:20:20Z
[ "python", "matplotlib", "python-2.7", "markers" ]
I'm trying to make a scatter plot of some PCA data. I do some pretty typical code: ``` plt.plot(pca[:,0], pca[:,1], '.',ms=3, markerfacecolor = self.colors[k], markeredgecolor = 'none') ``` I want it to show just the marker face color with no outline. The problem is that the markers disappear completely ...
I think this is a bug that was fixed a few months ago: <https://github.com/matplotlib/matplotlib/pull/598> Regardless of how large you make the markers or if you use `marker='o'` instead of `'.'`, they'll be invisible if you use `markeredgecolor='none'`. As a workaround, you can just set the edge colors to the same a...
Unicode error when outputting python script output to file
10,018,271
16
2012-04-04T19:51:48Z
10,018,956
9
2012-04-04T20:44:09Z
[ "python", "unicode", "beautifulsoup" ]
This is the code: ``` print '"' + title.decode('utf-8', errors='ignore') + '",' \ ' "' + title.decode('utf-8', errors='ignore') + '", ' \ '"' + desc.decode('utf-8', errors='ignore') + '")' ``` title and desc are returned by Beautiful Soup 3 (*p[0].text* and *p[0].prettify*) and as far as I can figure out ...
You can use the codecs module to write unicode data to the file ``` import codecs file = codecs.open("out.txt", "w", "utf-8") file.write(something) ``` 'print' outputs to the standart output and if your console doesn't support utf-8 it can cause such error even if you pipe stdout to a file.
Accurate binary image classification
10,018,525
9
2012-04-04T20:10:40Z
10,019,099
11
2012-04-04T20:55:28Z
[ "python", "image-processing", "opencv", "ocr", "simplecv" ]
I'm trying to extract letters from a game board for a project. Currently, I can detect the game board, segment it into the individual squares and extract images of every square. The input I'm getting is like this (these are individual letters): ![enter image description here](http://i.stack.imgur.com/xd0fc.png)![ente...
I think this is necessarily some sort of Supervised Learning. You need to do some feature extraction on the images and then do your classification on the basis of the feature vector you've computed for each image. **Feature Extraction** On the first sight, that Feature Extraction part looks like a good scenario for [...
Python: find closest string (from a list) to another string
10,018,679
26
2012-04-04T20:22:33Z
10,018,734
37
2012-04-04T20:27:09Z
[ "python", "string", "algorithm", "list" ]
Let's say I have a `string` `"Hello"` and a list ``` words = ['hello', 'Hallo', 'hi', 'house', 'key', 'screen', 'hallo','question', 'Hallo', 'format'] ``` How can I find the `n words` that are the closest to `"Hello"` and present in the list `words` ? In this case, we would have `['hello', 'hallo', 'Hallo', 'hi', 'f...
Use [`difflib.get_close_matches`](http://docs.python.org/library/difflib.html#difflib.get_close_matches). ``` >>> words = ['hello', 'Hallo', 'hi', 'house', 'key', 'screen', 'hallo', 'question', 'format'] >>> difflib.get_close_matches('Hello', words) ['hello', 'Hallo', 'hallo'] ``` Please look at the documentation, be...
Python: find closest string (from a list) to another string
10,018,679
26
2012-04-04T20:22:33Z
10,020,219
7
2012-04-04T22:34:31Z
[ "python", "string", "algorithm", "list" ]
Let's say I have a `string` `"Hello"` and a list ``` words = ['hello', 'Hallo', 'hi', 'house', 'key', 'screen', 'hallo','question', 'Hallo', 'format'] ``` How can I find the `n words` that are the closest to `"Hello"` and present in the list `words` ? In this case, we would have `['hello', 'hallo', 'Hallo', 'hi', 'f...
There is an awesome article with a complete source code (21 lines) provided by Peter Norvig on spelling correction. <http://norvig.com/spell-correct.html> The idea is to build all possible edits of your word, ``` hello - helo - deletes hello - helol - transpose hello - hallo - replaces hello - heallo...
How use sql "like" in PyMongo?
10,018,730
15
2012-04-04T20:26:44Z
10,018,818
22
2012-04-04T20:34:09Z
[ "python", "mongodb", "nosql", "pymongo" ]
How use sql "like" in PyMongo? ``` >>> db.houses.find().count() 11616 >>> db.houses.find({"hid":u"16999"}).count() 1 >>> db.houses.find({"hid":u"/9/"}).count() 0 ``` The [documentation](http://www.mongodb.org/display/DOCS/SQL+to+Mongo+Mapping+Chart) says that sql "like" (`SELECT * FROM users WHERE name LIKE "%Joe%"`)...
pymongo doesn't support regex literals, you have to use the '$regex' predicate: ``` db.houses.find({"hid":{"$regex": u"9"}}) ```
How does the order of mixins affect the derived class?
10,018,757
21
2012-04-04T20:28:41Z
10,018,792
39
2012-04-04T20:32:35Z
[ "python", "django", "django-views", "django-class-based-views", "method-resolution-order" ]
Say, I have the following mixins that overlaps with each other by touching `dispatch()`: ``` class FooMixin(object): def dispatch(self, *args, **kwargs): # perform check A ... return super(FooMixin, self).dispatch(*args, **kwargs) class BarMixin(object): def dispatch(self, *args, **kwa...
The MRO is basically depth-first, left-to-right. See [Method Resolution Order (MRO) in new style Python classes](http://stackoverflow.com/questions/1848474/method-resolution-order-mro-in-new-style-python-classes) for some more info. You can look at the [`__mro__` attribute](http://docs.python.org/reference/datamodel.h...
Determining if a number evenly divides by 25, Python
10,018,937
5
2012-04-04T20:42:53Z
10,018,952
10
2012-04-04T20:44:02Z
[ "python", "math" ]
I'm trying to check if each number in a list is evenly divisible by 25 using Python. I'm not sure what is the right process. I want to do something like this: ``` n = [100, 101, 102, 125, 355, 275, 435, 134, 78, 550] for row in rows: if n / 25 == an evenly divisble number: row.STATUS = "Major" else: ...
Use the modulo operator to determine the division remainder: ``` if n % 25 == 0: ```
Determining if a number evenly divides by 25, Python
10,018,937
5
2012-04-04T20:42:53Z
10,018,958
15
2012-04-04T20:44:13Z
[ "python", "math" ]
I'm trying to check if each number in a list is evenly divisible by 25 using Python. I'm not sure what is the right process. I want to do something like this: ``` n = [100, 101, 102, 125, 355, 275, 435, 134, 78, 550] for row in rows: if n / 25 == an evenly divisble number: row.STATUS = "Major" else: ...
Use [the modulo operator](http://docs.python.org/reference/expressions.html#binary-arithmetic-operations): ``` for row in rows: if n % 25: row.STATUS = "Minor" else: row.STATUS = "Major" ``` or ``` for row in rows: row.STATUS = "Minor" if n % 25 else "Major" ``` `n % 25` means "Give me t...
Django: app with label XYZ could not be found. Are you sure your INSTALLED_APPS setting is correct?
10,019,393
5
2012-04-04T21:17:39Z
22,432,565
7
2014-03-16T03:22:11Z
[ "python", "django" ]
I'm trying to follow the Django tutorial (for v1.1) [here](https://docs.djangoproject.com/en/1.1/intro/tutorial01/). the problem that I'm running into is that it won't recognize my sample test app. For instance, I'm working in /home/user1234/rst . I can successfully run the server from there and create an app. However,...
Okay I had a very similar problem and this might seem dumb but I spent hours trying to solve it before I realized what I was doing wrong. What I did was put the app to the wrong location, instead of: ``` INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', ...
Python: is the "old" memory free'd when a variable is assigned new content?
10,019,442
3
2012-04-04T21:21:49Z
10,019,472
7
2012-04-04T21:24:52Z
[ "python", "memory-management", "garbage-collection" ]
If a variable is assigned any new content, will the memory allocated for the "old content" be "properly" free'd? For example, in the following script, will the memory for variable "a" as an array of zeros be free'd after "a" is assigned some new stuff ``` import numpy a = numpy.zeros(1000) a = a+1 ``` I would imaging...
Eventually, the old memory will be freed, though you cannot predict when this will happen. It is dependent on the Python implementation and many other factors. That said, for the example you gave and the CPython implementation, the old array should be garbage collected during the assignment. (Note that NumPy arrays a...
Usage of sys.stdout.flush() method
10,019,456
57
2012-04-04T21:22:57Z
10,019,596
46
2012-04-04T21:34:48Z
[ "python", "sys" ]
What does `sys.stdout.flush()` do?
Consider the following simple Python script: ``` import time import sys for i in range(5): print i, #sys.stdout.flush() time.sleep(1) ``` This is designed to print one number every second for five seconds, but if you run it as it is now (depending on your default system buffering) you may not see any out...
Usage of sys.stdout.flush() method
10,019,456
57
2012-04-04T21:22:57Z
10,019,605
68
2012-04-04T21:35:18Z
[ "python", "sys" ]
What does `sys.stdout.flush()` do?
Python's standard out is buffered (meaning that it collects some of the data "written" to standard out before it writes it to the terminal). Calling `sys.stdout.flush()` forces it to "flush" the buffer, meaning that it will write everything in the buffer to the terminal, even if normally it would wait before doing so. ...
Django mysql error
10,020,157
3
2012-04-04T22:27:33Z
10,020,341
10
2012-04-04T22:46:55Z
[ "python", "mysql", "django" ]
I'm using `mysql-python`. Here's my settings.py ``` import os, sys abspath = lambda *p: os.path.abspath(os.path.join(*p)) PROJECT_ROOT = abspath(os.path.dirname(__file__)) USERENA_MODULE_PATH = abspath(PROJECT_ROOT, '..') sys.path.insert(0, USERENA_MODULE_PATH) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ('...
Replacing 'ENGINE': 'mysql' with django.db.backends.mysql` is correct. Now, you have to change from: ``` DATABASES = { 'default': { 'ENGINE': 'mysql', 'NAME': 'test', 'DATABASE_USER': 'root', 'DATABASE_PASSWORD': 'pass', } } ``` to: ``` DATABASES = { 'default': { ...
Make Python stop emitting a carriage return when writing newlines to sys.stdout
10,020,325
8
2012-04-04T22:45:21Z
10,020,404
10
2012-04-04T22:53:46Z
[ "python", "windows", "python-2.7" ]
I'm on Windows and Python is (very effectively) preventing me from sending a stand-alone `'\n'` character to STDOUT. For example, the following will output `foo\r\nvar`: ``` sys.stdout.write("foo\nvar") ``` How can I turn this "feature" off? Writing to a file first is not an option, because the output is being piped.
Try the following before writing anything: ``` import sys if sys.platform == "win32": import os, msvcrt msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) ``` If you only want to change to binary mode temporarily, you can write yourself a wrapper: ``` import sys from contextlib import contextmanager @contextma...
How to resample a dataframe with different functions applied to each column?
10,020,591
15
2012-04-04T23:17:23Z
11,603,242
30
2012-07-22T19:13:55Z
[ "python", "numpy", "time-series", "pandas" ]
I have a times series with temperature and radiation in a pandas dataframe. The time resolution is 1 minute in regular steps. ``` import datetime import pandas as pd import numpy as np date_times = pd.date_range(datetime.datetime(2012, 4, 5, 8, 0), datetime.datetime(2012, 4, 5, 12, 0), ...
With pandas 0.18 the resample API changed (see the [docs](http://pandas.pydata.org/pandas-docs/version/0.18.0/whatsnew.html#resample-api)). So for pandas >= 0.18 the answer is: ``` In [31]: frame.resample('1H').agg({'radiation': np.sum, 'tamb': np.mean}) Out[31]: tamb radiation 2012-04-05 0...
Positioning of classes in UML diagram
10,020,822
5
2012-04-04T23:45:04Z
10,154,521
7
2012-04-14T14:54:25Z
[ "python", "drawing", "uml", "graph-drawing" ]
I'm creating a tool for displaying Python project as an UML diagram (+ displaying some code error detection using GUI) I scan some project using Pyreverse and I have all data I need for drawing UML diagram. The problem is positioning of the class boxes on the canvas For a start, I decided to use already implemented f...
It seems that the main enhancement you are missing is transforming your graph to a [layered graph.](http://en.wikipedia.org/wiki/Layered_graph_drawing) This is **no easy task, but it's doable**. (the quality of the result may vary by the amount of time and thought invested in the process). The main idea is to do a som...
Creating a popup message box with an Entry field
10,020,885
4
2012-04-04T23:51:57Z
10,021,242
8
2012-04-05T00:41:18Z
[ "python", "tkinter" ]
I am trying to have a popup message box which prompts user to enter an input. I am having this method inside a class. I googled for it and got this code from <http://www.java2s.com/Code/Python/GUI-Tk/Getinputvaluefromadialog.htm> : ``` class MyDialog: def __init__(self, parent): top = self.top = Toplevel(...
I'm a little confused about your two different blocks of code. Just addressing the first block of code, nothing happens because you never enter the mainloop. To do that, you need to call `root.mainloop()`. The typical way of doing this is to add a button to root widget and bind a callback function to the Button (which ...
Django Tastypie Advanced Filtering: How to do complex lookups with Q objects
10,021,749
24
2012-04-05T02:04:39Z
10,022,244
35
2012-04-05T03:20:07Z
[ "python", "django", "tastypie", "django-q" ]
I have a basic Django model like: ``` class Business(models.Model): name = models.CharField(max_length=200, unique=True) email = models.EmailField() phone = models.CharField(max_length=40, blank=True, null=True) description = models.TextField(max_length=500) ``` I need to execute a complex query on th...
You are on the right track. However, `build_filters` is supposed to transition resource lookup to an ORM lookup. The default implementation splits the query keyword based on `__` into key\_bits, value pairs and then tries to find a mapping between the resource looked up and its ORM equivalent. Your code is not suppos...
What conditions result in an opened, nonblocking named pipe (fifo) being "unavailable" for reads?
10,021,759
12
2012-04-05T02:06:56Z
10,021,958
10
2012-04-05T02:36:28Z
[ "python", "linux", "named-pipes", "fifo", "mkfifo" ]
Situation: ``` new_pipe = os.open(pipe_path, os.O_RDONLY | os.O_NONBLOCK) # pipe_path points to a FIFO data = os.read(new_pipe, 1024) ``` The read occasionally raises errno -11: Resource temporarily unavailable. When is this error raised? It seems very rare, as the common cases return data: * If no writer has the p...
From the [POSIX specification of the `read` system call](http://pubs.opengroup.org/onlinepubs/009695399/functions/read.html) (emphasis mine): > When attempting to read from an empty pipe or FIFO: > > * If no process has the pipe open for writing, read() shall return 0 to > indicate end-of-file. > * **If some process...
how do I make randint threadsafe in python?
10,021,882
2
2012-04-05T02:26:44Z
10,021,910
8
2012-04-05T02:30:28Z
[ "python", "random", "thread-safety" ]
I have an application requiring the same results given the same random seed. But I find random.randint not threadsafe. I have tried mutex but this does not work. Here is my experiment code(long but simple): ``` import threading import random def child(n, a): g_mutex = threading.Lock() g_mutex.acquire() ra...
You can create separate instances of `random.Random` for each thread ``` >>> import random >>> local_random = random.Random() >>> local_random.seed(1234) >>> local_random.randint(1,1000) 967 ```
What is a generative method?
10,021,899
19
2012-04-05T02:29:11Z
10,053,565
30
2012-04-07T10:13:52Z
[ "python", "sqlalchemy" ]
I'm familiar with Python generators, however I've just come across the term "generative method" which I am not familiar with and cannot find a satisfactory definition. To put it in context, I found the term in SQLAlchemy's narrative documentation: > Full control of the “autocommit” behavior is available using the...
It doesn't appear to be a common database concept, but SQLAlchemy uses the term *generative* in the sense "generated by your program iteratively at runtime". (So, no connection to python generators). An example from [the tutorial:](http://docs.sqlalchemy.org/en/latest/orm/tutorial.html#querying) > The `Query` object i...
How to debug indentation errors in python
10,022,018
5
2012-04-05T02:45:38Z
11,602,270
24
2012-07-22T17:08:05Z
[ "python", "debugging", "indentation" ]
I am trying to write my very first python script. This was working but then after some slight refactoring I have, apparently, broken the indentation. I can not determine what is the problem. The interpretor complains about the following method. Can someone point it out? ``` def dataReceived(self, data): a = data.s...
I encountered a similar problem using Sublime Text 2. To solve, click on the "Tab Size" at the bottom of the editor, and choose "Convert Indentation to Tabs".
overload += in python for a mapping type
10,022,405
2
2012-04-05T03:46:09Z
10,022,429
12
2012-04-05T03:50:05Z
[ "python", "dictionary", "operator-overloading" ]
I'd like to use a += notation for updating a dict-like object in Python. I want to have the same behavior as dict.update method. Here is my class (dictionary with "." access): ``` class sdict(dict): def __getattr__(self, attr): return self.get(attr, None) __setattr__= dict.__setitem__ __delattr__= ...
I think all you're missing is a def: ``` class sdict(dict): def __getattr__(self, attr): return self.get(attr, None) __setattr__= dict.__setitem__ __delattr__= dict.__delitem__ def __iadd__(self, other): self.update(other) return self >>> a = sdict() >>> a.b = 3 >>> a {'b': 3} ...
How to make a selection PyMongo only unique records?
10,022,839
4
2012-04-05T04:49:39Z
10,022,890
10
2012-04-05T04:57:57Z
[ "python", "mongodb", "nosql", "pymongo" ]
How to make a selection PyMongo only unique records? ``` >>> db.houses.find({"street":{"$regex": "Fl", "$options":"i"}}).count() 107 >>> for item in db.houses.find({"street":{"$regex": "Fl", "$options":"i"}}): ... print item["street"] ... Flatbush Avenue Flatbush Avenue Flatbush Avenue Flatlands Avenue Flatlands Aven...
According to the docs - [Cursor.distinct](http://api.mongodb.org/python/current/api/pymongo/cursor.html#pymongo.cursor.Cursor.distinct) should do the trick: ``` db.houses.find({"street":{"$regex": "май", "$options":"i"}}).distinct("street") ```
Extracting items out of a QueryDict
10,023,213
12
2012-04-05T05:43:00Z
10,023,515
29
2012-04-05T06:15:14Z
[ "python", "django" ]
I have a querydict that looks like the following: ``` <QueryDict: {u'{"content":"aa","id":"1"}': [u'']}> ``` How would I extract out `id`? I have tried doing `queryDictExample.get("id")`, but it didn't work.
It seems like your client is posting JSON rather than formencoded data. Instead of accessing `request.POST`, use `request.body` (`request.raw_post_data` in versions 1.3 or less) and use `json.loads()` to convert to a dict.
How to get unique list using a key word :Python
10,024,646
4
2012-04-05T07:51:40Z
10,024,750
10
2012-04-05T07:59:09Z
[ "python", "list", "set" ]
Background:- I have a list. This list has many objects. Each object has a id. Now the objects are of different types. ``` [ Aobject, Bobject, Cobject] Aobject != Bobject Aobject.id == Bobject.id ``` Problem:- I want a unique list based on the object.id. Something like this :- ``` set(list, key=operator.attrgetter...
``` seen = set() # never use list as a variable name [seen.add(obj.id) or obj for obj in mylist if obj.id not in seen] ``` This works because `set.add` returns `None`, so the expression in the list comprehension always yields `obj`, but only if `obj.id` has not already been added to `seen`. (The expression could on...
How can I denote unused function arguments?
10,025,680
20
2012-04-05T09:04:05Z
10,025,812
10
2012-04-05T09:13:02Z
[ "python", "python-2.x" ]
When "deconstructing" a tuple, I can use `_` to denote tuple elements I'm not interested in, e.g. ``` >>> a,_,_ = (1,2,3) >>> a 1 ``` Using Python 2.x, how can I express the same with function arguments? I tried to use underscores: ``` >>> def f(a,_,_): return a ... File "<stdin>", line 1 SyntaxError: duplicate ar...
Here's what I do with unused arguments: ``` def f(a, *unused): return a ```
How can I denote unused function arguments?
10,025,680
20
2012-04-05T09:04:05Z
14,836,005
28
2013-02-12T15:32:30Z
[ "python", "python-2.x" ]
When "deconstructing" a tuple, I can use `_` to denote tuple elements I'm not interested in, e.g. ``` >>> a,_,_ = (1,2,3) >>> a 1 ``` Using Python 2.x, how can I express the same with function arguments? I tried to use underscores: ``` >>> def f(a,_,_): return a ... File "<stdin>", line 1 SyntaxError: duplicate ar...
A funny way I just thought of is to delete the variable: ``` def f(foo, unused1, unused2, unused3): del unused1, unused2, unused3 return foo ``` This has numerous advantages: * the unused variable can still be used when calling the function both as a positional argument and as a keyword argument * if you sta...
os.path.abspath('file1.txt') doesn't return the correct path
10,025,863
4
2012-04-05T09:16:00Z
10,025,930
9
2012-04-05T09:19:59Z
[ "python", "path" ]
Say the path of the file 'file1.txt' is `/home/bentley4/Desktop/sc/file1.txt` Say my current working directory is `/home/bentley4` ``` import os os.path.abspath('file1.txt') ``` returns `/home/bentley4/file1.txt` ``` os.path.exists('file1.txt') ``` returns `False`. If I do ``` os.path.abspath('file_that_does_not_e...
`os.path.abspath(filename)` returns an absolute path as seen from your current working directory. It does no checking whether the file actually exists. If you want the absolute path of `/home/bentley4/Desktop/sc/file1.txt` and you are in `/home/bentley4` you will have to use `os.path.abspath("Desktop/sc/file1.txt")`.
Unable to install boto in python3
10,026,153
9
2012-04-05T09:35:20Z
10,026,341
13
2012-04-05T09:50:22Z
[ "python", "python-3.x", "boto" ]
I am trying to install boto from the source code / pypi, but I am unable to install it using python 3.2. Why is it failing? ``` c:\boto>..\Python32\python.exe setup.py install Traceback (most recent call last): File "setup.py", line 35, in <module> from boto import __version__ File "c:\boto\boto\__init__.py", ...
``` print s.getvalue() ``` is Python 2 syntax. From the `README`: > If you are interested in trying out boto with Python 3.x, check out the [`neo`](https://github.com/boto/boto/tree/neo) branch. This is under active development and the goal is a version of boto that works in Python 2.6, 2.7, and 3.x. Not everything i...
using JSON keys as python attributes in nested JSON
10,026,797
8
2012-04-05T10:22:06Z
10,028,055
10
2012-04-05T11:51:59Z
[ "json", "metaprogramming", "python" ]
I'm working with nested JSON-like data structures in python 2.7 that I exchange with some foreign perl code. I just want to 'work with' these nested structures of lists and dictionaries in amore pythonic way. So if I have a structure like this... ``` a = { 'x': 4, 'y': [2, 3, { 'a': 55, 'b': 66 }], } ``` ......
I think you're making this more complex than it needs to be. If I understand you correctly, all you should need to do is this: ``` import json class Struct(dict): def __getattr__(self, name): return self[name] def __setattr__(self, name, value): self[name] = value def __delattr__(self, n...
How to overwrite a imported python class for all calls
10,027,232
6
2012-04-05T10:53:00Z
10,028,797
8
2012-04-05T12:41:34Z
[ "python", "class" ]
I create a python-packages /MyLibPackage which I will import in my projects. `MyLibPackage.____init____.py` includes mymodiciation.py. Furthermore the MyLibPackage Folder contains another file :base\_classes.py(=external project) mymodiciation.py imports "`from base_classes import *`". Goal: I can import MyLibPackag...
What you want to do is called "monkey patching", and has little to do with Object Orientation. Python does support it, but you have control over all your classes, you should seriously review your project to check if you will really need it. Maybe using a framework like Zope Component Architecture, which allows you to...
Maximum size for multiprocessing.Queue item?
10,028,809
6
2012-04-05T12:42:08Z
10,029,074
11
2012-04-05T12:58:34Z
[ "python", "multithreading", "queue", "multiprocessing" ]
I'm working on a fairly large project in Python that requires one of the compute-intensive background tasks to be offloaded to another core, so that the main service isn't slowed down. I've come across some apparently strange behaviour when using `multiprocessing.Queue` to communicate results from the worker process. U...
Seems the underlying pipe is full, so the feeder thread blocks on the write to the pipe (actually when trying to acquire the lock protecting the pipe from concurrent access). Check this issue <http://bugs.python.org/issue8237>
Python why doesn't writing a contextmanager for an sqlite3 cursor work?
10,029,403
6
2012-04-05T13:20:17Z
10,057,734
13
2012-04-07T19:41:34Z
[ "python", "sqlite", "sqlite3", "connection", "contextmanager" ]
This is supposed to work yet just says no stocks table - supposed lost the connection somewhere inside the contextmanager? ``` import sqlite3 from contextlib import contextmanager @contextmanager def doquery(conn, q, params=()): c = conn.cursor() c.execute(q, params) conn.commit() yield c c.cl...
The problem is with the way you are using the context manager. Calling `doquery` simply creates a context manager object - you need to use it within a `with` statement, which calls its `__enter__` and `__exit__` methods as appropriate. For example, try the following: ``` from contextlib import contextmanager @context...
Python implementation of the Wilson Score Interval?
10,029,588
16
2012-04-05T13:32:45Z
10,029,645
20
2012-04-05T13:36:33Z
[ "python", "algorithm", "statistics", "ranking" ]
After reading [How Not to Sort by Average Rating](http://www.evanmiller.org/how-not-to-sort-by-average-rating.html), I was curious if anyone has a Python implementation of a Lower bound of Wilson score confidence interval for a Bernoulli parameter?
Reddit uses the Wilson score interval for comment ranking, an explanation and python implementation can be found [here](http://amix.dk/blog/post/19588) ``` #Rewritten code from /r2/r2/lib/db/_sorts.pyx from math import sqrt def confidence(ups, downs): n = ups + downs if n == 0: return 0 z = 1.0...
Python implementation of the Wilson Score Interval?
10,029,588
16
2012-04-05T13:32:45Z
10,087,096
18
2012-04-10T10:33:19Z
[ "python", "algorithm", "statistics", "ranking" ]
After reading [How Not to Sort by Average Rating](http://www.evanmiller.org/how-not-to-sort-by-average-rating.html), I was curious if anyone has a Python implementation of a Lower bound of Wilson score confidence interval for a Bernoulli parameter?
I think this one has a wrong wilson call, because if you have 1 up 0 down you get *NaN* because you can't do a `sqrt` on the negative value. The correct one can be found when looking at the ruby example from the article [How not to sort by average page](http://evanmiller.org/how-not-to-sort-by-average-rating.html): `...
Use "contains" and "iexact" at the same query in DJANGO
10,029,905
7
2012-04-05T13:51:36Z
10,029,958
16
2012-04-05T13:54:08Z
[ "python", "django", "django-queryset" ]
How can I use `contains` and `iexact` Field lookups at the same query in Django? Like that .. ``` casas = Casa.objects.filter(nome_fantasia__contains__iexact='green') ```
If you need case-insensitive `contains`, use [`icontains`](https://docs.djangoproject.com/en/dev/ref/models/querysets/#icontains): ``` casas = Casa.objects.filter(nome_fantasia__icontains = 'green') ``` Which is converted to ``` ... WHERE nome_fantasia ILIKE '%green%' ``` in SQL.
How do I output a config value in a Sphinx .rst file?
10,030,149
13
2012-04-05T14:05:49Z
10,042,061
14
2012-04-06T10:11:20Z
[ "python", "python-sphinx" ]
I've got the following in `conf.py`: ``` def setup(app): app.add_config_value('base_url','http://localhost:2000', True) ``` How do I get this into my .rst files? I wrote this: ``` :base_url:/my_app/api/application/ ``` But it only prints `:base_url:` instead of the actual URL. How do I get the actual config va...
For the substitution of links **extlinks** is fine, for including arbitrary config values as asked in your question you can use [rst\_epilog](http://sphinx.pocoo.org/config.html#confval-rst_epilog) for substitutions (or [rst\_prolog](http://sphinx.pocoo.org/config.html#confval-rst_prolog) for text, that should be added...
How to convert (inherit) parent to child class?
10,030,412
2
2012-04-05T14:20:36Z
10,030,468
9
2012-04-05T14:24:31Z
[ "python", "class", "inheritance" ]
I would like to know how to convert parent object that was return by some function to child class. ``` class A(object): def __init__(): pass class B(A): def functionIneed(): pass i = module.getObject()# i will get object that is class A j = B(i)# this will return exception j.functionIneed() `...
Python does not support "casting". You will need to write `B.__init__()` so that it can take a `A` and initialize itself appropriately.
How to write simple geometric shapes into numpy arrays
10,031,580
16
2012-04-05T15:32:41Z
10,031,877
14
2012-04-05T15:53:43Z
[ "python", "image", "numpy", "geometry" ]
I would like to generate a numpy array of 200x200 elements in size and put into it a circle centered into 100,100 coordinates, radius 80 and stroke width of 3 pixels. How to do this in python 2.7 without involving file operations? Possibly using geometry or imaging libraries to allow generalisation to other shapes.
[Cairo](http://www.cairographics.org/) is a modern, flexible and fast 2D graphics library. It has [Python bindings](http://www.cairographics.org/pycairo/) and allows creating "surfaces" based on NumPy arrays: ``` import numpy import cairo import math data = numpy.zeros((200, 200, 4), dtype=numpy.uint8) surface = cairo...
How to write simple geometric shapes into numpy arrays
10,031,580
16
2012-04-05T15:32:41Z
10,032,271
20
2012-04-05T16:19:26Z
[ "python", "image", "numpy", "geometry" ]
I would like to generate a numpy array of 200x200 elements in size and put into it a circle centered into 100,100 coordinates, radius 80 and stroke width of 3 pixels. How to do this in python 2.7 without involving file operations? Possibly using geometry or imaging libraries to allow generalisation to other shapes.
The usual way is to define a coordinate mesh and apply your shape's equations. To do that the easiest way is to use `numpy.mgrid`: <http://docs.scipy.org/doc/numpy/reference/generated/numpy.mgrid.html> ``` # xx and yy are 200x200 tables containing the x and y coordinates as values # mgrid is a mesh creation helper xx...
How to overload `float()` for a custom class in Python?
10,034,097
6
2012-04-05T18:39:27Z
10,034,173
10
2012-04-05T18:44:48Z
[ "python", "floating-point", "operator-overloading", "overloading" ]
## Summary How can I overload the built-in `float` for my class so when I call `float()` on an instance of it, my custom function gets called instead of the default built-in? ## My Class Hi, I was coding my own `Fractions` class (for arbitrarily-high floating-point operation precision). It goes like this (I haven't ...
Define the [`__float__()`](http://docs.python.org/reference/datamodel.html#emulating-numeric-types) special method on your class. ``` class MyClass(object): def __float__(self): return 0.0 float(MyClass()) # 0.0 ``` Note that this method must return a `float`! The calculation `self.num / self.denom`, ...
Python Sphinx referencing long names
10,034,303
7
2012-04-05T18:52:37Z
10,066,799
8
2012-04-08T21:43:40Z
[ "python", "documentation", "python-sphinx", "restructuredtext" ]
I'm working on documentation for my Python module (using Sphinx and reST), and I'm finding that when cross-referencing other Python objects (modules, classes, functions, etc) the full object name ends up being incredibly long. Often it is longer than 80 characters, which I would like to avoid at all costs. Here is an ...
According to the sphinx documentation (<http://sphinx.pocoo.org/domains.html?highlight=current#cross-referencing-python-objects>) you could use a dot before your target class: ``` :class:`.ReallyLongExampleClassName` ``` or ``` :class:`.module5.ReallyLongExampleClassName` ``` and let sphinx search for the class: >...