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
Sublime Text 3 API : Get all text from a file
20,182,008
8
2013-11-24T22:37:09Z
20,182,214
14
2013-11-24T22:57:49Z
[ "python", "select", "text", "sublimetext3", "sublime-text-plugin" ]
I am trying to create a plugin for sublime text 3. For now I only get possible to select all text in a window and copy it in another window. Code : ``` import sublime, sublime_plugin class PrintCodeCommand(sublime_plugin.WindowCommand): def run(self): # for each caracter, add it to a string with the ...
You can get the contents of the current doc with: ``` contents = self.view.substr(sublime.Region(0, self.view.size())) ```
Nginx is throwing an 403 Forbidden on Static Files
20,182,329
7
2013-11-24T23:10:51Z
20,182,383
19
2013-11-24T23:18:12Z
[ "python", "django", "configuration", "nginx" ]
I have a django app, python 2.7 with gunicorn and nginx. Nginx is throwing a `403 Forbidden Error`, if I try to view anything in my `static` folder @: ``` /home/ubuntu/virtualenv/myapp/myapp/homelaunch/static ``` **nginx config**(`/etc/nginx/sites-enabled/myapp`) contains: ``` server { listen 80; ...
It appears the user nginx is running as (*nginx*?) is missing privileges to read the local file `/home/ubuntu/virtualenv/myapp/myapp/homelaunch/static/img/templated/home/img.png`. You probably wanna check file permissions as well as permissions on the directories in the hierarchy.
How to sort multidimensional array by column?
20,183,069
7
2013-11-25T00:38:25Z
20,183,121
9
2013-11-25T00:44:20Z
[ "python", "arrays", "list", "sorting" ]
Is there a way to use the sort() method or any other method to sort a list by column? Lets say I have the list: ``` [ [John,2], [Jim,9], [Jason,1] ] ``` And I wanted to sort it so that it would look like this: ``` [ [Jason,1], [John,2], [Jim,9], ] ``` What would be the best approach to do this? Edit: Right now I ...
Yes. The `sorted` built-in accepts a `key` argument: ``` sorted(li,key=lambda x: x[1]) Out[31]: [['Jason', 1], ['John', 2], ['Jim', 9]] ``` note that `sorted` returns a new list. If you want to sort in-place, use the `.sort` method of your list (which also, conveniently, accepts a `key` argument). or alternatively, ...
Python Multiprocessing a for loop
20,190,668
14
2013-11-25T11:09:12Z
20,192,216
8
2013-11-25T11:43:38Z
[ "python", "multiprocessing" ]
I have an array (called data\_inputs) containing the names of hundreds of astronomy images files. These images are then manipulated. My code works and takes a few seconds to process each image. However, it can only do one image at a time because I'm running the array through a 'for' loop: ``` for name in data_inputs: ...
You can use `multiprocessing.Pool`: ``` from multiprocessing import Pool class Engine(object): def __init__(self, parameters): self.parameters = parameters def __call__(self, filename): sci = fits.open(filename + '.fits') manipulated = manipulate_image(sci, self.parameters) retu...
Python Multiprocessing a for loop
20,190,668
14
2013-11-25T11:09:12Z
20,192,251
18
2013-11-25T11:45:35Z
[ "python", "multiprocessing" ]
I have an array (called data\_inputs) containing the names of hundreds of astronomy images files. These images are then manipulated. My code works and takes a few seconds to process each image. However, it can only do one image at a time because I'm running the array through a 'for' loop: ``` for name in data_inputs: ...
You can simply use `multiprocessing.Pool`: ``` from multiprocessing import Pool def process_image(name): sci=fits.open('{}.fits'.format(name)) <process> if __name__ == '__main__': pool = Pool(processes=4) # process per core pool.map(process_image, data_inputs) # proces data_inputs itera...
Creating Custom user registration form Django
20,192,144
5
2013-11-25T11:39:18Z
20,192,185
8
2013-11-25T11:42:02Z
[ "python", "django" ]
I am trying to create custom user registration forms in Django but I am getting the following error. Everything on my page displays correctly however I get the error. Error: ``` Exception Type: KeyError Exception Value: 'First name' ``` My form.py: ``` from django import forms from django.contrib.aut...
Here is the problem, you are accessing fields by using label rather it should be accessed by form field name: ``` self.cleaned_data['First name'] ``` should be ``` self.cleaned_data['first_name'] ``` Similarly `last_name` and `birthday`.
Python - how to get the import pjsua? giving no module named pjsua
20,195,542
2
2013-11-25T14:27:07Z
20,245,316
8
2013-11-27T14:39:30Z
[ "python", "linux", "pjsip" ]
How to get python pjsua? ``` $ wget http://www.pjsip.org/release/2.1/pjproject-2.1.tar.bz2 $ tar xvfj pjproject-2.1.tar.bz2 $ cd pjproject-2.1.0 $ ./configure $ make dep && make $ make install $ ldconfig $ ldconfig -p | grep pj $ cd ./pjsip-apps/src/python $ python setup.py install running install running build run...
`setup.py` is trying to create shared library `build/lib.linux-x86_64-2.7/_pjsua.so` by dynamically linking pjsip's libraries, but, those doesn't provide a [global offsets table(GOT)](https://en.wikipedia.org/wiki/Position-independent_code) (check the link to see why this is needed). The problem is that `./configure` ...
Problems running python script by windows task scheduler that does pscp
20,196,049
5
2013-11-25T14:51:18Z
21,116,923
8
2014-01-14T15:10:53Z
[ "python", "scheduled-tasks", "scp" ]
Not sure if anyone has run into this, but I'll take suggestions for troubleshooting and/or alternative methods. I have a Windows 2008 server on which I am running several scheduled tasks. One of those tasks is a python script that uses pscp to log into a linux box, checks for new files and if there is anything new, co...
I had the same issue when trying to open an MS Access database on a Linux VM. Running the script at the Windows 7 command prompt worked but running it in Task Scheduler didn't. With Task Scheduler it would find the database and verify it existed but wouldn't return the tables within it. The solution was to have Task S...
How to display line numbers in IPython Notebook code cell by default
20,197,471
16
2013-11-25T15:58:27Z
20,197,878
18
2013-11-25T16:18:44Z
[ "python", "ipython", "ipython-notebook" ]
I would like my default display for IPython notebook code cells to include line numbers. I learned from [ipython notebook line number](http://stackoverflow.com/questions/10979667/ipython-notebook-line-number) that I can toggle this with ctrl-M L, which is great, but manual. In order to include line numbers by default,...
In your `custom.js` file (location depends on your OS) put `IPython.Cell.options_default.cm_config.lineNumbers = true;` If you can't find custom.js, you can just search for it, but generally it will be in your profile\_default folder. If it doesn't exist, create the file at `$(ipython locate profile)/static/custom/cu...
How to display line numbers in IPython Notebook code cell by default
20,197,471
16
2013-11-25T15:58:27Z
29,916,445
21
2015-04-28T10:09:27Z
[ "python", "ipython", "ipython-notebook" ]
I would like my default display for IPython notebook code cells to include line numbers. I learned from [ipython notebook line number](http://stackoverflow.com/questions/10979667/ipython-notebook-line-number) that I can toggle this with ctrl-M L, which is great, but manual. In order to include line numbers by default,...
**(For Jupyter 4+)** In the latest Jupyter versions, they have [documented](https://jupyter.readthedocs.org/en/latest/migrating.html) the place to make config changes. So basically, in the Jupyter update, they've removed the concept of profiles, so the `custom.js` file location is now `.jupyter/custom/custom.js`, depen...
how to make argsort result to be random between equal values?
20,197,990
6
2013-11-25T16:24:08Z
20,199,459
9
2013-11-25T17:31:35Z
[ "python", "sorting", "random", "numpy" ]
Say you have a `numpy` vector `[0,3,1,1,1]` and you run `argsort` you will get `[0,2,3,4,1]` but all the ones are the same! What I want is an efficient way to shuffle indices of identical values. Any idea how to do that without a while loop with two indices on the sorted vector? ``` numpy.array([0,3,1,1,1]).argsort() ...
Use `lexsort`: `np.lexsort((b,a))` means Sort by `a`, then by `b` ``` >>> a array([0, 3, 1, 1, 1]) >>> b=np.random.random(a.size) >>> b array([ 0.00673736, 0.90089115, 0.31407214, 0.24299867, 0.7223546 ]) >>> np.lexsort((b,a)) array([0, 3, 2, 4, 1]) >>> a.argsort() array([0, 2, 3, 4, 1]) >>> a[[0, 3, 2, 4, 1]] arr...
Reading a JSON file using Python
20,199,126
73
2013-11-25T17:15:09Z
20,199,213
84
2013-11-25T17:19:32Z
[ "python", "json" ]
I am getting a bit of headache just because a simple looking, easy statement is throwing some errors in my face. I have a json file called strings.json like this: ``` "strings": [ {"-name": "city", "#text": "City"}, {"-name": "phone", "#text": "Phone"}, ..., {"-name": "address", "#text": "Address"} ] ``` I want to r...
The [`json.load()` method](http://docs.python.org/3/library/json.html#json.load) (without "s" in "load") can read a file directly: ``` import json with open('strings.json') as json_data: d = json.load(json_data) print(d) ``` You were using the [`json.loads()` method](http://docs.python.org/3/library/json.htm...
Reading a JSON file using Python
20,199,126
73
2013-11-25T17:15:09Z
20,200,782
80
2013-11-25T18:46:17Z
[ "python", "json" ]
I am getting a bit of headache just because a simple looking, easy statement is throwing some errors in my face. I have a json file called strings.json like this: ``` "strings": [ {"-name": "city", "#text": "City"}, {"-name": "phone", "#text": "Phone"}, ..., {"-name": "address", "#text": "Address"} ] ``` I want to r...
Here is a copy of code which works fine for me ``` import json with open("test.json") as json_file: json_data = json.load(json_file) print(json_data) ``` with the data ``` { "a": [1,3,"asdf",true], "b": { "Hello": "world" } } ``` you may want to wrap your json.load line with a try catch...
Reading a JSON file using Python
20,199,126
73
2013-11-25T17:15:09Z
25,984,135
23
2014-09-22T22:38:06Z
[ "python", "json" ]
I am getting a bit of headache just because a simple looking, easy statement is throwing some errors in my face. I have a json file called strings.json like this: ``` "strings": [ {"-name": "city", "#text": "City"}, {"-name": "phone", "#text": "Phone"}, ..., {"-name": "address", "#text": "Address"} ] ``` I want to r...
The problem is using **with** statement: ``` with open('strings.json') as json_data: d = json.load(json_data) pprint(d) ``` The file is going to be implicitly closed already. There is no need to call `json_data.close()` again.
Pandas: Get duplicated indexes
20,199,129
11
2013-11-25T17:15:14Z
20,199,798
7
2013-11-25T17:47:18Z
[ "python", "indexing", "pandas" ]
Given a dataframe, I want to get the duplicated indexes, which do not have duplicate values in the columns, and see which values are different. Specifically, I have this dataframe: ``` import pandas as pd wget https://www.dropbox.com/s/vmimze2g4lt4ud3/alt_exon_repeatmasker_intersect.bed alt_exon_repeatmasker = pd.rea...
``` >>> df[df.groupby(level=0).transform(len)['type'] > 1] type genome_location1 MIR3 genome_location1 AluJb ```
Pandas: Get duplicated indexes
20,199,129
11
2013-11-25T17:15:14Z
20,200,594
10
2013-11-25T18:36:14Z
[ "python", "indexing", "pandas" ]
Given a dataframe, I want to get the duplicated indexes, which do not have duplicate values in the columns, and see which values are different. Specifically, I have this dataframe: ``` import pandas as pd wget https://www.dropbox.com/s/vmimze2g4lt4ud3/alt_exon_repeatmasker_intersect.bed alt_exon_repeatmasker = pd.rea...
``` df.groupby(level=0).filter(lambda x: len(x) > 1)['type'] ``` We added `filter` method for this kind of operation. You can also use masking and transform for equivalent results, but this is faster, and a little more readable too. **Important:** The `filter` method was introduced in version 0.12, but it failed to ...
pyodbc insert into sql
20,199,569
7
2013-11-25T17:36:34Z
20,199,702
14
2013-11-25T17:42:31Z
[ "python", "sql", "sql-server-express", "python-2.6", "pyodbc" ]
I use a MS SQL express db. I can connect and fetch data. But inserting data does not work: ``` cursor.execute("insert into [mydb].[dbo].[ConvertToolLog] ([Message]) values('test')") ``` I get no error but nothing is inserted into the table. Directly after I fetch the data the inserted row is fetched. But nothing is s...
You need to commit the data. Each SQL command is in a transaction and the transaction must be committed to write the transaction to the SQL Server so that it can be read by other SQL commands. Under MS SQL Server Management Studio the default is to allow auto-commit which means each SQL command immediately works and y...
Reading data into numpy array from text file
20,200,353
7
2013-11-25T18:21:51Z
20,200,407
13
2013-11-25T18:24:55Z
[ "python", "arrays", "file-io", "numpy", "genfromtxt" ]
I have a file with some metadata, and then some actual data consisting of 2 columns with headings. Do I need to separate the two types of data before using genfromtxt in numpy? Or can I somehow split the data maybe? What about placing the file pointer to the end of the line just above the headers, and then trying genfr...
If you don't want the first `n` rows, try (if there is no missing data): ``` data = numpy.loadtxt(yourFileName,skiprows=n) ``` or (if there are missing data): ``` data = numpy.genfromtxt(yourFileName,skiprows=n) ``` If you then want to parse the header information, you can go back and `open` the file parse the head...
OverflowError: (34, 'Result too large')
20,201,706
4
2013-11-25T19:36:51Z
20,201,818
9
2013-11-25T19:42:51Z
[ "python", "overflow", "decimal", "pi" ]
I'am getting an overflow error(OverflowError: (34, 'Result too large') I want to calculate pi to 100 decimals here's my code: ``` def pi(): pi = 0 for k in range(350): pi += (4./(8.*k+1.) - 2./(8.*k+4.) - 1./(8.*k+5.) - 1./(8.*k+6.)) / 16.**k return pi print(pi()) ```
You reached the limits of your platform's `float` support, probably after `k = 256`: ``` >>> k = 256 >>> (4./(8.*k+1.) - 2./(8.*k+4.) - 1./(8.*k+5.) - 1./(8.*k+6.)) / 16.**k Traceback (most recent call last): File "<stdin>", line 1, in <module> OverflowError: (34, 'Result too large') >>> k = 255 >>> (4./(8.*k+1.) - ...
OverflowError: (34, 'Result too large')
20,201,706
4
2013-11-25T19:36:51Z
20,201,845
12
2013-11-25T19:44:16Z
[ "python", "overflow", "decimal", "pi" ]
I'am getting an overflow error(OverflowError: (34, 'Result too large') I want to calculate pi to 100 decimals here's my code: ``` def pi(): pi = 0 for k in range(350): pi += (4./(8.*k+1.) - 2./(8.*k+4.) - 1./(8.*k+5.) - 1./(8.*k+6.)) / 16.**k return pi print(pi()) ```
Python floats are neither arbitary precision nor of unlimited size. When k = 349, `16.**k` is much too large - that's almost 2^1400. Fortunately, the `decimal` library allows arbitrary precision and can handle the size: ``` import decimal decimal.getcontext().prec = 100 def pi(): pi = decimal.Decimal(0) for k ...
sqlalchemy flask: AttributeError: 'Session' object has no attribute '_model_changes' on session.commit()
20,201,809
12
2013-11-25T19:42:23Z
20,203,277
20
2013-11-25T21:04:17Z
[ "python", "sqlalchemy", "flask", "flask-sqlalchemy" ]
I've seen a lot of problems with SessionMaker, but this one is slightly different. Not sure why, but sqlalchemy won't let my session object commit. In my app, I have some code that does: views.py ``` rec = session.query(Records).filter(Records.id==r).first() n = rec.checkoutRecord(current_user.id) session.add(n) ses...
Yes this is exactly problem when using `flask-sqlalchemy` models mixed with pure `sqlalchemy` session. Thing is that `flask-sqlalchemy` subclasses the base `Session` from `sqlalchemy` and adds some internals one of which is the `_model_changes` dict. This dict is used for model modification tracking. So if you want to...
Why is the cmp parameter removed from sort/sorted in Python3.0?
20,202,418
26
2013-11-25T20:16:53Z
20,202,452
13
2013-11-25T20:18:51Z
[ "python", "sorting", "object", "cmp" ]
from [python wiki](https://wiki.python.org/moin/HowTo/Sorting/#The_Old_Way_Using_the_cmp_Parameter): `In Py3.0, the cmp parameter was removed entirely (as part of a larger effort to simplify and unify the language, eliminating the conflict between rich comparisons and the __cmp__ methods).` I do not understand the rea...
`cmp` was removed because the `key` attribute to `.sort()` and `sorted()` is superior in most cases. It was a hold-over from C more than anything, and was confusing to boot. Having to implement a separate `__cmp__` method *next* to the rich comparison operators (`__lt__`, `__gt__`, etc.) was befuddling and unhelpful. ...
Why is the cmp parameter removed from sort/sorted in Python3.0?
20,202,418
26
2013-11-25T20:16:53Z
20,202,496
17
2013-11-25T20:21:12Z
[ "python", "sorting", "object", "cmp" ]
from [python wiki](https://wiki.python.org/moin/HowTo/Sorting/#The_Old_Way_Using_the_cmp_Parameter): `In Py3.0, the cmp parameter was removed entirely (as part of a larger effort to simplify and unify the language, eliminating the conflict between rich comparisons and the __cmp__ methods).` I do not understand the rea...
For two objects `a` and `b`, `__cmp__` requires that *one of* `a < b`, `a == b`, and `a > b` is true. But that might not be the case: consider sets, where it's very common that *none of those* are true, e.g. `{1, 2, 3}` vs `{4, 5, 6}`. So `__lt__` and friends were introduced. But that left Python with two separate ord...
Python string encoding for a variable
20,203,265
6
2013-11-25T21:03:37Z
20,203,312
8
2013-11-25T21:06:08Z
[ "python", "unicode", "encoding" ]
I'm aware of the fact that for Python < 3, unicode encoding for the string 'Plants vs. Zombies䋢 2' is as below: ``` u"Plants vs. Zombies䋢 2".encode("utf-8") ``` What if I have an variable (say appName) instead of a string can I do it like this: ``` appName = "Plants vs. Zombies䋢 2" u+appName.enc...
No. The `u` notation is only for string literals. Variables containing string data don't need the `u`, because the variable contains an object that is either a unicode string or a byte string. (I'm assuming here that `appName` contains string data; if it doesn't, it doesn't make sense to try to encode it. Convert it to...
class M: or class M():?
20,205,141
2
2013-11-25T22:53:42Z
20,205,174
7
2013-11-25T22:55:30Z
[ "python", "python-3.x", "coding-style" ]
For a class definition with no inheritance, is there any difference or stylistic preference between: ``` class M: pass ``` and ``` class M(): pass ``` ? I couldn't find it mentioned in PEP8.
It's not in PEP 8 because in the early days of Python 3, Guido suggested that everyone should be explicitly inheriting from `object` during the transition period. Possibly this should be updated… However, if you look at all of the examples in the documentation that don't use `class M(object):`, they all use the firs...
How to correctly parse UTF-8 encoded HTML to Unicode strings with BeautifulSoup?
20,205,455
11
2013-11-25T23:15:43Z
20,215,100
11
2013-11-26T10:55:30Z
[ "python", "unicode", "utf-8", "beautifulsoup", "urllib2" ]
I'm running a Python program which fetches a UTF-8-encoded web page, and I extract some text from the HTML using BeautifulSoup. However, when I write this text to a file (or print it on the console), it gets written in an unexpected encoding. Sample program: ``` import urllib2 from BeautifulSoup import BeautifulSoup...
As justhalf points out above, my question here is essentially a duplicate of [this question](http://stackoverflow.com/q/7219361/234938). The HTML content reported itself as UTF-8 encoded and, for the most part it was, except for one or two rogue invalid UTF-8 characters. This apparently confuses BeautifulSoup about w...
How can a pandas merge preserve order?
20,206,615
11
2013-11-26T00:59:09Z
20,206,825
7
2013-11-26T01:18:23Z
[ "python", "pandas" ]
I have two DataFrames in pandas, trying to merge them. But pandas keeps changing the order. I've tried setting indexes, resetting them, no matter what I do, I can't get the returned output to have the rows in the same order. Is there a trick? Note we start out with the loans order 'a,b,c' but after the merge, it's "a,c...
Hopefully someone will provide a better answer, but in case no one does, this will definitely work, so… Zeroth, I'm assuming you don't want to just end up sorted on `loan`, but to preserve *whatever* original order was in `x`, which may or may not have anything to do with the order of the `loan` column. (Otherwise, ...
Pushing Radix Sort (and python) to its limits
20,207,791
6
2013-11-26T03:09:45Z
20,208,114
8
2013-11-26T03:47:03Z
[ "python", "sorting", "optimization", "numpy", "radix-sort" ]
I've been immensely frustrated with many of the implementations of python radix sort out there on the web. They consistently use a radix of 10 and get the digits of the numbers they iterate over by dividing by a power of 10 or taking the log10 of the number. This is incredibly inefficient, as log10 is not a particular...
You already realized that ``` for num in unsorted: byte_at_offset = (num & byte_check) >> offset*8 buckets[byte_at_offset].append(num) ``` is where most of the time goes - good ;-) There are two standard tricks for speeding that kind of thing, both having to do with moving invariants out of loops: 1. Comput...
python set contains vs. list contains
20,208,257
6
2013-11-26T04:04:00Z
20,208,425
8
2013-11-26T04:20:44Z
[ "python", "list", "set", "contains", "equality" ]
i'm using python 2.7 consider the following snippet of code (the example is contrived): ``` import datetime class ScheduleData: def __init__(self, date): self.date = date def __eq__(self, other): try: return self.date == other.date except AttributeError as e: ...
The issue is the comparison is invoking an `__eq__` function opposite of what you're looking for. The `__eq__` method defined works when you have a `ScheduleData() == datetime.date()` but the `in` operator is performing the comparison in the opposite order, `datetime.date() == ScheduleData()` which is not invoking your...
homepage login form Django
20,208,562
10
2013-11-26T04:32:46Z
20,210,318
9
2013-11-26T06:50:12Z
[ "python", "html", "django", "login" ]
I want to create a homepage with a header that asks to login with username/password and a login button to login. Currently, how I have my page set up is that pressing login will send me to a login page. I want to simply enter in the information and press "login" to login on the homepage of my site. How can I design my ...
If you just want to have a homepage with static content that handles logins, the Django built-in auth application can handle this with very little effort. You just need to bind a URL to `django.contrib.auth.views.login` and probably one to `django.contrib.auth.views.logout`, write a login template and a post-logout tem...
panda dataframe remove constant column
20,209,600
6
2013-11-26T05:59:18Z
20,209,822
7
2013-11-26T06:16:10Z
[ "python", "pandas", "dataframe" ]
I have a dataframe that may or may not have columns that are the same value. For example ``` row A B 1 9 0 2 7 0 3 5 0 4 2 0 ``` I'd like to return just ``` row A 1 9 2 7 3 5 4 2 ``` Is there a simple way t...
Ignoring `NaN`s like usual, a column is constant if `nunique() == 1`. So: ``` >>> df A B row 0 9 0 1 1 7 0 2 2 5 0 3 3 2 0 4 >>> df = df.loc[:,df.apply(pd.Series.nunique) != 1] >>> df A row 0 9 1 1 7 2 2 5 3 3 2 4 ```
panda dataframe remove constant column
20,209,600
6
2013-11-26T05:59:18Z
20,210,048
10
2013-11-26T06:31:45Z
[ "python", "pandas", "dataframe" ]
I have a dataframe that may or may not have columns that are the same value. For example ``` row A B 1 9 0 2 7 0 3 5 0 4 2 0 ``` I'd like to return just ``` row A 1 9 2 7 3 5 4 2 ``` Is there a simple way t...
I believe this option will be faster than the other answers here as it will traverse the data frame only once for the comparison and short-circuit if a non-unique value is found. ``` >>> df 0 1 2 0 1 9 0 1 2 7 0 2 3 7 0 >>> df.loc[:, (df != df.ix[0]).any()] 0 1 0 1 9 1 2 7 2 3 7 ```
How to iterator over every [:2] overlapping characters in a string of DNA code?
20,211,024
3
2013-11-26T07:32:50Z
20,211,204
7
2013-11-26T07:42:52Z
[ "python", "string", "for-loop", "iterator", "n-gram" ]
Let's say I have a string of DNA 'GAAGGAGCGGCGCCCAAGCTGAGATAGCGGCTAGAGGCGGGTAACCGGCA' Consider the first 5 letters: GAAGG And I want to replace each overlapping bi-gram 'GA','AA','AG','GG' with some number that corresponds to their likelihood of occurrence, summing them. Like 'GA' = 1, 'AA' = 2, 'AG' = .7, 'GG' = .5....
Forget playing with `range` and index arithmetic, iterating over pairs is exactly what `zip` is for: ``` >>> dna = 'GAAGG' >>> for bigram in zip(dna, dna[1:]): ... print(bigram) ... ('G', 'A') ('A', 'A') ('A', 'G') ('G', 'G') ``` If you have the corresponding likelihoods stored in a dictionary, like so: ``` like...
Insert Null into SQLite3 in Python
20,211,942
4
2013-11-26T08:33:28Z
20,212,024
10
2013-11-26T08:39:09Z
[ "python", "sqlite3", "sql-insert" ]
I am trying to insert a None value into a row entry of my db. the table `present` exists ``` db.execute("INSERT INTO present VALUES('test', ?, 9)", "This is a test!") db.execute("INSERT INTO present VALUES('test2', ?, 10)", None) ``` but I get the error: ``` ValueError: parameters are of unsupported type ``` how do...
Use a tuple, I.E.: ``` db.execute("INSERT INTO present VALUES('test2', ?, 10)", (None,)) ```
How do I get Flask to run on port 80?
20,212,894
43
2013-11-26T09:22:46Z
20,213,086
17
2013-11-26T09:30:53Z
[ "python", "networking", "flask", "port" ]
I have a Flask server running through port 5000, and it's fine. I can access it at <http://example.com:5000> But is it possible to simply access it at <http://example.com>? I'm assuming that means I have to change the port from 5000 to 80. But when I try that on Flask, I get this error message when I run it. ``` Trac...
So it's throwing up that error message because you have `apache2` running on port 80. If this is for development, I would just leave it as it is on port 5000. If it's for production either: **Not Recommended** * Stop `apache2` first; Not recommended as it states in the documentation: > You can use the builtin ser...
How do I get Flask to run on port 80?
20,212,894
43
2013-11-26T09:22:46Z
29,079,598
88
2015-03-16T14:40:16Z
[ "python", "networking", "flask", "port" ]
I have a Flask server running through port 5000, and it's fine. I can access it at <http://example.com:5000> But is it possible to simply access it at <http://example.com>? I'm assuming that means I have to change the port from 5000 to 80. But when I try that on Flask, I get this error message when I run it. ``` Trac...
1- Stop other applications that are using port 80. 2- run application with port 80 : ``` if __name__ == '__main__': app.run(host='0.0.0.0', port=80) ```
Python count all possible combinations for a table
20,214,126
8
2013-11-26T10:16:07Z
20,296,866
15
2013-11-30T05:20:18Z
[ "python", "table", "matrix", "combinations", "permutation" ]
I have a table that looks like below: ``` PotA PotB PotC PotD PotE A + + + + + B - ? + + ? C + + + + + D + - + - + E + + + + + ``` From here, I have to find all the possible combinations of "+","-" and "?" for all combina...
Assuming I understand what you're after, how about something like: ``` import itertools import collections def read_table(filename): with open(filename) as fp: header = next(fp).split() rows = [line.split()[1:] for line in fp if line.strip()] columns = zip(*rows) data = dict(zip(header...
Annoying white space in bar chart (matplotlib, Python)
20,214,497
11
2013-11-26T10:30:42Z
20,217,920
13
2013-11-26T13:05:50Z
[ "python", "matplotlib", "bar-chart" ]
It's probably a trivial question, but I am trying to plot a bar chart with matplotlib and with rotated text on the x axis. The code I'm using is shown below: ``` fig = plt.figure() x_labels_list = [] for i in range(0, pow(2, N)): x_labels_list.append(str(f(i))) # The function f() converts i to a binary string ...
Try calling `plt.xlim()` with the number of bins, e.g. ``` plt.xlim([0,bins.size]) ``` Here is an example: ``` #make some data N = 22 data = np.random.randint(1,10,N) bin = np.arange(N) width = 1 #plot it ax = plt.subplot(111) ax.bar(bin, data, width, color='r') plt.show() ``` No `plt.xlim()` output: ![no xlim]...
Analyzing high WSGI/Response time data of django with mod_wsgi on NewRelic
20,214,508
4
2013-11-26T10:31:21Z
20,231,590
8
2013-11-27T02:02:56Z
[ "python", "django", "apache", "mod-wsgi", "newrelic" ]
Project deployment as: django with apache mod\_wsgi Got New Relic lite version configured to track web performance. On the New Relic -> Monitoring -> Web transactions panel -> Sort on Most time consuming -> Selecting on First entry -> Breakdown Table -> WSGI/Response seems to consume 81% of the time * What exactly ...
Consider a simple WSGI hello world program. ``` def application(environ, start_response): status = '200 OK' output = 'Hello World!' response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))] start_response(status, response_headers) return [ou...
How to write to an existing excel file without overwriting data (using pandas)?
20,219,254
19
2013-11-26T14:05:22Z
20,221,655
32
2013-11-26T15:45:59Z
[ "python", "excel", "python-2.7", "pandas" ]
I use pandas to write to excel file in the following fashion: ``` import pandas writer = pandas.ExcelWriter('Masterfile.xlsx') data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2']) writer.save() ``` Masterfile.xlsx already consists of number of different tabs. Pandas correctly writes to "Main" sheet, u...
Pandas docs says it uses openpyxl for xlsx files. Quick look through the code in `ExcelWriter` gives a clue that something like this might work out: ``` import pandas from openpyxl import load_workbook book = load_workbook('Masterfile.xlsx') writer = pandas.ExcelWriter('Masterfile.xlsx', engine='openpyxl') writer.bo...
How to write to an existing excel file without overwriting data (using pandas)?
20,219,254
19
2013-11-26T14:05:22Z
31,061,820
13
2015-06-25T22:22:15Z
[ "python", "excel", "python-2.7", "pandas" ]
I use pandas to write to excel file in the following fashion: ``` import pandas writer = pandas.ExcelWriter('Masterfile.xlsx') data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2']) writer.save() ``` Masterfile.xlsx already consists of number of different tabs. Pandas correctly writes to "Main" sheet, u...
For me skyjur's answer almost worked. I had to set the engine for the writer explicitly with: ``` writer = pd.ExcelWriter(excel_file, engine='openpyxl') ``` otherwise it would throw ``` AttributeError: 'Workbook' object has no attribute 'add_worksheet' ```
Problems with python easy install
20,219,628
2
2013-11-26T14:21:35Z
20,221,312
8
2013-11-26T15:31:01Z
[ "python", "python-2.7", "matplotlib", "easy-install" ]
I have a problem using easy\_install for matplotlib-venn. I'm on a windows computer using python2.7. I'm suspecting the path is not correct but I do not know how to fix the problem. Could anyone help me? I'm attaching the output from trying to run the easy\_install command in the CMD prompter. ``` C:\Python27\Scripts>...
Based on ``` Download error on https://pypi.python.org/simple/matplotlib-venn/: [Errno 11004] getaddrinfo failed ``` and ``` Cannot fetch index base URL https://pypi.python.org/simple/ ``` it seems that your have network issue. Do you run your machine behind a firewall or a proxy? For `easy_install` to work behind...
python multiprocessing on windows, if __name__ == "__main__"
20,222,534
6
2013-11-26T16:26:23Z
20,222,706
13
2013-11-26T16:34:20Z
[ "python", "multiprocessing" ]
Running python 2.7 on windows 7 (64bit). When reading the docs for library module `multiprocessing`, it states several times the importance of the `__main__` module, including the conditional (especially in Windows): ``` if __name__ == "__main__": # create Process() here ``` My understanding, is that you don't w...
You do not have to call `Process()` to the "top level" of the module. It is perfectly fine to call `Process` from a class method. The only caveat is that you can not allow `Process()` to be called if or when *the module is imported*. Since Windows has no `fork`, the multiprocessing module starts a new Python process ...
how to extract the decision rules from scikit-learn decision-tree?
20,224,526
36
2013-11-26T17:58:00Z
20,225,985
10
2013-11-26T19:14:46Z
[ "python", "machine-learning", "scikit-learn", "decision-tree", "random-forest" ]
Can I extract the underlying decision-rules (or 'decision paths') from a trained tree in a decision tree - as a textual list ? something like: `"if A>0.4 then if B<0.2 then if C>0.8 then class='X'` etc... If anyone knows of a simple way to do so, it will be very helpful.
``` from StringIO import StringIO out = StringIO() out = tree.export_graphviz(clf, out_file=out) print out.getvalue() ``` You can see a digraph Tree. Then, `clf.tree_.feature` and `clf.tree_.value` are array of nodes splitting feature and array of nodes values respectively. You can refer to more details from this [git...
how to extract the decision rules from scikit-learn decision-tree?
20,224,526
36
2013-11-26T17:58:00Z
22,261,053
29
2014-03-07T21:31:16Z
[ "python", "machine-learning", "scikit-learn", "decision-tree", "random-forest" ]
Can I extract the underlying decision-rules (or 'decision paths') from a trained tree in a decision tree - as a textual list ? something like: `"if A>0.4 then if B<0.2 then if C>0.8 then class='X'` etc... If anyone knows of a simple way to do so, it will be very helpful.
I created my own function to extract the rules from the decision trees created by sklearn: ``` import pandas as pd import numpy as np from sklearn.tree import DecisionTreeClassifier # dummy data: df = pd.DataFrame({'col1':[0,1,2,3],'col2':[3,4,5,6],'dv':[0,1,0,1]}) # create decision tree dt = DecisionTreeClassifier(...
how to extract the decision rules from scikit-learn decision-tree?
20,224,526
36
2013-11-26T17:58:00Z
30,104,792
28
2015-05-07T14:58:42Z
[ "python", "machine-learning", "scikit-learn", "decision-tree", "random-forest" ]
Can I extract the underlying decision-rules (or 'decision paths') from a trained tree in a decision tree - as a textual list ? something like: `"if A>0.4 then if B<0.2 then if C>0.8 then class='X'` etc... If anyone knows of a simple way to do so, it will be very helpful.
I modified the code submitted by [Zelazny7](http://stackoverflow.com/users/919872/zelazny7) to print some pseudocode: ``` def get_code(tree, feature_names): left = tree.tree_.children_left right = tree.tree_.children_right threshold = tree.tree_.threshold features = [feature_n...
Comparing two dataframes and getting the differences
20,225,110
11
2013-11-26T18:31:15Z
20,228,113
20
2013-11-26T21:14:50Z
[ "python", "pandas", "dataframe" ]
I have two dataframes. Examples: ``` df1: Date Fruit Num Color 2013-11-24 Banana 22.1 Yellow 2013-11-24 Orange 8.6 Orange 2013-11-24 Apple 7.6 Green 2013-11-24 Celery 10.2 Green df2: Date Fruit Num Color 2013-11-24 Banana 22.1 Yellow 2013-11-24 Orange 8.6 Orange 2013-11-24 Apple 7.6 Green 2013...
This approach, `df1 != df2`, works only for dataframes with identical rows and columns. In fact, all dataframes axes are compared with `_indexed_same` method, and exception is raised if differences found, even in columns/indices order. If I got you right, you want not to find changes, but symmetric difference. For tha...
Why does this Python script have a \ before the multi-line string and what does it do?
20,225,449
6
2013-11-26T18:49:25Z
20,225,470
8
2013-11-26T18:50:22Z
[ "python", "string", "multiline" ]
In a Python script I'm looking at the string has a \ before it: ``` print """\ Content-Type: text/html\n <html><body> <p>The submited name was "%s"</p> </body></html> """ % name ``` If I remove the \ it breaks. What does it do?
It tells Python to ignore the newline directly following the backslash. The resulting string starts with `Content-Type:`, not with `\nContent-Type:`: ``` >>> '''\ This is the first line. This is the second line. ''' 'This is the first line.\nThis is the second line.\n' >>> ''' ... This is the first line. ... This is t...
How to document a module constant in Python?
20,227,051
23
2013-11-26T20:15:01Z
20,227,174
26
2013-11-26T20:21:12Z
[ "python", "python-sphinx", "restructuredtext" ]
I have a module, `errors.py` in which several global constants are defined (note: I understand that Python doesn't have constants, but I've defined them by convention using UPPERCASE). ``` """Indicates some unknown error.""" API_ERROR = 1 """Indicates that the request was bad in some way.""" BAD_REQUEST = 2 """Indic...
Unfortunately, variables (and constants) do not have docstrings. After all, the variable is just a name for an integer, and you wouldn't want to attach a docstring to the number `1` the way you would to a function or class object. If you look at almost any module in the stdlib, like [`pickle`](http://hg.python.org/cpy...
How to document a module constant in Python?
20,227,051
23
2013-11-26T20:15:01Z
20,230,473
8
2013-11-26T23:57:32Z
[ "python", "python-sphinx", "restructuredtext" ]
I have a module, `errors.py` in which several global constants are defined (note: I understand that Python doesn't have constants, but I've defined them by convention using UPPERCASE). ``` """Indicates some unknown error.""" API_ERROR = 1 """Indicates that the request was bad in some way.""" BAD_REQUEST = 2 """Indic...
If you put a string *after* the variable, then sphinx will pick it up as the variable's documentation. I know it works because I do it all over the place. Like this: ``` FOO = 1 """ Constant signifying foo. Blah blah blah... """ # pylint: disable=W0105 ``` The pylint directive tells pylint to avoid flagging the doc...
Programmatically Download Content from Shared Dropbox Folder Links
20,227,324
14
2013-11-26T20:29:06Z
20,243,081
12
2013-11-27T12:53:35Z
[ "python", "dropbox", "dropbox-api" ]
I'm building an application to automatically trigger a download of a Dropbox file shared with a user (shared file/folder link). This was straight forward to implement for Dropbox links to files, as is outlined [here](https://www.dropbox.com/developers/blog/53/programmatically-download-content-from-share-links). Unfort...
Dropbox's support team just filled me in on the best way to do this: Just add `?dl=1` to the end of the shared link. That'll give you a zipped version of the shared folder. So if the link shared with a user is `https://www.dropbox.com/sh/xyz/xyz-YZ` (or similar, which links to a shared folder), to download a zipped v...
Put data in a particularly shaped list
20,227,867
2
2013-11-26T21:00:51Z
20,227,981
8
2013-11-26T21:08:24Z
[ "python", "numpy", "scipy" ]
I have a list that looks like this: ``` my_list = [[20, 15, 10], [15, 22, 37, 46], [22, 91]] ``` So it is two dimensional, but not every line has the same number of elements. I now have a flat ndarray, like: ``` my_ndarray = np.array([9, 2, 4, 4, 1, 6, 7, 8, 17]) ``` That have the same amount of elements with my\_...
``` >>> it = iter([9, 2, 4, 4, 1, 6, 7, 8, 17]) >>> my_list = [[20, 15, 10], [15, 22, 37, 46], [22, 91]] >>> [[next(it) for i in j] for j in my_list] [[9, 2, 4], [4, 1, 6, 7], [8, 17]] ```
How do I apply some function to a python meshgrid?
20,228,546
4
2013-11-26T21:41:06Z
20,228,722
11
2013-11-26T21:51:26Z
[ "python", "numpy", "matplotlib" ]
Say I want to calculate a value for every point on a grid. I would define some function `func` that takes two values `x` and `y` as parameters and returns a third value. In the example below, calculating this value requires a look-up in an external dictionary. I would then generate a grid of points and evaluate `func` ...
I'd use numpy.vectorize to "vectorize" your function. Note that despite the name, `vecotrize` is not intended to make your code run faster -- Just simplify it a bit. Here's some examples: ``` >>> import numpy as np >>> @np.vectorize ... def foo(a, b): ... return a + b ... >>> foo([1,3,5], [2,4,6]) array([ 3, 7, ...
Check if all values in list are greater than a certain number
20,229,822
10
2013-11-26T23:01:18Z
20,229,831
31
2013-11-26T23:02:04Z
[ "python", "list", "function", "max" ]
``` my_list1 = [30,34,56] my_list2 = [29,500,43] ``` How to I check if all values in list are >= 30? `my_list1` should work and `my_list2` should not. The only thing I could think of doing was: ``` boolean = 0 def func(ls): for k in ls: if k >= 30: boolean = boolean + 1 else: ...
Use the [`all()` function](http://docs.python.org/2/library/functions.html#all) with a generator expression: ``` >>> my_list1 = [30, 34, 56] >>> my_list2 = [29, 500, 43] >>> all(i >= 30 for i in my_list1) True >>> all(i >= 30 for i in my_list2) False ``` Note that this tests for greater than *or equal to* 30, otherwi...
Why do python's itertools permutations have a lot of repeated elements?
20,230,352
4
2013-11-26T23:44:42Z
20,230,410
8
2013-11-26T23:49:24Z
[ "python", "permutation", "itertools" ]
I am trying to find the different permutations of the string "0000111". All the different strings that contain three 1s and four 0s. This is my code: ``` p = itertools.permutations("0000111") l = list(p) print len(l) #5040 print len(set(l)) #35 ``` What's wrong? And is there a better way?
It's in the manual: <http://docs.python.org/2.7/library/itertools.html#itertools.permutations> > Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values in each permutation. That means that `itertools.permutations('000')` will hap...
arithmetic expression reader in python
20,231,306
3
2013-11-27T01:27:15Z
20,231,411
7
2013-11-27T01:39:03Z
[ "python" ]
I am trying to make an expression reader in python to compute basic arithmetic. given the expression `subtract(4,add(4,times(3,4)))` --> -12 What would be the most pythonic way to build this? My method would be to convert the expression to a string, then create many if statements or switch cases to find keywords such...
Here's some working code to get you started using `ast`: ``` import ast s = 'subtract(4,add(4,times(3,4)))' # Probably better to use functions from the operator module here :-) functions = {'subtract': lambda a,b: a-b, 'add': lambda a, b: a+b, 'times': lambda a,b: a*b} def _evaluate(node)...
Filter Pandas DataFrame by time index
20,233,071
14
2013-11-27T02:59:30Z
20,233,649
19
2013-11-27T04:01:40Z
[ "python", "pandas" ]
I have a pandas DataFrame from 6:36 AM to 5:31 PM. I want to remove all observations where the time is less than 8:00:00 AM. Here is my attempt: ``` df = df[df.index < '2013-10-16 08:00:00'] ``` This does nothing, please help.
You want `df.loc[df.index < '2013-10-16 08:00:00']` since you're selecting by label (index) and not by value. [selecting by label](http://pandas.pydata.org/pandas-docs/stable/indexing.html#selection-by-label)
Python find max number of combinations in binary
20,233,224
3
2013-11-27T03:14:43Z
20,233,260
7
2013-11-27T03:18:58Z
[ "python", "list", "binary" ]
Hi I'm trying to figure out a function where given a length n of a list [x1, x2... xn], how many digits would be needed for a base 2 number system to assign a unique code to each value in the list. For example, one digit can hold two unique values: ``` x1 0 x2 1 ``` two digits can hold four: ``` x1 00 x2 01 x3 10 x...
``` >>> for i in range(10): ... print i, i.bit_length() 0 0 1 1 2 2 3 2 4 3 5 3 6 3 7 3 8 4 9 4 ``` I'm not clear on exactly what it is you want, but it *appears* you want to subtract 1 from what `bit_length()` returns - or maybe not ;-) On third thought ;-), maybe you really want this: ``` def calcBitDigits(n): ...
django translate model choices
20,233,319
3
2013-11-27T03:26:20Z
20,810,940
8
2013-12-28T04:18:12Z
[ "python", "django", "django-models" ]
I need translate a choices for a field on the model. I have something like this: ``` from django.utils.translation import ugettext as _ from django.db import models class MyModel(models.Model): TYPES = ( (1, _("Option one")), (2, _("Option two")) (3, _("Option three")) ) type = mod...
In models.py, you need to ``` from django.utils.translation import ugettext_lazy as _ ``` ugettext\_lazy will return a callable rather than the translated string. When the callable is evaluated later, it will return the translated string. It will be late enough that it will get the right language for the view/templat...
Why are Python decorators with arguments syntactically different from those without?
20,234,533
7
2013-11-27T05:22:58Z
20,234,636
8
2013-11-27T05:31:04Z
[ "python", "arguments", "decorator", "callable" ]
[This article](http://www.artima.com/weblogs/viewpost.jsp?thread=240845), linked to a number of times from various stackoverflow questions, describes how decorators with arguments are syntactically different from those without arguments. * Decorators without arguments: "Notice that `__init__()` is the only method call...
It's because it's the decorator object that's being called in both cases. To make it clearer, given this: ``` def my_decorator(a): def wrapper(f): def wrapped_function(): return f() + a return wrapped_function return wrapper ``` this: ``` @my_decorator(5) def function(): retur...
Python "in" operator speed
20,234,935
4
2013-11-27T05:54:42Z
20,234,990
17
2013-11-27T05:58:57Z
[ "python", "time", "size", "in-operator" ]
Is the `in` operator's speed in python proportional to the length of the iterable? So, ``` len(x) #10 if(a in x): #lets say this takes time A pass len(y) #10000 if(a in y): #lets say this takes time B pass ``` Is A > B?
A summary for in: ``` list - Average: O(n) set/dict - Average: O(1), Worst: O(n) ``` See [this](https://wiki.python.org/moin/TimeComplexity) for more details.
Python "in" operator speed
20,234,935
4
2013-11-27T05:54:42Z
20,234,998
7
2013-11-27T05:59:18Z
[ "python", "time", "size", "in-operator" ]
Is the `in` operator's speed in python proportional to the length of the iterable? So, ``` len(x) #10 if(a in x): #lets say this takes time A pass len(y) #10000 if(a in y): #lets say this takes time B pass ``` Is A > B?
There's no general answer to this: it depends on the types of `a` and especially of `b`. If, for example, `b` is a list, then yes, `in` takes worst-case time `O(len(b))`. But if, for example, `b` is a dict or a set, then `in` takes expected-case time `O(1)` (i.e., constant time). About "Is A > B?", you didn't define `...
Remove NaN from pandas series
20,235,401
24
2013-11-27T06:26:28Z
20,235,451
43
2013-11-27T06:29:56Z
[ "python", "pandas", "series" ]
Is there a way to remove a NaN values from a panda series? I have a series that may or may not have some NaN values in it, and I'd like to return a copy of the series with all the NaNs removed.
``` >>> s = pd.Series([1,2,3,4,np.NaN,5,np.NaN]) >>> s[~s.isnull()] 0 1 1 2 2 3 3 4 5 5 ``` **update** or even better approach as @DSM suggested in comments, using [`pandas.Series.dropna()`](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.dropna.html): ``` >>> s.dropna() 0 1 1 2 ...
Django python manage.py migrate
20,238,317
13
2013-11-27T09:22:04Z
20,239,353
17
2013-11-27T10:05:11Z
[ "python", "django", "windows" ]
I have installed on Win7 portable Python 2.7.5.1 and Django 1.6. I followed the first polls tutorial instructions and got an error in the migrate stage, `python manage.py migrate`: ``` C:\Natan\Dev\Portable Python 2.7.5.1\App\Scripts\mysite>..\..\python.exe manage.py migrate Unknown command: 'migrate' Type 'manage.py...
If you've installed 1.6, you should use the [1.6 tutorial](https://docs.djangoproject.com/en/1.6/intro/tutorial01/), not the one for the development version.
Django python manage.py migrate
20,238,317
13
2013-11-27T09:22:04Z
23,512,362
8
2014-05-07T08:15:48Z
[ "python", "django", "windows" ]
I have installed on Win7 portable Python 2.7.5.1 and Django 1.6. I followed the first polls tutorial instructions and got an error in the migrate stage, `python manage.py migrate`: ``` C:\Natan\Dev\Portable Python 2.7.5.1\App\Scripts\mysite>..\..\python.exe manage.py migrate Unknown command: 'migrate' Type 'manage.py...
First Step, Install South: > pip install south Second Step, Add South to INSTALLED APPS in settings > INSTALLED\_APPS = ( > ..., > 'south' )
Error: That port is already in use.
20,239,232
58
2013-11-27T10:00:43Z
20,240,445
149
2013-11-27T10:53:11Z
[ "python", "django" ]
when i try django restarting its showing message : this port is already running.... this problem specially on ubunut 10.x not all OS.how I might achieve this on the current system that I am working on? can you suggest me?
A more simple solution just type `sudo fuser -k 8000/tcp`. This should kill all the processes associated with port 8000. EDIT: For osx users you can use `sudo lsof -t -i tcp:8000 | xargs kill -9`
Error: That port is already in use.
20,239,232
58
2013-11-27T10:00:43Z
34,824,239
8
2016-01-16T06:29:12Z
[ "python", "django" ]
when i try django restarting its showing message : this port is already running.... this problem specially on ubunut 10.x not all OS.how I might achieve this on the current system that I am working on? can you suggest me?
``` netstat -ntlp ``` It will show something like this. ``` Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 127.0.0.1:8000 0.0.0.0:* LISTEN 6599/python tcp ...
Python Logging Handler
20,239,857
4
2013-11-27T10:27:28Z
20,241,020
7
2013-11-27T11:18:30Z
[ "python", "logging" ]
I want to add a userdefined variable to the logger format using ContextFiltering. My code is as follows : ``` import logging import logging.handlers CMDID='TEST' class ContextFilter(logging.Filter): def filter(self,record): record.CMDID=CMDID return True FORMAT='%(asctime)s [%(CMDID)s] - %(message)s' logge...
Change `logger.handlers.` to `logging.handlers.` and beware of typos (there is no `setlevel`-method, but a `setLevel`-method). The following code works fine: ``` import logging import logging.handlers CMDID='TEST' class ContextFilter(logging.Filter): def filter(self,record): record.CMDID=CMDID return True ...
python logging file is not working when using logging.basicConfig
20,240,464
4
2013-11-27T10:53:51Z
20,280,587
13
2013-11-29T07:36:29Z
[ "python", "logging" ]
I have the following lines of code that initialize logging. I comment one out and leave the other to be used. The problem that I'm facing is that the one that is meant to log to the file not loggint to file. It is instead logging to the console. Please help. ## For logging to Console: ``` logging.basicConfig(level=lo...
I found out what the problem was. It was in the ordering of the imports and the logging definition. The effect of the poor ordering was that the libraries that I imported before defining the logging using `loggin.basicConfig()` defined the logging. This therefore took precedence to the logging that I was trying to def...
Updating m2m not possible when using serializers as fields
20,241,542
4
2013-11-27T11:43:44Z
22,155,708
7
2014-03-03T19:37:50Z
[ "python", "django", "django-rest-framework" ]
I have following models: ``` class Song(models.Model): name = models.CharField(max_length=64) def __unicode__(self): return self.name class UserProfile(AbstractUser): current = models.ManyToManyField(Song, related_name="in_current", blank=True) saved = models.ManyToManyField(Song, related_nam...
Yes you can. you need to set `allow_add_remove` to `True` and `read_only` to `False`: ``` current = SongSerializer(many=True, allow_add_remove=True, read_only=False) ``` Note that the current implementation of nested serializers will remove the whole Song object from DB, not only the relation.
Printing a Tree data structure in Python
20,242,479
9
2013-11-27T12:25:49Z
20,242,504
11
2013-11-27T12:26:44Z
[ "python", "python-2.7", "printing", "tree" ]
I was looking for a possible implementation of tree printing, which prints the tree in a user-friendly way, and not as an instance of object. I came across this solution on the net: source: <http://cbio.ufs.ac.za/live_docs/nbn_tut/trees.html> ``` class node(object): def __init__(self, value, children = []): ...
Yes, move the `__repr__` code to `__str__`, then call `str()` on your tree or pass it to the `print` statement. Remember to use `__str__` in the recursive calls too: ``` class node(object): def __init__(self, value, children = []): self.value = value self.children = children def __str__(self, ...
Open a page programatically in python
20,242,794
3
2013-11-27T12:40:30Z
20,243,056
7
2013-11-27T12:52:29Z
[ "python", "web-scraping", "beautifulsoup", "urllib2", "mechanize" ]
Can you extract the VIN number from this [webpage](https://www.iaai.com/Vehicles/VehicleDetails.aspx?auctionID=14712591&itemID=15775059&RowNumber=0)? I tried `urllib2.build_opener`, requests, and mechanize. I provided user-agent as well, but none of them could see the VIN. ``` opener = urllib2.build_opener() opener.a...
That page has much of the information loaded and displayed with Javascript (probably through Ajax calls), most likely as a direct protection against scraping. To scrape this you therefore either need to use a browser that runs Javascript, and control it remotely, or write the scraper itself in javascript, or you need t...
PyQt4 center window on active screen
20,243,637
6
2013-11-27T13:20:24Z
20,244,839
7
2013-11-27T14:17:32Z
[ "python", "user-interface", "python-3.x", "pyqt", "pyqt4" ]
How I can center window on active screen but not on general screen? This code moves window to center on general screen, not active screen: ``` import sys from PyQt4 import QtGui class MainWindow(QtGui.QWidget): def __init__(self): super(MainWindow, self).__init__() self.initUI() def initUI(...
Modify your `center` method to be as follows: ``` def center(self): frameGm = self.frameGeometry() screen = QtGui.QApplication.desktop().screenNumber(QtGui.QApplication.desktop().cursor().pos()) centerPoint = QtGui.QApplication.desktop().screenGeometry(screen).center() frameGm.moveCenter(centerPoint) ...
Multiple incompatible subclass instances of InteractiveShellEmbed are being created
20,243,754
6
2013-11-27T13:25:54Z
20,252,673
8
2013-11-27T20:40:29Z
[ "python", "django", "ipython", "anaconda" ]
If I install the [Anaconda Python Distribution](http://docs.continuum.io/anaconda/) and try to run `ipython manage.py shell` from within my django app, the error below is thrown. I know that when I install anaconda, it comes packaged with python and ipython whose version differs from the other python/ipython versions I...
You want to use ``` python manage.py shell ``` not ``` ipython manage.py shell ``` `manage.py` shell starts an embedded IPython instance. When you run this via `ipython manage.py`, you are starting a regular IPython session, in which you run a script that tries to embed IPython. That means you are starting two inst...
Flask-RESTful - Return custom Response format
20,243,850
9
2013-11-27T13:30:34Z
20,246,014
10
2013-11-27T15:09:18Z
[ "python", "python-2.7", "flask", "flask-restful" ]
I have defined a custom Response format as per the Flask-RESTful documentation as follow. ``` app = Flask(__name__) api = restful.Api(app) @api.representation('application/octet-stream') def binary(data, code, headers=None): resp = api.make_response(data, code) resp.headers.extend(headers or {}) return re...
What representation is used is determined by the *request*, the `Accept` header mime type. A request of `application/octet-stream` will be responded to by using your `binary` function. If you need a specific response type from an API method, then you'll have to use `flask.make_response()` to return a 'pre-baked' resp...
Python lambda expression
20,244,171
9
2013-11-27T13:46:21Z
20,244,192
13
2013-11-27T13:47:14Z
[ "python", "lambda" ]
Consider the following: ``` >>> a=2 >>> f=lambda x: x**a >>> f(3) 9 >>> a=4 >>> f(3) 81 ``` I would like for `f` not to change when `a` is changed. What is the nicest way to do this?
You need to bind `a` to a keyword argument when defining the `lambda`: ``` f = lambda x, a=a: x**a ``` Now `a` is a local (bound as an argument) instead of a global name. Demo: ``` >>> a = 2 >>> f = lambda x, a=a: x**a >>> f(3) 9 >>> a = 4 >>> f(3) 9 ```
Python & Selenium - how do I find all element IDs on a page?
20,244,691
8
2013-11-27T14:10:24Z
20,245,620
9
2013-11-27T14:52:54Z
[ "python", "selenium" ]
I know that I can use methods such as: ``` find_elements_by_tag_name() find_elements_by_id() find_elements_by_css_selector() find_elements_by_xpath() ``` But what I would like to do is simply get a list of all the element IDs that exist in the page, perhaps along with the tag type they occur in. How can I accomplish...
Not had to do this before, but thinking about it logically you could use XPath to do this (may be other ways, XPath is the first thing that appears into my head). Use `find_elements_by_xpath` using the XPath `//*[@id]` (**any** element that has an ID of some sort). You could then iterate through the collection, and u...
Content-Type in for individual files in python requests
20,244,757
3
2013-11-27T14:13:24Z
20,245,210
7
2013-11-27T14:35:23Z
[ "python", "request", "content-type" ]
I want to request to my server running in python flask with file and some meta information. Hence my request content-Type will be 'multipart/form-data. Is there a way i can set the content type of file like image/jpg, image/gif etc... How do i set the content-type for the file. Is it possible or not
If you make each file specification a tuple, you can specify the mime type as a third parameter: ``` files = { 'file1': ('foo.gif', open('foo.gif', 'rb'), 'image/gif'), 'file2': ('bar.png', open('bar.png', 'rb'), 'image/png'), } response = requests.post(url, files=files) ``` You can give a 4th parameter as we...
Difference Between numpy.genfromtxt and numpy.loadtxt, and Unpack
20,245,593
6
2013-11-27T14:51:48Z
20,245,874
7
2013-11-27T15:03:43Z
[ "python", "function", "python-2.7", "numpy" ]
I am rather new to python--actually, new to programming in general, though I am afraid I can't use that excuse forever--, and am curious to know the difference between the two functions alluded to in the title of this thread. From the website containing the documentation, it says, "numpy.loadtxt [is] [an] equivalent fu...
You are correct. Using `np.genfromtxt` gives you some options like the parameters `missing_values`, `filling_values` that can help you dealing with an incomplete `csv`. Example: ``` 1,2,,,5 6,,8,, 11,,,, ``` Could be read with: ``` filling_values = (111, 222, 333, 444, 555) # one for each column np.genfromtxt(filena...
How references to variables are resolved in Python
20,246,523
46
2013-11-27T15:30:58Z
20,250,802
17
2013-11-27T18:58:29Z
[ "python", "variables", "python-2.7", "scope", "python-internals" ]
This message is a a bit long with many examples, but I hope it will help me and others to better grasp the full story of variables and attribute lookup in Python 2.7. I am using the terms of PEP 227 (<http://www.python.org/dev/peps/pep-0227/>) for code blocks (such as modules, class definition, function definitions, e...
In two words, the difference between example 5 and example 6 is that in example 5 the variable `x` is also assigned to in the same scope, while not in example 6. This triggers a difference that can be understood by historical reasons. This raises UnboundLocalError: ``` x = "foo" def f(): print x x = 5 f() ```...
How references to variables are resolved in Python
20,246,523
46
2013-11-27T15:30:58Z
20,251,362
20
2013-11-27T19:27:21Z
[ "python", "variables", "python-2.7", "scope", "python-internals" ]
This message is a a bit long with many examples, but I hope it will help me and others to better grasp the full story of variables and attribute lookup in Python 2.7. I am using the terms of PEP 227 (<http://www.python.org/dev/peps/pep-0227/>) for code blocks (such as modules, class definition, function definitions, e...
In an ideal world, you'd be right and some of the inconsistencies you found would be wrong. However, CPython has optimized some scenarios, specifically function locals. These optimizations, together with how the compiler and evaluation loop interact and historical precedent, lead to the confusion. Python translates co...
Limiting/throttling the rate of HTTP requests in GRequests
20,247,354
15
2013-11-27T16:06:15Z
20,365,264
20
2013-12-04T01:42:25Z
[ "python", "http", "python-requests", "throttling", "rate-limiting" ]
I'm writing a small script in Python 2.7.3 with [GRequests](https://github.com/kennethreitz/grequests) and lxml that will allow me to gather some collectible card prices from various websites and compare them. Problem is one of the websites limits the number of requests and sends back HTTP error 429 if I exceed it. Is...
Going to answer my own question since I had to figure this by myself and there seems to be very little info on this going around. The idea is as follows. Every request object used with GRequests can take a session object as a parameter when created. Session objects on the other hand can have HTTP adapters mounted that...
Limiting/throttling the rate of HTTP requests in GRequests
20,247,354
15
2013-11-27T16:06:15Z
21,584,637
8
2014-02-05T17:48:34Z
[ "python", "http", "python-requests", "throttling", "rate-limiting" ]
I'm writing a small script in Python 2.7.3 with [GRequests](https://github.com/kennethreitz/grequests) and lxml that will allow me to gather some collectible card prices from various websites and compare them. Problem is one of the websites limits the number of requests and sends back HTTP error 429 if I exceed it. Is...
Take a look at this for automatic requests throttling: <https://pypi.python.org/pypi/RequestsThrottler/0.2.2> You can set both a fixed amount of delay between each request or set a number of requests to send in a fixed amount of seconds (which is basically the same thing): ``` import requests from requests_throttler ...
Rolling mean with customized window with Pandas
20,249,149
6
2013-11-27T17:28:30Z
20,249,295
12
2013-11-27T17:36:02Z
[ "python", "pandas" ]
Is there a way to customize the window of the rolling\_mean function? ``` data 1 2 3 4 5 6 7 8 ``` Let's say the window is set to 2, that is to calculate the average of 2 datapoints before and after the obervation including the observation. Say the 3rd observation. In this case, we will have `(1+2+3+4+5)/5 = 3`. So o...
Compute the usual rolling mean with a forward (or backward) window and then use the `shift` method to re-center it as you wish. ``` data_mean = pd.rolling_mean(data, window=5).shift(-2) ``` If you want to average over 2 datapoints before and after the observation (for a total of 5 datapoints) then make the `window=5`...
Django: Error: Unknown command: 'makemigrations'
20,250,123
21
2013-11-27T18:19:36Z
20,250,158
22
2013-11-27T18:21:22Z
[ "python", "django", "migration" ]
I am trying to follow the `Django` tutorial and I faced the following error when I enter `python manage.py makemigrations polls` ``` Unknown command: 'makemigrations' ``` Here's the [link](https://docs.djangoproject.com/en/dev/intro/tutorial01/) to the tutorial and I accomplished all the previous steps successfully a...
Migrations were first added in version 1.7, officially released on September 2, 2014. You need to make sure your tutorial matches the version of Django you're working with. For instance, this version of the tutorial covers 1.9: <https://docs.djangoproject.com/en/1.9/intro/tutorial01/> Or, if you're using an older ver...
Converting string that looks like a list into a real list - python
20,250,396
2
2013-11-27T18:36:12Z
20,250,415
8
2013-11-27T18:37:06Z
[ "python", "string", "list", "int", "tuples" ]
My input files have lines that looks like this: ``` [(0, 1), (1, 3), (2, 1), (3, 1), (4, 1)] [(0, 1, 6), (1, 3,7), (3, 1,4), (3, 1,3), (8, 1,2)] [1,2,3,5,3] ``` There are no letters, no decimals, only integers and number of element in tuples will be consistent. How do i make them into real list of tuples / list of i...
Python comes with batteries included - that problem is solved by [`ast.literal_eval()`](http://docs.python.org/2/library/ast.html#ast.literal_eval): ``` >>> import ast >>> ast.literal_eval("[(0, 1), (1, 3), (2, 1), (3, 1), (4, 1)]") [(0, 1), (1, 3), (2, 1), (3, 1), (4, 1)] >>> ast.literal_eval("[(0, 1, 6), (1, 3,7), (...
Plotting a large number of points using matplotlib and running out of memory
20,250,689
6
2013-11-27T18:52:36Z
20,252,623
7
2013-11-27T20:36:59Z
[ "python", "matplotlib", "large-data" ]
I have a large (~6GB) text file in a simple format ``` x1 y1 z1 x2 y2 z2 ... ``` Since I may load this data more than once, I've created a `np.memmap` file for efficiency reasons: ``` X,Y,Z = np.memmap(f_np_mmap,dtype='float32',mode='r',shape=shape).T ``` What I'm trying to do is plot: ``` plt.scatter(X, Y, ...
@tcaswell's suggestion to override the `Axes.draw` method is definitely the most flexible way to approach this. However, you can use/abuse blitting to do this without subclassing `Axes`. Just use `draw_artist` each time without restoring the canvas. There's one additional trick: We need to have a special `save` metho...
Remap values in pandas column with a dict
20,250,771
32
2013-11-27T18:56:58Z
20,250,947
11
2013-11-27T19:04:34Z
[ "python", "dictionary", "pandas", "remap" ]
I have a dictionary which looks like this: `di = {1: "A", 2: "B"}` I would like to apply it to the "col1" column of a dataframe similar to: ``` col1 col2 0 w a 1 1 2 2 2 NaN ``` to get: ``` col1 col2 0 w a 1 A 2 2 B NaN ``` How can I best ...
There is a bit of ambiguity in your question. There are at least three two interpretations: 1. the keys in `di` refer to index values 2. the keys in `di` refer to `df['col1']` values 3. the keys in `di` refer to index locations (not the OP's question, but thrown in for fun.) Below is a solution for each case. --- *...
Remap values in pandas column with a dict
20,250,771
32
2013-11-27T18:56:58Z
20,250,996
41
2013-11-27T19:06:53Z
[ "python", "dictionary", "pandas", "remap" ]
I have a dictionary which looks like this: `di = {1: "A", 2: "B"}` I would like to apply it to the "col1" column of a dataframe similar to: ``` col1 col2 0 w a 1 1 2 2 2 NaN ``` to get: ``` col1 col2 0 w a 1 A 2 2 B NaN ``` How can I best ...
You can use `.replace`. For example: ``` >>> df = pd.DataFrame({'col2': {0: 'a', 1: 2, 2: np.nan}, 'col1': {0: 'w', 1: 1, 2: 2}}) >>> di = {1: "A", 2: "B"} >>> df col1 col2 0 w a 1 1 2 2 2 NaN >>> df.replace({"col1": di}) col1 col2 0 w a 1 A 2 2 B NaN ``` or directly on the `Series...
Python/SQL Alchemy Migrate - "ValueError: too many values to unpack" when migrating changes in db
20,250,901
4
2013-11-27T19:02:59Z
26,217,724
9
2014-10-06T13:49:22Z
[ "python", "sqlalchemy", "migration", "flask" ]
I have several models in SQLAlchemy written and I just started getting an exception when running my migrate scripts: ValueError: too many values to unpack Here are my models: ``` from app import db ROLE_USER = 0 ROLE_ADMIN = 1 class UserModel(db.Model): __tablename__ = 'user' id = db.Column(db.Integer, pri...
I came across the same problem with sqlalchemy + mysql. I had boolean fields in my model and they where created in mysql with smallint In migration script, it compares the model datatype with schema datatype (from mysql in my case). sqlalchemy translates the boolean datatype by default to tinyint and in mysql the schem...
Sphinx and relative imports in Python 3.*
20,251,007
7
2013-11-27T19:07:32Z
20,251,326
9
2013-11-27T19:25:05Z
[ "python", "python-3.x", "python-sphinx" ]
I have a directory with a python package as follows: ``` --docs/index.rst --docs/... --app/__init__.py --app/foo.py ``` and I'm using sphinx with autodocs for documenting the app (in python 3.3). Now, in the `conf.py` (inside `docs/`), I have ``` sys.path.insert(0, os.path.abspath('../app')) ``` I `cd` into `docs/...
Your `app` directory is a package. A package is a directory with `__init.py__` and other files inside it. If you put a package directory on your `sys.path`, all kinds of things go wrong. Let's take an example: ``` root/ app/ app/__init__.py app/spam.py app/eggs.py ``` --- If you have `r...
tkinter.TclError: image "pyimage3" doesn't exist
20,251,161
2
2013-11-27T19:16:44Z
20,259,317
10
2013-11-28T06:38:48Z
[ "python", "windows", "python-3.x", "tkinter" ]
I'm having trouble with a function that shows an image for two seconds on screen, and then is destroyed. When the program runs the functions initial call procedurely works fine, but if the function is then called via a button built in tkinter I get an error. ``` appcwd = os.getcwd() user32 = ctypes.windll.user32 scree...
I found the issue so figured I'd answer myself for anyone who has this issue in the future. When the wlcm\_scrn runs procedurely it is the only window that exists at that point in time, and so it can use tkinter.Tk(). The error arises because the button that calls the function is itself sitting in an active window tha...
Pycharm and unittest does not work
20,251,386
10
2013-11-27T19:28:22Z
27,848,632
18
2015-01-08T20:05:31Z
[ "python", "pycharm", "python-unittest" ]
I have a problem with PYCharm 3.0.1 I can't run basic unittests. Here is my code : ``` import unittest from MysqlServer import MysqlServer class MysqlServerTest(unittest.TestCase): def setUp(self): self.mysqlServer = MysqlServer("ip", "username", "password", "db", port) def test_canConnect(self)...
Although this wasn't the case with the original poster, I'd like to note that another thing that will cause this are test functions that don't begin with the word 'test.' ``` class TestSet(unittest.TestCase): def test_will_work(self): pass def will_not_work(self): pass ```
How to install django for python 3.3
20,251,562
11
2013-11-27T19:39:00Z
20,265,002
21
2013-11-28T11:29:39Z
[ "python", "django", "osx" ]
I had python 2.6.1 because it was old I decide to install python 3.3.2 but, when I type "python" in my mac it prints it is version 2.6.1 and when I type python3 it shows that this is 3.3.2. I installed django 1.6 but when I check, understand that it is installed for old version of python (python 2.6.1). I want to insta...
You could use `pip` to manage the package for you. If `pip` is not installed. use ``` sudo easy_install pip ``` to install it. Then ``` pip3 install django ``` would install `django` for your python3.
Python: Replace every 5th value of numpy array
20,251,684
2
2013-11-27T19:45:24Z
20,251,722
7
2013-11-27T19:47:36Z
[ "python", "numpy" ]
I've got a numpy array full of floats. How can I replace every 5th value with `np.inf*0` so that I get a `NaN` value at every 5th index? ``` my_array = np.array([5.0, 8.1, 3.2, 2.7, 8.4, 4.9 ...]) ``` to ``` my_array = np.array([5.0, 8.1, 3.2, 2.7, NaN, 4.9 ...]) ``` and so on.
How about using slicing and striding? `L[::5]` takes every 5th element from list `L`: ``` >>> my_array = np.arange(20.) >>> my_array[4::5] = np.nan >>> my_array array([ 0., 1., 2., 3., nan, 5., 6., 7., 8., nan, 10., 11., 12., 13., nan, 15., 16., 17., 18., nan]) ```
How to query an HDF store using Pandas/Python
20,255,485
4
2013-11-28T00:03:30Z
20,256,692
10
2013-11-28T02:31:16Z
[ "python", "pandas", "hdfs" ]
To manage the amount of RAM I consume in doing an analysis, I have a large dataset stored in hdf5 (.h5) and I need to query this dataset efficiently using Pandas. The data set contains user performance data for a suite of apps. I only want to pull a few fields out of the 40 possible, and then filter the resulting data...
You are pretty close. ``` In [1]: df = DataFrame({'A' : ['foo','foo','bar','bar','baz'], 'B' : [1,2,1,2,1], 'C' : np.random.randn(5) }) In [2]: df Out[2]: A B C 0 foo 1 -0.909708 1 foo 2 1.321838 2 bar 1 0.368994 3 bar 2 -0.058657 4 baz 1 -1....
Django: How to write query to sort using multiple columns, display via template
20,256,909
16
2013-11-28T02:56:54Z
20,257,014
10
2013-11-28T03:06:57Z
[ "python", "django", "postgresql", "sorting", "django-queryset" ]
I'm quite new to Django, and not too experienced with MVC, DB queries. I have a Customer table which includes customer\_name, city\_name, as well as a state\_name (pulled from a foreign key table). In the HTML, I'm trying to display the results in a list first sorted alphabetically by state\_name, then by city\_name, ...
You can specify the ordering inside the model, ``` class Customer(models.Model): customer_name = models.CharField(max_length=60) city_name = models.CharField(max_length=30) state = models.ForeignKey('State') def __unicode__(self): return self.customer_name class Meta: ordering...
Django: How to write query to sort using multiple columns, display via template
20,256,909
16
2013-11-28T02:56:54Z
20,257,999
26
2013-11-28T04:54:09Z
[ "python", "django", "postgresql", "sorting", "django-queryset" ]
I'm quite new to Django, and not too experienced with MVC, DB queries. I have a Customer table which includes customer\_name, city\_name, as well as a state\_name (pulled from a foreign key table). In the HTML, I'm trying to display the results in a list first sorted alphabetically by state\_name, then by city\_name, ...
There are several levels for display ordered models objects in template, each one overwrite the previous level: 1. **(MODEL LEVEL) Meta attribute `ordering`** as shows @Bithin in his answer (*more on [django docs](https://docs.djangoproject.com/en/dev/ref/models/options/#django.db.models.Options.ordering)*) 2. **(VIEW...
How to call self in a mock method of an object in Python?
20,257,252
8
2013-11-28T03:35:15Z
20,258,218
7
2013-11-28T05:14:26Z
[ "python", "mocking" ]
I try to test some codes which don't return anything but save the result to the DB. By mocking the save method, I wish to check whether things have been processed correctly: ``` def mock_save(self): assert(self.attr, 'dest_val') with mock.patch.object(Item, "save", create=True) as save: save.side_effect = mock...
You need `autospec=True` ``` def mock_save(self): assert self.attr == 'dest_val' with mock.patch.object(Item, "save", autospec=True) as save: save.side_effect = mock_save func_to_call() ```
Concise Ruby hash equivalent of Python dict.get()
20,258,632
4
2013-11-28T05:50:06Z
20,258,699
14
2013-11-28T05:54:31Z
[ "python", "ruby", "dictionary", "hash" ]
In know that I can manipulate a Ruby default `Hash` value like this: ``` h={a:1, b:2, c:3} h[:x] # => nil h.default = 5 h[:x] # => 5 h.default = 8 h[:y] # => 8 ``` but this gets quite tedious when doing it repeatedly for multiple values with different defaults. It also could get dangerous if the hash is passed to ot...
Yes, it is called [`fetch`](http://www.ruby-doc.org/core-2.0.0/Hash.html#method-i-fetch), and it can also take a block: ``` h.fetch(:x, 5) h.fetch(:x) {|missing_key| "Unfortunately #{missing_key} is not available"} ```