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
Logging formatters in django
10,710,591
5
2012-05-22T21:40:52Z
10,710,601
8
2012-05-22T21:41:39Z
[ "python", "django", "logging" ]
From the [Django documentation](https://docs.djangoproject.com/en/1.7/topics/logging/#examples), here is an example format for logging: ``` 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s: %(message)s' } } ``` This prints something like: > ERROR 2012-05-22 14:33:07,261 vi...
<http://docs.python.org/library/logging.html#logrecord-attributes>
Logging formatters in django
10,710,591
5
2012-05-22T21:40:52Z
26,276,689
13
2014-10-09T10:58:11Z
[ "python", "django", "logging" ]
From the [Django documentation](https://docs.djangoproject.com/en/1.7/topics/logging/#examples), here is an example format for logging: ``` 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s: %(message)s' } } ``` This prints something like: > ERROR 2012-05-22 14:33:07,261 vi...
From [Python logging module documentation](http://docs.python.org/library/logging.html#logrecord-attributes): * **asctime**: `%(asctime)s` Human-readable time when the [`LogRecord`](https://docs.python.org/2/library/logging.html#logging.LogRecord) was created. By default this is of the form ‘2003-07-08 16:49:45,...
string manipulation - stringing '&' between a list of args
10,710,823
2
2012-05-22T22:02:12Z
10,710,839
10
2012-05-22T22:03:25Z
[ "python", "string" ]
I have a list of args ``` args = ['abc', 'def', 'ghi'... ... ... (long list)] ``` I would like make a string called 'clipboard' where: ``` clipboard = 'abc&def&ghi&... ... ... (long list)' ``` **Pointers would be appreciated.**
`clipboard = '&'.join(args)`
Strip spaces/tabs/newlines - python
10,711,116
26
2012-05-22T22:37:01Z
10,711,150
19
2012-05-22T22:40:43Z
[ "python", "string", "strip" ]
I am trying to remove all spaces/tabs/newlines in python 2.7 on Linux. I wrote this, that should do the job: ``` myString="I want to Remove all white \t spaces, new lines \n and tabs \t" myString = myString.strip(' \n\t') print myString ``` output: ``` I want to Remove all white spaces, new lines and tabs ``` ...
If you want to remove multiple whitespace items and replace them with single spaces, the easiest way is with a regexp like this: ``` >>> import re >>> myString="I want to Remove all white \t spaces, new lines \n and tabs \t" >>> re.sub('\s+',' ',myString) 'I want to Remove all white spaces, new lines and tabs ' ``` Y...
Strip spaces/tabs/newlines - python
10,711,116
26
2012-05-22T22:37:01Z
10,711,166
54
2012-05-22T22:42:54Z
[ "python", "string", "strip" ]
I am trying to remove all spaces/tabs/newlines in python 2.7 on Linux. I wrote this, that should do the job: ``` myString="I want to Remove all white \t spaces, new lines \n and tabs \t" myString = myString.strip(' \n\t') print myString ``` output: ``` I want to Remove all white spaces, new lines and tabs ``` ...
Use `str.split([sep[, maxsplit]])` with no `sep` or `sep=None`: From [docs](http://docs.python.org/2/library/stdtypes.html#str.split): > If `sep` is not specified or is `None`, a different splitting algorithm is > applied: runs of consecutive whitespace are regarded as a single > separator, and the result will contai...
Strip spaces/tabs/newlines - python
10,711,116
26
2012-05-22T22:37:01Z
14,101,019
7
2012-12-31T11:32:23Z
[ "python", "string", "strip" ]
I am trying to remove all spaces/tabs/newlines in python 2.7 on Linux. I wrote this, that should do the job: ``` myString="I want to Remove all white \t spaces, new lines \n and tabs \t" myString = myString.strip(' \n\t') print myString ``` output: ``` I want to Remove all white spaces, new lines and tabs ``` ...
``` import re mystr = "I want to Remove all white \t spaces, new lines \n and tabs \t" print re.sub(r"\W", "", mystr) Output : IwanttoRemoveallwhitespacesnewlinesandtabs ```
python reduce to check if all elements are equal
10,711,918
8
2012-05-23T00:27:50Z
10,711,965
7
2012-05-23T00:34:13Z
[ "python", "reduce" ]
Suppose `a = [[1,2,3],[1,2,3]]` `reduce(lambda x,y: x==y, a)` returns `True` But if `a = [[1,2,3],[1,2,3],[1,2,3]]` `reduce(lambda x,y: x==y, a)` returns `False` Why in the second case, the outcome is `False`? please help thanks
Try this instead, it works for lists of any size: ``` all(e == a[0] for e in a) ``` Notice that your proposed solution using `reduce` doesn't work for more than two items, as the accumulated value after the first comparison is `True`, and you'd be comparing `True` against each of the elements from that point on, and ...
Create an empty list in python with certain size
10,712,002
120
2012-05-23T00:38:24Z
10,712,017
13
2012-05-23T00:40:21Z
[ "python", "list" ]
I want to create an empty list (or whatever is the best way) that can hold 10 elements. After that I want to assign values in that list, for example this is supposed to display 0 to 9: ``` s1 = list(); for i in range(0,9): s1[i] = i print s1 ``` But when I run this code, it generates an error or in another case...
You can `.append(element)` to the list, e.g.: `s1.append(i)`. What you are currently trying to do is access an element (`s1[i]`) that does not exist.
Create an empty list in python with certain size
10,712,002
120
2012-05-23T00:38:24Z
10,712,032
40
2012-05-23T00:41:42Z
[ "python", "list" ]
I want to create an empty list (or whatever is the best way) that can hold 10 elements. After that I want to assign values in that list, for example this is supposed to display 0 to 9: ``` s1 = list(); for i in range(0,9): s1[i] = i print s1 ``` But when I run this code, it generates an error or in another case...
Try this instead: ``` lst = [None] * 10 ``` The above will create a list of size 10, where each position is initialized to `None`. After that, you can add elements to it: ``` lst = [None] * 10 for i in range(10): lst[i] = i ``` Admittedly, that's not the Pythonic way to do things. Better do this: ``` lst = [] ...
Create an empty list in python with certain size
10,712,002
120
2012-05-23T00:38:24Z
10,712,044
194
2012-05-23T00:44:12Z
[ "python", "list" ]
I want to create an empty list (or whatever is the best way) that can hold 10 elements. After that I want to assign values in that list, for example this is supposed to display 0 to 9: ``` s1 = list(); for i in range(0,9): s1[i] = i print s1 ``` But when I run this code, it generates an error or in another case...
You cannot assign to a list like `lst[i] = something`. You need to use append. `lst.append(i)`. (You could use the assignment notation if you were using a dictionary). Creating an empty list: ``` >>> l = [None] * 10 >>> l [None, None, None, None, None, None, None, None, None, None] ``` range(x) creates a list from ...
Directing Sublime Text 2 Packages to the correct python installation
10,712,390
13
2012-05-23T01:35:36Z
10,712,650
18
2012-05-23T02:19:37Z
[ "python", "osx", "sublimetext2", "environment-variables", "sublimetext" ]
I just want to direct a Sublime Text 2 Package (**SublimeREPL**) to the *correct* python installation--at the moment, it's picking up the wrong one. The story here is familiar to Mac users. The Mac OS comes includes a python install which it uses for various OS stuff for which python is required. Like many others, i p...
If you want to use `repl_open` you could edit the `cmd` parameter in the config. I am using Ubuntu and it is located in: `/home/stav/.config/sublime-text-2/Packages/SublimeREPL/config/Python/Main.sublime-menu` ``` {"command": "repl_open", "caption": "Python", "id": "repl_python", "mnemonic": "p", "args": { "type": ...
harmonic mean in python
10,712,842
7
2012-05-23T02:53:18Z
10,712,918
19
2012-05-23T03:06:42Z
[ "python", "math", "statistics", "scipy", "mean" ]
The Harmonic Mean function in Python (scipy.stats.hmean) requires that the input be positive numbers. For example: ``` from scipy import stats print stats.hmean([ -50.2 , 100.5 ]) ``` results in: ``` ValueError: Harmonic mean only defined if all elements greater than zero ``` I don't mathematically see why this sho...
The harmonic mean is only defined for sets of positive real numbers. If you try and compute it for sets with negatives you get all kinds of strange and useless results even if you don't hit div by 0. For example, applying the formula to the set (3, -3, 4) gives a mean of 12!
Find length of 2D array Python
10,713,004
25
2012-05-23T03:19:40Z
10,713,016
48
2012-05-23T03:21:34Z
[ "python", "arrays" ]
How do I find how many rows and columns are in a 2d array? For example, ``` Input = ([[1, 2], [3, 4], [5, 6]])` ``` should be displayed as 3 rows and 2 columns.
Like this: ``` numrows = len(input) # 3 rows in your example numcols = len(input[0]) # 2 columns in your example ``` Assuming that all the sublists have the same length (that is, it's not a jagged array).
Find length of 2D array Python
10,713,004
25
2012-05-23T03:19:40Z
10,713,034
17
2012-05-23T03:24:28Z
[ "python", "arrays" ]
How do I find how many rows and columns are in a 2d array? For example, ``` Input = ([[1, 2], [3, 4], [5, 6]])` ``` should be displayed as 3 rows and 2 columns.
You can use `numpy.shape`. ``` import numpy as np x = np.array([[1, 2],[3, 4],[5, 6]]) ``` Result: ``` >>> x array([[1, 2], [3, 4], [5, 6]]) >>> np.shape(x) (3, 2) ``` First value in the tuple is number rows = 3; second value in the tuple is number of columns = 2.
Find length of 2D array Python
10,713,004
25
2012-05-23T03:19:40Z
10,713,045
7
2012-05-23T03:26:07Z
[ "python", "arrays" ]
How do I find how many rows and columns are in a 2d array? For example, ``` Input = ([[1, 2], [3, 4], [5, 6]])` ``` should be displayed as 3 rows and 2 columns.
Assuming input[row][col], ``` rows = len(input) cols = map(len, input) #list of column lengths ```
How to sum a 2d array in Python?
10,713,150
2
2012-05-23T03:43:01Z
10,713,241
8
2012-05-23T03:58:07Z
[ "python" ]
**I want to sum a 2 dimensional array in python:** Here is what I have: ``` def sum1(input): sum = 0 for row in range (len(input)-1): for col in range(len(input[0])-1): sum = sum + input[row][col] return sum print sum1([[1, 2],[3, 4],[5, 6]]) ``` It displays `4` instead of `21` (1+...
You could rewrite that function as, ``` def sum1(input): return sum(map(sum, input)) ``` Basically, `map(sum, input)` will return a list with the sums across all your rows, then, the outer most `sum` will add up that list. Example: ``` >>> a=[[1,2],[3,4]] >>> sum(map(sum, a)) 10 ```
how to generate random num with conditions
10,713,250
2
2012-05-23T03:58:56Z
10,713,317
9
2012-05-23T04:08:48Z
[ "python", "algorithm" ]
I want to generate 2n-1 random integers in the range [1,n] with each element appearing twice except for random value, which only appears once. for example: ``` n = 3 seq = [1, 2, 3, 1, 3] ``` in this example 2 appears only once. My algorithm is to use dictionary, like this: ``` ------------- | num |times| | 1 ...
I am not sure that I am 100 sure what you are after, but here is a try: ``` import random as rn x = range(3)*2 #generate a list where each number appears twice rn.shuffle(x) #shuffle it x.pop() #remove one number ``` Result: ``` >>> x [2, 0, 2, 1, 0] #the result is a list where every number appears twice, ex...
Interactive(?) plotting in Spyder with matplotlib
10,713,966
10
2012-05-23T05:28:59Z
10,724,654
14
2012-05-23T17:04:24Z
[ "python", "plot", "interactive", "figure", "spyder" ]
I am trying to migrate over to Python from Matlab and can't figure out how to get interactive(?) plotting working within the Spyder IDE. My test code is shown below. With the .ion() nothing happens, I get a quick flash of a figure being drawn then the window instantly closes and spits out my Hello. Without the .ion() t...
The run configuration should be set to *Execute in current Python or IPython interpreter* which by default allows for interactive plotting. If the interpreter is set to *Execute in a new dedicated Python interpreter* then *Interact with the Python interpreter after execution* must be selected.
Try Except in python :syntax issue
10,714,512
2
2012-05-23T06:20:32Z
10,714,537
7
2012-05-23T06:22:27Z
[ "python" ]
``` class ShortInputException(Exception): '''A user-defined exception class.''' def __init__(self, length, atleast): Exception.__init__(self) self.length = length self.atleast = atleast try: s = raw_input('Enter something --> ') if len(s) < 3...
``` except ShortInputException, x: ``` catches an exception of class ShortInputException and binds the instance of the exception object to x. The more common syntax for this is ``` except ShortInputException as x ``` which is to be preferred as described in [PEP3110](http://www.python.org/dev/peps/pep-3110/). Unles...
Update request.POST or request.GET using a view decorator
10,715,617
7
2012-05-23T07:48:23Z
10,716,329
10
2012-05-23T08:37:04Z
[ "python", "django" ]
I try to translate a code i use in my templates and js to a content\_type and object\_id that is being used by the wrapped function: ``` def translate_modelcode(function=None,redirect_field_name=None): """ translate an item-code specified in settings to a content_type and the item-id to the object_id "...
The `update(...)` method does not have a return value, it updates its instance in-place. So instead of `request.GET = request.GET.copy().update(ud_dict)` you should write ``` request.GET = request.GET.copy() request.GET.update(ud_dict) ```
Opening A large JSON file in Python
10,715,628
8
2012-05-23T07:49:22Z
10,715,686
10
2012-05-23T07:53:04Z
[ "python", "json", "nltk" ]
I have a 1.7 GB JSON file when I am trying to open with json.load() then it is giving memory error, How could read the json file in python? My JSON file is a big array of objects containing specific keys. EDIT: Well if it is just one big array of objects and it is known the structure of objects beforehand then there ...
You want an incremental json parser like [yajl](http://lloyd.github.com/yajl/) and one of its python bindings. An incremental parser reads as little as possible from the input and invokes a callback when something meaningful is decoded. For example, to pull only numbers from a big json file: ``` class ContentHandler(Y...
Python unicode codepoint to unicode character
10,715,669
5
2012-05-23T07:52:08Z
10,715,694
13
2012-05-23T07:53:41Z
[ "python", "encoding" ]
I'm trying to write out to a flat file some Chinese, or Russian or various non-English character-sets for testing purposes. I'm getting stuck on how to output a Unicode hex-decimal or decimal value to its corresponding character. For example in Python, if you had a hard coded set of characters like `абвгдежзи...
Use [`unichr()`](http://docs.python.org/library/functions.html#unichr) (Python 2) or [`chr()`](https://docs.python.org/3/library/functions.html#chr) (Python 3): ``` In [4]: print(unichr(1081)) Out[4]: й ```
add one row in a pandas.DataFrame
10,715,965
187
2012-05-23T08:12:31Z
10,716,007
127
2012-05-23T08:14:43Z
[ "python", "pandas" ]
I understand that pandas is designed to load fully populated DataFrame but I need to **create an empty DataFrame then add rows, one by one**. What is the best way to do this ? I successfully created an empty DataFrame with : ``` res = DataFrame(columns=('lib', 'qty1', 'qty2')) ``` Then I can add a new row and fill a...
You could use `pandas.concat()` or `DataFrame.append()`. For details and examples, see [Merge, join, and concatenate](http://pandas.pydata.org/pandas-docs/stable/merging.html).
add one row in a pandas.DataFrame
10,715,965
187
2012-05-23T08:12:31Z
17,496,530
88
2013-07-05T20:38:13Z
[ "python", "pandas" ]
I understand that pandas is designed to load fully populated DataFrame but I need to **create an empty DataFrame then add rows, one by one**. What is the best way to do this ? I successfully created an empty DataFrame with : ``` res = DataFrame(columns=('lib', 'qty1', 'qty2')) ``` Then I can add a new row and fill a...
You could create a list of dictionary. Where each dictionary in the list corresponds to a input data row. These rows are then added to the main list in a for loop. Once the list is complete, then create a data frame. This is a much faster approach. I has a similar problem where if I created a data frame for each row a...
add one row in a pandas.DataFrame
10,715,965
187
2012-05-23T08:12:31Z
23,394,497
22
2014-04-30T17:31:04Z
[ "python", "pandas" ]
I understand that pandas is designed to load fully populated DataFrame but I need to **create an empty DataFrame then add rows, one by one**. What is the best way to do this ? I successfully created an empty DataFrame with : ``` res = DataFrame(columns=('lib', 'qty1', 'qty2')) ``` Then I can add a new row and fill a...
For efficient appending see [How to add an extra row to a pandas dataframe](http://stackoverflow.com/questions/19365513/how-to-add-an-extra-row-to-a-pandas-dataframe/19368360#19368360) and [*Setting With Enlargement*](http://pandas.pydata.org/pandas-docs/dev/indexing.html#setting-with-enlargement). Add rows through `l...
add one row in a pandas.DataFrame
10,715,965
187
2012-05-23T08:12:31Z
24,888,331
100
2014-07-22T13:10:25Z
[ "python", "pandas" ]
I understand that pandas is designed to load fully populated DataFrame but I need to **create an empty DataFrame then add rows, one by one**. What is the best way to do this ? I successfully created an empty DataFrame with : ``` res = DataFrame(columns=('lib', 'qty1', 'qty2')) ``` Then I can add a new row and fill a...
Example at @Nasser's answer: ``` >>> df = DataFrame(columns=('lib', 'qty1', 'qty2')) >>> for i in range(5): >>> df.loc[i] = [randint(-1,1) for n in range(3)] >>> >>> print(df) lib qty1 qty2 0 0 0 -1 1 -1 -1 1 2 1 -1 1 3 0 0 0 4 1 -1 -1 [5 rows x 3 columns] ``...
add one row in a pandas.DataFrame
10,715,965
187
2012-05-23T08:12:31Z
24,913,075
31
2014-07-23T14:21:45Z
[ "python", "pandas" ]
I understand that pandas is designed to load fully populated DataFrame but I need to **create an empty DataFrame then add rows, one by one**. What is the best way to do this ? I successfully created an empty DataFrame with : ``` res = DataFrame(columns=('lib', 'qty1', 'qty2')) ``` Then I can add a new row and fill a...
If you know the number of entries ex ante, you should preallocate the space by also providing the index (taking the data example from a different answer): ``` import pandas as pd import numpy as np # we know we're gonna have 5 rows of data numberOfRows = 5 # create dataframe df = pd.DataFrame(index=np.arange(0, number...
add one row in a pandas.DataFrame
10,715,965
187
2012-05-23T08:12:31Z
31,037,040
21
2015-06-24T21:06:31Z
[ "python", "pandas" ]
I understand that pandas is designed to load fully populated DataFrame but I need to **create an empty DataFrame then add rows, one by one**. What is the best way to do this ? I successfully created an empty DataFrame with : ``` res = DataFrame(columns=('lib', 'qty1', 'qty2')) ``` Then I can add a new row and fill a...
``` mycolumns = ['A', 'B'] df = pd.DataFrame(columns=mycolumns) rows = [[1,2],[3,4],[5,6]] for row in rows: df.loc[len(df)] = row ```
add one row in a pandas.DataFrame
10,715,965
187
2012-05-23T08:12:31Z
35,583,219
11
2016-02-23T16:43:07Z
[ "python", "pandas" ]
I understand that pandas is designed to load fully populated DataFrame but I need to **create an empty DataFrame then add rows, one by one**. What is the best way to do this ? I successfully created an empty DataFrame with : ``` res = DataFrame(columns=('lib', 'qty1', 'qty2')) ``` Then I can add a new row and fill a...
You can append a single row as a dictionary using the `ignore_index` option. ``` >>> f = pandas.DataFrame(data = {'Animal':['cow','horse'], 'Color':['blue', 'red']}) >>> f Animal Color 0 cow blue 1 horse red >>> f.append({'Animal':'mouse', 'Color':'black'}, ignore_index=True) Animal Color 0 cow blue 1...
nginx and supervisor setup in Ubuntu
10,716,159
40
2012-05-23T08:25:44Z
10,716,427
9
2012-05-23T08:42:26Z
[ "python", "django", "apache", "nginx", "supervisord" ]
I'm using django-gunicorn-nginx setup by following this tutorial <http://ijcdigital.com/blog/django-gunicorn-and-nginx-setup/> Upto nginx setup, it is working. Then I installed supervisor, configured it and then I reboot my server and checked, it shows 502 bad gateway. I'm using Ubuntu 12.04 LTS /etc/supervisor/conf.d...
Are you sure that supervisord is installed and running? Is there a socket file in present at `/var/run/supervisor.sock`? The error indicates that `supervisorctl`, the control CLI, cannot reach the UNIX socket to communicate with `supervisord`, the daemon. You could also check `/etc/supervisor/supervisord.conf` and se...
nginx and supervisor setup in Ubuntu
10,716,159
40
2012-05-23T08:25:44Z
17,917,577
20
2013-07-29T06:45:54Z
[ "python", "django", "apache", "nginx", "supervisord" ]
I'm using django-gunicorn-nginx setup by following this tutorial <http://ijcdigital.com/blog/django-gunicorn-and-nginx-setup/> Upto nginx setup, it is working. Then I installed supervisor, configured it and then I reboot my server and checked, it shows 502 bad gateway. I'm using Ubuntu 12.04 LTS /etc/supervisor/conf.d...
I have met the same issue as you and after several times, here comes the solution: 1. First remove the apt-get supervisor version: ``` sudo apt-get remove supervisor ``` 2. Kill the backend supervisor process: ``` sudo ps -ef | grep supervisor ``` 3. Then get the newest version(apt-get version w...
nginx and supervisor setup in Ubuntu
10,716,159
40
2012-05-23T08:25:44Z
18,858,970
52
2013-09-17T20:07:04Z
[ "python", "django", "apache", "nginx", "supervisord" ]
I'm using django-gunicorn-nginx setup by following this tutorial <http://ijcdigital.com/blog/django-gunicorn-and-nginx-setup/> Upto nginx setup, it is working. Then I installed supervisor, configured it and then I reboot my server and checked, it shows 502 bad gateway. I'm using Ubuntu 12.04 LTS /etc/supervisor/conf.d...
That there is no socket file probably means that supervisor isn't running. A reason that it isn't running might be that your qlimp.conf file has some sort of error in it. If you do a ``` sudo service supervisor start ``` you can see whether or not this is the case. If supervisor is already running, it will say. And i...
nginx and supervisor setup in Ubuntu
10,716,159
40
2012-05-23T08:25:44Z
26,785,043
12
2014-11-06T16:56:08Z
[ "python", "django", "apache", "nginx", "supervisord" ]
I'm using django-gunicorn-nginx setup by following this tutorial <http://ijcdigital.com/blog/django-gunicorn-and-nginx-setup/> Upto nginx setup, it is working. Then I installed supervisor, configured it and then I reboot my server and checked, it shows 502 bad gateway. I'm using Ubuntu 12.04 LTS /etc/supervisor/conf.d...
Try this ``` cd /etc/supervisor sudo supervisord sudo supervisorctl restart all ```
What are the correct usage/parameter values for HoughCircles in OpenCV for Iris detection?
10,716,464
6
2012-05-23T08:44:31Z
10,718,967
12
2012-05-23T11:27:11Z
[ "python", "opencv", "computer-vision", "image-recognition", "biometrics" ]
I've been reading about the subject but cannot get the idea in "plain English" about the usage and parameters for HoughCircles (specially the ones after CV\_HOUGH\_GRADIENT). What's an accumulator threshold? Are 100 "votes" a right value? I could find and "mask" the pupil, and worked my way through the Canny function...
`HoughCircles` can be kind of tricky, I suggest looking through [this thread](http://stackoverflow.com/questions/9860667/writing-robust-color-and-size-invariant-circle-detection-with-opencv-based-on). Where a bunch of people, including me ;), discuss how to use it. The key parameter is `param2`, the so-called `accumula...
Where is nose's assert_raises function?
10,716,506
4
2012-05-23T08:47:16Z
10,716,688
7
2012-05-23T08:58:56Z
[ "python", "nose" ]
I'm using nose 1.1.2 to write tests for a Python project. There is this `assert_raises` function that happens to be mentioned in the documentation but I can't find it anywhere. It should be a shorthand for something like this: ``` value_error_raised = False try: do_something_that_should_raise_value_error() except...
``` >>> from nose.tools import assert_raises >>> assert_raises <bound method Dummy.assertRaises of <nose.tools.Dummy testMethod=nop>> >>> import nose >>> nose.__version__ '1.1.2' ``` I personally use the unittest2.TestCase classes with nosetests, and use self.assertRaises.
How to convert a string to its Base-10 representation?
10,716,796
5
2012-05-23T09:09:51Z
10,716,923
7
2012-05-23T09:17:31Z
[ "python", "string", "base-conversion" ]
Is there any python module that would help me to convert a string into a 64-bit integer? (the maximum length of this string is 8 chars, so it should fit in a long). I would like to avoid having to write my own method. Example: ``` Input String Hex result (Base-10 Integer) 'Y' 59 89 'Y...
This is a job for [`struct`](http://docs.python.org/library/struct.html): ``` >>> s = 'YZ' >>> struct.unpack('>Q', '\x00' * (8 - len(s)) + s) (22874,) ``` Or a bit trickier: ``` >>> int(s.encode('hex'), 16) 22874 ```
python underscores: learn python the hard way exercise 40
10,716,916
2
2012-05-23T09:16:59Z
10,716,961
8
2012-05-23T09:19:32Z
[ "python", "python-2.7" ]
Iam trying to do the exercises in the book "Learn Python the hard way" page: 106. The example is below: ``` cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'} cities['NY'] = 'New York' cities['OR'] = 'Portland' def find_city(themap, state): if state in themap: return themap[state] ...
This code: ``` cities['_find'] = find_city ``` simply inserts the function `find_city` into the `cities` dictionary, using the key `_find`. The underscore has no particular meaning, it's just part of the key string. Probably chosen to not collide with actual city names. This code: ``` city_found = cities['_find'](c...
Common title to many subplots in Matplotlib
10,717,104
24
2012-05-23T09:27:25Z
10,717,180
44
2012-05-23T09:32:04Z
[ "python", "matplotlib" ]
I am making a chart in matplotlib and I have many subplots in it each of them with a different title, but on the top I also want to a put a title to the whole chart. How this can be done?
You can use the [`pyplot.suptitle`](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.suptitle) command to add a *centered title to the figure* in addition to sub plot titles.
Have the same README both in Markdown and reStructuredText
10,718,767
92
2012-05-23T11:12:53Z
10,719,349
70
2012-05-23T11:53:40Z
[ "python", "github", "markdown", "restructuredtext", "pypi" ]
I have a project hosted on GitHub. For this I have written my README using the Markdown syntax in order to have it nicely formatted on GitHub. As my project is in Python I also plan to upload it to [PyPi](http://pypi.python.org/pypi). The syntax used for READMEs on PyPi is reStructuredText. I would like to avoid havi...
I would recommend [Pandoc](http://johnmacfarlane.net/pandoc/), the "swiss-army knife for converting files from one markup format into another" (check out the diagram of supported conversions at the bottom of the page, it is quite impressive). Pandoc allows markdown to reStructuredText translation directly. There is als...
Have the same README both in Markdown and reStructuredText
10,718,767
92
2012-05-23T11:12:53Z
23,265,673
35
2014-04-24T10:00:08Z
[ "python", "github", "markdown", "restructuredtext", "pypi" ]
I have a project hosted on GitHub. For this I have written my README using the Markdown syntax in order to have it nicely formatted on GitHub. As my project is in Python I also plan to upload it to [PyPi](http://pypi.python.org/pypi). The syntax used for READMEs on PyPi is reStructuredText. I would like to avoid havi...
As @Chris suggested, you can use Pandoc to convert Markdown to RST. This can be simply automated using *pypandoc* module and some magic in setup.py: ``` from setuptools import setup try: from pypandoc import convert read_md = lambda f: convert(f, 'rst') except ImportError: print("warning: pypandoc module n...
Have the same README both in Markdown and reStructuredText
10,718,767
92
2012-05-23T11:12:53Z
23,749,948
19
2014-05-20T02:11:48Z
[ "python", "github", "markdown", "restructuredtext", "pypi" ]
I have a project hosted on GitHub. For this I have written my README using the Markdown syntax in order to have it nicely formatted on GitHub. As my project is in Python I also plan to upload it to [PyPi](http://pypi.python.org/pypi). The syntax used for READMEs on PyPi is reStructuredText. I would like to avoid havi...
The [Markup](https://github.com/github/markup) library used by GitHub supports reStructuredText. This means you can write a README.rst file. They even support syntax specific color highlighting using the `code` and `code-block` directives ([Example](https://github.com/canassa/superbar/blob/master/README.rst))
Python, how to POST statuses/update_with_media to Twitter?
10,719,714
5
2012-05-23T12:16:02Z
11,442,747
9
2012-07-11T22:54:30Z
[ "python", "twitter" ]
I am able to successfully post status updates (tweet) in Python with that: ``` import urllib import oauth2 as oauth token = oauth.Token(access_token,access_token_secret) consumer = oauth.Consumer(consumer_key,consumer_secret) client = oauth.Client(consumer,token) data = {'status': 'hello world'} request_uri = 'http...
At last i got it working and wanted to let know for people who is struggling with this how i finally easily did it with the nice Twython library, it abstract the functions nicely: ``` from twython import Twython twitter = Twython( twitter_token = 'consumer_key', twitter_secret = 'consumer_secret', oauth_t...
Python's itertools product memory consumption
10,720,247
13
2012-05-23T12:48:35Z
10,720,402
9
2012-05-23T12:57:20Z
[ "python", "generator", "itertools" ]
The [documentation](http://docs.python.org/library/itertools.html#itertools.product) says that the cartesian product function ``` the actual implementation does not build up intermediate results in memory. ``` How can that be possible with generators? Can somebody show me an example with a bounded memory consumption ...
Looking at the module's source code, `itertools.product()` actually converts every argument to a tuple: ``` // product_new() in itertoolsmodule.c for (i=0; i < nargs ; ++i) { PyObject *item = PyTuple_GET_ITEM(args, i); PyObject *pool = PySequence_Tuple(item); //<==== Call tuple(arg) if (pool == NULL) ...
Can we use the login page at /admin in django for our own use?
10,721,143
6
2012-05-23T13:37:28Z
10,721,550
9
2012-05-23T14:00:16Z
[ "python", "django", "django-login" ]
Can I use the login page available at: `/admin` for non-staff users to login? I'm using the following settings in my django settings file: ``` LOGIN_URL = '/admin/' LOGIN_REDIRECT_URL = '/' ``` When I login, it doesn't redirect me to the root folder. Am I doing it the right way? Note: I'm using decorator `@login_req...
Non-staff members can't login through the admin view, so you can't. There is a Django view that does exactly what you need, however: `django.contrib.auth.views.login` You can easily add it to your `urlconf`: ``` from django.contrib.auth.views import login urlpatterns = ('', #snip url(r'^login/$', login) ) `...
Can we use the login page at /admin in django for our own use?
10,721,143
6
2012-05-23T13:37:28Z
24,038,829
7
2014-06-04T13:30:49Z
[ "python", "django", "django-login" ]
Can I use the login page available at: `/admin` for non-staff users to login? I'm using the following settings in my django settings file: ``` LOGIN_URL = '/admin/' LOGIN_REDIRECT_URL = '/' ``` When I login, it doesn't redirect me to the root folder. Am I doing it the right way? Note: I'm using decorator `@login_req...
With Django 1.6 I was able to use django's own admin login template with the following setup. Then when I open '/' it will redirect me to the login screen, and after logging in it sends me back to '/' **settings.py** ``` INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.con...
Why does json serialization of datetime objects in python not work out of the box for datetime objects
10,721,409
41
2012-05-23T13:52:03Z
10,721,485
9
2012-05-23T13:57:00Z
[ "python", "json", "serialization", "simplejson" ]
Why does the json serialization not work for datetime objects . As I understand json serialization the basic idea for any object can be call the `__str__` builtin function and then urlencode the object that you get as a response. But in case of datetime i get the following error ``` TypeError: datetime.datetime(2012, ...
How would you like them to be serialized? JSON doesn't specify how to handle dates, so the python `json` library cannot make the decision on how to then represent these for you. That completely depends on how the other side (browser, script, whatever) handles dates in JSON as well.
Why does json serialization of datetime objects in python not work out of the box for datetime objects
10,721,409
41
2012-05-23T13:52:03Z
10,721,564
76
2012-05-23T14:01:05Z
[ "python", "json", "serialization", "simplejson" ]
Why does the json serialization not work for datetime objects . As I understand json serialization the basic idea for any object can be call the `__str__` builtin function and then urlencode the object that you get as a response. But in case of datetime i get the following error ``` TypeError: datetime.datetime(2012, ...
No it doesn't work that way in `json` module. The module provides you with a default encoder: `json.JSONEncoder`. You need to extend this to provide your implementation of `default` method to serialize objects. Something like this: ``` import json import datetime from time import mktime class MyEncoder(json.JSONEncod...
Shared-memory objects in python multiprocessing
10,721,915
49
2012-05-23T14:20:21Z
10,724,332
49
2012-05-23T16:42:54Z
[ "python", "parallel-processing", "multiprocessing", "shared-memory" ]
Suppose I have a large in memory numpy array, I have a function `func` that takes in this giant array as input (together with some other parameters). `func` with different paremeters can be run in parallel. For example ``` def func(arr, param): # do stuff to arr, param # build array arr pool = Pool(processes = 6...
If you use an operating system that uses copy-on-write `fork()` semantics (like any common unix), then as long as you never alter your data structure it will be available to all child processes without taking up additional memory. You will not have to do anything special (except make absolutely sure you don't alter the...
class is not defined despite being imported
10,722,415
7
2012-05-23T14:48:15Z
10,722,426
17
2012-05-23T14:48:49Z
[ "python", "class", "module" ]
I'm trying to brush up on my python skills, and I'm dicking around with writing classes but I seem to have run into a really confusing error. Despite importing the .py file containing my class, python is insistent that the class doesn't actually exist. class def: ``` class greeter: def __init__(self, arg1=None): ...
Use the fully-qualified name: ``` sayinghi = testclass.greeter("hello world!") ``` There is an alternative form of `import` that would bring `greeter` into your namespace: ``` from testclass import greeter ```
class is not defined despite being imported
10,722,415
7
2012-05-23T14:48:15Z
10,722,489
9
2012-05-23T14:52:05Z
[ "python", "class", "module" ]
I'm trying to brush up on my python skills, and I'm dicking around with writing classes but I seem to have run into a really confusing error. Despite importing the .py file containing my class, python is insistent that the class doesn't actually exist. class def: ``` class greeter: def __init__(self, arg1=None): ...
``` import testclass # change to from testclass import greeter ``` or ``` import testclass sayinghi = greeter("hello world!") # change to import testclass sayinghi = testclass.greeter("hello world!") ``` You imported the module/package, but you need to reference the class inside it. You could also do this instead ...
python subprocess is overwriting file used for stdout - I need it to append to the file (windows)
10,722,752
3
2012-05-23T15:07:16Z
10,722,790
7
2012-05-23T15:09:05Z
[ "python", "windows", "file", "subprocess", "stdout" ]
I want to append the `STDOUT` of `subprocess.call()` to an existing file. My code below overwrites the file - ``` log_file = open(log_file_path, 'r+') cmd = r'echo "some info for the log file"' subprocess.call(cmd, shell=True, stdout=log_file, stderr=STDOUT) log_file.close() ``` I'm looking for the equivalent of `>>`...
Use the 'a' append mode instead: ``` log_file = open(log_file_path, 'a+') ``` If you still see previous content overwritten, perhaps Windows needs you to explicitly seek to the end of the file; open as 'r+' or 'w' and seek to the end of the file: ``` import os log_file = open(log_file_path, 'r+') log_file.seek(0, o...
Custom addition method fails during string interpolation
10,722,859
8
2012-05-23T15:12:56Z
10,722,946
17
2012-05-23T15:17:13Z
[ "python", "python-3.x" ]
``` #it's python 3.2.3 class point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, point): self.x += point.x self.y += point.y return self def __repr__(self): return 'point(%s, %s)' % (self.x, self.y) class Test: def __init__(self): ...
Your `__add__` function modifies the left-hand argument to `+`. For example: ``` >>> x = point(0, 0) >>> x + point(1, 1) point(1, 1) >>> x point(1, 1) ``` You should change `__add__` to be like ``` def __add__(self, oth): return point(self.x + oth.x, self.y + oth.y) ```
Flask-WTF - validate_on_submit() is never executed
10,722,968
16
2012-05-23T15:18:28Z
10,729,135
9
2012-05-23T23:10:19Z
[ "python", "forms", "validation", "flask", "wtforms" ]
I'm using Flask-WTF: Here is my form: ``` from flask.ext.wtf import Form, TextField class BookNewForm(Form): name = TextField('Name') ``` Here is the controller: ``` @book.route('/book/new', methods=['GET', 'POST']) def customers_new(): form = BookNewForm() if form.is_submitted(): print "submit...
you can print errors ``` print form.errors ``` or ``` app.logger.debug(form.errors) ``` and if you got csrf-error, you should set **form.csrf\_token** in your template.
Flask-WTF - validate_on_submit() is never executed
10,722,968
16
2012-05-23T15:18:28Z
10,793,200
23
2012-05-29T04:47:15Z
[ "python", "forms", "validation", "flask", "wtforms" ]
I'm using Flask-WTF: Here is my form: ``` from flask.ext.wtf import Form, TextField class BookNewForm(Form): name = TextField('Name') ``` Here is the controller: ``` @book.route('/book/new', methods=['GET', 'POST']) def customers_new(): form = BookNewForm() if form.is_submitted(): print "submit...
You're not inserting the CSRF field in the HTML form. ``` <form method=post> {{ form.csrf_token }} {{ form.name }} <input type=submit> </form> ``` After adding `form.csrf_token` to the template ([docs](http://flask-wtf.readthedocs.io/en/latest/quickstart.html#creating-forms)), the form will validate as ex...
Summing over lists in python - is there a better way?
10,723,659
5
2012-05-23T15:55:36Z
10,723,703
17
2012-05-23T15:58:58Z
[ "python", "list", "sum" ]
Is there a more sensible way of doing this? I want to make a new list by summing over the indices of a lot of other lists. I'm fairly new to programming and this seems like a very clunky method! ``` list1 = [1,2,3,4,5] list2 = [1,1,1,4,1] list3 = [1,22,3,1,5] list4 = [1,2,5,4,5] ... list100 = [4,5,6,7,8] i = 0 while ...
This is a pretty good use case for [`zip`](http://docs.python.org/library/functions.html#zip). ``` >>> list1 = [1,2,3,4,5] >>> list2 = [1,1,1,4,1] >>> list3 = [1,22,3,1,5] >>> list4 = [1,2,5,4,5] >>> [sum(x) for x in zip(list1, list2, list3, list4)] [4, 27, 12, 13, 16] ``` or if you have your data as a list of lists ...
Expand alphabetical range to list of characters in Python
10,724,255
6
2012-05-23T16:36:40Z
10,724,297
10
2012-05-23T16:40:03Z
[ "python", "string", "character", "alphabetical", "alphabet" ]
I have strings describing a range of characters alphabetically, made up of two characters separated by a hyphen. I'd like to expand them out into a list of the individual characters like this: ``` 'a-d' -> ['a','b','c','d'] 'B-F' -> ['B','C','D','E','F'] ``` What would be the best way to do this in Python?
``` In [19]: s = 'B-F' In [20]: list(map(chr, range(ord(s[0]), ord(s[-1]) + 1))) Out[20]: ['B', 'C', 'D', 'E', 'F'] ``` The trick is to convert both characters to their ASCII codes, and then use `range()`. P.S. Since you require a list, the `list(map(...))` construct can be replaced with a list comprehension.
Getting all arguments and values passed to a Python function
10,724,495
7
2012-05-23T16:54:11Z
10,724,568
8
2012-05-23T16:59:35Z
[ "python" ]
I have a Python function, `fetch_data`, that goes and hits a remote API, grabs some data, and returns it wrapped in a response object. It looks a bit like the below: ``` def fetch_data(self, foo, bar, baz, **kwargs): response = Response() # Do various things, get some data return response ``` Now, it's po...
I think a more Pythonic way is to turn your function into a generator, fetching and `yield`ing data for as long as the server keeps returning stuff. This should result in neat code and would enable you to side-step all of the complexities of preserving the arguments across iterations (Python will magically do it for y...
Getting all arguments and values passed to a Python function
10,724,495
7
2012-05-23T16:54:11Z
10,724,602
11
2012-05-23T17:01:19Z
[ "python" ]
I have a Python function, `fetch_data`, that goes and hits a remote API, grabs some data, and returns it wrapped in a response object. It looks a bit like the below: ``` def fetch_data(self, foo, bar, baz, **kwargs): response = Response() # Do various things, get some data return response ``` Now, it's po...
Not something I'd do, but you could use [`inspect.getargspec`](http://docs.python.org/library/inspect.html#inspect.getargspec) to introspect the arguments your method takes: ``` >>> import inspect >>> def foobar(foo, bar, baz): ... return inspect.getargspec(foobar) ... >>> foobar(1, 2, 3) ArgSpec(args=['foo', 'ba...
Getting all arguments and values passed to a Python function
10,724,495
7
2012-05-23T16:54:11Z
23,982,966
10
2014-06-01T18:18:16Z
[ "python" ]
I have a Python function, `fetch_data`, that goes and hits a remote API, grabs some data, and returns it wrapped in a response object. It looks a bit like the below: ``` def fetch_data(self, foo, bar, baz, **kwargs): response = Response() # Do various things, get some data return response ``` Now, it's po...
> Essentially, I'm trying to work out how to, from within a function, get a completely populated \*args and \*\*kwargs, including the function's named parameters. How about saving the arguments via `locals()` at the beginning of the function? ``` def my_func(a, *args, **kwargs): saved_args = locals() print("s...
Python's hasattr on list values of dictionaries always returns false?
10,724,766
9
2012-05-23T17:13:55Z
10,724,850
13
2012-05-23T17:19:55Z
[ "python", "list", "class", "dictionary", "hasattr" ]
I have a dictionary that sometimes receives calls for non-existent keys, so I try and use `hasattr` and `getattr` to handle these cases: ``` key_string = 'foo' print "current info:", info print hasattr(info, key_string) print getattr(info, key_string, []) if hasattr(info, key_string): array = getattr(info, key_str...
`hasattr` does not test for members of a dictionary. Use the `in` operator instead, or the `.has_key` method: ``` >>> example = dict(foo='bar') >>> 'foo' in example True >>> example.has_key('foo') True >>> 'baz' in example False ``` But note that `dict.has_key()` has been deprecated, is recommended against by the PEP...
how to do a conditional decorator in python 2.6
10,724,854
13
2012-05-23T17:20:04Z
10,724,892
8
2012-05-23T17:23:07Z
[ "python", "conditional", "decorator" ]
Is it possible to decorator a function conditionally. For example, I want to decorate the function `foo()` with a timer function (`timeit`) only doing\_performance\_analysis is `True` (see the psuedo-code below). ``` if doing_performance_analysis: @timeit def foo(): """ do something, timeit function will r...
A decorator is simply a function applied to another function. You can apply it manually: ``` def foo(): # whatever time.sleep(2) if doing_performance_analysis: foo = timeit(foo) ```
how to do a conditional decorator in python 2.6
10,724,854
13
2012-05-23T17:20:04Z
10,724,898
18
2012-05-23T17:24:08Z
[ "python", "conditional", "decorator" ]
Is it possible to decorator a function conditionally. For example, I want to decorate the function `foo()` with a timer function (`timeit`) only doing\_performance\_analysis is `True` (see the psuedo-code below). ``` if doing_performance_analysis: @timeit def foo(): """ do something, timeit function will r...
Decorators are simply callables that return a replacement, optionally the same function, a wrapper, or something completely different. As such, you could create a conditional decorator: ``` class conditional_decorator(object): def __init__(self, dec, condition): self.decorator = dec self.condition ...
Python class that extends int doesn't entirely behave like an int
10,725,057
15
2012-05-23T17:34:55Z
10,729,666
13
2012-05-24T00:27:06Z
[ "python" ]
I'm seeing some weird behavior when trying to convert a string to a class I wrote that extends `int`. Here's a simple program that demonstrates my problem: ``` class MyInt(int): pass toInt = '123456789123456789123456789' print "\nConverting to int..." print type(int(toInt)) print "\nConverting to MyInt..." prin...
The secret is all in the `__new__()` method: ``` >>> class MyInt(int): pass >>> MyInt.__new__ == int.__new__ True >>> MyInt.__new__(MyInt, '123456789101234567890') Traceback (most recent call last): File "<stdin>", line 1, in <module> OverflowError: Python int too large to convert to C long >>> MyInt.__new__(int, '1...
Semantics of tuple unpacking in python
10,725,322
28
2012-05-23T17:56:09Z
10,728,611
27
2012-05-23T22:10:55Z
[ "python", "tuples", "iterable-unpacking" ]
Why does python only allow named arguments to follow a tuple unpacking expression in a function call? ``` >>> def f(a,b,c): ... print a, b, c ... >>> f(*(1,2),3) File "<stdin>", line 1 SyntaxError: only named arguments may follow *expression ``` Is it simply an aesthetic choice, or are there cases where allowi...
i am pretty sure that the reason people "naturally" don't like this is because it makes the meaning of later arguments ambiguous, depending on the length of the interpolated series: ``` def dangerbaby(a, b, *c): hug(a) kill(b) >>> dangerbaby('puppy', 'bug') killed bug >>> cuddles = ['puppy'] >>> dangerbaby(*...
Arbitrary precision of square roots
10,725,522
12
2012-05-23T18:09:46Z
10,725,610
34
2012-05-23T18:16:38Z
[ "python", "math" ]
I was quite disappointed when `decimal.Decimal(math.sqrt(2))` yielded ``` Decimal('1.4142135623730951454746218587388284504413604736328125') ``` and the digits after the 15th decimal place turned out wrong. (Despite happily giving you much more than 15 digits!) How can I get the first `m` *correct* digits in the deci...
Use the `sqrt` method on Decimal ``` >>> from decimal import * >>> getcontext().prec = 100 >>> Decimal(2).sqrt() Decimal('1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573') >>> ```
Authenticating to Active Directory with python-ldap always returns (97, [])
10,725,891
11
2012-05-23T18:38:11Z
10,743,770
12
2012-05-24T19:06:00Z
[ "python", "authentication", "active-directory", "python-ldap" ]
Similar to [this question](http://stackoverflow.com/questions/140439/authenticating-against-active-directory-using-python-ldap), I am trying to perform simple authentication to a 2003 Active Directory using python ldap (CentOS 6.2 x86\_64, Python 2.6.6, python-ldap 2.3.10). Despite following all the usual steps in the...
Michael Ströder, the author of the python-ldap library, enlightened me thus: > The 97 is not the LDAP result code. It's the result type > ldap.RES\_BIND. Normally you don't have to look at the results returned > by LDAPObject.simple\_bind\_s() (unless you want to extract the bind > response controls). > > If the LDAP...
Tornado URL query parameters
10,726,486
21
2012-05-23T19:21:51Z
10,726,702
32
2012-05-23T19:39:10Z
[ "python", "tornado" ]
I've been playing around with Tornado, and I've written some code that doesn't seem very nice. I'm writing an app to store recipes as an example. These are my handlers: ``` handlers = [ (r"/recipes/", RecipeHandler), (r"/recipes", RecipeSearchHandler), #so query params can be used to search ] ``` This lead m...
There is a better way for GET requests. There is a demo in the tornado source on github [here](https://github.com/facebook/tornado/blob/master/demos/blog/blog.py#L87) ``` # url handler handlers = [(r"/entry/([^/]+)", EntryHandler),] class EntryHandler(BaseHandler): def get(self, slug): entry = self.db.get...
Tornado URL query parameters
10,726,486
21
2012-05-23T19:21:51Z
13,926,043
19
2012-12-18T04:01:00Z
[ "python", "tornado" ]
I've been playing around with Tornado, and I've written some code that doesn't seem very nice. I'm writing an app to store recipes as an example. These are my handlers: ``` handlers = [ (r"/recipes/", RecipeHandler), (r"/recipes", RecipeSearchHandler), #so query params can be used to search ] ``` This lead m...
`get_argument` allows you to provide a default value: ``` details=self.get_argument("details", None, True) ``` If it is provided, then no exception will occur if the argument isn't provided
What error to raise when class state is invalid?
10,726,919
15
2012-05-23T19:55:30Z
10,727,476
13
2012-05-23T20:39:34Z
[ "python", "exception" ]
In a Python class, what type of error should I raise from an instance method when some of the other attributes of the class must be changed before running that method? I'm coming from a C# background where I would use `InvalidOperationException`, "the exception that is thrown when a method call is invalid for the obje...
`ValueError` is the best thing to raise in this case. For python, you should prefer using the [built-in exception types](http://docs.python.org/library/exceptions.html) over creating your own. You should only create new exception types when you expect that you will need to catch it and behave very differently than you'...
javascript pass
10,727,025
28
2012-05-23T20:03:38Z
10,727,053
35
2012-05-23T20:06:28Z
[ "javascript", "python", "exception", "exception-handling" ]
Is there something along the lines of python 'pass' in javascript? I want to do the javascript equivalent of: ``` try: # Something that throws exception catch: pass ```
[`pass` is a no-op in Python.](http://docs.python.org/release/2.5.2/ref/pass.html) You need it for empty blocks because ``` try: # Something that throws exception catch: # continue other stuff ``` [is a syntax error](http://ideone.com/W13ic). In JavaScript you can just use an empty `catch` block. ``` try { ...
javascript pass
10,727,025
28
2012-05-23T20:03:38Z
10,727,055
26
2012-05-23T20:06:35Z
[ "javascript", "python", "exception", "exception-handling" ]
Is there something along the lines of python 'pass' in javascript? I want to do the javascript equivalent of: ``` try: # Something that throws exception catch: pass ```
There is, and here it is: ``` ``` That's right, nothing at all: ``` try { somethingThatThrowsAnException(); } catch (e) { } ```
jsonify is not defined - Internal Server Error
10,727,366
3
2012-05-23T20:30:20Z
10,727,482
12
2012-05-23T20:39:54Z
[ "python", "json", "flask", "internal-server-error" ]
Playing around with Flask and just wanted to print out some data as JSON formatted, but I keep getting the error: > NameError: global name 'jsonify' is not defined ``` from flask import Flask from flask import json app = Flask(__name__) @app.route("/") def testJSON(): x = "Test1" y = "Test2" ...
`jsonify()` [is a function contained within the `flask` module](https://bitbucket.org/mitsuhiko/flask/src/4d82231621fc/flask.py#cl-207). So you would need to import it. Change the beginning of your script to: ``` from flask import jsonify # <- `jsonify` instead of `json` ```
Underlining Text in Python/Matplotlib
10,727,368
7
2012-05-23T20:30:32Z
10,727,730
10
2012-05-23T20:57:47Z
[ "python", "matplotlib", "underline" ]
I couldn't find another thread or documentation on this topic - has anyone ever been successful underlining in pythons matplotlib package? The syntax I am using is something like this for all the other attributes: ``` plt.text(0.05, 0.90, 'Parameters: ', fontsize=12) ``` However, I can't figure out how to underline t...
Matplotlib can use LaTeX to handle all text, see [this page](http://matplotlib.sourceforge.net/users/usetex.html) of the documnetation for more information. The command for underlining text in LaTeX is simply `\underline`. From the docstring of one of the example scripts: > You can use TeX to render all of your matplo...
Why isn't this 'if' statement being read?
10,728,166
4
2012-05-23T21:31:19Z
10,728,200
11
2012-05-23T21:33:30Z
[ "python" ]
In my code, I want the two answers 'Opposite' and 'Hypotenuse,' to have two separate outcomes, however, whenever I test the code and answer, 'opposite,' it ignores the rest of the code and goes down to the 'hypotenuse' questions. Have I formatted it wrong/is there a simpler way to do this/etc.? ``` from math import * ...
## Short answer You probably want to change those: ``` if answer == ("Hypotenuse") or ("Hypotenuse.") ... ``` By this: ``` if answer in ("Hypotenuse", "Hypotenuse.", ...): ``` ## Explanation The expression: ``` answer == ("Foo") or ("Bar") ``` It is evaluated like: ``` (answer == ("Foo")) or (("Bar")) ``` And...
Is there feature in Pyramid to specify a route in the template like Django templates?
10,728,333
3
2012-05-23T21:44:32Z
10,730,436
10
2012-05-24T02:41:41Z
[ "python", "pyramid" ]
For example in Django if I have a url named 'home' then I can put {% url home %} in the template and it will navigate to that url. I couldn't find anything specific in the Pyramid docs so I am looking to tou Stack Overflow. Thanks
The brackets depend on the templating engine you are using, but `request.route_url('home')` is the Python code you need inside. For example, in your desired template file: * jinja2--> `{{ request.route_url('home') }}` * mako/chameleon--> `${ request.route_url('home') }` If your route definition includes pattern matc...
Why not assign __init__ to superclass's __init__?
10,728,605
3
2012-05-23T22:10:45Z
10,728,696
9
2012-05-23T22:19:40Z
[ "python" ]
Why don't I ever see the following in Python code? ``` class A: def __init__(self, ...): # something important class B(A): __init__ = A.__init__ ``` It seems to work on my box with Python 2.5, 2.6, 2.7, and PyPy 1.8. I see the following a lot, instead: ``` class B(A): def __init__(self, *args, ...
Sure, it'll work (assuming you get it right, which it is not in your example), but there's no reason to do it. If you want `B` to call `A`'s `__init__()`, just don't define `__init__()` on `B` and that'll happen automatically. That's the whole point of inheritance, after all. The only reason you'd ever want to write a...
Can this Python list comprehension expression be simplified?
10,728,936
3
2012-05-23T22:49:42Z
10,729,033
9
2012-05-23T23:00:15Z
[ "python", "list-comprehension" ]
``` input = "foo ,,bar ,baz," tags = [x.strip() for x in input.split(',') if len(x.strip()) > 0] ``` Desired output is obviously a list with no empty strings in it. The question is in the spirit of micro optimisation; is there a way to not `strip()` the candidate `x` twice, ie once for the test and once for the appen...
Creating a new string is always going to be more expensive than scanning it. `x.isspace()` will return after the first not space character is encountered ``` tags = [x.strip() for x in input.split(',') if x and not x.isspace()] ```
Adding a module (Specifically pymorph) to Spyder (Python IDE)
10,729,116
20
2012-05-23T23:08:31Z
10,741,803
39
2012-05-24T16:44:18Z
[ "python", "import", "module", "easy-install", "spyder" ]
I have managed (after much reading, learning, and frustration :)) to get spyder installed and functioning on my mac. I want to add in a few modules that it doesn't include by default (mahotas and pymorph). I installed both via easy\_install in the terminal and both seemed to install without any error messages. Running ...
Ok, no one has answered this yet but I managed to figure it out and get it working after also posting on the spyder discussion boards. For any libraries that you want to add that aren't included in the default search path of spyder (whatever that is) you need to go into *Tools* and add a path to EACH library via the PY...
Adding a module (Specifically pymorph) to Spyder (Python IDE)
10,729,116
20
2012-05-23T23:08:31Z
12,036,303
16
2012-08-20T10:48:09Z
[ "python", "import", "module", "easy-install", "spyder" ]
I have managed (after much reading, learning, and frustration :)) to get spyder installed and functioning on my mac. I want to add in a few modules that it doesn't include by default (mahotas and pymorph). I installed both via easy\_install in the terminal and both seemed to install without any error messages. Running ...
1. Find the location of a module in Terminal: ``` $ python # open python import pygame # import a module pygame # get the location ``` 2. Copy-paste the module folder to the 'Spyder.app/Contents/Resources/lib/python2.7' 3. Relaunch Spyder.app
Adding a module (Specifically pymorph) to Spyder (Python IDE)
10,729,116
20
2012-05-23T23:08:31Z
33,694,347
8
2015-11-13T13:55:33Z
[ "python", "import", "module", "easy-install", "spyder" ]
I have managed (after much reading, learning, and frustration :)) to get spyder installed and functioning on my mac. I want to add in a few modules that it doesn't include by default (mahotas and pymorph). I installed both via easy\_install in the terminal and both seemed to install without any error messages. Running ...
Using `!` on the IPython console within spyder allows you to use `pip`. So, in the example, you could do: ``` [1] !pip install pymorph ``` Note, this is also available (though perhaps unreliably) on the Python console for Spyder versions before ~2.3.3. Thanks to @CarlosCordoba for this clarification.
How can I set the y axis in radians in a Python plot?
10,729,737
6
2012-05-24T00:38:53Z
10,731,637
9
2012-05-24T05:29:13Z
[ "python", "matplotlib", "axes", "radians" ]
I would like to write the radian units of the axes as proportional to `\pi`: something like ``` $\frac{\pi}{4}$, $\frac{\pi}{2}$, ... ``` in place of ``` 0.785, 1.5707 ... ``` Is there any standard way? As an example, what should I add to the following code? ``` from pylab import * x=arange(-10.0,10.0,0.1) y= arc...
hard code them in fractions or accept floating numbers ``` import matplotlib.pyplot as plt import numpy as np x=np.arange(-10.0,10.0,0.1) y=np.arctan(x) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x,y,'b.') y_pi = y/np.pi unit = 0.25 y_tick = np.arange(-0.5, 0.5+unit, unit) y_label = [r"$-\frac{\pi}...
add numbers together in python, numbers are extracted from a list of dict
10,729,816
2
2012-05-24T00:51:19Z
10,729,832
9
2012-05-24T00:53:59Z
[ "python", "syntax" ]
New to python! Here is the list of dictionaries I have in python: ``` [{'amt': 400, 'name': 'whatever1'}, {'amt': 300, 'name': 'whatever3'}, {'amt': 500, 'name': 'whatever2'}] ``` I would like to add all the 'amt' together without using a complete for loop. Any ideas?
``` sum(L['amt'] for L in list_of_dicts) ``` should do it.
Create dynamic button in PyQt
10,730,131
4
2012-05-24T01:49:30Z
10,730,209
14
2012-05-24T02:03:12Z
[ "python", "qt", "pyqt" ]
I try to add a function in a PyQt class, but it always returns me an error. ``` # Error: TypeError: connect() slot argument should be a callable or a signal, not 'NoneType' # ``` ``` def commander (self, arg): exec arg def aButton (self, layout, **kwargs): name = kwargs.pop("name","Button") command =...
You need a function: ``` button.clicked.connect(lambda: self.commander(command)) ``` Note the lambda will avoid the evaluation of the function call, so it'll call `self.commander(command)` only when clicked
Pydoop on Amazon EMR
10,730,311
8
2012-05-24T02:22:13Z
10,889,157
8
2012-06-04T22:15:41Z
[ "python", "hadoop", "amazon-web-services", "emr" ]
How would I use [Pydoop](http://sourceforge.net/apps/mediawiki/pydoop/index.php?title=Main_Page) on Amazon EMR? I tried googling this topic to no avail: is it at all possible?
I finally got this working. Everything happens on the master node...ssh to that node as the user hadoop You need some packages: ``` sudo easy_install argparse importlib sudo apt-get update sudo apt-get install libboost-python-dev ``` To build stuff: ``` wget http://apache.mirrors.pair.com/hadoop/common/hadoop-0.20....
Sorting a list of lists by length and by value
10,731,038
6
2012-05-24T04:12:49Z
10,731,062
9
2012-05-24T04:15:57Z
[ "python", "list" ]
I have a list of lists: ``` >>> a = [['3D'], ['3D', '4D', '5D'], ['4C'], ['2C'],['4C', '4D'], ['4D'], ['5D'], \ ... ['JC'], ['JC', 'JS'], ['JS']] ``` You may notice that this is card values i.e. C= Clubs etc. J = Jack etc. I also have a reference list: ``` >>> confrom = {'3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9'...
Try this: ``` sorted(a, key = lambda x: (len(x), [confrom[card[0]] for card in x])) ``` [ideone](http://ideone.com/u9uJz)
Following backreferences of unknown kinds in NDB
10,731,433
7
2012-05-24T05:03:13Z
10,739,054
8
2012-05-24T14:04:00Z
[ "python", "google-app-engine", "gae-datastore", "app-engine-ndb" ]
I'm in the process of writing my first RESTful web service atop GAE and the Python 2.7 runtime; I've started out using Guido's shiny new ndb API. However, I'm unsure how to solve a particular case without the implicit back-reference feature of the original db API. If the user-agent requests a particular resource and t...
Interesting question! So basically you want to look at the Contact class and find out if there is some other model class that has a KeyProperty referencing it; in this example PhoneNumber (but there could be many). I think the solution is to ask your users to explicitly add this link when the PhoneNumber class is crea...
python - get list of tuples first index?
10,735,282
15
2012-05-24T10:03:41Z
10,735,307
19
2012-05-24T10:05:05Z
[ "python", "list", "tuples" ]
What's the most compact way to return the following: Given a list of tuples, return a list consisting of the tuples first (or second, doesn't matter) elements. For: ``` [(1,'one'),(2,'two'),(3,'three')] ``` returned list would be ``` [1,2,3] ```
``` >>> tl = [(1,'one'),(2,'two'),(3,'three')] >>> [item[0] for item in tl] [1, 2, 3] ```
python - get list of tuples first index?
10,735,282
15
2012-05-24T10:03:41Z
10,735,330
9
2012-05-24T10:06:35Z
[ "python", "list", "tuples" ]
What's the most compact way to return the following: Given a list of tuples, return a list consisting of the tuples first (or second, doesn't matter) elements. For: ``` [(1,'one'),(2,'two'),(3,'three')] ``` returned list would be ``` [1,2,3] ```
``` >>> mylist = [(1,'one'),(2,'two'),(3,'three')] >>> [j for i,j in mylist] ['one', 'two', 'three'] >>> [i for i,j in mylist] [1, 2, 3] ``` This is using a [list comprehension (have a look at this link)](http://docs.python.org/tutorial/datastructures.html). So it iterates through the elements in `mylist`, setting `i`...
python - get list of tuples first index?
10,735,282
15
2012-05-24T10:03:41Z
10,735,413
26
2012-05-24T10:12:14Z
[ "python", "list", "tuples" ]
What's the most compact way to return the following: Given a list of tuples, return a list consisting of the tuples first (or second, doesn't matter) elements. For: ``` [(1,'one'),(2,'two'),(3,'three')] ``` returned list would be ``` [1,2,3] ```
use zip if you need both ``` >>> r=(1,'one'),(2,'two'),(3,'three') >>> zip(*r) [(1, 2, 3), ('one', 'two', 'three')] ```
Using a Ruby gem from a Django application
10,735,998
2
2012-05-24T10:50:00Z
10,736,225
7
2012-05-24T11:03:01Z
[ "python", "ruby-on-rails", "ruby", "django", "interop" ]
Lets say I have a few Ruby gems that I'd like to use from my Python (Django) application. I know this isn't the most straightforward question but let's assume that rewriting the Ruby gem in Python is a lot of work, how can I use it? Should I create an XML-RPC wrapper around it using Rails and call it? Is there somethi...
I suggest you either: * Expose a ruby service using REST or XML-RPC. or * Shell out to a ruby script from Django. To transfer data between Python and Ruby I suggest you use JSON, XML or plain text (depending on what kind of data you need to transfer). I would recommend to use option 2 (start a ruby script from the...
Sentry + Raven, HTTP Error 401: UNAUTHORIZED
10,736,404
6
2012-05-24T11:15:20Z
10,769,059
7
2012-05-26T19:15:00Z
[ "python", "django", "haproxy", "sentry", "raven" ]
I have a [Sentry](http://sentry.readthedocs.org/en/latest/index.html) application, running correctly on the url: mydomain.com:11011. I have a project created with the CDN: <http://XXX:YYY@mydomain.com:11011/2> This url is served with HAProxy with this configuration: ``` listen sentry *:11011 mode tcp server ...
The problem was the different versions of raven on the client and server In the Sentry server: ``` raven==1.8.4 sentry==4.4.5 ``` In the django application: ``` raven==1.9.1 ``` To fix this, do the following, in django application. ``` pip uninstall raven pip install raven==1.8.4 ```
Python missing __exit__ method
10,736,671
4
2012-05-24T11:32:51Z
10,736,851
10
2012-05-24T11:45:08Z
[ "python" ]
Some background: I work in a large bank and I'm trying to re-use some Python modules, which I cannot change, only import. I also don't have the option of installing any new utilities/functions etc (running Python 2.6 on Linux). I've got this at present: In my module: ``` from common.databaseHelper import Backtesting...
Using the `with` protocol assumes that the object used in `with` implements the [context manager protocol](http://docs.python.org/library/stdtypes.html#context-manager-types). Basically this means that the class definition should have `__enter__()` and `__exit__()` methods defined. If you use an object without these, ...
Embedding a matplotlib figure inside a WxPython panel
10,737,459
18
2012-05-24T12:25:41Z
10,741,760
25
2012-05-24T16:41:10Z
[ "python", "wxpython", "matplotlib" ]
How do I embed a **matplotlib figure object** inside a WxPython panel? I googled around and saw complicated examples involving interactive graphics and other extra stuff. Can anybody help with a minimal example?
This is a minimal example for a Panel with a matplotlib canvas: ``` from numpy import arange, sin, pi import matplotlib matplotlib.use('WXAgg') from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas from matplotlib.backends.backend_wx import NavigationToolbar2Wx from matplotlib.figure import ...
Search algorithm but for functions
10,737,986
6
2012-05-24T13:00:17Z
10,738,030
10
2012-05-24T13:03:05Z
[ "python", "algorithm" ]
Given a list of input (let's say they are just integers), and a list of functions (and these functions takes an integer, and returns either True or False). I have to take this list of input, and see if any function in the list would return True for any value in the list. Is there any way to do this faster than O(n^2)...
Without any further information on the functions, the results of the `len(functions) * len(values)` possible function calls must be considered independent from each other, so there is no faster way than checking them all. You can write this a little more concisely, though: ``` any(f(v) for v in values for f in functi...
Can I rewrite my expensive pygame functions in C?
10,738,409
4
2012-05-24T13:24:59Z
10,738,482
8
2012-05-24T13:30:22Z
[ "python", "c", "pygame", "path-finding", "a-star" ]
Is it possible for me to find the expensive functions(for example, A\* pathfinding) in my pygame game and rewrite them as extensions as outlined [here](http://docs.python.org/extending/extending.html)? Is there a speed benefit to doing so? Is there a better (python) solution? I ask this question because I have just s...
> Is there a speed benefit to doing so? It's impossible to say without knowing what it is exactly that you're doing, but the general answer is "very likely". > Is there a better (python) solution? Again, it is impossible to say. Better than what exactly? If you are working with numerical arrays, then the first step...
How do I add a path to PYTHONPATH in virtualenv
10,738,919
55
2012-05-24T13:57:03Z
10,739,838
87
2012-05-24T14:47:30Z
[ "python", "virtualenv" ]
I am trying to add a path to the PYTHONPATH environment variable, that would be only visible from a particular virtualenv environment. I tried `SET PYTHONPATH=...` under a virtualenv command prompt, but that sets the variable for the whole environment. How do I achieve that?
You can usually avoid having to do anything with PYTHONPATH by [using `.pth` files](http://docs.python.org/install/index.html#modifying-python-s-search-path). Just put a file with a .pth extension (any basename works) in your virtualenv's site-packages folder, e.g. `lib\python2.7\site-packages`, with the absolute path ...
How do I add a path to PYTHONPATH in virtualenv
10,738,919
55
2012-05-24T13:57:03Z
15,282,950
62
2013-03-07T22:23:26Z
[ "python", "virtualenv" ]
I am trying to add a path to the PYTHONPATH environment variable, that would be only visible from a particular virtualenv environment. I tried `SET PYTHONPATH=...` under a virtualenv command prompt, but that sets the variable for the whole environment. How do I achieve that?
If you're using `virtualenv`, you should probably also be using [virtualenvwrapper](http://virtualenvwrapper.readthedocs.org/), in which case you can use the [add2virtualenv](http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html#add2virtualenv) command to add paths to the Python path for the current virtu...
How to programmatically change volume in Ubuntu
10,739,390
21
2012-05-24T14:22:43Z
10,739,764
34
2012-05-24T14:42:31Z
[ "python", "audio", "ubuntu", "gnome", "alsa" ]
How do you programmatically change volume in Gnome on Ubuntu, either from the command line or an API (Python preferrably)? The only answers I found to similar questions use `amixer`, which seems to have no effect on Ubuntu 12.04. Running: ``` amixer set Headphone 10- ``` shows: ``` Simple mixer control 'Headphone',...
Ubuntu uses pulseaudio as sounderver. It can be controlled from the command line using the `pactl` and `pacmd` utilities, for example: ``` pactl set-sink-volume 0 20% ``` would set the volume of the sink #0 to 20%. see: `man pactl` and `pacmd help` --- edit: to avoid `-xx` being interpreted as command line option...
How to programmatically change volume in Ubuntu
10,739,390
21
2012-05-24T14:22:43Z
10,745,169
14
2012-05-24T20:57:44Z
[ "python", "audio", "ubuntu", "gnome", "alsa" ]
How do you programmatically change volume in Gnome on Ubuntu, either from the command line or an API (Python preferrably)? The only answers I found to similar questions use `amixer`, which seems to have no effect on Ubuntu 12.04. Running: ``` amixer set Headphone 10- ``` shows: ``` Simple mixer control 'Headphone',...
I do it using ALSA mixer. You probably need to download python-alsaaudio ``` sudo apt-get install python-alsaaudio ``` Then to control volume, ``` import alsaaudio m = alsaaudio.Mixer() # defined alsaaudio.Mixer to change volume m.setvolume(50) # set volume vol = m.getvolume() # get volume float value ``` Read <h...
How should I format a long url in a python comment and still be PEP8 compliant
10,739,843
37
2012-05-24T14:47:47Z
10,739,989
40
2012-05-24T14:55:13Z
[ "python", "pep8" ]
In a block comment, I want to reference a URL that is over 80 characters long. What is the preferred convention for displaying this URL? I know bit.ly is an option, but the URL itself is descriptive. Shortening it and then having a nested comment describing the shortened URL seems like a crappy solution.
From [PEP8](http://www.python.org/dev/peps/pep-0008/#a-foolish-consistency-is-the-hobgoblin-of-little-minds) > But most importantly: know when to be inconsistent -- sometimes the style guide just doesn't apply. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don't hesitate...