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
from sys import argv - what is the function of "script"
13,666,346
9
2012-12-02T04:15:33Z
13,666,377
12
2012-12-02T04:21:34Z
[ "python", "argv" ]
I am reading "Learn Python the Hard Way" and was confused by the "script" part of the second line. ``` from sys import argv script, filename = argv ``` From what I understand, the second line says: `script` and `filename` comprise `argv`. I tried running my code without the "script" part and it worked just fine. I'm ...
Generally, the first argument to a command-line executable is the script name, and the rest are the expected arguments. Here, `argv` is a list that is expected to contain two values: the script name and an argument. Using Python's unpacking notation, you can write ``` script = argv[0] filename = argv[1] ``` as ``` ...
web.py and gunicorn
13,667,103
4
2012-12-02T06:54:20Z
13,693,774
11
2012-12-03T23:40:24Z
[ "python", "heroku", "web.py", "gunicorn" ]
My question is basically what's in the title: how can I setup gunicorn to run a web.py app? (Also, if there are any differences, how would I do it on heroku?) I already have my app running on heroku using the built in cherrypy, but I have not been able to get gunicorn to work with web.py (I just have no idea where to ...
I'm afraid I'm not familar with Heroku, but I can answer your basic question. gunicorn is a HTTP server for running Python web apps via WSGI. web.py is a framework for creating Python web apps using WSGI. So you don't really need a tutorial for using both together, as all you need to do is figure out how to pass the ...
Python 2.6.1 : expected path separator ([)
13,667,979
11
2012-12-02T09:28:40Z
13,668,045
14
2012-12-02T09:37:40Z
[ "python", "xpath", "python-2.6", "elementtree" ]
I am getting a path separator error in python 2.6.1. I have not found this issue with python 2.7.2 version, but unfortunately I need this in 2.6.1 only. Is there any another way to achieve the same? :( my code :- ``` import xml.etree.ElementTree as ET #version 1.2.6 import sys class usersDetail(object): def...
You are using an XPath expression, that is not supported by the `ElementTree` version included in Python 2.6. You'll need to filter for the attribute manually, after a `.findall()`: ``` def final_xml(self,username): users = self.root.findall("user") for user in users: if user.attrib.get('username') == ...
python sorting two lists
13,668,393
14
2012-12-02T10:25:57Z
13,668,413
23
2012-12-02T10:29:34Z
[ "python", "list", "sorting" ]
I am trying to sort two lists together: ``` list1 = [1, 2, 5, 4, 4, 3, 6] list2 = [3, 2, 1, 2, 1, 7, 8] list1, list2 = (list(x) for x in zip(*sorted(zip(list1, list2)))) ``` Anyway, doing this gives me on output ``` list1 = [1, 2, 3, 4, 4, 5, 6] list2 = [3, 2, 7, 1, 2, 1, 8] ``` while I would want to keep the init...
Use a `key` parameter for your sort that only compares the first element of the pair. Since Python's sort is stable, this guarantees that the order of the second elements will remain the same when the first elements are equal. ``` >>> from operator import itemgetter >>> [list(x) for x in zip(*sorted(zip(list1, list2),...
Failing fixture load: DoesNotExist: ... matching query does not exist
13,668,728
3
2012-12-02T11:16:07Z
13,668,774
9
2012-12-02T11:21:36Z
[ "python", "django", "fixtures" ]
Running Django 1.5.x from git repo. Using south to manage migrations. I have a model such as this: ``` class Company(models.Model): name = models.CharField(max_length = 100) subdomain = models.CharField(max_length = 50) is_active = models.BooleanField(default=True) prefs = models.TextField(max_length=8...
I had pre\_save and post\_save signal triggers on my Company model. These were not checking the `raw` param and were trying to do some smart things on database values which did not exist.
What is key=lambda
13,669,252
13
2012-12-02T12:24:41Z
13,669,265
36
2012-12-02T12:26:44Z
[ "python", "lambda", "key" ]
While using some built-in functions like sorted, sum... I noticed the usage of `key=lambda` What is lambda? How does it work? What other functions use key=lambda? Are there any other key values like, `key=?`
A [`lambda`](http://docs.python.org/2/reference/expressions.html#lambda) is an anonymous function: ``` >>> f = lambda: 'foo' >>> print f() foo ``` It is often used in functions such as `sorted()` that take a callable as a parameter (often the `key` keyword parameter). You could provide an existing function instead of...
In context of Python Raw string
13,669,682
7
2012-12-02T13:24:36Z
13,669,799
9
2012-12-02T13:39:25Z
[ "python", "string", "rawstring" ]
My Python version is: ``` ~$ python --version Python 2.6.6 ``` I tried following in Python (I wants to show all): 1: `\` use as escape sequence ``` >>> str('Let\'s Python') "Let's Python" ``` 2: `\` use as escape sequence ``` >>> 'Let\'s Python' "Let's Python" ``` 3: `str()` and print as va...
You are confusing raw string literals `r''` with string representations. There is a big difference. `repr()` and `r''` are *not* the same thing. `r''` raw string literals produce a string just like a normal string literal does, with the exception to how it handles escape codes. The produced result is still a python st...
Find the smallest number that is greater than a given number in a sorted list
13,669,770
8
2012-12-02T13:36:29Z
13,669,823
10
2012-12-02T13:42:10Z
[ "python", "algorithm", "binary-search" ]
Given a sorted list of numbers, I need to find the smallest number that is greater than a given number. Consider this list: --- ``` arr=[1,2,3,5,7,11,101,131,151,181,191,313,353,373,383] ``` Say the specified number is 320. Then, my method should return 353 as 353 is the smallest number greater than 320. I am tryin...
There is a standard module, [`bisect`](http://docs.python.org/2/library/bisect.html), that does this already: ``` In [49]: arr[bisect.bisect(arr, 320)] Out[49]: 353 ``` I think this should be the go-to method for searching sorted lists. There are a few [examples](http://docs.python.org/2/library/bisect.html#searching...
Variables evaluated to False in a tuple
13,670,139
2
2012-12-02T14:20:29Z
13,670,169
7
2012-12-02T14:24:28Z
[ "python", "boolean", "tuples", "transitions" ]
Why are the `inSetStates`, `inInputAlph` and `isCorrectDirection` variables evaluated to `False` in the following code: ``` class POC(object): def __init__(self): self.__set_states = (1,2,3,4,5) self.__input_alph = ('a','b') self.__directions = ('i','d') def enterTransition(self): while True: ...
`trans` is a string, not a tuple. Strings are indexable too, so `trans[1]` is then the *string* `'1`' (the character at position 1). You'd need to convert the input to a tuple first. An easy method to do that would be to use the [`ast.literal_eval()` function](http://docs.python.org/2/library/ast.html#ast.literal_eval...
Multiple variables in SciPy's optimize.minimize
13,670,333
12
2012-12-02T14:43:54Z
13,670,414
13
2012-12-02T14:54:56Z
[ "python", "math", "scipy" ]
According to the [SciPy documentation](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html) it is possible to minimize functions with multiple variables, yet it doesn't tell how to optimize on such functions. ``` from scipy.optimize import minimize from math import * def f(c): return sq...
Pack the multiple variables into a single array: ``` import scipy.optimize as optimize def f(c): return sqrt(c[0]**2 + c[1]**2 + c[2]**2) result = optimize.minimize(f, [1,1,1]) print(result) ```
Python PIL - changing colour profile to untagged RGB on crop, scale and save
13,672,777
13
2012-12-02T19:16:20Z
14,537,273
13
2013-01-26T13:12:46Z
[ "python" ]
Can't figure out why the document profile is being changed on a crop, scale and save with PIL. Have tested with an image that had sRGB as color profile, and after it has untagged RGB. ``` def scale(self, image): images = [] image.seek(0) try: im = PIL.open(image) except IOError, e: lo...
PIL has a function to read the icc\_profile and also a way to save with icc\_profile. So what I did was to open the file to get the icc\_profile: ``` try: im1 = PIL.open(image) icc_profile = im1.info.get("icc_profile") ``` And the add it to the file again on save: ``` im.save(d, "JPEG", icc_profile=icc_profi...
Split string into strings by length?
13,673,060
15
2012-12-02T19:45:01Z
13,673,133
37
2012-12-02T19:51:30Z
[ "python" ]
Is there a way to take a string that is `4*x` characters long, and cut it into 4 strings, each `x` characters long, without knowing the length of the string? For example: ``` >>>x = "qwertyui" >>>split(x, one, two, three, four) >>>two 'er' ```
``` >>> x = "qwertyui" >>> chunks, chunk_size = len(x), len(x)/4 >>> [ x[i:i+chunk_size] for i in range(0, chunks, chunk_size) ] ['qw', 'er', 'ty', 'ui'] ```
Split string into strings by length?
13,673,060
15
2012-12-02T19:45:01Z
23,384,110
8
2014-04-30T09:12:48Z
[ "python" ]
Is there a way to take a string that is `4*x` characters long, and cut it into 4 strings, each `x` characters long, without knowing the length of the string? For example: ``` >>>x = "qwertyui" >>>split(x, one, two, three, four) >>>two 'er' ```
I tried Alexanders answer but got this error in Python3: ``` TypeError: 'float' object cannot be interpreted as an integer ``` This is because the division operator in Python3 is returning a float. This works for me: ``` >>> x = "qwertyui" >>> chunks, chunk_size = len(x), len(x)//4 >>> [ x[i:i+chunk_size] for i in r...
Splitting a string where it switches between numeric and alphabetic characters
13,673,781
4
2012-12-02T20:58:16Z
13,673,825
8
2012-12-02T21:04:26Z
[ "python" ]
I am parsing some data where the standard format is something like `10 pizzas`. Sometimes, data is input correctly and we might end up with `5pizzas` instead of `5 pizzas`. In this scenario, I want to parse out the number of pizzas. The naïve way of doing this would be to check character by character, building up a s...
To split the string at digits you can use [`re.split`](http://docs.python.org/2/library/re.html#re.split) with the regular expression `\d+`: ``` >>> import re >>> def my_split(s): return filter(None, re.split(r'(\d+)', s)) >>> my_split('5pizzas') ['5', 'pizzas'] >>> my_split('foo123bar') ['foo', '123', 'bar'] ```...
Splitting a string where it switches between numeric and alphabetic characters
13,673,781
4
2012-12-02T20:58:16Z
13,673,827
7
2012-12-02T21:04:34Z
[ "python" ]
I am parsing some data where the standard format is something like `10 pizzas`. Sometimes, data is input correctly and we might end up with `5pizzas` instead of `5 pizzas`. In this scenario, I want to parse out the number of pizzas. The naïve way of doing this would be to check character by character, building up a s...
You ask for a way to split a string on digits, but then in your example, what you actually want is just the first numbers, this done easily with [`itertools.takewhile()`](http://docs.python.org/3/library/itertools.html#itertools.takewhile): ``` >>> int("".join(itertools.takewhile(str.isdigit, "10pizzas"))) 10 ``` Thi...
Python's string.format() and Unicode
13,674,663
11
2012-12-02T22:33:09Z
13,674,809
17
2012-12-02T22:50:47Z
[ "python", "unicode" ]
I'm having a problem with Python's `string.format()` and passing Unicode strings to it. This is similar to [this older question](http://stackoverflow.com/questions/1545263/utf-8-in-python-logging-how), except that in my case the test code explodes on the print, not on the `logging.info()` call. Passing the same Unicode...
No this should not work (can you cite the part of the documentation that says so ?), but it should work if the formatting pattern is unicode (or with the old formatting which 'promotes' the pattern to unicode instead of trying to 'demote' arguments). ``` >>> x = "\xc3\xb4".decode('utf-8') >>> x u'\xf4' >>> x + 'a' u'\...
Python: TypeError: unhashable type: 'list'
13,675,296
19
2012-12-02T23:49:20Z
13,675,324
7
2012-12-02T23:52:14Z
[ "python", "list", "dictionary", "typeerror" ]
I'm trying to take a file that looks like this ``` AAA x 111 AAB x 111 AAA x 112 AAC x 123 ... ``` And use a dictionary to so that the output looks like this ``` {AAA: ['111', '112'], AAB: ['111'], AAC: [123], ...} ``` This is what I've tried ``` file = open("filename.txt", "r") readline = file.readline().rstrip(...
You're trying to use `k` (which is a list) as a key for `d`. Lists are mutable and can't be used as dict keys. Also, you're never initializing the lists in the dictionary, because of this line: ``` if k not in d == False: ``` Which should be: ``` if k not in d == True: ``` Which should actually be: ``` if k not i...
Python: TypeError: unhashable type: 'list'
13,675,296
19
2012-12-02T23:49:20Z
13,675,403
15
2012-12-03T00:01:40Z
[ "python", "list", "dictionary", "typeerror" ]
I'm trying to take a file that looks like this ``` AAA x 111 AAB x 111 AAA x 112 AAC x 123 ... ``` And use a dictionary to so that the output looks like this ``` {AAA: ['111', '112'], AAB: ['111'], AAC: [123], ...} ``` This is what I've tried ``` file = open("filename.txt", "r") readline = file.readline().rstrip(...
As indicated by the other answers, the error is to due to `k = list[0:j]`, where your key is converted to a list. One thing you could try is reworking your code to take advantage of the `split` function: ``` # Using with ensures that the file is properly closed when you're done with open('filename.txt', 'rb') as f: ...
Zipping nested lists in Python
13,675,505
2
2012-12-03T00:15:28Z
13,675,517
7
2012-12-03T00:17:22Z
[ "python" ]
Say I have the following two lists/numpy arrays: ``` List1 = [[1,2,3,4], [10,11,12], ...] List2 = [[-1,-2-3,-4], [-10,-11,-12], ...] ``` I would like to obtain a list that holds the zipping of the nested lists above: ``` Result = [[(1,-1), (2,-2), (3,-3), (4,-4)], [(10,-10), (11, -11), (12,-12)], ...] ``` Is there ...
``` l1 = [[1,2,3,4], [10,11,12]] l2 = [[-1,-2,-3,-4], [-10,-11,-12]] print [zip(a,b) for a,b in zip(l1,l2)] ``` ``` [[(1, -1), (2, -2), (3, -3), (4, -4)], [(10, -10), (11, -11), (12, -12)]] ```
Python programming - numpy polyfit saying NAN
13,675,912
4
2012-12-03T01:24:55Z
13,693,657
12
2012-12-03T23:27:31Z
[ "python", "numpy", null ]
I am having some issues with a pretty simple code I have written. I have 4 sets of data, and want to generate polynomial best fit lines using numpy polyfit. 3 of the lists yield numbers when using polyfit, but the third data set yields NAN when using polyfit. Below is the code and the print out. Any ideas? Code: ### ...
Just looked at your data. This is happening because you have a `NaN` in `dep_3` (element 713). You can make sure that you only use finite values in the fit like this: ``` idx = np.isfinite(ind_3) & np.isfinite(dep_3) print(np.polyfit(ind_3[idx], dep_3[idx], 2)) ``` As for finding for bad values in large datasets, num...
Getting SQLAlchemy to issue CREATE SCHEMA on create_all
13,677,781
9
2012-12-03T05:41:30Z
13,677,782
15
2012-12-03T05:41:30Z
[ "python", "postgresql", "sqlalchemy" ]
I have a SqlAlchemy model with a schema argument like so: ``` Base = declarative_base() class Road(Base): __tablename__ = "roads" __table_args__ = {'schema': 'my_schema'} id = Column(Integer, primary_key=True) ``` When I use Base.metadata.create\_all(engine) it correctly issues a CREATE TABLE with the schema n...
I have done it manually on my db init script like so: ``` from sqlalchemy.schema import CreateSchema engine.execute(CreateSchema('my_schema')) ``` But this seems less magical than I was expecting.
Getting SQLAlchemy to issue CREATE SCHEMA on create_all
13,677,781
9
2012-12-03T05:41:30Z
22,212,214
7
2014-03-06T00:10:32Z
[ "python", "postgresql", "sqlalchemy" ]
I have a SqlAlchemy model with a schema argument like so: ``` Base = declarative_base() class Road(Base): __tablename__ = "roads" __table_args__ = {'schema': 'my_schema'} id = Column(Integer, primary_key=True) ``` When I use Base.metadata.create\_all(engine) it correctly issues a CREATE TABLE with the schema n...
I ran into the same issue and believe the "cleanest" way of issuing the DDL is something like this: ``` from sqlalchemy import event from sqlalchemy.schema import CreateSchema event.listen(Base.metadata, 'before_create', CreateSchema('my_schema')) ``` This will ensure that before anything contained in the metadata o...
Python - Flask Default Route possible?
13,678,397
9
2012-12-03T06:44:37Z
13,678,543
13
2012-12-03T06:56:47Z
[ "python", "flask", "cherrypy" ]
In Cherrypy it's possible to do this: ``` @cherrypy.expose def default(self, url, *suburl, **kwarg): pass ``` Is there a flask equivalent?
There is a snippet on Flask's website about a 'catch-all' route for flask. [You can find it here](http://flask.pocoo.org/snippets/57/). Basically the decorator works by chaining two URL filters. The example on the page is: ``` @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def catch_all(path): ...
How can I pass kwargs in URL in django
13,678,933
11
2012-12-03T07:29:19Z
13,678,956
8
2012-12-03T07:31:30Z
[ "python", "django" ]
In the django doc the url function is like this ``` url(regex, view, kwargs=None, name=None, prefix='') ``` I have this ``` url(r'^download/template/(?P<object_id>\d+)/$', views.myview().myfunction,model=models.userModel, name="sample") ``` This is my view ``` class myview(TemplateView): def myfunction(self,r...
This: ``` url(r'^download/template/(?P<object_id>\d+)/$', views.myview().myfunction,model=models.userModel, name="sample") ``` Should be: ``` url(r'^download/template/(?P<object_id>\d+)/$', views.myview.as_view(model=models.userModel), name="sample") ``` See [docs](https://docs.djangoproject.com/en/dev/topics/class...
How can I pass kwargs in URL in django
13,678,933
11
2012-12-03T07:29:19Z
13,678,966
16
2012-12-03T07:33:05Z
[ "python", "django" ]
In the django doc the url function is like this ``` url(regex, view, kwargs=None, name=None, prefix='') ``` I have this ``` url(r'^download/template/(?P<object_id>\d+)/$', views.myview().myfunction,model=models.userModel, name="sample") ``` This is my view ``` class myview(TemplateView): def myfunction(self,r...
You are trying to pass in a `model` keyword argument to the `url()` function; you need to pass in a `kwargs` argument instead (it takes a dictionary): ``` url(r'^download/template/(?P<object_id>\d+)/$', views.myview().myfunction, kwargs=dict(model=models.userModel), name="sample") ```
Pandas DataFrame: remove unwanted parts from strings in a column
13,682,044
27
2012-12-03T11:11:56Z
13,682,381
31
2012-12-03T11:33:51Z
[ "python", "dataframe", "pandas" ]
I am looking for an efficient way to remove unwanted parts from strings in a DataFrame column. Data looks like: ``` time result 1 09:00 +52A 2 10:00 +62B 3 11:00 +44a 4 12:00 +30b 5 13:00 -110a ``` I need to trim these data to: ``` time result 1 09:00 52 2 10:00 62 3...
``` data['result'] = data['result'].map(lambda x: x.lstrip('+-').rstrip('aAbBcC')) ```
Pandas DataFrame: remove unwanted parts from strings in a column
13,682,044
27
2012-12-03T11:11:56Z
13,688,105
8
2012-12-03T17:00:37Z
[ "python", "dataframe", "pandas" ]
I am looking for an efficient way to remove unwanted parts from strings in a DataFrame column. Data looks like: ``` time result 1 09:00 +52A 2 10:00 +62B 3 11:00 +44a 4 12:00 +30b 5 13:00 -110a ``` I need to trim these data to: ``` time result 1 09:00 52 2 10:00 62 3...
There's a bug here: currently cannot pass arguments to `str.lstrip` and `str.rstrip`: <http://github.com/pydata/pandas/issues/2411> EDIT: 2012-12-07 this works now on the dev branch: ``` In [8]: df['result'].str.lstrip('+-').str.rstrip('aAbBcC') Out[8]: 1 52 2 62 3 44 4 30 5 110 Name: result ```
lxml not adding newlines when inserting a new element into existing xml
13,683,014
6
2012-12-03T12:12:56Z
13,683,115
7
2012-12-03T12:18:53Z
[ "python", "lxml" ]
I have a large set of existing xml files, and I am trying to add one element to all of them (they are pom.xml for a number of maven projects, and I am trying to add a parent element to all of them). The following is my exact code. The problem is that the final xml output in pom2.xml has the complete `parent` element i...
This might be of intrest to you. <http://lxml.de/FAQ.html#why-doesn-t-the-pretty-print-option-reformat-my-xml-output> In short for future reference: ``` parser = etree.XMLParser(remove_blank_text=True) pom = etree.parse("pom.xml",parser) ```
How to add hours to current time in python
13,685,201
43
2012-12-03T14:23:04Z
13,685,221
114
2012-12-03T14:23:56Z
[ "python", "time", "add" ]
I can able to get the current time as below ``` from datetime import datetime str(datetime.now())[11:19] ``` **Result** ``` '19:43:20' ``` Now i am trying to add `9 hours` to the above time, how can we add hours to current time in python
``` from datetime import datetime, timedelta nine_hours_from_now = datetime.now() + timedelta(hours=9) #datetime.datetime(2012, 12, 3, 23, 24, 31, 774118) ``` And then use string formatting to get the relevant pieces: ``` >>> '{:%H:%M:%S}'.format(nine_hours_from_now) '23:24:31' ``` If you're only formatting the dat...
Retrieving GroupResult from taskset_id in Celery?
13,685,344
4
2012-12-03T14:30:46Z
14,186,115
11
2013-01-06T19:57:07Z
[ "python", "celery", "celery-task" ]
I am starting a set of celery tasks by using celery group as described in the [official documentation](http://celery.github.com/celery/userguide/tasksets.html#groups) I am also storing the group (taskset) id into a db, in order to poll celery for the taskset state. ``` job = group([ single_test.s(1, 1), ...
Yes you have to save the result and then restore it. ``` job = group([ single_test.s(1, 1), single_test.s(1, 2), single_test.s(1, 3), ]) result = job.apply_async() result.save() from celery.result import GroupResult saved_result = GroupResult.restore(result.id) ``` I had the same issue and after seeing y...
matplotlib (equal unit length): with 'equal' aspect ratio z-axis is not equal to x- and y-
13,685,386
32
2012-12-03T14:33:32Z
13,701,747
30
2012-12-04T11:21:58Z
[ "python", "matplotlib", "aspect-ratio" ]
When I set up equal aspect ratio for 3d graph the z-axis does not change to 'equal'. So, this: ``` fig = pylab.figure() mesFig = fig.gca(projection='3d', adjustable='box') mesFig.axis('equal') mesFig.plot(xC, yC, zC, 'r.') mesFig.plot(xO, yO, zO, 'b.') pyplot.show() ``` gives me the following: ![enter image descripti...
I believe matplotlib does not yet set correctly equal axis in 3D... But I found a trick some times ago (I don't remember where) that I've adapted using it. The concept is to create a fake cubic bounding box around your data. You can test it with the following code: ``` from mpl_toolkits.mplot3d import Axes3D from matp...
matplotlib (equal unit length): with 'equal' aspect ratio z-axis is not equal to x- and y-
13,685,386
32
2012-12-03T14:33:32Z
21,765,085
19
2014-02-13T20:44:50Z
[ "python", "matplotlib", "aspect-ratio" ]
When I set up equal aspect ratio for 3d graph the z-axis does not change to 'equal'. So, this: ``` fig = pylab.figure() mesFig = fig.gca(projection='3d', adjustable='box') mesFig.axis('equal') mesFig.plot(xC, yC, zC, 'r.') mesFig.plot(xO, yO, zO, 'b.') pyplot.show() ``` gives me the following: ![enter image descripti...
I simplified Remy F's solution by using the `set_x/y/zlim` [functions](http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_xlim). ``` from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.gca(projection='3d') ax.se...
OpenCV Python calcOpticalFlowFarneback
13,685,771
6
2012-12-03T14:55:14Z
13,687,932
12
2012-12-03T16:51:02Z
[ "python", "opencv" ]
Thanks a lot, if any people can help me. Im try, use a example of book "OReilly Programming Computer Vision with Python", at end of page 216. ``` #!/usr/bin/env python import cv2 def draw_flow(im,flow,step=16): h,w = im.shape[:2] y,x = mgrid[step/2:h:step,step/2:w:step].reshape(2,-1) fx,fy = flow[y,x]...
You need to change the code a little bit. First of all, include Numpy library since methods like `mgrid`, `int32`, `vstack` are numpy functions. So at top of the code, add : ``` from numpy import * ``` Second, coming to your question, fourth argument should be an `int`. You have supplied it as float. Make it 1 (or ...
Python module for getting latitude and longitude from the name of a US city?
13,686,001
6
2012-12-03T15:08:10Z
13,686,031
17
2012-12-03T15:09:50Z
[ "python", "geolocation" ]
I am looking for a python module which can take in the name of the city as the input and return the latitude and longitude of the input.
Have a look at [**geopy**](https://github.com/geopy/geopy). In the "getting started" documentation it shows: ``` >>> from geopy import geocoders >>> gn = geocoders.GeoNames() >>> print gn.geocode("Cleveland, OH 44106") (u'Cleveland, OH, US', (41.4994954, -81.6954088)) >>> gn.geocode("Cleveland, OH", exactly_one=Fa...
Django generate the model from database
13,687,764
2
2012-12-03T16:41:49Z
13,687,860
7
2012-12-03T16:46:21Z
[ "python", "django", "python-2.7" ]
I already have a pre-existing database but now want to use Django. Is there a way to auto generate the model Django needs from my database? For example if I already had a database with tables defined from another application.
You should take a look at the command `inspectdb` in the [Django documentation](https://docs.djangoproject.com/en/dev/ref/django-admin/#inspectdb). This is a management command to do that, although it doesn't always works, it would be a good starting point.
Setting a value in a nested python dictionary given a list of indices and value
13,687,924
14
2012-12-03T16:50:33Z
13,688,108
16
2012-12-03T17:00:42Z
[ "python", "list", "dictionary" ]
Sorry if this question has been answered before - I've been searching for solutions but I maybe am not using the correct search terms. Anyway, what I'm trying to do is to programmatically set a value in a dictionary, potentially nested, given a list of indices and a value. So for example, let's say my list of indices...
Something like this could help: ``` def nested_set(dic, keys, value): for key in keys[:-1]: dic = dic.setdefault(key, {}) dic[keys[-1]] = value ``` And you can use it like this: ``` >>> d = {} >>> nested_set(d, ['person', 'address', 'city'], 'New York') >>> d {'person': {'address': {'city': 'New York...
Why that version of mergesort is faster
13,688,084
8
2012-12-03T16:59:14Z
13,688,977
10
2012-12-03T17:56:45Z
[ "python", "mergesort" ]
Based on [that answer](http://stackoverflow.com/a/7064487/381130) here are two versions of merge function used for mergesort. Could you help me to understand why the second one is much faster. I have tested it for list of 50000 and the second one is 8 times faster ([Gist](https://gist.github.com/4196181)). ``` def mer...
Similar answer as [kreativitea](http://stackoverflow.com/a/13688540/432913)'s above, but with more info (i think!) So profiling the actual merge functions, for the merging of two 50K arrays, ### merge 1 ``` 311748 function calls in 15.363 seconds Ordered by: standard name ncalls tottime percall c...
SSLSocket passphrase/password in Python
13,688,713
5
2012-12-03T17:38:35Z
13,692,715
18
2012-12-03T22:13:45Z
[ "python", "ios", "ssl", "python-2.7", "push-notification" ]
I've been looking into making an iOS push notification service for one of my apps lately. It has a Python 2.7 backend so I wanted to do it in Python rather than PHP (or anything else). I've got code that sends a notification and the device receives it, however every time I run the code it asks me to manually enter a '...
So the answer as BorrajaX suggested was to not set a password for the key when prompted. However this is not possible as (at least on my Mac) wants the password to be a minimum 4 characters. The steps to fix this are: 1. Create the certificate in the developer portal. 2. Download and open the certificate locally in K...
numpy diff on a pandas Series
13,689,512
8
2012-12-03T18:35:28Z
13,689,607
8
2012-12-03T18:41:47Z
[ "python", "numpy", "pandas" ]
I want to use numpy.diff on a pandas Series. Am I right that this is a bug? Or am I doing it wrong? ``` In [163]: s = Series(np.arange(10)) In [164]: np.diff(s) Out[164]: 0 NaN 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 NaN In [165]: np.diff(np.arange(10)) Out[165]: array([1, 1, 1, 1, 1, ...
Pandas implements `diff` like so: ``` In [3]: s = pd.Series(np.arange(10)) In [4]: s.diff() Out[4]: 0 NaN 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 ``` Using `np.diff` directly: ``` In [7]: np.diff(s.values) Out[7]: array([1, 1, 1, 1, 1, 1, 1, 1, 1]) In [8]: np.diff(np.array(s)) Out...
How to get the amount of "work" left to be done by a Python multiprocessing Pool?
13,689,927
6
2012-12-03T19:05:11Z
16,000,687
7
2013-04-14T15:21:25Z
[ "python", "process", "parallel-processing", "multiprocessing", "pool" ]
So far whenever I needed to use [`multiprocessing`](http://docs.python.org/2/library/multiprocessing.htm) I have done so by manually creating a "process pool" and sharing a working Queue with all subprocesses. For example: ``` from multiprocessing import Process, Queue class MyClass: def __init__(self, num_pro...
Use a `Manager` queue. This is a queue that is shared between worker processes. If you use a normal queue it will get pickled and unpickled by each worker and hence copied, so that the queue can't be updated by each worker. You then have your workers add stuff to the queue and monitor the queue's state while the worke...
Ternary operation on dictionary
13,690,961
3
2012-12-03T20:17:09Z
13,690,987
10
2012-12-03T20:19:12Z
[ "python", "dictionary", "conditional-operator" ]
Is there a way to do a ternary operation on a dict where the test is has\_key() without hitting the key error? i.e. ``` variable = dict["the_key"] if dict.has_key("the_key") else "something" ``` (this hits the key error obviously) failing that, what's the most pythonic way to assign a bunch of variables values based...
This: ``` mydict.get(key, default_value) ``` Not 100% the same as `default_value` is evaluated straight away while the `else` part is only evaluated when the condition is met.
Python: Pinpointing the Linear Part of a Slope
13,691,775
8
2012-12-03T21:10:23Z
13,728,059
17
2012-12-05T16:40:30Z
[ "python", "linear" ]
I have several plots that look like the following: ![enter image description here](http://i.stack.imgur.com/hbJfU.png) I am wondering what kind of methods there might be for finding the slope between approximately 5.5 and 8 for the x-axis. Where there are several plots like this, I am moreso wondering if there is a w...
A generic way to find linear parts in data sets is to calculate the second derivative of the function, and see where it is (close to) zero. There are several things to consider on the way to the solution: * How to calculate the second derivative of noisy data? One fast and simple method, that can easily be adapted to ...
linux bash script running multiple python
13,692,519
9
2012-12-03T22:00:27Z
13,692,565
18
2012-12-03T22:03:05Z
[ "python", "linux", "bash" ]
I have 2 python scripts a.py and b.py and I want to write a bash script that will load a.py and not run b.py until a.py is done doing it's thing. simplistically ``` #!/usr/bin/env bash python a.py python b.py ``` but this is naive, a check to see if a.py is done... how do I do that?
This by default will already run one after the other. --- To check that `python a.py` completed successfully as a required condition for running `python b.py`, you can do: ``` #!/usr/bin/env bash python a.py && python b.py ``` --- Conversely, attempt to run `python a.py`, and ONLY run 'python b.py' if `python a.py...
Can SQLAlchemy events be used to update a denormalized data cache?
13,693,872
5
2012-12-03T23:49:24Z
13,765,857
28
2012-12-07T15:15:38Z
[ "python", "sqlalchemy", "denormalization" ]
For performance reasons, I've got a denormalized database where some tables contain data which has been aggregated from many rows in other tables. I'd like to maintain this denormalized data cache by using [SQLAlchemy events](http://docs.sqlalchemy.org/en/rel_0_8/orm/events.html). As an example, suppose I was writing f...
the after\_insert() event is one way to do this, and you might notice it is passed a SQLAlchemy `Connection` object, instead of a `Session` as is the case with other flush related events. The mapper-level flush events are intended to be used normally to invoke SQL directly on the given `Connection`: ``` @event.listens...
Accessing dict elements with leading underscores in Django Templates
13,693,888
2
2012-12-03T23:50:02Z
13,694,031
8
2012-12-04T00:08:45Z
[ "python", "django", "elasticsearch" ]
I am trying to access elements of a dict with keys that start with the underscore character. For example: `my_dict = {"_source": 'xyz'}` I'm trying to access them in a Django template. Obviously I realise that you can't access underscored python variables from a Django template (because they are considered private in...
[The docs mention](https://docs.djangoproject.com/en/dev/ref/templates/api/#variables-and-lookups) that you can't have a variable start with an underscore: > Variable names must consist of any letter (A-Z), any digit (0-9), an underscore (but they must not start with an underscore) or a dot. but you can easily write ...
If dict key doesn't exist or is zero?
13,694,025
2
2012-12-04T00:08:09Z
13,694,079
7
2012-12-04T00:14:43Z
[ "python", "dictionary" ]
I'd like to determine which of the following states a dict key's value is in: 1. Doesn't exist 2. Exists, but is equal to an int of 0 3. Exists, and is equal to an int greater than 0 Here's what I'm currently trying: ``` if item[itemTo] == 0: print("You don't have a %s." % (itemTo)) elif item[itemTo] > 0: pr...
You want to change the order of the tests: ``` if itemTo not in item: print("%s doesn't exist." % (itemTo)) elif item[itemTo] > 0: print("You have %i of %s." % (item[itemTo])) else: print("You don't have a %s." % (itemTo)) ```
Is a Python list guaranteed to have its elements stay in the order they are inserted in?
13,694,034
146
2012-12-04T00:09:26Z
13,694,053
179
2012-12-04T00:11:45Z
[ "python" ]
If I have the following Python code ``` >>> x = [] >>> x = x + [1] >>> x = x + [2] >>> x = x + [3] >>> x [1, 2, 3] ``` Will `x` be guaranteed to always be `[1,2,3]`, or are other orderings of the interim elements possible?
Yes, the order of elements in a python list is persistent.
Is a Python list guaranteed to have its elements stay in the order they are inserted in?
13,694,034
146
2012-12-04T00:09:26Z
13,694,111
41
2012-12-04T00:17:25Z
[ "python" ]
If I have the following Python code ``` >>> x = [] >>> x = x + [1] >>> x = x + [2] >>> x = x + [3] >>> x [1, 2, 3] ``` Will `x` be guaranteed to always be `[1,2,3]`, or are other orderings of the interim elements possible?
In short, yes, the order is preserved. In long: In general the following definitions will always apply to objects like lists: A **list** is a collection of elements that can contain duplicate elements and has a defined order that generally does not change unless explicitly made to do so. **stacks** and **queues** are...
Parsing CDATA in xml with python
13,694,143
8
2012-12-04T00:21:02Z
14,432,066
10
2013-01-21T03:22:55Z
[ "python", "xml", "parsing", "lxml" ]
I need to parse an XML file with a number of blocks of CDATA that I need to retain for later plotting: `<process id="process1"> <log name="name1" device="device1"><![CDATA[timestamp value]]]></log> <log name="name2" device="device2"><![CDATA[timestamp value, timestamp value, timestamp]]]></log> </process>` I will nee...
Here are two examples of how to do it: ``` from lxml import etree import xml.etree.ElementTree as ElementTree CONTENT = """ <process id="process1"> <log name="name1" device="device1"><![CDATA[timestamp value]]></log> <log name="name2" device="device2"><![CDATA[timestamp value, timestamp value, timestamp]]></log> </...
Convert to Float without Rounding Decimal Places
13,695,692
3
2012-12-04T03:37:40Z
13,695,752
9
2012-12-04T03:46:26Z
[ "python", "list", "floating-point" ]
I have a list and it contains a certain number `'5.74536541'` in it which I convert to a float. I am printing it out in Python 3 using `("%0.2f" % (variable))` but it always prints out 5.75 instead of 5.74. I know you're thinking who cares, but it is for a currency converter program and I don't want the currencies to...
You shouldn't use floating point numbers for currency, due to rounding errors like you mentioned. Your best bet is to use a [fixed-precision `decimal`](http://docs.python.org/2/library/decimal.html) where you also have full control over how rounding and truncation works. From the docs: ``` >>> from decimal import * >...
Storing and Accessing node attributes python networkx
13,698,352
11
2012-12-04T07:56:11Z
13,702,743
18
2012-12-04T12:19:32Z
[ "python", "attributes", "networkx" ]
I have a network of nodes created using python `networkx`. i want to store information in nodes such that i can access the information later based on the node label (the name of the node) and the field that in which the information has been stored (like node attributes). the information stored can be a string or a numb...
As you say, it's just a matter of adding the attributes when adding the nodes to the graph ``` G.add_node('abc', dob=1185, pob='usa', dayob='monday') ``` or as a dictionary ``` G.add_node('abc', {'dob': 1185, 'pob': 'usa', 'dayob': 'monday'}) ``` To access the attributes, just access them as you would with any dict...
Python: Searching for an int in a list
13,698,497
3
2012-12-04T08:08:34Z
13,698,524
13
2012-12-04T08:10:13Z
[ "python", "list", "search" ]
Say I have this list ``` x = [1,2,3,1,5,1,8] ``` Is there a way to find every index that `1` is in the list?
Sure. A list comprehension plus [enumerate](http://docs.python.org/2/library/functions.html#enumerate) should work: ``` [i for i, z in enumerate(x) if z == 1] ``` And the proof: ``` >>> x = [1, 2, 3, 1, 5, 1, 8] >>> [i for i, z in enumerate(x) if z == 1] [0, 3, 5] ```
how to get the caller's filename, method name in python
13,699,283
8
2012-12-04T09:06:12Z
13,699,329
10
2012-12-04T09:08:11Z
[ "python" ]
for example, `a.boo` method calls `b.foo` method. In `b.foo` method, how can I get a's file name (I don't want to pass `__file__` to `b.foo` method)...
You can use the `inspect` module to achieve this: ``` frame = inspect.stack()[1] module = inspect.getmodule(frame[0]) # Use module.__name__ ```
How to set TCP_NODELAY flag when loading URL with urllib2?
13,699,973
11
2012-12-04T09:45:20Z
17,882,197
11
2013-07-26T13:10:12Z
[ "python", "sockets", "urllib2", "urlopen", "setsockopt" ]
I am using urllib2 for loading web-page, my code is: ``` httpRequest = urllib2.Request("http:/www....com") pageContent = urllib2.urlopen(httpRequest) pageContent.readline() ``` How can I get hold of the socket properties to set `TCP_NODELAY`? In normal socket I would be using function: ``` socket.setsockopt(socket....
If you need to access to such low level property on the socket used, you'll have to overload some objects. First, you'll need to create a subclass of [HTTPHandler](http://docs.python.org/2/library/urllib2.html?highlight=urllib2#urllib2.HTTPHandler), that in the standard library do : ``` class HTTPHandler(AbstractHTTP...
How to set TCP_NODELAY flag when loading URL with urllib2?
13,699,973
11
2012-12-04T09:45:20Z
17,951,729
7
2013-07-30T15:53:11Z
[ "python", "sockets", "urllib2", "urlopen", "setsockopt" ]
I am using urllib2 for loading web-page, my code is: ``` httpRequest = urllib2.Request("http:/www....com") pageContent = urllib2.urlopen(httpRequest) pageContent.readline() ``` How can I get hold of the socket properties to set `TCP_NODELAY`? In normal socket I would be using function: ``` socket.setsockopt(socket....
for requests, the classes seem to be in request.packages.urllib3; there are 2 classes, HTTPConnection, and HTTPSConnection. They should be monkeypatchable in place at the module top level: ``` from request.packages.urllib3 import connectionpool _HTTPConnection = connectionpool.HTTPConnection _HTTPSConnection = connec...
How to duplicate an estimator in order to use it on multiple data sets?
13,701,603
7
2012-12-04T11:12:48Z
13,701,833
8
2012-12-04T11:26:37Z
[ "python", "machine-learning", "scikit-learn" ]
Here is an example that creates two data sets: ``` from sklearn.linear_model import LogisticRegression from sklearn.datasets import make_classification # data set 1 X1, y1 = make_classification(n_classes=2, n_features=5, random_state=1) # data set 2 X2, y2 = make_classification(n_classes=2, n_features=5, random_state...
``` from sklearn.base import clone lr1 = LogisticRegression() lr2 = clone(lr1) ```
How do I hide a sub-menu in QMenu
13,703,136
3
2012-12-04T12:40:37Z
13,703,310
12
2012-12-04T12:49:16Z
[ "python", "hide", "pyqt4", "submenu" ]
I have an application where I generate menu items, and I want to set the visibility of a particular sub-menu. I tried using `setVisibility(False)`, but this did not work. `setVisibility()` works for menu items, but not for sub-menus in QMenus. Have a look at the code snippet below: ``` import sys from PyQt4 import Q...
You very nearly had it; Instead of this: ``` self.submenu2.setVisible(False) ``` You want this: ``` self.submenu2.menuAction().setVisible(False) ```
Converting between datetime, Timestamp and datetime64
13,703,720
99
2012-12-04T13:08:29Z
13,703,930
16
2012-12-04T13:22:10Z
[ "python", "datetime", "numpy", "pandas" ]
How do I convert a `numpy.datetime64` object to a `datetime.datetime` (or `Timestamp`)? In the following code, I create a datetime, timestamp and datetime64 objects. ``` import datetime import numpy as np import pandas as pd dt = datetime.datetime(2012, 5, 1) # A strange way to extract a Timestamp object, there's sur...
``` >>> dt64.tolist() datetime.datetime(2012, 5, 1, 0, 0) ``` For `DatetimeIndex`, the `tolist` returns a list of `datetime` objects. For a single `datetime64` object it returns a single `datetime` object.
Converting between datetime, Timestamp and datetime64
13,703,720
99
2012-12-04T13:08:29Z
13,704,307
52
2012-12-04T13:42:08Z
[ "python", "datetime", "numpy", "pandas" ]
How do I convert a `numpy.datetime64` object to a `datetime.datetime` (or `Timestamp`)? In the following code, I create a datetime, timestamp and datetime64 objects. ``` import datetime import numpy as np import pandas as pd dt = datetime.datetime(2012, 5, 1) # A strange way to extract a Timestamp object, there's sur...
To convert `numpy.datetime64` to datetime object that represents time in UTC on `numpy-1.8`: ``` >>> from datetime import datetime >>> import numpy as np >>> dt = datetime.utcnow() >>> dt datetime.datetime(2012, 12, 4, 19, 51, 25, 362455) >>> dt64 = np.datetime64(dt) >>> ts = (dt64 - np.datetime64('1970-01-01T00:00:00...
Converting between datetime, Timestamp and datetime64
13,703,720
99
2012-12-04T13:08:29Z
13,753,918
69
2012-12-06T22:40:22Z
[ "python", "datetime", "numpy", "pandas" ]
How do I convert a `numpy.datetime64` object to a `datetime.datetime` (or `Timestamp`)? In the following code, I create a datetime, timestamp and datetime64 objects. ``` import datetime import numpy as np import pandas as pd dt = datetime.datetime(2012, 5, 1) # A strange way to extract a Timestamp object, there's sur...
Welcome to hell. You can just pass a datetime64 object to `pandas.Timestamp`: ``` In [16]: Timestamp(numpy.datetime64('2012-05-01T01:00:00.000000')) Out[16]: <Timestamp: 2012-05-01 01:00:00> ``` I noticed that this doesn't work right though in NumPy 1.6.1: ``` numpy.datetime64('2012-05-01T01:00:00.000000+0100') ```...
Converting between datetime, Timestamp and datetime64
13,703,720
99
2012-12-04T13:08:29Z
21,916,253
73
2014-02-20T18:17:06Z
[ "python", "datetime", "numpy", "pandas" ]
How do I convert a `numpy.datetime64` object to a `datetime.datetime` (or `Timestamp`)? In the following code, I create a datetime, timestamp and datetime64 objects. ``` import datetime import numpy as np import pandas as pd dt = datetime.datetime(2012, 5, 1) # A strange way to extract a Timestamp object, there's sur...
You can just use the pd.Timestamp constructor. The following diagram may be useful for this and related questions. ![Conversions between time representations](http://i.stack.imgur.com/uiXQd.png)
tastypie - where to restrict fields that may be updated by PATCH?
13,704,344
3
2012-12-04T13:44:18Z
17,111,959
12
2013-06-14T15:24:18Z
[ "python", "django", "patch", "tastypie" ]
I have a working GET / tastypie (read-only) solution. I've allowed PUT/PATCH requests and been successful in PATCHING a record. However I want to limit PATCH capability to only certain fields, on appropriate modelresources, for (already) authenticated and authorised users. I still want users to be able to GET (see) a...
A bit late but maybe this will help somebody. My solution was to override `update_in_place` and check for the data passed. ``` from tastypie.resources import ModelResource from tastypie.exceptions import BadRequest class MyResource(ModelResource): class Meta: ... allowed_update_fields = ['field1...
zip lists in python
13,704,860
38
2012-12-04T14:13:00Z
13,704,903
73
2012-12-04T14:15:11Z
[ "python", "python-2.7" ]
I am a python newbie and I am trying to learn how to "zip" lists. To this end, I have a program, where at a particular point, I do the following: ``` x1, x2, x3 = stuff.calculations(withdataa) ``` This gives me three lists, `x1`, `x2`, and `x3`, each of, say, size 20. Now, I do: ``` zipall = zip(x1, x2, x3) ``` Ho...
When you `zip()` together three lists containing 20 elements each, the result has twenty elements. Each element is a three-tuple. See for yourself: ``` In [1]: a = b = c = range(20) In [2]: zip(a, b, c) Out[2]: [(0, 0, 0), (1, 1, 1), ... (17, 17, 17), (18, 18, 18), (19, 19, 19)] ``` To find out how many eleme...
zip lists in python
13,704,860
38
2012-12-04T14:13:00Z
13,704,933
13
2012-12-04T14:17:12Z
[ "python", "python-2.7" ]
I am a python newbie and I am trying to learn how to "zip" lists. To this end, I have a program, where at a particular point, I do the following: ``` x1, x2, x3 = stuff.calculations(withdataa) ``` This gives me three lists, `x1`, `x2`, and `x3`, each of, say, size 20. Now, I do: ``` zipall = zip(x1, x2, x3) ``` Ho...
`zip` creates a new list, filled with tuples containing elements from the iterable arguments: ``` >>> zip ([1,2],[3,4]) [(1,3), (2,4)] ``` I expect what you try to so is create a tuple where each element is a list.
zip lists in python
13,704,860
38
2012-12-04T14:13:00Z
13,704,950
21
2012-12-04T14:18:25Z
[ "python", "python-2.7" ]
I am a python newbie and I am trying to learn how to "zip" lists. To this end, I have a program, where at a particular point, I do the following: ``` x1, x2, x3 = stuff.calculations(withdataa) ``` This gives me three lists, `x1`, `x2`, and `x3`, each of, say, size 20. Now, I do: ``` zipall = zip(x1, x2, x3) ``` Ho...
`zip` takes a bunch of lists likes ``` a: a1 a2 a3 a4 a5 a6 a7... b: b1 b2 b3 b4 b5 b6 b7... c: c1 c2 c3 c4 c5 c6 c7... ``` and "zips" them into one list whose entries are 3-tuples `(ai, bi, ci)`. Imagine drawing a zipper horizontally from left to right.
how to get static files in Flask without url_for('static', file_name='xxx')
13,706,382
9
2012-12-04T15:34:42Z
13,706,984
16
2012-12-04T16:05:28Z
[ "python", "flask", "jinja2", "static-files" ]
I don't want use url\_for('static', file\_name='foo.jpg') to get static file in template. how to get static file in this way: ``` <img src="/pic/foo.jpg" /> ``` thanks
You can set up your own route to serve static files. Add this method and update the static path directory in the `send_from_directory` method, then your img tag should work. ``` @app.route('/pic/<path:filename>') def send_pic(filename): return send_from_directory('/path/to/static/files', filename) ``` For a produ...
Python: value that occurs the most in a list
13,707,457
6
2012-12-04T16:32:39Z
13,707,531
22
2012-12-04T16:35:49Z
[ "python", "list" ]
I have a two list as follows ``` x = ['a','a','b','c','b','a'] ``` and ``` x = ['a','a','b','c','c','d'] ``` Thanks to Rohit I have found that this works for the second x value. ``` from collections import Counter count = counter(x) count.most_common() ``` I added ``` mc = [i for i,z in count.most_common() if z ...
You can use `Counter` module from `collections`, if you want to find the occurrences of each element in the list: - ``` >>> x = ['a','a','b','c','c','d'] >>> from collections import Counter >>> count = Counter(x) >>> count Counter({'a': 2, 'c': 2, 'b': 1, 'd': 1}) >>> count.most_common() [('a', 2), ('c', 2), ('b', 1)...
Httplib2 ssl error
13,707,606
7
2012-12-04T16:39:17Z
13,707,774
16
2012-12-04T16:48:27Z
[ "python", "foursquare", "httplib2" ]
Today I faced one interesting issue. I'm using the foursquare recommended python library httplib2 raise ``` SSLHandshakeError(SSLError(1, '_ssl.c:504: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed'),) ``` while trying to request an oauth token ``` response, body = h.request(url, ...
If you know that the site you're trying to get is a "good guy", you can try creating your "opener" like this: ``` import httplib2 if __name__ == "__main__": h = httplib2.Http(".cache", disable_ssl_certificate_validation=True) resp, content = h.request("https://site/whose/certificate/is/bad/", "GET") ``` (the ...
Httplib2 ssl error
13,707,606
7
2012-12-04T16:39:17Z
22,783,425
9
2014-04-01T10:39:10Z
[ "python", "foursquare", "httplib2" ]
Today I faced one interesting issue. I'm using the foursquare recommended python library httplib2 raise ``` SSLHandshakeError(SSLError(1, '_ssl.c:504: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed'),) ``` while trying to request an oauth token ``` response, body = h.request(url, ...
Recent versions of httplib2 is defaulting to its own certificate store. ``` # Default CA certificates file bundled with httplib2. CA_CERTS = os.path.join( os.path.dirname(os.path.abspath(__file__ )), "cacerts.txt") ``` In case if you're using ubuntu/debian, you can explicitly pass the path to system certificate ...
python-dev installation error: ImportError: No module named apt_pkg
13,708,180
8
2012-12-04T17:07:20Z
13,717,755
11
2012-12-05T06:46:16Z
[ "python", "linux", "installation", "debian" ]
I got stuck in a problem. I am Debian user, and I want to install python-dev, but when I run the code in the shell as a root: ``` # aptitude install python-dev ``` I get the following error: ``` Traceback (most recent call last): File "/usr/bin/apt-listchanges", line 28, in <module> import apt_pkg Impor...
Make sure you have a working python-apt package. You could try and remove and install that package again to fix the problem with apt\_pkg.so not being located. ``` apt-get install python-apt ```
Recursion function in Python
13,708,670
5
2012-12-04T17:36:35Z
13,708,714
9
2012-12-04T17:38:56Z
[ "python", "recursion" ]
Consider this basic recursion in Python: ``` def fibonacci(number): if number == 0: return 0 elif number == 1: return 1 else: return fibonacci(number-1) + fibonacci(number-2) ``` Which makes sense according to the (n-1) + (n-2) function of the Fibonacci series. How does Python execute rec...
In the expression `fibonacci(number-1) + fibonacci(number-2)` the first function call will have to complete before the second function call is invoked. So, the whole recursion stack for the first call has to be complete before the second call is started.
Recursion function in Python
13,708,670
5
2012-12-04T17:36:35Z
13,708,736
10
2012-12-04T17:40:16Z
[ "python", "recursion" ]
Consider this basic recursion in Python: ``` def fibonacci(number): if number == 0: return 0 elif number == 1: return 1 else: return fibonacci(number-1) + fibonacci(number-2) ``` Which makes sense according to the (n-1) + (n-2) function of the Fibonacci series. How does Python execute rec...
## Short Answer Each time Python "sees" `fibonacci()` it makes another function call and doesn't progress further until it has finished that function call. ## Example So let's say it's evaluating `fibonacci(4)`. Once it gets to the line `return fibonacci(number-1) + fibonacci(number-2)`, it "sees" the call `fibonac...
cx_oracle and python 2.7
13,708,998
5
2012-12-04T17:57:07Z
13,801,474
10
2012-12-10T13:00:30Z
[ "python", "python-2.7", "cx-oracle" ]
Im using python 2.7 and cx\_oracle ( Windows x86 Installer (Oracle 10g, Python 2.7) ) and 'm having a bad time to set this simple example bellow to work: ``` import cx_Oracle connection = cx_Oracle.connect('user/pass@someserver:port') cursor = connection.cursor() cursor.execute('select sysdate from dual') for row in ...
I was able to solve this problem with the following steps: 1. Download **instantclient-basic-win32-10.2.0.5** from [Oracle Website](http://www.oracle.com/technetwork/topics/winsoft-085727.html) 2. unzipped the into my c:\ with the name oraclient 3. Created the directory structure C:\oraclient\network\admin to add the ...
Already Registered at /appname/: The model User is already registered
13,709,177
13
2012-12-04T18:08:00Z
13,709,239
28
2012-12-04T18:12:37Z
[ "python", "django", "django-registration" ]
I'm trying to connect the django.contrib.auth User with my own UserProfile, and I'm getting an 'AlreadyRegistered' error when I go on the site. Here's the traceback: ``` Environment: Request Method: GET Request URL: myurl.com/django/appname/ Django Version: 1.4.2 Python Version: 2.6.8 Installed Applications: ('dja...
When you define a custom user admin in your app's `admin.py`, you must first unregister the default `User` model admin before registering your own. ``` admin.site.unregister(User) admin.site.register(User, MyUserAdmin) ```
How to update values using pymongo?
13,710,770
18
2012-12-04T19:50:32Z
13,711,077
43
2012-12-04T20:11:47Z
[ "python", "mongodb", "pymongo" ]
I've a mongodb collection in this form: ``` {id=ObjectId(....),key={dictionary of values}} where dictionary of values is {'a':'1','b':'2'.....} ``` Let dictionary of values be `'d'`. I need to update the values of the key in the `'d'`. i.e I want to change `'a':'1'` to `'a':'2'` How can do I this in pymongo? Code go...
You can use the $set syntax if you want to set the value of a document to an arbitrary value. This will either update the value if the attribute already exists on the document or create it if it doesn't. If you need to set a single value in a dictionary like you describe, you can use the dot notation to access child va...
recursive function to add digits in python fails when leading digit is zero
13,710,812
2
2012-12-04T19:53:48Z
13,710,840
12
2012-12-04T19:55:32Z
[ "python", "recursion" ]
I'm trying to create a recursive function that adds all the digits in a number. Here's what I've come up with: ``` def sumOfDigits(num): num=str(num) if len(num)==0: return 0 elif len(num)==1: return int(num) elif len(num)>1: return int(num[0]) + int(num[-1]) + int(sumOfDigits(n...
**In Python 2, integer literals that start with zero are [octal](http://docs.python.org/2/reference/lexical_analysis.html#integer-and-long-integer-literals)**. To take your examples: ``` In [46]: 012 Out[46]: 10 In [47]: 0123 Out[47]: 83 In [48]: 0010 Out[48]: 8 ``` Since your function works in base ten, it is doi...
Extract Coordinates from KML BatchGeo File with Python
13,712,132
4
2012-12-04T21:19:09Z
13,716,220
9
2012-12-05T04:19:41Z
[ "python", "geocoding", "kml", "lxml" ]
I've uploaded some addresses to BatchGeo and downloaded the resulting KML file from which I want to extract the coordinates. I managed to prettify the jumbled text file online [here](http://jsbeautifier.org/), but I don't know how to parse it to extract the co-ordinates. ``` <?xml version="1.0" ?> <kml xmlns="http://e...
``` from pykml import parser root = parser.fromstring(open('BatchGeo.kml', 'r').read()) print root.Document.Placemark.Point.coordinates ``` see [the pykml docs](http://packages.python.org/pykml/tutorial.html#parsing-existing-kml-documents) hope that helps!
Simultaneously replacing all values of a dictionary to zero python
13,712,229
5
2012-12-04T21:26:58Z
13,712,257
12
2012-12-04T21:28:58Z
[ "python", "dictionary" ]
I have a very large dictionary, maybe about `10,000 keys/values` and I want to simultaneously change all values to `0`. I am aware that I can loop through and set all the values to `0` but it take forever. Is there anyway that I can *simultaneously* set **all** values to `0`? Looping method, very slow: ``` #example d...
You want `dict.fromkeys()`: ``` a = dict.fromkeys(a, 0) ```
Interpret (and use) the output from Fabric local command
13,713,085
5
2012-12-04T22:28:09Z
13,713,133
9
2012-12-04T22:32:37Z
[ "python", "fabric" ]
I would like to use a Fabric command to set up a local development environment, and as part of that I want to be able to set up a git remote. This works fine: ``` from fabric.api import local def set_remote(): """ Set up git remote for pushing to dev.""" local('git remote add myremote git@myremote.com:myrepo....
You can use the [`settings`](http://docs.fabfile.org/en/1.5/api/core/context_managers.html#fabric.context_managers.settings) context manager to `warn_only`: ``` from fabric.context_managers import settings with settings(warn_only=True): # some command we are all right with having fail ``` Alternately, you can se...
Deploying Flask app to Heroku
13,714,205
9
2012-12-05T00:07:54Z
13,714,363
14
2012-12-05T00:25:11Z
[ "python", "heroku", "flask" ]
I'm trying to develop my first "large" app with Flask on Heroku and I'm attempting to combine the basic tutorial here: <https://devcenter.heroku.com/articles/python> with the instructions here: <http://flask.pocoo.org/docs/patterns/packages/#larger-applications>. It works locally with "foreman start" but when I push to...
I haven't used Heroku, but to me, it looks like they have a reserved port for Flask, specifically 33507. It looks like it will try to use an environment variable, which I am not sure how to set in Heroku. The good news is you can tell Flask which port to use. try this: ``` app.run(debug=True, port=33507) ``` and it ...
Specifying and saving a figure with exact size in pixels
13,714,454
33
2012-12-05T00:34:49Z
13,714,720
42
2012-12-05T01:04:51Z
[ "python", "matplotlib", "scipy" ]
Say I have an image of size 3841 x 7195 pixels. I would like to save the contents of the figure to disk, resulting in an image of the **exact size** I specify in pixels. No axis, no titles. Just the image. I don't personally care about DPIs, as I only want to specify the size the image takes in the screen in disk **in...
Matplotlib doesn't work with pixels directly, but rather physical sizes and DPI. If you want to display a figure with a certain pixel size, you need to know the DPI of your monitor. For example [this link](http://www.infobyip.com/detectmonitordpi.php) will detect that for you. If you have an image of 3841x7195 pixels ...
Replace list of list with "condensed" list of list while maintaining order
13,714,755
21
2012-12-05T01:08:03Z
13,715,626
13
2012-12-05T03:04:34Z
[ "python", "algorithm", "python-2.x", "nested-lists", "itertools" ]
I have a list of list as in the code I attached. I want to link each sub list if there are any common values. I then want to replace the list of list with a condensed list of list. **Examples:** if I have a list `[[1,2,3],[3,4]]` I want `[1,2,3,4]`. If I have `[[4,3],[1,2,3]]` I want `[4,3,1,2]`. If I have `[[1,2,3],[a...
Here's a brute-force approach (it might be easier to understand): ``` from itertools import chain def condense(*lists): # remember original positions positions = {} for pos, item in enumerate(chain(*lists)): if item not in positions: positions[item] = pos # condense disregarding o...
How to set QDockWidget initial (default) size in the app with no central widget (PyQt4)?
13,715,365
5
2012-12-05T02:27:00Z
13,715,893
7
2012-12-05T03:35:47Z
[ "python", "qt", "pyqt", "pyqt4", "qdockwidget" ]
I have an app with a lot of [QDockWidgets](http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qdockwidget.html) and without central widget. I want to set some of those [QDockWidgets](http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qdockwidget.html) initial size (size at application's start), but I do...
The dockwidgets will be incorporated into the layout of the main window, so any attempt to resize them will be ignored. The standard workaround for this is to create a subclass of the content widget and reimplement its `sizeHint`: ``` class TreeWidget(QtGui.QTreeWidget): def sizeHint(self): return QtCore....
psycopg2 not actually inserting data
13,715,743
17
2012-12-05T03:16:59Z
13,715,838
37
2012-12-05T03:28:47Z
[ "python", "postgresql", "psycopg2" ]
I need to insert JSON data from tornado to postgres, so here's test like this: ``` from psycopg2 import connect conn = connect("user='pguser' host='localhost' dbname='pgdb' password='pgpass'") cursor = conn.cursor() data = '[{"id":"sdf","name":"wqe","author":"vb"}]' for row in eval(data): print row cursor.execu...
You didn't commit the transaction. Psycopg2 opens a transaction automatically, and you must tell it to commit in order to make the data visible to other sessions. See [the psycopg2 FAQ](http://initd.org/psycopg/docs/faq.html) and the [`connection.commit()` method](http://initd.org/psycopg/docs/connection.html#connect...
Python - Understanding the send function of a generator
13,716,591
10
2012-12-05T04:58:11Z
13,716,644
10
2012-12-05T05:04:26Z
[ "python", "generator", "yield", "yield-keyword" ]
I'm studying in Python `yield` and find that `yield` is not only the way in which generators output a return value but also a way to put values into a generator. For example the following code ``` def f(): print (yield), print 0, print (yield), print 1 g = f() g.send(None) g.send('x') g.send('y') ``` ...
From [the documentation](http://docs.python.org/2/reference/expressions.html#generator.send): > When `send()` is called to start the generator, it must be called with `None` as the argument, because there is no `yield` expression that could receive the value. As for the exception, you can't really avoid it. The gener...
Find the indices of elements greater than x
13,717,463
10
2012-12-05T06:21:22Z
13,717,480
12
2012-12-05T06:23:37Z
[ "python", "indexing" ]
Given the following vector, ``` a = [1, 2, 3, 4, 5, 6, 7, 8, 9] ``` I need to identify the indices of "a" whose elements are >= than 4, like this: ``` idx = [3, 4, 5, 6, 7, 8] ``` The info in "idx" will be used to delete the elements from another list X (X has the same number of elements that "a"): ``` del X[idx] ...
``` >>> [i for i,v in enumerate(a) if v > 4] [4, 5, 6, 7, 8] ``` `enumerate` returns the index and value of each item in an array. So if the value `v` is greater than `4`, include the index `i` in the new array. Or you can just modify your list in place and exclude all values above `4`. ``` >>> a[:] = [x for x in a ...
Weird behaviour initializing a numpy array of string data
13,717,554
8
2012-12-05T06:29:53Z
13,717,700
18
2012-12-05T06:40:21Z
[ "python", "numpy" ]
I am having some seemingly trivial trouble with numpy when the array contains string data. I have the following code: ``` my_array = numpy.empty([1, 2], dtype = str) my_array[0, 0] = "Cat" my_array[0, 1] = "Apple" ``` Now, when I print it with `print my_array[0, :]`, the response I get is `['C', 'A']`, which is clear...
Numpy requires string arrays to have a fixed maximum length. When you create an empty array with `dtype=str`, it sets this maximum length to 1 by default. You can see if you do `my_array.dtype`; it will show "|S1", meaning "one-character string". Subsequent assignments into the array are truncated to fit this structure...
Merging 3 dict()'s in python
13,718,558
3
2012-12-05T07:51:54Z
13,718,790
9
2012-12-05T08:10:21Z
[ "python", "dictionary" ]
Is there a method of logically merging multiple dictionaries if they have common strings between them? Even if these common strings match between values of one dict() to a key of another? I see a lot of similar questions on SO but none that seem to address my specific issue of relating multiple keys in "lower level fi...
This is a problem of connected component subgraphs and can be best determined if you want to use [networkx](http://networkx.lanl.gov/). Here is a solution to your problem ``` >>> import networkx as nx >>> level1dict = { '1':[1,3], '2':2 } >>> level2dict = { '1':4, '3':[5,9], '2':10 } >>> level3dict = { '1':[6,8,11], '...
Can i divide the models in different files in django
13,718,656
8
2012-12-05T07:59:25Z
13,718,936
9
2012-12-05T08:21:35Z
[ "python", "django", "django-models" ]
Currently all my models are in models.py. Ist becomming very messy. Can i have the separate file like `base_models.py` so that i put my main models there which i don't want to touch Also same case for views and put in separate folder rather than develop a new app
Yes, it's doable. It's not particularly pretty though: make models a module, so your directory structure looks like this: ``` - models |- __init__.py |- some_model.py |- some_other_model.py |- ... ``` now, the magic lies in `__init__.py` and some little extras in the models. `__init__.py`: ``` from some_model impor...
Run python script as daemon at boot time (Ubuntu)
13,718,821
8
2012-12-05T08:12:20Z
13,720,327
10
2012-12-05T09:49:40Z
[ "python", "upstart", "werkzeug" ]
I've created small web server using werkzeug and I'm able to run it in usual python way with `python my_server.py`. Pages load, everything works fine. Now I want to start it when my pc boots. What's the easiest way to do that? I've been struggling with upstart but it doesn't seem to "live in a background" cuz after I e...
One simple way to do is using crontab: ``` $ crontab -e ``` A crontab file will appear for editing, write the line at the end: ``` @reboot python myserver.py ``` and quit. Now, after each reboot, the cron daemon will run your myserver python script.
Run python script as daemon at boot time (Ubuntu)
13,718,821
8
2012-12-05T08:12:20Z
13,720,944
16
2012-12-05T10:21:46Z
[ "python", "upstart", "werkzeug" ]
I've created small web server using werkzeug and I'm able to run it in usual python way with `python my_server.py`. Pages load, everything works fine. Now I want to start it when my pc boots. What's the easiest way to do that? I've been struggling with upstart but it doesn't seem to "live in a background" cuz after I e...
In addition to gg.kaspersky method, you could also turn your script into a "service", so that you can start or stop it using: ``` $ sudo service myserver start * Starting system myserver.py Daemon [ OK ] $ sudo service myserver status * /path/to/myserver.py is running $ sudo service myserver...
change database (postgresql) in python using psycopg2 dynamically
13,719,674
4
2012-12-05T09:13:35Z
13,722,890
8
2012-12-05T12:06:03Z
[ "python", "postgresql", "psycopg2" ]
Can anybody tell me how can I change database dynamically which I have created just now.. using the following code... I think during the execution of this code I will be in default postgres database (which is template database) and after new database creation I want to change my database at runtime to do further proces...
You can simply connect again with `database=dbname` argument. Note usage of `SELECT current_database()` to show on which database we work, and `SELECT * FROM pg_database` to show available databases: ``` from psycopg2 import connect from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT def show_query(title, qry)...
what does "__require__" mean in python?
13,720,065
9
2012-12-05T09:36:23Z
13,720,352
9
2012-12-05T09:50:58Z
[ "python", "setuptools" ]
I am newbie in python. Could anybody answer what does `__require__` means in the following code? Why would they put `__requires__ = 'flower==0.4.0'` in the beginning of the file? ``` #!/srv/virtualenvs/zeusenv/bin/python __requires__ = 'flower==0.4.0' import sys from pkg_resources import load_entry_point sys.exit( ...
The `__requires__` line is part of a generated console script. It has no meaning to Python itself, only the `setuptools` library itself uses this information. Console scripts are python scripts defined in a python package metadata, and `setuptools` installs wrapper script files to let you run them as command line scri...
Reportlab. Floating Text with two Columns
13,720,357
5
2012-12-05T09:51:19Z
13,750,159
8
2012-12-06T18:31:18Z
[ "python", "reportlab", "pisa", "xhtml2pdf" ]
First of all, I'm new to python, reportlab, xhtml2pdf. I've already done my first pdf files with reportlab, but I ran into the following problem. I need a large text in two columns. First I create my canvas, create my story, append my large text as a paragraph to the story, create my Frame and finally add the story t...
This can be done using `BaseDocTemplate` and `Frame` as you can read [here](http://code.activestate.com/recipes/123612-basedoctemplate-with-2-pagetemplate/). I modified that receipe to only use a two frame layout: ``` from reportlab.platypus import BaseDocTemplate, Frame, Paragraph, PageBreak, PageTemplate from report...
Python module installation error: command 'gcc' failed with exit status 1
13,720,578
4
2012-12-05T10:03:18Z
13,720,656
16
2012-12-05T10:06:56Z
[ "python", "linux", "unix", "installation", "debian" ]
I am on Debian Squeeze, and I want to install the module *[igraph](http://igraph.sourceforge.net/)*. So, I am going through all the [steps](http://igraph.wikidot.com/installing-python-igraph-on-linux), but when i try doing ``` python setup.py build ``` I get error that says: ``` error: command 'gcc' failed with exit...
The Python header files are in the `python-dev` package, which includes: > Header files, a static library and development tools for building Python modules, extending the Python interpreter or embedding Python in applications. Try: ``` apt-get install python-dev ``` That should do the trick. You can also download i...
How to get the scrapy failure URLs?
13,724,730
28
2012-12-05T13:49:55Z
13,799,984
39
2012-12-10T11:22:28Z
[ "python", "web-scraping", "report", "scrapy" ]
I'm a newbie of scrapy and it's amazing crawler framework i have known! In my project, I sent more than 90, 000 requests, but there are some of them failed. I set the log level to be INFO, and i just can see some statistics but no details. ``` 2012-12-05 21:03:04+0800 [pd_spider] INFO: Dumping spider stats: {'downloa...
Yes, this is possible. I added a failed\_urls list to my spider class and appended urls to it if the response's status was 404 (this will need to be extended to cover other error statuses). Then I added a handle that joins the list into a single string and add it to the stats when the spider is closed. Based on your...
How to get the scrapy failure URLs?
13,724,730
28
2012-12-05T13:49:55Z
14,593,509
12
2013-01-29T22:49:49Z
[ "python", "web-scraping", "report", "scrapy" ]
I'm a newbie of scrapy and it's amazing crawler framework i have known! In my project, I sent more than 90, 000 requests, but there are some of them failed. I set the log level to be INFO, and i just can see some statistics but no details. ``` 2012-12-05 21:03:04+0800 [pd_spider] INFO: Dumping spider stats: {'downloa...
Here's another example how to handle and collect 404 errors (checking github help pages): ``` from scrapy.selector import HtmlXPathSelector from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.item import Item, Field class GitHubLinkItem(It...
How to get the scrapy failure URLs?
13,724,730
28
2012-12-05T13:49:55Z
18,453,647
8
2013-08-26T21:52:47Z
[ "python", "web-scraping", "report", "scrapy" ]
I'm a newbie of scrapy and it's amazing crawler framework i have known! In my project, I sent more than 90, 000 requests, but there are some of them failed. I set the log level to be INFO, and i just can see some statistics but no details. ``` 2012-12-05 21:03:04+0800 [pd_spider] INFO: Dumping spider stats: {'downloa...
The answers from @Talvalin and @alecxe helped me a great deal, but they do not seem to capture downloader events that do not generate a response object (for instance, `twisted.internet.error.TimeoutError` and `twisted.web.http.PotentialDataLoss`). These errors show up in the stats dump at the end of the run, but withou...
Is "*_" an acceptable way to ignore arguments in python
13,726,155
6
2012-12-05T15:06:04Z
13,726,418
8
2012-12-05T15:19:02Z
[ "python" ]
If I have a function/method that is an implementation of a callback for some framework, and do not care for any further arguments, it seems to be syntactically correct, and to not have pylint/IDE complaints to use \*\_ to express no interest in any further arguments. The point I think is to express intent to both the t...
It's just a variable like any other, but by convention it means that you don't intend to use that value, just read it and ignore it. `[OrderedSet() for _ in xrange(n)]` builds a list of n empty ordered sets. `_` is the index, but is unused; `_` is commonly used as required, but unused, variable name (not only in pyth...
Bessel functions in Python that work with large exponents
13,726,464
7
2012-12-05T15:20:39Z
13,728,374
7
2012-12-05T16:56:12Z
[ "python", "scipy", "bessel-functions" ]
I've got some code that uses the modified Bessel functions of both 1st and 2nd order (iv and kv). Annoyingly they seem to have limits, those are iv(0,713) and kv(0,697), add one to each and you get infinity and 0 respectively. This is a problem for me because I need to use values higher than this, often up to 2000 or m...
The `iv` and `kv` functions in Scipy are more or less as good as you can get if using double precision machine floating point. As noted in the comments above, you are working in the range where the results overflow from the floating point range. You can use the `mpmath` library, which does adjustable precision (softwa...