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
Flask vs webapp2 for Google App Engine
6,774,371
95
2011-07-21T10:03:51Z
6,786,745
123
2011-07-22T07:07:49Z
[ "python", "google-app-engine", "flask", "webapp2" ]
I'm starting new Google App Engine application and currently considering two frameworks: [Flask](http://flask.pocoo.org/) and [webapp2](http://webapp-improved.appspot.com/). I'm rather satisfied with built-in webapp framework that I've used for my previous App Engine application, so I think webapp2 will be even better ...
**Disclaimer:** I'm the author of tipfy and webapp2. A big advantage of sticking with webapp (or its natural evolution, webapp2) is that you don't have to create your own versions for existing SDK handlers for your framework of your choice. For example, [deferred](http://code.google.com/appengine/articles/deferred.ht...
Unknown specifier in URL when using Django-Tagging
6,774,557
2
2011-07-21T10:21:39Z
6,774,631
9
2011-07-21T10:27:52Z
[ "python", "django", "django-tagging" ]
Hi I am getting the following error; ``` error at / unknown specifier: ?P[ ``` This is what my URLS file looks like; ``` urlpatterns = patterns('mainpage.views', (r'^$', 'index'), (r'^post/(?P<id>\d+)/$', 'post'), (r'^projects/$', 'projects'), (r'^about/$', 'about'), (r'^tags/$', 'tags'), (r'^tag/(?P[-_A-Za-...
This is not related to django-tagging, it's a regex syntax error. `?P` indicates a named group, and requires a name after it: `?P<foo>`. So, either add names to your groups, or make them numbered (i.e. remove `?P` part).
Graphically represent lists
6,774,716
6
2011-07-21T10:37:49Z
6,774,912
7
2011-07-21T10:55:01Z
[ "python" ]
Is there a quick way (without the overhead of using a GUI or graphics module) to visually render 2d and 3d lists. For example if I have a 2d array of zeros and ones, I would like to draw a black and white grid according to this array. I am looking for a module that allows me to do these thing in simple ways. Similar ...
The command matshow in matplotlib displays a matrix: ``` import pylab as p p.matshow(p.array([[0,1],[1,1]]),cmap="Greys") ; p.show() ``` This would work for 2d lists. As for 3d lists, I'm not sure I fully understand how you're planning on visualising them.
Why python has limit for count of file handles?
6,774,724
12
2011-07-21T10:38:39Z
6,774,995
24
2011-07-21T11:03:00Z
[ "python" ]
I writed simple code for test, how much files may be open in python script: ``` for i in xrange(2000): fp = open('files/file_%d' % i, 'w') fp.write(str(i)) fp.close() fps = [] for x in xrange(2000): h = open('files/file_%d' % x, 'r') print h.read() fps.append(h) ``` and I get a exception ```...
The number of open files is limited by the operating system. On linux you can type ``` ulimit -n ``` to see what the limit is. If you are root, you can type ``` ulimit -n 2048 ``` now your program will run ok (as root) since you have lifted the limit to 2048 open files
Python copy on PIL image object
6,775,216
8
2011-07-21T11:21:41Z
6,775,266
22
2011-07-21T11:25:37Z
[ "python", "copy", "python-imaging-library" ]
I'm trying to create a set of thumbnails, each one separately downscaled from the original image. ``` image = Image.open(path) image = image.crop((left, upper, right, lower)) for size in sizes: temp = copy.copy(image) temp.thumbnail((size, height), Image.ANTIALIAS) temp.save('%s%s%s.%s' % (path, name, size, form...
I guess `copy.copy()` does not work for the PIL `Image` class. Try using `Image.copy()` instead, since it is there for a reason: ``` image = Image.open(path) image = image.crop((left, upper, right, lower)) for size in sizes: temp = image.copy() # <-- Instead of copy.copy(image) temp.thumbnail((size, height), Imag...
psycopg - Get formatted sql instead of executing
6,775,497
10
2011-07-21T11:47:24Z
6,776,033
10
2011-07-21T12:27:32Z
[ "python", "postgresql", "psycopg" ]
I have a piece of Python code, that interacts with a PostgreSQL database via psycopg. All literature warns against doing sql formatting by oneself, and recommends letting the driver do it. E.g.: ``` cur.execute('select name, age from people where name = %s;', ('ann',) ) ``` The driver then formats the sql string. Le...
you wold use function curs.mogrify(): ``` SQLstring = curs.mogrify('select name, age from people where name = %s;', ('ann',) ) ```
wrapping a list of structs with boost.python
6,776,888
3
2011-07-21T13:33:55Z
6,778,254
11
2011-07-21T15:05:05Z
[ "c++", "python", "list", "wrapping", "boost-python" ]
I have a C++ function that returns a list of structs. Inside the struct, there are more lists of structs. ``` struct CameraInfo { CamName name; std::list<CamImageFormat> lImgFormats; std::list<CamControls> lCamControls; }; std::list<CameraInfo> getCameraInfo() { std::list<Cam...
Does it have to be `std::list` ? If you use `std::vector` instead you can use `boost::python::vector_indexing_suite` to wrap the list. See [this post](http://stackoverflow.com/questions/6157409/stdvector-to-boostpythonlist/6158370#6158370 "this post") for details. If you must use `std::list` you'll need to create a he...
Modifying a Python dict while iterating over it
6,777,485
37
2011-07-21T14:15:58Z
6,777,569
10
2011-07-21T14:21:34Z
[ "python", "dictionary" ]
Let's say we have a Python dictionary `d`, and we're iterating over it like so: ``` for k,v in d.iteritems(): del d[f(k)] # remove some item d[g(k)] = v # add a new item ``` (`f` and `g` are just some black-box transformations.) In other words, we try to add/remove items to `d` while iterating over it using ...
You cannot do that, at least with `d.iteritems()`. I tried it, and Python fails with ``` RuntimeError: dictionary changed size during iteration ``` If you instead use `d.items()`, then it works. In Python 3, `d.items()` is a view into the dictionary, like `d.iteritems()` in Python 2. To do this in Python 3, instead ...
Modifying a Python dict while iterating over it
6,777,485
37
2011-07-21T14:15:58Z
6,777,632
30
2011-07-21T14:24:45Z
[ "python", "dictionary" ]
Let's say we have a Python dictionary `d`, and we're iterating over it like so: ``` for k,v in d.iteritems(): del d[f(k)] # remove some item d[g(k)] = v # add a new item ``` (`f` and `g` are just some black-box transformations.) In other words, we try to add/remove items to `d` while iterating over it using ...
Alex Martelli weighs in on this [here](http://stackoverflow.com/questions/2315520/in-python-how-do-i-loop-through-the-dictionary-and-change-the-value-if-it-equals/2315529#2315529). It may not be safe to change the container (e.g. dict) while looping over the container. So `del d[f(k)]` may not be safe. As you know, th...
Modifying a Python dict while iterating over it
6,777,485
37
2011-07-21T14:15:58Z
6,777,832
26
2011-07-21T14:37:01Z
[ "python", "dictionary" ]
Let's say we have a Python dictionary `d`, and we're iterating over it like so: ``` for k,v in d.iteritems(): del d[f(k)] # remove some item d[g(k)] = v # add a new item ``` (`f` and `g` are just some black-box transformations.) In other words, we try to add/remove items to `d` while iterating over it using ...
It is explicitely mentioned on the Python doc page: <http://docs.python.org/library/stdtypes.html#dict.iteritems> that `Using iteritems() while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries`. The same holds for `iter(d)`, `d.iterkeys()` and `d.itervalues()`, ...
lat/lon to utm to lat/lon is extremely flawed, how come?
6,778,288
7
2011-07-21T15:07:09Z
14,176,034
13
2013-01-05T20:23:06Z
[ "python", "latitude-longitude", "utm" ]
I've tried the following, input: lat/lon data then I'll calculate a box around it by, let's say 50 m, so +/- 50 m on easting/northing value. Now I reconvert it to lat/lon and with a script: <http://robotics.ai.uiuc.edu/~hyoon24/LatLongUTMconversion.py> I get a result that just can't be, lon before is around 7, afterw...
I've created a small UTM conversion library for Python last week and uploaded it to the Python Package Index: <http://pypi.python.org/pypi/utm> I have compared it to using pyproj and it is faster and more accurate. Given your sample data, this is the result: ``` >>> import utm >>> u = utm.from_latlon(47.9941214, 7.8...
lat/lon to utm to lat/lon is extremely flawed, how come?
6,778,288
7
2011-07-21T15:07:09Z
18,620,929
7
2013-09-04T18:10:30Z
[ "python", "latitude-longitude", "utm" ]
I've tried the following, input: lat/lon data then I'll calculate a box around it by, let's say 50 m, so +/- 50 m on easting/northing value. Now I reconvert it to lat/lon and with a script: <http://robotics.ai.uiuc.edu/~hyoon24/LatLongUTMconversion.py> I get a result that just can't be, lon before is around 7, afterw...
The error is in your code. First off, the PyProj issue listed in one of the other answers is real. You should check your epsg file and make sure it includes the line ``` <2392> +proj=tmerc +lat_0=0 +lon_0=24 +k=1.000000 +x_0=2500000 +y_0=0 +ellps=intl +towgs84=-90.7,-106.1,-119.2,4.09,0.218,-1.05,1.37 +units=m +no_de...
manage.py runserver Error: [Errno 10013]
6,778,638
5
2011-07-21T15:30:52Z
6,778,708
18
2011-07-21T15:35:44Z
[ "python", "django", "python-2.7" ]
I am having some problems running django. When I use the command `manage.py runserver` I receive an error that says: `Error: [Errno 10013] An attempt was made to access a socket in a way forbidden by access permissions` I use postgreSQL as my database. Edit: I run Windows Vista
If you don't have permission to bind to a socket, you can try `sudo manage.py runserver` to do it with root privileges. With Windows Vista / 7 you need to run the shell with administrator privileges. You can right click on the icon and select "Run as administrator" or go to `c:\windows\system32\` and right click on `c...
Python File Creation Date & Rename - Request for Critique
6,778,923
6
2011-07-21T15:49:46Z
6,779,275
7
2011-07-21T16:13:58Z
[ "python", "file", "date", "rename", "creation" ]
Scenario: When I photograph an object, I take multiple images, from several angles. Multiplied by the number of objects I "shoot", I can generate a large number of images. Problem: Camera generates images identified as, 'DSCN100001', 'DSCN100002", etc. Cryptic. I put together a script that will prompt for directory sp...
The way you're doing it looks Pythonic. A few alternatives (not necessarily suggestions): You could skip `os.chdir(target)` and do `os.path.join(target, filename)` in the loop. You could do `strftime('{0}-%Y-%m-%d-%H:%M:%S.jpg'.format(prefix))` to avoid string concatenation. This is the only one I'd reccomend. You c...
python sqlalchemy + postgresql program freezes
6,778,942
14
2011-07-21T15:50:37Z
6,810,165
22
2011-07-24T22:24:43Z
[ "python", "sqlalchemy" ]
I've ran into a strange situation. I'm writing some test cases for my program. The program is written to work on sqllite or postgresqul depending on preferences. Now I'm writing my test code using unittest. Very basically what I'm doing: ``` def setUp(self): """ Reset the database before each test. """...
PostgreSQL based applications freeze because PG locks tables fairly aggressively, in particular it will not allow a DROP command to continue if any connections are open in a pending transaction, which have accessed that table in any way (SELECT included). If you're on a unix system, the command "ps -ef | grep 'post'" ...
utf-16 file seeking in python. how?
6,779,315
10
2011-07-21T16:17:33Z
6,779,642
15
2011-07-21T16:41:15Z
[ "python", "utf-16" ]
For some reason i can not seek my utf16 file. It produces 'UnicodeException: UTF-16 stream does not start with BOM'. My code: ``` f = codecs.open(ai_file, 'r', 'utf-16') seek = self.ai_map[self._cbClass.Text] #seek is valid int f.seek(seek) while True: ln = f.readline().strip() ``` I tried random stuff like firs...
Well, the error message is telling you why: it's not reading a byte order mark. The byte order mark is at the beginning of the file. Without having read the byte order mark, the UTF-16 decoder can't know what order the bytes are in. Apparently it does this lazily, the first time you read, instead of when you open the f...
(python) how to run " ps cax | grep something " in python?
6,780,035
15
2011-07-21T17:16:45Z
6,780,074
7
2011-07-21T17:19:58Z
[ "python", "command", "pipe" ]
as in question how do I run command with '|' in it? subprocess module seems complex.. there's nothing like output,error = `ps cax | grep something` as in shell script? :(
``` import subprocess process = subprocess.Popen("ps cax | grep something", shell=True, stdout=subprocess.PIPE, ) stdout_list = process.communicate()[0].split('\n') ```
(python) how to run " ps cax | grep something " in python?
6,780,035
15
2011-07-21T17:16:45Z
6,780,118
29
2011-07-21T17:23:57Z
[ "python", "command", "pipe" ]
as in question how do I run command with '|' in it? subprocess module seems complex.. there's nothing like output,error = `ps cax | grep something` as in shell script? :(
See [Replacing shell pipeline](http://docs.python.org/library/subprocess.html#replacing-shell-pipeline): ``` import subprocess import shlex proc1 = subprocess.Popen(shlex.split('ps cat'),stdout=subprocess.PIPE) proc2 = subprocess.Popen(shlex.split('grep python'),stdin=proc1.stdout, stdout=subp...
(python) how to run " ps cax | grep something " in python?
6,780,035
15
2011-07-21T17:16:45Z
6,781,895
9
2011-07-21T19:51:09Z
[ "python", "command", "pipe" ]
as in question how do I run command with '|' in it? subprocess module seems complex.. there's nothing like output,error = `ps cax | grep something` as in shell script? :(
You've already accepted an answer, but: Do you really *need* to use grep? I'd write something like: ``` import subprocess ps = subprocess.Popen(('ps', 'cax'), stdout=subprocess.PIPE) output = ps.communicate()[0] for line in output.split('\n'): if 'something' in line: ... ``` This has the advantages of no...
How to compare values within an array in Python - find out whether 2 values are the same
6,780,048
5
2011-07-21T17:17:51Z
6,780,097
9
2011-07-21T17:21:58Z
[ "python", "arrays", "list", "random", "integer" ]
I basically have an array of 50 integers, and I need to find out whether any of the 50 integers are equal, and if they are, I need to carry out an action. How would I go about doing this? As far as I know there isn't currently a function in Python that does this is there? Thanks in advance
If you mean you have a list and you want to know if there are any duplicate values, then make a set from the list and see if it's shorter than the list: ``` if len(set(my_list)) < len(my_list): print "There's a dupe!" ``` This won't tell you what the duplicate value is, though.
Is it possible to subclass Lock() objects in Python? If not, other ways to debug deadlock?
6,780,613
6
2011-07-21T18:08:36Z
6,781,257
12
2011-07-21T18:59:29Z
[ "python", "multithreading", "oop", "thread-safety", "deadlock" ]
So, I've got a multithreaded python program, which is currently suffering from deadlock. I was going to log lock acquiring by subclassing threading.Lock objects: ``` import traceback class DebugLock(threading.Lock): def acquire(self): print >>sys.stderr, "acquired", self #traceback.print_tb ...
You could just use the "has a lock" versus "is a lock" approach, like so: ``` import threading, traceback, sys class DebugLock(object): def __init__(self): self._lock = threading.Lock() def acquire(self): print >>sys.stderr, "acquired", self #traceback.print_tb self._lock.acquir...
Python Wrap Class Method
6,780,907
8
2011-07-21T18:31:58Z
6,781,146
11
2011-07-21T18:50:40Z
[ "python", "class", "methods", "wrapper", "wrap" ]
I'm trying to create an object with a run method that will be wrapped by a \_wrap\_run method. I'd like to be able to call the method and it's wrapper by simply typing instance.run() and I'd like to be able to subclass the object so I can override the run() method and have it still execute the wrapper. More simply put...
Use a Metaclass. ``` class MetaClass(type): @staticmethod def wrap(run): """Return a wrapped instance method""" def outer(self): print "PRE", return_value = run(self) print "POST" return return_value return outer def __new__(cls, name,...
How to change behavior of dict() for an instance
6,780,952
18
2011-07-21T18:36:11Z
6,781,411
27
2011-07-21T19:12:39Z
[ "python", "dictionary", "override", "autovivification" ]
So I'm writing a class that extends a dictionary which right now uses a method "dictify" to transform itself into a dict. What I would like to do instead though is change it so that calling dict() on the object results in the same behavior, but I don't know which method to override. Is this not possible, or I am I miss...
Nothing wrong with your approach, but this is similar to the Autovivification feature of Perl, which has been implemented in Python [in this question](http://stackoverflow.com/questions/651794/whats-the-best-way-to-initialize-a-dict-of-dicts-in-python). Props to @nosklo for this. ``` class RecursiveDict(dict): """...
batch equivalent of "source" on windows: how to run a python script from a virtualenv
6,781,799
30
2011-07-21T19:43:05Z
6,782,236
47
2011-07-21T20:20:01Z
[ "python", "windows", "scripting", "batch-file", "virtualenv" ]
So, I've done a fair bit of bash scripting, but very little batch scripting on Windows. I'm trying to activate a python virtualenv, run a python script, then deactivate the virtualenv when the script exits. I've got a folder called env, which is my virtualenv, and a folder called work, which contains my scripts This ...
I'd say you just need to prepend 'call' to your activate.bat invocation, to ensure that the current batch file is resumed after activate is executed: call %~dp0env\Scripts\activate.bat Consider doing the same for deactivate.bat . Furthermore, if you want to ensure that the current cmd.exe environment is not polluted ...
BoostBuild: patchlevel.h does not exist
6,782,071
16
2011-07-21T20:05:38Z
6,782,280
16
2011-07-21T20:23:30Z
[ "python", "boost", "boost-build" ]
I'm trying to compile a C++ project using bjam on Ubuntu 11.04. I keep getting the following error: ``` ../../libraries/boost_1_44_0/boost/python/detail/wrap_python.hpp:75:24: fatal error: patchlevel.h: No such file or directory ``` I searched my project directory and there are several files named patchlevel.h but I ...
IIRC patchlevel.h is a python-dev header, check this package is installed (i dont remember the exact name but it si the C header for python binding). ovcam.h is not part of boost in anyway.
SQLAlchemy One-to-Many relationship on single table inheritance - declarative
6,782,133
6
2011-07-21T20:11:34Z
6,782,238
8
2011-07-21T20:20:16Z
[ "python", "orm", "sqlalchemy", "data-modeling" ]
Basically, I have this model, where I mapped in a single table a "BaseNode" class, and two subclasses. The point is that I need one of the subclasses, to have a one-to-many relationship with the other subclass. So in sort, it is a relationship with another row of different class (subclass), but in the same table. How d...
I was struggling through this myself earlier. I was able to get this self-referential relationship working: ``` class Employee(Base): __tablename__ = 'employee' id = Column(Integer, primary_key=True) name = Column(String(64), nullable=False) Employee.manager_id = Column(Integer, ForeignKey(Employee.id)) Employee...
Call a Python script from a Applescript
6,782,158
5
2011-07-21T20:13:38Z
6,782,270
7
2011-07-21T20:22:45Z
[ "python", "osx", "shell", "applescript" ]
My Applescript and Python script are in the present working directory. Now I need to call the Python script named test.py with admin privileges from the applescript using shell commands. **This code in Applescript gives the pwd** ``` tell application "Finder" to get folder of (path to me) as Unicode text set presentD...
If you know the script is in the same directory, just use: ``` do shell script presentDir & "test.py " user name "me" password "mypassword" with administrator privileges ``` Notice the space after `test.py` before the close-quote. You may possibly need the string to be `/test.py`, rather than `test.py`, I'm not sure....
No connection could be made because the target machine actively refused it (Django)
6,782,732
11
2011-07-21T21:01:10Z
6,810,553
23
2011-07-24T23:54:36Z
[ "python", "django" ]
I have followed the [Django Book](http://www.djangobook.com) up until chapter seven, and I am currently messing around with forms, GET, POST and all that goodness. At one point, the guide made me figure out the reaction, after a form is filled out and sent, but when I send the form data, I get this error: ``` error at...
I managed to find out what the problem was (no thanks to the error message). As it turns out, I needed to set up my e-mail server: > Note that in order to send e-mail using send\_mail(), your server must be configured to send mail, and Django must be told about your outbound e-mail server. See <http://docs.djangoproje...
Which maximum does Python pick in the case of a tie?
6,783,000
43
2011-07-21T21:25:34Z
6,783,051
11
2011-07-21T21:30:31Z
[ "python", "max" ]
When using the `max()` function in Python to find the maximum value in a list (or tuple, dict etc.) and there is a tie for maximum value, which one does Python pick? Is it random? This is relevant if, for instance, one has a list of tuples and one selects a maximum (using a `key=`) based on the first element of the tu...
From empirical testing, it appears that `max()` and `min()` on a list will return the first in the list that matches the `max()`/`min()` in the event of a tie: ``` >>> test = [(1, "a"), (1, "b"), (2, "c"), (2, "d")] >>> max(test, key=lambda x: x[0]) (2, 'c') >>> test = [(1, "a"), (1, "b"), (2, "d"), (2, "c")] >>> max(...
Which maximum does Python pick in the case of a tie?
6,783,000
43
2011-07-21T21:25:34Z
6,783,101
50
2011-07-21T21:34:33Z
[ "python", "max" ]
When using the `max()` function in Python to find the maximum value in a list (or tuple, dict etc.) and there is a tie for maximum value, which one does Python pick? Is it random? This is relevant if, for instance, one has a list of tuples and one selects a maximum (using a `key=`) based on the first element of the tu...
This isn't specified in the documentation and isn't in the portable in-Python section of the standard library, so this behaviour may vary between implementations. In the source to CPython 2.7 this is implemented in `./Python/bltinmodule.c` by `builtin_max` [[source](http://hg.python.org/cpython/file/8527427914a2/Pyth...
Background thread with QThread in PyQt
6,783,194
33
2011-07-21T21:43:03Z
6,789,205
59
2011-07-22T11:18:47Z
[ "python", "multithreading", "pyqt", "pyqt4", "qthread" ]
I have a program which interfaces with a radio I am using via a gui I wrote in PyQt. Obviously one of the main functions of the radio is to transmit data, but to do this continuously, I have to loop the writes, which causes the gui to hang. Since I have never dealt with threading, I tried to get rid of these hangs usin...
I created a little example that shows 3 different and simple ways of dealing with threads. I hope it will help you find the right approach to your problem. ``` import sys import time from PyQt5.QtCore import (QCoreApplication, QObject, QRunnable, QThread, QThreadPool, pyqtSignal) # Subclas...
Background thread with QThread in PyQt
6,783,194
33
2011-07-21T21:43:03Z
19,017,560
20
2013-09-26T00:51:42Z
[ "python", "multithreading", "pyqt", "pyqt4", "qthread" ]
I have a program which interfaces with a radio I am using via a gui I wrote in PyQt. Obviously one of the main functions of the radio is to transmit data, but to do this continuously, I have to loop the writes, which causes the gui to hang. Since I have never dealt with threading, I tried to get rid of these hangs usin...
According to the Qt developers, subclassing QThread is incorrect (see <http://blog.qt.digia.com/blog/2010/06/17/youre-doing-it-wrong/>). But that article is really hard to understand (plus the title is a bit condescending). I found a better blog post that gives a more detailed explanation about why you should use one s...
Background thread with QThread in PyQt
6,783,194
33
2011-07-21T21:43:03Z
22,060,122
26
2014-02-27T05:50:45Z
[ "python", "multithreading", "pyqt", "pyqt4", "qthread" ]
I have a program which interfaces with a radio I am using via a gui I wrote in PyQt. Obviously one of the main functions of the radio is to transmit data, but to do this continuously, I have to loop the writes, which causes the gui to hang. Since I have never dealt with threading, I tried to get rid of these hangs usin...
Very nice example from Matt, I fixed the typo and also pyqt4.8 is common now so I removed the dummy class as well and added an example for the dataReady signal ``` # -*- coding: utf-8 -*- import sys from PyQt4 import QtCore, QtGui from PyQt4.QtCore import Qt # very testable class (hint: you can use mock.Mock for the...
Background thread with QThread in PyQt
6,783,194
33
2011-07-21T21:43:03Z
33,453,124
10
2015-10-31T15:13:41Z
[ "python", "multithreading", "pyqt", "pyqt4", "qthread" ]
I have a program which interfaces with a radio I am using via a gui I wrote in PyQt. Obviously one of the main functions of the radio is to transmit data, but to do this continuously, I have to loop the writes, which causes the gui to hang. Since I have never dealt with threading, I tried to get rid of these hangs usin...
Take this answer updated for PyQt5, python 3.4 Use this as a pattern to start a worker that does not take data and return data as they are available to the form. 1 - Worker class is made smaller and put in its own file worker.py for easy memorization and independent software reuse. 2 - The main.py file is the file t...
Python function that accepts file object or path
6,783,472
8
2011-07-21T22:14:55Z
6,783,680
11
2011-07-21T22:41:07Z
[ "python", "file-io" ]
I want to write a function that accepts either a path as a string or a file object. So far I have: ``` def awesome_parse(path_or_file): if isinstance(path_or_file, basestring): f = open(path_or_file, 'rb') else: f = path_or_file with f as f: return do_stuff(f) ``` where `do_stuff` ...
The odd thing about your code is that if it is passed an open file, it will close it. This isn't good. Whatever code opened the file should be responsible for closing it. This makes the function a bit more complex though: ``` def awesome_parse(path_or_file): if isinstance(path_or_file, basestring): f = fil...
Python Unicode object and C API ( retrieving char* from pyunicode objects )
6,783,493
8
2011-07-21T22:17:44Z
16,905,726
7
2013-06-03T20:59:01Z
[ "python", "string", "unicode", "binding", "ascii" ]
I am currently binding all of my C++ engine classes to python for game play scripting purposes. The latest challenge is that when say you make a variable in the script a string such as ``` string = 'hello world' ``` this becomes a PyUnicodeObject. Next we want to call a function on this object in the script from a bo...
I was facing a similar problem with Python3. I solved it as follows. If you have a [PyUnicodeObject](http://docs.python.org/2/c-api/unicode.html) "mystring", do something like ``` PyObject * ascii_mystring=PyUnicode_AsASCIIString(mystring); PrintToLog(PyBytes_AsString(ascii_mystring)); Py_DECREF(ascii_mystring); ``` ...
Is there a function for Converting IP address to decimal number in python?
6,783,926
6
2011-07-21T23:09:14Z
6,783,994
16
2011-07-21T23:18:13Z
[ "python", "ip", "decimal" ]
Is there any function or API or method that will convert a doted IP string to decimal number?
I'm not sure what is the decimal number you really want, but take a look at `socket.inet_aton`. It will give you string with binary representation of the IP address in network byte order. If you want to get a regular integer out of it, you could use `struct.unpack` with either `"!I"` or `"I"`, depending on which byte o...
How to pass arguments to functions by the click of button in PyQt?
6,784,084
9
2011-07-21T23:31:08Z
6,784,311
11
2011-07-22T00:06:19Z
[ "python", "function", "arguments", "pyqt4", "argument-passing" ]
I want to pass the arguments to a function when I click the button. What should I add to this line `button.connect(button, QtCore.SIGNAL('clicked()'), calluser(name))` so it will pass the value to the function: ``` def calluser(name): print name def Qbutton(): button = QtGui.QPushButton("button",widget) n...
Usually GUIs are built using classes. By using bound methods as callbacks (see `self.calluser` below) you can "pass" information to the callback through `self`'s attributes (e.g. `self.name`): For example, using slightly modified code from [this tutorial](http://zetcode.com/tutorials/pyqt4/widgets/): ``` import sys i...
Given a list of elements in lexicographical order (i.e. ['a', 'b', 'c', 'd']), find the nth permutation - Average time to solve?
6,784,148
2
2011-07-21T23:39:56Z
6,784,359
9
2011-07-22T00:15:38Z
[ "python", "list", "recursion", "combinations" ]
I stumbled across this interview question: > Given a list of elements in lexicographical order (i.e. ['a', 'b', 'c', 'd']), find the nth permutation I tried it myself, and it took me about ~30 minutes to solve. (I ended up with a ~8-9 line solution in Python). Just curious -- how long "should" it take to solve this t...
9 min, including test ``` import math def nthperm(li, n): n -= 1 s = len(li) res = [] if math.factorial(s) <= n: return None for x in range(s-1,-1,-1): f = math.factorial(x) d = n / f n -= d * f res.append(li[d]) del(li[d]) return res #now that'...
python yield and stopiteration in one loop?
6,784,934
13
2011-07-22T02:01:01Z
6,785,015
24
2011-07-22T02:15:29Z
[ "python", "generator", "stopiteration" ]
i have a generator where i would like to add an initial and final value to the actual content, it's something like this: ``` # any generic queue where i would like to get something from q = Queue() def gen( header='something', footer='anything' ): # initial value header yield header for c in count(): ...
You seem to be overcomplicating this quite a bit: ``` >>> q = [1, 2, 3, 4] >>> def gen(header='something', footer='anything'): yield header for thing in q: yield thing yield footer >>> for tmp in gen(): print(tmp) something 1 2 3 4 anything ``` `StopIteration` will auto...
Django "Unable to determine the file's size" error with tempfile.TemporaryFile
6,785,666
9
2011-07-22T04:27:24Z
8,282,407
11
2011-11-26T23:23:51Z
[ "python", "django" ]
I'm having problems with the standard Django FileField and tempfile.TemporaryFile. Whenever I try to save a FileField with the TemporaryFile, I get the "Unable to determine the file's size" error. For example, given a model named Model, a filefield named FileField, and a temporaryfile named TempFile: ``` Model.FileFi...
I had this problem with `tempfile.TemporaryFile`. When I switched to `tempfile.NamedTemporaryFile` it went away. I believe that `TemporaryFile` just simulates being a file (on some operating system at least), whereas `NamedTemporaryFile` really is a file.
import error while bundling using py2exe
6,786,473
3
2011-07-22T06:34:52Z
8,171,978
11
2011-11-17T17:58:17Z
[ "python" ]
I bundled a small script written in python using py2exe. The script uses many packages and one of them is reportlab. After bundling using py2exe I tried to run the executable file and it is returning following error: ``` C:\Python26\dist>DELchek.exe Traceback (most recent call last): File "DELchek.py", line 12, in <mo...
I've had the same problem in the past bundling reportlab with py2exe. It imports of a bunch of modules dynamically, which py2exe does not recognize when assembling the dependencies. The brute-force fix is to import the required modules directly in your code: ``` from reportlab.pdfbase import _fontdata_enc_winansi from...
Automatic version number both in setup.py (setuptools) AND source code?
6,786,555
14
2011-07-22T06:47:31Z
6,786,823
13
2011-07-22T07:16:44Z
[ "python", "git", "version", "setuptools", "distutils" ]
**SITUATION:** I have a python library, which is controlled by git, and bundled with distutils/setuptools. And I want to automatically generate version number based on git tags, both for `setup.py sdist` and alike commands, and for the library itself. For the first task I can use `git describe` or alike solutions (se...
A classic issue when toying with [keyword expansion](http://stackoverflow.com/questions/1127177/to-put-the-prefix-revision-number-to-codes-by-git-svn/1127241#1127241) ;) The key is to realize that your tag is part of the release management process, not part of the development (and its version control) process. In oth...
Automatic version number both in setup.py (setuptools) AND source code?
6,786,555
14
2011-07-22T06:47:31Z
7,502,821
12
2011-09-21T15:53:22Z
[ "python", "git", "version", "setuptools", "distutils" ]
**SITUATION:** I have a python library, which is controlled by git, and bundled with distutils/setuptools. And I want to automatically generate version number based on git tags, both for `setup.py sdist` and alike commands, and for the library itself. For the first task I can use `git describe` or alike solutions (se...
You could also reverse the dependency: put the version in `mylib/__init__.py`, parse that file in setup.py to get the version parameter, and use git tag $(setup.py --version) on the command line to create your tag. ``` git tag -a v$(python setup.py --version) -m 'description of version' ``` Is there anything more com...
How to remove this special character?
6,786,609
3
2011-07-22T06:54:30Z
6,786,646
7
2011-07-22T06:59:27Z
[ "python", "string" ]
I was trying to unify the lines in my file when I observed the following: word1 word2 word1 word2 I did not understand why these lines were not combined so I opened the file in vim and used `:set list` to see if there are any special characters and I found this: ``` word1 <feff>word2 word1 word2 ``` I am not su...
U+FEFF is the [Byte Order Mark](http://en.wikipedia.org/wiki/Byte-order_mark) character, which should only occur at the start of a document. In documents, [it should be treated as a `ZERO WIDTH NON-BREAKING SPACE`](http://unicode.org/faq/utf_bom.html#bom6). If this causes issues, you can remove it like any other charac...
Find out time it took for a python script to complete execution
6,786,990
59
2011-07-22T07:36:03Z
6,787,008
109
2011-07-22T07:38:36Z
[ "python" ]
I have the following code in a python script: ``` def fun() #Code here fun() ``` I want to execute this script and also find out how much time it took to execute in minutes. How to find out how much time it took for this script to execute ?.Some example would be really appreciated. Thank You
``` from datetime import datetime startTime = datetime.now() #do something print datetime.now() - startTime ```
Find out time it took for a python script to complete execution
6,786,990
59
2011-07-22T07:36:03Z
6,787,010
60
2011-07-22T07:38:44Z
[ "python" ]
I have the following code in a python script: ``` def fun() #Code here fun() ``` I want to execute this script and also find out how much time it took to execute in minutes. How to find out how much time it took for this script to execute ?.Some example would be really appreciated. Thank You
Do you execute the script from the command line on Linux or UNIX? In that case, you could just use ``` time ./script.py ```
Find out time it took for a python script to complete execution
6,786,990
59
2011-07-22T07:36:03Z
6,787,661
11
2011-07-22T08:49:25Z
[ "python" ]
I have the following code in a python script: ``` def fun() #Code here fun() ``` I want to execute this script and also find out how much time it took to execute in minutes. How to find out how much time it took for this script to execute ?.Some example would be really appreciated. Thank You
What I usually do is use `clock()` or `time()` from the `time` library. `clock` measures interpreter time, while `time` measures system time. Additional caveats can be found in the [docs](http://docs.python.org/library/time.html). For example, ``` def fn(): st = time() dostuff() print 'fn took %.2f second...
Find out time it took for a python script to complete execution
6,786,990
59
2011-07-22T07:36:03Z
6,791,946
26
2011-07-22T15:02:59Z
[ "python" ]
I have the following code in a python script: ``` def fun() #Code here fun() ``` I want to execute this script and also find out how much time it took to execute in minutes. How to find out how much time it took for this script to execute ?.Some example would be really appreciated. Thank You
``` import time start = time.time() fun() print 'It took', time.time()-start, 'seconds.' ```
How can I install various Python libraries in Jython?
6,787,015
39
2011-07-22T07:39:34Z
6,787,069
31
2011-07-22T07:45:23Z
[ "java", "python", "jython", "pip", "easy-install" ]
I know that I can install Jython with Java and that I can use Jython where I use Python. The Jython shell is working fine. In Jython, how can I install libraries like `lxml`, `Scrappy` and `BeautifulSoup` that I'd normally install via `pip` or `easy_install`
Some Python modules, like `lxml`, have required components in C. These won't work in Jython. Most Python packages will work fine, and you can install them using the same tools as you use in CPython. This is [described in Appendix A of Jython Book](http://www.jython.org/jythonbook/en/1.0/appendixA.html#setuptools): > ...
How to save progressive jpeg using Python PIL 1.1.7?
6,788,398
17
2011-07-22T09:58:34Z
6,789,301
13
2011-07-22T11:27:50Z
[ "python", "python-imaging-library" ]
I'm trying to save with the following call and it raises error, but if i remove progressive and optimize options, it saves. Here is my test.py that doesn't work: ``` import Image img = Image.open("in.jpg") img.save("out.jpg", "JPEG", quality=80, optimize=True, progressive=True) ``` It raises this error: ``` Suspens...
Here's a hack that might work, but you may need to make the buffer even larger: ``` from PIL import Image, ImageFile ImageFile.MAXBLOCK = 2**20 img = Image.open("in.jpg") img.save("out.jpg", "JPEG", quality=80, optimize=True, progressive=True) ```
How to save progressive jpeg using Python PIL 1.1.7?
6,788,398
17
2011-07-22T09:58:34Z
6,789,306
32
2011-07-22T11:28:13Z
[ "python", "python-imaging-library" ]
I'm trying to save with the following call and it raises error, but if i remove progressive and optimize options, it saves. Here is my test.py that doesn't work: ``` import Image img = Image.open("in.jpg") img.save("out.jpg", "JPEG", quality=80, optimize=True, progressive=True) ``` It raises this error: ``` Suspens...
``` import PIL from exceptions import IOError img = PIL.Image.open("c:\\users\\adam\\pictures\\in.jpg") destination = "c:\\users\\adam\\pictures\\test.jpeg" try: img.save(destination, "JPEG", quality=80, optimize=True, progressive=True) except IOError: PIL.ImageFile.MAXBLOCK = img.size[0] * img.size[1] img...
How can I get this Python code to run more quickly? [Project Euler Problem #7]
6,789,649
3
2011-07-22T11:58:16Z
6,789,734
11
2011-07-22T12:05:17Z
[ "python", "performance", "interpreter" ]
I'm trying to complete this Project Euler challenge: > By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can > see that the 6th prime is 13. > > What is the 10 001st prime number? My code seem to be right because it works with small numbers, e.g 6th prime is 13. How can i improve it so that the code...
A few questions to ponder: * Do you really need to check the division until n-1? How earlier can you stop? * Apart from 2, do you really need to check the division by all the multiples of two ? * What about the multiples of 3? 5? Is there a way to extend this idea to all the multiples of previously tested primes?
How can I get this Python code to run more quickly? [Project Euler Problem #7]
6,789,649
3
2011-07-22T11:58:16Z
6,789,780
10
2011-07-22T12:08:36Z
[ "python", "performance", "interpreter" ]
I'm trying to complete this Project Euler challenge: > By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can > see that the 6th prime is 13. > > What is the 10 001st prime number? My code seem to be right because it works with small numbers, e.g 6th prime is 13. How can i improve it so that the code...
The purpose of Project Euler is not really to think learn programming, but to think about **algorithms**. On problem #10, your algorithm will need to be even faster than on #7, etc. etc. So you need to come up with a better way to find prime numbers, not a faster way to run Python code. People solve these problems unde...
Is there a python module to solve linear equations?
6,789,927
28
2011-07-22T12:19:39Z
6,789,948
14
2011-07-22T12:21:39Z
[ "python" ]
I want to solve a linear equation with three or more variables. Is there a good library in python to do it?
See <http://sympy.org/> and <http://numpy.scipy.org/>. Specifically, <http://docs.scipy.org/doc/numpy/reference/routines.linalg.html> And <http://docs.sympy.org/0.7.0/tutorial.html#algebra>, <http://docs.sympy.org/dev/modules/solvers/solvers.html> Edit: Added solvers link from the comment.
Is there a python module to solve linear equations?
6,789,927
28
2011-07-22T12:19:39Z
6,789,990
45
2011-07-22T12:24:42Z
[ "python" ]
I want to solve a linear equation with three or more variables. Is there a good library in python to do it?
Yes, the very-popular [NumPy](http://numpy.scipy.org/) package has [a function to do this](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.solve.html). Their example: > Solve the system of equations `3 * x0 + x1 = 9` and `x0 + 2 * x1 = 8`: > > ``` > >>> import numpy as np > >>> a = np.array([[3,1], [1...
What is the benefit to define a function in a function in python?
6,791,198
14
2011-07-22T14:04:05Z
6,791,250
32
2011-07-22T14:07:40Z
[ "python", "function", "syntax" ]
I encountered this piece of python code (pasted below) on [effbot](http://effbot.org/zone/re-sub.htm#unescape-html) and I was wondering: **Why defining a function within a function?** ``` import re, htmlentitydefs ## # Removes HTML or XML character references and entities from a text string. # # @param text The HTML...
> Why defining a function within a function? To keep it isolated. It's only used in this one place. Why define it more globally when it's used locally?
GDAL WriteArray issue
6,791,233
3
2011-07-22T14:06:39Z
6,865,109
9
2011-07-28T20:15:35Z
[ "python", "gdal" ]
I'm utilizing python GDAL to write a raster data into a .tif file. Here's the code: ``` import numpy, sys from osgeo import gdal, utils from osgeo.gdalconst import * # register all of the GDAL drivers gdal.AllRegister() # open the image inDs = gdal.Open("C:\\Documents and Settings\\patrick\\Desktop\\tiff elevation\\...
You don't need to `Create` then `Open` a raster (which you were reading `GA_ReadOnly`). You also don't need `gdal.AllRegister()` at the beginning, as it has already been called when you load GDAL into Python (see the [GDAL API Tutorial](http://www.gdal.org/gdal_tutorial.html)). Picking up somewhere above (with modific...
Execute code when Django starts ONCE only?
6,791,911
69
2011-07-22T15:00:10Z
6,792,076
46
2011-07-22T15:11:17Z
[ "python", "django" ]
I'm writing a Django Middleware class that I want to execute only once at startup, to initialise some other arbritary code. I've followed the very nice solution posted by sdolan [here](http://stackoverflow.com/questions/3495964/in-django-how-do-i-call-the-subcommand-syncdb-from-the-initialization-script), but the "Hell...
Don't do it this way. You don't want "middleware" for a one-time startup thing. You want to execute code in the top-level `urls.py`. That module is imported and executed once. `urls.py` ``` from django.confs.urls.defaults import * from my_app import one_time_startup urlpatterns = ... one_time_startup() ```
Execute code when Django starts ONCE only?
6,791,911
69
2011-07-22T15:00:10Z
16,111,968
107
2013-04-19T19:15:19Z
[ "python", "django" ]
I'm writing a Django Middleware class that I want to execute only once at startup, to initialise some other arbritary code. I've followed the very nice solution posted by sdolan [here](http://stackoverflow.com/questions/3495964/in-django-how-do-i-call-the-subcommand-syncdb-from-the-initialization-script), but the "Hell...
## Update: Django 1.7 now has a [hook for this](https://docs.djangoproject.com/en/dev/ref/applications/#django.apps.AppConfig.ready) file: `myapp/apps.py` ``` from django.apps import AppConfig class MyAppConfig(AppConfig): name = 'myapp' verbose_name = "My Application" def ready(self): pass # star...
Execute code when Django starts ONCE only?
6,791,911
69
2011-07-22T15:00:10Z
19,689,002
18
2013-10-30T16:50:20Z
[ "python", "django" ]
I'm writing a Django Middleware class that I want to execute only once at startup, to initialise some other arbritary code. I've followed the very nice solution posted by sdolan [here](http://stackoverflow.com/questions/3495964/in-django-how-do-i-call-the-subcommand-syncdb-from-the-initialization-script), but the "Hell...
This question is well-answered in the blog post [Entry point hook for Django projects](http://eldarion.com/blog/2013/02/14/entry-point-hook-django-projects/), which will work for Django >= 1.4. Basically, you can use `<project>/wsgi.py` to do that, and it will be run only once, when the server starts, but not when you...
Execute code when Django starts ONCE only?
6,791,911
69
2011-07-22T15:00:10Z
32,510,585
7
2015-09-10T19:57:35Z
[ "python", "django" ]
I'm writing a Django Middleware class that I want to execute only once at startup, to initialise some other arbritary code. I've followed the very nice solution posted by sdolan [here](http://stackoverflow.com/questions/3495964/in-django-how-do-i-call-the-subcommand-syncdb-from-the-initialization-script), but the "Hell...
If it helps someone, in addition to [pykler's](http://stackoverflow.com/users/742390/pykler) answer, "--noreload" option prevents runserver from executing command on startup twice: ``` python manage.py runserver --noreload ``` But that command won't reload runserver after other code's changes as well.
How to mask numpy structured array on multiple columns?
6,792,395
8
2011-07-22T15:34:50Z
6,792,497
9
2011-07-22T15:42:25Z
[ "python", "numpy", "mask", "masked-array" ]
I have a numpy structured array with a dtype such as: ``` A = numpy.empty(10, dtype=([('segment', '<i8'), ('material', '<i8'), ('rxN', '<i8')])) ``` I know I can create a mask such as: ``` A[A['segment'] == 42] = ... ``` Is there a way to create a mask on multiple columns? For example (I know this doesn't work, but...
You can use the `&` operator instead of `and`: ``` A[(A['segment'] == 42) & (A['material'] == 5)] ``` Note that extra parantheses are required.
Auto Increment on Composite Primary Key - Sqlite3 + Python
6,793,205
2
2011-07-22T16:38:54Z
6,793,274
9
2011-07-22T16:44:24Z
[ "python", "sqlite3" ]
I have a code like this ``` c.execute('CREATE TABLE IF NOT EXISTS base (ID INTEGER NOT NULL, col2 TEXT NOT NULL, col3 INTEGER, PRIMARY KEY(ID, col2))') ``` This code gives me an **sqlite3.IntegrityError** exception even though I am very sure that I am writing the record for the first time. So, I tried ``` c.execute...
In sqlite, you only get autoincrement behavior when only one integer column is the primary key. composite keys prevent autoincrement from taking effect. You can get a similar result by defining `id` as the only primary key, but then adding an additional unique constraint on `id, col3`. If that's still not quite what ...
Python, doing conditional imports the right way
6,793,748
5
2011-07-22T17:25:39Z
6,794,451
11
2011-07-22T18:25:48Z
[ "python", "import", "conditional", "factory-pattern" ]
Right now I have a class called A. I have some code like this.. ``` from my.package.location.A import A ... foo = A.doSomething(bar) ``` This is great. But now I have a new version of A called A, but in a different package, but I only want to use this other A in a certain scenario. So I can do something like thi...
Put your lines into a\_finder.py: ``` if OldVersion: from my.package.location.A import A else: from new.package.location.A import A ``` Then in your product code: ``` from a_finder import A ``` and you will get the proper A.
Variable assignment and modification (in python)
6,793,872
10
2011-07-22T17:36:46Z
6,793,905
10
2011-07-22T17:39:39Z
[ "python", "list", "variables" ]
When I ran this script (Python v2.6): ``` a = [1,2] b = a a.append(3) print a >>>> [1,2,3] print b >>>> [1,2,3] ``` I expected `print b` to output `[1,2]`. Why did b get changed when all I did was change a? Is b permanently tied to a? If so, can I make them independent? How?
Objects in Python are stored by reference—you aren't assigning the value of `a` to `b`, but a pointer to the object that `a` is pointing to. To emulate assignation by value, you can make a copy like so: ``` import copy b = copy.copy(a) # now the code works as "expected" ``` Be aware this has performance disadvan...
Variable assignment and modification (in python)
6,793,872
10
2011-07-22T17:36:46Z
6,794,990
27
2011-07-22T19:21:15Z
[ "python", "list", "variables" ]
When I ran this script (Python v2.6): ``` a = [1,2] b = a a.append(3) print a >>>> [1,2,3] print b >>>> [1,2,3] ``` I expected `print b` to output `[1,2]`. Why did b get changed when all I did was change a? Is b permanently tied to a? If so, can I make them independent? How?
Memory management in Python involves a private heap memory location containing all Python objects and data structures. Python's runtime only deals in references to objects (which all live in the heap): what goes on Python's stack are always references to values that live elsewhere. ``` >>> a = [1, 2] ``` ![python va...
Python function "remembering" earlier argument (**kwargs)
6,794,285
4
2011-07-22T18:12:23Z
6,794,329
10
2011-07-22T18:15:37Z
[ "python", "kwargs" ]
I have some objects that have a dictionary of attributes, `obj.attrs`. The constructor for these objects accepts a dict and/or `**kwargs`, for convenience. It looks a little like this: ``` class Thing: def __init__(self, attrs={}, **kwargs): for arg in kwargs: attrs[arg] = kwargs[arg] ...
The problem with using default arguments is that only one instance of them actually exists. When you say `attrs={}` in your **init** method definition, that single default {} instance is the default for every call to that method (it doesn't make a new default empty dict every time, it uses the same one). The problem i...
JSON vs. Pickle security
6,794,454
6
2011-07-22T18:26:17Z
6,794,484
10
2011-07-22T18:29:21Z
[ "python", "json", "pickle" ]
I recently came across the security problems of the Python pickle and cPickle modules. Obviously, there are no real security measures implemented in pickle unless you overwrite the find\_class method as a basic modification to get a bit more security. But I often heard that JSON is more secure. Can anyone elaborate a ...
json is more secure because it's fundamentally more limited. The only python types that a json document can encode are `unicode`, `int`, `float`, `NoneType`, `bool`, `list` and `dict`. these are marshaled/unmarshalled in a basically trivial fashion that isn't vulnerable to code injection attacks.
Creating a dict from list of key, value tuples while maintaining duplicate keys
6,795,361
8
2011-07-22T19:54:53Z
6,795,385
16
2011-07-22T19:56:51Z
[ "python" ]
So I've got a comprehension to the effect of: ``` dict((x.key, x.value) for x in y) ``` The problem, of course, is that if there's multiple `x.key`s with the same value, they get collapsed with the last `x.value` with that particular `x.key` as the only surviving member. I want to actually make the values of the resu...
You can add the elements one by one to a dictionary that contains empty lists by default: ``` import collections result_dict = collections.defaultdict(list) for x in y: result_dict[x.key].append(x.value) ``` You can also do something very similar without having to use the collections module: ``` result_dict = {...
SQLite database file size didn't shrink after dropping huge table
6,795,444
2
2011-07-22T20:01:24Z
6,795,465
9
2011-07-22T20:03:01Z
[ "python", "sqlite", "sqlite3" ]
I created a table in my database file which turned out to be way too huge (increased my database file's size from 2 GB to around 50GB). I just dropped it but the file size didn't go down. Any way to get the db file back to normal? I'm using sqlite3 from Python.
Try [vacuum](http://www.sqlite.org/lang_vacuum.html).
Numpy: arr[...,0,:] works. But how do I store the data contained in the slice command (..., 0, :)?
6,795,657
5
2011-07-22T20:20:08Z
6,795,738
9
2011-07-22T20:26:58Z
[ "python", "indexing", "numpy", "slice" ]
In Numpy (and Python in general, I suppose), how does one store a slice-index, such as (...,0,:), in order to pass it around and apply it to various arrays? It would be nice to, say, be able to pass a slice-index to and from functions.
Python creates special objects out of the slice syntax, but only inside the square brackets for indexing. You can either create those objects by hand (in this case, `(...,0,:)` is `(Ellipsis, 0, slice(None, None, None))`, or you can create a little helper object: ``` class ExtendedSliceMaker(object): def __getitem...
Temporarily Redirect stdout/stderr
6,796,492
43
2011-07-22T21:49:53Z
6,796,536
13
2011-07-22T21:56:37Z
[ "python", "redirect", "stdout", "stderr" ]
Is it possible to temporarily redirect stdout/stderr in Python (i.e. for the duration of a method)? ### Edit: The problem with the current solutions (which I at first remembered but then forgot) is that they don't *redirect*; rather, they just replace the streams in their entirety. Hence, if a method has a ***local* ...
I am not sure what temporary redirection means. But, you can reassign streams like this and reset it back. ``` temp = sys.stdout sys.stdout = sys.stderr sys.stderr = temp ``` Also to write to sys.stderr within print stmts like this. ``` print >> sys.stderr, "Error in atexit._run_exitfuncs:" ``` Regular print will ...
Temporarily Redirect stdout/stderr
6,796,492
43
2011-07-22T21:49:53Z
6,796,539
10
2011-07-22T21:56:55Z
[ "python", "redirect", "stdout", "stderr" ]
Is it possible to temporarily redirect stdout/stderr in Python (i.e. for the duration of a method)? ### Edit: The problem with the current solutions (which I at first remembered but then forgot) is that they don't *redirect*; rather, they just replace the streams in their entirety. Hence, if a method has a ***local* ...
It's possible with a decorator such as the following: ``` import sys def redirect_stderr_stdout(stderr=sys.stderr, stdout=sys.stdout): def wrap(f): def newf(*args, **kwargs): old_stderr, old_stdout = sys.stderr, sys.stdout sys.stderr = stderr sys.stdout = stdout ...
Temporarily Redirect stdout/stderr
6,796,492
43
2011-07-22T21:49:53Z
6,796,752
66
2011-07-22T22:29:09Z
[ "python", "redirect", "stdout", "stderr" ]
Is it possible to temporarily redirect stdout/stderr in Python (i.e. for the duration of a method)? ### Edit: The problem with the current solutions (which I at first remembered but then forgot) is that they don't *redirect*; rather, they just replace the streams in their entirety. Hence, if a method has a ***local* ...
You can also put the redirection logic in a contextmanager. ``` import os import sys class RedirectStdStreams(object): def __init__(self, stdout=None, stderr=None): self._stdout = stdout or sys.stdout self._stderr = stderr or sys.stderr def __enter__(self): self.old_stdout, self.old_s...
Temporarily Redirect stdout/stderr
6,796,492
43
2011-07-22T21:49:53Z
22,434,728
10
2014-03-16T08:37:10Z
[ "python", "redirect", "stdout", "stderr" ]
Is it possible to temporarily redirect stdout/stderr in Python (i.e. for the duration of a method)? ### Edit: The problem with the current solutions (which I at first remembered but then forgot) is that they don't *redirect*; rather, they just replace the streams in their entirety. Hence, if a method has a ***local* ...
To solve the issue that some function might have cached `sys.stdout` stream as a local variable and therefore replacing the global `sys.stdout` won't work inside that function, you could redirect at a file descriptor level (`sys.stdout.fileno()`) e.g.: ``` from __future__ import print_function import os import sys de...
Use of return in long if-elseif-else statements (Python)
6,796,523
7
2011-07-22T21:54:41Z
6,796,614
10
2011-07-22T22:07:33Z
[ "python", "coding-style", "refactoring", "if-statement" ]
I am using Python for my example, but my question is referring to programmming languages in general. ``` def some_function(eggs): if eggs == 1: do_something_1() elif eggs == 2: do_something_2() elif eggs == 3: do_something_3() else: do_error() return do_somet...
The main issue I see with your code is that the error case is hidden more than half way down the function body. It makes the code difficult to read. Since what you are doing is validating the arguments to the function, you should do that first. My preference in the case of an invalid argument is to raise an appropriat...
Use of return in long if-elseif-else statements (Python)
6,796,523
7
2011-07-22T21:54:41Z
6,796,618
8
2011-07-22T22:08:06Z
[ "python", "coding-style", "refactoring", "if-statement" ]
I am using Python for my example, but my question is referring to programmming languages in general. ``` def some_function(eggs): if eggs == 1: do_something_1() elif eggs == 2: do_something_2() elif eggs == 3: do_something_3() else: do_error() return do_somet...
Definitely **do not** copy identical code into each `if` clause. How about: ``` def some_function(eggs): options = {1: do_something_1, 2: do_something_2, 3: do_something_3} if eggs in options: options[eggs]() do_something_4() do_something_5() do_something_6() else: ...
Yahoo BOSS V2 authorization troubles
6,796,722
8
2011-07-22T22:24:02Z
7,696,492
7
2011-10-08T11:29:39Z
[ "python", "oauth", "yahoo" ]
I'm having an awfully hard time with Yahoo's authentication/authorization. I've enabled BOSS in my account, set up a payment method, and now I'm trying to run a search using some python code: ``` import urllib2 import oauth2 as oauth import time OAUTH_CONSUMER_KEY = "blahblahblah" OAUTH_CONSUMER_SECRET = "blah" def ...
I made some small changes to make your example work. See code for comments. ``` import urllib2 import oauth2 as oauth import time OAUTH_CONSUMER_KEY = "blahblahblah" OAUTH_CONSUMER_SECRET = "blah" def oauth_request(url, params, method="GET"): # Removed trailing commas here - they make a difference. params['o...
Call super().__init__() in classes derived from `object`?
6,796,996
10
2011-07-22T23:00:36Z
6,797,008
13
2011-07-22T23:02:44Z
[ "python" ]
The Python [documentation](http://docs.python.org/reference/datamodel.html?highlight=__init__#object.__init__) says that the `__init__` method of each class is responsible for initializing its super class. But for new-style classes, the ultimate base class is `object`. Doing `dir(object)` shows that `object` itself has...
You don't *need* to initialize `object`; its `__init__` is a no-op. It's still good practice, though, as you might want to introduce an intermediate class in the hierarchy later on.
Why doesnt Pythons += (plus equals) operator modify variables from inner functions?
6,797,164
5
2011-07-22T23:29:32Z
6,797,200
10
2011-07-22T23:36:39Z
[ "python", "list", "scope" ]
I would like to know details about why this doesn't work as expected: ``` def outer(): mylist = [] def inner(): mylist += [1] inner() outer() ``` Especially because `mylist.__iadd__([1])` works fine.
The problem is that when you assign to a variable name inside a function, Python assumes you're trying to create a new local variable that will mask a similarly-named variable in outer scope. Since `+=` has to *get* the value of `mylist` before it can modify it, it complains, because the local version of `mylist` isn't...
Getting the Parameter name of a Value in a URL request
6,797,354
4
2011-07-23T00:11:13Z
6,797,388
8
2011-07-23T00:17:33Z
[ "python", "google-app-engine", "url", "urlparse" ]
I have a Python App Engine web app class that I am accessing with the following POST url: `http://localhost:8087/moderate?5649364211118945661=on` How can I get the **Parameter** name - not the **value** of the `5649364211118945661`parameter, but a list of all the parameter names that contain the `on` value. For examp...
Use urlparse, <http://docs.python.org/library/urlparse.html>. ``` import urlparse url = urlparse.urlparse('http://localhost:8087/moderate?5649364211118945661=on&23984729386481734=on&456287432349725=on&6753847523429875=off') query = urlparse.parse_qs(url.query) print [key for key, value in query.iteritems() if value ==...
How to convert string to lowercase in Python?
6,797,984
827
2011-07-23T03:08:53Z
6,797,990
1,385
2011-07-23T03:09:58Z
[ "python", "string", "unicode", "uppercase", "lowercase" ]
Is there any way to convert an entire user inputted string from uppercase, or even part uppercase to lowercase? E.g. Kilometers --> kilometers.
``` s = "Kilometer" print(s.lower()) ``` Official documentation [here](https://docs.python.org/3.4/library/stdtypes.html?highlight=str.lower#str.lower)
How to convert string to lowercase in Python?
6,797,984
827
2011-07-23T03:08:53Z
6,798,246
59
2011-07-23T04:34:10Z
[ "python", "string", "unicode", "uppercase", "lowercase" ]
Is there any way to convert an entire user inputted string from uppercase, or even part uppercase to lowercase? E.g. Kilometers --> kilometers.
You can do what Peter said, or if you want the user to input something you could do this: ``` raw_input('Type Something').lower() ``` It will then automatically convert the thing they typed into lowercase. :) Note: `raw_input` was renamed to `input` in Python 3.x and above.
How to convert string to lowercase in Python?
6,797,984
827
2011-07-23T03:08:53Z
20,055,196
15
2013-11-18T18:35:07Z
[ "python", "string", "unicode", "uppercase", "lowercase" ]
Is there any way to convert an entire user inputted string from uppercase, or even part uppercase to lowercase? E.g. Kilometers --> kilometers.
also, you can overwrite some variables: ``` s = input('UPPER CASE') lower = s.lower() ``` if you use like this: ``` s = "Kilometer" print(s.lower()) - kilometer print(s) - Kilometer ``` it will work just when call.
How to convert string to lowercase in Python?
6,797,984
827
2011-07-23T03:08:53Z
26,175,350
53
2014-10-03T08:02:17Z
[ "python", "string", "unicode", "uppercase", "lowercase" ]
Is there any way to convert an entire user inputted string from uppercase, or even part uppercase to lowercase? E.g. Kilometers --> kilometers.
This doesn't work for non-english words in utf-8. In this case `decode('utf-8')` can help. ``` >>> s='Километр' >>> print s.lower() Километр >>> print s.decode('utf-8').lower() километр ```
How to convert string to lowercase in Python?
6,797,984
827
2011-07-23T03:08:53Z
31,599,276
29
2015-07-23T22:40:45Z
[ "python", "string", "unicode", "uppercase", "lowercase" ]
Is there any way to convert an entire user inputted string from uppercase, or even part uppercase to lowercase? E.g. Kilometers --> kilometers.
> # How to convert string to lowercase in Python? > > Is there any way to convert an entire user inputted string from uppercase, or even part uppercase to lowercase? > > E.g. Kilometers --> kilometers The canonical Pythonic way of doing this is ``` >>> 'Kilometers'.lower() 'kilometers' ``` ## Unicode Python 3 [Pyth...
Python String Concatenation - concatenating '\n'
6,800,040
8
2011-07-23T11:22:44Z
6,800,063
16
2011-07-23T11:28:32Z
[ "python", "repeater", "newline", "concatenation" ]
I am new to Python and need help trying to understand two problems i am getting relating to concatenating strings. I am aware that strings can be added to concatenate each other using + symbol like so. ``` >>> 'a' + 'b' 'ab' ``` However, i just recently found out you do not even need to use the + symbol to concatenat...
When `"a" "b"` is turned into `"ab"`, this ins't the same as concatenating the strings with `+`. When the Python source code is being read, adjacent strings are automatically joined for convenience. This isn't a normal operation, which is why it isn't following the order of operations you expect for `+` and `*`. ``` ...
What is the most efficient way of finding all the factors of a number in Python?
6,800,193
61
2011-07-23T12:00:18Z
6,800,214
134
2011-07-23T12:04:32Z
[ "python", "performance", "algorithm", "factorization" ]
Can someone explain to me an efficient way of finding all the factors of a number in Python (2.7)? I can create algorithms to do this job, but i think it is poorly coded, and takes too long to execute a result for a large numbers.
``` def factors(n): return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))) ``` This will return all of the factors, very quickly, of a number `n`. Why square root as the upper limit? `sqrt(x) * sqrt(x) = x`. So if the two factors are the same, they're ...
What is the most efficient way of finding all the factors of a number in Python?
6,800,193
61
2011-07-23T12:00:18Z
6,800,586
10
2011-07-23T13:10:10Z
[ "python", "performance", "algorithm", "factorization" ]
Can someone explain to me an efficient way of finding all the factors of a number in Python (2.7)? I can create algorithms to do this job, but i think it is poorly coded, and takes too long to execute a result for a large numbers.
An alternative approach to agf's answer: ``` def factors(n): result = set() for i in range(1, int(n ** 0.5) + 1): div, mod = divmod(n, i) if mod == 0: result |= {i, div} return result ```
What is the most efficient way of finding all the factors of a number in Python?
6,800,193
61
2011-07-23T12:00:18Z
6,909,532
19
2011-08-02T08:57:08Z
[ "python", "performance", "algorithm", "factorization" ]
Can someone explain to me an efficient way of finding all the factors of a number in Python (2.7)? I can create algorithms to do this job, but i think it is poorly coded, and takes too long to execute a result for a large numbers.
agf's answer is really quite cool. I wanted to see if I could rewrite it to avoid using `reduce()`. This is what I came up with: ``` import itertools flatten_iter = itertools.chain.from_iterable def factors(n): return set(flatten_iter((i, n//i) for i in range(1, int(n**0.5)+1) if n % i == 0)) ``` ...
What is the most efficient way of finding all the factors of a number in Python?
6,800,193
61
2011-07-23T12:00:18Z
19,578,818
19
2013-10-24T23:57:04Z
[ "python", "performance", "algorithm", "factorization" ]
Can someone explain to me an efficient way of finding all the factors of a number in Python (2.7)? I can create algorithms to do this job, but i think it is poorly coded, and takes too long to execute a result for a large numbers.
The solution presented by @agf is great, but one can achieve ~50% faster run time for an arbitrary **odd** number by checking for parity. As the factors of an odd number always are odd themselves, it is not necessary to check these when dealing with odd numbers. I've just started solving [Project Euler](http://en.wiki...
Python map object is not subscriptable
6,800,481
14
2011-07-23T12:52:14Z
6,800,507
23
2011-07-23T12:56:00Z
[ "python", "python-3.x" ]
Why does the following script give the error: `payIntList[i] = payIntList[i] + 1000 TypeError: 'map' object is not subscriptable` ``` payList = [] numElements = 0 while True: payValue = raw_input("Enter the pay amount: ") numElements = numElements + 1 payList.append(payValue) choice...
In Python 3, `map` returns an iterable object of type `map`, and not a subscriptible list, which would allow you to write `map[i]`. To force a list result, write ``` payIntList = list(map(int,payList)) ``` However, in many cases, you can write out your code way nicer by not using indices. For example, with [list comp...
Installing MatplotLib in mac osx lion
6,800,488
17
2011-07-23T12:53:35Z
6,809,293
9
2011-07-24T19:59:36Z
[ "python", "osx", "matplotlib", "osx-lion" ]
I was trying to install matplotlib in Mac OSX Lion. Tried to used the binary that is in the sourcefourge site, but I got this error: "matplotlib requires System Python 2.7 to install". I went to the Terminal and typed python --version and its check the requirements. After this I tried to used the pip, and while doing...
This is because of a change in the API for libpng v1.5 (which is included with Mac OSX Lion). The changes has already been pushed upstream, so you will need to compile from the upstream repository until the next release. You can follow the instructions on <http://jholewinski.wordpress.com/2011/07/21/installing-matplot...
Django returns 403 error when sending a POST request
6,800,894
19
2011-07-23T14:04:54Z
6,801,207
21
2011-07-23T14:58:53Z
[ "python", "django", "http-status-code-403", "http-post" ]
when I'm using following Python code to send a POST request to my Django website I'm getting 403: Forbidden error. ``` url = 'http://www.sub.domain.com/' values = { 'var': 'test' } try: data = urllib.urlencode(values, doseq=True) req = urllib2.Request(url, data) response = urllib2.urlopen(req) the_pag...
Does the view that you are posting to have a Django Form on it? If so, I wonder if it's giving a csrf error. I think that manifests itself as a 403. In that case, you'd need to add the {{ csrf\_token }} tag. Just a thought.
Django returns 403 error when sending a POST request
6,800,894
19
2011-07-23T14:04:54Z
6,801,448
38
2011-07-23T15:37:27Z
[ "python", "django", "http-status-code-403", "http-post" ]
when I'm using following Python code to send a POST request to my Django website I'm getting 403: Forbidden error. ``` url = 'http://www.sub.domain.com/' values = { 'var': 'test' } try: data = urllib.urlencode(values, doseq=True) req = urllib2.Request(url, data) response = urllib2.urlopen(req) the_pag...
Look here <https://docs.djangoproject.com/en/dev/ref/csrf/#how-to-use-it>. Try marking your view with `@csrf_exempt`. That way, Django's CSRF middleware will ignore CSRF protection. You'll also need to use `from django.views.decorators.csrf import csrf_exempt`. See: <https://docs.djangoproject.com/en/dev/ref/csrf/#uti...
Python: How to pass and run a callback method in Python
6,800,984
11
2011-07-23T14:22:27Z
6,801,633
12
2011-07-23T16:06:43Z
[ "python", "multithreading", "callback", "notifications" ]
I have a Manager (main thread), that creates other Threads to handle various operations. I would like my Manager to be notified when a Thread it created ends (when run() method execution is finished). I know I could do it by checking the status of all my threads with the Thread.isActive() method, but polling sucks, so...
The thread can't call the manager unless it has a reference to the manager. The easiest way for that to happen is for the manager to give it to the thread at instantiation. ``` class Manager(object): def new_thread(self): return MyThread(parent=self) def on_thread_finished(self, thread, data): ...
Python - From DST-adjusted local time to UTC
6,801,429
5
2011-07-23T15:34:16Z
6,802,306
7
2011-07-23T18:09:41Z
[ "python", "timezone", "utc", "dst", "pytz" ]
A specific bank has branches in all major cities in the world. They all open at 10:00 AM local time. If within a timezone that uses DST, then of course the local opening time also follows the DST-adjusted time. So how do I go from the local time to the utc time. What I need is a function `to_utc(localdt, tz)` like thi...
Using [pytz](http://pytz.sourceforge.net/), and in particular its [localize method](http://pytz.sourceforge.net/#localized-times-and-date-arithmetic): ``` import pytz import datetime as dt def to_utc(localdt,tz): timezone=pytz.timezone(tz) utc=pytz.utc return timezone.localize(localdt).astimezone(utc) if...
How do I get the IDENTITY / AUTONUMBER value for the row I inserted in pymysql
6,802,061
2
2011-07-23T17:22:23Z
6,802,069
7
2011-07-23T17:24:27Z
[ "python", "mysql" ]
Is possible to get ID for the row I inserted using pymysql? ``` curr = db.cursor() curr.execute("INSERT INTO `accounts` (`name`, `password`) VALUES ('%s', '%s')", accName, passwd) curr.execute("INSERT INTO `person` (`name`, `accoiunt_id`) VALUES ('%s', '%d')", pName, HERE_I_NEED_ACCID) ``` There is autoincrement prim...
You can use `lastrowid` property of your cursor object. Or you can execute [`SELECT LAST_INSERT_ID()`](http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id), and fetch the result as scalar with `fetchone()`
Python - Rotation of 3D vector
6,802,577
28
2011-07-23T18:57:33Z
6,802,723
53
2011-07-23T19:20:52Z
[ "python", "vector", "rotation" ]
I have two vectors as Python lists and an angle. E.g.: ``` v = [3,5,0] axis = [4,4,1] theta = 1.2 #radian ``` What is the best/easiest way to get the resulting vector when rotating the v vector around the axis? The rotation should appear to be counter clockwise for an observer to whom the axis vector is pointing. Th...
Using the [Euler-Rodrigues formula](http://en.wikipedia.org/wiki/Euler%E2%80%93Rodrigues_parameters): ``` import numpy as np import math def rotation_matrix(axis, theta): """ Return the rotation matrix associated with counterclockwise rotation about the given axis by theta radians. """ axis = np.a...