title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
How to specify table relationships in SQLAlchemy with multi-level/multiple joins?
22,229,099
7
2014-03-06T15:39:41Z
22,243,575
7
2014-03-07T06:55:50Z
[ "python", "sqlalchemy", "flask", "flask-sqlalchemy" ]
I'm trying to define a relationship between two tables whose relations are indirect (i.e. through two other tables). The results I'm looking for can be fetched with this query: ``` (db.session.query(Telnum) .filter(Account.customer==customer) .filter(Account.account_id == Subscription.account_id...
In general, I would not define an *indirect* relationship as a `relationship`, because you risk these *indirect* relationships becoming out-of-sync when you make modifications. You might work-around some of these limitations by specifying the [`viewonly=False`](http://docs.sqlalchemy.org/en/rel_0_9/orm/relationships.ht...
Reading 4 byte integers from binary file in Python
22,229,229
2
2014-03-06T15:44:25Z
22,229,297
9
2014-03-06T15:47:41Z
[ "python", "python-2.7" ]
I have a some sets of binary files (some are potentially large (100MB)) that contain 4 byte integers. Can anyone supply a code snippet to show how to extract each 4 byte integer until the end of the file is reached? Using Python 2.7. Thanks
You could use [`struct.unpack()`](http://docs.python.org/2/library/struct.html#struct.unpack): ``` with open(filename, 'rb') as fileobj: for chunk in iter(lambda: fileobj.read(4), ''): integer_value = struct.unpack('<I', chunk)[0] ``` This uses `<I` to interpret the bytes as little-endian unsigned integer...
Confusing with the usage of regex in Python
22,229,255
15
2014-03-06T15:45:16Z
22,229,642
15
2014-03-06T16:01:17Z
[ "python", "regex" ]
I'm confused with the following three patterns, would someone explain it in more detail? ``` ## IPython with Python 2.7.3 In [62]: re.findall(r'[a-z]*',"f233op") Out[62]: ['f', '', '', '', 'op', ''] ## why does the last '' come out? In [63]: re.findall(r'([a-z])*',"f233op") Out[63]: ['f', '', '', '', 'p', ''] ## wh...
### Example 1 ``` re.findall(r'[a-z]*',"f233op") ``` This pattern is matching zero-or-more instances of lower case alphabet characters. The ZERO-or-more part is key here, since a match of nothing, starting from every index position in the string, is just as valid as a match of `f` or `op`. The last empty string retur...
Pandas: change data type of Series to String
22,231,592
6
2014-03-06T17:24:23Z
22,231,860
13
2014-03-06T17:36:09Z
[ "python", "pandas", "series" ]
I use Pandas 'ver 0.12.0' with Python 2.7 and have a dataframe as below: ``` df = pd.DataFrame({'id' : [123,512,'zhub1', 12354.3, 129, 753, 295, 610], 'colour': ['black', 'white','white','white', 'black', 'black', 'white', 'white'], 'shape': ['round',...
You can convert all elements of id to `str` using `apply` ``` df.id.apply(str) 0 123 1 512 2 zhub1 3 12354.3 4 129 5 753 6 295 7 610 ``` **Edit by OP:** I think the issue was related to the Python version (2.7.), this worked: ``` df['id'].astype(basestring) 0 ...
Pandas: drop a level from a multi-level column index?
22,233,488
46
2014-03-06T18:58:06Z
22,233,719
60
2014-03-06T19:08:47Z
[ "python", "pandas" ]
If I've got a multi-level column index: ``` >>> cols = pd.MultiIndex.from_tuples([("a", "b"), ("a", "c")]) >>> pd.DataFrame([[1,2], [3,4]], columns=cols) ``` ``` a ---+-- b | c --+---+-- 0 | 1 | 2 1 | 3 | 4 ``` How can I drop the "a" level of that index, so I end up with: ``` b | c --+---+-- 0 | 1 | ...
You can use [`MultiIndex.droplevel`](http://pandas.pydata.org/pandas-docs/version/0.18.0/generated/pandas.MultiIndex.droplevel.html): ``` >>> cols = pd.MultiIndex.from_tuples([("a", "b"), ("a", "c")]) >>> df = pd.DataFrame([[1,2], [3,4]], columns=cols) >>> df a b c 0 1 2 1 3 4 [2 rows x 2 columns] >>> d...
Pandas: drop a level from a multi-level column index?
22,233,488
46
2014-03-06T18:58:06Z
30,991,980
8
2015-06-23T00:29:18Z
[ "python", "pandas" ]
If I've got a multi-level column index: ``` >>> cols = pd.MultiIndex.from_tuples([("a", "b"), ("a", "c")]) >>> pd.DataFrame([[1,2], [3,4]], columns=cols) ``` ``` a ---+-- b | c --+---+-- 0 | 1 | 2 1 | 3 | 4 ``` How can I drop the "a" level of that index, so I end up with: ``` b | c --+---+-- 0 | 1 | ...
You could also achieve that by renaming the columns: `df.columns = ['a', 'b']` This involves a manual step but could be an option especially if you would eventually rename your data frame.
Ignoring missing values in multiple OLS regression with statsmodels
22,234,589
2
2014-03-06T19:55:46Z
22,235,800
8
2014-03-06T20:57:55Z
[ "python", "regression", "statsmodels" ]
I'm trying to run a multiple OLS regression using statsmodels and a pandas dataframe. There are missing values in different columns for different rows, and I keep getting the error message: ValueError: array must not contain infs or NaNs I saw this SO question, which is similar but doesn't exactly answer my question: [...
You answered your own question. Just pass ``` missing = 'drop' ``` to ols ``` import statsmodels.formula.api as smf ... results = smf.ols(formula = "da ~ cfo + rm_proxy + cpi + year", data=df, missing='drop').fit() ``` If this doesn't work then it's a bug and please report it with a MWE on github....
Calculate summary statistics of columns in dataframe
22,235,245
12
2014-03-06T20:28:56Z
22,235,393
31
2014-03-06T20:36:18Z
[ "python", "csv", "pandas", "dataframe" ]
I have a dataframe of the following form (for example) ``` shopper_num,is_martian,number_of_items,count_pineapples,birth_country,tranpsortation_method 1,FALSE,0,0,MX, 2,FALSE,1,0,MX, 3,FALSE,0,0,MX, 4,FALSE,22,0,MX, 5,FALSE,0,0,MX, 6,FALSE,0,0,MX, 7,FALSE,5,0,MX, 8,FALSE,0,0,MX, 9,FALSE,4,0,MX, 10,FALSE,2,0,MX, 11,FAL...
[`describe`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.describe.html#pandas.DataFrame.describe) may give you everything you want otherwise you can perform aggregations using groupby and pass a list of agg functions: <http://pandas.pydata.org/pandas-docs/stable/groupby.html#applying-multiple...
NumPy - What is the difference between frombuffer and fromstring?
22,236,749
6
2014-03-06T21:46:57Z
22,237,279
8
2014-03-06T22:15:51Z
[ "python", "numpy" ]
They appear to give the same result to me: ``` In [32]: s Out[32]: '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x15\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0...
From a practical standpoint, the difference is that: ``` x = np.fromstring(s, dtype='int8') ``` Will make a copy of the string in memory, while: ``` x = np.frombuffer(s, dtype='int8') ``` or ``` x = np.frombuffer(buffer(s), dtype='int8') ``` Will use the memory buffer of the string directly and won't use any\* ad...
Validating URLs in Python
22,238,090
4
2014-03-06T23:04:25Z
22,238,205
11
2014-03-06T23:12:21Z
[ "python", "url", "url-validation" ]
I've been trying to figure out what the best way to validate a URL is (specifically in Python) but haven't really been able to find an answer. It seems like there isn't one known way to validate a URL, and it depends on what URLs you think you may need to validate. As well, I found it difficult to find an easy to read ...
This looks like it might be a duplicate of [How do you validate a URL with a regular expression in Python?](http://stackoverflow.com/questions/827557/how-do-you-validate-a-url-with-a-regular-expression-in-python) (I would make a comment, but I don't have enough reputation). You should be able to use the urlparse libr...
Jinja2 if statement in vs equals on dict
22,238,265
2
2014-03-06T23:19:02Z
22,238,519
8
2014-03-06T23:38:27Z
[ "python", "if-statement", "jinja2" ]
I'm new to Jinja2 and using it as part of Flask. I've got two statements below. The one with "in" works. The one with "equals" isn't. The equals version is getting a syntax error shown below. I'm curious as to why, as the way the equals version is written, to me at least, is easier to read. ``` {% if "SN" in P01["type...
In Jinja2 you would use `==` instead of `equals`, for example: ``` {% if P01["type"] == "SN" %} {% include 'sn.html' %} {% endif %} ``` <http://jinja.pocoo.org/docs/switching/#conditions> I'm pretty sure this is what you are looking for, but you should note that this has a different meaning than `"SN" in P01["type...
How to do a clean reinstall with macports?
22,238,561
5
2014-03-06T23:41:40Z
27,784,713
8
2015-01-05T17:30:02Z
[ "python", "osx", "macports" ]
How can one do a complete clean reinstall of a port and at the same time a complete clean reinstall of all its dependenceis?
From the MacPorts wiki (migration): <https://trac.macports.org/wiki/Migration> After having saved a list of installed ports using: ``` port -qv installed > myports.txt ``` and having removed them with: ``` sudo port -f uninstall installed ``` Download and execute the restore\_ports script. (If you installed MacPo...
Code for line of best fit of a scatter plot in python
22,239,691
10
2014-03-07T01:28:18Z
23,377,802
12
2014-04-30T00:47:12Z
[ "python", "plot" ]
Below is my code for scatter plotting the data in my text file. The file I am opening contains two columns. The left column is x coordinates and the right column is y coordinates. the code creates a scatter plot of x vs. y. I need a code to overplot a line of best fit to the data in the scatter plot, and none of the bu...
You can use numpy's polyfit. I use the following (you can safely remove the bit about coefficient of determination and error bounds, I just think it looks nice): ``` #!/usr/bin/python3 import numpy as np import matplotlib.pyplot as plt import csv with open("example.csv", "r") as f: data = [row for row in csv.rea...
Code for line of best fit of a scatter plot in python
22,239,691
10
2014-03-07T01:28:18Z
31,800,660
16
2015-08-04T04:22:14Z
[ "python", "plot" ]
Below is my code for scatter plotting the data in my text file. The file I am opening contains two columns. The left column is x coordinates and the right column is y coordinates. the code creates a scatter plot of x vs. y. I need a code to overplot a line of best fit to the data in the scatter plot, and none of the bu...
A one-line version of [this excellent answer](http://stackoverflow.com/a/19069001/1397061) to plot the line of best fit is: ``` plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x))) ``` Using `np.unique(x)` instead of `x` handles the case where `x` isn't sorted or has duplicate values.
Least-Squares Fit to a Straight Line python code
22,240,280
4
2014-03-07T02:27:46Z
23,260,978
7
2014-04-24T06:02:57Z
[ "python", "plot" ]
I have a scatter plot composed of X and Y coordinates. I want to use the Least-Squares Fit to a Straight Line to obtain the line of best fit. The Least-Squares Fit to a Straight Line refers to: If(x\_1,y\_1),....(x\_n,y\_n) are measured pairs of data, then the best straight line is y = A + Bx. Here is my code in pyth...
Simplest if you just want a line is `scipy.stats.linregress`: ``` >>> from scipy import stats >>> slope, intercept, r_value, p_value, std_err = stats.linregress(x,y) ``` [Link to docs](http://docs.scipy.org/doc/scipy-0.13.0/reference/generated/scipy.stats.linregress.html)
How do I check if all elements in a list are the same?
22,240,602
3
2014-03-07T03:01:48Z
22,240,612
12
2014-03-07T03:02:58Z
[ "python", "list", "python-2.7" ]
If i have this list; ``` mylist = ['n', 'n', '4', '3', 'w'] ``` How do I get it to read the list, and tell me whether or not they are all the same? I am aware that it is easy to tell they are not all the same in this example. I have much larger lists I would like it to read for me. Would I go about this using: ```...
You can use set like this ``` len(set(mylist)) == 1 ``` **Explanation** sets store only unique items in them. So, we try and convert the list to a set. After the conversion, if the set has more than one element in it, it means that not all the elements of the list are the same. **Note:** If the list has unhashable ...
Execution of Python code with -m option or not
22,241,420
13
2014-03-07T04:25:38Z
22,250,157
14
2014-03-07T12:30:22Z
[ "python", "module", "package" ]
The python interpreter has `-m` *module* option that "Runs library module *module* as a script". With this python code a.py: ``` if __name__ == "__main__": print __package__ print __name__ ``` I tested `python -m a` to get ``` "" <-- Empty String __main__ ``` whereas `python a.py` returns ``` None <-- Non...
When you use the [`-m` command-line flag](http://docs.python.org/2/using/cmdline.html#cmdoption-m), Python will import a module *or package* for you, then run it as a script. When you don't use the `-m` flag, the file you named is run as *just a script*. The distinction is important when you try to run a package. Ther...
What does self = None do?
22,245,002
22
2014-03-07T08:24:21Z
22,245,059
23
2014-03-07T08:27:45Z
[ "python", "garbage-collection", "python-internals", "python-asyncio" ]
I'm reading [the source code of the incoming `asyncio` package](http://code.google.com/p/tulip/source/browse/asyncio/events.py#37). Note that at the end of the method, there is a `self = None` statement. What does it do? ``` def _run(self): try: self._callback(*self._args) except Exception as exc: ...
It simply clears the local reference to `self`, making sure that if an exception occurs the reference passed to `self._loop.call_exception_handler()` is the only remaining reference and no cycle has been created. This is still needed here because the local namespace is referenced by the exception traceback; it will **...
How to lowercase a python dataframe string column if it has missing values?
22,245,171
12
2014-03-07T08:34:49Z
22,247,593
29
2014-03-07T10:30:48Z
[ "python", "string", "pandas", "missing-data" ]
The following code does not work. ``` import pandas as pd import numpy as np df=pd.DataFrame(['ONE','Two', np.nan],columns=['x']) xLower = df["x"].map(lambda x: x.lower()) ``` How should I tweak it to get xLower = ['one','two',np.nan] ? Efficiency is important since the real data frame is huge.
use pandas [vectorized string methods](http://pandas.pydata.org/pandas-docs/stable/basics.html#vectorized-string-methods); as in the documentation: > these methods exclude missing/NA values automatically `.str.lower()` is the very first example there; ``` >>> df['x'].str.lower() 0 one 1 two 2 NaN Name: x, d...
from ... import OR import ... as for modules
22,245,711
11
2014-03-07T09:05:14Z
22,245,722
11
2014-03-07T09:05:40Z
[ "python", "import", "module" ]
Should I use ``` from foo import bar ``` OR ``` import foo.bar as bar ``` when **importing a module** and and there is **no need/wish for changing the name** (`bar`)? Are there any differences? Does it matter?
Assuming that `bar` is a module or package in `foo`, there is no difference, it doesn't matter. The two statements have exactly the same result: ``` >>> import os.path as path >>> path <module 'posixpath' from '/Users/mj/Development/venvs/stackoverflow-2.7/lib/python2.7/posixpath.pyc'> >>> from os import path >>> path...
Efficient way of inputting large raster data into PyTables
22,250,197
10
2014-03-07T12:31:58Z
24,718,084
7
2014-07-12T23:04:17Z
[ "python", "numpy", "scipy", "gdal", "pytables" ]
I am looking for the efficient way to feed up the raster data file (GeoTiff) with 20GB size into PyTables for further out of core computation. Currently I am reading it as numpy array using Gdal, and writing the numpy array into pytables using the code below: ``` import gdal, numpy as np, tables as tb inraster = gda...
I do not have a geotiff file, so I fiddled around with a normal tif file. You may have to omit the 3 in the shape and the slice in the writing if the data to the pytables file. Essentially, I loop over the array without reading everything into memory in one go. You have to adjust n\_chunks so the chunksize that gets re...
Stop pip from failing on single package when installing with requirements.txt
22,250,483
18
2014-03-07T12:46:28Z
28,795,395
12
2015-03-01T15:35:40Z
[ "python", "pip" ]
I am installing packages from requirements.txt > pip install -r requirements.txt The requirements.txt file reads: ``` Pillow lxml cssselect jieba beautifulsoup nltk ``` `lxml` is the only package failing to install and this leads to everything failing (expected results as pointed out by larsks in the comments). How...
Running each line with `pip install` may be a workaround. ``` xargs -a requirements.txt -n 1 pip install ```
How to limit Flask dev server to only one visiting ip address
22,251,038
3
2014-03-07T13:11:58Z
22,251,171
11
2014-03-07T13:18:17Z
[ "python", "flask", "ip-address" ]
I'm developing a website using the Python [Flask framework](http://flask.pocoo.org/) and I now do some devving, pushing my changes to a remote dev server. I set this remote dev server up to serve the website publically using `app.run(host='0.0.0.0')`. This works fine, but I just don't want other people to view my webs...
Using *just* the features of Flask, you could use a [`before_request()` hook](https://flask.readthedocs.org/en/latest/api/#flask.Flask.before_request) testing the [`request.remote_addr` attribute](http://werkzeug.pocoo.org/docs/wrappers/#werkzeug.wrappers.BaseRequest.remote_addr): ``` from flask import abort, request ...
ImportError: No module named MySQLdb
22,252,397
34
2014-03-07T14:12:16Z
22,252,975
58
2014-03-07T14:36:13Z
[ "python", "mysql", "flask", "mysql-python" ]
I am referring the following tutorial to make a login page for my web application. <http://code.tutsplus.com/tutorials/intro-to-flask-signing-in-and-out--net-29982> I am having issue with the database. I am getting an ``` ImportError: No module named MySQLdb ``` when I execute ``` http://127.0.0.1:5000/testdb ``` ...
If you're having issues compiling the binary extension, or on a platform where you cant, you can try using the pure python [`PyMySQL`](https://github.com/PyMySQL/PyMySQL) bindings. Simply `pip install pymysql` and switch your SQLAlchemy URI to start like this: ``` SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://.....' ```...
ImportError: No module named MySQLdb
22,252,397
34
2014-03-07T14:12:16Z
24,364,863
42
2014-06-23T11:33:57Z
[ "python", "mysql", "flask", "mysql-python" ]
I am referring the following tutorial to make a login page for my web application. <http://code.tutsplus.com/tutorials/intro-to-flask-signing-in-and-out--net-29982> I am having issue with the database. I am getting an ``` ImportError: No module named MySQLdb ``` when I execute ``` http://127.0.0.1:5000/testdb ``` ...
Or try this: ``` apt-get install python-mysqldb ```
ImportError: No module named MySQLdb
22,252,397
34
2014-03-07T14:12:16Z
27,973,420
9
2015-01-15T21:36:36Z
[ "python", "mysql", "flask", "mysql-python" ]
I am referring the following tutorial to make a login page for my web application. <http://code.tutsplus.com/tutorials/intro-to-flask-signing-in-and-out--net-29982> I am having issue with the database. I am getting an ``` ImportError: No module named MySQLdb ``` when I execute ``` http://127.0.0.1:5000/testdb ``` ...
I got this issue when I was working on SQLAlchemy. The default dialect used by SQLAlchemy for MySQL is `mysql+mysqldb`. ``` engine = create_engine('mysql+mysqldb://scott:tiger@localhost/foo') ``` I got the "`No module named MySQLdb`" error when the above command was executed. To fix it I installed the `mysql-python` ...
Iterate through list of dictionary and create new list of dictionary
22,253,055
4
2014-03-07T14:39:24Z
22,253,086
8
2014-03-07T14:40:42Z
[ "python", "dictionary" ]
My data is as follows. ``` [ { "id" : "123", "type" : "process", "entity" : "abc" }, { "id" : "456", "type" : "product", "entity" : "ab" } ] ``` I am looping though it as follows to get id and entity ``` for test in serializer.data: qaResultUnique[...
You are reusing the `qaResultUnique` dictionary object. Create a *new* dictionary in the loop each time: ``` for test in serializer.data: qaResultUnique = {} qaResultUnique['id'] = test['id'] qaResultUnique['entity'] = test['entity'] uniqueList.append(qaResultUnique) ``` or more succinctly expressed: ...
Mayavi points3d with different size and colors
22,253,298
7
2014-03-07T14:49:24Z
22,385,777
7
2014-03-13T17:03:00Z
[ "python", "data-visualization", "vtk", "mayavi" ]
Is it possible in mayavi to specify individually both the size and the colors of every point? That API is cumbersome to me. ``` points3d(x, y, z...) points3d(x, y, z, s, ...) points3d(x, y, z, f, ...) x, y and z are numpy arrays, or lists, all of the same shape, giving the positions of the points. If only 3 arrays x...
Each VTK source has a dataset for both scalars and vectors. The trick I use in my program to getting the color and size to differ is to bypass the mayavi source and directly in the VTK source, use scalars for color and vectors for size (it probably works the other way around as well). This is pretty much without doubt...
Python: understanding (None for g in g if (yield from g) and False)
22,254,986
19
2014-03-07T16:07:27Z
22,255,146
10
2014-03-07T16:14:23Z
[ "python" ]
James Powell, in his short description for an upcoming presentation, says he is the proud inventor of one of the gnarliest Python one-liners: ``` (None for g in g if (yield from g) and False) ``` I am trying to figure out this generator, and since I live with Python 2.7.x, I'm also tripping over the `(yield from g)` ...
This expression seems to be a code-golf way of writing: ``` (a for b in g for a in b) ``` ((Or maybe the motivation be taking advantage of generator delegations, but IMHO readability really suffers.)) For example: ``` #! /usr/bin/python3.3 g = ['abc', 'def', 'ghi'] a = (None for g in g if (yield from g) and False...
Homebrew brew doctor warning about /Library/Frameworks/Python.framework, even with brew's Python installed
22,255,579
48
2014-03-07T16:33:44Z
22,265,200
22
2014-03-08T04:50:13Z
[ "python", "osx", "python-2.7", "homebrew", "brew-doctor" ]
When I ran **Homebrew's** `brew doctor` (Mac OS X 10.9.2), I get the following warning message: > Warning: Python is installed at /Library/Frameworks/Python.framework > > Homebrew only supports building against the System-provided Python or > a brewed Python. In particular, Pythons installed to /Library can > interfer...
I had the same problem. When I upgraded python3 through Homebrew, I started getting this: ``` -bash: python3: command not found ``` I had the same conflict with Python somehow being installed in `/Library/Framework/Python.framework`. I just did a `brew link overwrite` and everything is working fine now. There is some...
Homebrew brew doctor warning about /Library/Frameworks/Python.framework, even with brew's Python installed
22,255,579
48
2014-03-07T16:33:44Z
22,355,720
26
2014-03-12T15:09:50Z
[ "python", "osx", "python-2.7", "homebrew", "brew-doctor" ]
When I ran **Homebrew's** `brew doctor` (Mac OS X 10.9.2), I get the following warning message: > Warning: Python is installed at /Library/Frameworks/Python.framework > > Homebrew only supports building against the System-provided Python or > a brewed Python. In particular, Pythons installed to /Library can > interfer...
I also received this message. Something, sometime installed > /Library/Frameworks/Python.framework on my machine (the folder date was about 4 years old). I've chosen to remove it. Please note that the Apple provided framework lives in > /System/Library/Frameworks/Python.framework/
Homebrew brew doctor warning about /Library/Frameworks/Python.framework, even with brew's Python installed
22,255,579
48
2014-03-07T16:33:44Z
24,622,389
16
2014-07-08T01:30:38Z
[ "python", "osx", "python-2.7", "homebrew", "brew-doctor" ]
When I ran **Homebrew's** `brew doctor` (Mac OS X 10.9.2), I get the following warning message: > Warning: Python is installed at /Library/Frameworks/Python.framework > > Homebrew only supports building against the System-provided Python or > a brewed Python. In particular, Pythons installed to /Library can > interfer...
per [this thread](https://github.com/Homebrew/homebrew/issues/27146), enter this command: `sudo rm -rf /Library/Frameworks/Python.framework` because there are multiple installations of Python on your computer, and this removes the one that may cause additional problems in the future.
Get all keys in Redis database with python
22,255,589
9
2014-03-07T16:34:19Z
22,255,608
14
2014-03-07T16:35:43Z
[ "python", "database", "redis" ]
There is a post about a Redis command to get all available keys, but I would like to do it with Python. Any way to do this?
Yes, use [`keys()`](http://redis-py.readthedocs.org/en/latest/#redis.StrictRedis.keys) from the StrictRedis module: ``` >>> import redis >>> r = redis.StrictRedis(host=YOUR_HOST, port=YOUR_PORT, db=YOUR_DB) >>> r.keys() ``` Giving a null pattern will fetch all of them. As per the page linked: > keys(pattern='\*') > ...
Get all keys in Redis database with python
22,255,589
9
2014-03-07T16:34:19Z
34,166,690
8
2015-12-08T21:50:39Z
[ "python", "database", "redis" ]
There is a post about a Redis command to get all available keys, but I would like to do it with Python. Any way to do this?
I find SCAN to be a better command because it gives you an iterator you can use rather than trying to load all the KEYS into memory. I had a 1B records in my redis and I could never get enough memory to return all the keys at once. Here is a python snippet to get all keys from the store matching a pattern and delete t...
converting each element of list to tuple
22,256,366
2
2014-03-07T17:11:05Z
22,256,388
8
2014-03-07T17:11:57Z
[ "python", "list", "tuples" ]
I to convert each element of list to tuple like following : ``` l = ['abc','xyz','test'] ``` convert to tuple list: ``` newl = [('abc',),('xyz',),('test',)] ``` Actually I have dict with keys like this so for searching purpose I need to have these, Thanks in advance
You can use a [list comprehension](http://docs.python.org/3/tutorial/datastructures.html#list-comprehensions): ``` >>> l = ['abc','xyz','test'] >>> [(x,) for x in l] [('abc',), ('xyz',), ('test',)] >>> ``` --- Or, if you are on Python 2.x, you could just use [`zip`](http://docs.python.org/2/library/functions.html#zi...
How do I reverse a sublist in a list in place?
22,257,249
3
2014-03-07T17:53:28Z
22,257,860
8
2014-03-07T18:26:39Z
[ "python", "list", "function", "sublist" ]
I'm supposed to create a function, which input is a list and two numbers, the function reverses the sublist which its place is indicated by the two numbers. for example this is what it's supposed to do: ``` >>> lst = [1, 2, 3, 4, 5] >>> reverse_sublist (lst,0,4) >>> lst [4, 3, 2, 1, 5] ``` I created a function and...
``` def reverse_sublist(lst,start,end): lst[start:end] = lst[start:end][::-1] return lst ```
Numpy hstack - "ValueError: all the input arrays must have same number of dimensions" - but they do
22,257,836
12
2014-03-07T18:25:25Z
22,258,061
7
2014-03-07T18:37:35Z
[ "python", "arrays", "numpy", "pandas", "scikit-learn" ]
I am trying to join two numpy arrays. In one I have a set of columns/features after running TF-IDF on a single column of text. In the other I have one column/feature which is an integer. So I read in a column of train and test data, run TF-IDF on this, and then I want to add another integer column because I think this ...
Use `.column_stack`. Like so: ``` X = np.column_stack((X, AllAlexaAndGoogleInfo)) ``` From the [docs](http://docs.scipy.org/doc/numpy/reference/generated/numpy.column_stack.html): > Take a sequence of 1-D arrays and stack them as columns to make a > single 2-D array. 2-D arrays are stacked as-is, just like with hsta...
Read a small random sample from a big CSV file into a Python data frame
22,258,491
13
2014-03-07T19:00:09Z
22,259,008
15
2014-03-07T19:29:08Z
[ "python", "pandas", "random", "io", "import-from-csv" ]
The CSV file that I want to read does not fit into main memory. How can I read a few (~10K) random lines of it and do some simple statistics on the selected data frame?
Assuming no header in the CSV file: ``` import pandas import random n = 1000000 #number of records in file s = 10000 #desired sample size filename = "data.txt" skip = sorted(random.sample(xrange(n),n-s)) df = pandas.read_csv(filename, skiprows=skip) ``` would be better if read\_csv had a keeprows, or if skiprows too...
How to send request to endpoint with Boto
22,258,738
4
2014-03-07T19:13:03Z
25,376,589
7
2014-08-19T05:59:56Z
[ "python", "amazon-s3", "boto" ]
I am trying to list items in a S3 container with the following code. ``` import boto.s3 from boto.s3.connection import OrdinaryCallingFormat conn = boto.connect_s3(calling_format=OrdinaryCallingFormat()) mybucket = conn.get_bucket('Container001') for key in mybucket.list(): print key.name.encode('utf-8') ``` Th...
As @garnaat mentioned and @Rico [answered in another question](http://stackoverflow.com/a/22462419/3162882) `connect_to_region` works with `OrdinaryCallingFormat`: ``` conn = boto.s3.connect_to_region( region_name = '<your region>', aws_access_key_id = '<access key>', aws_secret_access_key = '<secret key>', ...
How to aggregate multiple columns in pandas groupby
22,259,241
4
2014-03-07T19:42:18Z
22,259,898
7
2014-03-07T20:18:15Z
[ "python", "pandas" ]
I have created a pandas dataframe mn using following input: ``` keyA state n1 n1 d1 d2 key1 CA 100 1000 1 2 key2 FL 200 2000 2 4 key1 CA 300 3000 3 6 key1 AL 400 4000 4 8 key2 FL 500 5000 5 2 key1 NY 600 6000 6 4 key2 CA 700 7000 7 6 ``` Have crea...
Pretty much just write it like your pseudocode. ``` In [14]: s = mn.groupby(['keyA','state'], as_index=False).sum() In [15]: s['v1'] = s['n1'] / s['d1'] In [16]: s['v2'] = s['n2'] / s['d2'] In [17]: s[['keyA', 'state', 'v1', 'v2']] Out[17]: keyA state v1 v2 0 key1 AL 100 500.000000 1 key1 ...
Application not picking up .css file (flask/python)
22,259,847
12
2014-03-07T20:15:22Z
22,260,791
21
2014-03-07T21:14:39Z
[ "python", "html", "css", "templates", "flask" ]
I am rendering a template, that I am attempting to style with an external style sheet. File structure is as follows. ``` /app - app_runner.py /services - app.py /templates - mainpage.html /styles - mainpage.css ``` mainpage.html looks like this ``` <html> <head> <...
You need to have a 'static' folder setup (for css/js files) unless you specifically override it during Flask initialization. I am assuming you did not override it. Your directory structure for css should be like: ``` /app - app_runner.py /services - app.py /templates - mainpage.html /...
Where in flask/gunicorn to initialize application
22,260,127
4
2014-03-07T20:32:04Z
22,260,176
8
2014-03-07T20:35:15Z
[ "python", "web-services", "flask", "gunicorn" ]
I'm using Flask/Gunicorn to run a web application and have a question about the lifecycle management. I have more experience in the Java world with servlets. I'm creating a restful interface to a service. The service is always running on the server and communicates and controls with a set of sub-servers. In Java, my s...
You can still use the same main() method paradigm. See this starter code below: ``` app = Flask(your_app_name) # Needs defining at file global scope for thread-local sharing def setup_app(app): # All your initialization code setup_app(app) if __name__ == '__main__': app.run(host=my_dev_host, port=my_dev_port,...
How is order of items in matplotlib legend determined?
22,263,807
14
2014-03-08T01:29:11Z
27,512,450
19
2014-12-16T19:31:33Z
[ "python", "matplotlib", "legend" ]
I am having to reorder items in a legend, when I don't think I should have to. I try: ``` from pylab import * clf() ax=gca() ht=ax.add_patch(Rectangle((1,1),1,1,color='r',label='Top',alpha=.01)) h1=ax.bar(1,2,label='Middle') hb=ax.add_patch(Rectangle((1,1),1,1,color='k',label='Bottom',alpha=.01)) legend() show() ``` ...
Here's a quick snippet to sort the entries in a legend. It assumes that you've already added your plot elements with a label, for example, something like ``` ax.plot(..., label='label1') ax.plot(..., label='label2') ``` and then the main bit: ``` handles, labels = ax.get_legend_handles_labels() # sort both labels an...
Importing matplotlib.pyplot and BeautifulSoup with cxFreeze
22,263,953
5
2014-03-08T01:48:41Z
22,306,134
8
2014-03-10T16:42:31Z
[ "python", "matplotlib", "beautifulsoup", "cx-freeze" ]
I am attempting to compile an executable for my python script using cxFreeze. Out of the many libraries which I need to import for my script, two seem to fail with cxFreeze. In particular, consider the following test.py script: ``` print('matplotlib.pyplot') import matplotlib.pyplot ``` compiling this with cxFreeze a...
After some digging around, I was able to resolve the issue. For those who may be encountering the same issue, this is what solved it for me: For the issue with matplotlib: I simply needed to explicitly specify to cxFreeze to include matplotlib.backends.backend\_tkagg. My setup file ended up looking like this: ``` imp...
How to sort dictionary by key in numerical order Python
22,264,956
10
2014-03-08T04:16:53Z
22,265,007
13
2014-03-08T04:24:07Z
[ "python", "sorting", "dictionary" ]
Here is the dictionary looks like: ``` {'57481': 50, '57480': 89, '57483': 110, '57482': 18, '57485': 82, '57484': 40} ``` I would like to sort the dictionary in numerical order, the result should be: ``` {'57480': 89, '57481': 50, '57482': 18, '57483': 110, '57484': 40, '57485': 82} ``` I tried `sorted(self.docs_i...
If you only need to sort by key, you're 95% there already. Assuming your dictionary seems to be called `docs_info`: ``` for key, value in sorted(docs_info.items()): # Note the () after items! print(key, value) ``` Since dictionary keys are always unique, calling `sorted` on `docs_info.items()` (which is a sequenc...
indexing current value in for loop? Python
22,267,488
3
2014-03-08T09:23:01Z
22,267,495
7
2014-03-08T09:23:33Z
[ "python" ]
So I have a for loop. ``` >>> row = [5, 2, 5, 4, 2, 2, 5, 5, 5, 2] >>> for i in row: if i == 5: print(row.index(i)) if i == 2: print(row.index(i)) ``` **OUTPUT** ``` 0 1 0 1 1 0 0 0 1 ``` I want to get: `0 1 2 4 5 6 7 8 9`. In other words, I want to get the index of the `i` I'm currently loo...
Use the [`enumerate()` function](http://docs.python.org/3/library/functions.html#enumerate) to produce a running index: ``` for index, i in enumerate(row): if i == 5: print(index) if i == 2: print(index) ``` or simpler still: ``` for index, i in enumerate(row): if i in (2, 5): pri...
What is the difference between os.path.basename() and os.path.dirname()?
22,272,003
31
2014-03-08T16:35:07Z
22,272,009
66
2014-03-08T16:35:38Z
[ "python" ]
I'm new in Python programming and while studying I had this doubt about this two functions. I already searched for answers and read some links, but didn't understood. Can anyone give some simple explanation?
Both functions use the `os.path.split(path)` function to split the pathname `path` into a pair; `(head, tail)`. The `os.path.dirname(path)` function returns the head of the path. E.g.: The dirname of `'/foo/bar/item'` is `'/foo/bar'`. The `os.path.basename(path)` function returns the tail of the path. E.g.: The bas...
Label python data points on plot
22,272,081
16
2014-03-08T16:41:19Z
22,272,358
32
2014-03-08T17:06:22Z
[ "python", "matplotlib", "labels", "annotate" ]
I searched for ages (hours which is like ages) to find the answer to a really annoying (seemingly basic) problem, and because I cant find a question that quite fits the answer I am posting a question and answering it in the hope that it will save someone else the huge amount of time I just spent on my noobie plotting s...
How about print `(x, y)` at once. ``` from matplotlib import pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0 B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54 plt.plot(A,B) for xy in zip(A, B): # <-- ax.annotate('(%s, %s)' % xy...
How do I alter a response in flask in the after_request function?
22,274,137
4
2014-03-08T19:41:57Z
22,274,189
12
2014-03-08T19:46:15Z
[ "python", "flask" ]
I am new to Flask and python. I have a bunch of views that return a dictionary in jsonify() format. For each of these views I'd like to add an after\_request handler to alter the response so I can add a key to that dictionary. I have: ``` @app.route('/view1/') def view1(): .. return jsonify({'message':'You got ser...
`response` is a WSGI object, and that means the body of the response must be an iterable. For `jsonify()` responses that's just a list with just one string in it. However, you should use the [`response.get_data()` method](http://werkzeug.pocoo.org/docs/wrappers/#werkzeug.wrappers.BaseResponse.get_data) here to retriev...
pySerial write() won't take my string
22,275,079
12
2014-03-08T21:05:29Z
22,315,432
18
2014-03-11T02:42:51Z
[ "python", "pyserial" ]
Using Python 3.3 and pySerial for serial communications. I'm trying to write a command to my COM PORT but the write method won't take my string. (Most of the code is from here [Full examples of using Pyserial package](http://stackoverflow.com/questions/676172/full-examples-of-using-pyserial-package) What's going on? ...
It turns out that the string needed to be turned into a bytearray and to do this I editted the code to ``` ser.write("%01#RDD0010000107**\r".encode()) ``` This solved the problem
./xx.py: line 1: import: command not found
22,275,350
4
2014-03-08T21:31:35Z
22,275,386
14
2014-03-08T21:34:52Z
[ "python", "url" ]
I am trying to use this [Python urllib2 Basic Auth Problem](http://stackoverflow.com/questions/2407126/python-urllib2-basic-auth-problem) bit of code to download a webpage content from an URL which requires authentication. The code I am trying is: ``` import urllib2, base64 request = urllib2.Request("http://api.four...
It's not an issue related to authentication at the first step. Your `import` is not working. So, try writing this on first line: ``` #!/usr/bin/python ``` and for the time being run using ``` python xx.py ``` For you here is one explanation: ``` >>> abc = "Hei Buddy" >>> print "%s" %abc Hei Buddy >>> >>> print "...
What is a good way to store strings in Python?
22,275,843
3
2014-03-08T22:23:13Z
22,275,881
8
2014-03-08T22:27:55Z
[ "python", "json", "string", "csv", "text" ]
I am building a conversation bot in Python. While I would like to generate as much text as possible from scratch, I still need a way to catalog and store a bunch of dialog fragment strings. Ideally I would like to contain some sort of hierarchy/classifications among the strings. For example: Greetings: `"Oh, nice to ...
That depends on how do you want to use it. If the strings are only meant to be used by Python you should consider storing them in their very own `.py` file. Yes, a module, but it is also a simple text file which happens that can be interpreted by Python :) A lot of projects use `.py` files as configuration files (Djan...
Python: Plot multiple graphs on the same figure
22,276,066
10
2014-03-08T22:48:58Z
22,276,109
29
2014-03-08T22:53:31Z
[ "python", "graph", "matplotlib" ]
I want to plot: ``` t = linspace(0,2*pi,400) a = sin(t) b = cos(t) c = a + b ``` I tried `plot(t,a,b,c)` but I get a baffling error message. How could I plot these 3 graphs with a range of `t` in the same figure?
To plot multiple graphs on the same figure you will have to do: ``` from numpy import * import math import matplotlib.pyplot as plt t = linspace(0,2*math.pi,400) a = sin(t) b = cos(t) c = a + b plt.plot(t,a,'r') # plotting t,a separately plt.plot(t,b,'b') # plotting t,b separately plt.plot(t,c,'g') # plotting t,c ...
How to I change data-type of pandas data frame to string with a defined format
22,276,503
10
2014-03-08T23:34:11Z
22,276,757
28
2014-03-09T00:08:09Z
[ "python", "string", "floating-point", "pandas", "format" ]
I'm starting to tear my hair out with this - so I hope someone can help. I have a pandas DataFrame that was created from an Excel spreadsheet using openpyxl. The resulting DataFrame looks like: ``` print image_name_data id image_name 0 1001 1001_mar2014_report 1 1002 1002_mar2014_report 2 1003 100...
I'm unable to reproduce your problem but have you tried converting it to an integer first? `image_name_data['id'] = image_name_data['id'].astype(int).astype('str')` Then, regarding your more general question you could use `map` ([as in this answer](http://stackoverflow.com/questions/20937538/how-to-display-pandas-dat...
Where is pip installed to when using get-pip.py?
22,278,138
5
2014-03-09T03:45:27Z
22,278,580
8
2014-03-09T04:56:44Z
[ "python", "osx", "pip" ]
I just installed pip on OS X using the [get-pyp.py](https://raw.github.com/pypa/pip/master/contrib/get-pip.py) script provided by the developers. The script said it ran successfully, but I cannot execute `pip` from the command line. I guess `pip` is not in my path, but I don't know where it installed to so I can't add ...
Do you know your **python path**? If yes, then look under the **Scripts** directory. For me (Windows user), `pip` it is located in > C:\Python27\Scripts\pip.exe Correspondingly for Linux, I think it should be inside > /usr/lib/python2.7/Scripts/ Also, if you have [`Homebrew`](http://mxcl.github.io/homebrew/) insta...
Where is pip installed to when using get-pip.py?
22,278,138
5
2014-03-09T03:45:27Z
24,151,884
15
2014-06-10T22:28:11Z
[ "python", "osx", "pip" ]
I just installed pip on OS X using the [get-pyp.py](https://raw.github.com/pypa/pip/master/contrib/get-pip.py) script provided by the developers. The script said it ran successfully, but I cannot execute `pip` from the command line. I guess `pip` is not in my path, but I don't know where it installed to so I can't add ...
If you can't find the path to `pip` you can simply use `python -m pip` instead: ``` python -m pip install awesome_package ```
AttributeError: 'module' object has no attribute 'request'
22,278,993
22
2014-03-09T06:01:44Z
22,279,013
38
2014-03-09T06:04:09Z
[ "python", "python-3.x", "python-3.3" ]
When i run the following code in Python - 3.3: ``` import urllib tempfile = urllib.request.urlopen("http://yahoo.com") ``` I get the following error: ![enter image description here](http://i.stack.imgur.com/7AoY2.jpg) I did this too to verify: ![enter image description here](http://i.stack.imgur.com/xpHhS.jpg) Wh...
Import `urllib.request` instead of `urllib`. ``` import urllib.request ```
Dynamic Django Mail Configuration
22,281,865
3
2014-03-09T11:56:13Z
22,287,776
7
2014-03-09T20:32:53Z
[ "python", "django", "email" ]
I don't want to use email configuration fields in setting.py, i want to put them in to a model. ``` class Configuration(models.Model): email_use_tls = models.BooleanField(_(u'EMAIL_USE_TLS'),default=True) email_host = models.CharField(_(u'EMAIL_HOST'),max_length=1024) email_host_user = models.CharField(_(u...
Very interesting question. It seems like this is already implemented in EmailMessage class. First you need to configure email backend ``` from django.core.mail import get_connection, EmailMessage from django.core.mail.backends.smtp import EmailBackend config = Configuration.objects.get(**lookup_kwargs) backend = E...
FileNotFoundError: [Errno 2] No such file or directory
22,282,760
5
2014-03-09T13:25:26Z
22,282,855
8
2014-03-09T13:34:52Z
[ "python", "file", "find" ]
I am trying to open a CSV file but for some reason python cannot locate it. Here is my code (it's just a simple code but I cannot solve the problem): ``` import csv with open('address.csv','r') as f: reader = csv.reader(f) for row in reader: print row ```
You are using a relative path, which means that the program looks for the file in the working directory. The error is telling you that there is no file of that name in the working directory. Try using the exact, or absolute, path.
Highest Posterior Density Region and Central Credible Region
22,284,502
10
2014-03-09T16:01:06Z
22,290,087
7
2014-03-10T00:19:46Z
[ "python", "statistics", "scipy", "statsmodels", "pymc" ]
Given a posterior p(Θ|D) over some parameters Θ, one can [define](http://rads.stackoverflow.com/amzn/click/0262018020) the following: ## Highest Posterior Density Region: The **Highest Posterior Density Region** is the set of most probable values of Θ that, in total, constitute 100(1-α) % of the posterior mass. ...
From my understanding "central credible region" is not any different from how confidence intervals are calculated; all you need is the inverse of `cdf` function at `alpha/2` and `1-alpha/2`; in `scipy` this is called `ppf` ( percentage point function ); so as for Gaussian posterior distribution: ``` >>> from scipy.sta...
Highest Posterior Density Region and Central Credible Region
22,284,502
10
2014-03-09T16:01:06Z
22,306,939
7
2014-03-10T17:20:33Z
[ "python", "statistics", "scipy", "statsmodels", "pymc" ]
Given a posterior p(Θ|D) over some parameters Θ, one can [define](http://rads.stackoverflow.com/amzn/click/0262018020) the following: ## Highest Posterior Density Region: The **Highest Posterior Density Region** is the set of most probable values of Θ that, in total, constitute 100(1-α) % of the posterior mass. ...
PyMC has a built in function for computing the hpd. In v2.3 it's in utils. See the source [here](https://github.com/pymc-devs/pymc/blob/2.3/pymc/utils.py). As an example of a linear model and it's HPD ``` import pymc as pc import numpy as np import matplotlib.pyplot as plt ## data np.random.seed(1) x = np.array(ran...
How to disable xkcd in a matplotlib figure?
22,284,843
4
2014-03-09T16:34:20Z
22,284,894
9
2014-03-09T16:38:22Z
[ "python", "matplotlib" ]
You turn on xkcd style by: ``` import matplotlib.pyplot as plt plt.xkcd() ``` But how to disable it? I try: ``` self.fig.clf() ``` But it won't work.
I see this in the doc, does it help? ``` with plt.xkcd(): # This figure will be in XKCD-style fig1 = plt.figure() # ... # This figure will be in regular style fig2 = plt.figure() ``` If not, you can look at `matplotlib.pyplot.xkcd`'s code and see how they generate the context manager that allows reversin...
How to disable xkcd in a matplotlib figure?
22,284,843
4
2014-03-09T16:34:20Z
22,287,611
12
2014-03-09T20:20:17Z
[ "python", "matplotlib" ]
You turn on xkcd style by: ``` import matplotlib.pyplot as plt plt.xkcd() ``` But how to disable it? I try: ``` self.fig.clf() ``` But it won't work.
In a nutshell, either use the context manager as @Valentin mentioned, or call `plt.rcdefaults()` afterwards. What's happening is that the `rc` parameters are being changed by `plt.xkcd()` (which is basically how it works). `plt.xkcd()` saves the current `rc` params returns a context manager (so that you can use a `wi...
How do I activate a virtualenv inside PyCharm's terminal?
22,288,569
37
2014-03-09T21:43:38Z
22,289,136
44
2014-03-09T22:35:33Z
[ "python", "django", "shell", "virtualenv", "pycharm" ]
I've set up PyCharm, created my virtualenv (either through the virtual env command, or directly in PyCharm) and activated that environment as my Interpreter. Everything is working just fine. However, if I open a terminal using "Tools, Open Terminal", the shell prompt supplied is *not* using the virtual env; I still ha...
Create a file `.pycharmrc` in your home folder with the following contents ``` source ~/.bashrc source ~/pycharmvenv/bin/activate ``` Using your virtualenv path as the last parameter. Then set the shell Preferences->Project Settings->Shell path to ``` /bin/bash --rcfile ~/.pycharmrc ```
How do I activate a virtualenv inside PyCharm's terminal?
22,288,569
37
2014-03-09T21:43:38Z
22,414,419
7
2014-03-14T19:46:53Z
[ "python", "django", "shell", "virtualenv", "pycharm" ]
I've set up PyCharm, created my virtualenv (either through the virtual env command, or directly in PyCharm) and activated that environment as my Interpreter. Everything is working just fine. However, if I open a terminal using "Tools, Open Terminal", the shell prompt supplied is *not* using the virtual env; I still ha...
Based on answers from Peter and experimentation, I've come up with a good "general solution", which solves the following: * Restores the behaviour of a login shell. PyCharm normally runs a login shell, but --rcfile stopped this happening. Script still uses --rcfile, but attempts to emulate the INVOCATION behaviour of ...
How do I activate a virtualenv inside PyCharm's terminal?
22,288,569
37
2014-03-09T21:43:38Z
22,861,755
18
2014-04-04T11:36:56Z
[ "python", "django", "shell", "virtualenv", "pycharm" ]
I've set up PyCharm, created my virtualenv (either through the virtual env command, or directly in PyCharm) and activated that environment as my Interpreter. Everything is working just fine. However, if I open a terminal using "Tools, Open Terminal", the shell prompt supplied is *not* using the virtual env; I still ha...
For Windows users: when using PyCharm with a virtual environment, you can use the `/K` parameter to `cmd.exe` to set the virtual environment automatically. PyCharm 3 or 4: `Settings`, `Terminal`, `Default shell` and add `/K <path-to-your-activate.bat>`. PyCharm 5: `Settings`, `Tools`, `Terminal`, and add `/K <path-to...
How do I activate a virtualenv inside PyCharm's terminal?
22,288,569
37
2014-03-09T21:43:38Z
23,730,300
28
2014-05-19T05:32:37Z
[ "python", "django", "shell", "virtualenv", "pycharm" ]
I've set up PyCharm, created my virtualenv (either through the virtual env command, or directly in PyCharm) and activated that environment as my Interpreter. Everything is working just fine. However, if I open a terminal using "Tools, Open Terminal", the shell prompt supplied is *not* using the virtual env; I still ha...
For Windows users when using PyCharm and a virtual environment under Windows, you can use the /k parameter to cmd.exe to set the virtual environment automatically. Go to Settings, Terminal, Default shell and add `/K <path-to-your-activate.bat>`. I don't have the reputation to comment on the earlier response so postin...
Lambda functions unequal behaviors in Python 3 and Python 2
22,288,604
5
2014-03-09T21:47:23Z
22,288,632
12
2014-03-09T21:49:50Z
[ "python", "python-3.x", "lambda", "python-2.x" ]
Why this code ``` >>> i=1 >>> add_one=lambda x:x+i >>> my_list=[add_one(i) for i in [0,1,2]] ``` in Python 2.7 throws this result: ``` >>> my_list [0, 2, 4] ``` But the same code in Python 3.3 throws this other result: ``` >>> my_list [1, 2, 3] ``` It's more sense for me the result with Python 2.7, because the 'i...
The difference is that in Python 3, list comprehensions do not leak their variable into the enclosing scope. You can see some discussion of this by Guido [here](http://python-history.blogspot.com/2010/06/from-list-comprehensions-to-generator.html); that post includes an example very similar to yours. In both versions,...
How to display a list vertically?
22,289,068
2
2014-03-09T22:29:46Z
22,289,090
7
2014-03-09T22:31:36Z
[ "python", "string", "list", "python-3.x" ]
I have a list of letters and want to be able to display them vertically like so: ``` a d b e c f def main(): letters = ["a", "b", "c", "d","e", "f"] for i in letters: print(i) ``` this code only display them like this: ``` a b c d e ```
That's because you're [printing](http://docs.python.org/3.3/library/functions.html?highlight=print#print) them in separate lines. Although you haven't given us enough info on *how* actually you want to print them, I can infer that you want the first half on the first column and the second half on the second colum. Wel...
Does Python optimize lambda x: x
22,290,675
5
2014-03-10T01:31:31Z
22,290,708
8
2014-03-10T01:35:38Z
[ "python", "lambda" ]
[So I wrote some code for a max/min that assumes a bottleneck on generating the data](http://stackoverflow.com/questions/22203740/get-minimum-and-maximum-values-from-a-for-in-loop/22204272#22204272) (else I'd just use `max` and `min`), and it takes a key function, which if not given uses an identity function: ``` if k...
Good question ! An optimizer could see that foo might be an identity function under certain predictable conditions and create an alternative path to replace it's invocation by it's known result ## Let's see the opcodes : ``` >>> def foo(n): ... f = lambda x:x ... return f(n) ... >>> import dis >>> dis.dis(fo...
Compare two lists, dictionaries in easy way
22,293,696
3
2014-03-10T06:45:09Z
22,293,751
8
2014-03-10T06:48:41Z
[ "python", "nose" ]
How to compare two lists or dictionaries in easy way, eg. ``` assert orig_list == new_list ``` If I want to check two lists in python nose tests, Is there any built-in function can let me use? Does compare two lists is a bad practice when doing testing ?(because I've never see it) If there is no built-in, plugin ...
You can use [assertListEqual(a, b)](http://docs.python.org/2/library/unittest.html#unittest.TestCase.assertListEqual) and [assertDictEqual(a, b)](http://docs.python.org/2/library/unittest.html#unittest.TestCase.assertDictEqual) from the `unittest` library.
Plotting a decision boundary separating 2 classes using Matplotlib's pyplot
22,294,241
22
2014-03-10T07:22:00Z
22,356,267
10
2014-03-12T15:28:54Z
[ "python", "numpy", "matplotlib" ]
I could really use a tip to help me plotting a decision boundary to separate to classes of data. I created some sample data (from a Gaussian distribution) via Python NumPy. In this case, every data point is a 2D coordinate, i.e., a 1 column vector consisting of 2 rows. E.g., ``` [ 1 2 ] ``` Let's assume I have 2 cl...
Your question is more complicated than a simple plot : you need to draw the contour which will maximize the inter-class distance. Fortunately it's a well-studied field, particularly for SVM machine learning. The easiest method is to download the `scikit-learn` module, which provides a lot of cool methods to draw bound...
Plotting a decision boundary separating 2 classes using Matplotlib's pyplot
22,294,241
22
2014-03-10T07:22:00Z
22,356,551
9
2014-03-12T15:40:32Z
[ "python", "numpy", "matplotlib" ]
I could really use a tip to help me plotting a decision boundary to separate to classes of data. I created some sample data (from a Gaussian distribution) via Python NumPy. In this case, every data point is a 2D coordinate, i.e., a 1 column vector consisting of 2 rows. E.g., ``` [ 1 2 ] ``` Let's assume I have 2 cl...
Based on the way you've written `decision_boundary` you'll want to use the `contour` function, as Joe noted above. If you just want the boundary line, you can draw a single contour at the 0 level: ``` f, ax = plt.subplots(figsize=(7, 7)) c1, c2 = "#3366AA", "#AA3333" ax.scatter(*x1_samples.T, c=c1, s=40) ax.scatter(*x...
What magic does staticmethod() do, so that the static method is always called without the instance parameter?
22,294,450
6
2014-03-10T07:34:40Z
22,294,577
8
2014-03-10T07:42:10Z
[ "python", "python-3.x", "static-methods" ]
I am trying to understand how static methods work internally. I know how to use `@staticmethod` decorator but I will be avoiding its use in this post in order to dive deeper into how static methods work and ask my questions. From what I know about Python, if there is a class `A`, then calling `A.foo()` calls `foo()` w...
It's implemented as a [descriptor](http://docs.python.org/2/howto/descriptor.html#definition-and-introduction). For example: ``` In [1]: class MyStaticMethod(object): ...: def __init__(self, func): ...: self._func = func ...: def __get__(self, inst, cls): ...: return self._func ....
Using Mechanize (Python) to fill form
22,294,489
5
2014-03-10T07:36:28Z
22,294,760
7
2014-03-10T07:54:30Z
[ "python", "forms", "python-2.7", "web-scraping", "mechanize" ]
I want to fill the form on this page using python mechanize and then record the response. How should I do it? When I search for forms on this page using the following code, it shows the form only for the search. How should I locate the form name of the other form with fields such as name, gender etc? <http://aapmahara...
The form you need (with an `id="form1"`) is loaded dynamically on the fly - this is why you don't see it in the `select_forms()` results. By using browser developer tools you may find out that the form is loaded from `http://internal.aamaadmiparty.org/Directory/Format.aspx?master=blank` link. Here's what you should s...
Python double inheritance
22,294,584
3
2014-03-10T07:42:19Z
22,294,814
7
2014-03-10T07:58:27Z
[ "python", "inheritance" ]
I'm trying to find a suitable inheritance configuration for the following problem: My base class is an Agent Class which has 3 abstract methods: ``` class Agent(): __metaclass__ = abc.ABCMeta def __init__(self): @abc.abstractmethod def bidding_curve(self): @abc.abstractmethod def evaluate_biddi...
Make `Heater` a simple object which accepts an agent in its constructor: ``` class Heater(object): def __init__(self, agent): self.agent = agent # define other methods for interaction with Heater application # in which you can access agent methods like self.agent.a_method(...) ```
How to store django objects as session variables ( object is not JSON serializable)?
22,294,788
4
2014-03-10T07:57:02Z
22,294,933
8
2014-03-10T08:05:25Z
[ "python", "django" ]
I have a simple view ``` def foo(request): card = Card.objects.latest(datetime) request.session['card']=card ``` For the above code I get the error ``` "<Card: Card object> is not JSON serializable" ``` Django version 1.6.2. What am I doing wrong ?
In a cookie, I'd just store the object primary key: ``` request.session['card'] = card.id ``` and when loading the card from the session, obtain the card again with: ``` try: card = Card.objects.get(id=request.session['card']) except (KeyError, Card.DoesNotExist): card = None ``` which will set `card` to `N...
Skip multiple iterations in loop python
22,295,901
24
2014-03-10T09:05:34Z
22,296,065
29
2014-03-10T09:14:00Z
[ "python", "loops", "iterator", "next", "continue" ]
I have a list in a loop and I want to skip 3 elements after `look` has been reached. In [this answer](http://stackoverflow.com/questions/5509302/whats-the-best-way-of-skip-n-values-of-the-iteration-variable-in-python) a couple of suggestions were made but I fail to make good use of them: ``` song = ['always', 'look', ...
`for` uses `iter(song)` to loop; you can do this in your own code and then advance the iterator inside the loop; calling `iter()` on the iterable again will only return the same iterable object so you can advance the iterable inside the loop with `for` following right along in the next iteration. Advance the iterator ...
Add element to a json in python
22,296,496
11
2014-03-10T09:35:38Z
22,296,537
19
2014-03-10T09:37:32Z
[ "python", "json" ]
I am trying to add an element to a json file in python but I am not able to do it. This is what I tried untill now (with some variation which I deleted): ``` import json data = [ { 'a':'A', 'b':(2, 4), 'c':3.0 } ] print 'DATA:', repr(data) var = 2.4 data.append({'f':var}) print 'JSON', json.dumps(data) ``` But, wh...
You can do this. ``` data[0]['f'] = var ```
Show a progress bar for my multithreaded process
22,297,239
10
2014-03-10T10:10:48Z
22,365,624
7
2014-03-12T22:56:19Z
[ "python", "multithreading", "flask" ]
I have a simple Flask web app that make many HTTP requests to an external service when a user push a button. On the client side I have an angularjs app. The server side of the code look like this (using [multiprocessing.dummy](http://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.dummy)): ``` w...
For interprocess communication you can use a [multiprocessiong.Queue](http://docs.python.org/2/library/multiprocessing.html#multiprocessing.Queue) and your workers can `put_nowait` tuples with progress information on it while doing their work. Your main process can update whatever your view\_progress is reading until a...
"unit tests have failed" for beautifulsoup
22,301,307
9
2014-03-10T13:20:48Z
22,301,642
19
2014-03-10T13:34:33Z
[ "python", "python-3.x", "beautifulsoup" ]
i am trying to install beautifulsoup for python33 but its not installing properly it gives error like that: ``` C:\Python33>pip install beautifulsoup Downloading/unpacking beautifulsoup Downloading BeautifulSoup-3.2.1.tar.gz Running setup.py egg_info for package beautifulsoup Traceback (most recent call last): File ...
You are trying to install BeautifulSoup 3, which is not Python 3 compatible. Install [`beautifulsoup4`](https://pypi.python.org/pypi/beautifulsoup4) instead: ``` pip install beautifulsoup4 ``` Most code that assumes BeautifulSoup 3 will also work with BeautifulSoup 4. For new projects, just stick with BS4.
python pip broken after update
22,304,681
5
2014-03-10T15:42:17Z
22,335,256
12
2014-03-11T19:54:25Z
[ "python", "pip" ]
I am seeing the following error from pip on several versions of python3 that I am running: ``` ... raise MissingSchema('Proxy URLs must have explicit schemes.') pip._vendor.requests.exceptions.MissingSchema: Proxy URLs must have explicit schemes. ``` It looks like something with the requests library. And this is...
I'm guessing that the new version is more strict about checking that your proxy settings are valid. If you have an environment variable like `http_proxy=localhost:3128` then update it to `http_proxy=http://localhost:3128` and you should be fine again. (Ditto for `https_proxy` -- actually I guess recent versions of pip ...
Why does locals() return a strange self referential list?
22,307,520
14
2014-03-10T17:47:44Z
22,308,080
25
2014-03-10T18:15:12Z
[ "python", "list-comprehension", "python-2.6", "python-internals", "locals" ]
So I'm using locals() to grab some arguments in the function. Works nicely: ``` def my_function(a, b): print locals().values() >>> my_function(1,2) [1, 2] ``` Standard stuff. But now let's introduce a list comprehension: ``` def my_function(a, b): print [x for x in locals().values()] >>> my_function(1,2) [...
Python versions before 2.7 and 3.1 used suboptimal bytecode to produce a list comprehension. In those Python versions, the list comprehension was stored in a local variable (or even a global, if at module scope): ``` >>> import dis >>> def foo(): ... return [x for x in y] ... >>> dis.dis(foo) 2 0 BUIL...
How do i print the longest and shortest words out of a given set of words?
22,307,696
5
2014-03-10T17:54:53Z
22,307,729
18
2014-03-10T17:56:36Z
[ "python", "list" ]
What I want is to write a code to detect the longest and shortest words from those given in a list. I tried to write a code to find the longest word using the number of characters which failed really bad...I'm wondering if there is a simple function or line that I'm missing. ``` mywords=['how','no','because','sheep','...
You can use `max`, and `min`. ``` >>> max(mywords, key=len) 'mahogany' >>> min(mywords, key=len) 'no' ```
Difference between A[1:3][0:2] and A[1:3,0:2]
22,309,409
3
2014-03-10T19:24:50Z
22,309,610
7
2014-03-10T19:35:39Z
[ "python", "numpy" ]
I can't figure out the difference between these two kinds of indexing. It seems like they should produce the same results but they do not. Any explanation?
`A[1:3, 0:2]` takes rows `1-3` and columns `0-2` thus returning a `2x2` array. `A[1:3][0:2]` first takes rows `1-3` *and from this subarray* takes the rows `0-2`, resulting in a `2xn` array where `n` is the original number of columns. ``` In [1]: import numpy as np In [2]: a = np.arange(16).reshape(4,4) In [3]: a O...
Check Python 3 source with Pylint running with Python 2
22,309,636
3
2014-03-10T19:36:39Z
22,318,936
8
2014-03-11T07:22:35Z
[ "python", "python-2.7", "python-3.x", "pylint" ]
Some checks of Pylint are depending on whether the checked source code is of kind Python 2 or Python 3. E.g., see [How to avoid Pylint warnings for constructor of inherited class in Python 3?](http://stackoverflow.com/questions/22235021/how-to-avoid-pylint-warnings-for-constructor-of-inherited-class-in-python-3). In m...
Short answer: you can't. Pylint is using the builtin Python parser, and also get standard library information on demand, so the Python version running Pylint has a high impact on its output. You should have several Pylint installations if you want to use it to check both Python 2 and Python 3 code.
Matplotlib Bar Chart Choose Color if Value is Postive vs Value is Negative
22,311,139
4
2014-03-10T20:58:00Z
22,311,398
8
2014-03-10T21:11:38Z
[ "python", "matplotlib", "pandas" ]
I have a Pandas DataFrame with positive and negative values as a bar chart. I want to plot the positive colors 'green' and the negative values 'red'(very original...lol). I'm not sure how to pass and if > 0 'green' else < 0 'red'? ``` data = pd.DataFrame([[-15], [10], [8], [-4.5]],index=['a', 'b', 'c', 'd'],columns=['...
I would create a dummy column for whether the observation is larger than 0. ``` In [39]: data['positive'] = data['values'] > 0 In [40]: data Out[40]: values positive a -15.0 False b 10.0 True c 8.0 True d -4.5 False [4 rows x 2 columns] In [41]: data['values'].plot(kind='barh', color=d...
Remote tcp connection in python with zeromq
22,312,016
4
2014-03-10T21:46:02Z
22,474,105
9
2014-03-18T08:39:54Z
[ "python", "tcp", "client-server", "zeromq" ]
I have a python client that needs to talk to a remote server I manage. They communicate using zeromq. When I tested the client/server locally everything worked. But now I have the client and server deployed on the cloud, each using a different provider. My question is, what's the simplest way (that is safe) to make the...
Indeed, ZMQ way is - tunnelling connection with the SSH. Your example is exactly what needs to be done, except that one should either use `connect` or `tunnel_connection`, not both. Also, when specifying server to connect to, make sure to define the SSH port, not the ZMQ REP socket port. That is, instead of `myuser@re...
clang error: unknown argument: '-mno-fused-madd' (python package installation failure)
22,313,407
259
2014-03-10T23:19:51Z
22,315,129
76
2014-03-11T02:11:12Z
[ "python", "clang", "pip", "osx-mavericks" ]
I get the following error when attempting to install `psycopg2` via pip on Mavericks 10.9: ``` clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future] ``` Not sure how to proceed and have searched here and elsewhere for this particular error. Any help is much appreciate...
Update: 10.9.3 resolves the issue with system CPython. This is caused by the latest clang update from Apple that came with Xcode 5.1 today and is affecting many, many people, so hopefully a fix will appear soon. Update: Did not expect this to get so much attention, but here's more detail: the clang 3.4 Apple is shipp...
clang error: unknown argument: '-mno-fused-madd' (python package installation failure)
22,313,407
259
2014-03-10T23:19:51Z
22,322,068
15
2014-03-11T09:51:51Z
[ "python", "clang", "pip", "osx-mavericks" ]
I get the following error when attempting to install `psycopg2` via pip on Mavericks 10.9: ``` clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future] ``` Not sure how to proceed and have searched here and elsewhere for this particular error. Any help is much appreciate...
Here is a work around that involves removing the flag from the python installation. In `/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_sysconfigdata.py` are several places where the `-mfused-madd` / `-mno-fused-madd` flag is set. Edit this file and remove all of the references to that flag yo...
clang error: unknown argument: '-mno-fused-madd' (python package installation failure)
22,313,407
259
2014-03-10T23:19:51Z
22,322,645
433
2014-03-11T10:15:21Z
[ "python", "clang", "pip", "osx-mavericks" ]
I get the following error when attempting to install `psycopg2` via pip on Mavericks 10.9: ``` clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future] ``` Not sure how to proceed and have searched here and elsewhere for this particular error. Any help is much appreciate...
You can tell clang to not raise this as an error by setting the following environment variables prior compilation: ``` export CFLAGS=-Qunused-arguments export CPPFLAGS=-Qunused-arguments ``` Then `pip install psycopg2`should work. I had the same when trying to `pip install lxml`. Edit: if you are installing as supe...
clang error: unknown argument: '-mno-fused-madd' (python package installation failure)
22,313,407
259
2014-03-10T23:19:51Z
22,372,751
63
2014-03-13T08:18:35Z
[ "python", "clang", "pip", "osx-mavericks" ]
I get the following error when attempting to install `psycopg2` via pip on Mavericks 10.9: ``` clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future] ``` Not sure how to proceed and have searched here and elsewhere for this particular error. Any help is much appreciate...
xCode 5.1 ``` ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install psycopg2 ```
Parsing and computing boolean set definitions
22,315,566
8
2014-03-11T02:56:04Z
22,316,212
23
2014-03-11T04:01:39Z
[ "python", "math", "set", "boolean", "scipy" ]
Say I have a set `S` defined as a string, e.g. as follows: ``` S = '(A or B) and not(A and C)' ``` where A, B and C are finite sets, e.g.: ``` A = {0, 1} B = {0, 2} C = {1, 3} ``` If we analyze `S` step by step, we have: ``` (A or B) = {0, 1, 2} (A & C) = {1} not(A & C) = {0, 2, 3} ``` which gives us the fin...
There is no need to write your own parser if you're willing to transform *S* in to a string suitable for use with [*eval()*](http://docs.python.org/2.7/library/functions.html#eval). Change *S* from `'(A or B) and not(A and C)'` into an equivalent *T* that uses Python's *in*-operator `'(x in A or x in B) and not(x in A ...
Saving dictionary of header information using numpy.savez()
22,315,595
4
2014-03-11T03:00:06Z
22,315,746
11
2014-03-11T03:16:00Z
[ "python", "numpy", "dictionary", "header" ]
I am trying to save an array of data along with header information. Currently, I am using numpy.savez() to save the header information (a dictionary) in one array, and the data in another. ``` data = [[1,2,3],[4,5,6]] header = {'TIME': time, 'POSITION': position} np.savez(filename, header=header, data=data...
`np.savez` saves only numpy arrays. If you give it a dict, it will call `np.array(yourdict)` before saving it. So this is why you see something like `type(arrays['header'])` as `np.ndarray`: ``` arrays = np.load(filename) h = arrays['header'] # square brackets!! >>> h array({'POSITION': (23, 54), 'TIME': 23.5}, dtype...
Install GeoIP on Windows?
22,315,846
2
2014-03-11T03:25:53Z
22,317,955
7
2014-03-11T06:22:17Z
[ "python", "django", "geoip" ]
Does anybody know how to install `GeoIP's C library` on `Windows` in a few simple steps. Even a few complicated steps will do. I researched and tried to compile it from the setup file but failed several times. Sometimes, I get errors saying that `GeoIP.h` could not be located. Other times I get that `bugtrack_url` is n...
The 'GeoIP.h could not be located' error indicates that you need to install `libgeoip-dev` first. Though I have no idea how to install it on windows easiy. I suggest you to use the [pygeoip](https://pypi.python.org/pypi/pygeoip/) package, based on the following reasons: * pygeoip is a pure python package * pygeoip su...
Flask 404 when using SERVER_NAME
22,315,887
4
2014-03-11T03:29:40Z
22,315,983
9
2014-03-11T03:39:09Z
[ "python", "apache", "flask" ]
In my Flask config, I'm setting SERVER\_NAME to a domain like "app.example.com". I'm doing that because I need to use `url_for` with `_external` URLs. If SERVER\_NAME is not set, Flask thinks the server is 127.0.0.1:5000 (it's actually running behind a reverse-proxy), and returns an external URL like `http://127.0.0.1:...
Just found the answer. Apache has an option called `ProxyPreserveHost`. Once it's set to On, everything works as expected. More information here: <http://flask.pocoo.org/mailinglist/archive/2011/3/14/problem-with-apache-proxy-and-canonical-urls/>
How can I resolve TypeError with StringIO in Python 2.7?
22,316,333
8
2014-03-11T04:14:01Z
22,316,392
12
2014-03-11T04:20:59Z
[ "python", "python-2.7", "stringio" ]
Trying to read following string as file using `StringIO` but getting the error below. How can I resolve it? ``` >> from io import StringIO >>> >>> datastring = StringIO("""\ ... Country Metric 2011 2012 2013 2014 ... USA GDP 7 4 0 2 ... USA Pop. 2 3...
You can resolve the error by simply adding a u before your string to make the string unicode: ``` datastring = StringIO(u"""\ Country Metric 2011 2012 2013 2014 USA GDP 7 4 0 2 USA Pop. 2 3 0 3 GB GDP 8 7 0 ...
scikit-learn roc_auc_score() returns accuracy values
22,318,922
3
2014-03-11T07:21:40Z
22,323,154
10
2014-03-11T10:36:59Z
[ "python", "scikit-learn", "scikits" ]
I am trying to compute area under the ROC curve using `sklearn.metrics.roc_auc_score` using the following method: ``` roc_auc = sklearn.metrics.roc_auc_score(actual, predicted) ``` where `actual` is a binary vector with ground truth classification labels and `predicted` is a binary vector with classification labels t...
This is because you are passing in the decisions of you classifier instead of the scores it calculated. There was a [question on this on SO recently](http://stackoverflow.com/questions/21829131/binary-vectors-as-y-score-argument-of-roc-curve) and a related pull request to `scikit-learn`. The point of a ROC curve (and ...
What is the best way to convert a printed list in Python back into an actual list
22,322,577
5
2014-03-11T10:12:35Z
22,322,647
11
2014-03-11T10:15:25Z
[ "python", "string", "list" ]
So given the a a textual representation of a list ``` ['cellular organisms', 'Bacteria', 'Bacteroidetes/Chlorobi group', 'Bacteroidetes', 'Bacteroidia', 'Bacteroidales', 'Bacteroidaceae', 'Bacteroides', 'Bacteroides vulgatus'] ``` What is the easiest way to convert this text back into an actual list within a python...
``` >>> import ast >>> a = "['cellular organisms', 'Bacteria', 'Bacteroidetes/Chlorobi group', 'Bacteroidetes', 'Bacteroidiroidales', 'Bacteroidaceae', 'Bacteroides', 'Bacteroides vulgatus']" >>> ast.literal_eval(a) ['cellular organisms', 'Bacteria', 'Bacteroidetes/Chlorobi group', 'Bacteroidetes', 'Bacteroidia', 'Ba...
Better way to mock class attribute in python unit test
22,324,628
7
2014-03-11T11:39:11Z
22,324,835
8
2014-03-11T11:49:08Z
[ "python", "unit-testing", "mocking", "python-mock" ]
I have a base class that defines a class attribute and some child classes that depend on it, e.g. ``` class Base(object): assignment = dict(a=1, b=2, c=3) ``` I want to unittest this class with different *assignments*, e.g. empty dictionary, single item, etc. This is extremely simplified of course, it's not a mat...
`base.Base.assignment` is simply replaced with a `Mock` object. You *made* it a descriptor by adding a `__get__` method. It's a little verbose and a little unnecessary; you could simply set `base.Base.assignment` directly: ``` def test_empty(self): Base.assignment = {} assert len(Base().assignment.values()) =...