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
check if a directory is already created python
21,488,481
3
2014-01-31T19:32:37Z
21,488,556
7
2014-01-31T19:36:27Z
[ "python", "python-2.7" ]
A very basic question, I have a module that creates directories on the fly, however, sometimes I want to put more than one file in a dir. If this happens, python rises an exception and says that the dir is already created, how can I avoid this and check if the dir is already created or not? The save module looks somet...
You could go for a try except: ``` try: os.mkdir(path,0755) except OSError: pass ``` “Easier to ask forgiveness than permission !” Also this method is more safe that testing the directory before doing `mkdir`. Indeed, it is fairly possible that between the two os call implied by `ispath` and `mkdir` the ...
Is there a way to output multiple lists from a single list comprehension expression?
21,489,242
3
2014-01-31T20:16:05Z
21,489,290
8
2014-01-31T20:18:59Z
[ "python" ]
Something like ``` x, y = [expression for d in data] ``` Basically I'd like to obtain the equivalent of this: ``` x = [] y = [] for d in data: x.append(d[0]) y.append(d[1]) ``` where `data` is a nested list? And what if data is a list of dictionaries? ``` x = [] y = [] for d in data: x.append(d['key1'...
``` x, y = zip(*[d[:2] for d in data]) ``` I think is what you want ... that will give you a list of x's and a list of y's if each row in data only has d[0] and d[1] then you can just do ``` x1,x2,x3 = 1,2,3 y1,y2,y3 = 3,4,5 data = [(x1,y1),(x1,y2),(x3,y3)] x,y = zip(*data) ``` if you have a dict ``` from operator...
Installing PyQuery Via Pip
21,489,720
7
2014-01-31T20:44:35Z
23,840,547
13
2014-05-24T01:50:59Z
[ "python", "pip", "pyquery" ]
I'm attempting to install `PyQuery` via `pip` but I'm getting an error I do not understand. The command I used was: ``` sudo pip install pyquery ``` I get the output below: ``` Requirement already satisfied (use --upgrade to upgrade): pyquery in /usr/local/lib/python2.7/dist-packages Downloading/unpacking lxml>=2.1 ...
You have missing dependencies. Try running: `sudo apt-get install libxml2-dev libxslt1-dev python-dev`
Remove all quotes within values in Pandas
21,491,291
2
2014-01-31T22:30:38Z
21,491,485
7
2014-01-31T22:47:16Z
[ "python", "pandas", "dataframe" ]
I want to remove all double quotes within all columns and all values in a dataframe. So if I have a value such as ``` potatoes are "great" ``` I want to return ``` potatoes are great ``` DataFrame.replace() lets me do this if I know the entire value I'm changing, but is there a way to remove individual characters?
You can do this on each Series/column using [str.replace](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html): ``` In [11]: s = pd.Series(['potatoes are "great"', 'they are']) In [12]: s Out[12]: 0 potatoes are "great" 1 they are dtype: object In [13]: s.str.replac...
How to run Python script on terminal
21,492,214
31
2014-01-31T23:51:06Z
21,492,246
34
2014-01-31T23:53:31Z
[ "python", "osx", "terminal" ]
I want to run a Python script in terminal but I don't know how? I already have saved a file called gameover.py in /User/luca/Documents/python.
You need [*python*](http://www.python.org/) installed on your system. Then you can run this in the terminal in the correct directory: ``` python gameover.py ```
How to run Python script on terminal
21,492,214
31
2014-01-31T23:51:06Z
27,178,609
14
2014-11-27T21:02:31Z
[ "python", "osx", "terminal" ]
I want to run a Python script in terminal but I don't know how? I already have saved a file called gameover.py in /User/luca/Documents/python.
You can execute your file by using this: ``` python /Users/luca/Documents/python/gameover.py ``` You can also run the file by moving to the path of the file you want to run and typing: ``` python gameover.py ```
Create a Pandas DataFrame from deeply nested JSON
21,494,030
11
2014-02-01T04:21:07Z
21,500,413
11
2014-02-01T16:16:15Z
[ "python", "json", "pandas" ]
I'm trying to create a single Pandas DataFrame object from a deeply nested JSON string. The JSON schema is: ``` {"intervals": [ { pivots: "Jane Smith", "series": [ { "interval_id": 0, "p_value": 1 }, { "interval_id": 1, "p_value": 1.1162791357932633e-8 }, { ...
I think organizing your data in way that yields repeating column names is only going to create headaches for you later on down the road. A better approach IMHO is to create a column for each of `pivots`, `interval_id`, and `p_value`. This will make extremely easy to query your data after loading it into pandas. Also, ...
How do I do a F-test in python
21,494,141
12
2014-02-01T04:39:51Z
21,503,346
17
2014-02-01T20:38:17Z
[ "python", "statistics" ]
How do I do an F-test to check if the variance is equivalent in two vectors in Python? For example if I have ``` a = [1,2,1,2,1,2,1,2,1,2] b = [1,3,-1,2,1,5,-1,6,-1,2] ``` is there something similar to ``` scipy.stats.ttest_ind(a, b) ``` I found ``` sp.stats.f(a, b) ``` But it appears to be something different t...
The test statistic F test for equal variances is simply: ``` F = Var(X) / Var(Y) ``` Where `F` is distributed as `df1 = len(X) - 1, df2 = len(Y) - 1` [`scipy.stats.f`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.f.html) which you mentioned in your question has a CDF method. This means you can gen...
Django self.cleaned_data Keyerror
21,497,497
3
2014-02-01T11:32:24Z
21,497,552
7
2014-02-01T11:40:08Z
[ "python", "django", "django-forms" ]
I'm writing a Django website and i'm writing my own validation for a form : ``` class CreateJobOpportunityForm(forms.Form): subject = forms.CharField(max_length=30) start_date = forms.DateField(widget=SelectDateWidget) end_date = forms.DateField(widget=SelectDateWidget) def clean_start_date(self): ...
Since one field depends on another field, it's best if you did your cleaning in the `clean` method for the form, instead of the individual `clean_field` method. ``` def clean(self): cleaned_data = super(CreateJobOpportunityForm, self).clean() end_date = cleaned_data['end_date'] start_date = cleaned_data['s...
Flask: get current route
21,498,694
12
2014-02-01T13:35:21Z
21,498,733
9
2014-02-01T13:39:13Z
[ "python", "url", "flask" ]
In Flask, when I have several routes for the same function, how can I know which route is used at the moment? For example: ``` @app.route("/antitop/") @app.route("/top/") @requires_auth def show_top(): .... ``` How can I know, that now I was called using `/top/` or `/antitop/`? **UPDATE** I know about `request...
Simply use [`request.path`](http://flask.pocoo.org/docs/api/#flask.Request.path). ``` from flask import request ... @app.route("/antitop/") @app.route("/top/") @requires_auth def show_top(): ... request.path ... ```
Flask: get current route
21,498,694
12
2014-02-01T13:35:21Z
21,498,747
16
2014-02-01T13:40:07Z
[ "python", "url", "flask" ]
In Flask, when I have several routes for the same function, how can I know which route is used at the moment? For example: ``` @app.route("/antitop/") @app.route("/top/") @requires_auth def show_top(): .... ``` How can I know, that now I was called using `/top/` or `/antitop/`? **UPDATE** I know about `request...
the most 'flasky' way to check which route triggered your view is, by [`request.url_rule`](http://flask.pocoo.org/docs/api/#flask.Request.url_rule). ``` rule = request.url_rule if 'antitop' in rule.rule: # request by '/antitop' elif 'top' in rule.rule: # request by '/top' ```
How to circumvent the fallacy of Python's os.path.commonprefix?
21,498,939
11
2014-02-01T14:00:24Z
21,499,676
7
2014-02-01T15:05:13Z
[ "python", "path", "prefix" ]
My problem is to find the common *path* prefix of a given set of files. Literally I was expecting that "os.path.commonprefix" would do just that. Unfortunately, the fact that `commonprefix` is located in `path` is rather misleading, since it actually will search for string prefixes. The question to me is, how can thi...
Awhile ago I ran into this where `os.path.commonprefix` is a string prefix and not a path prefix as would be expected. So I wrote the following: ``` def commonprefix(l): # this unlike the os.path.commonprefix version # always returns path prefixes as it compares # path component wise cp = [] ls = [...
How to see which tests were run during Django's manage.py test command
21,500,354
27
2014-02-01T16:09:29Z
21,500,417
41
2014-02-01T16:16:30Z
[ "python", "django", "unit-testing", "django-unittest" ]
After tests execution is finished using Django's `manage.py test` command only number of passed tests is printed to the console. ``` (virtualenv) G:\Project\>python manage.py test Creating test database for alias 'default'... True .. ---------------------------------------------------------------------- Ran 2 tests in...
You can pass `-v 2` to the `test` command: ``` python manage.py test -v 2 ``` After running this command you'll get something like this (I'm using django 1.9, feel free to ignore migrations/database stuff): ``` Creating test database for alias 'default' (':memory:')... Operations to perform: Synchronize unmigrated...
Form validation fails due missing CSRF
21,501,058
8
2014-02-01T17:17:00Z
21,501,593
7
2014-02-01T18:04:29Z
[ "python", "forms", "flask", "flask-wtforms" ]
A few days ago I have reset my local flask environment without having captured the dependencies via a `pip freeze` before I deleted it. Hence I had to re-install the latest version of the entire stack. Now out of the blue I am no longer able to validate with forms. Flask claims CSRF would be missing. ``` def register...
The Flask-WTF CSRF infrastructure rejects a token if: * the token is missing. Not the case here, you can see the token in the form. * it is too old (default expiration is set to 3600 seconds, or an hour). Set the `TIME_LIMIT` attribute on forms to override this. Probably not the case here. * if no `'csrf_token'` key i...
Form validation fails due missing CSRF
21,501,058
8
2014-02-01T17:17:00Z
21,504,769
7
2014-02-01T22:58:34Z
[ "python", "forms", "flask", "flask-wtforms" ]
A few days ago I have reset my local flask environment without having captured the dependencies via a `pip freeze` before I deleted it. Hence I had to re-install the latest version of the entire stack. Now out of the blue I am no longer able to validate with forms. Flask claims CSRF would be missing. ``` def register...
I finally found the problem after nearly a day working on it. :( Big thanks to Martijn though for his help. The actual problem lies in the way the latest `flask_wtf.csrf` is working. The makers have overhauled it completely. You have to replace all `{{form.hidden_tag()}}` in your templates with `<input type="hidden" ...
Python 3 CSV file giving UnicodeDecodeError: 'utf-8' codec can't decode byte error when I print
21,504,319
2
2014-02-01T22:11:23Z
21,504,899
8
2014-02-01T23:12:41Z
[ "python", "csv", "python-3.x", "encoding", "utf-8" ]
I have the following code in Python 3, which is meant to print out each line in a csv file. ``` import csv with open('my_file.csv', 'r', newline='') as csvfile: lines = csv.reader(csvfile, delimiter = ',', quotechar = '|') for line in lines: print(' '.join(line)) ``` But when I run it, it gives me thi...
We know the file contains the byte `b'\x96'` since it is mentioned in the error message: ``` UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 7386: invalid start byte ``` Now we can write a little script to find out if there are any encodings where `b'\x96'` decodes to `ñ`: ``` import pkgutil im...
Why aren't my dictionary values being stored as integers?
21,504,408
2
2014-02-01T22:20:51Z
21,504,436
8
2014-02-01T22:23:41Z
[ "python", "python-3.x" ]
I'm writing a function that returns the number of occurrences of each letter in a string: ``` def count_all(text): text = text.lower() counts = {} for char in text: if char not in counts: counts.setdefault(char,[1]) else: counts[char] = counts[char] + 1 print(cou...
> I suspect it's reading the value of key char as a list with a single item rather than an integer Exactly, because you set it to a list: `counts.setdefault(char,[1])`. Just don't do that and it'll work: `counts.setdefault(char,1)`. `setdefault` is in fact unnecessary, since you already checked that `char not in count...
Best way to combine probabilistic classifiers in scikit-learn
21,506,128
15
2014-02-02T01:54:06Z
21,544,196
21
2014-02-04T04:53:12Z
[ "python", "machine-learning", "classification", "scikit-learn" ]
I have a logistic regression and a random forest and I'd like to combine them (ensemble) for the final classification probability calculation by taking an average. Is there a built-in way to do this in sci-kit learn? Some way where I can use the ensemble of the two as a classifier itself? Or would I need to roll my ow...
For what it's worth I ended up doing this as follows: ``` class EnsembleClassifier(BaseEstimator, ClassifierMixin): def __init__(self, classifiers=None): self.classifiers = classifiers def fit(self, X, y): for classifier in self.classifiers: classifier.fit(X, y) def predict_pr...
Python: List comprehension list of lists
21,507,319
3
2014-02-02T05:13:04Z
21,507,349
14
2014-02-02T05:17:37Z
[ "python", "list", "python-2.7" ]
I have a list of lists, and would like to use list comprehension to apply a function to each element in the list of lists, but when I do this, I end up with one long list rather than my list of lists. So, I have ``` x = [[1,2,3],[4,5,6],[7,8,9]] [number+1 for group in x for number in group] [2, 3, 4, 5, 6, 7, 8, 9, 1...
Use this: ``` [[number+1 for number in group] for group in x] ``` Or use this if you know map: ``` [map(lambda x:x+1 ,group) for group in x] ```
Flask-Restful POST fails due CSRF protection of Flask-WTF
21,509,728
4
2014-02-02T10:57:26Z
21,509,994
8
2014-02-02T11:25:32Z
[ "python", "rest", "flask", "flask-wtforms", "flask-restful" ]
I am using normal flask web + flask-restful. So I need CSRF protection for web but not for REST. The moment I enable `CsrfProtect(app)` of `flask-wtf`, all my post unit tests for `flask-restful` return a 400. Is there a way to disable CSRF protection for REST services since they are coming from mobile handsets withou...
You can use the [`@csrf.exempt` decorator](https://flask-wtf.readthedocs.org/en/latest/api.html#flask_wtf.csrf.CsrfProtect.exempt), which you need to add directly on the API object, with the [`decorators` argument](http://flask-restful.readthedocs.org/en/latest/api.html#id1); this would apply the decorator to *all* API...
Retrieve all items from DynamoDB using query?
21,515,765
5
2014-02-02T20:27:30Z
21,516,625
9
2014-02-02T21:43:25Z
[ "python", "boto", "amazon-dynamodb" ]
I am trying to retrieve all items in a dynamodb table using a query. Below is my code: ``` import boto.dynamodb2 from boto.dynamodb2.table import Table from time import sleep c = boto.dynamodb2.connect_to_region(aws_access_key_id="XXX",aws_secret_access_key="XXX",region_name="us-west-2") tab = Table("rip.irc",co...
Ahh ok, figured it out. If anyone needs: You can't use the query method on a table without specifying a specific hash key. The method to use instead is scan. So if I replace: ``` x = tab.query() ``` with ``` x = tab.scan() ``` I get all the items in my table.
Running code in PyCharm's console
21,516,027
10
2014-02-02T20:48:16Z
22,387,377
18
2014-03-13T18:13:14Z
[ "python", "pycharm", "pyscripter" ]
Are there any smooth way to run Python scripts in the PyChram's console? My previous IDE - PyScripter - provides me with that nice little feature. As far as I know PyCharm has 2 ways of running script in console: 1) Select a bunch of code and press `Ctrl`+`Alt`+`E`. 2) Save the code in a file and import it from the Co...
In the Run/Debug Configuration, add -i to the interpreter options. This will stop it from closing a python session even after a successful run. I.e. you will be able to see all the variable contents
Difference between two numpy arrays in python
21,516,089
13
2014-02-02T20:52:55Z
21,516,130
16
2014-02-02T20:55:43Z
[ "python", "arrays", "numpy", "array-difference" ]
I have two arrays, for example: ``` array1=numpy.array([1.1, 2.2, 3.3]) array2=numpy.array([1, 2, 3]) ``` How can I find the difference between these two arrays in Python, to give: ``` [0.1, 0.2, 0.3] ``` As an array as well? Sorry if this is an amateur question - but any help would be greatly appreciated!
This is pretty simple with `numpy`, just subtract the arrays: ``` diffs = array1 - array2 ``` I get: ``` diffs == array([ 0.1, 0.2, 0.3]) ```
Command python setup.py egg_info failed with error code 1
21,517,051
12
2014-02-02T22:23:51Z
21,536,934
17
2014-02-03T20:21:27Z
[ "python", "pip" ]
I am trying to do `make install`, but I keep getting an error. I already tried following this answer: [Can't install via pip because of egg\_info error](http://stackoverflow.com/questions/17886647/cant-install-via-pip-because-of-egg-info-error) ``` Command python setup.py egg_info failed with error code 1 in /abc/abc_...
There were several problems with the original code. First, `MySQL-python` version `1.2.4` for some reason fails to install. Changing this to `1.2.5` fixes that error. Second, `argparse` cannot be installed as is. It needs `--allow-all-external`. The new Makefile is below: ``` virtualenv-2.7 my_env && \ source my_env...
Python Class Fields
21,517,740
8
2014-02-02T23:34:54Z
21,519,815
13
2014-02-03T04:42:23Z
[ "python" ]
I am new to Python having come from mainly Java programming. I am currently pondering over how classes in Python are instantiated. I understand that `__init__()`: is like the constructor in Java. However, sometimes python classes do not have an `__init__()` method which in this case I assume there is a default constr...
> I understand that `__init__()`: is like the constructor in Java. To be more precise, in Python `__new__` is the constructor method, `__init__` is the initializer. When you do `SomeClass('foo', bar='baz')`, the `type.__call__` method basically does: ``` def __call__(cls, *args, **kwargs): instance = cls.__new__(...
why does this work in c but not in python: (a = 5) == 5
21,518,819
2
2014-02-03T02:22:26Z
21,518,829
7
2014-02-03T02:23:48Z
[ "python", "c" ]
New to both python, and fairly beginner in C. Why will the subject code return an error in python? Does the assignment not have a return value?
This is simply not valid in Python. You can't use an assignment as an expression.
Plotting a list of (x, y) coordinates in python matplotlib
21,519,203
15
2014-02-03T03:21:52Z
21,519,229
32
2014-02-03T03:26:06Z
[ "python", "matplotlib", "plot", "coordinates" ]
I have a list of pairs `(a, b)` that I would like to plot with `matplotlib` in python as actual x-y coordinates. Currently, it is making two plots, where the index of the list gives the x-coordinate, and the first plot's y values are the `a`s in the pairs and the second plot's y values are the `b`s in the pairs. To cl...
As per [this example](http://matplotlib.org/examples/shapes_and_collections/scatter_demo.html): ``` import numpy as np import matplotlib.pyplot as plt N = 50 x = np.random.rand(N) y = np.random.rand(N) plt.scatter(x, y) plt.show() ``` will produce: ![enter image description here](http://i.stack.imgur.com/9Zd2j.png...
Efficient way of counting number of elements smaller (larger) than cutoff in a sorted list
21,520,003
2
2014-02-03T05:00:44Z
21,520,034
9
2014-02-03T05:04:12Z
[ "python" ]
Let's assume we have a sorted list: ``` lst = [1,3,4,89,456,543] # a long one ``` and what we'd like to do is to find the number of elements in a list which are smaller than, `mx`. Easy: ``` n = len([x for x in lst if x < mx]) ``` or with generator: ``` n = sum(1 for x in lst if x < mx) ``` I assume the second a...
We can do even better with a binary search, which is handily implemented for us in the [`bisect`](http://docs.python.org/2/library/bisect.html) module: ``` import bisect n = bisect.bisect_left(lst, mx) ``` This takes time logarithmic in the length of `lst`, whereas a linear search with early termination is linear in ...
How to read in only every second line of file?
21,523,528
2
2014-02-03T09:22:17Z
21,523,629
7
2014-02-03T09:27:09Z
[ "python", "file", "iterator" ]
I need to read in only every second line of a file (which is very big) so I don't want to use `readlines()`. I'm unsure how to implement the iterator so any suggestions are welcome. One possibility is to call next() twice. Not very appealing. ``` with open(pth_file, 'rw') as pth: pth.next() for i,r...
Using [`itertools.islice`](http://docs.python.org/2/library/itertools.html#itertools.islice): ``` import itertools with open(pth_file) as f: for line in itertools.islice(f, 1, None, 2): # 1: from the second line ([1]) # None: to the end # 2: step # Do something with the line ```
Python: converting a list of dictionaries to json
21,525,328
13
2014-02-03T10:50:18Z
21,525,380
31
2014-02-03T10:52:37Z
[ "python", "json", "list", "dictionary" ]
I have a list of dictionaries, looking some thing like this: ``` list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}] ``` and so on. There may be more documents in the list. I need to convert these to one JSON document, that can be returned via bottle, and I canno...
use json library ``` import json json.dumps(list) ``` by the way, you might consider changing variable list to another name, `list` is the builtin function for a list creation, you may get some unexpected behaviours or some buggy code if you don't change the variable name.
How to endif in Flask Jinja2 templating engine. Getting TemplateSyntaxError: expected token 'end of statement block', got 'session'
21,525,660
3
2014-02-03T11:05:03Z
21,525,726
8
2014-02-03T11:07:42Z
[ "python", "flask", "jinja2", "templating-engine" ]
I'm building a website using [the Flask Framework](http://flask.pocoo.org/) and I now run into an error which I don't understand. For the simple base.html file I pasted below I'm gettig a `TemplateSyntaxError: expected token 'end of statement block', got 'session'`, even though I clearly end the if with the `{% endif %...
In the following line, the code is missing an operand for `not in` operator. ``` {% if ?? not in session.logged_in %} ^^ ``` Or, you maybe mean `not` operator: ``` {% if not session.logged_in %} ```
Reversing a linked list in python
21,529,359
2
2014-02-03T14:02:25Z
22,049,871
12
2014-02-26T18:19:34Z
[ "python", "linked-list" ]
I am asked to reverse a which takes head as parameter where as head is a linked list e.g.: 1 -> 2 -> 3 which was returned from a function already defined I tried to implement the function reverse\_linked\_list in this way: ``` def reverse_linked_list(head): temp = head head = None temp1 = temp.next temp2 = temp1.next ...
The accepted answer doesn't make any sense to me, since it refers to a bunch of stuff that doesn't seem to exist (`number`, `node`, `len` as a number rather than a function). Since the homework assignment this was for is probably long past, I'll post what I think is the most effective code. This is for doing a destruc...
Reversing a linked list in python
21,529,359
2
2014-02-03T14:02:25Z
35,390,099
8
2016-02-14T09:09:49Z
[ "python", "linked-list" ]
I am asked to reverse a which takes head as parameter where as head is a linked list e.g.: 1 -> 2 -> 3 which was returned from a function already defined I tried to implement the function reverse\_linked\_list in this way: ``` def reverse_linked_list(head): temp = head head = None temp1 = temp.next temp2 = temp1.next ...
I found Blckknght's answer useful and it's certainly correct, but I struggled to understand what was actually happening, due mainly to Python's syntax allowing two variables to be swapped on one line. I also found the variable names a little confusing. In this example I use `previous, current, next`. ``` def re...
Is there an easy way to unpack a tuple while using enumerate in loop?
21,529,607
5
2014-02-03T14:14:26Z
21,529,652
10
2014-02-03T14:16:19Z
[ "python" ]
Consider this: ``` the_data = ['a','b','c'] ``` With enumerate this loop can be written as: ``` for index,item in enumerate(the_data): # index = 1 , item = 'a' ``` If `the_data = { 'john':'football','mary':'snooker','dhruv':'hockey'}` Loop with key value pair assigned in loop: ``` for name,sport in the_dat...
Use this: ``` for index, (name, sport) in enumerate(the_data.iteritems()): pass ``` This is equivalent to: ``` >>> a, (b, c) = [1, (2, 3)] >>> a, b, c (1, 2, 3) ``` This is commonly used with `zip` and `enumerate` combo as well: ``` for i, (a, b) in enumerate(zip(seq1, seq2)): pass ```
fatal error: Python.h: No such file or directory
21,530,577
330
2014-02-03T15:00:16Z
21,530,768
616
2014-02-03T15:10:01Z
[ "python", "gcc", "python-c-api", "python-c-extension" ]
I am trying to build a shared library using a C extension file but first I have to generate the output file using the command below: ``` gcc -Wall utilsmodule.c -o Utilc ``` After executing the command, I get this error message: > utilsmodule.c:1:20: fatal error: Python.h: No such file or directory > compilation ter...
Looks like you haven't properly installed the header files and static libraries for python dev. Use your package manager to install them system-wide. For apt (**ubuntu, debian...**): ``` sudo apt-get install python-dev # for python2.x installs sudo apt-get install python3-dev # for python3.x installs ``` For yum (...
fatal error: Python.h: No such file or directory
21,530,577
330
2014-02-03T15:00:16Z
21,530,866
32
2014-02-03T15:13:31Z
[ "python", "gcc", "python-c-api", "python-c-extension" ]
I am trying to build a shared library using a C extension file but first I have to generate the output file using the command below: ``` gcc -Wall utilsmodule.c -o Utilc ``` After executing the command, I get this error message: > utilsmodule.c:1:20: fatal error: Python.h: No such file or directory > compilation ter...
Two things you have to do. Install development package for Python, in case of Debian/Ubuntu/Mint it's done with command: ``` sudo apt-get install python-dev ``` Second thing is that include files are not by default in the include path, nor is Python library linked with executable by default. You need to add these fl...
fatal error: Python.h: No such file or directory
21,530,577
330
2014-02-03T15:00:16Z
21,531,170
9
2014-02-03T15:26:32Z
[ "python", "gcc", "python-c-api", "python-c-extension" ]
I am trying to build a shared library using a C extension file but first I have to generate the output file using the command below: ``` gcc -Wall utilsmodule.c -o Utilc ``` After executing the command, I get this error message: > utilsmodule.c:1:20: fatal error: Python.h: No such file or directory > compilation ter...
Make sure that the Python dev files come with your OS. You should not hard code the library and include paths. Instead, use pkg-config, which will output the correct options for your specific system: ``` $ pkg-config --cflags --libs python2 -I/usr/include/python2.7 -lpython2.7 ``` You may add it to your *gcc* line: ...
fatal error: Python.h: No such file or directory
21,530,577
330
2014-02-03T15:00:16Z
21,548,557
7
2014-02-04T09:32:02Z
[ "python", "gcc", "python-c-api", "python-c-extension" ]
I am trying to build a shared library using a C extension file but first I have to generate the output file using the command below: ``` gcc -Wall utilsmodule.c -o Utilc ``` After executing the command, I get this error message: > utilsmodule.c:1:20: fatal error: Python.h: No such file or directory > compilation ter...
I managed to solve this issue and generate the .so file in one command ``` gcc -shared -o UtilcS.so -fPIC -I/usr/include/python2.7 -lpython2.7 utilsmodule.c ```
fatal error: Python.h: No such file or directory
21,530,577
330
2014-02-03T15:00:16Z
22,077,790
171
2014-02-27T18:54:45Z
[ "python", "gcc", "python-c-api", "python-c-extension" ]
I am trying to build a shared library using a C extension file but first I have to generate the output file using the command below: ``` gcc -Wall utilsmodule.c -o Utilc ``` After executing the command, I get this error message: > utilsmodule.c:1:20: fatal error: Python.h: No such file or directory > compilation ter...
On Ubuntu, I was running Python 3 and I had to install ``` sudo apt-get install python3-dev ```
fatal error: Python.h: No such file or directory
21,530,577
330
2014-02-03T15:00:16Z
29,830,656
16
2015-04-23T17:38:45Z
[ "python", "gcc", "python-c-api", "python-c-extension" ]
I am trying to build a shared library using a C extension file but first I have to generate the output file using the command below: ``` gcc -Wall utilsmodule.c -o Utilc ``` After executing the command, I get this error message: > utilsmodule.c:1:20: fatal error: Python.h: No such file or directory > compilation ter...
If you are using [tox](https://tox.readthedocs.org/en/latest/) to run tests on multiple versions of Python, you may need to install the Python dev libraries for each version of Python you are testing on. ``` sudo apt-get install python2.6-dev sudo apt-get install python2.7-dev etc. ```
fatal error: Python.h: No such file or directory
21,530,577
330
2014-02-03T15:00:16Z
30,676,339
26
2015-06-05T21:48:06Z
[ "python", "gcc", "python-c-api", "python-c-extension" ]
I am trying to build a shared library using a C extension file but first I have to generate the output file using the command below: ``` gcc -Wall utilsmodule.c -o Utilc ``` After executing the command, I get this error message: > utilsmodule.c:1:20: fatal error: Python.h: No such file or directory > compilation ter...
on Fedora try this.. > sudo yum install python-devel
fatal error: Python.h: No such file or directory
21,530,577
330
2014-02-03T15:00:16Z
31,309,573
7
2015-07-09T06:20:04Z
[ "python", "gcc", "python-c-api", "python-c-extension" ]
I am trying to build a shared library using a C extension file but first I have to generate the output file using the command below: ``` gcc -Wall utilsmodule.c -o Utilc ``` After executing the command, I get this error message: > utilsmodule.c:1:20: fatal error: Python.h: No such file or directory > compilation ter...
In AWS API (centOS) its ``` yum install python27-devel ```
fatal error: Python.h: No such file or directory
21,530,577
330
2014-02-03T15:00:16Z
32,030,746
32
2015-08-16T00:36:05Z
[ "python", "gcc", "python-c-api", "python-c-extension" ]
I am trying to build a shared library using a C extension file but first I have to generate the output file using the command below: ``` gcc -Wall utilsmodule.c -o Utilc ``` After executing the command, I get this error message: > utilsmodule.c:1:20: fatal error: Python.h: No such file or directory > compilation ter...
If you are using a Raspberry Pi: ``` sudo apt-get install python-dev ```
fatal error: Python.h: No such file or directory
21,530,577
330
2014-02-03T15:00:16Z
35,121,730
10
2016-02-01T01:27:33Z
[ "python", "gcc", "python-c-api", "python-c-extension" ]
I am trying to build a shared library using a C extension file but first I have to generate the output file using the command below: ``` gcc -Wall utilsmodule.c -o Utilc ``` After executing the command, I get this error message: > utilsmodule.c:1:20: fatal error: Python.h: No such file or directory > compilation ter...
In my case, what fixed it in Ubuntu was to install the packages `libpython-all-dev` (or `libpython3-all-dev` if you use Python 3).
numpy histogram cumulative density does not sum to 1
21,532,667
4
2014-02-03T16:36:39Z
21,533,247
7
2014-02-03T17:06:23Z
[ "python", "numpy" ]
Taking a tip from another thread ([@EnricoGiampieri's answer](http://stackoverflow.com/questions/15408371/cumulative-distribution-plots-python/15419072#15419072) to [cumulative distribution plots python](http://stackoverflow.com/questions/15408371/cumulative-distribution-plots-python)), I wrote: ``` # plot cumulative ...
You can simply normalize your `values` variable yourself like so: `unity_values = values / values.sum()` A full example would look something like this: ``` import numpy as np import matplotlib.pyplot as plt x = np.random.normal(size=37) density, bins = np.histogram(x, normed=True, density=True) unity_density = dens...
Seeking from end of file throwing unsupported exception
21,533,391
5
2014-02-03T17:14:24Z
21,533,561
10
2014-02-03T17:21:47Z
[ "python", "file", "python-3.3" ]
I have this code snippet and I'm trying to seek backwards from the end of file using python: ``` f=open('D:\SGStat.txt','a'); f.seek(0,2) f.seek(-3,2) ``` This throws the following exception while running: ``` f.seek(-3,2) io.UnsupportedOperation: can't do nonzero end-relative seeks ``` Am i missing somethi...
From the [documentation](http://docs.python.org/3.2/tutorial/inputoutput.html#methods-of-file-objects) for Python 3.2 and up: > In text files (those opened without a `b` in the mode string), only seeks relative to the beginning of the file are allowed (the exception being seeking to the very file end with `seek(0, 2)`...
Python's syntactical sugar gone wrong
21,533,525
2
2014-02-03T17:19:57Z
21,533,579
8
2014-02-03T17:22:53Z
[ "python" ]
I am looking at the code listed [here](http://pastebin.com/aUZ1Ue6E) and they provide a very interesting structure to writing a "clock" in Python on line. I have never seen this quirky syntax before and quite honestly do not know how it works. This is utter black magic in Python. But even though it is not the most Pyth...
This is an archaic way of writing a ternary conditional. It should be: ``` qClock = time.clock if qDuration > 0 else lambda: 0 qDuration = (qClock() + qDuration) if qDuration > 0 else 1 ``` Before Python 2.5, which introduced the ternary conditional ([link](http://docs.python.org/3/faq/programming.html#is-there-an-eq...
How to compute an expensive high precision sum in python?
21,535,277
8
2014-02-03T18:50:02Z
21,536,184
15
2014-02-03T19:39:03Z
[ "python", "performance", "math", "numpy" ]
My problem is very simple. I would like to compute the following sum. ``` from __future__ import division from scipy.misc import comb import math for n in xrange(2,1000,10): m = 2.2*n/math.log(n) print sum(sum(comb(n,a) * comb(n-a,b) * (comb(a+b,a)*2**(-a-b))**m for b in xrange(n+1)) ...
The reason why you get NaNs is you end up evaluating numbers like ``` comb(600 + 600, 600) == 3.96509646226102e+359 ``` This is too large to fit into a floating point number: ``` >>> numpy.finfo(float).max 1.7976931348623157e+308 ``` Take logarithms to avoid it: ``` from __future__ import division, absolute_import...
Python and very small decimals
21,535,604
4
2014-02-03T19:07:02Z
21,535,652
7
2014-02-03T19:09:20Z
[ "python", "floating-point" ]
Interesting fact on Python 2.7.6 running on macosx: You have a very small number like: ``` 0.000000000000000000001 ``` You can represent it as: ``` >>> 0.1 / (10 ** 20) 1.0000000000000001e-21 ``` But you can see the floating pointing error at the end. What we *really* have is something like this: ``` 0.0000000000...
Floating point numbers work like scientific notation. `1.0000000000000001e-21` fits within the **53 bits of significand/mantissa** a 64-bit float allows. Adding `1` to that, many orders of magnitude larger than the tiny fraction, causes the minor detail to be discarded, and storing exactly `1` instead
Python and very small decimals
21,535,604
4
2014-02-03T19:07:02Z
21,537,005
7
2014-02-03T20:25:23Z
[ "python", "floating-point" ]
Interesting fact on Python 2.7.6 running on macosx: You have a very small number like: ``` 0.000000000000000000001 ``` You can represent it as: ``` >>> 0.1 / (10 ** 20) 1.0000000000000001e-21 ``` But you can see the floating pointing error at the end. What we *really* have is something like this: ``` 0.0000000000...
Consider what happens when you attempt to add 7.00 and .001 and are only permitted to use three digits for the answer. 7.001 is not allowed. What do you do? Of the values you can return, such as 6.99, 7.00, and 7.01, the closest to the correct answer is 7.00. So, when asked to add 7.00 and .001, you return 7.00. The ...
What's the difference between scipy.special.binom and scipy.misc.comb?
21,535,852
6
2014-02-03T19:21:11Z
21,538,085
10
2014-02-03T21:24:42Z
[ "python", "scipy" ]
What is the difference between scipy.special.binom and scipy.misc.comb? In ipython I can see they return different types and also have different accuracy. ``` scipy.special.binom(4,3) 4.0 scipy.misc.comb(4,3) array(4.000000000000001) ``` However what exactly are they doing differently? --- Looking at <https://git...
Whenever you come across a situation where you do not know what some code is doing and it is not straightforwardly easy to simply import the parent module in some interpreter and inspect the execution of the code, the docstrings, etc., then you have a few options. Let me describe two options that did not turn out to b...
Python pyodbc connections to IBM Netezza Erroring
21,536,059
7
2014-02-03T19:32:13Z
21,639,270
9
2014-02-07T22:55:05Z
[ "python", "odbc", "pyodbc", "netezza" ]
So. This issue is almost exactly the same as the one discussed [here](http://stackoverflow.com/questions/14270745/issue-with-querying-teradata-in-python-pyodbc) -- but the fix (such as it is) discussed in that post doesn't fix things for me. I'm trying to use Python 2.7.5 and pyodbc 3.0.7 to connect from an Ubuntu 12....
Turns out `pyodbc` can't gracefully convert all of Netezza's types. The table I was working with had two that are problematic: * A column of type `NUMERIC(7,2)` * A column of type `NVARCHAR(255)` The `NUMERIC` column causes a decimal conversion error on NULL. The `NVARCHAR` column returns a utf-16-le encoded string, ...
Python - are there other ways to apply a function and filter in a list comprehension?
21,538,689
5
2014-02-03T21:57:05Z
21,538,709
11
2014-02-03T21:58:02Z
[ "python", "list-comprehension" ]
this has been irking me for years. given I have a list of words : ``` words = [ 'one', 'two', 'three', '', ' four', 'five ', 'six', \ 'seven', 'eight ', ' nine', 'ten', ''] ``` even though it's super lightweight, I still feel weird writing this list comprehension: ``` cleaned = [ i.strip() for i in words i...
A generator expression: ``` cleaned = [i for i in (word.strip() for word in words) if i] ``` Using `filter()` and `map()`: ``` cleaned = filter(None, map(str.strip, words)) ``` The latter produces a generator in Python 3; apply `list()` to it or combine `map()` with a list comprehension: ``` cleaned = [i for i in ...
Pycharm: set environment variable for run manage.py Task
21,538,859
15
2014-02-03T22:07:26Z
21,619,127
25
2014-02-07T04:05:05Z
[ "python", "django", "pycharm" ]
I have moved my `SECRET_KEY` value out of my settings file, and it gets set when I load my virtualenv. I can confirm the value is present from `python manage.py shell`. When I run the Django Console, `SECRET_KEY` is missing, as it should. So in preferences, I go to Console>Django Console and load `SECRET_KEY` and the ...
Because Pycharm is not launching from a terminal your environment will not loaded. In short any GUI program will not inherit the SHELL variables. See [this](http://stackoverflow.com/questions/135688/setting-environment-variables-in-os-x) for reasons (assuming a Mac). However there are several basic solutions to this p...
Pycharm: set environment variable for run manage.py Task
21,538,859
15
2014-02-03T22:07:26Z
22,899,916
10
2014-04-06T20:56:10Z
[ "python", "django", "pycharm" ]
I have moved my `SECRET_KEY` value out of my settings file, and it gets set when I load my virtualenv. I can confirm the value is present from `python manage.py shell`. When I run the Django Console, `SECRET_KEY` is missing, as it should. So in preferences, I go to Console>Django Console and load `SECRET_KEY` and the ...
To set your environment variables in PyCharm do the following: * Open the 'File' menu * Click 'Settings' * Click the '+' sign next to 'Console' * Click Python Console * Click the '...' button next to environment variables * Click the '+' to add environment variables
Pycharm: set environment variable for run manage.py Task
21,538,859
15
2014-02-03T22:07:26Z
28,723,630
8
2015-02-25T15:58:44Z
[ "python", "django", "pycharm" ]
I have moved my `SECRET_KEY` value out of my settings file, and it gets set when I load my virtualenv. I can confirm the value is present from `python manage.py shell`. When I run the Django Console, `SECRET_KEY` is missing, as it should. So in preferences, I go to Console>Django Console and load `SECRET_KEY` and the ...
You can set the manage.py task environment variables via: Preferences| Languages&Frameworks| Django| Manage.py tasks Setting the env vars via the run/debug/console configuration won't affect the built in pycharm's manage.py task.
Get the constraint name out of an IntegrityError in SQLAlchemy+Postgres
21,540,702
4
2014-02-04T00:27:36Z
21,540,764
7
2014-02-04T00:33:53Z
[ "python", "postgresql", "error-handling", "unique-constraint" ]
Some types of constraints are best checked by the database, as attempting to check them manually could lead to race conditions. You'd think, then, that database drivers would make this easy, right? The database driver pq for postgres for golang parses out the whole error, including [the name of the constraint](https:/...
Oh, I found it. It's here: ``` try: db.session.commit() except sqlalchemy.exc.IntegrityError, e: constraint = e.orig.diag.constraint_name ``` In fact, the diag object has a lot of useful stuff in it: ``` >>> dir(e.orig.diag)[15:] ['column_name', 'constraint_name', 'context', 'datatype_name', 'internal_positi...
Difference between using commas, concatenation, and string formatters in Python
21,542,694
12
2014-02-04T03:58:26Z
21,542,726
20
2014-02-04T04:02:16Z
[ "python", "string" ]
I am learning python(2.7) on my own. I have learned that we can use the following ways to put strings and variables together in printing: ``` x = "Hello" y = "World" ``` By using commas: ``` print "I am printing" , x, y # I know that using comma gives automatic space ``` By using concatenation : ``` print "I am p...
To answer the general question first, you would use a print statement (or function in Python 3) in general to output information in your scripts to the screen when you're writing code to ensure that you're getting what you expect. As your coding becomes more sophisticated, you may find that logging would be better tha...
Load data from txt with pandas
21,546,739
6
2014-02-04T07:48:58Z
21,546,823
8
2014-02-04T07:53:58Z
[ "python", "io", "pandas" ]
I am loading a txt file containig a mix of float and string data. I want to store them in an array where I can access each element. Now I am just doing ``` import pandas as pd data = pd.read_csv('output_list.txt', header = None) print data ``` This is the structure of the input file: `1 0 2000.0 70.2836942112 1347.2...
You can use: ``` data = pd.read_csv('output_list.txt', sep=" ", header = None) data.columns = ["a", "b", "c", "etc."] ``` Add sep=" " in your code and leave a blank space between the quotes. So pandas can detect spaces beetween values and sort in columns. Data columns is for naming your columns.
Plotting histograms against classes in pandas / matplotlib
21,548,750
8
2014-02-04T09:41:13Z
21,549,391
12
2014-02-04T10:09:46Z
[ "python", "matplotlib", "plot", "pandas" ]
Is there a idiomatic way to plot the histogram of a feature for two classes? In pandas, I basically want ``` df.feature[df.class == 0].hist() df.feature[df.class == 1].hist() ``` To be in the same plot. I could do ``` df.feature.hist(by=df.class) ``` but that gives me two separate plots. This seems to be a common ...
How about `df.groupby("class").feature.hist()`? To see overlapping distributions you'll probably need to pass `alpha=0.4` to `hist()`. Alternatively, I'd be tempted to use a kernel density estimate instead of a histogram with `df.groupby("class").feature.plot(kind='kde')`. As an example, I plotted the iris dataset's c...
Using scikit-learn vectorizers and vocabularies with gensim
21,552,518
5
2014-02-04T12:25:15Z
21,553,171
7
2014-02-04T12:55:30Z
[ "python", "scikit-learn", "topic-modeling", "gensim" ]
I am trying to recycle scikit-learn vectorizer objects with gensim topic models. The reasons are simple: first of all, I already have a great deal of vectorized data; second, I prefer the interface and flexibility of scikit-learn vectorizers; third, even though topic modelling with gensim is very fast, computing its di...
Gensim doesn't require `Dictionary` objects. You can use your plain `dict` as input to `id2word` directly, as long as it maps ids (integers) to words (strings). In fact anything dict-like will do (including `dict`, `Dictionary`, `SqliteDict`...). (Btw gensim's `Dictionary` is a simple Python `dict` underneath. Not su...
Why is "except: pass" a bad programming practice?
21,553,327
194
2014-02-04T13:02:51Z
21,553,427
66
2014-02-04T13:07:43Z
[ "python", "exception", "exception-handling", "error-handling", "try-catch" ]
I often see comments on other Stack Overflow questions about how the use of `except: pass` is discouraged. Why is this bad? Sometimes I just don't care what the errors, are and I want to just continue with the code. ``` try: something except: pass ``` Why is using an `except: pass` block bad? What makes it ba...
Executing your pseudo code *literally* does not even give any error: ``` try: something except: pass ``` as if it is a perfectly valid piece of code, instead of throwing a `NameError`. I hope this is not what you want.
Why is "except: pass" a bad programming practice?
21,553,327
194
2014-02-04T13:02:51Z
21,553,429
21
2014-02-04T13:07:49Z
[ "python", "exception", "exception-handling", "error-handling", "try-catch" ]
I often see comments on other Stack Overflow questions about how the use of `except: pass` is discouraged. Why is this bad? Sometimes I just don't care what the errors, are and I want to just continue with the code. ``` try: something except: pass ``` Why is using an `except: pass` block bad? What makes it ba...
You should use at least `except Exception:` to avoid catching system exceptions like `SystemExit` or `KeyboardInterrupt`. Here's [link](http://docs.python.org/2/library/exceptions.html) to docs. In general you should define explicitly exceptions you want to catch, to avoid catching unwanted exceptions. You should know...
Why is "except: pass" a bad programming practice?
21,553,327
194
2014-02-04T13:02:51Z
21,553,433
10
2014-02-04T13:08:02Z
[ "python", "exception", "exception-handling", "error-handling", "try-catch" ]
I often see comments on other Stack Overflow questions about how the use of `except: pass` is discouraged. Why is this bad? Sometimes I just don't care what the errors, are and I want to just continue with the code. ``` try: something except: pass ``` Why is using an `except: pass` block bad? What makes it ba...
First, it violates two principles of [Zen of Python](https://www.python.org/dev/peps/pep-0020/#id3): * **Explicit is better than implicit** * **Errors should never pass silently** What it means, is that you intentionally make your error pass silently. Moreover, you don't event know, which error exactly occurred, beca...
Why is "except: pass" a bad programming practice?
21,553,327
194
2014-02-04T13:02:51Z
21,553,477
22
2014-02-04T13:10:08Z
[ "python", "exception", "exception-handling", "error-handling", "try-catch" ]
I often see comments on other Stack Overflow questions about how the use of `except: pass` is discouraged. Why is this bad? Sometimes I just don't care what the errors, are and I want to just continue with the code. ``` try: something except: pass ``` Why is using an `except: pass` block bad? What makes it ba...
``` >>> import this ``` > The Zen of Python, by Tim Peters > > Beautiful is better than ugly. > Explicit is better than implicit. > Simple is better than complex. > Complex is better than complicated. > Flat is better than nested. > Sparse is better than dense. > Readability counts. > Special cases aren'...
Why is "except: pass" a bad programming practice?
21,553,327
194
2014-02-04T13:02:51Z
21,553,515
242
2014-02-04T13:12:06Z
[ "python", "exception", "exception-handling", "error-handling", "try-catch" ]
I often see comments on other Stack Overflow questions about how the use of `except: pass` is discouraged. Why is this bad? Sometimes I just don't care what the errors, are and I want to just continue with the code. ``` try: something except: pass ``` Why is using an `except: pass` block bad? What makes it ba...
The main problem here is that it ignores all and any error: Out of memory, CPU is burning, user wants to stop, program wants to exit, Jabberwocky is killing users. This is way too much. In your head, you're thinking "I want to ignore this network error". If something *unexpected* goes wrong, then your code silently co...
Why is "except: pass" a bad programming practice?
21,553,327
194
2014-02-04T13:02:51Z
21,553,825
192
2014-02-04T13:27:40Z
[ "python", "exception", "exception-handling", "error-handling", "try-catch" ]
I often see comments on other Stack Overflow questions about how the use of `except: pass` is discouraged. Why is this bad? Sometimes I just don't care what the errors, are and I want to just continue with the code. ``` try: something except: pass ``` Why is using an `except: pass` block bad? What makes it ba...
As you correctly guessed, there are two sides to it: Catching *any* error by specifying no exception type after `except`, and simply passing it without taking any action. My explanation is “a bit” longer—so tl;dr it breaks down to this: 1. **Don’t catch *any* error**. Always specify which exceptions you are p...
Why is "except: pass" a bad programming practice?
21,553,327
194
2014-02-04T13:02:51Z
21,556,121
10
2014-02-04T15:10:33Z
[ "python", "exception", "exception-handling", "error-handling", "try-catch" ]
I often see comments on other Stack Overflow questions about how the use of `except: pass` is discouraged. Why is this bad? Sometimes I just don't care what the errors, are and I want to just continue with the code. ``` try: something except: pass ``` Why is using an `except: pass` block bad? What makes it ba...
The `except:pass` construct essentially silences any and all exceptional conditions that come up while the code covered in the `try:` block is being run. **What makes this bad practice is that it usually isn't what you really want.** More often, some specific condition is coming up that you want to silence, and `excep...
Why is "except: pass" a bad programming practice?
21,553,327
194
2014-02-04T13:02:51Z
21,563,149
29
2014-02-04T20:52:49Z
[ "python", "exception", "exception-handling", "error-handling", "try-catch" ]
I often see comments on other Stack Overflow questions about how the use of `except: pass` is discouraged. Why is this bad? Sometimes I just don't care what the errors, are and I want to just continue with the code. ``` try: something except: pass ``` Why is using an `except: pass` block bad? What makes it ba...
> # Why is “except: pass” a bad programming practice? This catches every possible exception, including `GeneratorExit`, `KeyboardInterrupt`, and `SystemExit` - which are exceptions you probably don't intend to catch. It's the same as catching `BaseException`. ## Python Exception Hierarchy Here's part of the [Pyt...
Why is "except: pass" a bad programming practice?
21,553,327
194
2014-02-04T13:02:51Z
21,567,036
10
2014-02-05T01:34:37Z
[ "python", "exception", "exception-handling", "error-handling", "try-catch" ]
I often see comments on other Stack Overflow questions about how the use of `except: pass` is discouraged. Why is this bad? Sometimes I just don't care what the errors, are and I want to just continue with the code. ``` try: something except: pass ``` Why is using an `except: pass` block bad? What makes it ba...
The #1 reason has already been stated - it hides errors that you did not expect. (#2) - **It makes your code difficult for others to read and understand.** If you catch a FileNotFoundException when you are trying to read a file, then it is pretty obvious to another developer what functionality the 'catch' block should...
Why is "except: pass" a bad programming practice?
21,553,327
194
2014-02-04T13:02:51Z
21,581,677
8
2014-02-05T15:41:07Z
[ "python", "exception", "exception-handling", "error-handling", "try-catch" ]
I often see comments on other Stack Overflow questions about how the use of `except: pass` is discouraged. Why is this bad? Sometimes I just don't care what the errors, are and I want to just continue with the code. ``` try: something except: pass ``` Why is using an `except: pass` block bad? What makes it ba...
So, what output does this code produce? ``` fruits = [ 'apple', 'pear', 'carrot', 'banana' ] found = False try: for i in range(len(fruit)): if fruits[i] == 'apple': found = true except: pass if found: print "Found an apple" else: print "No apples in list" ``` Now imagine the ...
Why is "except: pass" a bad programming practice?
21,553,327
194
2014-02-04T13:02:51Z
21,583,633
8
2014-02-05T17:01:27Z
[ "python", "exception", "exception-handling", "error-handling", "try-catch" ]
I often see comments on other Stack Overflow questions about how the use of `except: pass` is discouraged. Why is this bad? Sometimes I just don't care what the errors, are and I want to just continue with the code. ``` try: something except: pass ``` Why is using an `except: pass` block bad? What makes it ba...
In general, you can classify any error/exception in one of [three categories](http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx): * **Fatal**: Not your fault, you cannot prevent them, you cannot recover from them. You should certainly not ignore them and continue, and leave your program in ...
How do I prevent my FOR loop from ending too early?
21,556,097
2
2014-02-04T15:09:40Z
21,556,133
7
2014-02-04T15:11:17Z
[ "python", "for-loop" ]
CODE: ``` tsol = [6,7,8,9,10] lenth = len(tsol) for t,tnext in zip(tsol[0:lenth],tsol[1:lenth]): print t,tnext ``` RESULTS: 6,7 7,8 8,9 9,10 and t value "10" is missing
You want to use function [`itertools.izip_longest`](http://docs.python.org/2/library/itertools.html#itertools.izip_longest): ``` from itertools import izip_longest for t,tnext in izip_longest(tsol[0:lenth],tsol[1:lenth]): print t,tnext ``` Output: ``` 6 7 7 8 8 9 9 10 10 None ``` If you want to use a placeholder...
How to turn a string into a list in python?
21,559,207
2
2014-02-04T17:22:46Z
21,559,234
13
2014-02-04T17:24:20Z
[ "python", "string", "list" ]
``` l = "['Hello', 'my', 'name', 'is', 'Apple']" l1 = ['Hello', 'my', 'name', 'is', 'Apple'] ``` `type(l)` returns `str` but I want it to be a list, as `l1` is. How can I transform that string into a common list?
the `ast` module has a `literal_eval` that does what you want ``` import ast l = "['Hello', 'my', 'name', 'is', 'Apple']" l1 = ast.literal_eval(l) ``` Outputs: ``` ['Hello', 'my', 'name', 'is', 'Apple'] ``` [docs](http://docs.python.org/2/library/ast.html#ast.literal_eval)
How to write a nested dictionary to json
21,560,433
2
2014-02-04T18:27:38Z
21,560,696
10
2014-02-04T18:40:49Z
[ "python", "json", "dictionary", "nested" ]
I created a nested dictionary in Python like this: ``` { "Laptop": { "sony": 1 "apple": 2 "asus": 5 }, "Camera": { "sony": 2 "sumsung": 1 "nikon" : 4 }, } ``` But I couldn't figure out how to write this nested dict into a j...
``` d = { "Laptop": { "sony": 1, "apple": 2, "asus": 5, }, "Camera": { "sony": 2, "sumsung": 1, "nikon" : 4, }, } with open("my.json","w") as f: json.dump(d,f) ```
Django login form
21,562,619
6
2014-02-04T20:24:19Z
21,564,025
11
2014-02-04T21:38:31Z
[ "python", "django" ]
I'm a novice to django, altough I have some experience using python. I'm currently learning django, but when I try to use the included login system, I get the following error: ``` Template Loader Error: Django tried loading these templates, in this order: Using loader django.template.loaders.filesystem.Loader: Using l...
You need to provide the urls (project/urls.py) ``` from django.contrib.auth.views import login from django.contrib.auth.views import logout url( regex=r'^login/$', view=login, kwargs={'template_name': 'login.html'}, name='login' ), url( regex=r'^logout/$', view=logout, kwargs={'next_p...
Django allauth example [Errno 61] Connection refused
21,563,227
20
2014-02-04T20:56:54Z
21,563,228
44
2014-02-04T20:56:54Z
[ "python", "django", "django-allauth" ]
I have the following error when I run django allauth example and it tries to send an email: ``` File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 571, in create_connection raise err error: [Errno 61] Connection refused ``` Under OS X 10.9.1
From allauth documentation: > **When I sign up I run into connectivity errors (connection refused et al)** > > You probably have not got an e-mail (SMTP) server running on the > machine you are developing on. Therefore, allauth is unable to send > verification mails. > > You can work around this by adding the followin...
python 2 and 3 extract domain from url
21,563,744
5
2014-02-04T21:23:32Z
21,564,306
14
2014-02-04T21:53:33Z
[ "python", "parsing", "python-3.x", "compatibility", "python-2.x" ]
I have an url like: `http://xxx.abcdef.com/fdfdf/` And I want to get `xxx.abcdef.com` Which module can i use for accomplish this? I want to use the same module and method at python2 and python3 I don't like the try except way for python2/3 compatibility Thanks you so much!
Use [urlparse](http://docs.python.org/2/library/urlparse.html): ``` from urlparse import urlparse o = urlparse("http://xxx.abcdef.com/fdfdf/") print o print o.netloc ``` In Python 3, you import [urlparse](http://docs.python.org/3.3/library/urllib.parse.html?highlight=urlparse#urllib.parse.urlparse) like so: ``` fro...
Fitting a 2D Gaussian function using scipy.optimize.curve_fit - ValueError and minpack.error
21,566,379
10
2014-02-05T00:28:20Z
21,566,831
18
2014-02-05T01:14:18Z
[ "python", "numpy", "scipy", "data-fitting" ]
I intend to fit a 2D Gaussian function to images showing a laser beam to get its parameters like `FWHM` and position. So far I tried to understand how to define a 2D Gaussian function in Python and how to pass x and y variables to it. I've written a little script which defines that function, plots it, adds some noise ...
The output of `twoD_Gaussian` needs to be 1D. What you can do is add a `.ravel()` onto the end of the last line, like this: ``` def twoD_Gaussian((x, y), amplitude, xo, yo, sigma_x, sigma_y, theta, offset): xo = float(xo) yo = float(yo) a = (np.cos(theta)**2)/(2*sigma_x**2) + (np.sin(theta)**2)/(2*sigm...
Crop out partial image using NumPy (or SciPy)
21,566,610
4
2014-02-05T00:51:02Z
21,567,205
7
2014-02-05T01:51:58Z
[ "python", "numpy", "scipy" ]
Using `numpy` or `scipy` (I am not using `OpenCV`) I am trying to crop a region out of an image. For instance, I have this: ![enter image description here](http://i.stack.imgur.com/2QXbO.jpg) and I want to get this: ![enter image description here](http://i.stack.imgur.com/Y20wb.png) Is there something like `cropPo...
Are you using matplotlib? One approach I've taken previously is to use the `.contains_points()` method of a `matplotlib.path.Path` to construct a boolean mask, which can then be used to index into the image array. For example: ``` import numpy as np from matplotlib.path import Path from scipy.misc import lena img =...
Generate random array of 0 and 1 with specific ratio (python , numpy)
21,566,744
2
2014-02-05T01:04:47Z
21,566,866
10
2014-02-05T01:18:44Z
[ "python", "random", "numpy" ]
I want to generate random array of size N which only contains 0 and 1 but I want my array have some ratio between 0 and 1. For example 90% of array be 1 and the remaining 10% be 0(but I want this 90% be random along whole array). right now I have : ``` randomLabel = np.random.randint(2, size=numbers) ``` But I can't...
If you want an exact 1:9 ratio: ``` nums = numpy.ones(1000) nums[:100] = 0 numpy.random.shuffle(nums) ``` If you want independent 10% probabilities: ``` nums = numpy.random.choice([0, 1], size=1000, p=[.1, .9]) ``` or ``` nums = (numpy.random.rand(1000) > 0.1).astype(int) ```
What does this statement really do?
21,567,427
2
2014-02-05T02:19:01Z
21,567,469
10
2014-02-05T02:23:44Z
[ "python", "random" ]
I am new to python. Found a code online I am trying to understand. Can someone please help me understand what the following statement actually does? ``` self.record = [random.choice([0.0, 1.0]) for _ in range(10)] ```
``` random.choice([0.0, 1.0]) ``` The `random.choice` method will randomly pick an element of a given sequence. Here, it will randomly pick `0.0`, or `1.0`. ``` range(10) ``` This function will create a 10 element list (or iterable on python3) ``` [function() for _ in range(10)] ``` This is a list comprehension th...
Python partition and split
21,568,321
4
2014-02-05T03:53:58Z
21,568,355
9
2014-02-05T03:57:14Z
[ "python", "string", "python-2.7", "split", "partition" ]
I want to split a string with two words like "word1 word2" using split and partition and print (using a for) the words separately like: ``` Partition: word1 word2 Split: word1 word2 ``` This is my code: ``` print("Hello World") name = raw_input("Type your name: ") train = 1,2 train1 = 1,2 print("Separation with pa...
[`str.partition`](http://docs.python.org/2/library/stdtypes.html#str.partition) returns a tuple of three elements. String before the partitioning string, the partitioning string itself and the rest of the string. So, it has to be used like this ``` first, middle, rest = name.partition(" ") print first, rest ``` To us...
Python partition and split
21,568,321
4
2014-02-05T03:53:58Z
21,568,360
11
2014-02-05T03:57:53Z
[ "python", "string", "python-2.7", "split", "partition" ]
I want to split a string with two words like "word1 word2" using split and partition and print (using a for) the words separately like: ``` Partition: word1 word2 Split: word1 word2 ``` This is my code: ``` print("Hello World") name = raw_input("Type your name: ") train = 1,2 train1 = 1,2 print("Separation with pa...
A command like `name.split()` returns a list. You might consider iterating over that list: ``` for i in name.split(" "): print i ``` Because the thing you wrote, namely ``` for i in train: print name.split(" ") ``` will execute the command `print name.split(" ")` twice (once for value `i=1`, and once more for `...
Custom legend in matplotlib
21,570,007
5
2014-02-05T06:21:05Z
21,571,063
7
2014-02-05T07:25:49Z
[ "python", "matplotlib", "legend" ]
I have a a figure that looks like this: ![enter image description here](http://i.stack.imgur.com/foEVO.png) I'd like to make a legend that looks like this: ![enter image description here](http://i.stack.imgur.com/3OhdH.png) How can I do that? --- UPDATE: Note that this legend has a frame with an edgecolor: a val...
Separate headings for D and A lines: ``` from matplotlib.pyplot import * ds = [1,2,3] dc = [1.1, 1.9, 3.2] asim = [1.5, 2.2, 3.1] ac = [1.6, 2.15, 3.1] categories = ['simulated', 'calculated'] p1, = plot(ds, 'ko', label='D simulated') p2, = plot(dc, 'k:', label='D calculated') p3, = plot(asim, 'b+', label='A simulat...
Using Python and BeautifulSoup (Saved webpage source codes into a local file)
21,570,780
6
2014-02-05T07:10:53Z
21,577,649
11
2014-02-05T12:43:09Z
[ "python", "beautifulsoup" ]
Could you help me with this problem, please? (Environment: Python 2.7 + BeautifulSoup 4.3.2) I am trying to using Python and BeautifulSoup to pick up information on a webpage. Because the webpage is in the company website requires login and redirection, so I copy the source codes of the target page into a file and sa...
The best way to open a local file with BeautifulSoup is to pass it an open file handler directly. <http://www.crummy.com/software/BeautifulSoup/bs4/doc/#making-the-soup> ``` from bs4 import BeautifulSoup soup = BeautifulSoup(open("C:\\example.html")) for city in soup.find_all('span', {'class' : 'city-sh'}): prin...
convert csv file to list of dictionaries
21,572,175
9
2014-02-05T08:34:56Z
21,572,244
15
2014-02-05T08:38:34Z
[ "python", "list", "csv", "dictionary" ]
I have a csv file ``` col1, col2, col3 1, 2, 3 4, 5, 6 ``` I want to create a list of dictionary from this csv. output as : ``` a= [{'col1':1, 'col2':2, 'col3':3}, {'col1':4, 'col2':5, 'col3':6}] ``` How can I do this?
Use [`csv.DictReader`](http://docs.python.org/2/library/csv.html#csv.DictReader): ``` >>> import csv >>> >>> with open('test.csv') as f: ... a = [{k: int(v) for k, v in row.items()} ... for row in csv.DictReader(f, skipinitialspace=True)] ... >>> a [{'col2': 2, 'col3': 3, 'col1': 1}, {'col2': 5, 'col3': 6...
Map object has no len() in Python 3.3
21,572,840
7
2014-02-05T09:10:16Z
21,572,873
12
2014-02-05T09:12:10Z
[ "python", "python-3.x", "dictionary", "python-2.6" ]
So, I have this python tool wirtten by someone else to flash a certain microcontroller, but he has written his tool for python 2.6 and I am using python 3.3. So, most of it I got ported, but this line: ``` data = map(lambda c: ord(c), file(args[0], 'rb').read()) ``` is making problems. The `file` function does not e...
In Python 3.3, `map` returns an iterator, if your function expects a list, that has to be explicitly converted, like this ``` data = list(map(...)) ``` And we can do it simply, like this ``` with open(args[0], "rb") as input_file: data = list(input_file.read()) ``` `rb` refers to read in binary mode. So, it act...
matplotlib percent label position in pie chart
21,572,870
5
2014-02-05T09:11:55Z
21,580,755
8
2014-02-05T15:01:49Z
[ "python", "matplotlib" ]
Is there a way to change the default position of the percent label in a matplot lib pie chart? Here is an example pie chart: ![My pie chart](http://i.stack.imgur.com/0fo5C.png) Which I have created using: ``` plt.pie(sizes, labels=labels, colors=colors, explode=explode, autopct='%1.0f%%') ``` Now I don't like how ...
You can control the distance of the percents and labels from the center of the pie using `pctdistance=` and `labeldistance=`, try this on your code: ``` plt.pie(sizes, labels=labels, autopct='%1.0f%%', pctdistance=1.1, labeldistance=1.2) ``` You can also set a radius of the pie using `radius=` (by default is 1)
Python Scrapy can't extract text from class
21,575,540
5
2014-02-05T11:09:09Z
21,576,033
12
2014-02-05T11:30:55Z
[ "python", "css", "python-2.7", "css-selectors", "scrapy" ]
Please look this html code: ``` <header class="online"> <img src="http://static.flv.com/themes/h5/img/iconos/online.png"> <span>online</span> <img src="http://static.flv.com/themes/h5/img/iconos/ojo16.png"> 428 <p>xxfantasia</p> </header> ``` I want to get t...
CSS selectors [don't normally have syntax to extract text content](http://www.w3.org/TR/css3-selectors/). But Scrapy extends CSS selectors with the `::text` pseudo-element, so you want to use `cam.css('::text').extract()` that should give you the same thing as `cam.xpath('.//text()').extract()` Note: Scrapy also adds...
Flask-WTF / WTForms with Unittest fails validation, but works without Unittest
21,577,481
6
2014-02-05T12:35:35Z
21,584,511
13
2014-02-05T17:41:57Z
[ "python", "flask" ]
When I run app normally and do login in browser, it works. But with Unittest it won't log me in .... , it returns login page again. Both "print rv.data" just prints content of login page, but it should print content of index page, which is login\_required if it helps, I'm using SQLAlchemy as ORM. Anyone knows wha...
You should set `WTF_CSRF_ENABLED` not `CSRF_ENABLED` - right now, Flask-WTForms is trying to validate your CSRF token, but you are not providing one: ``` class TestCase(unittest.TestCase): def setUp(self): app.config['TESTING'] = True # Wrong key: # app.config['CSRF_ENABLED'] = False ...
Get grandParent using xpath in selenium webdriver
21,578,785
3
2014-02-05T13:31:51Z
21,579,064
11
2014-02-05T13:43:41Z
[ "python", "selenium", "xpath", "selenium-webdriver" ]
``` <div class="myclass"> <span>...</span> <div> <table> <colgroup>...</> <tbody> <tr>...</tr> <tr> <td> <input ...name="myname" ...> </td> ...
Instead of targeting a deeper level element and going up in the tree, you can select the higher level element and test for a descendant node attribute: ``` .//div[@class="myclass"][.//input[@name="myname"]] ```
TypeError: coercing to Unicode: need string or buffer, list found
21,580,270
3
2014-02-05T14:40:42Z
21,580,497
8
2014-02-05T14:49:34Z
[ "python", "python-2.7", "argparse" ]
trying to get this data parsing script up and running. It works as far as the data manipulation is concerned, what im trying to do is set this up so I can enter multiple user defined CSV's with a single command. e.g. ``` > python script.py One.csv Two.csv Three.csv ``` Also if you have any advice on how to automate ...
`args.infile` is a *list* of filenames, not one filename. Loop over it: ``` for filename in args.infile: base, ext = os.path.splitext(filename) with open("{}1{}".format(base, ext), "wb") as outf, open(filename, 'rb') as inf: output = csv.writer(outf) for line in csv.reader(inf): ``` Here I us...
Correct code to remove the vowels from a string in Python
21,581,824
4
2014-02-05T15:48:14Z
21,581,901
8
2014-02-05T15:51:40Z
[ "python" ]
I'm pretty sure my code is correct but it doesn't seem to returning the expected output: input `anti_vowel("Hey look words")` --> outputs: `"Hey lk wrds"`. Apparently it's not working on the `'e'`, can anyone explain why? ``` def anti_vowel(c): newstr = "" vowels = ('a', 'e', 'i', 'o', 'u') for x in c.lo...
The function [`str.replace(old, new[, max])`](http://www.tutorialspoint.com/python/string_replace.htm) don't changes `c` string itself (wrt to `c` you calls) just returns a new string which the occurrences of old have been replaced with new. So `newstr` just contains a string replaced by last vowel in `c` string that i...
How to check if a float value is a whole number
21,583,758
57
2014-02-05T17:06:10Z
21,583,817
110
2014-02-05T17:09:23Z
[ "python", "floating-point" ]
I am trying to find the largest cube root that is a whole number, that is less than 12,000. ``` processing = True n = 12000 while processing: n -= 1 if n ** (1/3) == #checks to see if this has decimals or not ``` I am not sure how to check if it is a whole number or not though! I could convert it to a string ...
To check if a float value is a whole number, use the [`float.is_integer()` method](http://docs.python.org/2/library/stdtypes.html#float.is_integer): ``` >>> (1.0).is_integer() True >>> (1.555).is_integer() False ``` The method was added to the `float` type in Python 2.6. Take into account that in Python 2, `1/3` is ...
Multiple copies of a py.test fixture
21,583,833
8
2014-02-05T17:09:47Z
21,590,140
11
2014-02-05T22:39:45Z
[ "python", "django", "testing", "py.test" ]
Let's say I have a simple fixture like the following (using pytest-django, but I think it should apply to pytest as well): ``` @pytest.fixture def my_thing(request, db): thing = MyModel.objects.create() request.addfinalizer(lambda: thing.delete()) return thing ``` This works great when my tests need a sin...
My approach would probably to create a fixture which can generate your objects: ``` @pytest.fixture def thing(request, db): class ThingFactory(object): def get(self): thing = MyModel.objects.create() request.addfinalizer(thing.delete) return thing return ThingFactory...
Matplotlib cursor value with two axes
21,583,965
5
2014-02-05T17:16:04Z
21,585,524
9
2014-02-05T18:30:18Z
[ "python", "matplotlib" ]
I used `twinx()` to get two y-axes on the plot. However, I'd like the navigation bar to report the y-coordinates of the first axis. It seems by default, it reports the position to the second axis. How do you change it to report the first axis, or better yet, report both?
Given help from tcaswell's answers ([here](http://stackoverflow.com/questions/16672530/cursor-tracking-using-matplotlib-and-twinx/16672970#16672970), and [here](http://stackoverflow.com/questions/14754931/matplotlib-values-under-cursor/14755358#14755358)), you could modify the tracker to display coordinates with respec...
Group by value of sum of columns with Pandas
21,584,434
3
2014-02-05T17:38:10Z
21,585,017
8
2014-02-05T18:06:03Z
[ "python", "group-by", "pandas", "dataframe" ]
I got lost in Pandas doc and features trying to figure out a way to `groupby` a `DataFrame` by the values of the sum of the columns. for instance, let say I have the following data : ``` In [2]: dat = {'a':[1,0,0], 'b':[0,1,0], 'c':[1,0,0], 'd':[2,3,4]} In [3]: df = pd.DataFrame(dat) In [4]: df Out[4]: a b c ...
Here you go: ``` In [57]: df.groupby(df.sum(), axis=1).sum() Out[57]: 1 9 0 2 2 1 1 3 2 0 4 [3 rows x 2 columns] ``` `df.sum()` is your grouper. It sums over the 0 axis (the index), giving you the two groups: `1` (columns `a`, `b`, and, `c`) and `9` (column `d`) . You want to group the columns (`axis=1`),...
URL query parameters to dict python
21,584,545
12
2014-02-05T17:43:42Z
21,584,580
21
2014-02-05T17:45:46Z
[ "python", "parsing", "url", "query-parameters" ]
Is there a way to parse a URL (with some python library) and return a python dictionary with the keys and values of a query parameters part of the URL? For example: ``` url = "http://www.example.org/default.html?ct=32&op=92&item=98" ``` expected return: ``` {'ct':32, 'op':92, 'item':98} ```
Use the [`urlparse` library](http://docs.python.org/2/library/urlparse.html).: ``` >>> import urlparse >>> url = "http://www.example.org/default.html?ct=32&op=92&item=98" >>> urlparse.urlsplit(url) SplitResult(scheme='http', netloc='www.example.org', path='/default.html', query='ct=32&op=92&item=98', fragment='') >>> ...
fibonacci works in python but fails in Java
21,585,932
20
2014-02-05T18:50:56Z
21,585,974
26
2014-02-05T18:52:56Z
[ "java", "python", "fibonacci" ]
I have this code for calculating `fibonacci` number in `python`. It works and gives the expected result. but when I translated the same to `Java`, it fails. Any idea of what is going wrong here? In `python`: ``` def fib3(n): a,b=0,1 while n>0: a,b=b,a+b n-=1 return a ``` `fib3(12) --> 144` In `Ja...
In this section: ``` a=b; b=a+b; ``` you're assigning `b` to `a+b`, but `a` is already `b`. So really you're doubling `b` Easiest solution is a temp variable: ``` public static int fib2(int n){ int a = 0; int b =1; while(n-- >0){ int old_a; old_a = a; a=b; b=old_a+b; ...