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
Algorithm to find least sum of squares of differences
13,727,222
3
2012-12-05T15:56:23Z
13,727,488
11
2012-12-05T16:10:33Z
[ "python", "algorithm" ]
Basically this algorithm I'm writing takes as input a List L and wants to find a number x such that all items in L, i, minus x squared and summed are minimized. Find minimum x for the sum of `abs(L[i]-x)**2`. So far my algorithm is doing what it's supposed to, just not in the cases of floating. I'm not sure how to impl...
It is easy to prove [\*] that the number that minimizes the sum of squared differences is the arithmetic [mean](http://en.wikipedia.org/wiki/Mean) of `L`. This gives the following simple solution: ``` In [26]: L = [2, 2, 3, 4] In [27]: sum(L) / float(len(L)) Out[27]: 2.75 ``` or, using [NumPy](http://numpy.scipy.org...
Several time series to DataFrame
13,728,208
9
2012-12-05T16:48:06Z
13,728,364
11
2012-12-05T16:55:39Z
[ "python", "pandas", "time-series" ]
I have problem merging several time series to a common DataFrame. The example code I'm using: ``` import pandas import datetime import numpy as np start = datetime.datetime(2001, 1, 1) end = datetime.datetime(2001, 1, 10) dates = pandas.date_range(start, end) serie_1 = pandas.Series(np.random.randn(10), index = dates...
Concatenating a list of `Series` returns a `DataFrame`. Thus, `serie_4` is a `DataFrame`. `serie_3` is a `Series`. Concatenating a `DataFrame` with a `Series` raises the exception. You could use ``` serie_5 = pandas.concat([serie_1, serie_2, serie_3], join='outer', axis = 1) ``` instead. --- Another way is to use ...
Passing DataTable to IronPython
13,728,305
4
2012-12-05T16:53:14Z
13,728,498
7
2012-12-05T17:02:55Z
[ "c#", "python", ".net", "ironpython" ]
I have a .NET project where I am using IronPython to perform some processing of the data. At present, the C# code loops through and generates an IronPython script for each row and column that requires dynamic calculation. However, I'd like to make the process more efficient by passing in the DataTable object and a scri...
DataTable object really *is* unsubscriptable, i.e. cannot be accessed through indexed properties (i.e. `dt[index]` ). You probably meant this: ``` for row in dt.Rows: row["calc"] = row["count"] + 1 ``` where I replaced `dt` variable with `row`.
Moving average or running mean
13,728,392
43
2012-12-05T16:57:05Z
13,730,849
13
2012-12-05T19:23:12Z
[ "python", "python-2.7", "numpy", "matplotlib", "scipy" ]
Is there a scipy function or numpy function or module for python that calculates the running mean of a 1D array given a specific window? /M
For a ready-to-use solution, see <http://www.scipy.org/Cookbook/SignalSmooth>. It provides running average with the `flat` window type. Note that this is a bit more sophisticated than the simple do-it-yourself convolve-method, since it tries to handle the problems at the beginning and the end of the data by reflecting ...
Moving average or running mean
13,728,392
43
2012-12-05T16:57:05Z
13,732,668
38
2012-12-05T21:21:38Z
[ "python", "python-2.7", "numpy", "matplotlib", "scipy" ]
Is there a scipy function or numpy function or module for python that calculates the running mean of a 1D array given a specific window? /M
You can calculate a running mean with: ``` import numpy as np def runningMean(x, N): y = np.zeros((len(x),)) for ctr in range(len(x)): y[ctr] = np.sum(x[ctr:(ctr+N)]) return y/N ``` But it's slow. Fortunately, numpy includes a [convolve](http://docs.scipy.org/doc/numpy/reference/generated/numpy...
Moving average or running mean
13,728,392
43
2012-12-05T16:57:05Z
22,621,523
64
2014-03-24T22:01:33Z
[ "python", "python-2.7", "numpy", "matplotlib", "scipy" ]
Is there a scipy function or numpy function or module for python that calculates the running mean of a 1D array given a specific window? /M
**UPD:** more efficient solutions have been proposed by [Alleo](http://stackoverflow.com/a/27681394/675674) and [jasaarim](http://stackoverflow.com/a/30141358/675674). --- You can use [`np.convolve`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html) for that: ``` np.convolve(x, np.ones((N,))/N...
Moving average or running mean
13,728,392
43
2012-12-05T16:57:05Z
27,681,394
33
2014-12-28T22:50:57Z
[ "python", "python-2.7", "numpy", "matplotlib", "scipy" ]
Is there a scipy function or numpy function or module for python that calculates the running mean of a 1D array given a specific window? /M
## Efficient solution Convolution is much better than straightforward approach, but (I guess) it uses FFT and thus quite slow. However specially for computing the running mean the following approach works fine ``` def running_mean(x, N): cumsum = numpy.cumsum(numpy.insert(x, 0, 0)) return (cumsum[N:] - cumsu...
Moving average or running mean
13,728,392
43
2012-12-05T16:57:05Z
30,141,358
27
2015-05-09T14:51:13Z
[ "python", "python-2.7", "numpy", "matplotlib", "scipy" ]
Is there a scipy function or numpy function or module for python that calculates the running mean of a 1D array given a specific window? /M
[pandas](http://pandas.pydata.org/) is more suitable for this than NumPy or SciPy. Its function [rolling\_mean](http://pandas.pydata.org/pandas-docs/stable/computation.html#moving-rolling-statistics-moments) does the job conveniently. It also returns a NumPy array when the input is an array. It is difficult to beat `r...
Moving average or running mean
13,728,392
43
2012-12-05T16:57:05Z
33,055,571
8
2015-10-10T15:21:39Z
[ "python", "python-2.7", "numpy", "matplotlib", "scipy" ]
Is there a scipy function or numpy function or module for python that calculates the running mean of a 1D array given a specific window? /M
> or module for python that calculates in my tests at Tradewave.net TA-lib always wins: ``` import talib as ta import numpy as np import pandas as pd import scipy from scipy import signal import time as t PAIR = info.primary_pair PERIOD = 30 def initialize(): storage.reset() storage.elapsed = storage.get('e...
Inverting a numpy boolean array using ~
13,728,708
15
2012-12-05T17:15:01Z
22,225,030
10
2014-03-06T12:47:48Z
[ "python", "arrays", "numpy", "boolean", "invert" ]
Can I use `~A` to invert a numpy array of booleans, instead of the rather awkward functions `np.logical_and()` and `np.invert()`? Indeed, `~` seems to work fine, but I can't find it in any nympy reference manual, and - more alarmingly - it certainly does *not* work with scalars (e.g. `bool(~True)` returns `True` !), so...
short answer: YES Ref: <http://docs.scipy.org/doc/numpy/reference/generated/numpy.invert.html> Notice: > Computes the bit-wise NOT of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator ~. and > bitwise\_not is an alias for invert: ``` >> np.bitwi...
Django + MySQL: savepoint does not exist?
13,728,843
2
2012-12-05T17:22:27Z
14,875,012
8
2013-02-14T12:34:53Z
[ "python", "mysql", "django" ]
I'm running a small Web app on a shared hosting plan. I have a "worker function" which contains an infinite loop; the loop checks a task queue in the DB for new things to do. This necessitated using `@transaction.commit_manually` in order to defeat Django's caching and get up-to-date info on every iteration. I recentl...
I had the same occasionally recurring nasty error ``` OperationalError: (1305, 'SAVEPOINT {{name}} does not exist') ``` and Googling didn't make it clearer, except that it's sort of "normal" concurrency issue. So it's non-deterministic and hard to reproduce in development environment. Luckily it was localized, so I ...
How can I filter Emoji characters from my input so I can save in MySQL <5.5?
13,729,638
9
2012-12-05T18:08:40Z
13,752,628
17
2012-12-06T21:11:01Z
[ "python", "mysql", "django", "utf-8", "character-encoding" ]
I have a Django app that takes tweet data from Twitter's API and saves it in a MySQL database. As far as I know (I'm still getting my head around the finer points of character encoding) I'm using UTF-8 everywhere, including MySQL encoding and collation, which works fine except when a tweet contains **Emoji** characters...
So it turns out this has been answered a few times, I just hadn't quite got the right Google-fu to find the existing questions. * [Python, convert 4-byte char to avoid MySQL error "Incorrect string value:"](http://stackoverflow.com/questions/12636489/python-convert-4-byte-char-to-avoid-mysql-error-incorrect-string-val...
How can I filter Emoji characters from my input so I can save in MySQL <5.5?
13,729,638
9
2012-12-05T18:08:40Z
26,740,753
10
2014-11-04T16:57:32Z
[ "python", "mysql", "django", "utf-8", "character-encoding" ]
I have a Django app that takes tweet data from Twitter's API and saves it in a MySQL database. As far as I know (I'm still getting my head around the finer points of character encoding) I'm using UTF-8 everywhere, including MySQL encoding and collation, which works fine except when a tweet contains **Emoji** characters...
I tryied the solution by BigglesZX and its wasn't woring for the emoji of the heart (❤) after reading the [emoji's wikipedia article][1] I've seen that the regular expression is not covering all the emojis while also covering other range of unicode that are not emojis. The following code create the 5 regular express...
Writelines writes lines without newline, Just fills the file..
13,730,107
23
2012-12-05T18:38:09Z
13,730,216
21
2012-12-05T18:44:58Z
[ "python", "django" ]
I have a program that writes a list to a file. The list is a list of pipe delimited lines and the lines should be written to the file like this: ``` 123|GSV|Weather_Mean|hello|joe|43.45 122|GEV|temp_Mean|hello|joe|23.45 124|GSI|Weather_Mean|hello|Mike|47.45 ``` BUT it wrote them line this ahhhh: ``` 123|GSV|Weather_...
The [documentation for `writelines()`](http://docs.python.org/2/library/stdtypes.html#file.writelines) states: > `writelines()` does not add line separators So you'll need to add them yourself. For example: ``` line_list.append(new_line + "\n") ``` whenever you append a new item to `line_list`.
Writelines writes lines without newline, Just fills the file..
13,730,107
23
2012-12-05T18:38:09Z
13,730,337
21
2012-12-05T18:52:01Z
[ "python", "django" ]
I have a program that writes a list to a file. The list is a list of pipe delimited lines and the lines should be written to the file like this: ``` 123|GSV|Weather_Mean|hello|joe|43.45 122|GEV|temp_Mean|hello|joe|23.45 124|GSI|Weather_Mean|hello|Mike|47.45 ``` BUT it wrote them line this ahhhh: ``` 123|GSV|Weather_...
This is actually a pretty common problem for newcomers to Python—especially since, across the standard library and popular third-party libraries, some reading functions strip out newlines, but almost no writing functions (except the `log`-related stuff) add them. So, there's a lot of Python code out there that does ...
From ND to 1D arrays
13,730,468
29
2012-12-05T18:59:13Z
13,730,506
71
2012-12-05T19:01:14Z
[ "python", "numpy" ]
Say I have an array `a`: ``` a = np.array([[1,2,3], [4,5,6]]) array([[1, 2, 3], [4, 5, 6]]) ``` I would like to convert it to a 1D array (i.e. a column vector): ``` b = np.reshape(a, (1,np.product(a.shape))) ``` but this returns ``` array([[1, 2, 3, 4, 5, 6]]) ``` which is not the same as: ``` array([1, ...
Use [np.ravel](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html#numpy-ravel) (for a 1D view) or [np.flatten](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html) (for a 1D copy) or [np.flat](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flat.html#numpy-...
From ND to 1D arrays
13,730,468
29
2012-12-05T18:59:13Z
13,730,520
8
2012-12-05T19:01:45Z
[ "python", "numpy" ]
Say I have an array `a`: ``` a = np.array([[1,2,3], [4,5,6]]) array([[1, 2, 3], [4, 5, 6]]) ``` I would like to convert it to a 1D array (i.e. a column vector): ``` b = np.reshape(a, (1,np.product(a.shape))) ``` but this returns ``` array([[1, 2, 3, 4, 5, 6]]) ``` which is not the same as: ``` array([1, ...
``` In [14]: b = np.reshape(a, (np.product(a.shape),)) In [15]: b Out[15]: array([1, 2, 3, 4, 5, 6]) ``` or, simply: ``` In [16]: a.flatten() Out[16]: array([1, 2, 3, 4, 5, 6]) ```
How do I return HTTP error code without default template in Tornado?
13,730,945
22
2012-12-05T19:30:03Z
13,735,021
22
2012-12-06T00:29:25Z
[ "python", "tornado" ]
I am currently using the following to raise a HTTP bad request: ``` raise tornado.web.HTTPError(400) ``` which returns a html output: ``` <html><title>400: Bad Request</title><body>400: Bad Request</body></html> ``` Is it possible to return just the HTTP response code with a custom body?
You may simulate [`RequestHandler.send_error`](http://tornado.readthedocs.org/en/stable/web.html#tornado.web.RequestHandler.send_error) method: ``` class MyHandler(tornado.web.RequestHandler): def get(self): self.clear() self.set_status(400) self.finish("<html><body>My custom body</body></h...
How do I return HTTP error code without default template in Tornado?
13,730,945
22
2012-12-05T19:30:03Z
13,739,277
19
2012-12-06T08:01:08Z
[ "python", "tornado" ]
I am currently using the following to raise a HTTP bad request: ``` raise tornado.web.HTTPError(400) ``` which returns a html output: ``` <html><title>400: Bad Request</title><body>400: Bad Request</body></html> ``` Is it possible to return just the HTTP response code with a custom body?
Tornado calls [`RequestHandler.write_error`](http://tornado.readthedocs.org/en/stable/web.html#tornado.web.RequestHandler.write_error) to output errors, so an alternative to [VisioN's approach](http://stackoverflow.com/a/13735021/2038264) would be override it as suggested by the Tornado [docs](http://tornado.readthedoc...
Get array elements from index to end
13,732,025
5
2012-12-05T20:40:29Z
13,732,111
10
2012-12-05T20:46:28Z
[ "python", "vector", "numpy", "indexing" ]
Suppose we have the following array: ``` import numpy as np a = np.arange(1, 10) a = a.reshape(len(a), 1) array([[1], [2], [3], [4], [5], [6], [7], [8], [9]]) ``` Now, i want to access the elements from index 4 to the end: ``` a[3:-1] array([[4], [5], ...
The `[:-1]` removes the last element. Instead of ``` a[3:-1] ``` write ``` a[3:] ``` You can read up on Python slicing notation here: [Good Primer for Python Slice Notation](http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) NumPy slicing is an extension of that. The NumPy tutorial ha...
Installing Python's easy_install using ez_setup.py from behind a proxy server
13,733,375
12
2012-12-05T22:08:37Z
18,790,045
15
2013-09-13T15:29:42Z
[ "python", "proxy", "easy-install" ]
Is there a way to install Python's easy\_install using ez\_setup.py when on a corporate network that uses a proxy server? Currently, I receive a connection timeout: ``` Downloading http://pypi.python.org/packages/2.7/s/setuptools/setuptools-0.6c11-py2.7.egg Traceback (most recent call last): File "C:\jsears\python\e...
On Windows 7, with PowerShell, the proxy settings above are ignored, and the tool won't work. But I found the solution. I modified the routine download\_file\_powershell by adding ``` [System.Net.WebRequest]::DefaultWebProxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials; ``` inside the scriptlet use...
logger configuration to log to file and print to stdout
13,733,552
83
2012-12-05T22:22:51Z
13,733,777
14
2012-12-05T22:37:43Z
[ "python", "file", "logging", "stdout" ]
I'm using Python's logging module to log some debug strings to a file which works pretty well. Now in addition, I'd like to use this module to also print the strings out to stdout. How do I do this? In order to log my strings to a file I use following code: ``` import logging import logging.handlers logger = logging.g...
Either run `basicConfig` with `stream=sys.stdout` as the argument prior to setting up any other handlers or logging any messages, or manually add a `StreamHandler` that pushes messages to stdout to the root logger (or any other logger you want, for that matter).
logger configuration to log to file and print to stdout
13,733,552
83
2012-12-05T22:22:51Z
13,733,863
116
2012-12-05T22:43:00Z
[ "python", "file", "logging", "stdout" ]
I'm using Python's logging module to log some debug strings to a file which works pretty well. Now in addition, I'd like to use this module to also print the strings out to stdout. How do I do this? In order to log my strings to a file I use following code: ``` import logging import logging.handlers logger = logging.g...
Just get a handle to the root logger and add the StreamHandler. The StreamHandler writes to stderr. Not sure if you really need stdout over stderr, but this is what I use when I setup the Python logger and I also add the FileHandler as well. Then all my logs go to both places (which is what it sounds like you want). `...
logger configuration to log to file and print to stdout
13,733,552
83
2012-12-05T22:22:51Z
26,007,714
11
2014-09-24T02:49:04Z
[ "python", "file", "logging", "stdout" ]
I'm using Python's logging module to log some debug strings to a file which works pretty well. Now in addition, I'd like to use this module to also print the strings out to stdout. How do I do this? In order to log my strings to a file I use following code: ``` import logging import logging.handlers logger = logging.g...
Adding a StreamHandler without arguments goes to stderr instead of stdout. If some other process has a dependency on the stdout dump (i.e. when writing an NRPE plugin), then make sure to specify stdout explicitly or you might run into some unexpected troubles. Here's a quick example reusing the assumed values and LOGF...
String split with indices in Python
13,734,451
12
2012-12-05T23:32:58Z
13,734,572
16
2012-12-05T23:42:16Z
[ "python" ]
I am looking for pythonic way to split a sentence into words, and also store the index information of all the words in a sentence e.g ``` a = "This is a sentence" b = a.split() # ["This", "is", "a", "sentence"] ``` Now, I also want to store the index information of all the words ``` c = a.splitWithIndices() #[(0,3),...
Here is a method using regular expressions: ``` >>> import re >>> a = "This is a sentence" >>> matches = [(m.group(0), (m.start(), m.end()-1)) for m in re.finditer(r'\S+', a)] >>> matches [('This', (0, 3)), ('is', (5, 6)), ('a', (8, 8)), ('sentence', (10, 17))] >>> b, c = zip(*matches) >>> b ('This', 'is', 'a', 'sente...
String split with indices in Python
13,734,451
12
2012-12-05T23:32:58Z
13,734,815
8
2012-12-06T00:04:55Z
[ "python" ]
I am looking for pythonic way to split a sentence into words, and also store the index information of all the words in a sentence e.g ``` a = "This is a sentence" b = a.split() # ["This", "is", "a", "sentence"] ``` Now, I also want to store the index information of all the words ``` c = a.splitWithIndices() #[(0,3),...
I think it's more natural to return the start and end of the corresponding splices. eg (0, 4) instead of (0, 3) ``` >>> from itertools import groupby >>> def splitWithIndices(s, c=' '): ... p = 0 ... for k, g in groupby(s, lambda x:x==c): ... q = p + sum(1 for i in g) ... if not k: ... yield p, q # or p, q-1 ...
How can I quickly disable a try statement in python for testing?
13,734,567
9
2012-12-05T23:42:02Z
13,734,650
11
2012-12-05T23:48:16Z
[ "python", "debugging", "testing", "exception-handling" ]
Say I have the following code: ``` try: print 'foo' # A lot more code... print 'bar' except: pass ``` How would I for testing purposes disable the try-statement temporary? You can't just comment the `try` and `except` lines out as the indention will still be off. Isn't there any easier way than this...
You could reraise the exception as the first line of your except block, which would behave just as it would without the try/except. ``` try: print 'foo' # A lot more code... print 'bar' except: raise # was: pass ```
Invalidate an old session in Flask
13,735,024
18
2012-12-06T00:30:09Z
13,735,134
22
2012-12-06T00:42:04Z
[ "python", "flask" ]
How do I create a new clean session and invalidate the current one in Flask? Do I use `make_null_session()` or `open_session()`?
I do this by calling [`session.clear()`](http://docs.python.org/2.7/library/stdtypes.html#dict.clear). EDIT: After reading your comment in another answer, I see that you're trying to prevent a replay attack that might be made using a cookie that was issued in the past. I solved that problem as much as possible\* with...
Invalidate an old session in Flask
13,735,024
18
2012-12-06T00:30:09Z
13,736,623
7
2012-12-06T03:45:48Z
[ "python", "flask" ]
How do I create a new clean session and invalidate the current one in Flask? Do I use `make_null_session()` or `open_session()`?
You can add an [`after_request`](http://flask.pocoo.org/docs/api/#flask.Flask.after_request) callback to remove the session cookie if a particular flag is set: ``` @app.after_request def remove_if_invalid(response): if "__invalidate__" in session: response.delete_cookie(app.session_cookie_name) return ...
Bottle.py session with Beaker
13,735,333
2
2012-12-06T01:05:40Z
13,735,586
19
2012-12-06T01:35:09Z
[ "python", "bottle", "beaker" ]
first time questioner here. I'm currently struggling on how to use Beaker properly using the Bottle micro-framework. Here's the problematic program: ``` #!/usr/bin/python # -*- coding: utf-8 -*- # filename: server.py import bottle as app from beaker.middleware import SessionMiddleware session_options = { 'sessi...
Using `beaker` in your `bottle` application is easy. First, set up your Bottle app: ``` import bottle from bottle import request, route, hook import beaker.middleware session_opts = { 'session.type': 'file', 'session.data_dir': './session/', 'session.auto': True, } app = beaker.middleware.SessionMiddlewa...
Recursion in Python 3.2
13,737,692
3
2012-12-06T05:48:42Z
13,738,321
7
2012-12-06T06:45:42Z
[ "python", "list", "recursion", "python-3.x" ]
I am trying to wrap my head around recursion and have posted a working algorithm to produce all the subsets of a given list. ``` def genSubsets(L): res = [] if len(L) == 0: return [[]] smaller = genSubsets(L[:-1]) extra = L[-1:] new = [] for i in smaller: new.append(i+extra) ...
I think this would actually be easier to visualize with a longer source list. If you use `[0, 1, 2]`, you'll see that the recursive calls repeatedly cut off the last item from the list. That is, recusion builds up a stack of recursive calls like this: ``` genSubsets([0,1,2]) genSubsets([0,1]) genSubsets([0...
How To apply a filter to a signal in python
13,740,348
6
2012-12-06T09:16:16Z
13,740,532
19
2012-12-06T09:27:54Z
[ "python", "scipy", "signal-processing" ]
is there any prepared function in python to apply a filter (for example Butterworth filter) to a given signal? I looking for such a function in 'scipy.signal' but I haven't find any useful functions more than filter design ones. actually I want this function to convolve a filter with the signal.
Yes! There are two: ``` scipy.signal.filtfilt scipy.signal.lfilter ``` There are also methods for convolution (`convolve` and `fftconvolve`), but these are probably not appropriate for your application because it involves IIR filters. Full code sample: ``` b, a = scipy.signal.butter(N, Wn, 'low') output_signal = sc...
in pandas how can I groupby weekday() for a datetime column?
13,740,672
10
2012-12-06T09:36:35Z
13,741,439
19
2012-12-06T10:19:32Z
[ "python", "pandas" ]
I'd like to filter out weekend data and only look at data for weekdays (mon(0)-fri(4)). I'm new to pandas, what's the best way to accomplish this in pandas? ``` import datetime from pandas import * data = read_csv("data.csv") data.my_dt Out[52]: 0 2012-10-01 02:00:39 1 2012-10-01 02:00:38 2 2012-10-01 0...
your call to the function "weekday" does not work as it operates on the index of data.my\_dt, which is an int64 array (this is where the error message comes from) you could create a new column in data containing the weekdays using something like: ``` data['weekday'] = data['my_dt'].apply(lambda x: x.weekday()) ``` t...
SciPy NumPy and SciKit-learn , create a sparse matrix
13,742,266
4
2012-12-06T11:05:44Z
13,742,435
11
2012-12-06T11:14:09Z
[ "python", "matrix", "numpy", "scipy", "scikit-learn" ]
I'm currently trying to classify text. My dataset is too big and as suggested [here](http://stackoverflow.com/questions/13741460/text-classification-with-scikit-learn-and-a-large-dataset/13741595#13741595), I need to use a sparse matrix. My question is now, what is the right way to add an element to a sparse matrix? Le...
Scikit-learn has a great documentation, with great tutorials that you really *should* read before trying to invent it yourself. [This](http://scikit-learn.org/dev/tutorial/text_analytics/working_with_text_data.html) one is the first one to read it explains how to classify text, step-by-step. Pay extra attention to the...
How to validate xml using python without third-party libs?
13,742,538
9
2012-12-06T11:20:14Z
13,742,662
12
2012-12-06T11:27:34Z
[ "python" ]
I have some xml pieces like this: ``` <!DOCTYPE mensaje SYSTEM "record.dtd"> <record> <player_birthday>1979-09-23</player_birthday> <player_name>Orene Ai'i</player_name> <player_team>Blues</player_team> <player_id>453</player_id> <player_height>170</player_height> <player_position>F&W</player_p...
Just try to parse it with ElementTree (xml.etree.ElementTree.fromstring) - it will raise an error if the XML is not well formed. ``` >>> a = """<record> ... <player_birthday>1979-09-23</player_birthday> ... <player_name>Orene Ai'i</player_name> ... <player_team>Blues</player_team> ... <player_id>453</p...
How to mpf an array?
13,743,785
7
2012-12-06T12:35:39Z
13,748,797
9
2012-12-06T17:06:54Z
[ "python", "arrays", "numpy", "mpf", "mpmath" ]
I have: ``` import numpy as np from mpmath import * mpf(np.array(range(0,600))) ``` But it won't let me do it: ``` TypeError: cannot create mpf from array ``` So what should I be doing? Essentially I'm going to have use this array and multiply element-wise with an incredibly large or incredible small number depen...
Multiplying an array by a mpf number just works: ``` import numpy as np import mpmath as mp small_number = mp.besseli(400, 2) # This is an mpf number # Note that creating a list using `range` and then converting it # to an array is not very efficient. Do this instead: A = np.arange(600) result = small_number * A # A...
Command line execution in different folder
13,744,473
17
2012-12-06T13:18:57Z
13,744,754
28
2012-12-06T13:35:03Z
[ "python", "shell", "command-line" ]
I'm calling a command line program in python using the `os.system(command)` call. How can I call this command passing a different folder for execution? There is a system call for this? Or I should save the current folder, and, after execution, change restore it.
The `subprocess` module is a very good solution. ``` import subprocess p = subprocess.Popen([command, argument1,...], cwd=working_directory) p.wait() ``` I has also arguments for modifying environment variables, redirecting input/output to the calling program etc.
Why does Go's map iteration order vary when printing?
13,744,996
3
2012-12-06T13:50:57Z
13,745,046
13
2012-12-06T13:53:13Z
[ "python", "map", "go" ]
``` package main import "fmt" func main(){ sample := map[string]string{ "key1":"value1", "key2":"value2", "key3":"value3", } for i := 0;i<3;i++{ fmt.Println(sample) } } ``` The above go code just print a map[string]string three times. I expect it to a fixed output,but it shows as...
You cannot rely on the order in which you will get the keys. The language spec [says](http://golang.org/ref/spec#Map_types) "A map is an unordered group of elements", and later "The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next."
django get key name from KeyError exception
13,745,514
6
2012-12-06T14:18:46Z
13,745,646
14
2012-12-06T14:25:15Z
[ "python", "django", "exception" ]
I would like to get the key name from the KeyError Exception For example: ``` myDict = {'key1':'value1'} try: x1 = myDict['key1'] x2 = myDict['key2'] except KeyError as e: # here i want to use the name of the key that was missing which is 'key2' in this example print error_msg[missing_key] ``` i hav...
You can use `e.args`: ``` [53]: try: x2 = myDict['key2'] except KeyError as e: print e.args[0] ....: key2 ``` From the [docs](http://docs.python.org/2/tutorial/errors.html): > The except clause may specify a variable after the exception name (or > tuple). The variable is bound to an exception ins...
Running bash script from within python
13,745,648
33
2012-12-06T14:25:16Z
13,745,842
14
2012-12-06T14:35:52Z
[ "python", "bash", "call" ]
I have a problem with the following code: **callBash.py:** ``` import subprocess print "start" subprocess.call("sleep.sh") print "end" ``` **sleep.sh:** ``` sleep 10 ``` I want the "end" to be printed after 10s. (I know that this is a dumb example, I could simply sleep within python, but this simple sleep.sh file ...
Actually, you just have to add the `shell=True` argument: ``` subprocess.call("sleep.sh", shell=True) ``` But beware - > Warning Invoking the system shell with shell=True can be a security hazard if combined with untrusted input. See the warning under Frequently Used Arguments for details. [source](http://docs.pyth...
Running bash script from within python
13,745,648
33
2012-12-06T14:25:16Z
13,745,968
29
2012-12-06T14:42:00Z
[ "python", "bash", "call" ]
I have a problem with the following code: **callBash.py:** ``` import subprocess print "start" subprocess.call("sleep.sh") print "end" ``` **sleep.sh:** ``` sleep 10 ``` I want the "end" to be printed after 10s. (I know that this is a dumb example, I could simply sleep within python, but this simple sleep.sh file ...
Making sleep.sh executable and adding `shell=True` to the parameter list (as suggested in previous answers) works ok. Depending on the search path, you may also need to add `./` or some other appropriate path. (Ie, change `"sleep.sh"` to `"./sleep.sh"`.) The `shell=True` parameter is not needed (under a Posix system l...
Running bash script from within python
13,745,648
33
2012-12-06T14:25:16Z
22,416,147
7
2014-03-14T21:35:09Z
[ "python", "bash", "call" ]
I have a problem with the following code: **callBash.py:** ``` import subprocess print "start" subprocess.call("sleep.sh") print "end" ``` **sleep.sh:** ``` sleep 10 ``` I want the "end" to be printed after 10s. (I know that this is a dumb example, I could simply sleep within python, but this simple sleep.sh file ...
If `sleep.sh` has the shebang `#!/bin/sh` and it has appropriate file permissions -- run `chmod u+rx sleep.sh` to make sure and it is in `$PATH` then your code should work as is: ``` import subprocess rc = subprocess.call("sleep.sh") ``` If the script is not in the PATH then specify the full path to it e.g., if it i...
Extracting an integer between = and ;
13,746,189
2
2012-12-06T14:53:04Z
13,746,279
8
2012-12-06T14:57:07Z
[ "python", "regex", "file-io", "readline" ]
Given the following string; ``` ....00.3276021,,,constString1=31;garbage=00:00:00.0090000;constString2=16;garbage2=00.00... ``` How can I extract the values for `constString1` and `constString2` so that I can assign them to a variable. For example: ``` string1_cummulativeTotal += [the magic returning the int] string...
``` In [1]: import re In [2]: s = '....00.3276021,,,constString1=31;garbage=00:00:00.0090000;constString2=16;garbage2=00.00...' In [3]: re.search('constString1=(\d+);', s).group(1) Out[3]: '31' In [4]: re.search('constString2=(\d+);', s).group(1) Out[4]: '16' ``` These are still strings, don't forget to convert the...
Does this prime function actually work?
13,747,873
16
2012-12-06T16:18:18Z
13,811,371
11
2012-12-10T23:53:40Z
[ "python", "algorithm", "math", "python-2.7", "primes" ]
Since I'm starting to get the hang of Python, I'm starting to test my newly acquired Python skills on some problems on projecteuler.net. Anyways, at some point, I ended up making a function for getting a list of all primes up until a number 'n'. Here's how the function looks atm: ``` def primes(n): """Returns li...
**It fails for much bigger numbers**. The first prime is **71** for that the candidate can fail. The smallest failing candidate for 71 is **10986448536829734695346889** which overshadows the number 10986448536829734695346889 + 142. ``` def primes(n, skip_range=None): """Modified "primes" with the original assertio...
How to use re.sub()
13,748,674
10
2012-12-06T16:59:52Z
13,748,823
25
2012-12-06T17:08:20Z
[ "python", "regex" ]
I am doing some text normalization using python and regular expressions. I would like to substitute all 'u'or 'U's with 'you'. Here is what I have done so far: ``` import re text = 'how are u? umberella u! u. U. U@ U# u ' print re.sub (' [u|U][s,.,?,!,W,#,@ (^a-zA-Z)]', ' you ', text) ``` The output I get is: ``` ho...
Firstly, why doesn't your solution work. You mix up a lot of concepts. Mostly [character class](http://www.regular-expressions.info/charclass.html) with other ones. In the first character class you use `|` which stems from [alternation](http://www.regular-expressions.info/alternation.html). In character classes you don...
Python - split string into smaller chunks and assign a variable
13,749,701
7
2012-12-06T18:01:52Z
13,749,963
9
2012-12-06T18:17:33Z
[ "python" ]
Is it possible to split a string in python and assign each piece split off to a variable to be used later? I would like to be able to split by length if possible, but im not sure how it would work using len(). i tried this but its not getting me what i needed: ``` x = 'this is a string' x.split(' ', 1) print x ``` r...
If you'd like to access a string 3 characters at a time, you're going to need to use [slicing](http://stackoverflow.com/a/509295/600110). You can get a list of the 3-character long pieces of the string using a list comprehension like this: ``` >>> x = 'this is a string' >>> step = 3 >>> [x[i:i+step] for i in range(0,...
Receiving 'ImportError: cannot import name etree' when using lxml in Python on Mac
13,749,916
5
2012-12-06T18:14:15Z
13,750,302
10
2012-12-06T18:40:43Z
[ "python", "osx", "lxml", "importerror" ]
I'm having difficulty properly installing lxml for Python on Mac. I have followed the instructions [here](http://lxml.de/installation.html#installation), which after installation indicates that the installation is successful (however, there are some warnings. The full log of the install and warnings can be found [here]...
Sounds like you have another `lxml` in your path. Make sure you are referencing the right one, it should look something like this: ``` >>> import lxml >>> lxml <module 'lxml' from '/path/to/lib/python2.7/site-packages/lxml/__init__.pyc'> ```
How to get the first word in the string
13,750,265
14
2012-12-06T18:38:11Z
13,750,283
7
2012-12-06T18:39:17Z
[ "python", "regex" ]
text is : ``` WYATT - Ranked # 855 with 0.006 % XAVIER - Ranked # 587 with 0.013 % YONG - Ranked # 921 with 0.006 % YOUNG - Ranked # 807 with 0.007 % ``` I want to get only ``` WYATT XAVIER YONG YOUNG ``` I tried : ``` (.*)?[ ] ``` But it gives me the : ``` WYATT - Ranked ```
Use this regex ``` ^\w+ ``` --- `\w+` matches 1 to many characters. `\w` is similar to `[a-zA-Z0-9_]` `^` depicts the start of a string --- **About Your Regex** Your regex `(.*)?[ ]` should be `^(.*?)[ ]` or `^(.*?)(?=[ ])` if you don't want the space
How to get the first word in the string
13,750,265
14
2012-12-06T18:38:11Z
13,750,308
45
2012-12-06T18:41:03Z
[ "python", "regex" ]
text is : ``` WYATT - Ranked # 855 with 0.006 % XAVIER - Ranked # 587 with 0.013 % YONG - Ranked # 921 with 0.006 % YOUNG - Ranked # 807 with 0.007 % ``` I want to get only ``` WYATT XAVIER YONG YOUNG ``` I tried : ``` (.*)?[ ] ``` But it gives me the : ``` WYATT - Ranked ```
Regex is unnecessary for this. Just use `some_string.split(' ', 1)[0]` or `some_string.partition(' ')[0]`.
How can I use an app-factory in Flask / WSGI servers and why might it be unsafe?
13,751,277
3
2012-12-06T19:44:10Z
13,754,387
11
2012-12-06T23:16:59Z
[ "python", "flask", "wsgi" ]
# A question on app callables, WSGI servers and Flask circular imports I am (possibly) confused. I want to safely create Flask / WSGI apps from app-factories and still be able to use them in WSGI servers easily. tl;dr 1. Can I safely avoid creating an app on import of **init** (as recommended)and instead create i...
According to the [Flask Documentation](http://flask.pocoo.org/docs/patterns/appfactories/), an application factory is good because: > 1. Testing. You can have instances of the application with different settings to test every case. > 2. Multiple instances. Imagine you want to run different versions of the same applica...
Python - How to change values in a list of lists?
13,752,461
8
2012-12-06T20:59:52Z
13,752,595
7
2012-12-06T21:09:06Z
[ "python", "python-2.7" ]
I have a list of lists, each list within the list contains 5 items, how do I change the values of the items in the list? I have tried the following: ``` for [itemnumber, ctype, x, y, delay] in execlist: if itemnumber == mynumber: ctype = myctype x = myx y = myy ...
The problem is that you are creating a copy of the list and then modifying the copy. What you want to do is modify the original list. Try this: ``` for i in range( len( execlist ) ): if execlist[i][0] == mynumber execlist[i][1] = myctype execlist[i][2] = myx execlist[i][3] = myy ...
how a class works
13,752,925
2
2012-12-06T21:27:49Z
13,752,966
8
2012-12-06T21:30:14Z
[ "python", "class" ]
I am trying to figure out a really simple problem but still I can't quite get how a class works. For example, in case I wanted to create a class called "Friend" with an attribute called "name", does this mean I will have to give a variable called "name"before anything else ? Then how can i define the constructor to all...
That code is not nonsense as in it accomplishes what you want to accomplish. It is not very pythonic, though. There are no reason you should use getter or setters. Just access the attributes directly. Like ``` class Friend: def __init__(self,name): self.name = name ``` you can [instantiate](http://docs.p...
Invalid and/or missing SSL certificate
13,755,041
10
2012-12-07T00:22:20Z
13,771,221
10
2012-12-07T21:26:06Z
[ "python", "google-app-engine", "gae-datastore", "stocktwits" ]
I'm trying to build a datastore on Google App Engine to collect some stream data off of StockTwits for a bunch of companies. I'm basically replicating one I did with Twitter, but it's giving me an HTTPException: Invalid and/or missing SSL certificate error for one of the URLs. I changed the URL to look at another compa...
I don't know why GAE is having a problem with it, but I notice the certificate returned by api.stocktwits.com doesn't match the server name on its Subject's Common Name (which is ssl2361.cloudflare.com), but only on one of its Subject Alternative Names ("DNS Name=\*.stocktwits.com"). Maybe Subject Alternatives Names ar...
web2py - allow external access - how?
13,756,154
8
2012-12-07T02:40:25Z
13,756,698
12
2012-12-07T03:59:53Z
[ "python", "web2py" ]
I want to start a web2py server so that it can be accessed externally to the hosting server. I've read this <http://web2py.com/books/default/chapter/29/03> > By default, web2py runs its web server on 127.0.0.1:8000 (port 8000 on > localhost), but you can run it on any available IP address and port. > You can query th...
``` python web2py.py --ip 0.0.0.0 ``` just works fine but the log message will point you to an invalid address: ``` please visit: http://0.0.0.0:8000 ``` alternatively you can use ethernet interface ip but it will not listen also on localhost
Unable to use flask.g to access variables in other functions
13,757,399
4
2012-12-07T05:24:49Z
13,757,486
11
2012-12-07T05:33:26Z
[ "python", "flask" ]
I'm trying to use `flask.g` to store variables that can be accessed in other functions, but I don't seem to be doing something correctly. The application generates the following error when I try to access `g.name`: `AttributeError: '_RequestGlobals' object has no attribute 'name'`. The [documentation](http://flask.poc...
The `g` object is a request-based object and does not persist between requests, i.e. `g` is recreated between your request to `index` and your request to `get_posts`. [Application Globals in Flask](http://flask.pocoo.org/docs/api/#application-globals): > Flask provides you with a special object that ensures it **is o...
Using .join() in Python
13,757,746
3
2012-12-07T06:01:28Z
13,757,804
7
2012-12-07T06:05:45Z
[ "python" ]
Very simple and quick question. Take this list for example: ``` a = ['hello1', 'hello2', 'hello3'] ','.join(a) ``` I would like to have 'and' instead of a comma before the last element of the list. So I would get: > hello 1, hello 2 and hello 3 instead of.... > hello 1, hello 2, hello 3 Is there a way to accompli...
In essence, you want to manipulate the two parts of the list separately, the first consisting of everything except the last string, and the other consisting of just the last one. ``` def my_func(lst): return ', '.join(lst[:-1])+' and '+lst[-1] ``` or using a lambda: ``` f = lambda x: ', '.join(x[:-1]) + ' and '+...
Why do some Flask session values disappear from the session after closing the browser window, but then reappear later without me adding them?
13,760,008
6
2012-12-07T09:11:25Z
13,771,844
8
2012-12-07T22:12:24Z
[ "python", "session", "flask", "session-cookies" ]
So my understanding of Flask sessions is that I can use it like a dictionary and add values to a session by doing: session['key name'] = 'some value here' And that works fine. On a route I have the client call using AJAX post, I assign a value to the session. And it works fine. I can click on various pages of my sit...
Turns out the problem was a multiple domain cookie thing. I am running the site locally at 127.0.0.1:5000 but sometimes the site was accessed at localhost:5000 - so each of those domains had a separate cookie. Which explains why the data was disappearing and then reappearing. It was just associated with different domai...
more pythonic way to format a JSON string from a list of tuples
13,761,054
3
2012-12-07T10:16:40Z
13,761,086
11
2012-12-07T10:19:34Z
[ "python", "json", "list", "tuples" ]
Currently I'm doing this: ``` def getJSONString(lst): join = "" rs = "{" for i in lst: rs += join + '"' + str(i[0]) + '":"' + str(i[1]) + '"' join = "," return rs + "}" ``` which I call like: ``` rs = getJSONString([("name", "value"), ("name2", "value2")]) ``` It doesn't need to be n...
There is a much better way to generate JSON strings: the [`json` module](http://docs.python.org/2/library/json.html). ``` import json rs = json.dumps(dict(lst)) ``` This takes advantage of the fact that `dict()` can take a sequence of key-value pairs (two-value tuples) and turn that into a mapping, which the `json` m...
BeautifulSoup, where are you putting my HTML?
13,761,164
2
2012-12-07T10:24:11Z
15,588,247
8
2013-03-23T15:02:15Z
[ "python", "parsing", "beautifulsoup", "urllib2", "urllib" ]
I'm using BS4 with python2.7. Here's the start of my code (Thanks root): ``` from bs4 import BeautifulSoup import urllib2 f=urllib2.urlopen('http://yify-torrents.com/browse-movie') html=f.read() soup=BeautifulSoup(html) ``` When I print html, its contents are the same as the source of the page viewed in chrome. When...
I had the same problem and this solved my problem: ``` soup = BeautifulSoup(html, 'html5lib') ``` You need to install html5lib: ``` pip install html5lib ``` or ``` easy_install html5lib ``` You can read more about different parsers (pros and cons) for Beautiful Soup here: <http://www.crummy.com/software/Beautifu...
Large file not flushed to disk immediately after calling close()?
13,761,961
11
2012-12-07T11:12:52Z
13,762,137
7
2012-12-07T11:25:10Z
[ "python", "windows", "io", "python-3.x", "large-files" ]
I'm creating large file with my python script (more than `1GB`, actually there's 8 of them). Right after I create them I have to create process that will use those files. The script looks like: ``` # This is more complex function, but it basically does this: def use_file(): subprocess.call(['C:\\use_file', 'C:\\f...
`f.close()` calls `f.flush()`, which sends the data to the OS. That *doesn't* necessarily write the data to disk, because the OS buffers it. As you rightly worked out, if you want to force the OS to write it to disk, you need to `os.fsync()`. Have you considered just piping the data directly into `use_file`? --- EDI...
Python metaclass arguments
13,762,231
11
2012-12-07T11:32:07Z
13,763,534
13
2012-12-07T12:55:43Z
[ "python", "metaprogramming", "metaclass" ]
I'm trying to dynamically generate classes in python 2.7, and am wondering if you can easily pass arguments to the metaclass from the class object. I've read [this](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python) post, which is awesome, but doesn't quite answer the question. at the moment I am...
Yes, there's an easy way to do it. In the metaclass's `__new__()` method just check in the class dictionary passed as the last argument. Anything defined in the `class` statement will be there. For example: ``` class MyMetaClass(type): def __new__(cls, class_name, parents, attrs): if 'meta_args' in attrs: ...
Python metaclass arguments
13,762,231
11
2012-12-07T11:32:07Z
25,191,150
7
2014-08-07T19:57:18Z
[ "python", "metaprogramming", "metaclass" ]
I'm trying to dynamically generate classes in python 2.7, and am wondering if you can easily pass arguments to the metaclass from the class object. I've read [this](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python) post, which is awesome, but doesn't quite answer the question. at the moment I am...
While the question is for Python 2.7 and already has an excellent answer, I had the same question for Python 3.3 and this thread was the closest thing to an answer I could find with Google. I found a better solution for Python 3.x by digging through the Python documentation, and I'm sharing my findings for anyone else ...
Using Fabric to deploy current git branch to heroku
13,763,777
2
2012-12-07T13:10:37Z
13,815,837
10
2012-12-11T07:51:30Z
[ "python", "git", "heroku", "fabric" ]
I'd like to shorten the process of deploying to Heroku (i.e. a git push) I use git-flow to organise my codebase - so typically the process would be: 1. start a new feature branch 2. Do the coding 3. Push this branch up to my dev heroku instance - `git push develop feature/somefeature:master`) 4. Merge into the develo...
OK - a bit more digging got me this: ``` from fabric.api import local my_branch = local('git rev-parse --abbrev-ref HEAD', capture=True) ``` which does exactly what I wanted.
Django South - Creating initial migration for an app that has already populated tables
13,763,922
3
2012-12-07T13:19:38Z
13,764,019
12
2012-12-07T13:25:36Z
[ "python", "django", "migration", "django-south" ]
Scenario: I have an app in my Django application that I have never put under South management. I ran a syncdb a long time ago, and the models of this app have never had to change. Throughout time, I have obviously added data to those tables. Now, I wish to put this app under south management, but once the tables alrea...
[This is covered in the manual](http://south.readthedocs.org/en/latest/convertinganapp.html#converting-an-app). > Converting an app to use South is very easy: > > * Edit your settings.py and put ‘south’ into `INSTALLED_APPS` (assuming you’ve installed it to the right place) > * Run `./manage.py syncdb` to load t...
How to unzip specific folder from a .zip with Python
13,765,486
5
2012-12-07T14:53:27Z
13,765,619
10
2012-12-07T15:01:25Z
[ "python" ]
I am looking to unzip a particular folder from a .zip in Python: e.g. `archive.zip` contains the folders `foo` and `bar`, I want to unzip `foo` to a specific location, retaining it's folder structure.
Check [zipfile](http://docs.python.org/2/library/zipfile) module. For your case: ``` import zipfile archive = zipfile.ZipFile('archive.zip') for file in archive.namelist(): if file.startswith('foo/'): archive.extract(file, 'destination_path') ```
What is the naming convention for Python class references
13,765,980
17
2012-12-07T15:23:35Z
13,766,060
10
2012-12-07T15:29:16Z
[ "python", "naming-conventions", "pep8" ]
What is the naming convention for a variable referencing a class in Python? ``` class MyClass(object): pass # which one is correct? reference_to_class = MyClass # or ReferenceToClass = MyClass ``` Here is another example that resembles my situation: ``` # cars.py class Car(object): pass class Sedan(Car): ...
On module level the second. As a function argument, the first.
Rolling back the random number generator in python?
13,766,695
5
2012-12-07T16:06:10Z
13,766,717
8
2012-12-07T16:07:12Z
[ "python", "random" ]
Is it possible to 'rollback' the random number generator by a specified number of steps to a earlier state to get repeated random numbers? I want to be able to do something like this: ``` print(random.random()) 0.5112747213686085 print(random.random()) 0.4049341374504143 print(random.random()) 0.7837985890347726 ran...
You want to take a look at [`random.getstate()`](http://docs.python.org/3/library/random.html#random.getstate) and [`random.setstate()`](http://docs.python.org/3/library/random.html#random.setstate). Combine this with keeping track of the number of items generated and it's pretty simple to do what you want. Note that ...
Browser caching issues in flask
13,768,007
12
2012-12-07T17:24:56Z
13,798,135
17
2012-12-10T09:28:43Z
[ "python", "caching", "flask", "browser-cache" ]
I have built a website using flask ([www.csppdb.com](http://www.csppdb.com)). Sometimes when I log in as one user, log out, then login as another user I still see pages from the first user I logged in as. This problem is immediately fixed when the page is refreshed. I think this is called "caching" if I am not mistaken...
Setting the cache to be max-age=0 fixed it. ``` @app.after_request def add_header(response): """ Add headers to both force latest IE rendering engine or Chrome Frame, and also to cache the rendered page for 10 minutes. """ response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1' response.header...
Requests with python 3.3
13,769,514
6
2012-12-07T19:10:13Z
13,769,901
12
2012-12-07T19:39:00Z
[ "python", "pip", "python-requests" ]
How to install [Requests](http://docs.python-requests.org/en/latest/user/install/#install) to use with python 3.3. I use mac, and have both python 3.3 and 2.7.1 installed. Paths. ``` 2.7.1 : which python /usr/bin/python 3.3: /Library/Frameworks/Python.framework/Versions/3.3/bin ``` I tried these to install ``` c...
The [Cheese Shop page](http://pypi.python.org/pypi/requests) currently shows "build status failing" for version 0.14.2. And it looks like downloading this tarball and trying to build/test/install it does actually fail with 3.3. This isn't *too* surprising, since 0.14.1 was the first version to work with 3.3, and probab...
Supplying NumPy site.cfg arguments to pip
13,769,936
23
2012-12-07T19:41:04Z
13,796,808
24
2012-12-10T07:41:10Z
[ "python", "numpy", "pip", "intel-mkl" ]
I'm using NumPy built against Intel's Math Kernel Library. I use virtualenv, and typically use pip to install packages. However, in order for NumPy to find the MKL libraries, it's necessary to create a site.cfg file in the NumPy source directory prior to compiling it, then manually build and install. I could script th...
From the source (<https://github.com/numpy/numpy/blob/master/site.cfg.example>): > To assist automatic installation like easy\_install, the user's home directory > will also be checked for the file ~/.numpy-site.cfg . Is that a workable solution? You'd still need to preload the home directories with the global .numpy...
CSS Problems with Flask Web App
13,772,884
12
2012-12-07T23:55:18Z
13,773,304
21
2012-12-08T00:50:42Z
[ "python", "css", "flask" ]
I can't get the CSS to output correctly - my webpages are all unstyled. This is my link in all my templates. What am I doing wrong? ``` <link type="text/css" rel="stylesheet" href="/stylesheets/style.css"/> ``` Is there anything special that I have to do with Flask to get it to work? I've been trying and changing t...
You shouldn't need to do anything special with Flask to get CSS to work. Maybe you're putting `style.css` in `flask_project/stylesheets/`? Unless properly configured, such directories won't be served by your application. Check out the [Static Files](http://flask.pocoo.org/docs/quickstart/#static-files) section of the [...
Python URL decoding?
13,773,365
5
2012-12-08T01:00:53Z
13,773,387
7
2012-12-08T01:03:49Z
[ "javascript", "python" ]
In javascript I do the following: ``` encodeURIComponent(comments) ``` while in Python i do the following: ``` urllib2.unquote(comments) ``` For some reason, when I do the following: ``` encodedURIComponents('ø') ``` I get `%C3%B8`, but when I decode ``` urllib2.unquote('%C3%B8') ``` I get `ø` instead of `Ã...
Simply try to decode it: ``` urllib2.unquote('%C3%B8').decode('utf-8') # --> 'ø' ```
Randomness in Python
13,773,716
6
2012-12-08T02:03:28Z
13,773,730
11
2012-12-08T02:05:46Z
[ "python", "random" ]
I'm using `random.random()` to get a random float (obviously!). But what I really want to do is something like: ``` there's a 30% chance my app does this: pass else: pass ``` Can you guys help me structure this?
``` if random.random() > 0.5: # your app does this pass else: # your app does that pass ```
How can we make __future__ imports global?
13,773,861
11
2012-12-08T02:29:10Z
13,773,913
12
2012-12-08T02:38:43Z
[ "python", "python-2.7" ]
Specs: Python 2.7 I'm working on a project that has several modules, I want to activate some features from the \_\_future\_\_ module in all of them. I would like to import all the features I need on one module, and then import that single module to every other, and have those features be active in all of them, or some...
There's no way to do this in-language; you really can't make `__future__` imports global in this sense. (Well, you probably can replace the normal `import` statements with something complicated around `imp` or something. See the [Future statement](http://docs.python.org/2/reference/simple_stmts.html#future) documentati...
PyQt: Prevent Resize and Maximize in QDialog?
13,775,351
6
2012-12-08T07:02:57Z
13,775,478
16
2012-12-08T07:24:52Z
[ "python", "resize", "pyqt", "qdialog" ]
How can I prevent a QDialog in PyQt from being resizeable or maximazable? I don't what the windows size to be changed...
Use [setFixedSize](http://qt-project.org/doc/qt-4.8/qwidget.html#setFixedSize-2): ``` mydialog.setFixedSize(width, height) ```
Django 1.5b1: executing django-admin.py causes "No module named settings" error
13,775,780
4
2012-12-08T08:22:47Z
17,215,700
11
2013-06-20T14:02:45Z
[ "python", "django", "osx", "django-1.5" ]
I've recently installed Django-1.5b1. My system configuration: * OSX 10.8 * Python 2.7.1 * Virtualenv 1.7.2 When I call **django-admin.py** command I get the following error ``` (devel)ninja Django-1.5b1: django-admin.py Usage: django-admin.py subcommand [options] [args] Options: -v VERBOSITY, --verbosity=VERBOS...
I had the same issue when starting a new project. I solved the problem by giving this command at the command prompt: ``` export DJANGO_SETTINGS_MODULE= ``` in this way I unset the variable that was pointing to a "`settings`" file (discovered using `env | grep DJANGO_SETTINGS_MODULE`) I set before starting using *virt...
How are arguments passed to a function through __getattr__
13,776,504
7
2012-12-08T10:12:53Z
13,776,530
12
2012-12-08T10:15:55Z
[ "python", "function", "inheritance", "arguments", "getattr" ]
Consider the following code example (python 2.7): ``` class Parent: def __init__(self, child): self.child = child def __getattr__(self, attr): print("Calling __getattr__: "+attr) if hasattr(self.child, attr): return getattr(self.child, attr) else: raise ...
You are not printing `20` in your `__getattr__` function. The function finds the `make_statement` *attribute* on the Child instance and returns that. As it happens, that attribute is a method, so it is callable. Python thus calls the returned method, and *that* method then prints `20`. If you were to remove the `()` c...
import httplib ImportError: No module named httplib
13,778,252
20
2012-12-08T14:13:44Z
13,778,285
34
2012-12-08T14:16:21Z
[ "python", "python-3.x" ]
I got this error when run test.py ``` C:\Python32>python.exe test.py Traceback (most recent call last): File "test.py", line 5, in <module> import httplib ImportError: No module named httplib ``` How to correct it ? Code block: ``` #!/usr/local/bin/python import httplib import sys import re from HTMLParser i...
You are running Python 2 code on Python 3. In Python 3, the module has been renamed to [`http.client`](http://docs.python.org/3/library/http.client.html). You could try to run the [`2to3` tool](http://docs.python.org/2/library/2to3.html#to3-reference) on your code, and try to have it translated automatically. Referenc...
python: finding substring within a list
13,779,526
20
2012-12-08T16:45:38Z
13,779,566
34
2012-12-08T16:49:22Z
[ "python", "string", "list" ]
This is sort of working, but after hours of frustration and thoroughly searching stack I'm still getting some weird behavior. **Background:** example list: `list = ['abc123', 'def456', 'ghi789']` I want to retrieve an element if there's a match for a substring, like `abc` **Code:** ``` sub = 'abc' if any(sub in st...
``` print [s for s in list if sub in s] ``` If you want them separated by newlines: ``` print "\n".join(s for s in list if sub in s) ``` Full example, with case insensitivity: ``` mylist = ['abc123', 'def456', 'ghi789', 'ABC987', 'aBc654'] sub = 'abc' print "\n".join(s for s in mylist if sub.lower() in s.lower()) ...
Matplotlib contour from xyz data: griddata invalid index
13,781,025
4
2012-12-08T19:24:31Z
13,781,317
12
2012-12-08T19:58:10Z
[ "python", "matplotlib", "interpolation" ]
I'm trying to do a contour plot using matplotlib of a file with the following format: x1 y1 z1 x2 y2 z2 etc I can load it with numpy.loadtxt to get the vectors. So far, no trouble. I read this to learn how to plot, and can reproduce it by copy paste, so i'm sure nothin is wrong with my installation: <http://matpl...
Consider: ``` x = np.linspace(1., 10., 20) y = np.linspace(1., 10., 20) z = np.linspace(1., 2., 20) ``` This means we know the z-values at certain points along the line `x=y`. From there, ``` zi = ml.griddata(x,y,z,xi,yi) ``` is asking `mlab.griddata` to extrapolate the values of `z` for all points in a rectangula...
Replace a string in list of lists
13,781,828
4
2012-12-08T20:51:36Z
13,781,853
8
2012-12-08T20:54:25Z
[ "python", "list", "python-3.x", "replace", "nested-lists" ]
I have a list of lists of strings like: ``` example = [["string 1", "a\r\ntest string:"],["string 1", "test 2: another\r\ntest string"]] ``` I'd like to replace the `"\r\n"` with a space (and strip off the `":"` at the end for all the strings). For a normal list I would use list comprehension to strip or replace an ...
Well, think about what your original code is doing: ``` example = [x.replace('\r\n','') for x in example] ``` You're using the `.replace()` method on each element of the list as though it were a string. But each element of this list is another list! You don't want to call `.replace()` on the child list, you want to c...
lambda function in sorted dictionary list comprehension
13,781,981
4
2012-12-08T21:11:14Z
13,782,037
7
2012-12-08T21:19:08Z
[ "python", "dictionary", "lambda", "list-comprehension" ]
I have the following dictionary: ``` student_loan_portfolio = { 'loan1': {'rate': .078, 'balance': 1000, 'payment': 100, 'prepayment': 0}, 'loan2': {'rate': .0645, 'balance': 10, 'payment': 5, 'prepayment': 0}, 'loan3': {'rate': .0871, 'balance': 250, 'payment': 60, 'prepayment': 0}, 'loan4': {'rate': ...
`lambda (k,v): v['rate']` is a function that takes a single argument (a 2-tuple), and returns the `'rate'` key of the second entry in the tuple. It is equivalent to `lambda t: t[1]['rate']` `lambda x,y,z:x + y + z` is a function which takes 3 values and returns their sum. `lambda (x,y,z): x + y + z` is a function tha...
django-social-auth redirect_uri invalid
13,782,979
6
2012-12-08T23:19:24Z
13,788,571
10
2012-12-09T15:00:32Z
[ "python", "django", "django-socialauth" ]
I've been banging my head against the wall trying to get django-social-auth working. My dev server is a server in a private network at my work, accessed by a 10.0.0.\* IP Address. We have multiple django apps running on this server. Here's the config I have for this app: ``` # Perceptual location /perceptual/static/ {...
django-social-auth uses `request.build_absolute_uri()` to build that `redirect_uri` parameter. Checking django code for [`build_absolute_uri()`](https://github.com/django/django/blob/master/django/http/request.py#L100) it calls [`get_host()`](https://github.com/django/django/blob/master/django/http/request.py#L51) whic...
Finding the indices of the top three values via argmin() or min() in python/numpy without mutation of list?
13,783,071
6
2012-12-08T23:33:16Z
13,783,132
7
2012-12-08T23:42:38Z
[ "python", "list", "numpy", "min" ]
So I have this list called sumErrors that's 16000 rows and 1 column, and this list is already presorted into 5 different clusters. And what I'm doing is slicing the list for each cluster and finding the index of the minimum value in each slice. However, I can only find the first minimum index using argmin(). I don't t...
Numpy includes an [`argsort`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html) function which will return all the indices. If I understand your requirement correctly, you should be able to do: ``` minidx = [] for cluster in sumErrors: minidx.append(np.argsort(cluster)[:3]) ```
Python, how to pass an argument to a function pointer parameter?
13,783,211
16
2012-12-08T23:55:03Z
13,783,227
28
2012-12-08T23:56:54Z
[ "python", "callback", "function-pointers" ]
I only just started learning Python and found out that I can pass a function as the parameter of another function. Now if I call `foo(bar())` it will not pass as a function pointer but the return value of the used function. Calling `foo(bar)` will pass the function, but this way I am not able to pass any additional arg...
You can either use a `lambda`: ``` repeat(lambda: bar(42)) ``` Or `functools.partial`: ``` from functools import partial repeat(partial(bar, 42)) ``` Or pass the arguments separately: ``` def repeat(times, f, *args): for _ in range(times): f(*args) ``` This final style is quite common in the standard ...
Sum of list of lists; returns sum list
13,783,315
14
2012-12-09T00:09:23Z
13,783,348
7
2012-12-09T00:15:54Z
[ "python", "list", "matrix", "sum" ]
Let `data = [[3,7,2],[1,4,5],[9,8,7]]` Let's say I want to sum the elements for the indices of each list in the list, like adding numbers in a matrix column to get a single list. I am assuming that all lists in data are equal in length. ``` print foo(data) [[3,7,2], [1,4,5], [9,8,7]] _______ >>>[...
For any matrix (or other ambitious numerical) operations I would recommend looking into NumPy. The sample for solving the sum of an array along the axis shown in your question would be: ``` >>> from numpy import array >>> data = array([[3,7,2], ... [1,4,5], ... [9,8,7]]) >>> from numpy import sum >>> sum(data...
Sum of list of lists; returns sum list
13,783,315
14
2012-12-09T00:09:23Z
13,783,363
36
2012-12-09T00:18:27Z
[ "python", "list", "matrix", "sum" ]
Let `data = [[3,7,2],[1,4,5],[9,8,7]]` Let's say I want to sum the elements for the indices of each list in the list, like adding numbers in a matrix column to get a single list. I am assuming that all lists in data are equal in length. ``` print foo(data) [[3,7,2], [1,4,5], [9,8,7]] _______ >>>[...
You could try this: ``` In [9]: l = [[3,7,2],[1,4,5],[9,8,7]] In [10]: [sum(i) for i in zip(*l)] Out[10]: [13, 19, 14] ``` This uses a combination of `zip` and `*` to unpack the list and then zip the items according to their index. You then use a list comprehension to iterate through the groups of similar indices, s...
What does s.strip() do exactly?
13,783,934
2
2012-12-09T01:52:53Z
13,783,937
7
2012-12-09T01:54:05Z
[ "python" ]
I was told it deletes whitespace but ``` s = "ss asdas vsadsafas asfasasgas" print(s.strip()) ``` prints out ``` ss asdas vsadsafas asfasasgas ``` shouldn't it be `ssasdasvsadsafasasfasasgas`?
You should perhaps check out the docs for the function. It trims leading and trailing whitespace. `" ss ss ".strip()` becomes `"ss ss"` Relevant link: <http://docs.python.org/2/library/stdtypes.html#str.strip> Additionally, there is a very powerful tool within the Python interactive interpreter - you can do something...
Creating an empty Pandas DataFrame, then filling it?
13,784,192
77
2012-12-09T02:50:38Z
13,786,327
72
2012-12-09T09:40:46Z
[ "python", "dataframe", "pandas" ]
I'm starting from the pandas Data Frame docs here: <http://pandas.pydata.org/pandas-docs/stable/dsintro.html> I'd like to iteratively fill the Data Frame with values in a time series kind of calculation. So basically, I'd like to initialize, data frame with columns A,B and timestamp rows, all 0 or all NaN. I'd then a...
Here's a couple of suggestions: Use [`date_range`](http://pandas.pydata.org/pandas-docs/dev/timeseries.html) for the index: ``` import datetime import pandas as pd import numpy as np todays_date = datetime.datetime.now().date() index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D') columns ...
Matplotlib 2 Subplots, 1 Colorbar
13,784,201
79
2012-12-09T02:52:45Z
13,784,887
128
2012-12-09T05:20:00Z
[ "python", "matplotlib", "subplot", "colorbar" ]
I've spent entirely too long researching how to get two subplots to share the same y-axis with a single colorbar shared between the two in Matplotlib. What was happening was that when I called the `colorbar()` function in either `subplot1` or `subplot2`, it would autoscale the plot such that the colorbar plus the plot...
Just place the colorbar in its own axis and use `subplots_adjust` to make room for it. As a quick example: ``` import numpy as np import matplotlib.pyplot as plt fig, axes = plt.subplots(nrows=2, ncols=2) for ax in axes.flat: im = ax.imshow(np.random.random((10,10)), vmin=0, vmax=1) fig.subplots_adjust(right=0....
Matplotlib 2 Subplots, 1 Colorbar
13,784,201
79
2012-12-09T02:52:45Z
21,304,001
30
2014-01-23T09:22:27Z
[ "python", "matplotlib", "subplot", "colorbar" ]
I've spent entirely too long researching how to get two subplots to share the same y-axis with a single colorbar shared between the two in Matplotlib. What was happening was that when I called the `colorbar()` function in either `subplot1` or `subplot2`, it would autoscale the plot such that the colorbar plus the plot...
Using `make_axes` is even easier and gives a better result. It also provides possibilities to customise the positioning of the colorbar. Also note the option of `subplots` to share x and y axes. ``` import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl fig, axes = plt.subplots(nrows=2, ncols=2, ...
Matplotlib 2 Subplots, 1 Colorbar
13,784,201
79
2012-12-09T02:52:45Z
23,795,901
30
2014-05-22T00:19:07Z
[ "python", "matplotlib", "subplot", "colorbar" ]
I've spent entirely too long researching how to get two subplots to share the same y-axis with a single colorbar shared between the two in Matplotlib. What was happening was that when I called the `colorbar()` function in either `subplot1` or `subplot2`, it would autoscale the plot such that the colorbar plus the plot...
You can simplify Joe Kington's code using the `ax`parameter of `figure.colorbar()` with a list of axes. From [the documentation](http://matplotlib.org/api/figure_api.html): > ax > > > None | parent axes object(s) from which space for a new colorbar axes will be stolen. If a list of axes is given they will all be resiz...
How To Run Postgres locally
13,784,340
4
2012-12-09T03:27:38Z
13,786,824
16
2012-12-09T11:01:05Z
[ "python", "postgresql", "heroku", "flask" ]
I read the Postgres docs for Flask and they said that to run Postgres you should have the following code ``` app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = postgresql://localhost/[YOUR_DB_NAME]' db = SQLAlchemy(app) ``` How do I know my database name? I wrote db as the name - but I got an error ``...
First step, is to get Flask + Postgresql running locally, and the first step to do *that* is to [install postgresql on your machine](http://wiki.postgresql.org/wiki/Detailed_installation_guides). Next, you should install the [python drivers for postgresql](http://www.initd.org/psycopg/). For Windows, you can use the [...
Are you allowed to modify func_defaults (__defaults__ in Python 3.x) in Python?
13,784,840
5
2012-12-09T05:09:57Z
13,784,871
9
2012-12-09T05:16:38Z
[ "python" ]
I've tried doing this in Python 2.6, and it does "work": ``` >>> def f(i='I'): return i ... >>> f.func_defaults = (10,) >>> f() 10 ``` But is this officially specified behavior, or am I hitting an implementation-specific behavior?
In [the documentation](http://docs.python.org/2/reference/datamodel.html) `func_defaults` is documented as "writable", so it would seem to be defined behavior.
Python probability
13,785,349
3
2012-12-09T06:44:33Z
13,785,384
7
2012-12-09T06:52:23Z
[ "python", "math", "probability" ]
We have a six sided die, with sides numbered 1 through 6. The probability of first seeing a 1 on the n-th roll decreases as n increases. I want to find the smallest number of rolls such that this probability is less than some given limit. ``` def probTest(limit): prob = 1.0 n = 1 while prob > limit: ...
The probably of rolling a one on the nth roll is 5/6^(n-1)\*1/6, not 1/6^n. 1/6^n is the probability of rolling one on *all* n rolls. The first n-1 rolls each have a 5/6 chance of not being one. The nth roll has a 1/6th chance of being one.
How do I override constructor parameters in Sphinx with autodoc?
13,786,030
6
2012-12-09T08:58:55Z
13,819,156
9
2012-12-11T11:13:30Z
[ "python", "python-sphinx" ]
Let's say I have a class like this: ``` class MyClass(object): """ Summary docs for my class. Extended documentation for my class. """ def __init__(self, *args): self.values = np.asarray(args) ``` If I use Sphinx with the `autodoc` extension to document this class like so: ``` .. automodule...
I think that the best option for you is to do something like this: ``` .. automodule:: mymodule :members: :exclude-members: MyClass .. autoclass:: MyClass(first, second, third) ``` `MyClass` will have params overwritten and other members of `mymodule` will be autodocumented. You need to exclude `MyClass`...
Regression on stock data using pandas and matplotlib
13,786,209
3
2012-12-09T09:23:54Z
13,787,487
7
2012-12-09T12:49:00Z
[ "python", "matplotlib", "pandas", "statsmodels" ]
I'd like to plot what Excel calls an "Exponential Trend/Regression" on a stock chart. When I run the code below in the IPython notebook it simply says "The kernel has died, would you like to restart it?". Any ideas on how to fix it? Also, this is just attempting to do a linear regression and I'm not quite sure how to d...
I took another look at this and realized that my previous answer fit poorly since it didn't include an intercept. I've updated my answer. The segfault comes from trying to us the Datetime index as the exogenous variable. Instead try: ``` import datetime import matplotlib.pyplot as plt import statsmodels.api as sm imp...
python subprocess.call() "no such file or directory"
13,786,797
13
2012-12-09T10:54:50Z
13,786,947
7
2012-12-09T11:23:40Z
[ "python", "subprocess", "tcsh" ]
I've found a few questions on the module but the more common problem seems to be getting the argument list right which I think I have managed (eventually) I am trying to run a program that expects an input like this in the command line, ``` fits2ndf in out ``` with 'in' being the filepath of the file to be converted...
`which fits2ndf` will show you the path of fits2ndf. After that you can write given full path to your code and it should work. Ex: ``` ~$ which mv /bin/mv ``` My python code: ``` import subprocess subprocess.call(["/bin/mv","/tmp/a","/tmp/b"]) ```
PyCrypto install error on Windows
13,787,258
10
2012-12-09T12:09:12Z
13,787,598
12
2012-12-09T13:04:37Z
[ "python", "python-3.x", "distutils", "pycrypto" ]
I am trying to install [PyCrypto 2.6](http://pypi.python.org/pypi/pycrypto/2.6) Library on my computer. But I keep getting the following error ``` D:\Software\Python\package\pycrypto-2.6>python setup.py build running build running build_py running build_ext warning: GMP or MPIR library not found; Not building Crypto.P...
I managed to install PyCrypto 2.6 by using the [prebuilt binary for Python3.3](http://www.voidspace.org.uk/downloads/pycrypto26/pycrypto-2.6.win-amd64-py3.3.exe) from [The Voidspace Python Modules](http://www.voidspace.org.uk/python/modules.shtml#pycrypto). It doesn't actually fix the `error: Unable to find vcvarsall....
How to view legend next to matplotlib?
13,787,275
4
2012-12-09T12:12:04Z
13,787,874
7
2012-12-09T13:37:39Z
[ "python", "matplotlib" ]
I've got a plot in matplotlib, which has a lot of lines. I've got a legend which is therefore rather extensive and I placed it next to my plot using the following code: ``` fontP = FontProperties() fontP.set_size('small') plt.legend(variablelist, loc=0, prop = fontP, bbox_to_anchor=(1.0, 1.0)) plt.savefig(filename+'.p...
Almost there now, just add a new parameter in `savefig`: `bbox_inches = 'tight'`. That makes matplotlib figure out the needed size for your plot.