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
Django: "projects" vs "apps"
4,879,036
142
2011-02-02T19:41:49Z
4,880,013
7
2011-02-02T21:22:37Z
[ "python", "django", "namespaces", "project-organization" ]
I have a fairly complex "product" I'm getting ready to build using Django. I'm going to avoid using the terms "project" and "application" in this context, because I'm not clear on their specific meaning in Django. Projects can have many apps. Apps can be shared among many projects. Fine. I'm not reinventing the blog ...
> If so... in terms of Django's project.app namespace, my inclination is to usemyproduct.myproduct, but of course this isn't allowed There is nothing like not allowed. Its your project, no one is restricting you. It is advisable to keep a reasonable name. > I don't see any portion of my product being reusable in any ...
Django: "projects" vs "apps"
4,879,036
142
2011-02-02T19:41:49Z
15,435,556
47
2013-03-15T14:58:37Z
[ "python", "django", "namespaces", "project-organization" ]
I have a fairly complex "product" I'm getting ready to build using Django. I'm going to avoid using the terms "project" and "application" in this context, because I'm not clear on their specific meaning in Django. Projects can have many apps. Apps can be shared among many projects. Fine. I'm not reinventing the blog ...
Once you graduate from using `startproject` and `startapp`, there's nothing to stop you from combining a "project" and "app" in the same Python package. A project is really nothing more than a `settings` module, and an app is really nothing more than a `models` module—everything else is optional. For small sites, it...
Python: How to use a list comprehension here?
4,879,641
4
2011-02-02T20:44:27Z
4,879,676
10
2011-02-02T20:48:14Z
[ "python", "list-comprehension" ]
I have data of the following form: ``` foos = [{'bar': [{'baz': 1}, {'baz': 2}]}, {'bar': [{'baz': 3}, {'baz': 4}]}, {'bar': [{'baz': 5}, {'baz': 6}]}] ``` I want a list comprehension that will yield: ``` [1, 2, 3, 4, 5, 6] ``` I'm not quite sure how to go about doing this. This sorta works: ``` >>> [[bar['baz'] f...
Instead of nesting list comprehensions, you can do it with two `for .. in` clauses in one list comprehension: ``` In [19]: [item['baz'] for foo in foos for item in foo['bar']] Out[19]: [1, 2, 3, 4, 5, 6] ``` Note that ``` [... for foo in foos for item in foo['bar']] ``` translates roughly into ``` for foo in foos:...
How to pass the remote IP to a proxied service? - Nginx
4,880,283
11
2011-02-02T21:51:52Z
4,880,480
17
2011-02-02T22:08:55Z
[ "python", "django", "ubuntu", "nginx", "gevent" ]
I'm running a service in localhost at `127.0.01:8000` and I'm proxying this by using: ``` proxy_pass http://127.0.0.1:8000; ``` **Problem is that I need to pass the user's IP address to the service.** --- Any ideas?
I send the real IP to django by setting a custom header: `proxy_set_header X-Real-IP $remote_addr;` Those headers are available in `request.META`
How to dynamically set the queryset of a models.ModelChoiceField on a forms.Form subclass
4,880,842
16
2011-02-02T22:48:27Z
4,880,869
35
2011-02-02T22:51:47Z
[ "python", "django", "django-forms" ]
The constructor for `forms.ModelChoiceField` requires a queryset. I do not know the queryset until the request happens. Distilled: ``` # models.py class Bar(models.model): text = models.TextField() class Foo(models.Model): name = models.CharField() bar = models.ForeignKey(Bar) # forms.py class FooForm(fo...
Override the form's `__init__` method and set the queryset there. ``` class FooForm(forms.Form): bar = forms.ModelChoiceField(queryset=Bar.objects.none()) def __init__(self, *args, **kwargs): qs = kwargs.pop('bars') super(FooForm, self).__init__(*args, **kwargs) self.fields['bar'].quer...
Sum of all values in a Python dict
4,880,960
86
2011-02-02T23:01:45Z
4,880,971
161
2011-02-02T23:02:38Z
[ "python", "dictionary", "hash", "sum" ]
I'm new to Python. Let's say I have a dictionary in which the keys map to integers like: ``` d = {'key1':1,'key2':14,'key3':47} ``` Is there a syntactically minimalistic way to return the sum of the values in d--i.e. 62 in this case. Thanks
As you'd expect: ``` sum(d.values()) ``` In Python<3, you may want to use `itervalues` instead (which does not build a temporary list).
Sum of all values in a Python dict
4,880,960
86
2011-02-02T23:01:45Z
4,880,985
8
2011-02-02T23:04:14Z
[ "python", "dictionary", "hash", "sum" ]
I'm new to Python. Let's say I have a dictionary in which the keys map to integers like: ``` d = {'key1':1,'key2':14,'key3':47} ``` Is there a syntactically minimalistic way to return the sum of the values in d--i.e. 62 in this case. Thanks
Sure there is. Here is a way to sum the values of a dictionary. ``` >>> d = {'key1':1,'key2':14,'key3':47} >>> sum(d.values()) 62 ```
Sum of all values in a Python dict
4,880,960
86
2011-02-02T23:01:45Z
4,881,100
48
2011-02-02T23:18:55Z
[ "python", "dictionary", "hash", "sum" ]
I'm new to Python. Let's say I have a dictionary in which the keys map to integers like: ``` d = {'key1':1,'key2':14,'key3':47} ``` Is there a syntactically minimalistic way to return the sum of the values in d--i.e. 62 in this case. Thanks
In Python 2 you can avoid making a temporary copy of all the values by using the `itervalues()` dictionary method, which returns an iterator of the dictionary's keys: ``` sum(d.itervalues()) ``` In Python 3 you can just use `d.values()` because that method was changed to do that (and `itervalues()` was removed since ...
Python: Is it possible to change the Windows command line shell current directory without changing the actual current directory?
4,881,312
5
2011-02-02T23:49:11Z
4,881,390
7
2011-02-03T00:01:15Z
[ "python", "cmd", "working-directory" ]
I'm using `os.system()` to do Windows command line shell executions. I would like to change the Windows cmd current directory. Here's one way of doing it: ``` os.chdir('newPath') ``` But `chdir()` will also change the actual Python current working directory. I don't want to change the actual Python working directory ...
The `subprocess` module is intended to replace `os.system`. Among other things, it gives you `subprocess.Popen()`, which takes a `cwd` argument to specify the working directory for the spawned process (for exactly your situation). See: <http://docs.python.org/library/subprocess.html> Example usage replacing `os.syst...
How to parse C++ source in Python?
4,881,377
11
2011-02-02T23:59:01Z
4,883,487
9
2011-02-03T07:34:08Z
[ "c++", "python", "parsing", "code-analysis" ]
We want to parse our huge C++ source tree to gain enough info to feed to another tool to make diagrams of class and object relations, discern the overall organization of things etc. My best try so far is a Python script that scans all .cpp and .h files, runs regex searches to try to detect class declarations, methods,...
I'll simply recommend [Clang](http://clang.llvm.org/). It's a C++ library-based compiler designed with ease of reuse in mind. It notably means that you can use it solely for parsing and generating an Abstract Syntax Tree. It takes care of all the tedious operator overloading resolution, template instantiation and so o...
Django Bi-directional ManyToMany - How to prevent table creation on second model?
4,881,578
8
2011-02-03T00:34:40Z
9,341,455
8
2012-02-18T13:11:17Z
[ "python", "django", "many-to-many" ]
I have two models, each has a shared ManyToMany, using the db\_table field. But how do I prevent syncdb from attempting to create the shared table, for the second model? ``` class Model1(models.Model): othermodels = ManyToManyField('Model2', db_table='model1_model2', related_name='model1_model2') class Model2(mod...
I also found this solution, which worked perfectly for me : ``` class Test1(models.Model): tests2 = models.ManyToManyField('Test2', blank=True) class Test2(models.Model): tests1 = models.ManyToManyField('Test1', through=Test1.tests2.through, blank=True) ```
Python project and package directories layout
4,881,897
9
2011-02-03T01:36:43Z
4,882,141
8
2011-02-03T02:35:53Z
[ "python", "packages" ]
I created a project in python, and I'm curious about how packages work in python. Here is my directory layout: ``` top-level dir \ tests __init__.py \ examples __init__.py example.py module.py ``` How would I go about including module.py in my example.py module. I know I could set PYTHONPATH to the ...
Python packages are very simple: a package is any directory under any entry in sys.path that has an `__init__.py` file. However, a module is only considered to be IN a package if it is imported via a relative import such as `import package.module` or `from package import module`. Note that this means that in general, s...
Find keys through values in a dict for Python
4,882,291
2
2011-02-03T03:09:05Z
4,882,297
9
2011-02-03T03:10:33Z
[ "python", "dictionary" ]
``` NAMES = ['Alice', 'Bob','Cathy','Dan','Ed','Frank', 'Gary','Helen','Irene','Jack', 'Kelly','Larry'] AGES = [20,21,18,18,19,20,20,19,19,19,22,19] def nameage(a,b): nameagelist = [x for x in zip(a,b)] nameagedict = dict(nameagelist) return nameagedict def name(a): for x in nameage(N...
``` print [key for (key,value) in nameagedict.items() if value == 19] ``` `nameagedict.items()` gives you a list of all items in the dictionary, as (key,value) tuples.
django - "manage.py test" fails "table already exists"
4,882,377
7
2011-02-03T03:26:38Z
4,882,942
15
2011-02-03T05:51:05Z
[ "python", "django" ]
I'm new to the django world. Running some tutorial apps, and when running python manage.py test i'm getting a failure saying that the table already exists. I'm not sure what is going on. I am also running south, and I got no errors when migrating the schema. Any insight is greatly appreciated. TIA Joey
It might be an error in one of your south migrations. You don't see the problem on the real db because the migration has been executed (with the--fake option maybe) You can try to recreate the db from scracth and see if it works. You can also disable South for unit-tests by adding `SOUTH_TESTS_MIGRATE = False` in you...
Optimize non-abundant sums algorithm
4,882,428
9
2011-02-03T03:34:31Z
4,882,525
9
2011-02-03T03:52:33Z
[ "python" ]
I am trying to solve [this Project Euler question](http://projecteuler.net/index.php?section=problems&id=23): > A perfect number is a number for which the sum of its proper divisors > is exactly equal to the number. For example, the sum of the proper > divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that ...
You're testing every number between 1 and the limit (let's say 30000) against every abundant number, so you're doing roughly 30000 \* 7428 iterations; and you're checking if the result is in a list, which is a very slow operation -- it checks every item on the list until it finds a match! Instead, you should *generate...
python regular expression
4,883,270
3
2011-02-03T07:02:21Z
4,883,306
14
2011-02-03T07:07:43Z
[ "python", "regex" ]
whats the difference between '{m}' and '{m,n}?' in <http://docs.python.org/library/re.html> it says '{m,n}?' matches numbers in range m to n times, but it is not a greedy search. Therefore if its not a greedy search wouldn't it only match up to m no matter what?
`{m,n}?` will preferably match only `m` repetitions, but it will expand as needed up to `n` repetitions if that's necessary for a longer match. Compare `^x{2}y$` and `^x{2,4}?y$`: The former will fail on `xxxy` whereas the latter will match. **To summarize:** `x{m}`: Match `x` *exactly* `m` times. `x{m,n}`: Try to...
Adding a datetime stamp to Python print
4,883,789
5
2011-02-03T08:22:33Z
4,883,872
15
2011-02-03T08:33:31Z
[ "python", "debugging", "monkeypatching", "built-in" ]
I am trying to debug the behaviour of a *large* library I depend on, which uses a scattering (no make that plethora) of debug print statements through its many source files. Trouble is, most if not all of these debug print statements do not contain a date/time stamp so it is hard to associate failures at the applicatio...
As you can’t override the `write` function (it's read-only) a simple monkey-patch could look like this (appending the timestamp to every printed line): ``` old_f = sys.stdout class F: def write(self, x): old_f.write(x.replace("\n", " [%s]\n" % str(datetime.now()))) sys.stdout = F() ``` An example would ...
Problem with Django-1.3 beta
4,883,802
10
2011-02-03T08:24:16Z
5,206,660
21
2011-03-05T20:43:34Z
[ "python", "django", "manage.py" ]
Guys!! I'm really enthusiastic in learning django and learnt a bit on Django-1.2 but then I installed 1.3 version which is ok till I run the server using the command "python manage.py runserver". It's giving a huge error. I can't figure out a way to solve this. And error is given as : ``` Traceback (most recent call l...
This can happen if you have two versions installed. Delete django (/usr/local/lib/python2.6/dist-packages/django) Just delete the whole folder. Now reinstall Django 1.3 and it should work.
Shortcut for super(type(self), self)
4,883,822
8
2011-02-03T08:26:40Z
4,883,897
15
2011-02-03T08:38:10Z
[ "python" ]
I often do this when overriding a method in a sub class: ``` def method_x(self): x = super(type(self), self).method_x() [Some extra code] return x ``` My question is: Is there a short cut for super(type(self), self) ?
Don't do that: if `super` could just use `type(self)` as its first argument then it wouldn't have been written to take two arguments in the first place. You must pass the actual class here not an expression which could change if the class has been subclassed. The first argument to super needs to be the class containin...
How to make super() work by manually filling the __class__ cell?
4,885,168
7
2011-02-03T10:45:17Z
4,885,951
12
2011-02-03T12:09:05Z
[ "python", "metaprogramming", "python-3.x", "super" ]
In Python 3 one can use `super()` instead of `super(MyClass, self)`, but this only works in methods that were defined inside the class. As described in [Michele Simionato's article](http://www.artima.com/weblogs/viewpost.jsp?thread=281127) the following example does not work: ``` def __init__(self): print('calling...
Seriously: you really don't want to do this. But, it's useful for advanced users of Python to understand this, so I'll explain it. Cells and freevars are the values assigned when a closure is created. For example, ``` def f(): a = 1 def func(): print(a) return func ``` `f` returns a closure base...
How can I read and edit Google Spreadsheets using Python 3.x?
4,886,052
4
2011-02-03T12:19:00Z
8,631,469
8
2011-12-25T20:43:58Z
[ "python", "python-3.x", "google-spreadsheet" ]
I know I can read and edit Google Spreadsheets with [gdata](http://code.google.com/p/gdata-python-client/), but there is no gdata version for Python 3. Is there a (not really really complicated) way to edit Google Spreadsheet even though I want to use Python 3?
I've authored an alternative [Python library for Google Spreadsheets](https://github.com/burnash/gspread). It supports Python 3 and has a less verbose API. You're welcome to check it out.
Python and pip, list all versions of a package that's available?
4,888,027
167
2011-02-03T15:24:30Z
4,902,398
15
2011-02-04T20:03:54Z
[ "python", "virtualenv", "pip" ]
Given the name of a Python (2.X) package that can be installed with [pip](http://pip.openplans.org/) and [virtualenv](http://pypi.python.org/pypi/virtualenv), is there any way to find out a list of all the possible versions of it that pip could install? Right now it's trial and error. I'm trying to install a version f...
After looking at pip's code for a while, it looks like the code responsible for locating packages can be found in the `PackageFinder` class in `pip.index`. Its method `find_requirement` looks up the versions of a `InstallRequirement`, but unfortunately only returns the most recent version. The code below is almost a 1...
Python and pip, list all versions of a package that's available?
4,888,027
167
2011-02-03T15:24:30Z
5,422,144
136
2011-03-24T16:11:42Z
[ "python", "virtualenv", "pip" ]
Given the name of a Python (2.X) package that can be installed with [pip](http://pip.openplans.org/) and [virtualenv](http://pypi.python.org/pypi/virtualenv), is there any way to find out a list of all the possible versions of it that pip could install? Right now it's trial and error. I'm trying to install a version f...
The script at pastebin does work. However it's not very convenient if you're working with multiple environments/hosts because you will have to copy/create it every time. A better all-around solution would be to use [yolk](https://pypi.python.org/pypi/yolk), which is available to install with pip. E.g. to see what vers...
Python and pip, list all versions of a package that's available?
4,888,027
167
2011-02-03T15:24:30Z
15,337,317
8
2013-03-11T11:21:41Z
[ "python", "virtualenv", "pip" ]
Given the name of a Python (2.X) package that can be installed with [pip](http://pip.openplans.org/) and [virtualenv](http://pypi.python.org/pypi/virtualenv), is there any way to find out a list of all the possible versions of it that pip could install? Right now it's trial and error. I'm trying to install a version f...
<https://pypi.python.org/pypi/Django/> - works for packages whose maintainers choose to show all packages <https://pypi.python.org/simple/pip/> - should do the trick anyhow (lists all links)
Python and pip, list all versions of a package that's available?
4,888,027
167
2011-02-03T15:24:30Z
19,355,548
60
2013-10-14T07:44:15Z
[ "python", "virtualenv", "pip" ]
Given the name of a Python (2.X) package that can be installed with [pip](http://pip.openplans.org/) and [virtualenv](http://pypi.python.org/pypi/virtualenv), is there any way to find out a list of all the possible versions of it that pip could install? Right now it's trial and error. I'm trying to install a version f...
Use `pip install -v`, you can see all versions that available ``` root@node7:~# pip install web.py -v Downloading/unpacking web.py Using version 0.37 (newest of versions: 0.37, 0.36, 0.35, 0.34, 0.33, 0.33, 0.32, 0.31, 0.22, 0.2) Downloading web.py-0.37.tar.gz (90Kb): 90Kb downloaded Running setup.py egg_info fo...
Python and pip, list all versions of a package that's available?
4,888,027
167
2011-02-03T15:24:30Z
25,234,919
12
2014-08-11T02:01:56Z
[ "python", "virtualenv", "pip" ]
Given the name of a Python (2.X) package that can be installed with [pip](http://pip.openplans.org/) and [virtualenv](http://pypi.python.org/pypi/virtualenv), is there any way to find out a list of all the possible versions of it that pip could install? Right now it's trial and error. I'm trying to install a version f...
You could the yolk3k package instead of yolk. yolk3k is a fork from the original yolk and it supports both python2 and 3. <https://github.com/myint/yolk> ``` pip install yolk3k ```
Python and pip, list all versions of a package that's available?
4,888,027
167
2011-02-03T15:24:30Z
26,664,162
147
2014-10-30T22:07:40Z
[ "python", "virtualenv", "pip" ]
Given the name of a Python (2.X) package that can be installed with [pip](http://pip.openplans.org/) and [virtualenv](http://pypi.python.org/pypi/virtualenv), is there any way to find out a list of all the possible versions of it that pip could install? Right now it's trial and error. I'm trying to install a version f...
Without actually having to download or install any additional packages you can use *the syntax* for specifying a particular version while *not actually specifying any version*, and the available versions will be printed: ``` $ pip install pylibmc== Collecting pylibmc== Could not find a version that satisfies the req...
Python and pip, list all versions of a package that's available?
4,888,027
167
2011-02-03T15:24:30Z
27,239,645
36
2014-12-02T00:03:59Z
[ "python", "virtualenv", "pip" ]
Given the name of a Python (2.X) package that can be installed with [pip](http://pip.openplans.org/) and [virtualenv](http://pypi.python.org/pypi/virtualenv), is there any way to find out a list of all the possible versions of it that pip could install? Right now it's trial and error. I'm trying to install a version f...
You don't need a third party package to get this information. pypi provides simple JSON feeds for all packages under ``` https://pypi.python.org/pypi/{PKG_NAME}/json ``` Here's some Python code using only the standard library which gets all versions. ``` import json import urllib2 from distutils.version import Stric...
Python and pip, list all versions of a package that's available?
4,888,027
167
2011-02-03T15:24:30Z
31,362,608
8
2015-07-11T22:48:01Z
[ "python", "virtualenv", "pip" ]
Given the name of a Python (2.X) package that can be installed with [pip](http://pip.openplans.org/) and [virtualenv](http://pypi.python.org/pypi/virtualenv), is there any way to find out a list of all the possible versions of it that pip could install? Right now it's trial and error. I'm trying to install a version f...
I came up with dead-simple bash script. Thanks to [jq](https://stedolan.github.io/jq/manual/)'s author. ``` #!/bin/bash set -e PACKAGE_JSON_URL="https://pypi.python.org/pypi/${1}/json" curl -s "$PACKAGE_JSON_URL" | jq -r '.releases | keys | .[]' ```
How to install mechanize for Python 2.7?
4,888,463
15
2011-02-03T16:02:17Z
6,417,929
29
2011-06-20T21:43:16Z
[ "python", "python-2.7", "mechanize" ]
I saved mechanize in my Python 2.7 directory. But when I type `import mechanize` into the Python shell, I get an error message that reads: ``` Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import mechanize ImportError: No module named mechanize ```
using [pip](http://www.pip-installer.org/): ``` pip install mechanize ``` or download the mechanize [distribution](http://wwwsearch.sourceforge.net/mechanize/src/) archive, open it, and run: ``` python setup.py install ```
How to install mechanize for Python 2.7?
4,888,463
15
2011-02-03T16:02:17Z
16,073,092
12
2013-04-18T01:36:06Z
[ "python", "python-2.7", "mechanize" ]
I saved mechanize in my Python 2.7 directory. But when I type `import mechanize` into the Python shell, I get an error message that reads: ``` Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import mechanize ImportError: No module named mechanize ```
Try this on Debian/Ubuntu: ``` sudo apt-get install python-mechanize ```
ElementTree instance has no attribute 'fromstring'. So, what I did wrong?
4,888,533
5
2011-02-03T16:08:42Z
4,888,573
13
2011-02-03T16:12:04Z
[ "python", "django", "parsing", "elementtree" ]
I'm trying open and parse some html. So far, it was ok, I'm able to open the source and print it for example. But when it comes to parsing I'm stuck with "ElementTree instance has no attribute 'fromstring'" this is my Django view.py code: ``` from django.template import loader, Context from django.http import HttpRes...
Your import statement is wrong... `fromstring` is a free function in the `xml.etree.ElementTree` module, not a method of the class `xml.etree.ElementTree.ElementTree`: ``` from xml.etree import ElementTree as etree ... tree = etree.fromstring(r) ```
Can I catch error codes when using Fabric to run() calls in a remote shell?
4,888,568
52
2011-02-03T16:11:44Z
5,974,427
77
2011-05-12T06:58:34Z
[ "python", "error-handling", "fabric" ]
Normally Fabric quits as soon as a run() call returns a non-zero exit code. For some calls, however, this is expected. For example, PNGOut returns an error code of 2 when it is unable to compress a file. Currently I can only circumvent this limitation by either using shell logic (`do_something_that_fails || true` or `...
You can prevent aborting on non-zero exit codes by using the `settings` context manager and the `warn_only` setting: ``` from fabric.api import settings with settings(warn_only=True): result = run('pngout old.png new.png') if result.return_code == 0: do something elif result.return_code == 2: ...
Can I catch error codes when using Fabric to run() calls in a remote shell?
4,888,568
52
2011-02-03T16:11:44Z
25,293,275
22
2014-08-13T18:13:22Z
[ "python", "error-handling", "fabric" ]
Normally Fabric quits as soon as a run() call returns a non-zero exit code. For some calls, however, this is expected. For example, PNGOut returns an error code of 2 when it is unable to compress a file. Currently I can only circumvent this limitation by either using shell logic (`do_something_that_fails || true` or `...
Yes, you can. Just change the environment's `abort_exception`. For example: ``` from fabric.api import settings class FabricException(Exception): pass with settings(abort_exception = FabricException): try: run(<something that might fail>) except FabricException: <handle the exception> ```...
User permissions for Django module
4,888,708
3
2011-02-03T16:24:41Z
4,888,805
11
2011-02-03T16:33:34Z
[ "python", "django", "django-templates", "django-views", "django-permissions" ]
I'm having a small issue with my permissions in my Django template. I'm trying to, based on permissions, show an icon in the menu bar for my project. I want to have it so that if the user has the permissions to add a new follow-up to the project, they can see the icon, if they don't have that permission, then do not d...
Since you are using the Django permission system, it's better you use the followingg template syntax... ``` {%if perms.followup.add_followup%}your URL here{%endif%} ``` EDIT: Django automatically creates 3 permissions for each model, 'add', 'change' and 'delete'. If there exists no model for adding a link, then you m...
How to get transparent background in window with PyGTK and PyCairo?
4,889,045
6
2011-02-03T16:53:10Z
4,902,541
9
2011-02-04T20:23:30Z
[ "python", "gtk", "pygtk", "cairo", "pycairo" ]
I've been trying really hard to create a window with no decoration and a transparent background using PyGTK. I would then draw the content of the window with Cairo. But I can't get it to work. I've tried a lot of different ways, they all failed, this is one of them ``` #!/usr/bin/env python import pygtk pygtk.requir...
So, I actually figured this out myself. This is a working example. I've commented the relevant parts just in case somebody else is interested in how to do this. ``` #!/usr/bin/env python import pygtk pygtk.require('2.0') import gtk, sys, cairo from math import pi def expose (widget, event): cr = widget.window.c...
Python: Excluding Modules Pyinstaller
4,890,159
8
2011-02-03T18:30:45Z
17,595,149
13
2013-07-11T13:48:16Z
[ "python", "pyinstaller" ]
I've begun using Pyinstaller over Py2Exe. However I've rather quickly run into a problem. How do I exclude modules that I don't want, and how do I view the ones that are getting included into the single executable file? I can remove some `pyd` and `dll` files from the DLL folder in my Python installation so Pyinstalle...
Just to summarise the options here as I use them. PyInstaller TOC's - are, as the documentation says: > A TOC appears to be a list of tuples of the form (name, path, > typecode). In fact, it's an ordered set, not a list. A TOC contains no > duplicates, where uniqueness is based on name only. In otherwords, simply: ...
Detecting thresholds in HSV color space (from RGB) using Python / PIL
4,890,373
7
2011-02-03T18:51:04Z
4,890,878
18
2011-02-03T19:44:13Z
[ "python", "image", "image-processing", "performance", "python-imaging-library" ]
I want to take an RGB image and convert it to a black and white RGB image, where a pixel is black if its HSV value is between a certain range and white otherwise. Currently I create a new image, then create a list of new pixel values by iterating through its data, then `.putdata()` that list to form the new image. It...
Ok, this *does* work (fixed some overflow errors): ``` import numpy, Image i = Image.open(fp).convert('RGB') a = numpy.asarray(i, int) R, G, B = a.T m = numpy.min(a,2).T M = numpy.max(a,2).T C = M-m #chroma Cmsk = C!=0 # Hue H = numpy.zeros(R.shape, int) mask = (M==R)&Cmsk H[mask] = numpy.mod(60*(G-B)/C, 360)[mask...
Summing up digits !
4,890,610
6
2011-02-03T19:17:53Z
4,890,850
9
2011-02-03T19:41:47Z
[ "python", "algorithm", "math" ]
Hi I have been trying out this [problem](http://mathalon.in/?page=show_problem.php&pid=133): > Suppose P(n) is sum of digits of 2^n > For example: > As 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26,so P(15)=26. > Catulate sum of the P(n) for n=1 to 10000. Here is my [python code](http://ideon...
If you had shown the comments, you would've noticed that the site owners, or problem maintainer, is a moron. He meant to say from "0 to 10000", not "1 to 10000", but apparently the problem cannot be edited, or the maintainer don't want to do it. The sum is off by 1 since `1<<0` is 1, which adds 1 to the sum. Try sub...
Installing pyOpenSSL on Amazon Linux (EC2)
4,891,417
7
2011-02-03T20:35:57Z
4,939,962
9
2011-02-09T00:00:41Z
[ "python", "amazon-ec2", "openssl", "easy-install", "pyopenssl" ]
I'm using the first default AMI for amazon Linux on ec2 and can't seem to install pyOpenSSL. I tried: sudo wget <http://launchpad.net/pyopenssl/main/0.11/+download/pyOpenSSL-0.11.tar.gz> && easy\_install pyOpenSSL-0.11.tar.gz. ``` Results were: error: can't create or remove files in install directory The following er...
yum install pyOpenSSL. Should have tried this to begin with
Calculating EuropeanOptionImpliedVolatility in quantlib-python
4,891,490
6
2011-02-03T20:41:36Z
4,896,061
16
2011-02-04T08:45:33Z
[ "python", "rpy2", "quantlib" ]
I have R code that uses RQuantlib library. In order to run it from python I am using RPy2. I know python has its own bindings for quantlib (quantlib-python). I'd like to switch from R to python completely. Please let me know how I can run the following using quantlib-python ``` import rpy2.robjects as robjects robje...
You'll need a bit of setup. For convenience, and unless you get name clashes, you better import everything: ``` from QuantLib import * ``` then, create the option, which needs an exercise and a payoff: ``` exercise = EuropeanExercise(Date(3,August,2011)) payoff = PlainVanillaPayoff(Option.Call, 100.0) option = Europ...
Django: Faking a field in the admin interface?
4,891,506
13
2011-02-03T20:43:20Z
4,893,172
29
2011-02-03T23:59:02Z
[ "python", "django", "django-admin" ]
I have a model, `Foo`. It has several database properties, and several properties that are calculated based on a combination of factors. I would like to present these calculated properties to the user as if they were database properties. (The backing factors would be changed to reflect user input.) Is there a way to do...
I would suggest you subclass a modelform for `Foo` (FooAdminForm) to add your own fields not backed by the database. Your custom validation can reside in the `clean_*` methods of ModelForm. Inside the `save_model` method of `FooAdmin` you get the request, an instance of `Foo` and the form data, so you could do all pro...
How do I use the unittest setUpClass method()?
4,891,671
21
2011-02-03T20:59:48Z
4,891,710
20
2011-02-03T21:03:11Z
[ "python", "unit-testing" ]
I'm looking for some basic examples of the python 2.7 unittest setUpClass() method. I'm trying to test some class methods in my module, and I've gotten as far as: ``` import unittest import sys import mymodule class BookTests(unittest.TestCase): @classmethod def setUpClass(cls): cls._mine...
In your test methods you can now access the global class atribute `_mine` through self. So you can do something like this: ``` def test_something(self): self.assertEqual(self._mine.attribute, 'myAttribute') ```
Django: String representation of models
4,892,049
8
2011-02-03T21:40:06Z
4,892,163
15
2011-02-03T21:54:25Z
[ "python", "django" ]
I would like my models to have two string representations: one that is displayed in the backend logs for debugging purposes, and a cleaner one that is displayed to end users when the model is represented in the HTML. Right now, I'm just overriding `__unicode__()`. Is there a way to do this?
You can also try `__repr__` and `__str__` for your logging/debugging purposes. It is possible (at least it should be this way) that your logger/debugger uses `repr( object )` to log your objects.
Django: String representation of models
4,892,049
8
2011-02-03T21:40:06Z
4,892,195
7
2011-02-03T21:57:37Z
[ "python", "django" ]
I would like my models to have two string representations: one that is displayed in the backend logs for debugging purposes, and a cleaner one that is displayed to end users when the model is represented in the HTML. Right now, I'm just overriding `__unicode__()`. Is there a way to do this?
Use properties ``` class SomeThing( models.Model ): foo= bar= baz= def __unicode__( self ): return "{0} {1}".format( self.foo, self.bar ) @property def details( self ): return repr( dict( foo=self.foo, bar=self.bar, baz=self.baz ) ) ``` Now you can log `someObject.details`
Is there a way to see if there are updates available from a central Mercurial repostiory before pulling them?
4,892,349
4
2011-02-03T22:13:17Z
4,892,363
9
2011-02-03T22:15:27Z
[ "python", "mercurial", "fabric" ]
I am using Fabric to deploy my Python application from my local machine. I would like to hit our central Mercurial repository (hosted on BitBucket.org) to see if my local repository is at the same rev as the tip. Is there a command I can call to see if there are updates available from the repository without actually p...
``` $ hg help incoming hg incoming [-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE] aliases: in show new changesets found in source ```
How to capture frames from Apple iSight using Python and PyObjC?
4,892,555
9
2011-02-03T22:37:19Z
4,903,076
15
2011-02-04T21:22:40Z
[ "python", "cocoa", "pyobjc", "qtkit", "isight" ]
I am trying to capture a single frame from the Apple iSight camera built into a Macbook Pro using Python (version 2.7 or 2.6) and the PyObjC (version 2.2). As a starting point, I used [this old StackOverflow](http://stackoverflow.com/questions/1576593/how-can-i-capture-isight-frames-with-python-in-snow-leopard) questi...
OK, I spent a day diving through the depths of PyObjC and got it working. For future record, the reason the code in the question did not work: **variable scope and garbage collection**. The *session* variable was deleted when it fell out of scope, which happened before the event processor ran. Something must be done t...
Look up a tuple in a python dictionary matching (x,y) or (y,x)
4,893,452
5
2011-02-04T00:44:16Z
4,893,482
10
2011-02-04T00:52:11Z
[ "python" ]
I've a dictionary with a `(x,y)` key, where `(x,y)` means the same as `(y,x)`, How should I do this ? I can do: ``` >>> d = {(1,2): "foo"} >>> i = d.get(2,1) >>> if i is None: ... i = d.get((1,2)) ... >>> i 'foo' ``` Is there a better way of doing this, so `d.get((2,1))` would match the key `(1,2)` directly ? id...
Use frozensets rather than tuples. ``` d = {frozenset((1,2)): "foo"} print d.get(frozenset((2,1))) ```
Fastest Python method for search and replace on a large string
4,893,506
9
2011-02-04T00:58:39Z
4,893,549
10
2011-02-04T01:06:55Z
[ "python", "regex" ]
I'm looking for the fastest way to replace a large number of sub-strings inside a very large string. Here are two examples I've used. findall() feels simpler and more elegant, but it takes an astounding amount of time. finditer() blazes through a large file, but I'm not sure this is the right way to do it. Here's so...
The standard method is to use the built-in ``` re.sub(reg, rep, text) ``` Incidentally the reason for the performance difference between your versions is that each replacement in your first version causes the entire string to be recopied. Copies are fast, but when you're copying 10 MB at a go, enough copies will beco...
Update entity from a sharded counter - Python
4,893,588
4
2011-02-04T01:12:33Z
4,893,699
9
2011-02-04T01:33:18Z
[ "python", "google-app-engine" ]
In my appengine python app, I have sharded counters that count the number of favs for a photo, and number of views. I have Photo and Counter models. To order photos by popularity (# of favs), I should have the # of favs stored in my Photo entities (Photo.all().order('num\_favs')). Since I'm keeping track of the num of...
If you need to sort or filter based on a value, you probably shouldn't use a sharded counter, but rather use one of the alternatives. In short, they are: 1. Simply use a regular counter. If you don't expect the rate of updates to exceed 1-5QPS for extended periods (brief spikes are okay), then this should work fine. 2...
Save a dictionary to a file (alternative to pickle) in Python?
4,893,689
38
2011-02-04T01:31:41Z
4,893,704
49
2011-02-04T01:34:23Z
[ "python", "dictionary", "save", "pickle" ]
**Answered** I ended up going with pickle at the end anyway Ok so with some advice on another question I asked I was told to use pickle to save a dictionary to a file. The dictionary that I was trying to save to the file was ``` members = {'Starspy' : 'SHSN4N', 'Test' : 'Test1'} ``` When pickle saved it to the file...
Sure, save it as CSV: ``` import csv w = csv.writer(open("output.csv", "w")) for key, val in dict.items(): w.writerow([key, val]) ``` Then reading it would be: ``` import csv dict = {} for key, val in csv.reader(open("input.csv")): dict[key] = val ``` Another alternative would be json (`json` for version 2....
Save a dictionary to a file (alternative to pickle) in Python?
4,893,689
38
2011-02-04T01:31:41Z
4,893,741
50
2011-02-04T01:40:07Z
[ "python", "dictionary", "save", "pickle" ]
**Answered** I ended up going with pickle at the end anyway Ok so with some advice on another question I asked I was told to use pickle to save a dictionary to a file. The dictionary that I was trying to save to the file was ``` members = {'Starspy' : 'SHSN4N', 'Test' : 'Test1'} ``` When pickle saved it to the file...
The most common serialization format for this nowadays is JSON, which is universally supported and represents simple data structures like dictionaries very clearly. ``` >>> members = {'Starspy' : 'SHSN4N', 'Test' : 'Test1'} >>> json.dumps(members) '{"Test": "Test1", "Starspy": "SHSN4N"}' >>> json.loads(json.dumps(memb...
Can a python program be run on a computer without Python? What about C/C++?
4,894,048
4
2011-02-04T02:42:57Z
4,894,071
7
2011-02-04T02:46:56Z
[ "c++", "python", "c" ]
Can I create a Python program, send it to a remote computer, and run it there without that computer having Python installed? I've heard that you cannot, as Python needs to be interpreted. If this is true, then it seems very odd as it would be hard to distribute your program unless everyone decides to install Python. A...
Look at py2exe and py2app for Windows and Mac. Macs running OSX and most modern Linuces have Python installed, however. C/C++ apps are normally compiled to executables which work on one machine/OS architecture (e.g. 32-bit Windows, or 64-bit OSX); such an executable can run on some but not all machines. For example, 6...
Can a python program be run on a computer without Python? What about C/C++?
4,894,048
4
2011-02-04T02:42:57Z
4,894,089
7
2011-02-04T02:50:56Z
[ "c++", "python", "c" ]
Can I create a Python program, send it to a remote computer, and run it there without that computer having Python installed? I've heard that you cannot, as Python needs to be interpreted. If this is true, then it seems very odd as it would be hard to distribute your program unless everyone decides to install Python. A...
python is interpreted, so it won't run without python. However, that doesn't mean that python has to be installed, you can include a copy in your program directory or even bundle your program and the python runtime into a single file. C and C++ compilers toolchains generate machine code (in most cases, C interpreters ...
Regular expression to return text between parenthesis
4,894,069
23
2011-02-04T02:46:50Z
4,894,134
14
2011-02-04T02:59:45Z
[ "python", "regex", "python-3.x" ]
``` u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')' ``` All I need is the contents inside the parenthesis.
**re.search('\((.\*?)\)',s).group(1)** ``` >>> import re >>> s = u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')' >>> re.search('\((.*?)\)',s).group(1) u"date='2/xc2/xb2',time='/case/test.png'" ``` you need to learn about the regular expression more. ;-)
Regular expression to return text between parenthesis
4,894,069
23
2011-02-04T02:46:50Z
4,894,156
73
2011-02-04T03:03:24Z
[ "python", "regex", "python-3.x" ]
``` u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')' ``` All I need is the contents inside the parenthesis.
If your problem is really just this simple, you don't need regex: ``` s[s.find("(")+1:s.find(")")] ```
Django Custom File Storage system
4,894,976
6
2011-02-04T05:47:24Z
4,905,384
10
2011-02-05T05:54:58Z
[ "python", "django" ]
I have a custom storage ``` import os from django.core.files.storage import Storage class AlwaysOverwriteFileSystemStorage(Storage): def get_available_name(self, name): """ Directly Returns a filename that's from what user input. """ if self.exists(name): # Remove the...
You don't need to put anything in your `settings.py`. Just use it directly in your model. For example, create `storage.py` wherever your app is located and put `OverwriteStorage()` in it. Then, your model could look like this: ``` from storage import OverwriteStorage ... class MyModel(models.Model): ... image ...
Creating a tree from self referential tables in SQLalchemy
4,896,104
10
2011-02-04T08:51:32Z
4,896,292
13
2011-02-04T09:15:04Z
[ "python", "sqlalchemy", "flask" ]
I'm building a basic CMS in flask for an iPhone oriented site and I'm having a little trouble with something. I have a very small database with just 1 table (pages). Here's the model: ``` class Page(db.Model): __tablename__ = 'pages' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(...
Look at <http://sqlamp.angri.ru/index.html> or <http://www.sqlalchemy.org/trac/browser/examples/adjacency_list/adjacency_list.py> **UPD:** For adjacency\_list.py declarative example ``` from sqlalchemy.ext.declarative import declarative_base Base = declarative_base(metadata=metadata) class TreeNode(Base): __ta...
bug or feature: open and io.open are not interchangeable
4,896,788
5
2011-02-04T10:12:15Z
4,897,088
7
2011-02-04T10:45:13Z
[ "python", "api", "file-io" ]
I always thought `open` and `io.open` were interchangeable. Apparently not, if I believe this snippet: ``` import ctypes, io class POINT(ctypes.Structure): _fields_ = [("x", ctypes.c_int),("y", ctypes.c_int)] # THIS WORKS with open("mypoints.bin", "wb") as f: for i in range(10): p = POINT(i,10-i) ...
Yes, it's a "bug", `io.open` in Python 2.6 is slightly broken. It was supposed to be work like 3.x's `open` to ease transition, but it doesn't work correctly in some cases. For example, it doesn't support objects with the buffer interface like in your case. This is fixed in Python 2.7 where the builtin `open` can be us...
Module imported multiple times
4,897,232
5
2011-02-04T10:59:43Z
4,897,479
8
2011-02-04T11:27:32Z
[ "python", "django" ]
I do some init stuff when a module is first loaded. The problem is that somehow it is imported twice, and I can't figure out why. I thought it might be imported using different path, as in this example: a.py: ``` from apps.blog import models ... ``` b.py: ``` from blog import models ... ``` I insert `print __name_...
Normally Python should not import a module twice regardless of absolute/relative references. It's likely that Python is seeing the source file as two different files and thus importing them separately. This could happen because of symlinked files/directories, or side-by-side different versions, or overlapping directori...
output to the same line overwriting previous output ? python (2.5)
4,897,359
36
2011-02-04T11:13:47Z
4,897,387
7
2011-02-04T11:17:05Z
[ "python", "refresh", "progress-bar" ]
I am writing a simple ftp downloader. Part of to the code is something like this: ``` ftp.retrbinary("RETR " + file_name, process) ``` i am calling function process to handle the callback: ``` def process(data): print os.path.getsize(file_name)/1024, 'KB / ', size, 'KB downloaded!' file.write(data) ``` and ...
Have a look at the [curses module documentation](http://docs.python.org/library/curses.html) and the [curses module HOWTO](http://docs.python.org/howto/curses.html). Really basic example: ``` import time import curses stdscr = curses.initscr() stdscr.addstr(0, 0, "Hello") stdscr.refresh() time.sleep(1) stdscr.add...
output to the same line overwriting previous output ? python (2.5)
4,897,359
36
2011-02-04T11:13:47Z
4,897,393
24
2011-02-04T11:17:54Z
[ "python", "refresh", "progress-bar" ]
I am writing a simple ftp downloader. Part of to the code is something like this: ``` ftp.retrbinary("RETR " + file_name, process) ``` i am calling function process to handle the callback: ``` def process(data): print os.path.getsize(file_name)/1024, 'KB / ', size, 'KB downloaded!' file.write(data) ``` and ...
If all you want to do is change a single line, use `\r`. `\r` means carriage return. It's effect is solely to put the caret back at the start of the current line. It does not erase anything. Similarly, `\b` can be used to go one character backward. (some terminals may not support all those features) ``` import sys de...
output to the same line overwriting previous output ? python (2.5)
4,897,359
36
2011-02-04T11:13:47Z
8,436,827
51
2011-12-08T19:56:02Z
[ "python", "refresh", "progress-bar" ]
I am writing a simple ftp downloader. Part of to the code is something like this: ``` ftp.retrbinary("RETR " + file_name, process) ``` i am calling function process to handle the callback: ``` def process(data): print os.path.getsize(file_name)/1024, 'KB / ', size, 'KB downloaded!' file.write(data) ``` and ...
Here's code for Python 3.x: ``` print(os.path.getsize(file_name)/1024+'KB / '+size+' KB downloaded!', end='\r') ``` The `end=` keyword is what does the work here -- by default, `print()` ends in a newline (`\n`) character, but this can be replaced with a different string. In this case, ending the line with a carriage...
A good side-project for learning python?
4,898,747
2
2011-02-04T13:57:25Z
4,898,770
10
2011-02-04T13:59:42Z
[ "python", "project", "pygtk" ]
I'm a 2nd year university student, and I thought it would be a good idea to expand my abilities. I will be using python later this year to complete a gui for a C program (using Tkinter), but I want to make a side project as well, and python seems like a great language to do it with. I want a project which has multiple...
> Considering I have no python experience, but I do have a strong background in C and Java, are there going to be any difficulties which will unexpectedly stop me? Yes. > I have never made a music application before, and I am not sure whats involved in keeping a music library, for example. That will stop you. Want ...
Python doesn't detect a closed socket until the second send
4,899,593
14
2011-02-04T15:17:47Z
4,899,773
13
2011-02-04T15:36:21Z
[ "python", "sockets" ]
When I close the socket on one end of a connection, the other end gets an error the second time it sends data, but not the first time: ``` import socket server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(("localhost", 12345)) server.listen(1) client = socket.create_connection(("localhost",12345))...
This is expected, and how the TCP/IP APIs are implemented (so it's similar in pretty much all languages and on all operating systems) The short story is, you cannot do anything to guarantee that a send() call returns an error directly if that send() call somehow cannot deliver data to the other end. send/write calls j...
Python: how to do basic data manipulation like in R?
4,899,851
15
2011-02-04T15:42:19Z
4,900,020
14
2011-02-04T15:58:01Z
[ "python" ]
I have been working with R for several years. R is very strong in data manipulation. I'm learning python and I would like to know how to manipulate data using python. Basically my data sets are organized as data frames (e.g excel sheet). I would like to know (by example) how this kind of basic data manipulation task ca...
``` import csv from itertools import izip with open('source.csv') as f: reader = csv.reader(f) # filter data data = (row for row in reader if row[1].strip() in ('5', '8')) # make a new variable data = (row + [int(row[2]) * 3] for row in data) # transpose data data = izip(*data) # write ...
Python: how to do basic data manipulation like in R?
4,899,851
15
2011-02-04T15:42:19Z
4,902,234
22
2011-02-04T19:45:50Z
[ "python" ]
I have been working with R for several years. R is very strong in data manipulation. I'm learning python and I would like to know how to manipulate data using python. Basically my data sets are organized as data frames (e.g excel sheet). I would like to know (by example) how this kind of basic data manipulation task ca...
I disagree with Cpfohl's comment - perhaps because I've been through this same transition myself, and it's not obvious how a naive user would be able to formulate the problem more precisely. It is actually an active development problem right now with a number of projects that have all come up with non-overlapping funct...
Python: how to do basic data manipulation like in R?
4,899,851
15
2011-02-04T15:42:19Z
7,768,708
11
2011-10-14T13:56:50Z
[ "python" ]
I have been working with R for several years. R is very strong in data manipulation. I'm learning python and I would like to know how to manipulate data using python. Basically my data sets are organized as data frames (e.g excel sheet). I would like to know (by example) how this kind of basic data manipulation task ca...
Simple answer: use [pandas](http://pandas.sourceforge.net) # 1 ``` In [2]: df = read_csv('foo.csv', index_col=None) In [3]: df Out[3]: var1 var2 var3 0 1 2 3 1 4 5 6 2 7 8 9 ``` # 2 ``` In [4]: df[df['var2'].isin([5, 8])] Out[4]: var1 var2 var3 1 4 5 6 2 7 ...
How to set any font in reportlab Canvas in python?
4,899,885
21
2011-02-04T15:45:17Z
4,900,031
33
2011-02-04T15:59:03Z
[ "python", "reportlab" ]
I'm using reportlab to create pdfs. When I try to set a font using the following method, I get a `KeyError`: ``` pdf = Canvas('test.pdf') pdf.setFont('Tahoma', 16) ``` But if I use `'Courier'` instead of `'Tahoma'` there isn't a problem. How can I use Tahoma?
Perhabs Tahoma is a TrueType font, and you need to register it first. According to the user guide of ReportLab you need to do this: ``` from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('Vera', 'Vera.ttf')) pdfmetrics.registerFont(TTFont('VeraBd', 'Ve...
Why do I get "AttributeError: 'unicode' object has no attribute 'user' " on some specify url only?
4,900,003
3
2011-02-04T15:56:21Z
4,900,357
9
2011-02-04T16:27:26Z
[ "python", "django", "login-required" ]
I'm using the @login\_required decorator in my project since day one and it's working fine, but for some reason, I'm starting to get " AttributeError: 'unicode' object has no attribute 'user' " on some specific urls (and those worked in the past). Example : I am the website, logged, and then I click on link and I'm ge...
The decorator was on a private method that doesn't have the request as a parameter. I removed that decorator (left there because of a refactoring and lack of test [bad me]). Problem solved.
Print new line in Google app engine
4,900,013
3
2011-02-04T15:57:19Z
4,900,281
8
2011-02-04T16:21:01Z
[ "python", "google-app-engine", "newline", "new-operator" ]
``` self.response.out.write("\n") ``` When i upload a data of multiline using text property and then printing it back it prints in a single line.... i upload the ascii hexa code .... so carriage return is 0x10 but when pringing it in ascii from datastore the new line is not inserted... instead it prints as a single li...
Where are you printing that data back out to? If it's inside of HTML (well, unless it's surrounded by `<pre>` tags), the newlines will be ignored regardless of whether the EOL is indicated by `\n` or `\r\n`. If that's what's going on, you can just do ``` self.response.out.write(myString.replace("\n", "<br />")) ```
Find all Key-Elements by the same Value in Dicts
4,900,308
6
2011-02-04T16:23:26Z
4,900,351
15
2011-02-04T16:27:05Z
[ "python", "dictionary", "key" ]
I just started with Python and have question about Dictionaries in Python. I do searched a lot of to get an awnser for my problem, but nothing helped. here it is: I have a dict like `dict = { 'abc':'a', 'cdf':'b', 'gh':'a', 'fh':'g', 'hfz':'g' }` Now i want to get all Key-Elements by the same value and save it in a ...
If you are fine with lists instead of tuples in the new dictionary, you can use ``` from collections import defaultdict some_dict = { 'abc':'a', 'cdf':'b', 'gh':'a', 'fh':'g', 'hfz':'g' } new_dict = defaultdict(list) for k, v in some_dict.iteritems(): new_dict[v].append(k) ``` If you want to avoid the use of `def...
Optimising Python dictionary access code
4,900,747
57
2011-02-04T17:06:18Z
4,901,516
16
2011-02-04T18:22:51Z
[ "python", "optimization", "dictionary", "sparse-matrix" ]
**Question:** I've profiled my Python program to death, and there is one function that is slowing everything down. It uses Python dictionaries heavily, so I may not have used them in the best way. If I can't get it running faster, I will have to re-write it in C++, so is there anyone who can help me optimise it in Pyt...
`node_after_b == node_a` will try to call `node_after_b.__eq__(node_a)`: ``` >>> class B(object): ... def __eq__(self, other): ... print "B.__eq__()" ... return False ... >>> class A(object): ... def __eq__(self, other): ... print "A.__eq__()" ... return False ... >>> a = A() ...
Trigonometry sin return negative
4,900,996
3
2011-02-04T17:27:34Z
4,901,053
12
2011-02-04T17:30:55Z
[ "python", "c", "trigonometry" ]
I made this code in Python ``` def hitsin(a): a = a*57.3 return math.sin(a) ``` so whenever i put hitsin(x) the x converted to radian. I confuse when I put hitsin(90) the answer is not 1 or any number near 1, but negative (it was -0.9971392129043587). Am I doing it wrong? p.s: I also try to write the same ki...
You should divide by `180/pi`, not multiply. In Python, you can also use `math.radians()` for the conversion from degree to radians: ``` def hitsin(a): return math.sin(math.radians(a)) hitsin(90) # 1.0 ``` Furthermore, I doubt the C code gives the same result as the Python code, because it uses `cos()` instead of...
Why can't I call a private method when I'm inside a public method?
4,901,209
5
2011-02-04T17:49:16Z
4,901,224
19
2011-02-04T17:51:13Z
[ "python", "private", "public" ]
I have the following code: ``` class MyClass: def __private(self): print "Hey man! This is private!" def public(self): __private() print "I don't care if you see this!" if __name__ == '__main__': x = MyClass() x.public() ``` However it gives me the following error: `NameErro...
You need `self`: ``` self.__private() ``` Classes in python take getting used to if you're coming from C#/C++/Java, like it looks like you are. This is probably butchering the "pythonic" way of wording things, but you can think about it like this (it helped me out): Each class defines a namespace defined from within...
How to print for loop with 2 lists?
4,901,220
2
2011-02-04T17:50:38Z
4,901,227
8
2011-02-04T17:51:31Z
[ "python", "list", "for-loop" ]
I have 2 lists: ``` filtered_items_list = [src1, scr2, scr3] filtered_items_url_list = [url1, url2, url3] ``` I want to print this as ``` src1, url1 src2, url2 src3, url3 ``` If I try: ``` >>> for src, url in filtered_items_list, filtered_items_url_list: print src, url ``` I get this error: ``` ValueError: t...
You should use `zip()`: ``` for src, url in zip(filtered_items_list, filtered_items_url_list): print src, url ```
What's a faster operation, re.match/search or str.find?
4,901,523
22
2011-02-04T18:23:51Z
4,901,580
11
2011-02-04T18:29:11Z
[ "python", "performance" ]
For one off string searches, is it faster to simply use str.find/rfind than to use re.match/search? That is, for a given string, s, should I use: ``` if s.find('lookforme') > -1: do something ``` or ``` if re.match('lookforme',s): do something else ``` ?
Use this: ``` if 'lookforme' in s: do something ``` Regex need to be compiled first, which adds some overhead. Python's normal string search is very efficient anyways. If you search the same term a lot or when you do something more complex then regex become more useful.
What's a faster operation, re.match/search or str.find?
4,901,523
22
2011-02-04T18:23:51Z
4,901,653
56
2011-02-04T18:35:36Z
[ "python", "performance" ]
For one off string searches, is it faster to simply use str.find/rfind than to use re.match/search? That is, for a given string, s, should I use: ``` if s.find('lookforme') > -1: do something ``` or ``` if re.match('lookforme',s): do something else ``` ?
The question: which is faster is best answered by using `timeit`. ``` from timeit import timeit import re def find(string, text): if string.find(text) > -1: pass def re_find(string, text): if re.match(text, string): pass def best_find(string, text): if text in string: pass print ...
Object of custom type as dictionary key
4,901,815
110
2011-02-04T18:51:40Z
4,901,841
14
2011-02-04T18:55:19Z
[ "python", "dictionary" ]
What must I do to use my objects of a custom type as keys in a Python dictionary (where I don't want the "object id" to act as the key) , e.g. ``` class MyThing: def __init__(self,name,location,length): self.name = name self.location = location self.length = length ``` I'd want...
You override `__hash__` if you want special hash-semantics, and `__cmp__` or `__eq__` in order to make your class usable as a key. Objects who compare equal need to have the same hash value. Python expects `__hash__` to return an integer, returning `Banana()` is not recommended :) User defined classes have `__hash__`...
Object of custom type as dictionary key
4,901,815
110
2011-02-04T18:51:40Z
4,901,847
118
2011-02-04T18:55:44Z
[ "python", "dictionary" ]
What must I do to use my objects of a custom type as keys in a Python dictionary (where I don't want the "object id" to act as the key) , e.g. ``` class MyThing: def __init__(self,name,location,length): self.name = name self.location = location self.length = length ``` I'd want...
You need to add two methods: ``` class MyThing: def __init__(self,name,location,length): self.name = name self.location = location self.length = length def __hash__(self): return hash((self.name, self.location)) def __eq__(self, other): return (self.name, self.loca...
Object of custom type as dictionary key
4,901,815
110
2011-02-04T18:51:40Z
4,902,870
23
2011-02-04T20:58:30Z
[ "python", "dictionary" ]
What must I do to use my objects of a custom type as keys in a Python dictionary (where I don't want the "object id" to act as the key) , e.g. ``` class MyThing: def __init__(self,name,location,length): self.name = name self.location = location self.length = length ``` I'd want...
An alternative in Python 2.6 or above is to use `collections.namedtuple()` -- it saves you writing any special methods: ``` from collections import namedtuple MyThingBase = namedtuple("MyThingBase", ["name", "location"]) class MyThing(MyThingBase): def __new__(cls, name, location, length): obj = MyThingBas...
PIL how to scale text size in relation to the size of the image
4,902,198
13
2011-02-04T19:41:36Z
4,902,713
25
2011-02-04T20:43:15Z
[ "python", "fonts", "image-manipulation", "python-imaging-library", "scaling" ]
I'm trying to dynamically scale text to be placed on images of varying but known dimensions. The text will be applied as a watermark. Is there any way to scale the text in relation to the image dimensions? I don't require that the text take up the whole surface area, just to be visible enough so its easily identifiable...
You could just increment the font size until you find a fit. `font.getsize()` is the function that tells you how large the rendered text is. ``` import ImageFont, ImageDraw, Image image = Image.open('hsvwheel.png') draw = ImageDraw.Draw(image) txt = "Hello World" fontsize = 1 # starting font size # portion of image...
Django: How to make a form with custom templating?
4,902,333
13
2011-02-04T19:56:31Z
4,902,790
8
2011-02-04T20:49:29Z
[ "python", "django", "django-templates", "django-forms" ]
I have a model: ``` class Setting(models.Model): class Meta: abstract = True name = models.CharField(max_length=120, primary_key=True) description = models.CharField(max_length=300, blank=True) class IntegerSetting(Setting): value = models.IntegerField() ``` I would like to create a form th...
I don't think you need a formset here. Take a look [here](http://docs.djangoproject.com/en/dev/topics/forms/#customizing-the-form-template) if you want a custom template for one view. If you want to create your own {{ form.as\_foobar }}, just subclass forms.Form, something like this: ``` class MyForm(forms.Form): de...
Django: How to make a form with custom templating?
4,902,333
13
2011-02-04T19:56:31Z
4,903,745
14
2011-02-04T22:57:48Z
[ "python", "django", "django-templates", "django-forms" ]
I have a model: ``` class Setting(models.Model): class Meta: abstract = True name = models.CharField(max_length=120, primary_key=True) description = models.CharField(max_length=300, blank=True) class IntegerSetting(Setting): value = models.IntegerField() ``` I would like to create a form th...
``` <form action="/contact/" method="post"> {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }}: {{ field }} </div> {% endfor %} <p><input type="submit" value="Send message" /></p> </form> ``` You can find the complete document...
How to get the URL of a redirect with Python
4,902,523
23
2011-02-04T20:19:52Z
4,902,578
35
2011-02-04T20:27:06Z
[ "python", "redirect", "urllib2" ]
In Python, I'm using urllib2 to open a url. This url redirects to another url, which redirects to yet another url. I wish to print out the url after each redirect. For example -> = redirects to A -> B -> C -> D I want to print the URL of B, C and D (A is already known because it's the start URL).
You can easily get D by just asking for the current URL. ``` req = urllib2.Request(starturl, datagen, headers) res = urllib2.urlopen(req) finalurl = res.geturl() ``` To deal with the intermediate redirects you'll probably need to [build your own opener](http://docs.python.org/library/urllib2.html#urllib2.build_opener...
How to get the URL of a redirect with Python
4,902,523
23
2011-02-04T20:19:52Z
4,902,605
8
2011-02-04T20:29:53Z
[ "python", "redirect", "urllib2" ]
In Python, I'm using urllib2 to open a url. This url redirects to another url, which redirects to yet another url. I wish to print out the url after each redirect. For example -> = redirects to A -> B -> C -> D I want to print the URL of B, C and D (A is already known because it's the start URL).
Probably the best way is to subclass `urllib2.HTTPRedirectHandler`. Dive Into Python's [chapter on redirects](http://www.diveintopython.net/http_web_services/redirects.html) may be helpful.
Python - Acquiring a count of file extensions across all directories
4,903,878
2
2011-02-04T23:19:37Z
4,903,944
8
2011-02-04T23:30:39Z
[ "python" ]
we have a hardrive with hundreds of thousands of files i need to figure out how many of every file extension we have how can i do this with python? i need it to go through every directory. this lawyers at my company need this. it can be a total for the entire hardrive it does not have to be broken down by directory ...
Have a look at `os.walk` call in the os module and traverse through the entire directory tree. Get the extension using `os.path.splitext`. Maintain a dictionary where key the extension.lower() and increment the count of each extension that you encounter. ``` import os import collections extensions = collections.defaul...
Execute a block of python code with exec, capturing all its output?
4,904,079
9
2011-02-04T23:55:35Z
4,904,200
11
2011-02-05T00:17:27Z
[ "python", "dynamic", "io", "exec" ]
What's a good way to exec a bunch of python code, like `exec mycode`, and capture everything it prints to stdout into a string?
Try replacing the default sys.stdout, like in this snippet: ``` import sys from StringIO import StringIO buffer = StringIO() sys.stdout = buffer exec "print 'Hello, World!'" #remember to restore the original stdout! sys.stdout = sys.__stdout__ print buffer.getvalue() ```
django : Change default value for an extended model class
4,904,230
9
2011-02-05T00:22:53Z
4,904,399
8
2011-02-05T00:58:57Z
[ "python", "django", "django-models" ]
I posted a similar question a while earlier, but this one is different. I have a model structure of related classes like: ``` class Question(models.Model): ques_type = models.SmallIntegerField(default=TYPE1, Choices= CHOICE_TYPES) class MathQuestion(Question): //Need to change default value of ques_type her...
First, in this use of inheritance it is (at least according to my tests) not possible to change the default of the field in the child class. **`MathQuestion` and `Question` share the same field here, changing the default in the child class affects the field in the parent class.** Now if what only differs between `Math...
Find all list permutations of a string in Python
4,904,430
7
2011-02-05T01:05:41Z
4,904,496
8
2011-02-05T01:23:07Z
[ "python", "string", "permutation" ]
I have a string of letters that I'd like to split into all possible combinations (the order of letters must be remain fixed), so that: ``` s = 'monkey' ``` becomes: ``` combinations = [['m', 'onkey'], ['mo', 'nkey'], ['m', 'o', 'nkey'] ... etc] ``` Any ideas?
<http://wordaligned.org/articles/partitioning-with-python> contains an interesting post about sequence partitioning, here is the implementation they use: ``` #!/usr/bin/env python # From http://wordaligned.org/articles/partitioning-with-python from itertools import chain, combinations def sliceable(xs): '''Retu...
Type casting in python
4,904,763
2
2011-02-05T02:34:10Z
4,904,847
9
2011-02-05T03:02:29Z
[ "python", "django", "inheritance" ]
I looked at similar question on SO but none of them answer my problem. For Ex. [How do you cast an instance to a derived class?](http://stackoverflow.com/questions/1120156/how-do-you-cast-an-instance-to-a-derived-class) . But the answer doesn't seem to be what I want. Here is my situation. I have a class structure lik...
This sort of inheritance in Django-land smells like [multi-table inheritance](http://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance) to me. According to the doc, assuming everything is wired properly, you should be able to do: ``` baseobj.derived # note: small 'd' ```
Python: Converting GIF frames to PNG
4,904,940
9
2011-02-05T03:25:57Z
4,905,209
11
2011-02-05T04:51:09Z
[ "python", "png", "python-imaging-library", "animated-gif" ]
I'm very new to python, trying to use it to split the frames of a GIF into PNG images. ``` # Using this GIF: http://www.videogamesprites.net/FinalFantasy1/Party/Before/Fighter-Front.gif from PIL import Image im = Image.open('Fighter-Front.gif') transparency = im.info['transparency'] im.save('test1.png', transparenc...
I don't think you're doing anything wrong. See a similar issue here: [animated GIF problem](http://code.activestate.com/lists/python-image-sig/5245/). It appears as if the palette information isn't correctly treated for later frames. The following works for me: ``` def iter_frames(im): try: i= 0 wh...
How to incrementally train an nltk classifier
4,905,368
15
2011-02-05T05:50:43Z
4,908,925
9
2011-02-05T18:58:58Z
[ "python", "nltk" ]
I am working on a project to classify snippets of text using the python nltk module and the naivebayes classifier. I am able to train on corpus data and classify another set of data but would like to feed additional training information into the classifier after initial training. If I'm not mistaken, there doesn't app...
There's 2 options that I know of: 1) Periodically retrain the classifier on the new data. You'd accumulate new training data in a corpus (that already contains the original training data), then every few hours, retrain & reload the classifier. This is probably the simplest solution. 2) Externalize the internal model,...
agent-based simulation: performance issue: Python vs NetLogo & Repast
4,905,873
11
2011-02-05T08:26:28Z
4,905,989
8
2011-02-05T08:57:18Z
[ "python", "performance", "simulation", "netlogo", "agent-based-modeling" ]
I'm replicating a small piece of Sugarscape agent simulation model in Python 3. I found the performance of my code is ~3 times slower than that of NetLogo. Is it likely the problem with my code, or can it be the inherent limitation of Python? Obviously, this is just a fragment of the code, but that's where Python spen...
This probably won't give dramatic speedups, but you should be aware that local variables are quite a bit faster in Python compared to accessing globals or attributes. So you could try assigning some values that are used in the inner loop into locals, like this: ``` def look_around(self): max_sugar_point = self.poi...
Python Default Inheritance?
4,906,014
5
2011-02-05T09:04:07Z
4,906,028
8
2011-02-05T09:08:43Z
[ "python", "class", "inheritance" ]
If I define a class in Python such as: ``` class AClass: __slots__ = ['a', 'b', 'c'] ``` Which class does it inherit from? It doesn't seem to inherit from `object`.
If you define a class and don't declare any specific parent, the class becomes a "classic class", which behaves a bit differently than "new-style classes" inherited from object. See here for more details: <http://docs.python.org/release/2.5.2/ref/node33.html> Classic classes don't have a common root, so essentially, y...
Pycharm (Python IDE) doesn't auto complete Django modules
4,906,246
9
2011-02-05T10:07:39Z
7,276,265
12
2011-09-01T20:42:42Z
[ "python", "django", "init", "pycharm" ]
My Python IDE (pycharm) has stopped auto completing my modules (suggestions). I get unresolved references after every django module I try to import so: `from django` - works, however soon as I add a 'dot' it fails so `from django.db import models` gives me unresolved errors... The ackward thing is after compiling ref...
I had exactly the same issue and couldn't find a definitive answer. Just invalidating caches didn't work for me. The problem lies in the fact that, at some point, `__init__.py` files got registered as text files and messed up the indexing. I worked out this fix: * Preferences > File Types > Text Files. * Remove `__ini...
Find the word which all character is matching with other words in python
4,906,673
3
2011-02-05T11:49:41Z
4,906,750
7
2011-02-05T12:08:19Z
[ "python" ]
like umbellar = umbrella both are equal words. Input = ["umbellar","goa","umbrella","ago","aery","alem","ayre","gnu","eyra","egma","game","leam","amel","year","meal","yare","gun","alme","ung","male","lame","mela","mage" ] so output should be : output=[ ["umbellar","umbrella"], ["ago","goa"], ["aery","ayre","eyra","y...
``` from itertools import groupby def group_words(word_list): sorted_words = sorted(word_list, key=sorted) grouped_words = groupby(sorted_words, sorted) for key, words in grouped_words: group = list(words) if len(group) > 1: yield group ``` Example: ``` >>> group_words(["umbel...
Access environment variables from Python
4,906,977
625
2011-02-05T13:03:35Z
4,907,002
14
2011-02-05T13:07:06Z
[ "python", "environment-variables" ]
I set an environment variable that I want to access in my Python application. How do I get this value?
You can access to the environment variables using ``` import os print os.environ ``` Try to see the content of PYTHONPATH or PYTHONHOME environment variables, maybe this will be helpful for your second question. However you should clarify it.
Access environment variables from Python
4,906,977
625
2011-02-05T13:03:35Z
4,907,053
982
2011-02-05T13:18:00Z
[ "python", "environment-variables" ]
I set an environment variable that I want to access in my Python application. How do I get this value?
Environment variables are accessed through [os.environ](http://docs.python.org/2/library/os.html#process-parameters) ``` import os print os.environ['HOME'] ``` Or you can see a list of all the environment variables using: ``` os.environ ``` As sometimes you might need to see a complete list! ``` # using get will r...
Access environment variables from Python
4,906,977
625
2011-02-05T13:03:35Z
9,926,915
15
2012-03-29T13:58:20Z
[ "python", "environment-variables" ]
I set an environment variable that I want to access in my Python application. How do I get this value?
The original question (first part) was "how to check environment variables in Python." Here's how to check if $FOO is set: ``` try: os.environ["FOO"] except KeyError: print "Please set the environment variable FOO" sys.exit(1) ```