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
pip-installed uWSGI ./python_plugin.so error
15,936,413
20
2013-04-10T21:06:37Z
15,941,424
33
2013-04-11T05:36:55Z
[ "python", "uwsgi" ]
I've installed uWSGI using pip and start it up with an XML to load my application. The XML config contains `<plugin>python</plugin>`. On my new server it leads to an error: ``` open("./python_plugin.so"): No such file or directory [core/utils.c line 3321] !!! UNABLE to load uWSGI plugin: ./python_plugin.so: cannot ope...
Distros should package uWSGI in a modular way, with each feature as a plugin. But when you install using language specific ways (pip, gem...) the relevant language is embedded, so you do not need to load the plugin
pip-installed uWSGI ./python_plugin.so error
15,936,413
20
2013-04-10T21:06:37Z
16,619,526
33
2013-05-18T00:20:50Z
[ "python", "uwsgi" ]
I've installed uWSGI using pip and start it up with an XML to load my application. The XML config contains `<plugin>python</plugin>`. On my new server it leads to an error: ``` open("./python_plugin.so"): No such file or directory [core/utils.c line 3321] !!! UNABLE to load uWSGI plugin: ./python_plugin.so: cannot ope...
For anyone that is having trouble with this, basically you need to remove lines that state your plugin from your configuration files if you change from a distro package to a pypi or gem install. I was previously using the Ubuntu/Debian package for uwsgi, but it was old so I upgraded to use pip instead. So, in my confi...
Converting empty strings to 0 using Numpy
15,936,732
2
2013-04-10T21:26:46Z
15,936,789
12
2013-04-10T21:30:37Z
[ "python", "numpy" ]
I have a numpy array where each element looks something like this: ``` ['3' '1' '35' '0' '0' '8.05' '2'] ['3' '1' '' '0' '0' '8.4583' '0'] ['1' '1' '54' '0' '0' '51.8625' '2'] ``` I would like to replace all empty strings like the ones in the second row above, with some default value like 0. How can I do this with nu...
If your array is t: ``` t[t=='']='0' ``` and then convert it. **Explanation:** `t==''` creates a boolean array with the same shape as `t` that has a True value where the corresponding `t` value is an empty space. This boolean array is then used to assign `'0'` only to the appropriate indices in the original `t`.
I'm having problems with wtforms selectfields when i use a POST with Flask
15,936,764
12
2013-04-10T21:28:19Z
15,939,584
22
2013-04-11T02:10:59Z
[ "python", "flask", "wtforms", "flask-wtforms" ]
I'm pretty new to wtforms and flask and was messing around with selectfields and got an error. The form itself works just fine without the selectfield but with it I get the following error: **Error:** ``` ....fields.py", line 386, in pre_validate for v, _ in self.choices: TypeError: 'NoneType' object is not itera...
You need to set your choices *before* you call `validate_on_submit` as `form.validate` will attempt to validate the provided value (if any) against the list of choices (which is `None` before you set `choices`): ``` form = PostForm() form.hometest.choices = [(h.key.id(), h.homename) for h in Home.query()] if form.val...
How can I permanently accept OSX firewall allow/deny confirmation when running python?
15,936,801
7
2013-04-10T21:31:16Z
19,776,456
11
2013-11-04T20:23:59Z
[ "python", "osx", "osx-mountain-lion", "firewall" ]
## Overview I am using the tornado web server within python on OSX Mt Lion. Every time I start the tornado server I get a popup and have to allow/deny incoming access to the application. I have listed the python binary in System Preferences -> Security & Privacy -> Firewall as "allowing incoming connections" ... but ...
(based on courteous' answer - thanks courteous) ``` codesign -f -s - /path/to/Python.app ``` worked for me (Lion asked only once afterwards, for the last time). `-s -` means Ad-hoc signing - no need for certificate at all.
Check if each element in a numpy array is in another array
15,939,748
14
2013-04-11T02:34:29Z
15,940,459
16
2013-04-11T03:51:42Z
[ "python", "numpy" ]
This problem seems easy but I cannot quite get a nice-looking solution. I have two numpy arrays (A and B), and I want to get the indices of A where the elements of A are in B and also get the indices of A where the elements are not in B. So, if ``` A = np.array([1,2,3,4,5,6,7]) B = np.array([2,4,6]) ``` Currently I ...
`searchsorted` may give you wrong answer if not every element of B is in A. You can use [`numpy.in1d`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html): ``` A = np.array([1,2,3,4,5,6,7]) B = np.array([2,4,6,8]) mask = np.in1d(A, B) print np.where(mask)[0] print np.where(~mask)[0] ``` output is: `...
How to get UTC time in Python?
15,940,280
27
2013-04-11T03:33:34Z
15,940,301
50
2013-04-11T03:35:52Z
[ "python", "datetime" ]
I've search a bunch on StackExchange for a solution but nothing does quite what I need. In JavaScript, I'm using the following to calculate UTC time since Jan 1st 1970: ``` function UtcNow() { var now = new Date(); var utc = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(),...
Try this code that uses [datetime.utcnow()](http://docs.python.org/2/library/datetime.html#datetime.datetime.utcnow): ``` from datetime import datetime datetime.utcnow() ``` For your purposes when you need to calculate an amount of time spent between two dates all that you need is to substract end and start dates. Th...
How to get UTC time in Python?
15,940,280
27
2013-04-11T03:33:34Z
15,940,303
14
2013-04-11T03:36:09Z
[ "python", "datetime" ]
I've search a bunch on StackExchange for a solution but nothing does quite what I need. In JavaScript, I'm using the following to calculate UTC time since Jan 1st 1970: ``` function UtcNow() { var now = new Date(); var utc = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(),...
In the form closest to your original: ``` import datetime def UtcNow(): now = datetime.datetime.utcnow() return now ``` If you need to know the number of seconds from 1970-01-01 rather than a native Python `datetime`, use this instead: ``` return (now - datetime.datetime(1970, 1, 1)).total_seconds() ``` Py...
how to get row count of pandas dataframe?
15,943,769
147
2013-04-11T08:14:08Z
15,943,975
197
2013-04-11T08:24:29Z
[ "python", "pandas", "dataframe" ]
I'm trying to get the number of rows of dataframe df with Pandas, and here is my code Method 1: ``` total_rows = df.count print total_rows +1 ``` Method 2: ``` total_rows = df['First_columnn_label'].count print total_rows +1 ``` both the code snippets give me this error: > TypeError: unsupported operand type(s) f...
You can use the `.shape` property or just `len(DataFrame.index)` as there are notable performance differences: ``` In [1]: import numpy as np In [2]: import pandas as pd In [3]: df = pd.DataFrame(np.arange(9).reshape(3,3)) In [4]: df Out[4]: 0 1 2 0 0 1 2 1 3 4 5 2 6 7 8 In [5]: df.shape Out[5]: (3,...
how to get row count of pandas dataframe?
15,943,769
147
2013-04-11T08:14:08Z
18,317,067
30
2013-08-19T15:02:45Z
[ "python", "pandas", "dataframe" ]
I'm trying to get the number of rows of dataframe df with Pandas, and here is my code Method 1: ``` total_rows = df.count print total_rows +1 ``` Method 2: ``` total_rows = df['First_columnn_label'].count print total_rows +1 ``` both the code snippets give me this error: > TypeError: unsupported operand type(s) f...
Use `len(df)`. This works as of pandas 0.11 or maybe even earlier. `__len__()` is currently (0.12) documented with `Returns length of index`. Timing info, set up the same way as in root's answer: ``` In [7]: timeit len(df.index) 1000000 loops, best of 3: 248 ns per loop In [8]: timeit len(df) 1000000 loops, best of ...
how to get row count of pandas dataframe?
15,943,769
147
2013-04-11T08:14:08Z
32,103,678
10
2015-08-19T19:07:17Z
[ "python", "pandas", "dataframe" ]
I'm trying to get the number of rows of dataframe df with Pandas, and here is my code Method 1: ``` total_rows = df.count print total_rows +1 ``` Method 2: ``` total_rows = df['First_columnn_label'].count print total_rows +1 ``` both the code snippets give me this error: > TypeError: unsupported operand type(s) f...
Apart from above answers use can use `df.axes` to get the tuple with row and column indexes and then use `len()` function: ``` total_rows=len(df.axes[0]) total_cols=len(df.axes[1]) ```
how to get row count of pandas dataframe?
15,943,769
147
2013-04-11T08:14:08Z
35,523,946
17
2016-02-20T13:30:05Z
[ "python", "pandas", "dataframe" ]
I'm trying to get the number of rows of dataframe df with Pandas, and here is my code Method 1: ``` total_rows = df.count print total_rows +1 ``` Method 2: ``` total_rows = df['First_columnn_label'].count print total_rows +1 ``` both the code snippets give me this error: > TypeError: unsupported operand type(s) f...
suppose df is your dataframe then: ``` Count_Row=df.shape[0] #gives number of row count Count_Col=df.shape[1] #gives number of col count ```
python threading blocks
15,946,075
3
2013-04-11T10:09:09Z
15,946,152
8
2013-04-11T10:12:52Z
[ "python", "python-multithreading" ]
I am trying to write a program which creates new threads in a loop, and doesn't wait for them to finish. As i understand it if i use .start() on the thread, my main loop should just continue, and the other thread will go off and do its work at the same time However once my new thread starts, the loop blocks until the ...
This calls the function and passes its *result* as `target`: ``` threading.Thread(target=DoWorkItem(), args=()) ``` Lose the parentheses to pass the function object itself: ``` threading.Thread(target=DoWorkItem, args=()) ```
Unix filename wildcards in Python?
15,949,694
5
2013-04-11T13:10:59Z
15,949,740
8
2013-04-11T13:13:14Z
[ "python", "unix", "pattern-matching", "wildcard" ]
How do Unix filename **wildcards** work from **Python**? A given directory contains only subdirectories, in each of which there is (among others) one file whose name ends with a known string, say **`_ext`**. The first part of the filename always varies, so I need to get to the file by using this pattern. I wanted to ...
Shell wildcard patterns don't work in Python. Use the [`fnmatch`](http://docs.python.org/2/library/fnmatch.html) or [`glob`](http://docs.python.org/2/library/fnmatch.html) modules to interpret the wildcards instead. `fnmatch` interprets wildcards and lets you match strings against them, `glob` uses `fnmatch` internally...
Use string variable **kwargs as named argument
15,949,816
5
2013-04-11T13:16:45Z
15,950,023
15
2013-04-11T13:26:22Z
[ "python", "command-line", "python-2.7", "kwargs" ]
I am trying to figure out a way to loop through a json config file and use a key name as the argument name to a method that uses \*\*kwargs. I have created a json config file and used key names as methods. I just append "set\_" to the key name to call the correct method. I convert the json to a dictionary to loop throu...
If I understand correctly what you're asking, you can just use the `**` syntax on the calling side to pass a dict that is converted into kwargs. ``` callable_method(user=user, **{option_name: user_defaults[option_name]}) ```
How to compute cluster assignments from linkage/distance matrices in scipy in Python?
15,951,711
14
2013-04-11T14:41:10Z
16,023,123
12
2013-04-15T19:18:18Z
[ "python", "numpy", "scipy", "cluster-analysis" ]
if you have this hierarchical clustering call in scipy in Python: ``` from scipy.cluster.hierarchy import linkage # dist_matrix is long form distance matrix linkage_matrix = linkage(squareform(dist_matrix), linkage_method) ``` then what's an efficient way to go from this to cluster assignments for individual points? ...
If I understand you right, that is what [fcluster](http://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.fcluster.html#scipy.cluster.hierarchy.fcluster) does: > `scipy.cluster.hierarchy.fcluster(Z, t, criterion='inconsistent', depth=2, R=None, monocrit=None)` > > Forms flat clusters from the hier...
pydot and graphviz error: Couldn't import dot_parser, loading of dot files will not be possible
15,951,748
98
2013-04-11T14:42:43Z
17,902,926
212
2013-07-27T22:07:48Z
[ "python", "python-2.7", "graphviz", "pydot" ]
When I run a very simple code with pydot ``` import pydot graph = pydot.Dot(graph_type='graph') for i in range(3): edge = pydot.Edge("king", "lord%d" % i) graph.add_edge(edge) vassal_num = 0 for i in range(3): for j in range(2): edge = pydot.Edge("lord%d" % i, "vassal%d" % vassal_num) graph.add_edge(e...
Answer for `pydot >= 1.1`: The incompatibility of (upstream) `pydot` has been fixed by [6dff94b3f1](https://github.com/erocarrera/pydot/commit/6dff94b3f1dbcf68e5a83ce17a36b098c06d7c6b), and thus `pydot >= 1.1` will be [compatible with `pyparsing >= 1.5.7`](https://github.com/erocarrera/pydot/commit/e26af21426fcf15955f...
pydot and graphviz error: Couldn't import dot_parser, loading of dot files will not be possible
15,951,748
98
2013-04-11T14:42:43Z
18,547,813
21
2013-08-31T11:49:44Z
[ "python", "python-2.7", "graphviz", "pydot" ]
When I run a very simple code with pydot ``` import pydot graph = pydot.Dot(graph_type='graph') for i in range(3): edge = pydot.Edge("king", "lord%d" % i) graph.add_edge(edge) vassal_num = 0 for i in range(3): for j in range(2): edge = pydot.Edge("lord%d" % i, "vassal%d" % vassal_num) graph.add_edge(e...
pydot used a private module variable (\_noncomma) from pyparsing. The below diff fixes it to use for pyparsing 2.0.1: ``` diff --git a/dot_parser.py b/dot_parser.py index dedd61a..138d152 100644 --- a/dot_parser.py +++ b/dot_parser.py @@ -25,8 +25,9 @@ from pyparsing import __version__ as pyparsing_version from pypar...
pydot and graphviz error: Couldn't import dot_parser, loading of dot files will not be possible
15,951,748
98
2013-04-11T14:42:43Z
21,489,354
55
2014-01-31T20:22:33Z
[ "python", "python-2.7", "graphviz", "pydot" ]
When I run a very simple code with pydot ``` import pydot graph = pydot.Dot(graph_type='graph') for i in range(3): edge = pydot.Edge("king", "lord%d" % i) graph.add_edge(edge) vassal_num = 0 for i in range(3): for j in range(2): edge = pydot.Edge("lord%d" % i, "vassal%d" % vassal_num) graph.add_edge(e...
There is a new package in the pip repo called pydot2 that functions correctly with pyparsing2. I couldn't downgrade my packages because matplotlib depends on the newer pyparsing package. Note: python2.7 from macports
How to change default directory for IDLE in windows?
15,953,303
6
2013-04-11T15:49:02Z
15,954,961
8
2013-04-11T17:17:43Z
[ "python", "python-idle" ]
The installation directory is "d:\python2.7", and every time I open IDLE and click on menu File and Open item, the default directory is also "d:\python2.7". So I have to change the directory to where I want. Is there any way I can change it? Using configuration file or changing environment variable? I tried to add PY...
If you're running IDLE from a Windows shortcut, you can just right-click on the shortcut, choose "Properties", and change the field "Start in" to any directory you like.
How to create multiple (but individual) empty lists in Python?
15,953,800
2
2013-04-11T16:13:17Z
15,953,860
8
2013-04-11T16:16:21Z
[ "python", "list" ]
I wrote a script that at one point generates a bunch of empty lists applying a code with the structure: ``` A,B,C,D=[],[],[],[] ``` which produces the output: ``` A=[] B=[] C=[] D=[] ``` The way it is right now, I have to manually modify the letters each time I use a different dataset as an input. I want to be able...
You are overcomplicating things. Just use a list or dictionary: ``` fields = {key: [] for key in 'ABCD'} ``` then refer to `fields['A']`, etc. as needed, or loop over the structure to process each in turn.
Python- how do I use re to match a whole string
15,954,650
3
2013-04-11T17:00:38Z
15,954,691
18
2013-04-11T17:02:42Z
[ "python", "string", "match" ]
I am validating the text input by a user so that it will only accept letters but not numbers. so far my code works fine when I type in a number (e.g. 56), it warns me that I should only type letters and when I type in letters it doesn't return anything (like it should do). My problem is that it accepts it when I start ...
Anchor it to the start and end, and match *one or more* characters: ``` if re.match("^[a-zA-Z]+$", aString): ``` Here `^` anchors to the start of the string, `$` to the end, and `+` makes sure you match 1 or more characters. You'd be better off just using [`str.isalpha()`](http://docs.python.org/2/library/stdtypes.h...
Setting selenium to use custom profile, but it keeps opening with default
15,954,682
18
2013-04-11T17:02:17Z
15,954,999
14
2013-04-11T17:20:04Z
[ "python", "osx", "firefox", "selenium-webdriver" ]
I am trying to use python and selenium to automate some tasks in firefox. When I download a file, that pop up comes up asking if you want to open or save, and a check box for do this every time with this kind of file. I have found that check box does not work unless you install the add on Web Page Fixer. I have that in...
> Error: fp.set\_preference("browser.download.dir",getcwd()) NameError: > name 'getcwd' is not defined `getcwd()` is not defined. So I assume you want the `getcwd` from the `os` module: * <http://docs.python.org/library/os.html> add: `import os` , and then invoke with `os.getcwd()`. or you could just add the import...
Setting selenium to use custom profile, but it keeps opening with default
15,954,682
18
2013-04-11T17:02:17Z
23,330,140
9
2014-04-27T23:06:21Z
[ "python", "osx", "firefox", "selenium-webdriver" ]
I am trying to use python and selenium to automate some tasks in firefox. When I download a file, that pop up comes up asking if you want to open or save, and a check box for do this every time with this kind of file. I have found that check box does not work unless you install the add on Web Page Fixer. I have that in...
I did the following: ![Open Profile Directory](http://i.stack.imgur.com/5CQ8U.png) Or: Linux: `ls -d /home/$USER/.mozilla/firefox/*.default/` to see user profile directories Mac: `ls -d ~/Library/Application\ Support/Firefox/Profiles/*` Output: ``` /home/jmunsch/.mozilla/firefox/xfoyzfsb.default/ /home/jmunsch/.m...
How do I test manual DB transaction code in Django?
15,955,089
6
2013-04-11T17:25:46Z
15,955,246
10
2013-04-11T17:34:52Z
[ "python", "django", "unit-testing", "transactions" ]
I'm transferring data from a legacy system into Django. In order to ensure the current database's integrity, I'm committing everything manually. However, when writing unit tests, the transactions won't rollback properly. Since `TestCase` is probably using transactions, is there any way to properly test code in Django ...
I believe you are looking for [`TransactionTestCase`](https://docs.djangoproject.com/en/dev/topics/testing/tools/#django.test.TransactionTestCase) which handles setup and teardown differently then the normal `TestCase`.
OpenERP ver 7 - explaination for Security.xml
15,955,389
2
2013-04-11T17:43:30Z
15,963,506
10
2013-04-12T05:07:43Z
[ "python", "xml", "openerp" ]
``` <?xml version="1.0" ?> <openerp> <data> <record model="ir.module.category" id="module_lunch_category"> <field name="name">Lunch</field> <field name="description">Helps you handle your lunch needs, if you are a manager you will be able to create new products, cashmoves and to conf...
``` 1. <record model="ir.module.category" id="module_lunch_category"> ``` This used to create category by your application name like purchase,warehouse, or your own module. For like particular group belong to this module, it is just a name of your moudle Like your module name bpl then you create a **BPL** in ir.module...
How does this lambda/yield/generator comprehension work?
15,955,948
44
2013-04-11T18:15:49Z
15,956,157
39
2013-04-11T18:28:15Z
[ "python", "ssh", "lambda", "functional-programming", "generator" ]
I was looking through my codebase today and found this: ``` def optionsToArgs(options, separator='='): kvs = [ ( "%(option)s%(separator)s%(value)s" % {'option' : str(k), 'separator' : separator, 'value' : str(v)} ) for k, v in options.items() ] return list( ...
Since Python 2.5, `yield <value>` is an expression, not a statement. See [PEP 342](http://www.python.org/dev/peps/pep-0342/). The code is hideously and unnecessarily ugly, but it's legal. Its central trick is using `f((yield x))` inside the generator expression. Here's a simpler example of how this works: ``` >>> def...
How does this lambda/yield/generator comprehension work?
15,955,948
44
2013-04-11T18:15:49Z
15,956,184
16
2013-04-11T18:30:10Z
[ "python", "ssh", "lambda", "functional-programming", "generator" ]
I was looking through my codebase today and found this: ``` def optionsToArgs(options, separator='='): kvs = [ ( "%(option)s%(separator)s%(value)s" % {'option' : str(k), 'separator' : separator, 'value' : str(v)} ) for k, v in options.items() ] return list( ...
Oh god. Basically, it boils down to this,: ``` def f(_): # I'm the lambda _: t return '-o' def thegenerator(): # I'm (f((yield x)) for x in l) for x in kvs: yield f((yield x)) ``` So when iterated over, thegenerator yields `x` (a member of `kvs`) and then the return value of `f`, which...
Averaging over every n elements of a numpy array
15,956,309
10
2013-04-11T18:37:28Z
15,956,341
15
2013-04-11T18:39:30Z
[ "python", "numpy", "average" ]
I have a numpy array. I want to create a new array which is the average over every third element. So the new array will be a third of the size as the original. As an example: ``` np.array([1,2,3,1,2,3,1,2,3]) ``` should return the array: ``` np.array([2,2,2]) ``` Can anyone suggest an efficient way of doing this...
If your array `arr` has a length divisible by 3: ``` np.mean(arr.reshape(-1, 3), axis=1) ``` Reshaping to a higher dimensional array and then performing some form of reduce operation on one of the additional dimensions is a staple of numpy programming.
Referencing self while overloading class methods
15,956,572
2
2013-04-11T18:52:27Z
15,956,601
11
2013-04-11T18:53:56Z
[ "python", "default", "self" ]
Forgive me if 'overloading' is not the correct term here... I am trying to do something like this: ``` class Length: def __init__(self, length = 0): self._length = length def twice(self, length = self._length): return length*2 ``` As you can see, I'm trying to reference `self._length` in th...
You can't use instance attributes as default arguments of methods. The methods, along with their default argument values, are defined when the class is defined, but the instance attributes don't exist until later, when you instantiate the class. You have to do: ``` def twice(self, length=None): if length is None:...
How to install django 1.4
15,957,766
6
2013-04-11T19:59:03Z
15,957,823
24
2013-04-11T20:02:09Z
[ "python", "django" ]
When trying to download django through: ``` sudo pip uninstall django ``` However, this downloads the new version of django 1.5. How would I force download version 1.4 through pip? Here is what I get when trying to install: ``` imac9:site-packages pdadmin$ sudo pip install django==1.4.1 Downloading/unpacking django=...
This can be done by using this command ``` sudo pip install django==1.4 #or any desired version. ``` should work.
Getting Errno 9: Bad file descriptor in python socket
15,958,026
8
2013-04-11T20:13:23Z
15,958,099
19
2013-04-11T20:18:06Z
[ "python", "sockets" ]
My code is this: ``` while 1: # Determine whether the server is up or down try: s.connect((mcip, port)) s.send(magic) data = s.recv(1024) s.close() print data except Exception, e: print e sleep(60) ``` It works fine on the first run, but gives me Errno 9...
You're calling `connect` on the same socket you closed. You can't do that. As for [the docs](http://docs.python.org/2/library/socket.html#socket.socket.close) for `close` say: > All future operations on the socket object will fail. Just move the `s = socket.socket()` (or whatever you have) into the loop. (Or, if you...
Extracting Data with Python Regular Expressions
15,958,394
3
2013-04-11T20:36:17Z
15,958,463
7
2013-04-11T20:40:27Z
[ "python", "regex", "parsing" ]
I am having some trouble wrapping my head around Python regular expressions to come up with a regular expression to extract specific values. The page I am trying to parse has a number of productIds which appear in the following format ``` \"productId\":\"111111\" ``` I need to extract all the values, `111111` in thi...
something like this: ``` In [13]: s=r'\"productId\":\"111111\"' In [14]: print s \"productId\":\"111111\" In [15]: import re In [16]: re.findall(r'\d+', s) Out[16]: ['111111'] ```
Extracting Data with Python Regular Expressions
15,958,394
3
2013-04-11T20:36:17Z
15,958,685
8
2013-04-11T20:54:09Z
[ "python", "regex", "parsing" ]
I am having some trouble wrapping my head around Python regular expressions to come up with a regular expression to extract specific values. The page I am trying to parse has a number of productIds which appear in the following format ``` \"productId\":\"111111\" ``` I need to extract all the values, `111111` in thi...
``` t = "\"productId\":\"111111\"" m = re.match("\W*productId[^:]*:\D*(\d+)", t) if m: print m.group(1) ``` meaning match non-word characters (`\W*`), then `productId` followed by non-column characters (`[^:]*`) and a `:`. Then match non-digits (`\D*`) and match and capture following digits (`(\d+)`). **Output** ...
Python - Visibility of global variables in imported modules
15,959,534
33
2013-04-11T21:53:11Z
15,959,638
81
2013-04-11T22:00:05Z
[ "python", "namespaces", "mysql-python", "python-2.6", "python-import" ]
I've run into a bit of a wall importing modules in a Python script. I'll do my best to describe the error, why I run into it, and why I'm tying this particular approach to solve my problem (which I will describe in a second): Let's suppose I have a module in which I've defined some utility functions/classes, which ref...
Globals in Python are global *to a module*, not across all modules. (Many people are confused by this, because in, say, C, a global is the same across all implementation files unless you explicitly make it `static`.) There are different ways to solve this, depending on your actual use case. --- Before even going dow...
How to pick a key with the highest value
15,961,768
2
2013-04-12T01:45:47Z
15,961,791
8
2013-04-12T01:48:58Z
[ "python" ]
heres an example code of what I have ``` my_dict = {'a':2, 'b':5, 'c':3, 'd':8, 'e':3} ``` How could i make it print the key that has the highest value. For example in the above code it would print: ``` d ``` thats all i would want to be printed, just the key that had the highest value. help would be appreciated th...
Use a key with max ``` max(my_dict, key=my_dict.get) ```
How do I plot a spectrogram the same way that pylab's specgram() does?
15,961,979
8
2013-04-12T02:12:49Z
15,962,017
14
2013-04-12T02:17:27Z
[ "python", "audio", "matplotlib", "spectrogram" ]
In Pylab, the `specgram()` function creates a spectrogram for a given list of amplitudes and automatically creates a window for the spectrogram. I would like to generate the spectrogram (instantaneous power is given by `Pxx`), modify it by running an edge detector on it, and then plot the result. ``` (Pxx, freqs, bin...
Use `pcolor` or `pcolormesh`. `pcolormesh` is much faster, but is limited to rectilinear grids, where as pcolor can handle arbitrary shaped cells. `specgram` uses `pcolormesh`, if I recall correctly. (It uses `imshow`.) As a quick example: ``` import numpy as np import matplotlib.pyplot as plt z = np.random.random((...
Is it possible to salt and or hash HOTP/TOTP secret on the server?
15,962,195
12
2013-04-12T02:39:47Z
16,020,498
7
2013-04-15T16:45:16Z
[ "python", "authentication", "encryption", "google-authenticator" ]
I am building a two-factor authentication system based on the TOTP/HOTP. In order to verify the otp both server and the otp device must know the shared secret. Since HOTP secret is quite similar to the user's password, I assumed that similar best practices should apply. Specifically it is highly recommended to never s...
> Is there a way to use one-way encryption of the OTP shared secret...? Not really. You could use a reversible encryption mechanism, but there's probably not much point. You could only hash an [HMAC](http://en.wikipedia.org/wiki/Hash-based_message_authentication_code) key on the server if the client authenticated by ...
Function name convention for "convert foo to bar"
15,962,550
6
2013-04-12T03:29:13Z
15,962,691
15
2013-04-12T03:45:16Z
[ "javascript", "python", "ruby", "clojure", "lisp" ]
I have a very common pattern of "given a `Foo`, return a `Bar`," for example, given a `user_id`, return a `User`. Is there a conventional naming pattern for these sorts of functions? Following [Joel on Software](http://www.joelonsoftware.com/articles/Wrong.html), I've personally used a lot of `bar_from_foo()`, but I r...
I would take advantage of Clojure's naming flexibility and call it: ``` (defn foo->bar [] ...) ``` To me that makes the intent quite clear and it's pretty short.
Set a value in a dict only if the value is not already set
15,965,146
5
2013-04-12T07:06:15Z
15,965,302
7
2013-04-12T07:15:59Z
[ "python" ]
What is the most *pythonic* way to set a value in a `dict` if the value is not already set? At the moment my code uses if statements: ``` if "timeout" not in connection_settings: connection_settings["timeout"] = compute_default_timeout(connection_settings) ``` `dict.get(key,default)` is appropriate for code cons...
[`dict.setdefault`](http://docs.python.org/2/library/stdtypes.html#dict.setdefault) will precisely "Set a value in a dict only if the value is not already set", which is your question. However, you'd still need to compute the value to pass it as the parameter, which is not what you want.
Python Interpreter Mode - What are some ways to explore Python's modules and its usage
15,965,260
3
2013-04-12T07:13:31Z
15,965,772
7
2013-04-12T07:44:43Z
[ "python", "interpreter", "code-documentation" ]
While inside the Python Interpreter: What are some ways to learn about the packages I have? ``` >>> man sys File "<stdin>", line 1 man sys ^ ``` SyntaxError: invalid syntax ``` >>> sys --help Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: bad operand type for unary -: ...
You can look at `help("modules")`, it displays the list of available modules. To explore a particular module/class/function use `dir` and `__doc__`: ``` >>> import sys >>> sys.__doc__ "This module ..." >>> dir(sys) [..., 'setprofile', ...] >>> print(sys.setprofile.__doc__) setprofile(function) Set the profiling fun...
Posting html form values to python script
15,965,646
4
2013-04-12T07:36:38Z
15,965,715
11
2013-04-12T07:42:13Z
[ "php", "python", "html" ]
I have created html form with text box and button enter ur search keyword My requirement is to pass the text box value in to my test.py code, is there any way to do it. Please suggest me how do it.
in the form action `form action=""`, put the location of your cgi script and the value of the textbox will be passed to the cgi script. eg. ``` <form name="search" action="/cgi-bin/test.py" method="get"> Search: <input type="text" name="searchbox"> <input type="submit" value="Submit"> </form> ``` in your test.py ```...
python one line save values of lists in dict to list
15,966,231
5
2013-04-12T08:11:39Z
15,966,267
9
2013-04-12T08:13:03Z
[ "python" ]
I would like to write for loop in one line: ``` d = {'a': [1, 2, 3], 'b': [5, 6, 7], 'c': [9, 0]} my_list = [] for k, v in d.items(): for x in v: my_list.append(x) ``` How can I do it?
``` >>> d = {'a': [1, 2, 3], 'b': [5, 6, 7], 'c': [9, 0]} >>> [y for x in d.values() for y in x] [1, 2, 3, 9, 0, 5, 6, 7] ``` This is a nested [list comprehension](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions). To show how this works, you can break it up into lines to see it's structure as...
How to show a window that was hidden using "withdraw" method?
15,967,690
3
2013-04-12T09:29:08Z
15,967,944
8
2013-04-12T09:40:47Z
[ "python", "python-2.7", "tkinter" ]
I would like to show a window after I called `withdraw`. The following is my current code: ``` from Tkinter import * def callback(): global root root.withdraw() win2 = Tk() root = Tk() Label(root,text='this is a window').pack() Button(root,text='withdraw',command=self.callback).pack() mainloop() ```...
Use the following commands when you want to show the window: ``` # root.update() # not required root.deiconify() ``` If you want to know more about it, see [here](http://www.blog.pythonlibrary.org/2012/07/26/tkinter-how-to-show-hide-a-window/).
shapefile and matplotlib: plot polygon collection of shapefile coordinates
15,968,762
6
2013-04-12T10:16:48Z
15,972,203
11
2013-04-12T13:06:07Z
[ "python", "matplotlib", "polygon", "geospatial", "shapefile" ]
I'm trying to plot filled polygons of countries on the world map with matplotlib in python. I've got a shapefile with country boundary coordinates of every country. Now, I want to convert these coordinates (for each country) into a polygon with matplotlib. Without using Basemap. Unfortunately, the parts are crossing o...
Ha! I found out, how.. I completely neglected, the sf.shapes[i].parts information! Then it comes down to: ``` # -- import -- import shapefile import matplotlib.pyplot as plt import matplotlib.patches as patches from matplotlib.patches import Polygon from matplotlib.collections import PatchCollection # -- input -- ...
Python 2.7: how to find the index of the first letter of each word in a string
15,969,513
2
2013-04-12T10:55:25Z
15,969,571
8
2013-04-12T10:57:36Z
[ "python", "python-2.7" ]
I'm looking for a way, in Python, to detect the index of the first character of each word in a string: ``` string = "DAY MONTH YEAR THIS HAS RANDOM SPACES" ``` I would like to find the position of each 'word', so this output would be: ``` [0, 4, 15, 23...] ``` Does anyone have any idea how I could achie...
``` >>> import re >>> string = "DAY MONTH YEAR THIS HAS RANDOM SPACES" >>> [match.start() for match in re.finditer(r'\b\w', string)] [0, 4, 15, 23, 30, 34, 43] ```
How do you rotate the numbers in an numpy array of shape (n,) or (n,1)?
15,969,708
2
2013-04-12T11:03:28Z
15,970,188
8
2013-04-12T11:28:46Z
[ "python", "numpy" ]
Say I have a numpy array: ``` >>> a array([0,1,2,3,4]) ``` and I want to "rotate" it to get: ``` >>> b array([4,0,1,2,3]) ``` What is the best way? I have been converting to a deque and back (see below) but is there a better way? ``` b = deque(a) b.rotate(1) b = np.array(b) ```
Just use the [`numpy.roll`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.roll.html) function: ``` a = np.array([0,1,2,3,4]) b = np.roll(a,1) print(b) >>> [4 0 1 2 3] ``` See also [this question](http://stackoverflow.com/questions/15792465/how-to-do-circular-shift-in-numpy/15792525#15792525).
numpy - scalar multiplication of column vector times row vector
15,971,257
3
2013-04-12T12:20:25Z
15,971,423
7
2013-04-12T12:27:50Z
[ "python", "vector", "matrix", "numpy" ]
What is the best and most efficient way to solve the following in python numpy: given a weight vector: ``` weights = numpy.array([1, 5, 2]) ``` and a value vector: ``` values = numpy.array([1, 3, 10, 4, 2]) ``` as result I need a matrix, which contains on each row the `values` vector scalar multiplied with the val...
This operation is called the [outer product](http://en.wikipedia.org/wiki/Outer_product). It can be performed using [`numpy.outer()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.outer.html): ``` In [6]: numpy.outer(weights, values) Out[6]: array([[ 1, 3, 10, 4, 2], [ 5, 15, 50, 20, 10], ...
Running single test from unittest.TestCase via command line
15,971,735
70
2013-04-12T12:43:13Z
15,971,771
84
2013-04-12T12:44:32Z
[ "python", "unit-testing" ]
In our team, we define most test cases like this: One "framework" class ourtcfw.py: ``` import unittest class OurTcFw(unittest.TestCase): def setUp: # something # other stuff that we want to use everywhere ``` and a lot of test cases like testMyCase.py: ``` import localweather class MyCase(OurTcF...
This works as you suggest - you just have to specify the class name as well: ``` python testMyCase.py MyCase.testItIsHot ```
Running single test from unittest.TestCase via command line
15,971,735
70
2013-04-12T12:43:13Z
15,971,942
26
2013-04-12T12:53:32Z
[ "python", "unit-testing" ]
In our team, we define most test cases like this: One "framework" class ourtcfw.py: ``` import unittest class OurTcFw(unittest.TestCase): def setUp: # something # other stuff that we want to use everywhere ``` and a lot of test cases like testMyCase.py: ``` import localweather class MyCase(OurTcF...
It can work well as you guess ``` python testMyCase.py MyCase.testItIsHot ``` And there is another way to just test `testItIsHot`: ``` suite = unittest.TestSuite() suite.addTest(MyCase("testItIsHot")) runner = unittest.TextTestRunner() runner.run(suite) ```
Running single test from unittest.TestCase via command line
15,971,735
70
2013-04-12T12:43:13Z
26,531,790
16
2014-10-23T15:34:14Z
[ "python", "unit-testing" ]
In our team, we define most test cases like this: One "framework" class ourtcfw.py: ``` import unittest class OurTcFw(unittest.TestCase): def setUp: # something # other stuff that we want to use everywhere ``` and a lot of test cases like testMyCase.py: ``` import localweather class MyCase(OurTcF...
If you organize your test cases, that is, follow the same organization like the actual code and also use relative imports for modules in the same package You can also use the following command format: ``` python -m unittest mypkg.tests.test_module.TestClass.test_method # In your case, this would be: python -m unittes...
Why doesn't this function "take" after I iterrows over a pandas DataFrame?
15,972,264
3
2013-04-12T13:09:14Z
15,972,594
9
2013-04-12T13:24:57Z
[ "python", "pandas" ]
I have a DataFrame with timestamped temperature and wind speed values, and a function to convert those into a "wind chill." I'm using iterrows to run the function on each row, and hoping to get a DataFrame out with a nifty "Wind Chill" column. However, while it seems to work as it's going through, and has actually "wo...
You can use [`apply`](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.apply.html) to do this: ``` In [11]: df.apply(lambda row: windchill(row['Temperature'], row['Wind Speed']), axis=1) Out[11]: 2003-03-01 06:00:00-05:00 24.794589 2003-03-01 07:00:00-05:00 25.136527 2003-03-0...
How to document an exception using Sphinx
15,972,544
13
2013-04-12T13:22:50Z
15,973,424
14
2013-04-12T14:04:57Z
[ "python", "exception", "documentation", "python-sphinx" ]
I can't seem to figure out how to document exceptions using Sphinx. I've tried the following: ``` def some_funct(): """ :raises: ExceptionType: Some multi-line exception description. """ def some_funct(): """ :raises: ExceptionType, Some multi-line exception description. """ ...
You can use a backslash for line continuation: ``` def some_funct(): """ :raises ExceptionType: Some multi-line \ exception description. """ ``` **Update:** Indenting seems to work instead of escaping the newline: ``` def some_funct(): """ :raises ExceptionType: Some multi-line e...
Handling of duplicate indices in NumPy assignments
15,973,827
22
2013-04-12T14:21:45Z
16,026,109
10
2013-04-15T23:07:43Z
[ "python", "numpy" ]
I am setting the values of multiple elements in a 2D array, however my data sometimes contains multiple values for a given index. It seems that the "later" value is always assigned (see examples below) but is this behaviour guaranteed or is there a chance I will get inconsistent results? How do I know that I can inter...
In NumPy 1.9 and later this will in general not be well defined. The current implementation iterates over all (broadcasted) fancy indexes (and the assignment array) at the same time using separate iterators, and these iterators all use C-order. In other words, currently, yes you can. Since you maybe want to know it mo...
ipython install new modules
15,974,100
7
2013-04-12T14:33:17Z
18,055,780
20
2013-08-05T10:20:08Z
[ "python", "module", "install", "pip", "ipython" ]
I am used to the R functionality of installing packages and I am trying to do the same thing with ipython. Sometimes the following method works but then again sometimes it doesn't and I would like to finally find out why it only works half the time. Normally to install a module (like the `requests` module for example)...
actually there is a much much much more elegant solution. when pip is installed then within python you can do things like this as well: ``` import pip def install(package): pip.main(['install', package]) install('requests') ``` which is easier. once logged into a virtualenv you can just make sure that you have w...
How do I get the different parts of a Flask request's url?
15,974,730
33
2013-04-12T15:02:05Z
15,975,041
83
2013-04-12T15:16:00Z
[ "python", "url", "flask" ]
I want to detect if the request came from the `localhost:5000` or `foo.herokuapp.com` host and what path was requested. How do I get this information about a Flask request?
You can examine the url through several [`Request` fields](http://flask.pocoo.org/docs/api/#flask.Request.path): > A user requests the following URL: > > ``` > http://www.example.com/myapplication/page.html?x=y > ``` > > In this case the values of the above mentioned attributes would be the following: > > ``` > ...
Difference between import tkinter as tk and from tkinter import
15,974,787
4
2013-04-12T15:04:37Z
15,974,854
8
2013-04-12T15:07:43Z
[ "python", "import", "tkinter" ]
I know it is a stupid question but I am just starting to learn python and i don't have good knowledge of python. My question is what is the difference between ``` from Tkinter import * ``` and ``` import Tkinter as tk ``` ?Why can't i just write ``` import Tkinter ``` Could anyone spare a few mins to enlighten me...
`from Tkinter import *` imports every exposed object in Tkinter into your current namespace. `import Tkinter` imports the "namespace" Tkinter in your namespace and `import Tkinter as tk` does the same, but "renames" it locally to 'tk' to save you typing let's say we have a module foo, containing the classes A, B, and ...
can't import import datetime in script
15,975,517
2
2013-04-12T15:38:33Z
15,975,547
7
2013-04-12T15:40:32Z
[ "python", "datetime", "python-import" ]
I cannot import datetime from a python script, but I can from the terminal command line. ``` 1)import datetime 2)From datetime import datetime month = datetime.datetime.now().strftime("%B") print month ``` These lines of code work when entered one by one into the command line Any ideas? I'm running 2.7 on mac
You named your *script* `datetime.py`, located at `/Users/ripple/Dropbox/Python/datetime.py`. This is being imported instead of the standard library module, because the directory of the main script is the first place Python looks for imports. You cannot give your scripts the same name as a module you are trying to imp...
Difference between nonzero(a), where(a) and argwhere(a). When to use which?
15,976,697
18
2013-04-12T16:42:50Z
15,976,877
7
2013-04-12T16:54:11Z
[ "python", "numpy" ]
In Numpy, [`nonzero(a)`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.nonzero.html#numpy.nonzero), [`where(a)`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html) and [`argwhere(a)`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.argwhere.html), with `a` being a numpy array, a...
I can't comment on the usefulness of having a separate convenience function that transposes the result of another, but I can comment on `where` vs `nonzero`. In it's simplest use case, `where` is indeed the same as `nonzero`. ``` >>> np.where(np.array([[0,4],[4,0]])) (array([0, 1]), array([1, 0])) >>> np.nonzero(np.ar...
Difference between nonzero(a), where(a) and argwhere(a). When to use which?
15,976,697
18
2013-04-12T16:42:50Z
15,976,952
8
2013-04-12T16:58:38Z
[ "python", "numpy" ]
In Numpy, [`nonzero(a)`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.nonzero.html#numpy.nonzero), [`where(a)`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html) and [`argwhere(a)`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.argwhere.html), with `a` being a numpy array, a...
`nonzero` and `argwhere` both give you information about where in the array the elements are `True`. `where` works the same as `nonzero` in the form you have posted, but it has a second form: ``` np.where(mask,a,b) ``` which can be roughly thought of as a numpy "ufunc" version of the conditional expression: ``` a[i]...
Why does one of these code segment work while the other throws an overflow
15,976,893
8
2013-04-12T16:54:57Z
15,976,920
7
2013-04-12T16:56:31Z
[ "python", "exponential" ]
I am working with python and I am trying to find powers of really large numbers but something interesting which happens is that this throws a math overflow ``` math.pow(1000, 1000) ``` but this below seems to work although I do not know if the value returned is correct ``` 1000**1000 ``` Anybody aware why this happ...
[math.pow](http://docs.python.org/3/library/math.html#math.pow): > Unlike the built-in `**` operator, `math.pow()` converts both its arguments to type `float`. Use `**` or the built-in `pow()` function for computing exact integer powers.
Why does one of these code segment work while the other throws an overflow
15,976,893
8
2013-04-12T16:54:57Z
15,976,926
8
2013-04-12T16:56:45Z
[ "python", "exponential" ]
I am working with python and I am trying to find powers of really large numbers but something interesting which happens is that this throws a math overflow ``` math.pow(1000, 1000) ``` but this below seems to work although I do not know if the value returned is correct ``` 1000**1000 ``` Anybody aware why this happ...
Simple, the `math.pow()` method uses C float libraries, while the `**` power operator uses integer maths. The two methods have different limitations. Python `int` size is only limited by how much memory your OS will let Python have, float numbers are limited by your computer architecture, see [`sys.float_info.max`](ht...
Making my NumPy array shared across processes
15,976,937
9
2013-04-12T16:57:16Z
15,977,923
8
2013-04-12T17:59:16Z
[ "python", "numpy", "multiprocessing", "shared-memory" ]
I have read quite a few of the questions on SO about sharing arrays and it seems simple enough for simple arrays but I am stuck trying to get it working for the array I have. ``` import numpy as np data=np.zeros(250,dtype='float32, (250000,2)float32') ``` I have tried converting this to a shared array by trying to so...
Note that you can start out with an array of complex dtype: ``` In [4]: data = np.zeros(250,dtype='float32, (250000,2)float32') ``` and view it as an array of homogenous dtype: ``` In [5]: data2 = data.view('float32') ``` and later, convert it back to complex dtype: ``` In [7]: data3 = data2.view('float32, (250000...
Why don't methods have reference equality?
15,977,808
8
2013-04-12T17:51:52Z
15,977,850
17
2013-04-12T17:54:31Z
[ "python", "methods", "reference", "identity", "equality" ]
I had a bug where I was relying on methods being equal to each other when using `is`. It turns out that's not the case: ``` >>> class What(object): def meth(self): pass >>> What.meth is What.meth False >>> inst = What() >>> inst.meth is inst.meth False ``` Why is that the case? It works for regular funct...
Method objects are created *each time you access them*. Functions act as [descriptors](http://docs.python.org/2/reference/datamodel.html#invoking-descriptors), returning a method object when their `.__get__` method is called: ``` >>> What.__dict__['meth'] <function meth at 0x10a6f9c80> >>> What.__dict__['meth'].__get_...
How to find integer nth roots?
15,978,781
10
2013-04-12T18:52:40Z
15,978,862
11
2013-04-12T18:57:00Z
[ "python", "algorithm", "math" ]
I want to find the greatest integer less than or equal to the kth root of n. I tried ``` int(n**(1/k)) ``` But for n=125, k=3 this gives the wrong answer! I happen to know that 5 cubed is 125. ``` >>> int(125**(1/3)) 4 ``` What's a better algorithm? --- Background: In 2011, this slip-up cost me beating Google Cod...
How about: ``` def nth_root(val, n): ret = int(val**(1./n)) return ret + 1 if (ret + 1) ** n == val else ret print nth_root(124, 3) print nth_root(125, 3) print nth_root(126, 3) print nth_root(1, 100) ``` Here, both `val` and `n` are expected to be integer and positive. This makes the `return` expression rel...
How to find integer nth roots?
15,978,781
10
2013-04-12T18:52:40Z
15,979,957
7
2013-04-12T20:04:46Z
[ "python", "algorithm", "math" ]
I want to find the greatest integer less than or equal to the kth root of n. I tried ``` int(n**(1/k)) ``` But for n=125, k=3 this gives the wrong answer! I happen to know that 5 cubed is 125. ``` >>> int(125**(1/3)) 4 ``` What's a better algorithm? --- Background: In 2011, this slip-up cost me beating Google Cod...
One solution first brackets the answer between lo and hi by repeatedly multiplying hi by 2 until n is between lo and hi, then uses binary search to compute the exact answer: ``` def iroot(k, n): hi = 1 while pow(hi, k) < n: hi *= 2 lo = hi / 2 while hi - lo > 1: mid = (lo + hi) // 2 ...
Where is pyvenv script in Python 3 on Windows installed?
15,981,111
7
2013-04-12T21:26:38Z
15,981,112
8
2013-04-12T21:26:38Z
[ "python", "windows", "python-3.x", "virtualenv", "python-venv" ]
After reading the following statement from PEP [405](http://www.python.org/dev/peps/pep-0405/) > A pyvenv installed script is also provided to make this more > convenient: > > `pyvenv /path/to/new/virtual/environment` I tried to create a new virtual environment and failed miserably; ``` C:\>python --version Python 3...
It looks like `pyvenv` script is placed in `Tools\Scripts` subfolder inside Python installation folder (`sys.prefix`). It seems like copying it to `Scripts` subfolder is a good idea as it allows to simply type `pyvenv` from the command line (assuming `Scripts` folder is already on the `PATH`). As there's no `exe` wrapp...
Custom sqlite database for unit tests for code using peewee ORM
15,982,801
5
2013-04-13T00:22:47Z
16,001,333
8
2013-04-14T16:25:34Z
[ "python", "sqlite", "peewee" ]
I am trying to implement a many-to-many scenario using peewee python ORM and I'd like some unit tests. Peewee tutorial is great but it assumes that database is defined at module level then all models are using it. My situation is different: I don't have a source code file (a module from python's point of view) with tes...
I just pushed a commit today that makes this easier. The fix is in the form of a context manager which allows you to override the database of a model: ``` from unittest import TestCase from playhouse.test_utils import test_database from peewee import * from my_app.models import User, Tweet test_db = SqliteDatabase(...
Does Python have sync?
15,983,272
11
2013-04-13T01:41:39Z
15,983,348
12
2013-04-13T01:52:44Z
[ "python", "linux", "sync" ]
The [sync man page](http://linux.die.net/man/2/sync) says: > sync() causes all buffered modifications to file metadata and data to > be written to the underlying file systems. Does Python have a call to do this? P.S. Not [fsync](http://docs.python.org/2/library/os.html#os.fsync), I see that.
Python 3.3 has os.sync, see [the docs](http://docs.python.org/3/library/os.html#os.sync). The [source](http://hg.python.org/releasing/3.3.1/file/8e5812b35480/Modules/posixmodule.c#l3062) confirms it is the same thing. For Python 2 you might have to make an [external call](http://docs.python.org/3/library/subprocess.ht...
Does Python have sync?
15,983,272
11
2013-04-13T01:41:39Z
15,983,693
11
2013-04-13T02:52:08Z
[ "python", "linux", "sync" ]
The [sync man page](http://linux.die.net/man/2/sync) says: > sync() causes all buffered modifications to file metadata and data to > be written to the underlying file systems. Does Python have a call to do this? P.S. Not [fsync](http://docs.python.org/2/library/os.html#os.fsync), I see that.
As said, Python 3.3 has the call - on Python 2.x, since it is a simple system call, requiring no data to be passed back and forth, you can use ctypes to make the call: ``` >>> import ctypes >>> libc = ctypes.CDLL("libc.so.6") >>> libc.sync() 0 ```
Django get display name choices
15,984,130
7
2013-04-13T04:10:45Z
15,984,469
8
2013-04-13T05:06:58Z
[ "python", "django", "templates" ]
I'm trying to find a solution to my problem. models.py ``` class Article(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() description = models.TextField() def archive_quality(self): return self.archive_set.order_by('-quality').distinct().values_list('quality', flat=Tr...
**Option #1:** models.py ``` CHOICES_QUALITY = ( ('1', 'HD YB'), ('2', 'HD BJ'), ('3', 'HD POQD'), ('4', 'HD ANBC'), ) class Article(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() description = models.TextField() def archive_quality(self): q...
How to perform two-sample one-tailed t-test with numpy/scipy
15,984,221
11
2013-04-13T04:25:42Z
15,984,310
24
2013-04-13T04:39:07Z
[ "python", "numpy", "statistics", "scipy" ]
In `R`, it is possible to perform two-sample one-tailed t-test simply by using ``` > A = c(0.19826790, 1.36836629, 1.37950911, 1.46951540, 1.48197798, 0.07532846) > B = c(0.6383447, 0.5271385, 1.7721380, 1.7817880) > t.test(A, B, alternative="greater") Welch Two Sample t-test data: A and B t = -0.4189, df = 6....
From your mailing list link: > because the one-sided tests can be backed out from the two-sided > tests. (With symmetric distributions one-sided p-value is just half > of the two-sided pvalue) It goes on to say that scipy always gives the test statistic as signed. This means that given p and t values from a two-taile...
Apps won't run on GAE - 'unable to bind to localhost:0'
15,985,130
15
2013-04-13T06:50:38Z
16,007,507
15
2013-04-15T04:07:27Z
[ "python", "google-app-engine" ]
I recently upgraded Google App Engine to 1.7.7. and have not been able to run any apps locally since. This includes apps that worked before the update and apps I've created since. I haven't come across any other references to this specific problem 'Unable to bind to localhost:0,' so any insights into clearing this hurd...
your socket is already in use. kill it and it should be resolved.`fuser -k 8080/tcp` for example the above code kills and frees the socket at 8080
Apps won't run on GAE - 'unable to bind to localhost:0'
15,985,130
15
2013-04-13T06:50:38Z
28,157,972
23
2015-01-26T20:13:51Z
[ "python", "google-app-engine" ]
I recently upgraded Google App Engine to 1.7.7. and have not been able to run any apps locally since. This includes apps that worked before the update and apps I've created since. I haven't come across any other references to this specific problem 'Unable to bind to localhost:0,' so any insights into clearing this hurd...
For people who got `Unknown key` when running `fuser -k 8080/tcp`, here is a solution which worked for me: ``` lsof -P | grep ':8080' | awk '{print $2}' | xargs kill -9 ```
How do I get current URL in Selenium Webdriver 2 Python?
15,985,339
52
2013-04-13T07:20:01Z
15,986,028
81
2013-04-13T08:53:39Z
[ "python", "selenium", "selenium-webdriver" ]
I'm trying to get the current url after a series of navigations in Selenium. I know there's a command called getLocation for ruby, but I can't find the syntax for Python.
Use current\_url element. Example: ``` print browser.current_url ```
How do I get current URL in Selenium Webdriver 2 Python?
15,985,339
52
2013-04-13T07:20:01Z
29,004,681
13
2015-03-12T08:08:08Z
[ "python", "selenium", "selenium-webdriver" ]
I'm trying to get the current url after a series of navigations in Selenium. I know there's a command called getLocation for ruby, but I can't find the syntax for Python.
According to [documentation](http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webdriver.WebDriver.current_url) (a place full of goodies:)): ``` driver.current_url ```
Python dictionary keys as set of numbers
15,987,208
6
2013-04-13T11:18:51Z
15,987,285
10
2013-04-13T11:28:15Z
[ "python", "dictionary", "key", "minmax" ]
I'd like to structure a dictionary in python whose keys are pairs of min/max values between 0 and 1. For instance: ``` myDict = {(0, .5): 'red', (.5, 1): 'orange'} ``` I'd like to be able to call entries in the dictionary with a number *within* the set [min, max). ``` >>> myDict[.464897] 'red' >>> myDict[.5] 'orange...
Assuming the intervals do not overlap, there are no gaps and they are sorted you use a binary search: ``` >>> keys = [0.5, 1] # goes from 0 to 1, specify end interval >>> vals = ['red', 'orange'] >>> import bisect >>> vals[bisect.bisect_right(keys, 0.464897)] 'red' >>> vals[bisect.bisect_right(keys, 0.5)] 'orange' ```
Common baseclass for iterables?
15,987,715
3
2013-04-13T12:18:56Z
15,987,725
10
2013-04-13T12:19:46Z
[ "python", "list", "python-3.x", "iterator", "tuples" ]
I'm trying to create a method which only accepts an iterable parameter, such as `list`, `tuple`, `set` or `dict`. Here's my code: ``` class MjmMenuControl(MjmBaseMenu): def __init__(self, items=None): iterables = (dict, list, set, tuple) for iterable in iterables: if isinstance(items, ...
Yes, use [`collections.abc.Iterable`](http://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable): ``` >>> from collections import abc >>> isinstance(set(), abc.Iterable) True >>> isinstance((), abc.Iterable) True >>> isinstance([], abc.Iterable) True >>> isinstance('', abc.Iterable) True >>> isins...
Python Pylab pcolor options for publication quality plots
15,988,413
4
2013-04-13T13:40:03Z
15,989,267
8
2013-04-13T15:11:59Z
[ "python", "numpy", "matplotlib", "plot", "wolfram-mathematica" ]
I am trying to make DFT (discrete fourier transforms) plots using `pcolor` in python. I have previously been using Mathematica 8.0 to do this but I find that the colorbar in mathematica 8.0 has bad one-to-one correlation with the data I try to represent. For instance, here is the data that I am plotting: ``` [[0.,0.,0...
The following will get you closer to what you want: ``` import matplotlib.pyplot as plt plt.pcolor(data, cmap=plt.cm.OrRd) plt.yticks(np.arange(0.5,10.5),range(0,10)) plt.xticks(np.arange(0.5,10.5),range(0,10)) plt.colorbar() plt.gca().invert_yaxis() plt.gca().set_aspect('equal') plt.show() ``` The list of available...
How to set and get a parent class attribute from an inherited class in Python?
15,989,217
4
2013-04-13T15:07:21Z
15,989,250
12
2013-04-13T15:10:27Z
[ "python", "class", "inheritance" ]
I have the `Family` and its inherited `Person` classes. How do I get the `familyName` attribute from the `Person` class? ``` class Family(object): def __init__(self, familyName): self.familyName = familyName class Person(Family): def __init__(self, personName): self.personName = personName ```...
You cannot. Instances only inherit the parent class methods and attributes, not *instance* attributes. You should not confuse the two. `strauss.familyName` is an *instance* attribute of a `Family` instance. The `Person` instances would have their *own* copies of the `familyName` attribute. You normally would code th...
python/pandas: how to combine two dataframes into one with hierarchical column index?
15,989,281
13
2013-04-13T15:13:34Z
15,990,537
14
2013-04-13T17:10:10Z
[ "python", "pandas" ]
I have two dataframes which look like this: ``` >>> df1 A B 2000-01-01 1.4 1.4 2000-01-02 1.7 -1.9 2000-01-03 -0.2 -0.8 >>> df2 A B 2000-01-01 0.6 -0.3 2000-01-02 -0.4 0.6 2000-01-03 1.1 -1.0 ``` How can I make one dataframe out of this two with hierarchical column index like ...
This is a doc example: <http://pandas.pydata.org/pandas-docs/stable/merging.html#more-concatenating-with-group-keys> ``` In [9]: df1 = pd.DataFrame(np.random.randn(3,2),columns=list('AB'),index=pd.date_range('20000101',periods=3)) In [10]: df2 = pd.DataFrame(np.random.randn(3,2),columns=list('AB'),index=pd.date_range...
Python settings file (config)
15,992,387
6
2013-04-13T20:10:27Z
15,992,413
11
2013-04-13T20:13:30Z
[ "python", "settings", "app-config", "ini" ]
I am developing an program that have settings window in which I can change various settings parameters for my program. What is the best way to read/save dose settings (some kind of config file)? I know that some software and games use .ini files or similar system. How can I achieve this in Python.
The Python standard library includes the [`ConfigParser` module](http://docs.python.org/2/library/configparser.html), which handles ini-style configuration files for you. It's more than adequate for most uses.
Python, "filtered" line editing, read stdin by char with no echo
15,992,651
9
2013-04-13T20:38:03Z
15,993,377
10
2013-04-13T21:58:46Z
[ "python", "readline", "curses" ]
I need a function that reads input into a buffer as `raw_input()` would, but instead of echoing input and blocking until returning a full line, it should **supress echo and invoke a callback every time the buffer changes**. I say "buffer changes" instead of "character is read" because, as `raw_input()`, I'd like it to...
Well, I wrote the code by hand. I'll leave an explanation for future reference. # Requirements ``` import sys, tty, termios, codecs, unicodedata from contextlib import contextmanager ``` # Disabling line buffering The first problem that arises when simply reading stdin is *line buffering*. We want single characters...
Python - Read all files from folder (.shp, .dbf, .mxd etc)
15,994,981
3
2013-04-14T02:05:39Z
15,995,146
7
2013-04-14T02:34:40Z
[ "python", "arcgis" ]
Can anyone help me? I'm trying to write a code that will read all the files from a data folder. The files all have different extensions: .shp, .dbf, .sbx, .mxd) I'm using windows. Thanks. I've got: ``` import os path=r'C:\abc\def\ghi\' folderList = os.listdir(path) ``` Now I need to read all the files in the...
You were on the right path: ``` import os path = r'C:\abc\def\ghi' # remove the trailing '\' data = {} for dir_entry in os.listdir(path): dir_entry_path = os.path.join(path, dir_entry) if os.path.isfile(dir_entry_path): with open(dir_entry_path, 'r') as my_file: data[dir_entry] = my_file.r...
Python tkinter - how to delete all children elements?
15,995,783
5
2013-04-14T04:23:46Z
15,995,920
8
2013-04-14T04:49:06Z
[ "python", "user-interface", "tkinter" ]
I am writing a program on `Python` with GUI based on `Tkinter` and i face some problem: i need to delete ALL children elements(without deleting a parent element - `colorsFrame`). My code: ``` infoFrame = Frame(toolsFrame, height = 50, bd = 5, bg = 'white') colorsFrame = Frame(toolsFrame) # adding some elements infoF...
You can use `winfo_children` to get a list of all children of a particular widget, which you can then iterate over: ``` for child in infoFrame.winfo_children(): child.destroy() ```
Python - Zelle book uses eval(), is it wrong?
15,995,787
5
2013-04-14T04:24:53Z
16,003,216
7
2013-04-14T19:14:17Z
[ "python", "eval" ]
PLEASE NOTE: This is NOT about the use of eval(), it is about the potential quality (or lack thereof) of a book it is used and taught in. SO already has countless threads about eval() in Python. Risking to invite the wrath and downvotes of SO, I nonetheless decided to ask this question, just in case. Please bear with ...
As the author of the book in question, let me weigh in on this issue. The use of eval in the book is largely a historical artifact of the conversion from Python 2 to Python 3 (although the same "flaw" exists in the use of input in Python 2). I am well aware of the dangers of using eval in production code where input m...
python- reverse 2 strings in 1 list separately?
15,995,987
2
2013-04-14T05:02:02Z
15,995,996
8
2013-04-14T05:02:39Z
[ "python" ]
In python, I have this list containing ``` ['HELLO', 'WORLD'] ``` how do I turn that list into ``` ['OLLEH', 'DLROW'] ```
``` >>> words = ['HELLO', 'WORLD'] >>> [word[::-1] for word in words] ['OLLEH', 'DLROW'] ```
AIML for Intelligent Answering Engine
15,996,951
3
2013-04-14T08:00:22Z
15,998,144
11
2013-04-14T10:39:03Z
[ "python", "xml", "website", "artificial-intelligence", "aiml" ]
I have heard about a programming language called **AIML** which can be used for programming Intelligent Robots. I am a web developer and have a web crawler build using Python 2.7 and have indexed Wikipedia ... So I wanted to build a answering engine using python which would use a string variable (It is a HUGE variable...
### AIML It looks like [AIML](https://en.wikipedia.org/wiki/AIML) is a form of pattern matching. Moreover, it looks like this is mainly meant for [dialog based agents](https://en.wikipedia.org/wiki/Dialog_system). Therefore, to use AIML, you would likely need to manually generate every question and the correct respons...
How can I obtain the element-wise logical NOT of a pandas Series?
15,998,188
49
2013-04-14T10:44:28Z
15,998,993
62
2013-04-14T12:20:27Z
[ "python", "pandas", "boolean-logic" ]
I have a relatively straightforward question, today. I have a pandas `Series` object containing boolean values. How can I get a series containing the logical `NOT` of each value? For example, consider a series containing: ``` True True True False ``` The series I'd like to get would contain: ``` False False False T...
To invert a boolean Series, use `~s`: ``` In [7]: s = pd.Series([True, True, False, True]) In [8]: ~s Out[8]: 0 False 1 False 2 True 3 False dtype: bool ``` Using Python2.7, NumPy 1.8.0, Pandas 0.13.1: ``` In [119]: s = pd.Series([True, True, False, True]*10000) In [10]: %timeit np.invert(s) 10000 l...
Convert ipython notebooks to pdf-html
15,998,491
13
2013-04-14T11:19:17Z
15,999,099
9
2013-04-14T12:31:13Z
[ "python", "ipython", "ipython-notebook" ]
I want to convert my ipython-notebooks to print them, or simply send them to other in html format. I have notice that exist already a tool to do that, [nbconvert](https://github.com/ipython/nbconvert). I have downloaded it, but I have no idea how to convert the notebook, with nbconvert2.py since nbconvert says that is ...
nbconvert is not yet fully replaced by nbconvert2, you can still use it if you wish, otherwise we would have removed the executable. It's just a warning that we do not bugfix nbconvert1 anymore. The following should work : ``` ./nbconvert.py --format=pdf yourfile.ipynb ``` If you are on a IPython recent enough versi...
Convert ipython notebooks to pdf-html
15,998,491
13
2013-04-14T11:19:17Z
25,942,111
7
2014-09-19T20:42:41Z
[ "python", "ipython", "ipython-notebook" ]
I want to convert my ipython-notebooks to print them, or simply send them to other in html format. I have notice that exist already a tool to do that, [nbconvert](https://github.com/ipython/nbconvert). I have downloaded it, but I have no idea how to convert the notebook, with nbconvert2.py since nbconvert says that is ...
1. Convert the IPython notebook file to html. ``` ipython nbconvert --to html notebook.ipynb ``` This will convert the IPython document file notebook.ipynb into the html output format. 2. Convert the html file notebook.html into a pdf file called notebook.pdf. In Windows, Mac or Linux, install [wkhtmltopd...
Tie breaking of round with numpy
16,000,574
7
2013-04-14T15:11:22Z
16,000,851
9
2013-04-14T15:35:43Z
[ "python", "numpy", "scipy", "rounding" ]
Standard numpy round tie breaking is following IEEE 754 convention, to round half towards the nearest even number. Is there a way to specify different rounding behavior, e.g. round towards zero or towards -inf? I'm not talking about ceil or floor, I just need different tie breaking.
NumPy doesn't give any control over the internal rounding mode. Here's two alternatives: 1. Use `gmpy2`, as outlined in [this answer](http://stackoverflow.com/a/15104444/1204143). This gives you full control over the rounding mode, but using `gmpy2` for simple float math is likely to be slower than NumPy. 2. Use `fese...
Get greatest key in dictionary but lower than a variable
16,002,115
2
2013-04-14T17:34:55Z
16,002,139
7
2013-04-14T17:37:39Z
[ "python" ]
Given a dictionary and a variable like this: ``` dic = {0 : 'some', 10 : 'values', 20 : 'whatever'} var = 14 ``` I want to get the value from the dictionary where the key is the greatest but lower or equal to the variable. I don't know if that's clear but in this case I am looking for `10`. I've come up with this fu...
If you want the maximum key which is less than or equal to `var`, then you can pass a generator expression to the `max` function: ``` >>> dic = {0 : 'some', 10 : 'values', 20 : 'whatever'} >>> var = 14 >>> max(k for k in dic if k <= var) 10 ``` with corresponding value ``` >>> dic[max(k for k in dic if k <= var)] 'v...
django social-auth multiple account association
16,002,576
4
2013-04-14T18:13:34Z
16,021,516
8
2013-04-15T17:46:50Z
[ "python", "django", "single-sign-on", "django-socialauth" ]
I am using django social-auth (<http://django-social-auth.readthedocs.org/en/latest/index.html>) and trying to create a user profile where the user can associate multiple accounts (like here on Stackoverflow). Currently I am at the point where single user can login using different authentication providers, but for eac...
DSA already supports multiple account association, the trick is to it is that the user must be logged in, otherwise DSA doesn't know it should be associated with an already existing account. Regarding your profile, the recommended way to add functionality to DSA is by extending the [pipeline](http://django-social-auth...
Installing bsddb package - python
16,003,224
11
2013-04-14T19:15:01Z
17,213,338
8
2013-06-20T12:10:57Z
[ "python", "osx", "installation", "package" ]
I am totally new to python and I have this message when I try to import bsdddb ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/bsddb/__init__.py", line 67, in <module> import _bsddb ImportError: No module na...
bsddb is [deprecated since 2.6](http://docs.python.org/2/library/bsddb.html#module-bsddb). The ideal is to use [the bsddb3 module](http://www.jcea.es/programacion/pybsddb.htm). My suggestion, and by far the easiest option, is to install [Homebrew](http://mxcl.github.io/homebrew/) and use it to get BerkeleyDB on your s...
Python dict.get() with multidimensional dict
16,003,408
7
2013-04-14T19:34:20Z
16,003,429
11
2013-04-14T19:36:29Z
[ "python", "dictionary" ]
I have a multidimensional dict, and I'd like to be able to retrieve a value by a key:key pair, and return 'NA' if the first key doesn't exist. All of the sub-dicts have the same keys. ``` d = { 'a': {'j':1,'k':2}, 'b': {'j':2,'k':3}, 'd': {'j':1,'k':3} } ``` I know I can use `d.get('c','NA')` to...
How about ``` d.get('a', {'j': 'NA'})['j'] ``` ? If not all subdicts have a `j` key, then ``` d.get('a', {}).get('j', 'NA') ``` To cut down on identical objects created, you can devise something like ``` class DefaultNASubdict(dict): class NADict(object): def __getitem__(self, k): return '...
A Fast Prime Number Sieve in Python
16,004,407
5
2013-04-14T21:15:48Z
18,997,575
7
2013-09-25T06:18:24Z
[ "python", "algorithm", "primes", "sieve-of-eratosthenes" ]
I have been going through prime number generation in python using the sieve of Eratosthenes and the solutions which people tout as a relatively fast option such as those in a few of [the answers to a question on optimising prime number generation in python](http://stackoverflow.com/questions/2068372/fastest-way-to-list...
I transformed your code to fit into the prime sieve comparison script of @unutbu at [Fastest way to list all primes below N in python](http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python) as follows: ``` def sieve_for_primes_to(n): size = n//2 sieve = [1]*size limit ...
python: what is best way to check multiple keys exists in a dictionary?
16,004,593
11
2013-04-14T21:34:45Z
16,004,601
8
2013-04-14T21:35:47Z
[ "python", "dictionary" ]
my dict looks like ``` d = { 'name': 'name', 'date': 'date', 'amount': 'amount', ... } ``` I want to test if `name` and `amount` exists, so I will do ``` if not `name` in d and not `amount` in d: raise ValueError # for example ``` Suppose I get the data from an api and I want to test if `10` of the fields...
``` if all(k not in d for k in ('name', 'amount')): raise ValueError ``` or ``` if all(k in d for k in ('name', 'amount')): # do stuff ```
python: what is best way to check multiple keys exists in a dictionary?
16,004,593
11
2013-04-14T21:34:45Z
16,004,611
22
2013-04-14T21:36:48Z
[ "python", "dictionary" ]
my dict looks like ``` d = { 'name': 'name', 'date': 'date', 'amount': 'amount', ... } ``` I want to test if `name` and `amount` exists, so I will do ``` if not `name` in d and not `amount` in d: raise ValueError # for example ``` Suppose I get the data from an api and I want to test if `10` of the fields...
You can use `set` intersections: ``` if not d.viewkeys() & {'amount', 'name'}: raise ValueError ``` In Python 3, that'd be: ``` if not d.keys() & {'amount', 'name'}: raise ValueError ``` because `.keys()` returns a dict view by default. [Dictionary view objects](http://docs.python.org/2/library/stdtypes.htm...
Django Class Based Views, get_absolute_url not working
16,004,679
3
2013-04-14T21:42:44Z
16,651,802
7
2013-05-20T14:32:52Z
[ "python", "django" ]
I bought and am Reading the Book Two Scoops of Django:Best Practices for Django 1.5 and in it has a example of Class based views. After this implementation I get the error after submitting the form. ``` ImproperlyConfigured at /NonProfitCreate/ No URL to redirect to. Either provide a url or define a get_absolute_url ...
This exception is produced because `self.object = None` when attempting to redirect after a valid edit. Since the value of `self.object` is the result of a `form.save()` call, the most likely reason for this error is that you have overridden the `save()` method in `NonProfitCreateForm`, but forgotten to return the save...