title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
how to set bug tracker url in setup.py script
14,459,828
17
2013-01-22T13:35:22Z
14,460,216
14
2013-01-22T13:55:46Z
[ "python", "setup.py", "pypi" ]
I have just discovered the pypi web UI have a field 'Bug tracker URL' in edit of egg metadata. This field exists so I guess it is supported in setup.py but I can't find anything about this using google. So the question how do I set up this field in my setup.py so when doing a dist release on pypi it can be automaticl...
The entry is called `bugtrack_url`, but it's not being picked up from `setup.py`. From [context](https://twitter.com/jezdez/status/274420414422335488) and [code](https://bitbucket.org/loewis/pypi/commits/29c38d0902719c46d7378bc19e13cb9f15c65d31) I understand it is intended to be used through-the-web on PyPI only, as p...
Is it possible rename fields in the outputs of a Mongo query in PyMongo?
14,463,087
8
2013-01-22T16:17:27Z
14,464,090
10
2013-01-22T17:08:03Z
[ "python", "mongodb", "pymongo" ]
I have some documents in Mongo: ``` {"name" : "John", "age" : 26} {"name" : "Paul", "age" : 34} {"name" : "George", "age" : 36} ``` and another function that expects documents of the form: ``` {"name" : "XXX", "value" : YY} ``` Is it possible to rename the 'age' field to 'value' in a find query in PyMongo?
I'd use the `aggregate` method with `$project` operator. From mongodb web docs. > You may also use $project to rename fields. Consider the following > example: ``` db.article.aggregate( { $project : { title : 1 , page_views : "$pageViews" , bar : "$other.foo" }} );` ``` e.g. ``` db.mycol.aggregate...
How to disable python warnings
14,463,277
71
2013-01-22T16:26:49Z
14,463,321
81
2013-01-22T16:28:31Z
[ "python", "suppress-warnings" ]
I am working with code with throws a lot of (for me at the moment) useless warnings using the [`warnings`](http://docs.python.org/2/library/warnings.html) library. Reading (/scanning) the documentation I only found a way [to disable warnings for single functions](http://docs.python.org/2/library/warnings.html#temporari...
There's the [-W option](http://docs.python.org/2/using/cmdline.html#cmdoption-W). `python -W ignore foo.py`
How to disable python warnings
14,463,277
71
2013-01-22T16:26:49Z
14,463,362
109
2013-01-22T16:31:00Z
[ "python", "suppress-warnings" ]
I am working with code with throws a lot of (for me at the moment) useless warnings using the [`warnings`](http://docs.python.org/2/library/warnings.html) library. Reading (/scanning) the documentation I only found a way [to disable warnings for single functions](http://docs.python.org/2/library/warnings.html#temporari...
Did you look at the [suppress warnings](http://docs.python.org/2/library/warnings.html#temporarily-suppressing-warnings) section of the python docs? > If you are using code that you know will raise a warning, such as a deprecated function, but do not want to see the warning, then it is possible to suppress the warning...
How to disable python warnings
14,463,277
71
2013-01-22T16:26:49Z
17,654,868
29
2013-07-15T12:59:26Z
[ "python", "suppress-warnings" ]
I am working with code with throws a lot of (for me at the moment) useless warnings using the [`warnings`](http://docs.python.org/2/library/warnings.html) library. Reading (/scanning) the documentation I only found a way [to disable warnings for single functions](http://docs.python.org/2/library/warnings.html#temporari...
You can also define an environment variable (new feature in 2010 - i.e. python 2.7) ``` export PYTHONWARNINGS="ignore" ``` Test like this: *Default* ``` $ export PYTHONWARNINGS="default" $ python >>> import warnings >>> warnings.warn('my warning') __main__:1: UserWarning: my warning >>> ``` *Ignore* warnings ``` $...
What is the right way to have custom instance attributes in Django models?
14,463,451
6
2013-01-22T16:35:29Z
14,463,498
7
2013-01-22T16:37:44Z
[ "python", "django", "django-models" ]
I want to add custom attributes to instances of a Django model. These attributes should not be stored in the database. In any other class, the attributes would simply be initialized by the `__init__` method. I can already see three different ways to do it, and none of them are completely satisfying. I wonder if there ...
I would use the property decorator available in python ``` class Foo(Model): @property def bar(self): if not hasattr(self, '_bar'): self._bar = 1 return self._bar ``` Then you can access that just like a property instead of invoking a function with () You could even get a little ...
Using numpy to efficiently convert 16-bit image data to 8 bit for display, with intensity scaling
14,464,449
5
2013-01-22T17:25:42Z
14,467,016
8
2013-01-22T20:01:03Z
[ "python", "image", "image-processing", "numpy" ]
I frequently convert 16-bit grayscale image data to 8-bit image data for display. It's almost always useful to adjust the minimum and maximum display intensity to highlight the 'interesting' parts of the image. The code below does roughly what I want, but it's ugly and inefficient, and makes many intermediate copies o...
What you are doing is [halftoning](http://en.wikipedia.org/wiki/Halftone) your image. The methods proposed by others work great, but they are repeating a lot of expensive computations over and over again. Since in a `uint16` there are at most 65,536 different values, using a look-up table (LUT) can streamline things a...
Sorting text file by using Python
14,465,154
4
2013-01-22T18:05:56Z
14,465,236
19
2013-01-22T18:10:47Z
[ "python", "algorithm", "sorting" ]
I have a text file includes over than 10 million lines. Lines like that: ``` 37024469;196672001;255.0000000000 37024469;196665001;396.0000000000 37024469;196664001;396.0000000000 37024469;196399002;85.0000000000 37024469;160507001;264.0000000000 37024469;160506001;264.0000000000 ``` As you seen, delimiter is ";". i w...
Don't sort 10 million lines in memory. Split this up in batches instead: * Run 100 100k line sorts (using the file as an iterator, combined with `islice()` or similar to pick a batch). Write out to separate files elsewhere. * Merge the sorted files. Here is an merge generator that you can pass 100 open files and it'll...
Delete all objects in a list
14,465,279
9
2013-01-22T18:13:14Z
14,465,359
17
2013-01-22T18:18:22Z
[ "python", "object", "memory", "del" ]
I create many object then I store in a list. But I want to delete them after some time because I create news one and don't want my memory goes high (in my case, it jumps to 20 gigs of ram if I don't delete it). Here is a little code to illustrate what I trying to do: ``` class test: def __init__(self): se...
cpython at least works on reference counting to determine when objects will be deleted. Here you have multiple references to the same objects. `a` refers to the same object that `c[0]` references. When you loop over `c` (`for i in c:`), at some point `i` also refers to that same object. the `del` keyword removes a sing...
Delete all objects in a list
14,465,279
9
2013-01-22T18:13:14Z
14,465,362
15
2013-01-22T18:18:35Z
[ "python", "object", "memory", "del" ]
I create many object then I store in a list. But I want to delete them after some time because I create news one and don't want my memory goes high (in my case, it jumps to 20 gigs of ram if I don't delete it). Here is a little code to illustrate what I trying to do: ``` class test: def __init__(self): se...
Here's how you delete every item from a list. ``` del c[:] ``` Here's how you delete the first two items from a list. ``` del c[:2] ``` Here's how you delete a single item from a list (`a` in your case), assuming `c` is a list. ``` del c[0] ```
Embedding python error Import by filename is not supported
14,465,473
6
2013-01-22T18:26:11Z
14,466,001
7
2013-01-22T19:00:22Z
[ "c++", "python" ]
I'm trying to embed python in to my application and have got stuck pretty early on. I am embedding python into my C++ application and using the code found at this tutorial: <http://docs.python.org/2/extending/embedding.html#pure-embedding> My application matches entirely and compiles successfully no errors. However o...
I can't be sure, but I'm thinking that since pName is set to argv[1] and you're using the full path to call the script, then argv[1] is the full path. This means the code would try to import "C:\Users\workspace\dpllib\pyscript.py", which python can't (it can only import "pyscript"). Try running the script by just typi...
PYPY installation for dummies - What to do with the zip file
14,465,583
5
2013-01-22T18:33:59Z
14,465,695
8
2013-01-22T18:41:57Z
[ "python", "install", "pypy" ]
I'm trying to use Pypy to make my code run faster, but I don't know what to do with the zip file I downloaded from the site (I tried to read the directions but it moves too fast and I don't know what's going on). I was wondering if anyone had simple step by step instructions on how to install and use Pypy. Also, Im usi...
Unzip the zip file to a suitable location, e.g. `C:\pypy` then run `pypy.exe` from the folder to which you unzipped. There is no installation for pypy. Similarly to uninstall just delete the folder. Running `C:\pypy\pypy.exe` gives you an interactive prompt, just like the one you get for running any other version of P...
Sort a list of tuples by second value, reverse=True and then by key, reverse=False
14,466,068
11
2013-01-22T19:04:36Z
14,466,141
15
2013-01-22T19:08:55Z
[ "python", "sorting", "dictionary", "reverse" ]
I need to sort a dictionary by first, values with `reverse=True`, and for repeating values, sort by keys, `reverse=False` So far, I have this ``` dict = [('B', 3), ('A', 2), ('A', 1), ('I', 1), ('J', 1)] sorted(dict.items(), key=lambda x: (x[1],x[1]), reverse=True) ``` which returns... ``` [('B', 3), ('A', 2), ('J'...
The following works with your input: ``` d = [('B', 3), ('A', 2), ('A', 1), ('I', 1), ('J', 1)] sorted(d,key=lambda x:(-x[1],x[0])) ``` Since your "values" are numeric, you can easily reverse the sort order by changing the sign. In other words, this sort puts things in order by value (`-x[1]`) (the negative sign put...
Why is my python/numpy example faster than pure C implementation?
14,466,950
6
2013-01-22T19:57:39Z
14,467,210
14
2013-01-22T20:14:39Z
[ "python", "c", "performance", "numpy" ]
I have pretty much the same code in python and C. Python example: ``` import numpy nbr_values = 8192 n_iter = 100000 a = numpy.ones(nbr_values).astype(numpy.float32) for i in range(n_iter): a = numpy.sin(a) ``` C example: ``` #include <stdio.h> #include <math.h> int main(void) { int i, j; int nbr_values = 8...
First, turn on optimization. Secondly, subtleties matter. Your C code is definitely not 'basically the same'. Here is equivalent C code: sinary2.c: ``` #include <math.h> #include <stdlib.h> float *sin_array(const float *input, size_t elements) { int i = 0; float *output = malloc(sizeof(float) * elements); ...
How to approach implementing 'class Card' as required by Python textbook
14,467,933
3
2013-01-22T21:02:34Z
14,468,057
9
2013-01-22T21:10:23Z
[ "python", "class", "python-3.x" ]
I'm currently working through John Zelle's Python Programming: An Introduction to Computer Science and hit a snag in Chapter 10. I'm having a conceptual issue in understanding the why and how of this exercise and require some assistance on how to approach the problem. The exercise asks me to create a program that displ...
It looks like the only thing you need to change in your code is to change the line: ``` deck.append([num, suite]) ``` to ``` deck.append(Card(num, suite)) ``` This makes the `deck` variable a list of 52 `Card` objects. That's useful because `Card` objects have some built-in functionality that a list of two items (l...
Understanding the syntax of numpy.r_() concatenation
14,468,158
12
2013-01-22T21:16:08Z
14,468,501
11
2013-01-22T21:39:29Z
[ "python", "numpy", "concatenation" ]
I read the following in the numpy documentation for the function [r\_](http://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html): > A string integer specifies which axis to stack multiple comma > separated arrays along. A string of two comma-separated integers > allows indication of the minimum number of dime...
`'n,m'` tells `r_` to concatenate along `axis=n`, and produce a shape with at least `m` dimensions: ``` In [28]: np.r_['0,2', [1,2,3], [4,5,6]] Out[28]: array([[1, 2, 3], [4, 5, 6]]) ``` So we are concatenating along axis=0, and we would normally therefore expect the result to have shape `(6,)`, but since `m=...
How do I use pymongo to connect to an existing document collection/db?
14,468,992
5
2013-01-22T22:10:33Z
14,470,294
7
2013-01-23T00:04:52Z
[ "python", "mongodb", "pymongo" ]
On the command line, this works: ``` $ mongo > show dbs mydatabase 1.0GB ``` However, this does not: ``` $ python >>> import pymongo >>> connection = pymongo.MongoClient() >>> connection.mydatabase.find() ``` I read through docs here: <http://api.mongodb.org/python/current/tutorial.html> But do not understa...
[Connect to an existing database](http://api.mongodb.org/python/current/tutorial.html#getting-a-database) ``` import pymongo from pymongo import MongoClient connection = MongoClient() db = connection.mydatabase ``` [List existing databases](http://api.mongodb.org/python/current/api/pymongo/mongo_client.html#pymongo.m...
Google App Engine Local (Development) IPython Shell
14,469,685
8
2013-01-22T23:03:27Z
14,475,246
7
2013-01-23T08:26:36Z
[ "python", "google-app-engine", "ipython" ]
In my local Google app engine development environment, I would like to use an ipython shell, especially to be able to check out models with data that was created via `dev_server.py`, very much like how django's `manage.py shell` command works. (This means that the ipython shell should be started after `sys.path` was f...
For starters, you can put your application root directory and the SDK root directory (`google_appengine`) in your Python path. You'll also need a few libraries like `yaml`, either installed or added to the library path from the SDK's `lib` directory. Then you can import modules and call some features. ``` >>> import s...
scipy.optimize.curvefit() - array must not contain infs or NaNs
14,470,012
10
2013-01-22T23:35:13Z
14,473,417
8
2013-01-23T06:02:38Z
[ "python", "scipy", "curve-fitting" ]
I am trying to fit some data to a curve in Python using [`scipy.optimize.curve_fit`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html). I am running into the error `ValueError: array must not contain infs or NaNs`. I don't believe either my `x` or `y` data contain infs or NaNs: ``` >>...
***Why it is failing*** Not your input arrays are entailing `nans` or `infs`, but evaluation of your objective function at some X points and for some values of the parameters results in `nans` or `infs`: in other words, the array with values `func(x,alpha,beta,b)` for some x, alpha, beta and b is giving `nans` or `inf...
Python: How to extract URL from HTML Page using BeautifulSoup?
14,470,504
4
2013-01-23T00:28:39Z
14,470,573
7
2013-01-23T00:34:55Z
[ "python", "beautifulsoup" ]
I have a HTML Page with multiple divs like ``` <div class="article-additional-info"> A peculiar situation arose in the Supreme Court on Tuesday when two lawyers claimed to be the representative of one of the six accused in the December 16 gangrape case who has sought shifting of t... <a class="more" href="http://www.t...
According to your criteria, it returns three URLs (not two) - did you want to filter out the third? Basic idea is to iterate through the HTML, pulling out only those elements in your class, and then iterating through all of the links in that class, pulling out the actual links: ``` In [1]: from bs4 import BeautifulSo...
SQLAlchemy Bidirectional Relationship association proxy
14,470,688
7
2013-01-23T00:47:38Z
14,471,166
7
2013-01-23T01:45:06Z
[ "python", "sqlalchemy" ]
**Update:** For anyone having this issue, with the [very latest SQLAlchemy](http://www.sqlalchemy.org/trac/changeset/f4f5206907a9/) this behaviour has been fixed. **Original issue:** I am having a problem with getting association proxies to update correctly. Using the example models here: <http://docs.sqlalchemy.or...
`UserKeyword` requires that it be associated with both a `Keyword` and `User` at the same time in order to be persisted. When you associate it with a `User` and `Keyword`, but then remove it from the `User.user_keywords` collection, it's still associated with the `Keyword`. ``` >>> rory.keywords.remove(chicken) # emp...
Python 2.7.1: How to Open, Edit and Close a CSV file
14,471,049
13
2013-01-23T01:30:09Z
14,471,485
11
2013-01-23T02:27:19Z
[ "python", "csv", "python-2.7" ]
I'm having trouble opening a file (amount2.csv) making a change, saving it and closing the file. How does one open a file edit, save and close it? ``` import csv changes = { '1 dozen' : '12' } with open('amount2.csv', 'r') as f: reader = csv.reader(f) print f f.close() ``` my error: open file 'amount2.csv',...
The ``` <open file 'amount2.csv', mode 'r' at 0x1004656f0> ``` you are seeing isn't an error, but the result of your 'print f'. To instead see the contents of your file, you would do ``` with open('test.csv', 'rb') as f: reader = csv.reader(f) for row in reader: # row is a list of strings # u...
Python - Check if the last characters in a string are numbers
14,471,177
21
2013-01-23T01:46:45Z
14,471,204
7
2013-01-23T01:50:48Z
[ "python", "regex", "string", "numbers" ]
Basically I want to know how I would do this. Here's an example string: ``` string = "hello123" ``` I would like to know how I would check if the string ends in a number, then print the number the string ends in. I know for this certain string you could use regex to determine if it ends with a number then use strin...
This doesn't account for anything in the middle of the string, but it basically says that if the last number is a digit, it ends with a number. ``` In [4]: s = "hello123" In [5]: s[-1].isdigit() Out[5]: True ``` With a few strings: ``` In [7]: for s in ['hello12324', 'hello', 'hello1345252525', 'goodbye']: ...: ...
Python - Check if the last characters in a string are numbers
14,471,177
21
2013-01-23T01:46:45Z
14,471,236
32
2013-01-23T01:53:57Z
[ "python", "regex", "string", "numbers" ]
Basically I want to know how I would do this. Here's an example string: ``` string = "hello123" ``` I would like to know how I would check if the string ends in a number, then print the number the string ends in. I know for this certain string you could use regex to determine if it ends with a number then use strin...
``` import re m = re.search(r'\d+$', string) # if the string ends in digits m will be a Match object, or None otherwise. if m is not None: print m.group() ```
Retrieving verb stems from a list of verbs
14,472,333
2
2013-01-23T04:11:16Z
14,472,549
7
2013-01-23T04:36:37Z
[ "python", "regex", "string", "list", "nlp" ]
I have a list of strings which are all verbs. I need to get the word frequencies for each verb, but I want to count verbs such as "want", "wants", "wanting" and "wanted" as one verb. Formally, a “verb” is defined as a set of 4 words that are of the form {X, Xs, Xed, Xing} or of the form {Xe, Xes, Xed, Xing}. How wo...
There is a library called [nltk](http://nltk.org/) which has an insane array of functions for text processing. One of the subsets of functions are `stemmers`, which do just what you want (using algorithms/code developed by people with a lot of experience in the area). Here is the result using the [Porter Stemming](http...
How do I sort a list of datetime or date objects?
14,472,795
24
2013-01-23T05:03:59Z
14,472,824
41
2013-01-23T05:06:08Z
[ "python", "list", "date", "sorting", "datetime" ]
How do I sort a list of date and/or datetime objects? The accepted answer [here](http://stackoverflow.com/questions/9907670/how-to-sort-list-of-date-object) isn't working for me: ``` from datetime import datetime,date,timedelta a=[date.today(), date.today() + timedelta(days=1), date.today() - timedelta(days=1)] prin...
You're getting `None` because `list.sort()` it operates **in-place**, meaning that it doesn't return anything, but modifies the list itself. You only need to call `a.sort()` without assigning it to `a` again. There is a built in function `sorted()`, which returns a sorted version of the list - `a = sorted(a)` will do ...
List's ngrams with zip
14,473,477
4
2013-01-23T06:07:45Z
14,473,524
10
2013-01-23T06:11:37Z
[ "python", "sequence" ]
I can make a quick and dirty bigram sequence like so: ``` >>> w = ['a', 'b', 'c', 'd'] >>> zip(w, w[1:]) [('a', 'b'), ('b', 'c'), ('c', 'd')] ``` I want to make a function that accepts a numerical argument, n, of an n-gram. How do I take that argument and automatically fill in the zip arguments as shown above? In oth...
``` def make_ngrams(lst, n): return zip(*(lst[i:] for i in xrange(n))) ``` The `*` operator basically takes all elements of an iterable and feeds them as separate arguments into the function.
django-autocomplete-light simple usage
14,474,441
14
2013-01-23T07:25:31Z
14,479,521
18
2013-01-23T12:16:17Z
[ "python", "django", "autocomplete", "django-autocomplete-light" ]
I am trying to understand how to use [django-autocomplete-light](https://github.com/yourlabs/django-autocomplete-light) for an existing project. This seems like a good autocomplete solution for django for which I am already using normal ModelChoiceFields. So, let's say that I have a Model named MyModel that has an id ...
## Select widget is default for ModelChoiceField This form field does not specify a widget, so [the select widget should be used by default](https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield) with: ``` mymodel = forms.ModelChoiceField( required=True, queryset=shi...
Why does scipy.stats.nanmean give different result from numpy.nansum?
14,475,485
4
2013-01-23T08:42:14Z
14,476,501
8
2013-01-23T09:39:42Z
[ "python", "numpy", "floating-point", "scipy", "floating-point-precision" ]
``` >>> import numpy as np >>> from scipy import stats >>> a = np.r_[1., 2., np.nan, 4., 5.] >>> stats.nanmean(a) 2.9999999999999996 >>> np.nansum(a)/np.sum(~np.isnan(a)) 3.0 ``` I'm aware of the limitation of floating point representation. Just curious why the more clumsy expression seems to give "better" result.
First of all, here is `scipy.nanmean()` so that we know what we're comparing to: ``` def nanmean(x, axis=0): x, axis = _chk_asarray(x,axis) x = x.copy() Norig = x.shape[axis] factor = 1.0-np.sum(np.isnan(x),axis)*1.0/Norig x[np.isnan(x)] = 0 return np.mean(x,axis)/factor ``` Mathematically, t...
Reshape an array in NumPy
14,476,415
11
2013-01-23T09:35:20Z
14,476,457
17
2013-01-23T09:37:31Z
[ "python", "arrays", "numpy", "reshape" ]
Consider an array of the following form (just an example): ``` [[ 0 1] [ 2 3] [ 4 5] [ 6 7] [ 8 9] [10 11] [12 13] [14 15] [16 17]] ``` It's shape is [9,2]. Now I want to transform the array so that each column becomes a shape [3,3], like this: ``` [[ 0 6 12] [ 2 8 14] [ 4 10 16]] [[ 1 7 13] [ 3 ...
``` a = np.arange(18).reshape(9,2) b = a.reshape(3,3,2).swapaxes(0,2) # a: array([[ 0, 1], [ 2, 3], [ 4, 5], [ 6, 7], [ 8, 9], [10, 11], [12, 13], [14, 15], [16, 17]]) # b: array([[[ 0, 6, 12], [ 2, 8, 14], [ 4, 10, 16]], [[ 1, ...
python regex: replacing <number>st, <number>nd, <number>th etc in a adress with a single sub
14,478,380
2
2013-01-23T11:16:32Z
14,478,473
8
2013-01-23T11:20:53Z
[ "python", "regex" ]
I have many adresses like "East 19th Street" or "West 141st Street" and I would like to remove the "th" and the "st" in a single call to re.sub. ``` re.sub("(\d+)st|(\d+)nd|(\d+)rd|(\d+)th", "g<1>", "East 19th Street") ``` doesn't work because it is not always the first gorup which is caught I could chain the subs b...
Let's try this: ``` re.sub(r"(\d+)(st|nd|rd|th)\b", r"\1", str) ``` or better ``` re.sub(r"(?<=\d)(st|nd|rd|th)\b", '', str) ``` `\b` prevents things like `21strange` from being replaced. To replace only grammatically correct constructs, you can also try: ``` re.sub(r"(?<=1\d)th\b|(?<=1)st\b|(?<=2)nd\b|(?<=3)rd\b...
Form validation with WTForms and and autofill SQLAlchemy model with form data in Flask
14,478,830
3
2013-01-23T11:39:29Z
14,487,070
7
2013-01-23T18:46:42Z
[ "python", "flask", "flask-sqlalchemy", "flask-wtforms" ]
I have a form that i have to validate and then save the data in the database. I have a `SQLAlchemy` model called `Campaign` which looks something like this ``` from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy() class Campaign(db.Model): __tablename__ = 'campaigns' id = db.Column(db.Integer, primar...
You can use the .populate\_obj method like this: ``` if form.validate_on_submit(): campaign = Campaign() form.populate_obj(campaign) ``` Also check out the [docs](http://wtforms.simplecodes.com/docs/0.6.1/forms.html#wtforms.form.Form.populate_obj) on this.
Empty lines while using minidom.toprettyxml
14,479,656
10
2013-01-23T12:23:12Z
14,493,981
12
2013-01-24T04:29:22Z
[ "python", "xml", "pretty-print", "minidom" ]
I've been using a minidom.toprettyxml for prettify my xml file. When I'm creating XML file and using this method, all works grate, but if I use it after I've modified the xml file (for examp I've added an additional nodes) and then I'm writing it back to XML, I'm getting empty lines, each time I'm updating it, I'm gett...
I found a solution here: <http://code.activestate.com/recipes/576750-pretty-print-xml/> Then I modified it to take a string instead of a file. ``` from xml.dom.minidom import parseString pretty_print = lambda data: '\n'.join([line for line in parseString(data).toprettyxml(indent=' '*2).split('\n') if line.strip()]) ...
link axis between different plot (no subplots) using matplotlib
14,482,422
4
2013-01-23T14:46:47Z
14,489,467
7
2013-01-23T21:12:02Z
[ "python", "matplotlib", "plot" ]
Here is my question. I know there is a simple way to link the axis of different plot if they are subplots in the same figure this way : ``` import matplotlib.pyplot as plt fig = plt.figure() ax1 = fig.add_subplot(211) ax2 = fig.add_subplot(212, sharex=ax1) ``` But I wonder if there is a way to do the same link (when ...
You simply do the same thing, but with a different figure. ``` import matplotlib.pyplot as plt fig = plt.figure() ax1 = fig.add_subplot(111) fig2 = plt.figure() ax2 = fig2.add_subplot(111, sharex=ax1) ```
How to handle asyncore within a class in python, without blocking anything?
14,483,195
7
2013-01-23T15:28:47Z
14,496,815
7
2013-01-24T08:24:54Z
[ "python", "multithreading", "smtp", "asyncore" ]
I need to create a class that can receive and store SMTP messages, i.e. E-Mails. To do so, I am using `asyncore` according to an example posted [here](http://www.doughellmann.com/PyMOTW/smtpd/). However, `asyncore.loop()` is blocking so I cannot do anything else in the code. So I thought of using threads. Here is an e...
The solution provided might not be the most sophisticated solution, but it works reasonable and has been tested. First of all, the matter with `asyncore.loop()` is that it blocks until all `asyncore` channels are closed, as user *Wessie* pointed out in a comment before. Referring to the [smtp example](http://www.dough...
Chained, nested dict() get calls in python
14,484,386
17
2013-01-23T16:24:13Z
14,484,580
52
2013-01-23T16:32:26Z
[ "python", "mongodb", "dictionary", "list-comprehension", "pymongo" ]
I'm interrogating a nested dictionary using the dict.get('keyword') method. Currently my syntax is... ``` M = cursor_object_results_of_db_query for m in M: X = m.get("gparents").get("parent").get("child") for x in X: y = x.get("key") ``` However, sometimes one of the "parent" or "child" tags doesn't ...
Since these are all python `dict`s and you are calling the `dict.get()` method on them, you can use an empty `dict` to chain: ``` [m.get("gparents", {}).get("parent", {}).get("child") for m in M] ``` By leaving off the default for the last `.get()` you fall back to `None`. Now, if any of the intermediary keys is not ...
Python built-in types subclassing
14,484,749
6
2013-01-23T16:40:24Z
14,484,801
13
2013-01-23T16:42:01Z
[ "python", "initialization", "subclassing", "built-in-types" ]
What's wrong with this code? ``` class MyList(list): def __init__(self, li): self = li ``` When I create an instance of `MyList` with, for example, `MyList([1, 2, 3])`, and then I print this instance, all I get is an empty list `[]`. If `MyDict` is subclassing `list`, isn't `MyDict` a `list` itself? NB: both in Py...
You need to call the list initializer: ``` class MyList(list): def __init__(self, li): super(MyList, self).__init__(li) ``` Assigning to `self` in the function just replaces the local variable with the list, not assign anything to the instance: ``` >>> class MyList(list): ... def __init__(self, li...
Image in Image with cvMatchTemplate - but how?
14,486,353
7
2013-01-23T18:04:08Z
14,487,262
7
2013-01-23T18:57:12Z
[ "python", "image-processing", "opencv", "python-2.7", "computer-vision" ]
I want to find out at which position of a source-image a certain sub-image appears (e.g. source image: <http://i.pictr.com/6xg895m69q.png>, sub-image: <http://i.pictr.com/jdaz9zwzej.png>). As far as I know it is necessary to transform the arrays to make them "readable" to OpenCV, this is what I tried, but for some reas...
``` import sys import cv2 import numpy img = cv2.imread(sys.argv[1]) template = cv2.imread(sys.argv[2]) th, tw = template.shape[:2] result = cv2.matchTemplate(img, template, cv2.TM_CCORR_NORMED) threshold = 0.99 loc = numpy.where(result >= threshold) for pt in zip(*loc[::-1]): cv2.rectangle(img, pt, (pt[0] + tw, ...
Flask confusion with app
14,486,370
13
2013-01-23T18:05:26Z
14,486,824
8
2013-01-23T18:32:52Z
[ "python", "flask" ]
I am starting a `flask` project, and in my code I have ``` from flask import Flask, render_template, abort app = Flask(__name__) ``` Now what exactly is `app`? I am following [this guide](http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world) and I am particularly confused about the structur...
The author made his code needlessly confusing by choosing a package name that is the same as Flask's usual application object instance name. This is the one you'll be most interested in: ``` app = Flask(__name__) ``` Here is the documentation on the Flask application object: <http://flask.pocoo.org/docs/api/#applica...
Flask confusion with app
14,486,370
13
2013-01-23T18:05:26Z
14,490,018
13
2013-01-23T21:47:31Z
[ "python", "flask" ]
I am starting a `flask` project, and in my code I have ``` from flask import Flask, render_template, abort app = Flask(__name__) ``` Now what exactly is `app`? I am following [this guide](http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world) and I am particularly confused about the structur...
I think the main confusion is in the line: ``` from app import app ``` You have a python package (a folder with `__init__.py` file) named "app". From this folder, you are now importing the variable "app" that you defined below in `__init__.py` file: ``` app = Flask(__name__) ``` Rename the folder from app to say "m...
What is Python's coerce() used for?
14,486,802
13
2013-01-23T18:31:25Z
14,496,271
11
2013-01-24T07:48:30Z
[ "python", "type-conversion", "python-2.x", "built-in" ]
What are common uses for Python's built-in `coerce` function? I can see applying it if I do not know the `type` of a numeric value [as per the documentation](http://docs.python.org/2/library/functions.html#coerce), but do other common usages exist? I would guess that `coerce()` is also called when performing arithmetic...
Its a left over from [early python](http://docs.python.org/release/1.5.2/ref/numeric-types.html), it basically makes a tuple of numbers to be the same underlying number type e.g. ``` >>> type(10) <type 'int'> >>> type(10.0101010) <type 'float'> >>> nums = coerce(10, 10.001010) >>> type(nums[0]) <type 'float'> >>> type...
Dropbox Python API: File size detection may have failed
14,487,507
2
2013-01-23T19:10:31Z
14,487,553
8
2013-01-23T19:14:26Z
[ "python", "api", "dropbox" ]
I'm attempting to upload a text file to Dropbox using this code: ``` def uploadFile(file): f = open('logs/%s.txt' % file) response = client.put_file('/%s.txt' % file, f) print "Uploaded log file %s" % file ``` Connecting to dropbox works perfectly fine, it's just when I upload files I recieve this error: ...
Sounds like you are a victim of newline unification. The file object reports a file size of 18 bytes (`"abcdefghijklmnop\r\n"`) but you read only 17 bytes (`"abcdefghijklmnop\n"`). Open the file in binary mode to avoid this: ``` f = open('logs/%s.txt' % file, 'rb') ``` > The default is to use text mode, which may co...
turning beautifulsoup output into matrix
14,487,526
5
2013-01-23T19:12:04Z
14,488,618
7
2013-01-23T20:19:12Z
[ "python", "matrix", "beautifulsoup" ]
I have scraped web data thanks to beautifulsoup, but i'm having trouble turning the output into a matrix/array that i can manipulate. ``` from bs4 import BeautifulSoup import urllib2 headers = { 'User-Agent' : 'Mozilla/5.0' } req = urllib2.Request('http://statsheet.com/mcb/teams/duke/game_stats', None, headers) html ...
You can use [pandas](http://pandas.pydata.org/). This example will convert the data into a *pandas* `DataFrame` that offers convenient methods for further processing the data, like splitting the columns or converting the them into a different data type. --- From the [docs](http://pandas.pydata.org/pandas-docs/stable/...
Drop row in Panda Series and clean up index
14,487,562
8
2013-01-23T19:14:55Z
14,487,598
7
2013-01-23T19:17:24Z
[ "python", "pandas", "series" ]
I have a Panda Series and based on a random number I want to pick a row (5 in the code example below) and drop that row. When the row is dropped I want to create a new index for the remaining rows (0 to 8). The code below: ``` print 'Original series: ', sample_mean_series print 'Length of original series', len(sample_...
Somewhat confusingly, `reindex` does not mean "create a new index". To create a new index, just assign to the `index` attribute. So at your last step just do `sample_mean_series.index = range(len(sample_mean_series))`.
get class name for empty queryset in django
14,487,690
18
2013-01-23T19:24:01Z
14,487,781
21
2013-01-23T19:29:33Z
[ "python", "django", "django-models", "django-views" ]
I have empty queryset of model *Student* ``` students = Students.objects.all() ``` If the above queryset is empty, then how can i get the model(class name)? How can i get the model name for empty queryset? EDIT: How can i get the app name from the queryset?
``` >>> students = Students.objects.all() # The queryset's model class: >>> students.model project.app.models.Student # Name of the model class: >>> students.model.__name__ 'Student' # Import path of the models module: >>> students.model.__module__ 'project.app.models' # Django app name: >>> students.model._meta.ap...
How to Fix Python Nose: Coverage not available: unable to import coverage module
14,488,601
36
2013-01-23T20:17:53Z
14,488,761
52
2013-01-23T20:28:11Z
[ "python", "nose", "coverage.py", "python-coverage" ]
I can't seem to get code coverage with Nose to work, despite having the plugin installed. Any ideas on how to fix this? ``` 12:15:25 ~/sandbox/ec$ nosetests --plugins Plugin xunit Plugin deprecated Plugin skip Plugin multiprocess Plugin failuredetail Plugin capture Plugin logcapture Plugin coverage Plugin attributese...
Have you tried `pip install coverage`? The coverage plugin depends on separate coverage module, which is not a nose's dependency, so needs to be installed manually.
Convert words between verb/noun/adjective forms
14,489,309
19
2013-01-23T21:01:47Z
16,752,477
9
2013-05-25T18:05:18Z
[ "python", "nlp", "nltk", "wordnet" ]
i would like a python library function that translates/converts across different parts of speech. sometimes it should output multiple words (e.g. "coder" and "code" are both nouns from the verb "to code", one's the subject the other's the object) ``` # :: String => List of String print verbify('writer') # => ['write']...
This is more a heuristic approach. I have just coded it so appologies for the style. It uses the derivationally\_related\_forms() from wordnet. I have implemented nounify. I guess verbify works analogous. From what I've tested works pretty well: ``` from nltk.corpus import wordnet as wn def nounify(verb_word): ""...
Python unittest - asserting dictionary with lists
14,491,164
7
2013-01-23T23:13:34Z
14,493,005
7
2013-01-24T02:36:26Z
[ "python", "unit-testing", "dictionary", "assert" ]
While writing some tests for my class, I encountered interesting simple problem. I would like to assertDictEqual two dictionaries containing some list. But this lists may not be sorted in a same way -> which results in failed test Example: ``` def test_myobject_export_into_dictionary(self): obj = MyObject() r...
You might try [PyHamcrest](https://github.com/hamcrest/PyHamcrest) *(Example corrected)* ``` assert_that(obj.exportToDict(), has_entries( { 'state': 2347, 'neighbours': contains_inanyorder(1,2,3) })) ``` (The first value 2347 actually gets wrap...
Gevent/Eventlet monkey patching for DB drivers
14,491,400
5
2013-01-23T23:36:04Z
14,492,660
13
2013-01-24T01:55:45Z
[ "python", "asynchronous", "pymongo", "gevent", "eventlet" ]
After doing Gevent/Eventlet monkey patching - can I assume that whenever DB driver (eg *redis-py*, *pymongo*) uses IO through standard library (eg `socket`) it will be asynchronous? So using eventlets monkey patching is enough to make eg: *redis-py* non blocking in eventlet application? From what I know it should be ...
You can assume it will be magically patched if all of the following are true. * You're sure of the I/O is built on top of standard Python `socket`s or other things that `eventlet`/`gevent` monkeypatches. No files, no native (C) socket objects, etc. * You pass `aggressive=True` to `patch_all` (or `patch_select`), or yo...
Scipy: Do sparse matrices support advanced indexing?
14,491,548
7
2013-01-23T23:49:54Z
14,492,151
10
2013-01-24T00:57:36Z
[ "python", "numpy", "scipy" ]
No problem: ``` >>> t = np.array([[1,1,1,1,1],[2,2,2,2,2],[3,3,3,3,3],[4,4,4,4,4],[5,5,5,5,5]]) >>> x = np.arange(5).reshape((-1,1)); y = np.arange(5) >>> print (t[[x]],t[[y]]) ``` Big problem: ``` >>> s = scipy.sparse.csr_matrix(t) >>> print (s[[x]].toarray(),s[[y]].toarray()) Traceback (most recent call last): F...
sparse matrices have a very limited indexing support, and what is available depends on the format of the matrix. For example: ``` >>> a = scipy.sparse.rand(100,100,format='coo') >>> a[2:5, 6:8] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'coo_matrix' object has no attribute '__...
httplib.InvalidURL: nonnumeric port:
14,491,814
2
2013-01-24T00:19:59Z
18,525,886
11
2013-08-30T05:51:20Z
[ "python", "file" ]
i'm trying to do a script which check if many urls exists: ``` import httplib with open('urls.txt') as urls: for url in urls: connection = httplib.HTTPConnection(url) connection.request("GET") response = connection.getresponse() if response.status == 200: print '[{}]: '...
This might be a simple solution, here ``` connection = httplib.HTTPConnection(url) ``` you are using the `httpconnection` so no need to give url like, [http://iGyan.org](http://igyan.org) but instead of that you need to give [iGyan.org](http://igyan.org). In short remove the `http://` and `https://` from your URL, b...
Run code from a Python module, modify module, then run again without exiting interpeter
14,492,150
7
2013-01-24T00:57:29Z
14,492,172
9
2013-01-24T00:59:42Z
[ "debugging", "testing", "python" ]
I'd like to be able to open a Python shell, execute some code defined in a module, then modify the module, then re-run it in the same shell without closing/reopening. I've tried reimporting the functions/objects after modifying the script, and that doesn't work: ``` Python 2.7.2 (default, Jun 20 2012, 16:23:33) [GCC...
use `imp.reload()`: ``` In [1]: import imp In [2]: print imp.reload.__doc__ reload(module) -> module Reload the module. The module must have been successfully imported before. ```
Why is matplotlib.PatchCollection messing with color of the patches?
14,492,241
5
2013-01-24T01:06:13Z
14,493,391
10
2013-01-24T03:21:38Z
[ "python", "colors", "matplotlib", "patch" ]
I make a number of patches like so - ``` node.shape = RegularPolygon((node.posX, node.posY), 6, radius = node.radius, edgecolor = 'none', facecolor = node.fillColor, z...
``` self.p = PatchCollection(self.patches, match_original=True) ``` By default patch collection over-rides the given color ([doc](http://matplotlib.org/api/collections_api.html#matplotlib.collections.PatchCollection)) for the purposes of being able to apply a color map, cycle colors, etc. This is a `collection` level ...
Hu moments comparison
14,492,274
6
2013-01-24T01:09:45Z
14,501,412
12
2013-01-24T12:29:33Z
[ "python", "opencv", "image-processing", "contour" ]
i tried to compare two images and use Hu moment to compare contour extracted from these images: <https://docs.google.com/file/d/0ByS6Z5WRz-h2WHEzNnJucDlRR2s/edit> and <https://docs.google.com/file/d/0ByS6Z5WRz-h2VnZyVWRRWEFva0k/edit> The second image is equal to the first only it's rotated and i expected as result same...
I think your numbers are probably ok, the differences between them are moderately small. As the guy says in the video you link to (around 3min): > To get some meaningful answers we take a log transform so if we do `-np.sign(a)*np.log10(np.abs(a))` on the data you post above, we get: First image: ``` [[ 0.16584062] ...
Adding 'class' as dict key
14,492,567
3
2013-01-24T01:44:40Z
14,492,580
14
2013-01-24T01:45:54Z
[ "python", "dictionary" ]
I am able to do this: ``` {'class': 'foo'} ``` But when I do this: ``` dict(class='foo') ``` I get: ``` File "<stdin>", line 1 {'class':} ^ SyntaxError: invalid syntax ``` Why can't python use 'class' as a \*\*kwarg? It can just as easily use list, int, len... as keyword arguments.
`list`, `int`, and `len` are not keywords, they are normal identifiers. `class` is a [keyword](http://docs.python.org/3/reference/lexical_analysis.html#keywords).
have sphinx report broken links
14,492,743
10
2013-01-24T02:07:55Z
14,735,060
11
2013-02-06T17:22:13Z
[ "python", "documentation", "python-sphinx" ]
When building html documentation, how do you force sphinx to report, or create an error, on links that don't exist? Specifically, I have properties and methods within my Python project that have been removed or renamed, and it is hard to find all the dead links with the sphinx generated html output. I feel like I'm s...
Set the [nitpicky](http://sphinx-doc.org/config.html?highlight=nitpicky#confval-nitpicky) configuration variable to `True` (you can also use the [-n option](http://sphinx-doc.org/invocation.html#cmdoption-sphinx-build-n) when running sphinx-build). In nitpicky mode, a cross-reference to a function (such as `` :func:`m...
When does python compile the constant string letters, to combine the constant strings to one constant string
14,493,236
5
2013-01-24T03:03:06Z
14,493,372
9
2013-01-24T03:19:14Z
[ "python" ]
such as ``` In [9]: dis.disassemble(compile("s = '123' + '456'", "<execfile>", "exec")) 1 0 LOAD_CONST 3 ('123456') 3 STORE_NAME 0 (s) 6 LOAD_CONST 2 (None) 9 RETURN_VALUE ``` I want to know, when does python combine the c...
It happens whenever the combined string is 20 characters or fewer. The optimization occurs in the peephole optimizer. See line 219 in the fold\_binops\_on\_constants() function in *Python/peephole.c*: <http://hg.python.org/cpython/file/cd87afe18ff8/Python/peephole.c#l149>
Add margin when plots run against the edge of the graph
14,493,334
6
2013-01-24T03:14:43Z
14,498,142
12
2013-01-24T09:41:13Z
[ "python", "matplotlib", "plot" ]
Often when I plot in matplotlib, I get graphs like this: ![frequency response running along top edge](http://i.stack.imgur.com/ihWom.png) You can't see the function because it runs against the edge of the plot. Is there any way to *automatically* add some margin in these cases, so that they look like this: ![freque...
You can use `ax.margins()` to set the [margins](http://matplotlib.org/api/axes_api.html?highlight=xlim#matplotlib.axes.Axes.margins). Example: ``` In [1]: fig, ax = plt.subplots() In [2]: ax.plot(np.arange(10), '-o') Out[2]: [<matplotlib.lines.Line2D at 0x302fb50>] ``` ![without margin](http://i.stack.imgur.com/IENt...
How to set self.maxDiff in nose to get full diff output?
14,493,670
20
2013-01-24T03:54:07Z
14,493,895
26
2013-01-24T04:18:57Z
[ "python", "nose" ]
When using nose 1.2.1 with Python 3.3.0, I sometimes get an error message similar to the following one ``` ====================================================================== FAIL: maxdiff2.test_equal ---------------------------------------------------------------------- Traceback (most recent call last): File "/...
You set `maxDiff` to `None`. But you will have to actually use a [`unittest.TestCase`](http://docs.python.org/2/library/unittest.html#unittest.TestCase.maxDiff) for your tests for that to work.This shold work. ``` class MyTest(unittest.TestCase): maxDiff = None def test_diff(self): <your test here...
How to set self.maxDiff in nose to get full diff output?
14,493,670
20
2013-01-24T03:54:07Z
21,615,720
15
2014-02-06T22:44:43Z
[ "python", "nose" ]
When using nose 1.2.1 with Python 3.3.0, I sometimes get an error message similar to the following one ``` ====================================================================== FAIL: maxdiff2.test_equal ---------------------------------------------------------------------- Traceback (most recent call last): File "/...
I had the same problem in Python 3 (from reading the other answers here) and using `im_class` did not work. The snippet below works in Python 3 (cf. [How to find instance of a bound method in Python?](http://stackoverflow.com/questions/4679592/how-to-find-instance-of-a-bound-method-in-python)): ``` assert_equal.__self...
How to set self.maxDiff in nose to get full diff output?
14,493,670
20
2013-01-24T03:54:07Z
23,617,918
11
2014-05-12T20:07:44Z
[ "python", "nose" ]
When using nose 1.2.1 with Python 3.3.0, I sometimes get an error message similar to the following one ``` ====================================================================== FAIL: maxdiff2.test_equal ---------------------------------------------------------------------- Traceback (most recent call last): File "/...
This works in python 2.7: ``` from unittest import TestCase TestCase.maxDiff = None ``` It'll set the default maxDiff for all TestCase instances, including the one that assert\_equals and friends are attached to.
Using other keys for the waitKey() function of opencv
14,494,101
15
2013-01-24T04:42:05Z
14,494,131
25
2013-01-24T04:44:17Z
[ "python", "opencv" ]
I'm working on a program (python ,opencv) in which I use the `spacebar` to go to the next frame, and `Esc` to exit the program. These are the only two keys i've got working. I tried to find out about more keys , tried various codes for them but didnt work. especially arrow keys. I found **[this](http://pklaus.github.c...
You can use `ord()` function in Python for that. For example, if you want to trigger 'a' key press, do as follows : ``` if cv2.waitKey(33) == ord('a'): print "pressed a" ``` See a sample code here: **[Drawing Histogram](http://code.opencv.org/projects/opencv/repository/revisions/master/entry/samples/python2/hist....
Using other keys for the waitKey() function of opencv
14,494,101
15
2013-01-24T04:42:05Z
20,577,067
10
2013-12-13T22:23:56Z
[ "python", "opencv" ]
I'm working on a program (python ,opencv) in which I use the `spacebar` to go to the next frame, and `Esc` to exit the program. These are the only two keys i've got working. I tried to find out about more keys , tried various codes for them but didnt work. especially arrow keys. I found **[this](http://pklaus.github.c...
The keycodes returned by `waitKey` seem platform dependent. However, it may be very educative, to see what the keys return (and by the way, on my platform, *Esc* does not return 27...) The integers thay Abid's answer lists are mosty useless to the human mind (unless you're a prodigy savant...). However, if you examine...
Using other keys for the waitKey() function of opencv
14,494,101
15
2013-01-24T04:42:05Z
33,555,071
7
2015-11-05T21:25:10Z
[ "python", "opencv" ]
I'm working on a program (python ,opencv) in which I use the `spacebar` to go to the next frame, and `Esc` to exit the program. These are the only two keys i've got working. I tried to find out about more keys , tried various codes for them but didnt work. especially arrow keys. I found **[this](http://pklaus.github.c...
The answers which have already been posted suggest that some of the unusual values obtained by `waitKey` are due to platform differences. Below, I propose that (at least on some platforms) the apparently odd behaviour of `waitKey` is due to keyboard modifiers. This post looks similar to Tomasz's answer because I initia...
Remainder in Python 3.0
14,494,118
5
2013-01-24T04:43:32Z
14,494,156
9
2013-01-24T04:47:11Z
[ "python" ]
This **remainder operation** (modulo) in Python 3.0 is quite confusing. (%) In python, if I wanted to ask: ``` 9 % 5 = 4 ``` But if I ask, ``` -9 % 5 = 1 ``` Why is the answer '1'? and not '-4'?
Because in python, the sign matches the denominator. ``` >>> 9 % -5 -1 >>> -9 % 5 1 ``` For an explanation of why it was implemented this way, read the [blog post by Guido](http://python-history.blogspot.com.au/2010/08/why-pythons-integer-division-floors.html).
Finding last occurence of substring in string, replacing that
14,496,006
49
2013-01-24T07:29:13Z
14,496,072
8
2013-01-24T07:34:37Z
[ "python", "string", "parsing" ]
So I have a long list of strings in the same format, and I want to find the last "." character in each one, and replace it with ". - ". I've tried using rfind, but I can't seem to utilize it properly to do this. Anyone? Thanks!
I would use a regex: ``` import re new_list = [re.sub(r"\.(?=[^.]*$)", r". - ", s) for s in old_list] ```
Finding last occurence of substring in string, replacing that
14,496,006
49
2013-01-24T07:29:13Z
14,496,084
79
2013-01-24T07:35:09Z
[ "python", "string", "parsing" ]
So I have a long list of strings in the same format, and I want to find the last "." character in each one, and replace it with ". - ". I've tried using rfind, but I can't seem to utilize it properly to do this. Anyone? Thanks!
This should do it ``` old_string = "this is going to have a full stop. some written sstuff!" k = old_string.rfind(".") new_string = old_string[:k] + ". - " + old_string[k+1:] ```
Finding last occurence of substring in string, replacing that
14,496,006
49
2013-01-24T07:29:13Z
14,496,145
19
2013-01-24T07:39:01Z
[ "python", "string", "parsing" ]
So I have a long list of strings in the same format, and I want to find the last "." character in each one, and replace it with ". - ". I've tried using rfind, but I can't seem to utilize it properly to do this. Anyone? Thanks!
To replace from the right: ``` def replace_right(source, target, replacement, replacements=None): return replacement.join(source.rsplit(target, replacements)) ``` In use: ``` >>> replace_right("asd.asd.asd.", ".", ". -", 1) 'asd.asd.asd. -' ```
In Python, can I call the main() of an imported module?
14,500,183
10
2013-01-24T11:23:52Z
14,500,228
22
2013-01-24T11:26:23Z
[ "python", "module", "arguments", "main" ]
In Python I have a **module** myModule.py where I define a few functions and a **main()**, which takes a few command line arguments. I usually call this main() from a bash script. Now, I would like to put everything into a small **package**, so I thought that maybe I could turn my simple bash script into a Python scri...
It's just a function. Import it and call it: ``` import myModule myModule.main() ``` If you need to parse arguments, you have two options: * Parse them in `main()`, but pass in `sys.argv` as a parameter (all code below in the same module `myModule`): ``` def main(args): # parse arguments using optparse o...
How to know which python is running under ipython?
14,500,373
2
2013-01-24T11:32:49Z
14,500,674
7
2013-01-24T11:48:33Z
[ "python", "ipython" ]
I have several versions of python installed on my computer: ``` $ which ipython /usr/local/share/python/ipython $ ipython Python 2.7.3 (default, Nov 28 2012, 13:43:07) $ which python /usr/bin/python $ python Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) ``` I would like to locate the python bin running under my ...
``` In [1]: import sys In [2]: sys.version Out[2]: '2.7.2 |EPD_free 7.2-2 (32-bit)| (default, Sep 14 2011, 11:02:05) [MSC v.1500 32 bit (Intel)]' In [3]: sys.executable Out[3]: 'C:\\Python27\\python2.7.exe' ```
How to write exception reraising code that's compatible with both Python 2 and Python 3?
14,503,751
17
2013-01-24T14:33:24Z
14,505,093
26
2013-01-24T15:38:26Z
[ "python", "python-3.x", "python-2.x" ]
I'm trying to make my WSGI server implementation compatible with both Python 2 and Python 3. I had this code: ``` def start_response(status, response_headers, exc_info = None): if exc_info: try: if headers_sent: # Re-raise original exception if headers sent. rais...
Can you use [`six`](http://packages.python.org/six/)? It exists to solve this very problem. ``` import six six.reraise(*exc_info) ``` See: <https://pythonhosted.org/six/index.html#six.reraise>
Python global keyword vs. Pylint W0603
14,503,973
6
2013-01-24T14:44:36Z
14,505,529
11
2013-01-24T16:00:36Z
[ "python", "global-variables", "global", "pylint" ]
Pylint W0603 states: > *Using the global statement.* Used when you use the "global" statement to > update a global variable. PyLint just try to discourage this usage. > That doesn't mean you can not use it ! I wonder why is it so? Is there any more Pythonic way of modifying immutable, module-wide variables inside a f...
Generalized use of global variables can make maintenance a nightmare, because they make tracing the flow of your program, and sometimes you get weird bug, because some module has read the variable and acted on its value before some other module changed the value of the variable (and this can result from inverting two i...
Querying a hybrid property in SQLAlchemy
14,504,284
8
2013-01-24T14:58:57Z
14,504,695
12
2013-01-24T15:18:36Z
[ "python", "sqlalchemy" ]
I'm storing file paths as relative paths in the database, but I'm then using hybrid properties to turn in into an absolute path when its mapped. When I query using this property it throws an error. Here's the model: ``` class File(Base): __tablename__ = 'files' ... _f_path = Column(Unicode(30)) ... ...
Your hybrid property must return a sql expression; yours does not, it returns a python string instead. To resolve that for this case, don't do the path join in python but in a SQL expression instead: ``` return env['project_dir'] + os.path.sep + self._f_path ``` which will resolve to `self._f_path.__radd__(result_of...
Python's xmlrpc extremely slow: one second per call
14,504,450
7
2013-01-24T15:06:37Z
14,504,452
14
2013-01-24T15:06:37Z
[ "python", "xml-rpc", "xmlrpclib", "simplexmlrpcserver" ]
I built an xml-rpc server in Python using SimpleXMLRPCServer, according to the example in the Python documentation. I'm calling it from a Python client on the same machine. The body of the server function executes very fast on its own. But I find that xmlrpc client performance is excruciatingly slow, taking one second...
The problem seemed to be with the client resolving *localhost*. New (fast) connect URI: ``` 'http://127.0.0.1:50080' ``` Similarly, adding this line in the hosts file %SystemRoot%\System32\drivers\etc\hosts has essentially the same effect: > 127.0.0.1 localhost Either of these changes increased the speed from 1 ca...
Implement K Neighbors Classifier in scikit-learn with 3 feature per object
14,505,716
3
2013-01-24T16:09:45Z
14,511,314
10
2013-01-24T21:41:05Z
[ "python", "machine-learning", "scikit-learn", "nearest-neighbor", "classification" ]
I would like to implement a KNeighborsClassifier with scikit-learn module (http://scikit-learn.org/dev/modules/generated/sklearn.neighbors.KNeighborsClassifier.html) I retrieve from my image solidity, elongation and Humoments faetures. How can i prepare these datas for training and validation? I must create a list wit...
### Your first segment of code defines a classifier on `1d` data. `X` represents the feature vectors. ``` [0] is the feature vector of the first data example [1] is the feature vector of the second data example .... [[0],[1],[2],[3]] is a list of all data examples, each example has only 1 feature. ``` `y` represe...
String formatting in Python: can I use %s for all types?
14,506,430
4
2013-01-24T16:45:34Z
14,506,437
12
2013-01-24T16:46:14Z
[ "python", "string", "floating-point", "integer", "string-formatting" ]
When doing **string formatting** in Python, I noticed that `%s` transforms also numbers to strings. ``` >>> a = 1 >>> b = 1.1 >>> c = 'hello' >>> print 'Integer: %s; Float: %s; String: %s' % (a, b, c) Integer: 1; Float: 1.1; String: hello ``` I don't know for other variable types, but is it safe to use `%s` like this...
using `%s` automatically calls `str` on the variable. Since everything has `__str__` defined, you should be able to do this without a problem (i.e. no exception will be raised). However, what you actually will have printed is another story ... Note that in newer python code, there's another option which uses the `form...
Can writing to a UDP socket ever block?
14,507,028
14
2013-01-24T17:18:38Z
14,507,997
9
2013-01-24T18:15:30Z
[ "python", "udp", "twisted", "statsd" ]
And if so, under what conditions? Or, phrased alternately, is it safe to run this code inside of twisted: ``` class StatsdClient(AbstractStatsdClient): def __init__(self, host, port): super(StatsdClient, self).__init__() self.addr = (host, port) self.server_hostname = socket.gethostname() self.udp_so...
Yes, oddly, a UDP socket can block. The conditions under which this can happen are basically, some buffers somewhere fill up, your operating system decides it's time for something to block. These are arguably kernel bugs, but I've seen them here and there. You can definitely get `EWOULDBLOCK` sometimes under obscure, ...
Python Dictionary Comprehension
14,507,591
166
2013-01-24T17:51:45Z
14,507,623
121
2013-01-24T17:53:50Z
[ "python", "dictionary", "list-comprehension" ]
Is it possible to create a dictionary comprehension in Python (for the keys)? Without list comprehensions, you can use something like this: ``` l = [] for n in range(1, 11): l.append(n) ``` We can shorten this to a list comprehension: `l = [n for n in range(1, 11)]`. However, say I want to set a dictionary's ke...
You can use the `dict.fromkeys` class method ... ``` >>> dict.fromkeys(range(1, 11), True) {1: True, 2: True, 3: True, 4: True, 5: True, 6: True, 7: True, 8: True, 9: True, 10: True} ``` This is the fastest way to create a dictionary where all the keys map to the same value. Be careful using this with mutable object...
Python Dictionary Comprehension
14,507,591
166
2013-01-24T17:51:45Z
14,507,637
201
2013-01-24T17:54:24Z
[ "python", "dictionary", "list-comprehension" ]
Is it possible to create a dictionary comprehension in Python (for the keys)? Without list comprehensions, you can use something like this: ``` l = [] for n in range(1, 11): l.append(n) ``` We can shorten this to a list comprehension: `l = [n for n in range(1, 11)]`. However, say I want to set a dictionary's ke...
There are dictionary comprehensions in Python 2.7+, but they don't work quite the way you're trying. Like a list comprehension, they create a *new* dictionary; you can't use them to add keys to an existing dictionary. Also, you have to specify the keys and values, although of course you can specify a dummy value if you...
Python Dictionary Comprehension
14,507,591
166
2013-01-24T17:51:45Z
14,507,643
14
2013-01-24T17:54:49Z
[ "python", "dictionary", "list-comprehension" ]
Is it possible to create a dictionary comprehension in Python (for the keys)? Without list comprehensions, you can use something like this: ``` l = [] for n in range(1, 11): l.append(n) ``` We can shorten this to a list comprehension: `l = [n for n in range(1, 11)]`. However, say I want to set a dictionary's ke...
``` >>> {i:i for i in range(1, 11)} {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10} ```
Python Dictionary Comprehension
14,507,591
166
2013-01-24T17:51:45Z
14,507,654
8
2013-01-24T17:55:26Z
[ "python", "dictionary", "list-comprehension" ]
Is it possible to create a dictionary comprehension in Python (for the keys)? Without list comprehensions, you can use something like this: ``` l = [] for n in range(1, 11): l.append(n) ``` We can shorten this to a list comprehension: `l = [n for n in range(1, 11)]`. However, say I want to set a dictionary's ke...
Use dict() on a list of tuples, this solution will allow you to have arbitrary values in each list, so long as they are the same length ``` i_s = range(1, 11) x_s = range(1, 11) # x_s = range(11, 1, -1) # Also works d = dict([(i_s[index], x_s[index], ) for index in range(len(i_s))]) ```
Python Pandas - How to flatten a hierarchical index in columns
14,507,794
51
2013-01-24T18:03:11Z
14,508,355
83
2013-01-24T18:37:10Z
[ "python", "pandas" ]
I have a data frame with a hierarchical index in axis 1 (columns) (from a groupby.agg operation): ``` USAF WBAN year month day s_PC s_CL s_CD s_CNT tempf sum sum sum sum amax amin 0 702730 26451 1993 1 1 1 0 12 13 30.92 2...
I think the easiest way to do this would be to set the columns to the top level: ``` df.columns = df.columns.get_level_values(0) ``` *Note: if the to level has a name you can also access it by this, rather than 0.* . If you want to combine/[`join`](http://docs.python.org/2/library/stdtypes.html#str.join) your Multi...
Python Pandas - How to flatten a hierarchical index in columns
14,507,794
51
2013-01-24T18:03:11Z
14,508,639
7
2013-01-24T18:54:14Z
[ "python", "pandas" ]
I have a data frame with a hierarchical index in axis 1 (columns) (from a groupby.agg operation): ``` USAF WBAN year month day s_PC s_CL s_CD s_CNT tempf sum sum sum sum amax amin 0 702730 26451 1993 1 1 1 0 12 13 30.92 2...
Andy Hayden's answer is certainly the easiest way -- if you want to avoid duplicate column labels you need to tweak a bit ``` In [34]: df Out[34]: USAF WBAN day month s_CD s_CL s_CNT s_PC tempf year sum sum sum sum amax amin 0 702730 26451 1 ...
Python Pandas - How to flatten a hierarchical index in columns
14,507,794
51
2013-01-24T18:03:11Z
34,262,133
15
2015-12-14T08:00:21Z
[ "python", "pandas" ]
I have a data frame with a hierarchical index in axis 1 (columns) (from a groupby.agg operation): ``` USAF WBAN year month day s_PC s_CL s_CD s_CNT tempf sum sum sum sum amax amin 0 702730 26451 1993 1 1 1 0 12 13 30.92 2...
``` pd.DataFrame(df.to_records()) # multiindex become columns and new index is integers only ```
How to Get Value Out from the Tkinter Slider ("Scale")?
14,508,727
3
2013-01-24T19:00:28Z
14,511,723
7
2013-01-24T22:10:04Z
[ "python", "python-2.7", "tkinter" ]
So, here is the code I have, and as I run it, the value of the slider bar appears above the slider, I wonder is there a way to get that value out? Maybe let a=that value. ;) ``` from Tkinter import * control=Tk() control.title("Control") control.geometry("350x200+100+50") cline0=Label(text="").pack() cline1=Label(tex...
To get the value as it is modified, associate a function with the parameter `command`. This function will receive the current value, so you just work with it. Also note that in your code you have `cline3 = Scale(...).pack()`. `cline3` is always None in this case, since that is what `pack()` returns. ``` import Tkinter...
Run PowerShell function from Python script
14,508,809
8
2013-01-24T19:05:02Z
14,554,665
12
2013-01-28T02:32:01Z
[ "python", "function", "powershell" ]
I have a need to run a PowerShell function from a Python script. Both the .ps1 and the .py files currently live in the same directory. The functions I want to call are in the PowerShell script. Most answers I've seen are for running entire PowerShell scripts from Python. In this case, I'm trying to run an individual fu...
You want two things: [dot source the script](http://blogs.technet.com/b/heyscriptingguy/archive/2010/08/10/how-to-reuse-windows-powershell-functions-in-scripts.aspx) (which is (as far as I know) similar to python's import), and [subprocess.call](http://docs.python.org/2/library/subprocess.html). ``` import subprocess ...
Sending messages between class threads Python
14,508,906
5
2013-01-24T19:11:27Z
14,508,963
9
2013-01-24T19:14:18Z
[ "python", "multithreading", "messaging" ]
Does anybody know how I can send a variable (or get a variable) from threadOne to threadTwo in this code without using a global variable? If not, how would I operate a global variable? Just define it before both classes and use the global definition in the run function? ``` import threading print "Press Escape to Qui...
You can use [queues](http://docs.python.org/2/library/queue.html) to send messages between threads in a thread safe way. ``` def worker(): while True: item = q.get() do_work(item) q.task_done() q = Queue() for i in range(num_worker_threads): t = Thread(target=worker) t.daemon = T...
How to import functions from other projects in Python?
14,509,192
7
2013-01-24T19:28:40Z
14,509,415
10
2013-01-24T19:42:45Z
[ "python", "import" ]
I have some code in a project which I'd like to reuse in another project. What do I need to do (in both folders) so that I can do this? The directory structure is something like: * Foo + Project1 - file1.py - file2.py * Bar + Project2 - fileX.py - fileY.py I want to use functions from file1.py an...
Ideally both projects will be an installable python package, replete with \_\_init\_\_.py and setup.py. They could then be installed with `python setup.py install` or similar. If that is not possible, *don't* use `execfile()`! Manipulate the `PYTHONPATH` to add `Foo` so that `import Project1.file1` works. For example...
How can I get the exponent of each number in a np.array?
14,509,626
2
2013-01-24T19:56:00Z
14,509,780
11
2013-01-24T20:06:03Z
[ "python", "numpy" ]
Lets say I have the array: ``` x = np.array([0.00001,0.001]) ``` numpy will make the numbers to ``` array([ 1.00000000e-05, 1.00000000e-03]) ``` Now I want to get the exponents, something like ``` x.get_exponent() ``` with result ``` [-5,-3] ```
You can use `np.floor(np.log10(np.abs(x)))`. For example: ``` In [13]: x = np.array([0.00001, -0.001, 0.0000025, 0.09, -13.25, 9876.5]) In [14]: x Out[14]: array([ 1.00000000e-05, -1.00000000e-03, 2.50000000e-06, 9.00000000e-02, -1.32500000e+01, 9.87650000e+03]) In [15]: np.floor(np.log10(np.abs(x)...
Python trick in finding leading zeros in string
14,509,986
3
2013-01-24T20:19:05Z
14,509,999
7
2013-01-24T20:20:52Z
[ "python" ]
I have a binary string say '01110000', and I want to return the number of leading zeros in front without writing a forloop. Does anyone have any idea on how to do that? Preferably a way that also returns 0 if the string immediately starts with a '1'
A simple one-liner: ``` x = '01110000' leading_zeros = len(x.split('1', 1)[0]) ``` This partitions the string into everything up to the first '1' and the rest after it, then counts the length of the prefix. The second argument to `split` is just an optimization and represents the number of splits to perform, meaning ...
Python trick in finding leading zeros in string
14,509,986
3
2013-01-24T20:19:05Z
14,510,015
7
2013-01-24T20:21:28Z
[ "python" ]
I have a binary string say '01110000', and I want to return the number of leading zeros in front without writing a forloop. Does anyone have any idea on how to do that? Preferably a way that also returns 0 if the string immediately starts with a '1'
If you're really *sure* it's a "binary string": ``` input = '01110000' zeroes = input.index('1') ``` Update: it breaks when there's nothing but "leading" zeroes An alternate form that handles the all-zeroes case. ``` zeroes = (input+'1').index('1') ```
Efficiency of reopening sqlite database after each query
14,511,337
6
2013-01-24T21:42:19Z
14,520,670
7
2013-01-25T11:15:25Z
[ "python", "sqlite" ]
I currently am working on a web server in tornado, but am having issues with different bits of code trying to access the database at once. I have simplified this by simply having a query function which basically does this (but slightly more advanced): ``` def query(command, arguments = []): db = sqlite3.open("mod...
I'm adding my own answer because I disagree with the currently accepted one. It states that the operation is not thread-safe, but this is plain wrong - [SQLite uses file locking](http://www.sqlite.org/lockingv3.html) appropriate to its current platform to ensure that all accesses comply with [ACID](http://en.wikipedia....
Find the first non-repeated character in a string
14,511,340
2
2013-01-24T21:42:22Z
14,511,382
7
2013-01-24T21:46:06Z
[ "python", "algorithm" ]
I read of a job interview question to write some code for the following: > Write an efficient function to find the first nonrepeated character in > a string. For instance, the first nonrepeated character in “total” is > 'o' and the first nonrepeated character in “teeter” is 'r'. Discuss > the efficiency of you...
``` In [1033]: def firstNonRep(word): ......: c = collections.Counter(word) ......: for char in word: ......: if c[char] == 1: ......: return char ......: In [1034]: word="googlethis" In [1035]: firstNonRep(word) Out[1035]: 'l' ``` **EDIT**: If you want to implemen...
SQLAlchemy ORM select multiple entities from subquery
14,511,633
3
2013-01-24T22:03:05Z
14,512,137
13
2013-01-24T22:39:05Z
[ "python", "sqlalchemy" ]
I need to query multiple entities, something like `session.query(Entity1, Entity2)`, only from a subquery rather than directly from the tables. The docs have something about [selecting one entity from a subquery](http://docs.sqlalchemy.org/en/rel_0_8/orm/tutorial.html?highlight=window#selecting-entities-from-subqueries...
``` from sqlalchemy import * from sqlalchemy.orm import * from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class A(Base): __tablename__ = "a" id = Column(Integer, primary_key=True) bs = relationship("B") class B(Base): __tablename__ = "b" id = Column(Integer, pr...
Why does python have os.path.curdir
14,512,087
9
2013-01-24T22:35:22Z
14,512,124
22
2013-01-24T22:38:10Z
[ "python" ]
`os.path.curdir` returns '.' which is totally truthful and totally worthless. To get anything useful from it, you have to wrap it with `os.path.abspath(os.path.curdir)` Why include a useless variable in the os.path module? Why not have os.path.curdir be a function that does the os.path.abspath for you? Is there some ...
It is a constant, just like `os.path.sep`. Platforms other than POSIX and Windows could use a different value to denote the 'current directory'. On Risc OS it's `@` for example, on the old Macintosh OS it's `:`. The value is used throughout the standard library to remain platform agnostic. Use [`os.getcwd()`](http:/...
Why does this Fibonacci evaluate much faster in Python than Haskell
14,512,107
2
2013-01-24T22:36:49Z
14,512,149
19
2013-01-24T22:39:55Z
[ "python", "haskell" ]
I have an algorithm for calculating the nth Fibonacci number, in Python it's expressed as: ``` def fib(n): if n == 0: return 1 if n == 1: return 1 else: return fib(n-1) + fib(n-2) ``` and in Haskell: ``` fib :: Integer -> Integer fib 0 = 1 fib 1 = 1 fib n = fib (n-1) + fib (n-2) `...
You said that you ran the Haskell code in GHCI, which means that you ran it without optimizations. That means that no strictness analysis was done, so the whole thing was evaluated lazily, creating a lot of unnecessary thunks. That would explain why it was slower. Also as delnan pointed out in a comment, ghci is much ...
SQLAlchemy raw SQL parameter substitution with an IN clause
14,512,228
7
2013-01-24T22:45:06Z
14,512,626
8
2013-01-24T23:17:13Z
[ "python", "sqlalchemy" ]
I have an SQL statement, `SELECT foo FROM bar WHERE id IN %s`. I have a list of integers, e.g. `[1, 2, 3]` and I'd like this to get turned into a SQL statement that looks like `SELECT foo FROM bar WHERE id IN (1, 2, 3)`. I use SQLAlchemy Core for its connection pooling and for making some inserts with multiple `VALUES...
This is an unusual format supported only by some DBAPIs, in that it renders a tuple of items as individual SQL expressions, including that it renders the comma and such in between parameters, so a statement like `execute("select * from table where value in %s", (somelist, ))` expands out at the database level into `sel...
How to plot specified data in thick line
14,513,006
5
2013-01-24T23:51:14Z
14,513,351
7
2013-01-25T00:27:10Z
[ "python", "matplotlib", "pandas" ]
I have a data file that includes several years' temperature records, I read-in the data file with Pandas and now it becomes a DataFrame below: ``` In [86]: tso Out[86]: <class 'pandas.core.frame.DataFrame'> DatetimeIndex: 28170 entries, 2005-05-20 13:28:42.239999+00:00 to 2012-12-05 13:26:49.919999+00:00 Da...
You could do something like: ``` ax.lines[-1].set_linewidth(8) plt.show() ```
Tracking the number of recursive calls without using global variables in Python
14,513,717
3
2013-01-25T01:06:25Z
14,513,793
9
2013-01-25T01:14:24Z
[ "python", "recursion" ]
How to track the number of recursive calls without using global variables in Python. For example, how to modify the following function to keep track the number of calls? ``` def f(n): if n == 1: return 1 else: return n * f(n-1) print f(5) ```
Here's a neat trick that doesn't use a global: you can stash the counter in the function itself. ``` def f(n): f.count += 1 if n == 1: return 1 else: return n * f(n-1) ``` After which: ``` >>> f.count = 0 # initialize the counter >>> f(5) 120 >>> f.count 5 >>> f(30) 2652528598121910586363...
Print just the value of a dictionary term for a specific key in Python
14,513,740
2
2013-01-25T01:09:07Z
14,513,768
7
2013-01-25T01:11:29Z
[ "python", "dictionary", "python-3.x" ]
I am wondering what I do in Python if I have a dictionary and I want to print out just the value for a specific key. It will be in a variable as well as in: ``` dict = {'Lemonade':["1", "45", "87"], 'Coke:["23", "9", "23"] 'Water':["98", "2", "127"} inp = input("Select key to print value for!" + "/r>>> ") if inp in d...
I have taken the liberty of renaming your `dict` variable, to avoid shadowing the built-in name. I'm also assuming you're on python3, if you're on 2.x you should change the `input` function to `raw_input` instead. ``` dict_ = {'Lemonade': ["1", "45", "87"], 'Coke': ["23", "9", "23"], 'Water': ["98", "2", "127"]} inp =...