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 |
|---|---|---|---|---|---|---|---|---|---|
Why does this piece of code loop infinitely? | 11,486,193 | 2 | 2012-07-14T18:14:35Z | 11,486,242 | 10 | 2012-07-14T18:22:27Z | [
"python",
"infinite-loop"
] | I am in the process of writing a search engine for the experience and the knowledge. Right now, I am in the process of building a crawler and its accompanying utilities. One of these is the URL normalizer. This is what I am trying to build right now, and more specifically I am stuck at the point where I have to make a ... | By static analysis, it loops forever because your `while True` never breaks. So where can it break? Only at the `break` statement only if the `next_encounter` becomes equal to -1; so you can deduce that it never does.
Why doesn't it? Try a `print next_encounter` after `url.find`. You'll quickly see that
```
url = url... |
django argument of type 'LazySettings' is not iterable; how then to check if a setting exists? | 11,486,721 | 7 | 2012-07-14T19:22:31Z | 11,486,775 | 14 | 2012-07-14T19:27:44Z | [
"python",
"django",
"django-settings"
] | ```
from django.conf import settings
def my_view(self, request, *args, **kwargs):
if 'LOCAL' in settings and settings.LOCAL:
# do something
```
> TypeError at ... argument of type
> 'LazySettings' is not iterable
How then to check if a setting exists? Otherwise I get an attribute error. | You can use the [`hasattr`](http://docs.python.org/library/functions.html#hasattr) function:
```
if hasattr(settings, 'name_of_setting'):
# the setting exists
else:
# the setting does not exist
``` |
Need to iterate over a Python list in reverse as fast as possible | 11,486,922 | 5 | 2012-07-14T19:50:05Z | 11,486,935 | 12 | 2012-07-14T19:51:46Z | [
"python",
"list",
"python-3.x",
"iteration"
] | I'm using Python 3.2.3. What's the fastest way to iterate over a list in reverse? [::-1], reversed, list.reverse() or maybe some other way? I'm dealing with a list of about 5e6 elements or so, so I really need to avoid copying the list. | `reversed` should be best as it returns an iterator, so it doesn't copy the list, just yields one element at a time. (`list.reverse()` also will not copy the list, but it will mutate it, so the list will be backwards after you're done, whereas `reversed` doesn't modify the original list.) |
Need to iterate over a Python list in reverse as fast as possible | 11,486,922 | 5 | 2012-07-14T19:50:05Z | 11,487,119 | 10 | 2012-07-14T20:21:56Z | [
"python",
"list",
"python-3.x",
"iteration"
] | I'm using Python 3.2.3. What's the fastest way to iterate over a list in reverse? [::-1], reversed, list.reverse() or maybe some other way? I'm dealing with a list of about 5e6 elements or so, so I really need to avoid copying the list. | ```
>>> from timeit import Timer
>>> t = Timer('[x for x in l[::-1]]', 'l = list(range(100000))')
>>> t.timeit(number=1000)
5.549649953842163
>>> t = Timer('l.reverse(); [x for x in l]', 'l = list(range(100000))')
>>> t.timeit(number=1000)
4.548457145690918
>>> t = Timer('[x for x in reversed(l)]', 'l = list(range(1000... |
Python: list of lists | 11,487,049 | 11 | 2012-07-14T20:09:44Z | 11,487,098 | 8 | 2012-07-14T20:18:55Z | [
"python"
] | Running the code
```
listoflists = []
list = []
for i in range(0,10):
list.append(i)
if len(list)>3:
list.remove(list[0])
listoflists.append((list, list[0]))
print listoflists
```
returns
```
[([7, 8, 9], 0), ([7, 8, 9], 0), ([7, 8, 9], 0), ([7, 8, 9], 1), ([7, 8, 9], 2), ([7, 8, 9], 3), ([7,... | First, I strongly recommend that you rename your variable `list` to something else. `list` is the name of the built-in list constructor, and you're hiding its normal function. I will rename `list` to `a` in the following.
Python names are *references* that are bound to objects. That means that unless you create more t... |
Python: list of lists | 11,487,049 | 11 | 2012-07-14T20:09:44Z | 11,487,104 | 21 | 2012-07-14T20:19:27Z | [
"python"
] | Running the code
```
listoflists = []
list = []
for i in range(0,10):
list.append(i)
if len(list)>3:
list.remove(list[0])
listoflists.append((list, list[0]))
print listoflists
```
returns
```
[([7, 8, 9], 0), ([7, 8, 9], 0), ([7, 8, 9], 0), ([7, 8, 9], 1), ([7, 8, 9], 2), ([7, 8, 9], 3), ([7,... | Lists are a mutable type - in order to create a copy (rather than just passing the same list around), you need to do so explicitly:
```
listoflists.append((list[:], list[0]))
```
However, `list` is already the name of a Python built-in - it'd be better not to use that name for your variable. Here's a version that... |
Python: Left-side bracket assignment | 11,487,400 | 4 | 2012-07-14T21:07:10Z | 11,487,413 | 9 | 2012-07-14T21:09:36Z | [
"python",
"kotti"
] | So I found this code inside [Kotti](https://github.com/Pylons/Kotti "Kotti"):
```
[child] = filter(lambda ch: ch.name == path[0], self._children)
```
And I was wondering: What do the left-hand square brackets do? I did some testing in a python shell, but I can't quite figure out the purpose of it.
Bonus question: Wha... | This is list unpacking, of a list with only a single element. An equivalent would be:
```
child = filter(lambda ch: ch.name == path[0], self._children)[0]
```
(The exception would be if more than one element of `self._children` satisfied the condition- in that case, Kotti's code would throw an error (too many values ... |
Python Matplotlib Basemap overlay small image on map plot | 11,487,797 | 21 | 2012-07-14T22:17:25Z | 11,495,585 | 12 | 2012-07-15T21:01:17Z | [
"python",
"image",
"matplotlib",
"overlay",
"matplotlib-basemap"
] | I am plotting data from an aircraft on a map and I would like to insert this 75px by 29px PNG image of an airplane at the coordinates of the latest data point on the plot.

As far as I know and have read, `pyplot.imshow()` is the best way to accomplish this. However, I am... | With basemap, you can generally just use normal pyplot style commands if you translate your coordinates using the map instance first. In this case, you can just transform the extent into uv coordinates with:
```
x0, y0 = m(x[-1], y[-1])
x1, y1 = m(x[-1] + 0.5, y[-1] + 0.5)
```
And then subsequently you will be able t... |
Python Matplotlib Basemap overlay small image on map plot | 11,487,797 | 21 | 2012-07-14T22:17:25Z | 11,497,850 | 19 | 2012-07-16T03:43:58Z | [
"python",
"image",
"matplotlib",
"overlay",
"matplotlib-basemap"
] | I am plotting data from an aircraft on a map and I would like to insert this 75px by 29px PNG image of an airplane at the coordinates of the latest data point on the plot.

As far as I know and have read, `pyplot.imshow()` is the best way to accomplish this. However, I am... | Actually, for this you want to use a somewhat undocumented feature of matplotlib: the `matplotlib.offsetbox` module. There's an example here: <http://matplotlib.sourceforge.net/trunk-docs/examples/pylab_examples/demo_annotation_box.html>
In your case, you'd do something like this:
```
import matplotlib.pyplot as plt
... |
Why doesn't this set comprehension work? | 11,488,459 | 12 | 2012-07-15T00:30:21Z | 11,488,473 | 7 | 2012-07-15T00:32:59Z | [
"python"
] | In Python 2.6.5, given this list
mylist = [20, 30, 25, 20]
Why does this set comprehension not work?
```
>>> {x for x in mylist if mylist.count(x) >= 2}
File "<stdin>", line 1
{x for x in mylist if mylist.count(x) >= 2}
^
SyntaxError: invalid syntax
```
Thank you. | What version of Python are you using? Set comprehensions [appeared in 2.7.x+ and 3.x+](http://en.wikipedia.org/wiki/List_comprehension#Set_comprehension). If you're using an older version, you'll get a `SyntaxError: invalid syntax`:
```
>>> {x for x in mylist if mylist.count(x) >= 2}
File "<stdin>", line 1
{x fo... |
Why doesn't this set comprehension work? | 11,488,459 | 12 | 2012-07-15T00:30:21Z | 11,488,488 | 24 | 2012-07-15T00:35:50Z | [
"python"
] | In Python 2.6.5, given this list
mylist = [20, 30, 25, 20]
Why does this set comprehension not work?
```
>>> {x for x in mylist if mylist.count(x) >= 2}
File "<stdin>", line 1
{x for x in mylist if mylist.count(x) >= 2}
^
SyntaxError: invalid syntax
```
Thank you. | ```
$ python2.6
>>> mylist = [20, 30, 25, 20]
>>> {x for x in mylist if mylist.count(x) >= 2}
File "<stdin>", line 1
{x for x in mylist if mylist.count(x) >= 2}
^
SyntaxError: invalid syntax
$ python2.7
>>> mylist = [20, 30, 25, 20]
>>> {x for x in mylist if mylist.count(x) >= 2}
set([20])
```
You can ... |
How do you get a decimal in python? | 11,488,523 | 4 | 2012-07-15T00:45:43Z | 11,488,528 | 14 | 2012-07-15T00:47:50Z | [
"python"
] | In a truly surreal experience, I have spent 20 minutes on a task I thought would take 20 seconds.
I want to use decimals with 3 or more places. I cannot get anything over 1 place, and even in that case it's nonsense.
For example, I am unable to get `1/3` to show as anything other than `0` or `0.0`.
Googling led me t... | In Python 2, `1/3` does integer division because both operands are integers. You need to do float division:
```
1.0/3.0
```
Or:
```
from __future__ import division
```
Which will make `/` do real division and `//` do integer division. This is the default as of Python 3. |
Difference between Flask and Webapp2 (GAE) | 11,488,555 | 8 | 2012-07-15T00:53:06Z | 11,502,366 | 7 | 2012-07-16T10:21:04Z | [
"python",
"google-app-engine",
"flask",
"webapp2"
] | I am still collecting information but it seems that i can't figure out what the difference of those two frameworks are.
Currently I am using webapp2 with jinja2 and wtforms. It comes right out of the box in GAE and works fine.
If i compare flask and webapp2 i can only see that flask has jinja and wtforms already inte... | Flask abstracts a bit more away than webapp2 does. It's (optionally) function-based, so you don't need to make handler classes for everything. The decorator syntax used for route handling is a bit more succinct. All in all, though, they're equally powerful and anything you can do in one you can do in the other. If you ... |
Multiple applications with django | 11,488,838 | 9 | 2012-07-15T02:06:37Z | 11,491,940 | 9 | 2012-07-15T12:35:10Z | [
"python",
"django",
"frameworks"
] | I am studying the Django framework, reading the documentation, but have not found references on how to create more than one application on the same project, where each application has multiple apps. For example, the application Blog, with apps Users, Comments, Posts, ..., implementation and Tasks with the apps Clients,... | Each app will have these in their folder:
* views.py
* models.py
* others optionals (admin.py...)
So, you have :
```
Project
-- manage.py
-- Project
-- -- views.py
-- -- models.py
-- -- others
-- -- APP1
-- -- -- views.py
-- -- -- models.py
-- -- -- others
-- -- APP2
-- -- -- views.py
-- -- -- models.py
-- -- -- oth... |
Print a float with precision right justified | 11,489,326 | 6 | 2012-07-15T04:04:26Z | 11,489,335 | 11 | 2012-07-15T04:06:57Z | [
"python",
"string",
"printing",
"floating-point"
] | I'm somewhat of a newb to programming with python so please go easy on me. I'm trying to call the string attribute rjust and also specify precision for a floating point. Here's the code and sample output (note the 0.00 is not justified to the right):
```
print '%s: %s %s \tchange: %.2f' % (Instance1.symbol.ljust(5),
... | This shows an example of how to format your output with two decimal points using the older `%` formatting method:
```
v1 = 55.39
v2 = -1.15
v3 = 6.54
v4 = 0.00
print '%8.2f %8.2f' % (v1, v2)
print '%8.2f %8.2f' % (v3, v4)
```
the corresponding output:
```
55.39 -1.15
6.54 0.00
```
Alternative... |
How do I choose between Tesseract and OpenCV? | 11,489,824 | 49 | 2012-07-15T06:07:22Z | 11,489,853 | 42 | 2012-07-15T06:12:48Z | [
"python",
"opencv",
"computer-vision",
"ocr",
"tesseract"
] | I recently came across [Tesseract](http://code.google.com/p/tesseract-ocr/) and [OpenCV](http://opencv.willowgarage.com/wiki/). It looks like Tesseract is a full-fledged OCR engine and OpenCV can be used as a framework to create an OCR application/service.
I tried using Tesseract on some of my images and its accuracy ... | * Tesseract is an OCR engine. It's used, worked on and funded by Google specifically to read text from images, perform basic document segmentation and operate on specific image inputs (a single word, line, paragraph, page, limited dictionaries, etc.).
* OpenCV, on the other hand, is a computer vision library that inclu... |
How do I choose between Tesseract and OpenCV? | 11,489,824 | 49 | 2012-07-15T06:07:22Z | 11,489,886 | 39 | 2012-07-15T06:21:17Z | [
"python",
"opencv",
"computer-vision",
"ocr",
"tesseract"
] | I recently came across [Tesseract](http://code.google.com/p/tesseract-ocr/) and [OpenCV](http://opencv.willowgarage.com/wiki/). It looks like Tesseract is a full-fledged OCR engine and OpenCV can be used as a framework to create an OCR application/service.
I tried using Tesseract on some of my images and its accuracy ... | I am the author of that digit recognition tutorial you mentioned, and **I would say, that is no way substitute for tesseract.**
Tesseract is a really good OCR engine, may be the best OpenSource OCR engine.
The tutorial you mentioned is just a try, to understand most simple working of OCR.
So, if you are looking for ... |
No autoincrement for Integer Primary key in sqlite3 | 11,490,100 | 18 | 2012-07-15T07:00:00Z | 11,490,192 | 23 | 2012-07-15T07:16:02Z | [
"python",
"sqlite",
"sqlite3"
] | In the sqlite3 [faq](http://www.sqlite.org/faq.html#q1), it is mentioned that an integer primary key being fed a null value would autoincrement. But this is not happening for me.
to replicate, a table in sqlite3, `CREATE TABLE dummy( serial_num INTEGER PRIMARY KEY, name TEXT);` and fill it using python,
```
import sq... | This is one of SQLite's quirks. From the [fine manual](http://www.sqlite.org/lang_createtable.html#primkeyconst):
> According to the SQL standard, PRIMARY KEY should always imply NOT NULL. Unfortunately, due to a long-standing coding oversight, this is not the case in SQLite. Unless the column is an INTEGER PRIMARY KE... |
Create a common-used functions module | 11,491,090 | 6 | 2012-07-15T10:11:53Z | 11,491,406 | 7 | 2012-07-15T11:16:01Z | [
"python",
"design",
"code-design"
] | I have a big projects with dozens of different modules.
I do have lots of commonly-used functions which I use in many places in my project. For example:
* Checking if a string contains Hebrew characters
* Generating a random 8-letters string
* Guessing binary data's image mime type
* Converting HTML Entitles
* Etc...
... | Variations on `util` or `utils` seem to be common. Personally, if I have packages like `myproj.foo`, `myproj.bar` etc., I tend to have a `myproj.util` package with a module per area of intent (perhaps `myproj.util.http` for Web-related helpers, `myproj.util.data` for data structure manipulation, etc.). Such helpers are... |
ImportError: Environment variable DJANGO_SETTINGS_MODULE is undefined | 11,491,243 | 13 | 2012-07-15T10:46:22Z | 11,491,452 | 7 | 2012-07-15T11:22:10Z | [
"python",
"django",
"django-admin"
] | I'm going through the basic django tutorial and I'm running the server using python manage.py runserver. And I get this error that I'm not quite understanding how to sort out:
```
Traceback (most recent call last):
File "manage.py", line 1, in <module>
from polls.models import Poll
File "/Users/davidhaddad/Des... | You need to be able to import the value of `DJANGO_SETTINGS_MODULE` when you're in a location that isn't in your project root. One easy way of doing that is to (1) add the parent of your project folder to `PYTHONPATH`, (2) change `DJANGO_SETTINGS_MODULE` to `projectfoldername.settings`. |
Install pycairo in virtualenv | 11,491,268 | 26 | 2012-07-15T10:51:17Z | 11,686,044 | 11 | 2012-07-27T10:32:01Z | [
"python",
"installation",
"install",
"virtualenv",
"pycairo"
] | I've tried to install `pycairo` in a virtualenv to use in a Django project. I've ran the `pip install pycairo==1.10.0` command which finds the package and downloads it unlike other commands like `pip install pycairo`, etc. but when starting to install the package it throws an error.
Here's the log:
```
Downloading/un... | pycairo currently does not support installation through pip/distutils. The projectâs [install docs](http://cgit.freedesktop.org/py2cairo/tree/INSTALL) instructs to use either waf or autotools.
To use pycairo in a virtualenv, you need to:
* Install pycairo system-wide, preferably through your distributionâs packag... |
Install pycairo in virtualenv | 11,491,268 | 26 | 2012-07-15T10:51:17Z | 13,279,739 | 23 | 2012-11-07T22:59:18Z | [
"python",
"installation",
"install",
"virtualenv",
"pycairo"
] | I've tried to install `pycairo` in a virtualenv to use in a Django project. I've ran the `pip install pycairo==1.10.0` command which finds the package and downloads it unlike other commands like `pip install pycairo`, etc. but when starting to install the package it throws an error.
Here's the log:
```
Downloading/un... | Although py2cairo doesn't install nicely using pip, you can still install py2cairo into the virtual environment using the build instructions in the INSTALL file from the distribution.
You will need the cairo-dev/cairo-devel package for you os installed in order to build the package.
Do the following to install into y... |
Install pycairo in virtualenv | 11,491,268 | 26 | 2012-07-15T10:51:17Z | 14,205,767 | 51 | 2013-01-07T23:14:46Z | [
"python",
"installation",
"install",
"virtualenv",
"pycairo"
] | I've tried to install `pycairo` in a virtualenv to use in a Django project. I've ran the `pip install pycairo==1.10.0` command which finds the package and downloads it unlike other commands like `pip install pycairo`, etc. but when starting to install the package it throws an error.
Here's the log:
```
Downloading/un... | Good news, everyone!
I just released cairocffi:
<http://packages.python.org/cairocffi/>
Itâs a replacement for pycairo that installs with pip in a virtualenv, runs on Python 2 and 3, as well as PyPy.
```
pip install cairocffi
```
In your code:
```
import cairocffi as cairo
# Enjoy the same API as Pycairo.
```
F... |
Python with statement in C++ | 11,491,505 | 8 | 2012-07-15T11:31:01Z | 11,493,847 | 9 | 2012-07-15T16:59:32Z | [
"c++",
"python",
"with-statement",
"state-management"
] | I am trying to implement something similar to the [python with statement](http://docs.python.org/reference/compound_stmts.html#the-with-statement) in C++. As I plan to use it mainly with Qt-OpenGL the methods are called `bind` and `release` (in python `__enter__`, `__exit__`).
Code I came up with:
header:
```
#inclu... | The with statement is a way to do in python what is already the normal thing in C++. It is called RAII: Resource acquisition is initialization.
In python, when a class object is created, the `__init__` method is called (but this is not a strict guarantee). The `__del__` method is called by the garbage collector at som... |
get nth line of string in python | 11,491,835 | 2 | 2012-07-15T12:20:52Z | 11,491,868 | 7 | 2012-07-15T12:24:45Z | [
"python",
"python-3.x"
] | How can you get the *nth* line of a string in Python 3?
For example
```
getline("line1\nline2\nline3",3)
```
Is there any way to do this using stdlib/builtin functions?
I prefer a solution in Python 3, but Python 2 is also fine. | Try the following:
```
s = "line1\nline2\nline3"
print s.splitlines()[2]
``` |
OpenCV via python: Is there a fast way to zero pixels outside a set of rectangles? | 11,492,214 | 6 | 2012-07-15T13:14:24Z | 11,492,411 | 8 | 2012-07-15T13:46:09Z | [
"python",
"opencv"
] | I have an image of a face and I have used haar cascades to detect the locations (x,y,width,height) of the mouth, nose and each eye. I would like to set all pixels outside these regions to zero. What would be the fastest (computationally) way to do this? I'll eventually be doing it to video frames in real time. | I don't know whether it is the fastest way, but It is a way to do it.
Create a mask image with region of face as white, then apply bitwise\_and function with original image and mask image.
```
x = y = 30
w = h = 100
mask = np.zeros(img.shape[:2],np.uint8)
mask[y:y+h,x:x+w] = 255
res = cv2.bitwise_and(img,img,mask = ... |
why is the construct x = (Condition and A or B) used? | 11,492,309 | 9 | 2012-07-15T13:29:02Z | 11,492,312 | 15 | 2012-07-15T13:29:53Z | [
"python",
"python-3.x"
] | One of the answers to [this question](http://stackoverflow.com/questions/11491944/better-way-than-using-if-else-statement-in-python) is
```
print len(s)>5 and 'y' or 'n'
print(len(s)>5 and 'y' or 'n') #python3
```
if the length of `s > 5`, then `'y'` is printed otherwise `'n'` is. Please explain how/why this works. T... | This is an old-fashioned hack. The new way is:
```
print 'y' if len(s) > 5 else 'n'
```
The reason it works is because "A and B" will evaluate A, and if it is true, will evaluate to B. But if A is false, it doesn't need to evaluate B. Similarly, "C or D" will evaluate C, and if it is false, will continue on to evalua... |
Create List of Dictionary python | 11,492,656 | 11 | 2012-07-15T14:19:26Z | 11,492,690 | 27 | 2012-07-15T14:25:04Z | [
"python",
"list",
"dictionary"
] | I'm want to get all the iframe from webpage. This is my code
```
site = "http://" + url
f = urllib2.urlopen(site)
web_content = f.read()
soup = BeautifulSoup(web_content)
info = {}
content = []
for iframe in soup.find_all('iframe'):
info['src'] = iframe.get('src')
info['height'] = iframe.get('height')
in... | You are not creating a separate dictionary for each iframe, you just keep modifying the same dictionary over and over, and you keep adding additional references to that dictionary in your list.
Remember, when you do something like `content.append(info)`, you aren't making a copy of the data, you are simply appending a... |
Create List of Dictionary python | 11,492,656 | 11 | 2012-07-15T14:19:26Z | 11,492,780 | 15 | 2012-07-15T14:37:49Z | [
"python",
"list",
"dictionary"
] | I'm want to get all the iframe from webpage. This is my code
```
site = "http://" + url
f = urllib2.urlopen(site)
web_content = f.read()
soup = BeautifulSoup(web_content)
info = {}
content = []
for iframe in soup.find_all('iframe'):
info['src'] = iframe.get('src')
info['height'] = iframe.get('height')
in... | You have misunderstood the python list object. It is similar to a C pointer-array. It does not actually "copy" the object which you append to it. Instead, it just store a "pointer" to that object.
Try following code:
```
>>> d={}
>>> dlist=[]
>>> for i in xrange(0,3):
d['data']=i
dlist.append(d)
print(d)
... |
Install Twisted in python failed with 'No such file' | 11,493,644 | 11 | 2012-07-15T16:32:20Z | 11,493,677 | 33 | 2012-07-15T16:36:49Z | [
"python",
"linux",
"twisted"
] | I want use Twisted in Python, but when I installing ,in comes this error, how to handle it?
```
....
running build_ext
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c conftest.c -o conftest.o
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2... | You are missing the python development headers, needed to build packages that need to compile extensions.
If you are building on OSX, make sure you either install a prebuilt mac python package or if building python from source, use the framework flag when configuring. And also make sure you have XCODE installed so tha... |
Django class-based view: How do I pass additional parameters to the as_view method? | 11,494,483 | 52 | 2012-07-15T18:26:01Z | 11,494,666 | 66 | 2012-07-15T18:54:02Z | [
"python",
"django",
"django-views",
"django-generic-views"
] | I have a custom class-based view
```
# myapp/views.py
from django.views.generic import *
class MyView(DetailView):
template_name = 'detail.html'
model = MyModel
def get_object(self, queryset=None):
return queryset.get(slug=self.slug)
```
I want to pass in the slug parameter (or other parameters ... | If your urlconf looks something like this:
```
url(r'^(?P<slug>[a-zA-Z0-9-]+)/$', MyView.as_view(), name = 'my_named_view')
```
then the slug will be available inside your view functions (such as 'get\_queryset') like this:
```
self.kwargs['slug']
``` |
Django class-based view: How do I pass additional parameters to the as_view method? | 11,494,483 | 52 | 2012-07-15T18:26:01Z | 11,494,733 | 55 | 2012-07-15T19:04:13Z | [
"python",
"django",
"django-views",
"django-generic-views"
] | I have a custom class-based view
```
# myapp/views.py
from django.views.generic import *
class MyView(DetailView):
template_name = 'detail.html'
model = MyModel
def get_object(self, queryset=None):
return queryset.get(slug=self.slug)
```
I want to pass in the slug parameter (or other parameters ... | Every parameter that's passed to the `as_view` method is an instance variable of the View class. That means to add `slug` as a parameter you have to create it as an instance variable in your sub-class:
```
# myapp/views.py
from django.views.generic import *
class MyView(DetailView):
template_name = 'detail.html'
... |
Django class-based view: How do I pass additional parameters to the as_view method? | 11,494,483 | 52 | 2012-07-15T18:26:01Z | 12,787,333 | 11 | 2012-10-08T18:24:18Z | [
"python",
"django",
"django-views",
"django-generic-views"
] | I have a custom class-based view
```
# myapp/views.py
from django.views.generic import *
class MyView(DetailView):
template_name = 'detail.html'
model = MyModel
def get_object(self, queryset=None):
return queryset.get(slug=self.slug)
```
I want to pass in the slug parameter (or other parameters ... | If you want to add an object to the context for the template you can override `get_context_data` and add to its context. The request is also a part of *self* in case you need the *request.user*.
```
def get_context_data(self, **kwargs):
context = super(MyTemplateView, self).get_context_data(**kwargs)
i... |
Django class-based view: How do I pass additional parameters to the as_view method? | 11,494,483 | 52 | 2012-07-15T18:26:01Z | 17,182,333 | 12 | 2013-06-19T03:17:32Z | [
"python",
"django",
"django-views",
"django-generic-views"
] | I have a custom class-based view
```
# myapp/views.py
from django.views.generic import *
class MyView(DetailView):
template_name = 'detail.html'
model = MyModel
def get_object(self, queryset=None):
return queryset.get(slug=self.slug)
```
I want to pass in the slug parameter (or other parameters ... | It's worth noting you don't need to override `get_object()` in order to look up an object based on a slug passed as a keyword arg - you can use the attributes of a `SingleObjectMixin` <https://docs.djangoproject.com/en/1.5/ref/class-based-views/mixins-single-object/#singleobjectmixin>
```
# views.py
class MyView(Detai... |
Writing first interpreter with Python - choice of OCaml language | 11,494,533 | 2 | 2012-07-15T18:33:44Z | 11,494,583 | 7 | 2012-07-15T18:41:56Z | [
"python",
"parsing",
"compiler-construction",
"ocaml",
"interpreter"
] | I am reading code for Scheme interpreters with Python by P. Norvig, and I would like to try to write an interpreter with Python. This is properly the subject of post: [What language can a junior programmer implement an interpreter for it?](http://stackoverflow.com/questions/1446065/what-language-can-a-junior-programmer... | You seem to be saying you want to create an OCaml interpreter in Python (not a Python interpreter in OCaml, right?). OCaml per se is too large a language to choose for an educational project, in my opinion. I would choose a much smaller language. That's why Scheme is a good choice--the core language is quite small.
Wi... |
Python: Passing parameters by name | 11,495,031 | 4 | 2012-07-15T19:42:10Z | 11,495,061 | 9 | 2012-07-15T19:46:04Z | [
"python",
"function",
"parameters",
"arguments"
] | Hi I was wondering how to implement this in python. Lets say for example you have a function with two parameters and both print out to console
```
def myFunc(varA, varB):
print 'varA=', varA
print 'varB=', varB
```
I have seen libraries (pymel being the one that comes to mind) where it allows you to specify t... | That's normal Python behavior. If you're seeing errors then you're goofing up something else (e.g. missing a required parameter, trying to pass positional arguments by name, etc.).
```
>>> def func(foo, bar):
... print foo, bar
...
>>> func(bar='quux', foo=42)
42 quux
``` |
Difference in Python statsmodels OLS and R's lm | 11,495,051 | 19 | 2012-07-15T19:44:50Z | 11,495,086 | 14 | 2012-07-15T19:49:30Z | [
"python",
"pandas",
"rpy2",
"statsmodels"
] | I'm not sure why I'm getting slightly different results for a simple OLS, depending on whether I go through [panda's experimental rpy interface](http://pandas.pydata.org/pandas-docs/dev/r_interface.html) to do the regression in `R` or whether I use [statsmodels](http://statsmodels.sourceforge.net/devel/index.html) in P... | Looks like Python does not add an intercept by default to your expression, whereas R does when you use the formula interface..
This means you did fit two different models. Try
```
lm( y ~ x - 1, data)
```
in R to exclude the intercept, or in your case and with somewhat more standard notation
```
lm(num_rx ~ ridagey... |
Mapping using a generator | 11,495,504 | 2 | 2012-07-15T20:48:31Z | 11,496,242 | 12 | 2012-07-15T22:40:37Z | [
"python",
"list",
"map",
"generator"
] | I can't seem to make this happen with my brain no matter what I try but there must be a way to map with a generator function.
For example, if I want to multiply each member in the list [1,2,3,4,5,6,7,8,9,10] with the corresponding member in the list [1,2,3] so after the [1,2,3] list runs out it would restart:
```
... | The [itertools module](http://docs.python.org/library/itertools.html) is your friend. One way to do this would be to use `itertools.cycle` to loop over the second list:
```
>>> import itertools
>>> a = range(1, 11)
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> b = itertools.cycle([1,2,3])
>>> b
<itertools.cycle object at ... |
Redirect subprocess stderr to stdout | 11,495,783 | 15 | 2012-07-15T21:33:07Z | 11,495,784 | 23 | 2012-07-15T21:33:07Z | [
"python",
"stderr",
"subprocess"
] | I want to redirect the stderr output of a subprocess to stdout. The constant [`STDOUT`](http://docs.python.org/library/subprocess.html#subprocess.STDOUT) should do that, shouldn't it?
However,
```
$ python >/dev/null -c 'import subprocess;\
subprocess.call(["ls", "/404"],stderr=subprocess.STDO... | A close read of the [source code](http://hg.python.org/cpython/file/0b4d0c2173ad/Lib/subprocess.py#l1284) gives the answer. In particular, the [documentation](http://docs.python.org/library/subprocess.html#subprocess.STDOUT) is misleading when it says:
> `subprocess.STDOUT`
> Special value that (...) indicates that ... |
python: recursive check to determine whether string is a palindrome | 11,496,637 | 4 | 2012-07-15T23:55:38Z | 11,496,673 | 7 | 2012-07-16T00:01:23Z | [
"python",
"string",
"recursion"
] | My task is to define a procedure is\_palindrome, that takes as input a string, and returns a boolean indicating if the input string is a palindrome. In this case a single letter should return True, as should an empty string `''`.
Unfortunately, I'm not getting the expected results. I appreciate the help.
My code vers... | In your first example, you forgot a return statement:
```
def is_palindrome(s):
if s == '':
return True
else:
if (ord(s[0]) - ord(s[len(s)-1])) == 0:
# v-- forgot this here
return is_palindrome(s[1:len(s)-1])
else:
return False
``` |
Regular expression for letters, dash, underscore, numbers, and space | 11,497,206 | 2 | 2012-07-16T01:45:02Z | 11,497,236 | 7 | 2012-07-16T01:49:09Z | [
"python",
"regex"
] | This is my attempt
```
def matcher(ex):
if re.match(r'^[\w|\d][A-Za-z0-9_-]+$', ex):
print 'yes'
```
My goal is to match only submission that satisfy all the followings
1. begins with only a letter or a numeric digit, and
2. only letter, space, dash, underscore and numeric digit are allowed
3. all ending... | ```
def matcher(ex):
ex = ex.rstrip()
if re.match(r'^[a-zA-Z0-9][ A-Za-z0-9_-]*$', ex):
print 'yes'
```
Problems in your original regex:
1. `|` doesn't mean alternation in a character class, it means a pipe character literally.
2. You used `+` for your following characters, meaning one or more, so a o... |
TypeError:exceptions must be old-style classes or derived from BaseException, not str | 11,497,234 | 23 | 2012-07-16T01:48:55Z | 11,497,246 | 12 | 2012-07-16T01:50:22Z | [
"python",
"typeerror",
"raise"
] | Following is my code:
```
test = 'abc'
if True:
raise test + 'def'
```
And when i run this, it gives me the `TypeError`
```
TypeError: exceptions must be old-style classes or derived from BaseException, not str
```
So what kind of type should the `test` be? | It should be an exception.
You want to do something like:
```
raise RuntimeError(test + 'def')
```
In Python 2.5 and below, your code would work, as then it was allowed to raise strings as exceptions. This was a very bad decision, and so removed in 2.6. |
TypeError:exceptions must be old-style classes or derived from BaseException, not str | 11,497,234 | 23 | 2012-07-16T01:48:55Z | 11,497,264 | 28 | 2012-07-16T01:52:17Z | [
"python",
"typeerror",
"raise"
] | Following is my code:
```
test = 'abc'
if True:
raise test + 'def'
```
And when i run this, it gives me the `TypeError`
```
TypeError: exceptions must be old-style classes or derived from BaseException, not str
```
So what kind of type should the `test` be? | You can't `raise` a `str`. Only `Exception`s can be `raise`d.
So, you're better off constructing an exception with that string and raising that. For example, you could do:
```
test = 'abc'
if True:
raise Exception(test + 'def')
```
OR
```
test = 'abc'
if True:
raise ValueError(test + 'def')
```
Hope that h... |
TypeError:exceptions must be old-style classes or derived from BaseException, not str | 11,497,234 | 23 | 2012-07-16T01:48:55Z | 11,515,614 | 31 | 2012-07-17T03:25:59Z | [
"python",
"typeerror",
"raise"
] | Following is my code:
```
test = 'abc'
if True:
raise test + 'def'
```
And when i run this, it gives me the `TypeError`
```
TypeError: exceptions must be old-style classes or derived from BaseException, not str
```
So what kind of type should the `test` be? | The sole argument to raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from Exception).
Try this:
```
test = 'abc'
if True:
raise Exception(test + 'def')
``` |
New line Python | 11,497,376 | 77 | 2012-07-16T02:14:11Z | 11,497,391 | 110 | 2012-07-16T02:16:23Z | [
"python"
] | How would I specify a new line in python?
For a comparison to Java in a String you would do something like "First Line\r\nSecond Line"
So How would you do that in Python? For purposes of saving files with more then one line. | Depends on how correct you want to be. `\n` will usually do the job. If you really want to get it right you look up the newline character in the [`os` package](http://docs.python.org/library/os.html). (It's actually called `linesep`.)
Note: when writing to files using the Python api, do not use the `os.linesep`. Just ... |
New line Python | 11,497,376 | 77 | 2012-07-16T02:14:11Z | 19,032,709 | 17 | 2013-09-26T15:42:27Z | [
"python"
] | How would I specify a new line in python?
For a comparison to Java in a String you would do something like "First Line\r\nSecond Line"
So How would you do that in Python? For purposes of saving files with more then one line. | The new line character is `\n`. It is used inside a string.
Example:
```
print 'First line \n Second line'
```
where `\n` is the newline character.
This would yield the result:
```
First line
Second line
``` |
New line Python | 11,497,376 | 77 | 2012-07-16T02:14:11Z | 27,764,925 | 7 | 2015-01-04T11:13:02Z | [
"python"
] | How would I specify a new line in python?
For a comparison to Java in a String you would do something like "First Line\r\nSecond Line"
So How would you do that in Python? For purposes of saving files with more then one line. | You can either write in the new lines separately or in one string which is easier
# example 1
## Input
```
line1 = "hello how are you"
line2 = "I am testing the new line escape sequence"
line3 = "this seems to work"
```
you can write the '\n' separately
```
file.write(line1)
file.write("\n")
file.write(line2)
file... |
python decorator in flask | 11,497,693 | 5 | 2012-07-16T03:10:48Z | 11,498,250 | 11 | 2012-07-16T04:48:18Z | [
"python",
"decorator",
"flask"
] | Here is my example:
```
from flask import Flask
app = Flask(__name__)
def add1(f):
def inner(*args, **kwargs):
return str(f(*args, **kwargs))+'1'
return inner
@app.route('/')
@add1
def hello1():
return "hello1";
@app.route('/hello2')
@add1
def hello2():
return "hello2";
if(__name__ =='__m... | The problem is that Flask keeps track of the functions by name, and because the functions getting passed to `app.route(path)` are both called `inner`, the second one (`hello2`) overwrites the first. To fix this, you will need the name of the `inner` function to be changed to the name of the function it is decorating. Y... |
What is this kind of assignment in Python called? a = b = True | 11,498,441 | 10 | 2012-07-16T05:13:25Z | 11,498,454 | 24 | 2012-07-16T05:15:37Z | [
"python",
"variable-assignment"
] | I know about [tuple unpacking](http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences) but what is this assignment called where you have multiple equals signs on a single line? a la `a = b = True`
It always trips me up a bit especially when the RHS is mutable, but I'm having real trouble finding the ... | It's a chain of assignments and the term used to describe it is...
- Could I get a drumroll please?
### *Chained Assignment*.
---
I just gave it a quite google run and found that there isn't that much to read on the topic, probably since most people find it very straight-forward to use (and only the true geeks woul... |
How to transfer a file to ssh server in an ssh-connection made by Python's paramiko? | 11,499,507 | 9 | 2012-07-16T07:02:16Z | 11,519,239 | 11 | 2012-07-17T09:03:51Z | [
"python",
"file",
"ssh",
"transfer",
"paramiko"
] | I am using Python's paramiko packet to keep an ssh-connection with an server :
```
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect("xxx.xxx.xxx.xxx",22,username=xxx,password='',timeout=4)
```
I want to use this ssh-connection to transfer a file to ssh server, how can i do?
... | Try this:
```
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect("xxx.xxx.xxx.xxx",22,username=xxx,password='',timeout=4)
sftp = s.open_sftp()
sftp.put('/home/me/file.ext', '/remote/home/file.ext')
``` |
Simulating CLI Shell with python | 11,499,646 | 2 | 2012-07-16T07:13:50Z | 11,499,697 | 10 | 2012-07-16T07:16:48Z | [
"python",
"command-line-interface"
] | I was asked to simulate CLI with Python.
This is what I did
```
def somefunction(a,b):
//codes here
//consider some other functions too
print "--- StackOverFlow Shell ---"
while True:
user_input = raw_input("#> ")
splitit = user_input.split(" ")
if splitit[0] == "add":
firstNum = splitit[1]
... | Use python `CMD` Module:
Check few examples given on the below pages
<http://docs.python.org/library/cmd.html> # Support for line-oriented command interpreters
<http://www.doughellmann.com/PyMOTW/cmd> - # Create line-oriented command processors
`prompt` can be set to a string to be printed each time the user is ask... |
How to implement authentication for REST API? | 11,499,995 | 10 | 2012-07-16T07:41:45Z | 11,500,106 | 10 | 2012-07-16T07:49:37Z | [
"python",
"api",
"authentication",
"rest",
"oauth"
] | I'm creating a web based service that I want to expose as a REST API so that developers are able to create apps using it. I want developers to be able to create/manage user accounts and authenticate through API. How to handle this? OAuth or something else?
I'm using python,flask,mongodb for this. | We have settled on the following, using [OAuth 2](http://tools.ietf.org/html/draft-ietf-oauth-v2-30) (which is much preferable to OAuth 1). In particular we are using the [resource owner password credentials](http://tools.ietf.org/html/draft-ietf-oauth-v2-30#section-1.3.3) flow. As to how to integrate it into our RESTf... |
Python numpy bug or feature | 11,501,214 | 2 | 2012-07-16T09:11:06Z | 11,501,325 | 8 | 2012-07-16T09:16:52Z | [
"python",
"numpy"
] | Is this a bug or a feature?
```
import numpy as np
a=b=c=0
print 'a=',a
print 'b=',b
print 'c=',c
a = 5
print 'a=',a
print 'b=',b
print 'c=',c
b = 3
print 'a=',a
print 'b=',b
print 'c=',c
x=y=z=np.zeros(5)
print 'x=',x
print 'y=',y
print 'z=',z
x[2]= 10
print 'x=',x
print 'y=',y
print 'z=',z
y[3]= 20
print 'x=',x... | this is not a bug,, and it is not about numpy initialization, this is a python thing,,
check `id` of both x,y & z in your case, they point to same element
What your code is doing is multiple initialization in the same line, when this happens, only 1 object is created and all the variables refer to the same.
See the b... |
ImportError: No module named mock | 11,501,520 | 31 | 2012-07-16T09:27:02Z | 11,501,626 | 38 | 2012-07-16T09:33:07Z | [
"python",
"python-2.7",
"python-import",
"importerror"
] | So I am trying to use unittest.mock to mock some of my methods in my unit tests. I do:
```
from unittest.mock import MagicMock
f = open("data/static/mock_ffprobe_response")
subprocess.check_output = MagicMock(return_value=f.read())
f.close()
```
But I am getting:
```
ImportError: No module named mock
```
I tried:
... | `unittest` is a built-in module; `mock` is an external library (pre-3.3 betas, anyway). After installing `mock` via `pip install`, you import it not by using
```
from unittest.mock import MagicMock
```
but
```
from mock import MagicMock
```
Edit: `mock` has been included in the `unittest` module (since Python3.3), ... |
How to get top-level protobuf enum value name by number in python? | 11,502,113 | 12 | 2012-07-16T10:01:29Z | 11,502,621 | 16 | 2012-07-16T10:38:43Z | [
"python",
"protocol-buffers"
] | For example, I have proto-file `File.proto`:
```
enum Test {
ONE = 1;
TWO = 2;
}
```
I generate file `File_pb2.py` with protoc from `File.proto`.
I want in a python-code get string "ONE" (that corresponds to the name of File\_pb2.ONE) by value 1 (that corresponds to the value of File\_pb2.ONE) from generated file... | Assuming the generated python is located in File\_pb2.py code Try this:
```
file_pb2._TEST.values_by_number[1].name
```
In your case, this should give `'ONE'`
The reverse is :
```
file_pb2._TEST.values_by_name['ONE'].number
```
will give `1`.
EDIT: As correctly pointed by @dyoo in the comments, a new method was l... |
tuple digits to number conversion | 11,502,175 | 4 | 2012-07-16T10:05:53Z | 11,502,188 | 10 | 2012-07-16T10:07:12Z | [
"python",
"tuples"
] | I am working on python and I'm stuck on this issue.
Input (there is a tuple):
```
a = (0, 1)
```
Output:
```
a = 0.1
``` | **Single digits and only two elements**
```
>>> a = (0, 1)
>>> a[0] + a[1] * 0.1
0.1
```
**Multiple single digits**
```
>>> from itertools import count
>>> a = (0, 1)
>>> sum(n * 10 ** i for i, n in zip(count(0, -1), a))
0.1
>>> a = (0, 1, 5, 3, 2)
>>> sum(n * 10 ** i for i, n in zip(count(0, -1), a))
0.153200000000... |
How does Python's comma operator works during assignment? | 11,502,268 | 12 | 2012-07-16T10:13:09Z | 11,502,290 | 14 | 2012-07-16T10:15:21Z | [
"python",
"tuples",
"variable-assignment",
"comma"
] | I was reading the assignment statements in the Python docs ( <http://docs.python.org/reference/simple_stmts.html#assignment-statements> ).
In that it is quoted that:
> If the target is a target list enclosed in parentheses or in square brackets: The object must be an iterable with the same number of items as there ar... | All the expressions to the right of the assignment operator are evaluated before any of the assignments are made.
From the [Python tutorial: First steps towards programming](http://docs.python.org/tutorial/introduction.html#first-steps-towards-programming):
> The first line contains a multiple assignment: the variabl... |
How does Python's comma operator works during assignment? | 11,502,268 | 12 | 2012-07-16T10:13:09Z | 11,502,296 | 7 | 2012-07-16T10:15:49Z | [
"python",
"tuples",
"variable-assignment",
"comma"
] | I was reading the assignment statements in the Python docs ( <http://docs.python.org/reference/simple_stmts.html#assignment-statements> ).
In that it is quoted that:
> If the target is a target list enclosed in parentheses or in square brackets: The object must be an iterable with the same number of items as there ar... | You can think of the assignments happening in parallel on copies rather than sequentially and in-place.
This is why in python you dont need a swap function:
```
a, b = b, a
```
works sufficiently without requiring a temp variable, `c`. |
How does Python's comma operator works during assignment? | 11,502,268 | 12 | 2012-07-16T10:13:09Z | 11,502,307 | 11 | 2012-07-16T10:16:29Z | [
"python",
"tuples",
"variable-assignment",
"comma"
] | I was reading the assignment statements in the Python docs ( <http://docs.python.org/reference/simple_stmts.html#assignment-statements> ).
In that it is quoted that:
> If the target is a target list enclosed in parentheses or in square brackets: The object must be an iterable with the same number of items as there ar... | Python does not have a "comma operator" as in C. Instead, the comma indicates that a tuple should be constructed. The right-hand side of
```
a, b = a + b, a
```
is a tuple with th two items `a + b` and `a`.
On the left-hand side of an assignment, the comma indicates that sequence unpacking should be performed accord... |
User based filtering:Recommendation system | 11,502,550 | 11 | 2012-07-16T10:33:47Z | 11,504,446 | 8 | 2012-07-16T12:35:42Z | [
"python",
"filtering"
] | I know this is not a coding specific problem but this is the most suitable place for asking such questions.So please bear with me.
Suppose I have a dictionary like given below,listing ten liked items of each person
```
likes={
"rajat":{"music","x-men","programming","hindi","english","himesh","lil wayne","rap","tr... | *(Disclaimer, I am not adept in this field and only have a passing knowledge of collective filtering. The following is simply a collection of resources that I have found useful)*
The basics of this is covered quite comprehensively in [Chapter 2 of the "*Programming Collective Intelligence*" book](http://books.google.c... |
simple animation using tkinter | 11,502,879 | 2 | 2012-07-16T10:57:33Z | 11,505,034 | 7 | 2012-07-16T13:09:28Z | [
"python",
"user-interface",
"animation",
"tkinter"
] | I have a simple code to visualise some data using tkinter. A button click is bound to the function that redraws the next "frame" of data. However, I'd like to have the option to redraw automatically with a certain frequency. I'm very green when it comes to GUI programming (I don't have to do a lot for this code), so mo... | The basic pattern for doing animation with Tkinter is to write a function that draws a single frame. Then, use something like this to call it at regular intervals:
```
def animate(self):
self.draw_one_frame()
self.after(100, self.animate)
```
Once you call this function once, it will continue to draw frames a... |
Python: Function to flatten generator containing another generator | 11,503,065 | 5 | 2012-07-16T11:12:28Z | 11,503,200 | 11 | 2012-07-16T11:21:39Z | [
"python",
"python-3.x",
"generator"
] | I would like to know how to write python function which can flatten generator which yields another generators or iteables (which can also yield another generators/iterables ... possibly infinitely).
Here is example:
`gen(gen(1,2,3), gen(4,5,6), [7,8,9], [gen(10,11,12), gen(13,14,15)])`
note: `gen` - means generator ... | The easiest way is a recursive flattening function. Assuming you want to descend into every iterable except for strings, you could do this:
```
def flatten(it):
for x in it:
if (isinstance(x, collections.Iterable) and
not isinstance(x, str)):
for y in flatten(x):
yie... |
Clickable Tkinter labels | 11,504,571 | 3 | 2012-07-16T12:43:35Z | 11,504,993 | 8 | 2012-07-16T13:06:44Z | [
"python",
"tkinter"
] | I will be populating a frame with a list of labels representing URLs. The url's will be fed in from a list and can be between 3 and 5 in number, decided by user. What is the easiest way to make these url's clickable, so the user can get to the website displayed? Is there a better way to do this than use labels?
Thanks | Labels are fine I think. You just need to bind a callback to a mouse click.
```
def open_url(url):
pass #Open the url in a browser
for i,url in enumerate(url_list):
label=tk.Label(frame,text=url)
label.grid(row=i)
label.bind("<Button-1>",lambda e,url=url:open_url(url))
``` |
How to pass a method that receives parameters as a parameter of another function in Python | 11,504,693 | 2 | 2012-07-16T12:50:26Z | 11,504,848 | 8 | 2012-07-16T12:59:26Z | [
"python",
"parameter-passing"
] | I know this is valid:
```
def printValue():
print 'This is the printValue() method'
def callPrintValue(methodName):
methodName()
print 'This is the callPrintValue() method'
```
but is there a way to pass a method that receives parameters as a parameter of another function?
Doing this is not possible:
`... | Some people find `lambda` ugly, but it is a useful tool in cases like this. Rather than modifying the signature of `callPrintValue()`, you can use `lambda` to quickly define a new function that binds the arguments to `printValue()`. Whether you really want to do this depends on many factors, and it may be that adding a... |
Installing Python imaging libary (PIL) on Ubuntu | 11,505,532 | 6 | 2012-07-16T13:35:24Z | 11,505,879 | 21 | 2012-07-16T13:56:34Z | [
"python",
"ubuntu",
"python-imaging-library"
] | Something that probably shouldn't be causing me so many problems, is.
I'm trying to install PIL on my Ubuntu server. It's installing fine. However everytime I try and update the database to add the image field I get the following error:
Error: One or more models did not validate:
product.product: "image": To use Imag... | I had to install python-dev then install PIL inside my virtualenv.
All working now.
Thanks for your help all! :) |
Fit a gaussian function | 11,507,028 | 13 | 2012-07-16T15:02:17Z | 11,507,600 | 7 | 2012-07-16T15:35:31Z | [
"python",
"matplotlib",
"scipy",
"histogram",
"curve-fitting"
] | I have a histogram (see below) and I am trying to find the mean and standard deviation along with code which fits a curve to my histogram. I think there is something in SciPy or matplotlib that can help, but every example I've tried doesn't work.
```
import matplotlib.pyplot as plt
import numpy as np
with open('gau_b... | You can try sklearn gaussian mixture model estimation as below :
```
import numpy as np
import sklearn.mixture
gmm = sklearn.mixture.GMM()
# sample data
a = np.random.randn(1000)
# result
r = gmm.fit(a[:, np.newaxis]) # GMM requires 2D data as of sklearn version 0.16
print("mean : %f, var : %f" % (r.means_[0, 0], r... |
Fit a gaussian function | 11,507,028 | 13 | 2012-07-16T15:02:17Z | 11,507,723 | 26 | 2012-07-16T15:42:02Z | [
"python",
"matplotlib",
"scipy",
"histogram",
"curve-fitting"
] | I have a histogram (see below) and I am trying to find the mean and standard deviation along with code which fits a curve to my histogram. I think there is something in SciPy or matplotlib that can help, but every example I've tried doesn't work.
```
import matplotlib.pyplot as plt
import numpy as np
with open('gau_b... | Take a look at [this answer](http://stackoverflow.com/a/10143572/623518) for fitting arbitrary curves to data. Basically you can use [`scipy.optimize.curve_fit`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html) to fit any function you want to your data. The code below shows how you can... |
Automatic insertion of a colon after 'def', 'if' etc | 11,507,039 | 9 | 2012-07-16T15:02:50Z | 11,509,793 | 8 | 2012-07-16T17:53:36Z | [
"python",
"vim"
] | I recently switched to Vim at the request of a friend after Sublime Text 2 decided it didn't believe a module was installed even though it was...I digress.
I've managed to set up some stuff to make editing Python (currently me only language) easier. However, there's one feature I'm missing from Sublime. It would autom... | Rather than use `imap`s like @CG Mortion's answer suggests, I would strongly advise you to use `iabbr`s for these sorts of small fixes instead.
With an `imap` you would never be able to type "define" in insert mode unless you paused between pressing 'd', 'e', or 'f', or did one of a number of other hacky things to pre... |
How to compile and link multiple python modules (or packages) using cython? | 11,507,101 | 10 | 2012-07-16T15:06:23Z | 11,507,867 | 7 | 2012-07-16T15:50:07Z | [
"python",
"compilation",
"package",
"cython"
] | I have several python modules (organized into packages), which **depend on each other**. e.g.
* Module1
* Module2: imports Module1
* Module3
* Module4: imports Module3, Module 2, Module 1
Let's assume the relevant interface to develop applications is in Module4 and I want to generate a Module4.so using **cython**.
If... | Edit. First two options refer to Cython's specific code, what I've missed is that the question is about pure python modules, so option 3 is the solution.
There are a few options:
1.
See this "How To Create A Hierarchy Of Modules In A Package":
<http://wiki.cython.org/PackageHierarchy>
2.
I prefer the "include" state... |
Python Virtualenv - No module named virtualenvwrapper.hook_loader | 11,507,186 | 43 | 2012-07-16T15:11:22Z | 11,512,580 | 40 | 2012-07-16T21:06:47Z | [
"python",
"virtualenv",
"virtualenvwrapper"
] | I'm running Mac OS 10.6.8. and wanted to install in addition to python 2.6 also python 2.7 and use python 2.7 in a new virtualenv. I executed the following steps:
I downloaded python 2.7 and installed it:
```
http://www.python.org/ftp/python/2.7.3/python-2.7.3-macosx10.6.dmg
```
Then I run the command to setup a new... | The issue was solved following the steps below:
```
#switch the /usr/bin/python link to point to current python link
cd /usr/bin
rm -f python
ln -s /Library/Frameworks/Python.framework/Versions/Current/bin/python python
```
Re-arrange the export command in order that it is placed before the virtualenv commands in my ... |
Python Virtualenv - No module named virtualenvwrapper.hook_loader | 11,507,186 | 43 | 2012-07-16T15:11:22Z | 18,628,082 | 11 | 2013-09-05T05:00:25Z | [
"python",
"virtualenv",
"virtualenvwrapper"
] | I'm running Mac OS 10.6.8. and wanted to install in addition to python 2.6 also python 2.7 and use python 2.7 in a new virtualenv. I executed the following steps:
I downloaded python 2.7 and installed it:
```
http://www.python.org/ftp/python/2.7.3/python-2.7.3-macosx10.6.dmg
```
Then I run the command to setup a new... | Also, if you have macports, make sure `/opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin` is listed before `/Library/Frameworks/Python.framework/Versions/2.7/bin` and `/usr/local/bin` in PATH. Then set the following in you `.profile`:
```
export VIRTUALENVWRAPPER_PYTHON=`which python`
export VIRTUALENVWR... |
Perform an operation during the last iteration of a for loop in python | 11,507,901 | 3 | 2012-07-16T15:52:14Z | 11,507,962 | 8 | 2012-07-16T15:55:09Z | [
"python",
"for-loop"
] | I have a loop that is parsing lines of a text file:
```
for line in file:
if line.startswith('TK'):
for item in line.split():
if item.startwith('ID='):
*stuff*
if last_iteration_of_loop
*stuff*
```
I need to do a few assignments, but I cant do them u... | Just refer to the last line outside the for loop:
```
for line in file:
if line.startswith('TK'):
item = None
for item in line.split():
if item.startwith('ID='):
# *stuff*
if item is not None:
# *stuff*
```
The `item` variable is still available out... |
String comparison in python | 11,508,988 | 2 | 2012-07-16T16:58:45Z | 11,509,013 | 7 | 2012-07-16T17:00:07Z | [
"python",
"string",
"string-comparison"
] | I've been working my way through Python, but can't seem to get past string comparisons. I wrote a function that takes user input and evaluates it. User input can only be either "a" or "b", otherwise an error occurs. I have been using this:
```
def checkResponse(resp):
#Make the incoming string trimmed & lowercase
... | `|` is the bitwise or operator. You want `or`. (You actually want `and`.)
You wrote:
```
if respStr != "a" | respStr != "b":
```
Bitwise operators have high precedence (similar to other arithmetic operators), so this is equivalent to:
```
if respStr != ("a" | respStr) != "b":
```
where the two `!=` operations are ... |
How do I initialize a dictionary of empty lists in Python? | 11,509,721 | 39 | 2012-07-16T17:48:30Z | 11,509,743 | 31 | 2012-07-16T17:50:10Z | [
"python"
] | My attempt to programmatically create a dictionary of lists is failing to allow me to individually address dictionary keys. Whenever I create the dictionary of lists and try to append to one key, all of them are updated. Here's a very simple test case:
```
data = {}
data = data.fromkeys(range(2),[])
data[1].append('he... | Use [defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict) instead:
```
from collections import defaultdict
data = defaultdict(list)
data[1].append('hello')
```
This way you don't have to initialize all the keys you want to use to lists beforehand.
What is happening in your example is... |
How do I initialize a dictionary of empty lists in Python? | 11,509,721 | 39 | 2012-07-16T17:48:30Z | 11,509,759 | 44 | 2012-07-16T17:50:49Z | [
"python"
] | My attempt to programmatically create a dictionary of lists is failing to allow me to individually address dictionary keys. Whenever I create the dictionary of lists and try to append to one key, all of them are updated. Here's a very simple test case:
```
data = {}
data = data.fromkeys(range(2),[])
data[1].append('he... | Passing `[]` as second argument to `dict.fromkeys()` gives a rather useless result â all values in the dictionary will be the *same* list object.
In Python 2.7 or above, you can use a dicitonary comprehension instead:
```
data = {k: [] for k in range(2)}
```
In earlier versions of Python, you can use
```
data = d... |
Python showing error - name 'Object' is not defined | 11,510,416 | 4 | 2012-07-16T18:35:46Z | 11,510,439 | 13 | 2012-07-16T18:37:19Z | [
"python"
] | Python interpreter is showing NameError on using Object.
```
>>> class test(Object): pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Object' is not defined
```
Python version is 2.7.3.
I haven't been able to remove this error. Am I missing something here? | [`object`](http://docs.python.org/reference/datamodel.html#basic-customization) must be lower-case. Try
```
>>> class test(object): pass
```
In Python 3.x, you can also just leave it out:
```
>>> class test: pass
```
(In 2.x, you should not do that until you are ready to face the monstrosity of [classic classes](ht... |
Python - Facebook API - Need a working example | 11,510,850 | 33 | 2012-07-16T19:03:32Z | 11,511,505 | 56 | 2012-07-16T19:48:24Z | [
"python",
"facebook",
"api",
"signature",
"pyfacebook"
] | Ok, so i've googled around, i've found threads here on stackoverflow and i've checked the official Facebook wiki and.. and what not..
I now hope that one of you guys sits on a Facebook API sample code for Python.
This is what i've got so far and all i get is "Invalid Signature" via PyFacebook which appears to be a dea... | The [unofficial fork of the python sdk](https://github.com/pythonforfacebook/facebook-sdk) is still working fine for me.
To retrieve your friends, generate an access token here:
<https://developers.facebook.com/tools/access_token/>
Limitations:
* A user access token with user\_friends permission is required to view
... |
Check if Google App Engine datastore entity has a particular property | 11,511,070 | 2 | 2012-07-16T19:21:14Z | 11,511,531 | 10 | 2012-07-16T19:50:46Z | [
"python",
"database",
"google-app-engine",
"gae-datastore",
"gql"
] | I am new with developing web applications with Google App Engine.
I wanted to check for entities in my datastore **which have a null value set for a list property** (`db.ListProperty`). However, when I tried to check anything against the `entity.list` GAE gives the error:
`'super' object has no attribute 'list'`.
Af... | I can think of three ways around this.
You're probably running into this situation because originally your model did not have a 'list' attribute, and you added one later, so you might have older instances in the datastore without the 'list' attribute. You can write a mapreduce function that goes through your datastore... |
Embedding IPython Qt console in a PyQt application | 11,513,132 | 23 | 2012-07-16T21:54:22Z | 11,525,205 | 14 | 2012-07-17T14:51:33Z | [
"python",
"qt",
"pyqt4",
"ipython"
] | I'd like to embed an IPython qt console widget in a PyQt application I am working on. The code provided below (and adapted from <http://stackoverflow.com/a/9796491/1332492>) Accomplishes this for IPython v0.12. However, this crashes in IPython v0.13 at the line `self.heartbeat.start()` with `RuntimeError: threads can o... | Ok, this code seems to do the trick (i.e. it puts a non-blocking ipython interpreter in a Qt widget, which can be embedded into other widgets). Keywords passed to `terminal_widget` get added to the namespace of the widget
```
import atexit
from IPython.zmq.ipkernel import IPKernelApp
from IPython.lib.kernel import fi... |
Embedding IPython Qt console in a PyQt application | 11,513,132 | 23 | 2012-07-16T21:54:22Z | 20,610,786 | 7 | 2013-12-16T12:17:52Z | [
"python",
"qt",
"pyqt4",
"ipython"
] | I'd like to embed an IPython qt console widget in a PyQt application I am working on. The code provided below (and adapted from <http://stackoverflow.com/a/9796491/1332492>) Accomplishes this for IPython v0.12. However, this crashes in IPython v0.13 at the line `self.heartbeat.start()` with `RuntimeError: threads can o... | The accepted answer by @ChrisB is fine for IPython version 0.13, but it doesn't work with newer versions. From the [examples section](https://github.com/ipython/ipykernel/tree/master/examples) of the IPython kernel repository on github, [this](https://github.com/ipython/ipykernel/blob/master/examples/embedding/inproces... |
Is it good idea to store python package eggs in artifactory? | 11,513,360 | 4 | 2012-07-16T22:14:46Z | 11,516,508 | 8 | 2012-07-17T05:30:29Z | [
"python",
"artifactory"
] | Currently I am developing automated test framework. This test-framework has different packages. These packages will be refer in different project and these may be modified locally by the developer. I want to manage the python package eggs. I am thinking of using Artifactory. I tried to look for Artifactory help for Pyt... | There are numerous reasons to prefer a binary repository manager over a simple shared directory/SCM binary storage:
1. Fine grained security.
2. Ability to proxy and cache remote repositories.
3. More efficient handling of binaries (because it's a tool that's tailored to do so).
4. Sharing the binaries with other team... |
__hash__ for javascript? | 11,514,716 | 2 | 2012-07-17T01:02:06Z | 11,514,786 | 7 | 2012-07-17T01:16:35Z | [
"javascript",
"python",
"hash",
"associative-array",
"dictionary"
] | Is there a way to give objects in js custom hashes, just as overriding
```
__hash__()
```
in python let's someone define how a given object is hashed into a dictionary.
My underlying question is: what hash function is used to put js objects into associative arrays, and can I over-ride it? | You mean using objects as keys, how do you make sure you access that key again?
The magic method is `toString()`. Turns out all objects in JS use string keys, and the `toString()` method is called if it's not a string.
<http://jsfiddle.net/udsdT/1/>
```
var objA = {
data: 'yay',
toString: function() {
... |
How to use multiprocessing queue in Python? | 11,515,944 | 27 | 2012-07-17T04:17:08Z | 11,516,406 | 37 | 2012-07-17T05:18:04Z | [
"python",
"multithreading",
"multiprocessing"
] | I'm having much trouble trying to understand just how the multiprocessing queue works on python and how to implement it. Lets say I have two python modules that access data from a shared file, let's call these two modules a writer and a reader. My plan is to have both the reader and writer put requests into two separat... | > My main problem is that I really don't know how to implement multiprocessing.queue correctly, you cannot really instantiate the object for each process since they will be separate queues, how do you make sure that all processes relate to a shared queue (or in this case, queues)
This is a simple example of a reader a... |
c++ back end call the python level defined callbacks with swig wrapper | 11,516,809 | 6 | 2012-07-17T06:00:57Z | 11,522,655 | 9 | 2012-07-17T12:41:34Z | [
"c++",
"python",
"swig"
] | I am wrapping a library which was written in C++ to Python API
[libwebqq](https://github.com/gtkqq/libwebqq.git)
There is a type which is defined in boost function .
```
typedef boost::function<void (std::string)> EventListener;
```
Python level can define "EventListener" variable callbacks.
There is also a map str... | The problem seems to be that you haven't included any code to map from a Python callable to your `EventListener` class. It's not provided for free, although it's something that comes up fairly regularly, e.g. [here](http://stackoverflow.com/questions/11435760/python-callback-from-swig-pyobject-call-segfault) which acte... |
Indicating the statistically significant difference in bar graph | 11,517,986 | 7 | 2012-07-17T07:38:24Z | 11,543,637 | 8 | 2012-07-18T14:26:17Z | [
"python",
"matplotlib",
"figure"
] | I use a bar graph to indicate the data of each group. Some of these bars differ significantly from each other. How can I indicate the significant difference in the bar plot?
```
import numpy as np
import matplotlib.pyplot as plt
menMeans = (5, 15, 30, 40)
menStd = (2, 3, 4, 5)
ind = np.arange(4) # the x locat... | I've done a couple of things here that I suggest when working with complex plots. Pull out the custom formatting into a dictionary, it makes life simple when you want to change a parameter - and you can pass this dictionary to multiple plots. I've also written a custom function to `annotate` the itervalues, as a bonus ... |
Why am I getting an IndentationError when my code is properly indented? | 11,518,085 | 3 | 2012-07-17T07:44:41Z | 11,518,104 | 11 | 2012-07-17T07:46:03Z | [
"python"
] | Below is my entire code. When trying to execute it, I keep getting the error message
```
File "/Users/thomas/prac.py", line 15
elif choice == "1":
IndentationError: expected an indented block
```
Now I'm sure my indenting is right (I didn't mix tabs and spaces!) but I don't know why this isn't working:
```
keepPro... | A comment isn't enough to be considered an indentation. If you want to have an empty block then you need to use the `pass` statement. |
How to find the list in a list of lists whose sum of elements is the greatest? | 11,519,787 | 11 | 2012-07-17T09:36:19Z | 11,519,819 | 24 | 2012-07-17T09:37:50Z | [
"python",
"list",
"sum",
"max"
] | I have a list of lists:
```
x = [[1,2,3], [4,5,6], [7,8,9], [2,2,0]]
```
I want to get the list whose sum of its elements is the greatest in the list. In this case `[7,8,9]`.
I'd rather have a fancy `map` or `lambda` or list comprehension method than a `for/while/if` loop.
Best Regards | [`max` takes a key argument](http://docs.python.org/library/functions.html#max), with it you can tell max how to calculate the value for each item in an iterable. [`sum`](http://docs.python.org/library/functions.html#sum) will do nicely here:
```
max(x, key=sum)
```
Demo:
```
>>> x = [[1,2,3], [4,5,6], [7,8,9], [2,2... |
How to write a python function that adds all arguments? | 11,520,236 | 2 | 2012-07-17T10:05:29Z | 11,520,265 | 9 | 2012-07-17T10:06:58Z | [
"python",
"function",
"arguments",
"add"
] | I'd like to write a python function which adds all its arguments, using `+` operator. Number of arguments are not specified:
```
def my_func(*args):
return arg1 + arg2 + arg3 + ...
```
How do I do it?
Best Regards | Just use the [sum](http://docs.python.org/library/functions.html#sum) built-in function
```
>>> def my_func(*args):
... return sum(args)
...
>>> my_func(1,2,3,4)
10
>>>
```
---
**Edit:**
I don't know why you want to avoid sum, but [here we go](http://docs.python.org/library/functions.html#reduce):
```
>>> def ... |
Difference between del, remove and pop on lists | 11,520,492 | 87 | 2012-07-17T10:21:41Z | 11,520,540 | 138 | 2012-07-17T10:24:09Z | [
"python",
"list"
] | ```
>>> a=[1,2,3]
>>> a.remove(2)
>>> a
[1, 3]
>>> a=[1,2,3]
>>> del a[1]
>>> a
[1, 3]
>>> a= [1,2,3]
>>> a.pop(1)
2
>>> a
[1, 3]
>>>
```
Is there any difference between the above three methods to remove an element from a list? | Yes, `remove` removes the *first* matching *value*, not a specific index:
```
>>> a = [0, 2, 2, 3]
>>> a.remove(2)
>>> a
[0, 2, 3]
```
`del` removes a specific index:
```
>>> a = [3, 2, 2, 1]
>>> del a[1]
[3, 2, 1]
```
and `pop` returns the removed element:
```
>>> a = [4, 3, 5]
>>> a.pop(1)
3
>>> a
[4, 5]
```
Th... |
Difference between del, remove and pop on lists | 11,520,492 | 87 | 2012-07-17T10:21:41Z | 11,520,566 | 37 | 2012-07-17T10:25:04Z | [
"python",
"list"
] | ```
>>> a=[1,2,3]
>>> a.remove(2)
>>> a
[1, 3]
>>> a=[1,2,3]
>>> del a[1]
>>> a
[1, 3]
>>> a= [1,2,3]
>>> a.pop(1)
2
>>> a
[1, 3]
>>>
```
Is there any difference between the above three methods to remove an element from a list? | Use `del` to remove an element by index, `pop()` to remove it by index if you need the returned value, and `remove()` to delete an element by value. The latter requires searching the list, and raises `ValueError` if no such value occurs in the list.
When deleting index `i` from a list of `n` elements, the computationa... |
Filter a list and order items by relevance | 11,520,739 | 2 | 2012-07-17T10:36:21Z | 11,520,867 | 7 | 2012-07-17T10:44:19Z | [
"python",
"search",
"filtering"
] | I have a list of strings:
```
my_list = ['Paul', 'Robinson', 'Hismith', 'Smith']
```
I need to filter it and order the results by relevance:
```
> filter_list(my_list, 'smith')
> ['Smith', 'Hismith']
>
> filter_list(my_list, 'paul')
> ['Paul']
```
My list is small and it would be nice if I could use as less logic/... | Try something like the following (you may want to tweak the `cutoff=` option though):
```
import difflib
my_list = ['Paul', 'Robinson', 'Hismith', 'Smith']
print difflib.get_close_matches('Paul', my_list)
# ['Paul']
print difflib.get_close_matches('Smith', my_list)
# ['Hismith', 'Smith']
``` |
How to implement bash's vertical bar operator in python console? | 11,521,770 | 2 | 2012-07-17T11:42:47Z | 11,521,783 | 9 | 2012-07-17T11:43:33Z | [
"python",
"bash",
"console"
] | I wish i could write like
```
>>> print many_lines_message | tail -1
```
in python console, how to do that? | ```
print many_lines_message.splitlines()[-1]
```
If you want to simulate `head`, `tail` and/or `grep` commands, it is easy with slices and/or list comprehensions.
If you want to do something different, give us more examples. |
Typical Angular.js workflow and project structure (with Python Flask) | 11,522,151 | 203 | 2012-07-17T12:10:07Z | 11,529,868 | 33 | 2012-07-17T19:51:54Z | [
"javascript",
"python",
"flask",
"angularjs"
] | I am pretty new to this whole MV\* client-side framework frenzy. It doesn't have to be Angular.js, but I picked it because it feels more natural to me than either Knockout, Ember or Backbone. Anyway what is the workflow like? Do people start with developing a client-side application in Angular.js and then hooking up th... | You can start on either end.
You are right that you probably don't need a full server-side framework with AngularJS. It's typically better to serve static HTML/CSS/JavaScript files, and provide a RESTful API for the back end for the client to consume. One thing that you should probably avoid is mixing server-side temp... |
Typical Angular.js workflow and project structure (with Python Flask) | 11,522,151 | 203 | 2012-07-17T12:10:07Z | 15,144,980 | 150 | 2013-02-28T20:23:33Z | [
"javascript",
"python",
"flask",
"angularjs"
] | I am pretty new to this whole MV\* client-side framework frenzy. It doesn't have to be Angular.js, but I picked it because it feels more natural to me than either Knockout, Ember or Backbone. Anyway what is the workflow like? Do people start with developing a client-side application in Angular.js and then hooking up th... | I would start out by organizing the Flask app in the standard structure as follows:
```
app
|-- app.py
|-- static
|-- css
|-- img
|-- js
|-- templates
```
And as btford mentioned, if you are doing an Angular app, you'll want to focus on using Angular client-side templates and stay away from server-side te... |
Typical Angular.js workflow and project structure (with Python Flask) | 11,522,151 | 203 | 2012-07-17T12:10:07Z | 18,570,994 | 15 | 2013-09-02T10:29:38Z | [
"javascript",
"python",
"flask",
"angularjs"
] | I am pretty new to this whole MV\* client-side framework frenzy. It doesn't have to be Angular.js, but I picked it because it feels more natural to me than either Knockout, Ember or Backbone. Anyway what is the workflow like? Do people start with developing a client-side application in Angular.js and then hooking up th... | **edit**: The new [Angular2 style guide](https://angular.io/docs/ts/latest/guide/style-guide.html) suggests a similar, if not the same structure in much more detail.
The answer below target large scale projects.
I have spend quite some time thinking and experimenting with several approaches so I can combine some serve... |
Typical Angular.js workflow and project structure (with Python Flask) | 11,522,151 | 203 | 2012-07-17T12:10:07Z | 21,610,464 | 19 | 2014-02-06T17:56:37Z | [
"javascript",
"python",
"flask",
"angularjs"
] | I am pretty new to this whole MV\* client-side framework frenzy. It doesn't have to be Angular.js, but I picked it because it feels more natural to me than either Knockout, Ember or Backbone. Anyway what is the workflow like? Do people start with developing a client-side application in Angular.js and then hooking up th... | This official Jetbrains PyCharm video by John Lindquist (angular.js and jetbrains guru) is a nice starting point as it shows the interplay of webservice, database and angular.js within flask.
He builds a **pinterest clone** with flask, sqlalchemy, flask-restless and angular.js in less than 25 minutes.
Enjoy:
<http://... |
Python floating point arbitrary precision available? | 11,522,933 | 23 | 2012-07-17T12:54:48Z | 11,523,128 | 23 | 2012-07-17T13:05:25Z | [
"python",
"floating-point",
"floating-accuracy"
] | Just for fun and because it was really easy, I've written a short program to generate [Grafting numbers](http://math.wikia.com/wiki/Grafting_number), but because of floating point precision issues it's not finding some of the larger examples.
```
def isGrafting(a):
for i in xrange(1, int(ceil(log10(a))) + 2):
if... | In the standard library, the [`decimal`](http://docs.python.org/library/decimal.html#module-decimal) module may be what you're looking for. Also, I have found [mpmath](http://mpmath.org/) to be quite helpful. The [documentation](http://mpmath.org/doc/current/basics.html) has many great examples as well (unfortunately m... |
Python - Start a Function at Given Time | 11,523,918 | 4 | 2012-07-17T13:49:25Z | 11,524,152 | 9 | 2012-07-17T14:01:09Z | [
"python",
"time",
"scheduler"
] | How can I run a function in *Python*, at a given time?
For example:
```
run_it_at(func, '2012-07-17 15:50:00')
```
and it will run the function `func` at 2012-07-17 15:50:00.
I tried the [sched.scheduler](http://docs.python.org/library/sched.html#scheduler-objects), but it didn't start my function.
```
import time... | Reading the docs from <http://docs.python.org/py3k/library/sched.html>:
Going from that we need to work out a delay (in seconds)...
```
from datetime import datetime
now = datetime.now()
```
Then use `datetime.strptime` to parse '2012-07-17 15:50:00' (I'll leave the format string to you)
```
# I'm just creating a d... |
Python - Start a Function at Given Time | 11,523,918 | 4 | 2012-07-17T13:49:25Z | 21,392,114 | 8 | 2014-01-27T21:31:50Z | [
"python",
"time",
"scheduler"
] | How can I run a function in *Python*, at a given time?
For example:
```
run_it_at(func, '2012-07-17 15:50:00')
```
and it will run the function `func` at 2012-07-17 15:50:00.
I tried the [sched.scheduler](http://docs.python.org/library/sched.html#scheduler-objects), but it didn't start my function.
```
import time... | Take a look at the Advanced Python Scheduler, APScheduler: <http://packages.python.org/APScheduler/index.html>
They have an example for just this usecase:
<http://packages.python.org/APScheduler/dateschedule.html>
```
from datetime import date
from apscheduler.scheduler import Scheduler
# Start the scheduler
sched =... |
How to get your hands on exception object caught by default ipython exception handler? | 11,524,475 | 6 | 2012-07-17T14:18:38Z | 11,524,613 | 16 | 2012-07-17T14:24:05Z | [
"python",
"exception-handling",
"ipython"
] | Suppose I'm running some code interactively in IPython and it produces an uncaught exception, like:
```
In [2]: os.waitpid(1, os.WNOHANG)
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
<ipython-input-2-bacc7636b058... | I think `sys.last_value` should do the trick:
```
In [8]: 1/0
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
/home/ubuntu/<ipython console> in <module>()
ZeroDivisionError: integer division or modulo by zero
In ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.