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
Python urlparse -- extract domain name without subdomain
14,406,300
32
2013-01-18T19:33:44Z
14,406,372
33
2013-01-18T19:38:35Z
[ "python", "parsing", "url", "urlparse" ]
Need a way to extract a domain name without the subdomain from a url using Python urlparse. For example, I would like to extract `"google.com"` from a full url like `"http://www.google.com"`. The closest I can seem to come with `urlparse` is the `netloc` attribute, but that includes the subdomain, which in this examp...
You probably want to check out [tldextract](http://pypi.python.org/pypi/tldextract), a library designed to do this kind of thing. It uses the Public Suffix List to try and get a decent split based on known gTLDs, but do note that this is just a brute-force list, nothing special, so it can get out of date (although hop...
Python urlparse -- extract domain name without subdomain
14,406,300
32
2013-01-18T19:33:44Z
22,228,140
14
2014-03-06T14:59:52Z
[ "python", "parsing", "url", "urlparse" ]
Need a way to extract a domain name without the subdomain from a url using Python urlparse. For example, I would like to extract `"google.com"` from a full url like `"http://www.google.com"`. The closest I can seem to come with `urlparse` is the `netloc` attribute, but that includes the subdomain, which in this examp...
This is an update, based on the bounty request for an updated answer Start by using the [tld](https://pypi.python.org/pypi/tld) package. A description of the package: > Extracts the top level domain (TLD) from the URL given. List of TLD > names is taken from Mozilla > <http://mxr.mozilla.org/mozilla/source/netwerk/dn...
Python logging - check location of log files?
14,406,347
7
2013-01-18T19:36:45Z
14,406,382
8
2013-01-18T19:39:02Z
[ "python", "linux", "file", "logging" ]
What is the methodology for knowing where Python log statements are stored? i.e. if i do: ``` import logging log = logging.getLogger(__name__) log.info('Test') ``` Where could I find the logfile? Also, when I call: ``` logging.getLogger(__name__) ``` Is that somehow related to how the logger will behave/save? Tha...
The `logging` module uses handlers attached to loggers to decide how, where, or even if messages ultimately get stored or displayed. You can configure `logging` by default to write to a file as well. You should really read the [docs](http://docs.python.org/2/library/logging.html), but if you call `logging.basicConfig(f...
Modify values of a list while iterating over it in Python?
14,406,449
6
2013-01-18T19:43:14Z
14,406,583
14
2013-01-18T19:51:01Z
[ "python" ]
For example: ``` def update_condition(self, type, params): for condition in self.conditions: condition_loaded = json.loads(condition) if condition_loaded['type'] == type: condition_loaded['params'] = params condition = json.dumps(condition_loaded) ``` The above code does no...
You could use `enumerate`: ``` def update_condition(self, type, params): for i,condition in enumerate(self.conditions): condition_loaded = json.loads(condition) if condition_loaded['type'] == type: condition_loaded['params'] = params self.conditions[i] = json.dumps(condition...
Paritition array into N chunks with Numpy
14,406,567
9
2013-01-18T19:50:27Z
14,406,661
16
2013-01-18T19:56:09Z
[ "python", "numpy" ]
There is this [How do you split a list into evenly sized chunks in Python?](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python) for splitting an array into chunks. Is there anyway to do this more efficiently for giant arrays using Numpy?
Try [`numpy.array_split`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.array_split.html#numpy.array_split). From the documentation: ``` >>> x = np.arange(8.0) >>> np.array_split(x, 3) [array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7.])] ``` Identical to [`numpy.split`](http://docs.sci...
Paritition array into N chunks with Numpy
14,406,567
9
2013-01-18T19:50:27Z
14,406,732
9
2013-01-18T20:01:21Z
[ "python", "numpy" ]
There is this [How do you split a list into evenly sized chunks in Python?](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python) for splitting an array into chunks. Is there anyway to do this more efficiently for giant arrays using Numpy?
Just some examples on usage of [array\_split](http://docs.scipy.org/doc/numpy/reference/generated/numpy.array_split.html#numpy.array_split), [split, hsplit and vsplit](http://docs.scipy.org/doc/numpy-1.3.x/reference/generated/numpy.split.html): ``` n [9]: a = np.random.randint(0,10,[4,4]) In [10]: a Out[10]: array([...
substitute of function pointers in python
14,407,181
8
2013-01-18T20:35:31Z
14,407,213
13
2013-01-18T20:37:46Z
[ "python" ]
I have worked in low level C programming for years and I don't have enough exposure to Object oriented approaches. In C if I was developing some layered architecture then each layer has interfaces defined by function pointers. The advantage of that the whole layer can be replaced by just setting those function pointers...
Python supports functions as a first-class data type. So you can do something like: ``` def foo(x): print("foo: " + x) def bar(x): print("bar: " + x) f = foo f("one") f = bar f("ten") ``` prints ``` foo: one bar: ten ``` This is very similar to your experience with function pointers in C. Although Python ...
unsupported operand type(s) for *: 'numpy.ndarray' and 'numpy.float64'
14,408,122
6
2013-01-18T21:42:46Z
14,408,749
7
2013-01-18T22:32:16Z
[ "python", "numpy", "operand" ]
long time reader, first time writer. I searched around on google and stack overflow, but wasn't really able to find a general answer to this question. I am getting an "unsupported operand type(s) for \*: 'numpy.ndarray' and 'numpy.float64'" error in python 2.7.3 using numpy 1.6.2. The error comes from multiplying a ...
I suspect that the problem here is that NumPy cannot store Python `long` values in its arrays. As soon as you try to do this, it switches the data type of the array to `object`. Arithmetic operations on the array then become trickier because NumPy can no longer do the arithmetic itself. ``` >>> np.array(27**40) array(...
Installing SciPy on Ubuntu
14,408,123
18
2013-01-18T21:42:48Z
14,408,210
21
2013-01-18T21:48:56Z
[ "python", "ubuntu" ]
I have Python 2.7 running and trying to install scipy by using easy\_install which returns following errors: ``` Searching for scipy Reading http://pypi.python.org/simple/scipy/ Reading http://www.scipy.org Reading http://sourceforge.net/project/showfiles.php?group_id=27747&package_id=19531 Reading http://new.scipy.or...
Ubuntu puts library files in a rather exotic directory. `/usr/lib/x86_64-linux-gnu/` or something, depending on your architecture. You need to add this directory to the site.cfg file or the BLAS environment variable. If easy install also needs the header files, you need to install the respective -dev packages. But, l...
Installing SciPy on Ubuntu
14,408,123
18
2013-01-18T21:42:48Z
21,073,913
53
2014-01-12T11:08:51Z
[ "python", "ubuntu" ]
I have Python 2.7 running and trying to install scipy by using easy\_install which returns following errors: ``` Searching for scipy Reading http://pypi.python.org/simple/scipy/ Reading http://www.scipy.org Reading http://sourceforge.net/project/showfiles.php?group_id=27747&package_id=19531 Reading http://new.scipy.or...
What worked for me: To actually install scipy from PIP, you need packages `libatlas-base-dev` (libraries etc. for ATLAS/BLAS) and `gfortran` (GNU Fortran compiler). Once these packages are installed, the scipy installer should finish as expected.
How to pass a variable to magic ´run´ function in IPython
14,409,167
39
2013-01-18T23:14:39Z
14,411,126
55
2013-01-19T04:35:24Z
[ "python", "ipython", "ipython-magic" ]
I want to do something like the following: ``` In[1]: name = 'long_name_to_type_every_now_and_then.py' In[2]: %run name ``` but this actually tries to run `'name.py'`, which is not what I want to do. Is there a general way to turn variables into strings? Something like the following: ``` In[3]: %run %name% ```
IPython expands variables with `$name`, bash-style. This is true for *all magics*, not just `%run`. So you would do: ``` In [1]: filename = "myscript.py" In [2]: %run $filename ['myscript.py'] ``` myscript.py contains: ``` import sys print(sys.argv) ``` Via Python's fancy string formatting, you can even put expre...
How to wrap and align comments in python code
14,409,320
2
2013-01-18T23:30:09Z
14,409,400
8
2013-01-18T23:38:30Z
[ "python", "emacs", "comments", "alignment", "wrap" ]
I'm trying to make my python code look better more readable. I read the [style guide](http://www.python.org/dev/peps/pep-0008/) but I don't know how to get something like this ``` x = foo(x); # compute the value of the next prime number # that is larger than x (foo is a really bad # choice...
I don't think you want this at all. Lattyware already explained the second case, but let's look at the first: ``` x = foo(x); # compute the value of the next prime number # that is larger than x (foo is a really bad # choice for this function's name) ``` Comments that are too long to fit ...
Setting up Python with WSGI on Apache for a directory
14,410,455
5
2013-01-19T02:08:42Z
14,410,686
10
2013-01-19T03:00:46Z
[ "python", "python-2.7", "mod-wsgi", "wsgi" ]
I am trying to setup Python with WSGI for a particular directory on Apache but I am getting the following error: ``` mod_wsgi (pid=3857): Target WSGI script '/var/www/test/test.py' does not contain WSGI application 'application'. ``` My test.py contains: ``` print 'Hello, World!' ``` And my wsgi.conf contains: ```...
You're using WSGI as though it was CGI (strangely without headers). What you need to do, for your immediate problem is adapt the following from <http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide> ``` def application(environ, start_response): status = '200 OK' output = 'Hello World!' response_...
Determine if a Python class is an Abstract Base Class or Concrete
14,410,860
11
2013-01-19T03:38:35Z
14,410,942
12
2013-01-19T03:54:17Z
[ "python", "abstract-class", "abc" ]
My Python application contains many abstract classes and implementations. For example: ``` import abc import datetime class MessageDisplay(object): __metaclass__ = abc.ABCMeta @abc.abstractproperty def display(self, message): pass class FriendlyMessageDisplay(MessageDisplay): def greet(self)...
``` import inspect print(inspect.isabstract(object)) # False print(inspect.isabstract(MessageDisplay)) # True print(inspect.isabstract(FriendlyMessageDisplay)) # True print(inspect.isabstract(FriendlyMessagePrinter)) # False ``` This checks that the internal flag `TPFLAGS_IS_ABSTRACT` is se...
Python - Fastest way to check if a string contains specific characters in any of the items in a list
14,411,633
7
2013-01-19T06:01:48Z
14,411,674
12
2013-01-19T06:08:58Z
[ "python", "performance", "list", "iteration" ]
What is the fastest way to check if a string contains some characters from any items of a list? Currently, I'm using this method: ``` lestring = "Text123" lelist = ["Text", "foo", "bar"] for x in lelist: if lestring.count(x): print 'Yep. "%s" contains characters from "%s" item.' % (lestring, x) ``` Is ...
You can try list comprehension with membership check ``` >>> lestring = "Text123" >>> lelist = ["Text", "foo", "bar"] >>> [e for e in lelist if e in lestring] ['Text'] ``` Compared to your implementation, though LC has an implicit loop but its faster as there is no explicit function call as in your case with `count` ...
get mimetype of file python
14,412,211
7
2013-01-19T07:38:20Z
14,412,233
13
2013-01-19T07:41:22Z
[ "python" ]
I want determine mimetype of an xml file , but I am getting error about some instance as first argument. I am new to python please help. Below is the code I am using and the error it throws. ``` from mimetypes import MimeTypes import urllib FILENAME = 'Upload.xml' url = urllib.pathname2url(FILENAME) type = MimeTypes....
The error says that you have to initialize the `MimeTypes` class: ``` >>> from mimetypes import MimeTypes >>> import urllib >>> >>> mime = MimeTypes() >>> url = urllib.pathname2url('Upload.xml') >>> mime_type = mime.guess_type(url) >>> >>> print mime_type ('application/xml', None) ``` Although you could skip this ...
Using sass with Flask and jinja2
14,412,677
27
2013-01-19T08:50:43Z
14,413,794
37
2013-01-19T11:20:36Z
[ "python", "flask", "sass", "jinja2" ]
I would like to include a sass compiler in my Flask application. Is there a generally accepted way of doing this?
[Flask-Assets](http://elsdoerfer.name/docs/flask-assets/) extension (which uses [webassets](http://elsdoerfer.name/docs/webassets/) library) can be used for that. Here's how to configure it to use [pyScss](http://pypi.python.org/pypi/pyScss) compiler (implemented in Python) for SCSS: ``` from flask import Flask, rende...
ImportError: cannot import name log
14,413,896
5
2013-01-19T11:34:20Z
14,414,520
12
2013-01-19T12:46:48Z
[ "python", "osx-lion" ]
Why is this happening? `python --version` **= 2.7.1** ``` import urllib def main(): urllib.urlretrieve('http://media2.apnonline.com.au/img/media/images/2011/02/28/apple-logo_fct825x508x16_t460.jpg', 'image.jpg') if __name__ == '__main__': main() ``` **Trace:** ``` Traceback (most recent call last): File...
Is it possible that you have a file named `math.py` in the same directory as the program you are running? If so python tries to import it before the math module. ***Solution:*** Just rename it to something else. ***Tip:*** In the future try to name your modules in a non-conflicting way.
Scrapy: why does my response object not have a body_as_unicode method?
14,413,900
3
2013-01-19T11:35:30Z
14,416,650
8
2013-01-19T17:03:38Z
[ "python", "scrapy" ]
I wrote a spider, that worked brilliantly the first time. The second time I tried to run it, it didn't venture beyond the `start_urls`. I tried to `fetch` the url in `scrapy shell` and create a `HtmlXPathSelector` object from the returned response. That is when I got the error So the steps were: ` ``` [scrapy shell] ...
`body_as_unicode` is a method of [TextResponse](http://doc.scrapy.org/en/latest/topics/request-response.html#scrapy.http.TextResponse). TextResponse, or one of its subclasses such as HtmlResponse, will be created by scrapy if the http response contains textual content. ``` In [1]: fetch('http://scrapy.org') ... In [2]...
What exactly is contained within a obj.__closure__?
14,413,946
12
2013-01-19T11:41:20Z
14,414,638
18
2013-01-19T12:59:54Z
[ "python", "closures", "python-internals" ]
Beazley pg 100 mentions: ``` >>>python.__closure__ (<cell at 0x67f50: str object at 0x69230>,) >>>python.__closure__[0].cell_contents ``` my understanding is that `__closure__` is a list but what's all this cell stuff and str object?? That looks like a 1-ary tuple?
Closure cells refer to values needed by the function but are taken from the surrounding scope. When Python compiles a nested function, it notes any variables that it references but are only defined in a parent function (not globals) in the code objects for both the nested function and the parent scope. These are the `...
Why does next raise a 'StopIteration', but 'for' do a normal return?
14,413,969
21
2013-01-19T11:44:06Z
14,413,978
33
2013-01-19T11:46:14Z
[ "python", "iterator", "generator", "stopiteration" ]
In this piece of code, why does using 'for' result in no 'StopIteration' or is the 'for' loop trapping all exceptions and then silently exiting? In which case, why do we have the extraneous 'return'?? Or is the `raise StopIteration` caused by: `return None`? ``` #!/usr/bin/python3.1 def countdown(n): print("counti...
The `for` loop listens for `StopIteration` explicitly. The purpose of the `for` statement is to loop over the sequence provided by an iterator and the exception is used to signal that the iterator is now done; `for` doesn't catch other exceptions raised by the object being iterated over, just that one. That's because...
Why 0 ** 0 equals 1 in python
14,414,430
20
2013-01-19T12:37:07Z
14,414,488
29
2013-01-19T12:43:54Z
[ "python", "math" ]
Why does `0 ** 0` equal `1` in Python? Shouldn't it throw an exception, like `0 / 0` does?
Wikipedia has interesting coverage of the [history and the differing points of view on](http://en.wikipedia.org/wiki/Exponentiation#Zero_to_the_power_of_zero) the value of `0 ** 0`: > The debate has been going on at least since the early 19th century. At that time, most mathematicians agreed that `0 ** 0 = 1`, until i...
Why 0 ** 0 equals 1 in python
14,414,430
20
2013-01-19T12:37:07Z
14,414,635
8
2013-01-19T12:59:20Z
[ "python", "math" ]
Why does `0 ** 0` equal `1` in Python? Shouldn't it throw an exception, like `0 / 0` does?
consider `x^x`: Using limits we can easily get to our solution and rearranging `x^x` we get : ``` x^x= exp(log(x^x)) ``` Now , we have from: ``` lim x->0 exp(log(x^x))= exp(lim x->0 xlog(x)) = exp(lim x->0 log(x)/(x^-1)) ``` Applying `L'Hôpital` rule , we get : ``` exp(lim x^-1/(-x^-2)) = exp(lim x->0 -x) = exp(...
Python: TypeError: argument of type 'builtin_function_or_method' is not iterable
14,414,720
5
2013-01-19T13:09:56Z
14,414,788
17
2013-01-19T13:18:47Z
[ "python", "python-3.x" ]
I have the following code: ``` def search(): os.chdir("C:/Users/Luke/Desktop/MyFiles") files = os.listdir(".") os.mkdir("C:/Users/Luke/Desktop/FilesWithString") string = input("Please enter the website your are looking for (in lower case):") for x in files: inputFile = open(x, "r") ...
Change the line ``` content = inputFile.read().lower ``` to ``` content = inputFile.read().lower() ``` Your original line assigns the built-in function lower to your variable content instead of calling the function `str.lower` and assigning the return value which is definitely not iterable.
Common folder/file structure in Flask app
14,415,500
27
2013-01-19T14:46:27Z
14,421,367
18
2013-01-20T03:16:42Z
[ "python", "flask" ]
I have just created a flask application and so far I have a router for my "Hello world!" template. I would like to add a little (a lot) more functionality, but I wonder how I should structure the app directory. What's the most common way of structuring a Flask app? For instance, should I create a `routes.py` for all ...
You should check out the Larger Applications page in the Patterns section of the Flask docs: <http://flask.pocoo.org/docs/patterns/packages/>. It seems to be the model that most people follow when their application calls for a package instead of a module. I believe `views.py` is what you are calling `routes.py`. After...
Numpy - array vs asarray
14,415,741
67
2013-01-19T15:18:46Z
14,415,801
68
2013-01-19T15:25:04Z
[ "python", "arrays", "numpy" ]
What is the difference between Numpy's [`array()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html#numpy.array) and [`asarray()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html#numpy.asarray) functions? When should you use one rather than the other? They seem to generate ide...
The [definition of `asarray`](https://github.com/numpy/numpy/blob/bcbed877f42ed6e9b01b2125134db4b6395f1d9d/numpy/core/numeric.py#L413-481) is: ``` def asarray(a, dtype=None, order=None): return array(a, dtype, copy=False, order=order) ``` So it is like `array`, except it has fewer options, and `copy = False`. `ar...
Numpy - array vs asarray
14,415,741
67
2013-01-19T15:18:46Z
14,415,806
10
2013-01-19T15:25:33Z
[ "python", "arrays", "numpy" ]
What is the difference between Numpy's [`array()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html#numpy.array) and [`asarray()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html#numpy.asarray) functions? When should you use one rather than the other? They seem to generate ide...
The differences are mentioned quite clearly in the documentation of [`array`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html#numpy.array) and [`asarray`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html#numpy.asarray). The differences lie in the argument list and hence the ac...
Multi-variable List Comprehension
14,416,596
8
2013-01-19T16:57:28Z
14,416,617
10
2013-01-19T17:00:01Z
[ "python", "list", "list-comprehension" ]
I am working on [Project Euler #35](http://projecteuler.net/problem=35), and I need to find the circular permutations of a number. Using `itertools`, I can easily get the permutations of a number. However, I want to do it with a list comprehension (as it seems more Pythonic; I am also trying to get familiar with list c...
The `for y in range(7)` part should come before the permutation loop.: ``` l = [x for y in range(7) for x in list(permutations('1397', y))] ``` The above list comprehension is equivalent to : ``` In [93]: l = [] In [94]: for y in range(7): ...: l.extend(list(permutations('1397', y))) ``` For example: ``` ...
PyPI local cache for Jenkins/local builds
14,417,515
4
2013-01-19T18:39:25Z
14,418,345
7
2013-01-19T20:06:39Z
[ "python", "django", "jenkins", "virtualenv", "pip" ]
I have a Jenkins instance which builds my project with its attendant [PyPI](http://pypi.python.org/pypi) packages from [requirements.txt](http://www.pip-installer.org/en/latest/requirements.html). However, like with [TravisCI](https://travis-ci.org/) builds, building from scratch each time is very time intensive, and m...
pip supports this out of the box ``` pip install --download-cache=DIR ``` if an existing file is requested, it's read from the cache. This can also be done with an environment variable `PIP_DOWNLOAD_CACHE`;
Breaking a line of python to multiple lines?
14,417,571
8
2013-01-19T18:44:45Z
14,417,604
18
2013-01-19T18:47:17Z
[ "python", "syntax" ]
In C++, I like to break up my lines of code if they get too long, or if an if statement if there are a lot of checks in it. ``` if (x == 10 && y < 20 && name == "hi" && obj1 != null) // Do things // vs if (x == 10 && y < 20 && name == "hi" && obj1 != null) { // Do things } AddAndSpawnParticleS...
Style guide says: > The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation. Make s...
Is Brython entirely client-side?
14,418,774
15
2013-01-19T20:57:05Z
14,421,320
26
2013-01-20T03:06:46Z
[ "python", "brython" ]
I have a piece of code written in Python. I would like to put that code in a webpage. Brython seems like the simplest way to glue the two things together, but I don't have a server that can actually run code on the server side. Does Brython require server-side code, or can I host a page using it on the cheap with (say...
Brython is pretty new, and as such is changing rapidly. But, you can use it pretty much anywhere without server side code. Some possibilities: * run locally, with no server whatsoever. You open the html file in your web browser * run on a free web site, without server side access, such as a blog. I use blogger, for e...
set very low values to zero in numpy
14,419,290
9
2013-01-19T21:56:22Z
14,419,318
10
2013-01-19T22:00:04Z
[ "python", "numpy" ]
In numpy I have an array like ``` [0 + 0.5j, 0.25 + 1.2352444e-24j, 0.25+ 0j, 2.46519033e-32 + 0j] ``` what is the fastest and easiest way to set the super low value to zero to get ``` [0 + 0.5j, 0.25 + 0j, 0.25+ 0j, 0 + 0j] ``` efficiency is not the paramount.
Hmmm. I'm not super-happy with it, but this seems to work: ``` >>> a = np.array([0 + 0.5j, 0.25 + 1.2352444e-24j, 0.25+ 0j, 2.46519033e-32 + 0j]) >>> a array([ 0.00000000e+00 +5.00000000e-01j, 2.50000000e-01 +1.23524440e-24j, 2.50000000e-01 +0.00000000e+00j, 2.46519033e-32 +0.00000000e+00j]) >>> ...
set very low values to zero in numpy
14,419,290
9
2013-01-19T21:56:22Z
14,419,441
8
2013-01-19T22:13:34Z
[ "python", "numpy" ]
In numpy I have an array like ``` [0 + 0.5j, 0.25 + 1.2352444e-24j, 0.25+ 0j, 2.46519033e-32 + 0j] ``` what is the fastest and easiest way to set the super low value to zero to get ``` [0 + 0.5j, 0.25 + 0j, 0.25+ 0j, 0 + 0j] ``` efficiency is not the paramount.
To set elements that are less than `eps` to zero: ``` a[np.abs(a) < eps] = 0 ``` There could be a specialized function that is more efficient. If you want to suppress printing of small floats instead: ``` import numpy as np a = np.array([1+1e-10j]) print a # -> [ 1. +1.00000000e-10j] np.set_printoptions(suppress=T...
Adding indexes to SQLAlchemy models after table creation
14,419,299
10
2013-01-19T21:57:47Z
16,736,472
11
2013-05-24T13:45:29Z
[ "python", "indexing", "sqlalchemy" ]
I have a flask-sqlalchemy model: ``` class MyModel(db.Model): __tablename__ = 'targets' id = db.Column(db.Integer, primary_key=True) url = db.Column(db.String(2048)) ``` The table has already been created, and is in use. I want to create an index on the url attribute, so I pass index=True to it: ``` url = db.Column(...
Call `create()` on the Index: ``` index.create() ``` <http://docs.sqlalchemy.org/en/latest/core/constraints.html#sqlalchemy.schema.Index.create>
Weird Python code results
14,419,898
2
2013-01-19T22:57:04Z
14,419,899
13
2013-01-19T23:10:47Z
[ "python" ]
Can I anyone tell me why the following code generates such results? ``` def weird(s): print s for ii in range(len(s)): for jj in range(ii, len(s)+1): print ii, jj return if __name__=="__main__": ss="acaacb" weird(ss) ``` results: ``` acaacb 0 0 0 1 0 2 0 3 0 4 0 5 0 6 ``` Sh...
No, you placed a `return` statement inside of the outer `for` loop. At the end of the first iteration, you exit the function. That's what a `return` statement does; it ends the function regardless of what loop construct you are currently executing. Remove the `return` statement and the loop will continue to run all th...
Storing lambdas in a dictionary
14,419,925
6
2013-01-19T23:15:20Z
14,419,937
14
2013-01-19T23:16:24Z
[ "python", "dictionary", "lambda" ]
I have been trying to create a dictionary with a string for each key and a lambda function for each value. I am not sure where I am going wrong but I suspect it is either my attempt to store a lambda in a dictionary in the first place, or the fact that my lambda is using a shortcut operator. Code: ``` dict = { 'A...
You cannot use assignments in a expression, and a `lambda` only takes an expression. You can store lambdas in dictionaries just fine otherwise: ``` dict = {'Applied_poison_rating_bonus' : (lambda target, magnitude: target.equipmentPoisonRatingBonus + magnitude)} ``` The above `lambda` of course only returns the resu...
write recursive Parser with pyparsing
14,420,156
5
2013-01-19T23:46:03Z
14,420,388
10
2013-01-20T00:17:24Z
[ "python", "parsing", "pyparsing" ]
I'm trying to understand the `Forward()` element from pyparsing. Suppose I have this simple BNF: ``` identifier = "a..z,$,_" < "a..z,$,_,0..9" > package_name = identifier / ( package_name "." identifier ) ``` and I try to parse a simple package like `java.lang.String` I get either just `java` as result...
The problem is not with `Forward` but with your grammar, which is inherently either limited too early, or recursive in a way that is undecidable with a naive recursive descent parser like Pyparsing. You have this: ``` package_name = identifier | (package_name "." identifier ) ``` If you match left to right, this wil...
Global and local variables in Python
14,421,733
3
2013-01-20T04:42:08Z
14,421,773
8
2013-01-20T04:53:25Z
[ "python", "function", "python-3.x", "global-variables" ]
I am learning Python. A book on Python 3 says the following code should work fine: ``` def funky(): print(myvar) myvar = 20 print(myvar) myvar = 10 funky() ``` But when I run it in Python 3.3, I got the ``` UnboundLocalError: local variable 'myvar' referenced before assignment ``` error. My understandi...
You need to call `global` in your function before assigning a value. ``` def funky(): global myvar print(myvar) myvar = 20 print(myvar) myvar = 10 funky() ``` Note that you can print the value without calling global because you can access global variables without using `global`, but attempting to ass...
Is the PySide Slot Decorator Necessary?
14,421,897
19
2013-01-20T05:15:49Z
14,431,607
29
2013-01-21T02:13:54Z
[ "python", "pyqt", "pyside", "signals-slots" ]
I've seen some example code for PySide slots that uses the @QtCore.Slot decorator, and some that does not. Testing it myself, it doesn't seem to make a difference. Is there a reason I should or should not use it? For example, in the following code: ``` import sys from PySide import QtCore # the next line seems to mak...
[This](http://pyqt.sourceforge.net/Docs/PyQt4/new_style_signals_slots.html) link explains the following about the `pyqtSlot` decorator: > Although PyQt4 allows any Python callable to be used as a slot when > connecting signals, it is sometimes necessary to explicitly mark a > Python method as being a Qt slot and to pr...
Manifest.in, package_data, and data_files clarification?
14,422,340
12
2013-01-20T06:45:04Z
14,425,562
10
2013-01-20T14:36:54Z
[ "python", "setuptools", "distutils" ]
I am trying to create a python package, and I have a directory structure like this. ``` mypkg __init__.py module1 x.py y.py z.txt module2 a.py b.py ``` Then I added all the files in manifest.in and when I check the created archive, it had all ...
Try using setuptools instead of distutils.
Difference between tuples and frozensets in Python
14,422,409
22
2013-01-20T07:00:17Z
14,422,446
41
2013-01-20T07:07:22Z
[ "python", "data-structures", "set", "tuples" ]
I'm learning Python 3 using The Quick Python Book, where the author talks about frozensets, stating that since sets are mutable and hence unhashable, thereby becoming unfit for being dictionary keys, their frozen counterparts were introduced. Other than the obvious difference that a tuple is an ordered data structure w...
`tuples` are immutable `lists`, `frozensets` are immutable `sets`. `tuples` are indeed an ordered collection of objects, but they can contain duplicates and unhashable objects, and have slice functionality `frozensets` aren't indexed, but you have the functionality of `sets` - O(1) element lookups, and functionality ...
Difference between tuples and frozensets in Python
14,422,409
22
2013-01-20T07:00:17Z
20,104,074
8
2013-11-20T18:32:01Z
[ "python", "data-structures", "set", "tuples" ]
I'm learning Python 3 using The Quick Python Book, where the author talks about frozensets, stating that since sets are mutable and hence unhashable, thereby becoming unfit for being dictionary keys, their frozen counterparts were introduced. Other than the obvious difference that a tuple is an ordered data structure w...
Somewhat counter intuitive - what about this bon mot: ``` sss = frozenset('abc') sss |= set('efg') ``` Will yield: ``` frozenset(['a', 'c', 'b', 'e', 'g', 'f']) ``` Of course, this is equivalent to x = x | y, so not changing the original frozenset, but it doesn't half make a mockery of the term 'immutable' to the c...
Grabbing current logged in user with Django class views?
14,422,651
4
2013-01-20T07:48:59Z
14,422,684
7
2013-01-20T07:57:01Z
[ "python", "django", "views" ]
I'm trying to grab the currently logged in user and display at the the top of every view. I've searched all over the place for this, but I can't ever find a straight answer for my problem. I was able to get it in the form view, but for some reason I can't display it in a normal view. It's driving me nuts. ``` from dj...
In your generic view implementation you will need to extend `get_context_data` ``` def get_context_data(self, **kwargs): # Call the base implementation first to get a context c = super(ReqListView, self).get_context_data(**kwargs) user = self.request.user return c ``` Then it depends on your r...
Find the smallest number in a python list and print the position
14,423,363
3
2013-01-20T09:52:46Z
14,423,368
16
2013-01-20T09:53:52Z
[ "python", "list" ]
I have a list of integer imported via a file ``` xy = [50, 2, 34, 6, 4, 3, 1, 5, 2] ``` I am aware of [Python: finding lowest integer](http://stackoverflow.com/questions/2622994/python-finding-lowest-integer) However, I wonder how can I print the position of it instead of just finding the smallest number?
Just use the `list.index` method: ``` print xy.index(min(xy)) # 6 ``` If the minimum is repeated, you'll only get the index of the first occurrence, though.
Equivalent of Haskell scanl in python
14,423,794
13
2013-01-20T10:58:46Z
14,423,816
13
2013-01-20T11:03:25Z
[ "python", "haskell", "functional-programming" ]
I would like to know if there is a built in function in python for the equivalent Haskell `scanl`, as `reduce` is the equivalent of `foldl`. Something that does this: ``` Prelude> scanl (+) 0 [1 ..10] [0,1,3,6,10,15,21,28,36,45,55] ``` The question is not about how to implement it, I already have 2 implementations, ...
You can use this, if its more elegant: ``` def scanl(f, base, l): for x in l: base = f(base, x) yield base ``` Use it like: ``` import operator list(scanl(operator.add, 0, range(1,11))) ``` Python 3.x has [`itertools.accumulate(iterable, func= operator.add)`](http://docs.python.org/3/library/ite...
Date object with year and month only
14,425,133
8
2013-01-20T13:46:50Z
14,425,153
9
2013-01-20T13:50:57Z
[ "python", "date", "dictionary", "key" ]
Is is possible to create [date](http://docs.python.org/2/library/datetime.html#datetime.date) object with year and month only? I don't need day. ``` In [5]: from datetime import date In [6]: date(year=2013, month=1) --------------------------------------------------------------------------- TypeError ...
No, you can't do that. For your usecase, use a tuple instead: ``` key = (2013, 1) ``` Since you don't need to do date manipulations on the value a tuple more than suffices.
Catch "socket.error: [Errno 111] Connection refused" exception
14,425,401
30
2013-01-20T14:19:19Z
14,425,454
58
2013-01-20T14:25:50Z
[ "python", "sockets" ]
How could I catch `socket.error: [Errno 111] Connection refused` exception ? ``` try: senderSocket.send("Hello") except ?????: print "catch !" ```
By catching *all* `socket.error` exceptions, and re-raising it if the `errno` attribute is not equal to 111. Or, better yet, use the [`errno.ECONNREFUSED`](http://docs.python.org/2/library/errno.html#errno.ECONNREFUSED) constant instead: ``` import errno from socket import error as socket_error try: senderSocket....
Python 3: ImportError "No Module named Setuptools"
14,426,491
59
2013-01-20T16:20:25Z
14,426,553
114
2013-01-20T16:27:51Z
[ "python", "module", "package", "setup.py", "python-3.3" ]
I'm having troubles with installing packages in Python 3. I have always installed packages with `setup.py install` command. But now when I try to install ansicolors package I get: > importerror "No Module named Setuptools" I have no idea what to do because I haven't have Setuptools never and still I have installed m...
Your `setup.py` file needs `setuptools`. Many of the Python packages use `distutils` for the distribution, but some use `setuptools`, a more complete package. [Here](http://stackoverflow.com/questions/6344076/differences-between-distribute-distutils-and-setuptools) is a question about the differences between them. ~~R...
Python 3: ImportError "No Module named Setuptools"
14,426,491
59
2013-01-20T16:20:25Z
16,511,140
39
2013-05-12T19:20:45Z
[ "python", "module", "package", "setup.py", "python-3.3" ]
I'm having troubles with installing packages in Python 3. I have always installed packages with `setup.py install` command. But now when I try to install ansicolors package I get: > importerror "No Module named Setuptools" I have no idea what to do because I haven't have Setuptools never and still I have installed m...
[Distribute](http://pythonhosted.org/distribute/) - is a setuptools fork which "offers Python 3 support". Installation instructions for distribute(setuptools) + pip: ``` curl -O http://python-distribute.org/distribute_setup.py python distribute_setup.py easy_install pip ``` Similar issue [here](http://stackoverflow.c...
Python 3: ImportError "No Module named Setuptools"
14,426,491
59
2013-01-20T16:20:25Z
19,778,062
10
2013-11-04T22:01:47Z
[ "python", "module", "package", "setup.py", "python-3.3" ]
I'm having troubles with installing packages in Python 3. I have always installed packages with `setup.py install` command. But now when I try to install ansicolors package I get: > importerror "No Module named Setuptools" I have no idea what to do because I haven't have Setuptools never and still I have installed m...
I was doing this inside a virtualenv on Oracle Linux 6.4 using python-2.6 so the apt-based solutions weren't an option for me, nor were the python-2.7 ideas. My fix was to upgrade my version of setuptools that had been installed by virtualenv: ``` pip install --upgrade setuptools ``` After that, I was able to install...
django admin search with multiple words
14,426,692
6
2013-01-20T16:42:49Z
14,490,862
11
2013-01-23T22:49:13Z
[ "python", "django", "django-admin" ]
I have troubles using the `search_fields` when the search expression has multiple words and i want to perform a *startswith* search I have a class ``` class Foo(models.Model): kw = models.CharField(max_length = 255) ... class FooAdmin(admin.ModelAdmin): search_fields = ('^kw',) ``` The `'^'` indicates that i ...
How about override `self.query` so `split()` doesn't work? ``` class UnsplitableUnicode(unicode): "An object that behaves like a unicode string but cannot be split()" def split(self, *args, **kwargs): return [self] class MultiWordSearchChangeList(ChangeList): "Changelist that allows searches to co...
NumPy min/max in-place assignment
14,428,183
6
2013-01-20T19:11:24Z
14,428,207
9
2013-01-20T19:13:38Z
[ "python", "numpy" ]
Is it possible to perform min/max in-place assignment with NumPy multi-dimensional arrays without an extra copy? Say, `a` and `b` are two 2D numpy arrays and I would like to have `a[i,j] = min(a[i,j], b[i,j])` for all `i` and `j`. One way to do this is: ``` a = numpy.minimum(a, b) ``` But according to the documenta...
`numpy.minimum()` takes an optional third argument, which is the output array. You can specify `a` there to have it modified in place: ``` In [9]: a = np.array([[1, 2, 3], [2, 2, 2], [3, 2, 1]]) In [10]: b = np.array([[3, 2, 1], [1, 2, 1], [1, 2, 1]]) In [11]: np.minimum(a, b, a) Out[11]: array([[1, 2, 1], [...
Shuffle a list within a specific range python
14,428,524
3
2013-01-20T19:45:48Z
14,428,543
9
2013-01-20T19:47:24Z
[ "python", "list", "range", "shuffle" ]
I'm very new to Python, so bear with me. I would like to run a program that will shuffle a string of integers in a specific range, but without having to input each integer within that range. I.e., I want to randomize the list of integers b/w 1-100 without typing out (1, 2, 3...100). Yes, I've looked at other answers t...
You can use `range()` to generate a list of integers, and then apply `random.shuffle()` on that list. ``` In [141]: lis=range(1,11) In [142]: lis Out[142]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] In [143]: random.shuffle(lis) In [144]: lis Out[144]: [1, 4, 3, 10, 8, 2, 6, 9, 5, 7] ``` `help()` on `range()`: > range([star...
ignore characters during .sort python
14,428,835
3
2013-01-20T20:19:05Z
14,428,857
9
2013-01-20T20:21:20Z
[ "python" ]
I need some help on sorting 2 lists..one with file listings and one with directory listings. These lists are generated through another part in a much larger script that I cannot put on here. ``` filelist = ['EN088_EFH_030_comp_v011.mov', 'EN086_EHA_010_comp_v031.mov', 'EN083_WDA_400_comp_v021.mov', 'EN086_EHA_020_comp...
``` ....sort(key=lambda x: x.strip('[]')) ```
When to call .join() on a process?
14,429,703
19
2013-01-20T21:45:34Z
14,429,866
13
2013-01-20T22:04:59Z
[ "python", "multiprocessing" ]
I am reading various tutorials on the multiprocessing module in Python, and am having trouble understanding why/when to call `process.join()`. For example, I stumbled across this example: ``` nums = range(100000) nprocs = 4 def worker(nums, out_q): """ The worker function, invoked in a process. 'nums' is a ...
At the point just before you call `join`, all workers have put their results into their queues, but they did not necessarily return, and their processes may not yet have terminated. They may or may not have done so, depending on timing. Calling `join` makes sure that all processes are given the time to properly termin...
When to call .join() on a process?
14,429,703
19
2013-01-20T21:45:34Z
14,430,044
10
2013-01-20T22:28:38Z
[ "python", "multiprocessing" ]
I am reading various tutorials on the multiprocessing module in Python, and am having trouble understanding why/when to call `process.join()`. For example, I stumbled across this example: ``` nums = range(100000) nprocs = 4 def worker(nums, out_q): """ The worker function, invoked in a process. 'nums' is a ...
Try to run this: ``` import math import time from multiprocessing import Queue import multiprocessing def factorize_naive(n): factors = [] for div in range(2, int(n**.5)+1): while not n % div: factors.append(div) n //= div if n != 1: factors.append(n) return fac...
Can I rename fields in a numpy record array
14,429,992
5
2013-01-20T22:20:20Z
14,430,013
12
2013-01-20T22:23:15Z
[ "python", "numpy", "matplotlib" ]
I am new to python so this may sound very basic. I have imported a csv file using csv2rec. The first row has headers. I want to change the headers to 'x', 'y', 'z'. What's the best way of doing this? ``` >>> import matplotlib >>> import matplotlib.mlab as mlab >>> r= mlab.csv2rec('HeightWeight.csv', delimiter= ',') >>...
You can simply assign to `.dtype.names`: ``` >>> d = np.array([(1.0, 2), (3.0, 4)], dtype=[('a', float), ('b', int)]) >>> d array([(1.0, 2), (3.0, 4)], dtype=[('a', '<f8'), ('b', '<i8')]) >>> d['a'] array([ 1., 3.]) >>> d.dtype.names ('a', 'b') >>> d.dtype.names = 'x', 'y' >>> d array([(1.0, 2), (3.0, 4)], ...
How to find the indexes of matches in two lists
14,430,501
4
2013-01-20T23:20:50Z
14,430,515
7
2013-01-20T23:22:04Z
[ "python", "list", "list-comprehension" ]
I'm currently stuck in trying to find a nice solution for the following list comprehension question: It's easy to find equal values with the same index in two lists, e.g. ``` >>> vec1 = [3,2,1,4,5,6,7] >>> vec2 = [1,2,3,3,5,6,9] >>> [a for a, b in zip(vec1, vec2) if a == b] [2,5,6] ``` However, I just need the index...
You were close, use `enumerate()` here. `enumerate()` returns a tuple where first element is the index and second element is the data fetched from the iterable. ``` In [169]: vec1 = [3,2,1,4,5,6,7] In [170]: vec2 = [1,2,3,3,5,6,9] In [171]: [i for i,(a, b) in enumerate(zip(vec1, vec2)) if a == b] Out[171]: [1, 4, 5...
Does x = None or object() equals to explicit check?
14,430,662
2
2013-01-20T23:42:01Z
14,430,673
7
2013-01-20T23:43:57Z
[ "python", "python-3.x" ]
I have function declaration like: ``` def function(list_of_objects = None) ``` and if \*list\_of\_objects\* not passed (is None) I need to define it like empty list. The explicit way is: ``` def function(list_of_objects = None): if not list_of_objects: list_of_objects = list() ``` or ``` def function(l...
No, since `None` is not the only false object. Also included are `[]`, `()`, `0`, and of course `False`.
Get the "bits" of a float in Python?
14,431,170
8
2013-01-21T01:01:24Z
14,431,225
12
2013-01-21T01:09:47Z
[ "python", "floating-point", "bitwise-operators" ]
I am looking for the Python equivalent of Java's `Float.floatToBits`. I found this [Python: obtain & manipulate (as integers) bit patterns of floats](http://stackoverflow.com/questions/1922771/python-obtain-manipulate-as-integers-bit-patterns-of-floats) but does anyone know of a less complicated way?
The answer that Alex Martelli gives in that question is really pretty simple -- you can reduce it to: ``` >>> import struct >>> >>> >>> def floatToBits(f): ... s = struct.pack('>f', f) ... return struct.unpack('>l', s)[0] ... ... >>> floatToBits(173.3125) 1127043072 >>> hex(_) '0x432d5000' ``` Once yo...
Django Serialize Queryset to JSON to construct RESTful response with only field information and id
14,431,580
9
2013-01-21T02:08:44Z
14,434,095
11
2013-01-21T07:26:55Z
[ "python", "django", "json", "api", "rest" ]
I currently have a Post model with 'title' and 'summary' fields. I'm retrieving all the Posts and returning them as JSON as part of a RESTful API interface. Here's the basic approach ``` from django.core import serializers def list_posts(request): posts = Post.objects.filter(owner=authenticated_user) seriali...
What you want to achieve is subset of fields dumped to json. What you're doing is serializing whole django's ORM objects. Not good. Keep it simple: ``` import json posts = (Post.objects.filter(owner=authenticated_user) .values('id', 'title', 'summary')) json_posts = json.dumps(list(posts)) ```
How to write Pandas dataframe to sqlite with Index
14,431,646
17
2013-01-21T02:19:42Z
14,432,914
18
2013-01-21T05:07:41Z
[ "python", "sqlite3", "pandas" ]
I have a list of stockmarket data pulled from Yahoo in a pandas DataFrame (see format below). The date is serving as the index in the DataFrame. I want to write the data (including the index) out to a SQLite database. ``` AAPL GE Date 2009-01-02 89.95 14.76 2009-01-05 93.75 14.38 2009-01-06 92.20...
As you mention, at the moment you save the index, but what we can do is [`reset_index`](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.reset_index.html), saving the old index as a column (`'Date'`). ``` price2 = price.reset_index() In [11]: price2 Out[11]: <class 'pandas.core.frame.DataFrame'> I...
How to retrieve all possible combinations given a sequence of keys from a dictionary with list values
14,431,814
4
2013-01-21T02:44:23Z
14,431,838
7
2013-01-21T02:47:31Z
[ "python", "biopython" ]
I have for instance this dictionary ``` d={'M':['ATG'],'D':['GAC','GAT'],'E':['GAA','GAG']} ``` What I'd like to have as an output given a sequence of keys is a list with all possible sequences. (could be a string as well, in which all the possible sequences would be in separate lines "\n") ``` sequence = "MDE" ``` ...
You can use [`itertools.product`](http://docs.python.org/2/library/itertools.html#itertools.product) here, it returns Cartesian product of the input iterables. ``` In [78]: seq="MED" In [79]: ["".join(x) for x in product(*(d[y] for y in seq))] Out[79]: ['ATGGAAGAC', 'ATGGAAGAT', 'ATGGAGGAC', 'ATGGAGGAT'] ```
python is not recognized as an internal or external command
14,433,499
4
2013-01-21T06:38:20Z
14,433,556
10
2013-01-21T06:41:53Z
[ "python", "node.js", "path-variables" ]
I try to install [this](https://github.com/joyent/node/wiki/Installation) software. For that Python is required. I installed Python from [here](http://python.org/ftp/python/2.7.3/) of name `python-2.7.3.msi`. I am working on Windows 7. Hierarchy of my Python software is same as in this [post](http://stackoverflow.co...
You want to append to your `PATH` the string `C:\Python27`, not the scripts folder. Basically, you want the folder with the actual binary `python.exe` on your path.
Python why would you use [:] over =
14,433,759
25
2013-01-21T06:59:57Z
14,433,812
39
2013-01-21T07:03:48Z
[ "python", "python-3.x" ]
I am just learning python and I am going though the tutorials on <https://developers.google.com/edu/python/strings> Under the **String Slices** section > s[:] is 'Hello' -- omitting both always gives us a copy of the whole > thing (this is the pythonic way to copy a sequence like a string or > list) Out of curiosity...
`=` makes a reference, by using `[:]` you create a copy. For strings, which are immutable, this doesn't really matter, but for lists etc. it is crucial. ``` >>> s = 'hello' >>> t1 = s >>> t2 = s[:] >>> print s, t1, t2 hello hello hello >>> s = 'good bye' >>> print s, t1, t2 good bye hello hello ``` but: ``` >>> li1 ...
What is the complexity of this python sort method?
14,434,490
6
2013-01-21T07:59:30Z
14,434,514
10
2013-01-21T08:02:09Z
[ "python", "algorithm", "sorting" ]
I have a list of lists and I am sorting them using the following ``` data=sorted(data, key=itemgetter(0)) ``` Was wondering what is the runtime complexity of this python method?
Provided `itemgetter(0)` is `O(1)` when used with `data`, the sort is `O(n log n)` both on average and in the worst case. For more information on the sorting method used in Python, see [Wikipedia](http://en.wikipedia.org/wiki/Timsort).
Divide one list by another list
14,434,605
7
2013-01-21T08:09:29Z
14,434,636
13
2013-01-21T08:11:45Z
[ "python", "list", "divide" ]
I have two lists like this: ``` monkey = ['2\n', '4\n', '10\n'] banana = ['18\n', '16\n', '120\n'] ``` What I want to do with these two list is make a third list, let's call it bananasplit. I have to strip away `' \n'`, leaving only values and then make a formula which divides into: ``` bananasplit[0] = banana[0]/...
The following will do it: ``` >>> bananasplit = [int(b) / int(m) for b,m in zip(banana, monkey)] >>> print(bananasplit) [9, 4, 12] ``` As far as your original code goes, the main issue is that the following are effectively no-ops: ``` [int(i) for i in monkey] [int(i) for i in banana] ``` To turn them into something...
How to access a tag called "name" in BeautifulSoup
14,435,268
11
2013-01-21T08:59:42Z
14,435,473
13
2013-01-21T09:14:46Z
[ "python", "xml", "beautifulsoup" ]
I want to access a tag called as `"name"` such as: ``` <contact><name>Yesügey</name><lastName>Yeşil</lastName><phone>+90 333 9695395</phone></contact> ``` Since `"name"` is a property of a BeautifulSoup tag object, I cannot access the child tag `name`: ``` >>> c1 <contact><name>Yesügey</name><lastname>Yeşil</las...
You can try like this, ``` >>> soup=BeautifulSoup.BeautifulSoup(content).findAll('name') >>> for field in soup: ... print field ... <name>Yesügey</name> ``` Or ``` print soup.find('name').string ```
Extracting a number from a string using regular expressions
14,437,422
3
2013-01-21T11:15:29Z
14,437,725
7
2013-01-21T11:33:24Z
[ "python", "regex" ]
I have the following string: ``` fname="VDSKBLAG00120C02 (10).gif" ``` How can I extract the value `10` from the string `fname` (using `re`)?
A simpler regex is `\((\d+)\)`: ``` regex = re.compile(r'\((\d+)\)') value = int(re.search(regex, fname).group(1)) ```
Using python with subprocess Popen
14,438,845
5
2013-01-21T12:40:18Z
14,438,887
7
2013-01-21T12:42:58Z
[ "python", "subprocess" ]
I am struggling to use subprocesses with python. Here is my task: 1. Start an api via the command line (this should be no different than running any argument on the command line) 2. Verify my API has come up. The easiest way to do this would be to poll the standard out. 3. Run a command against the API. A command prom...
To at least really start the subprocess, you have to tell the Popen-object to really communicate. ``` def run_command(command): p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) return p.communicate() ```
Python zip a sub folder and not the entire folder path
14,438,928
6
2013-01-21T12:45:11Z
14,439,300
9
2013-01-21T13:04:54Z
[ "python", "subfolder", "zipfile" ]
I have a program to zip all the contents in a folder. I did not write this code but I found it somewhere online and I am using it. I intend to zip a folder for example say, C:/folder1/folder2/folder3/ . I want to zip folder3 and all its contents in a file say folder3.zip. With the below code, once i zip it, the content...
You'll have to give an `arcname` argument to [`ZipFile.write()`](http://docs.python.org/2/library/zipfile.html#zipfile.ZipFile.write) that uses a relative path. Do this by giving the root path to remove to `makeArchive()`: ``` def makeArchive(fileList, archive, root): """ 'fileList' is a list of file names - f...
Creating a video using OpenCV 2.4.0 in python
14,440,400
4
2013-01-21T14:09:14Z
16,705,188
16
2013-05-23T03:28:58Z
[ "python", "video", "opencv" ]
I am trying to create a video using `OpenCV 2.4.0` in `python 2.7.2`. But the `avi` file size is 0. My code: ``` from cv2 import * im1 = cv.LoadImage("1.jpg") fps = 20 frame_size = cv.GetSize(im1) #writer = cv.CreateVideoWriter("out.avi", CV_FOURCC('M', 'J', 'P', 'G'), fps, frame_size, True) v = VideoWriter() v....
``` import cv2 img1 = cv2.imread('1.jpg') img2 = cv2.imread('2.jpg') img3 = cv2.imread('3.jpg') height , width , layers = img1.shape video = cv2.VideoWriter('video.avi',-1,1,(width,height)) video.write(img1) video.write(img2) video.write(img3) cv2.destroyAllWindows() video.release() ``` A simple code for what yo...
Alias a function in Python
14,440,552
7
2013-01-21T14:16:56Z
14,440,577
14
2013-01-21T14:18:33Z
[ "python" ]
I would like a copy of the `print` function that is called `debug`. How can I alias a function in Python?
You can simply assign `debug = print` in Python 3. In Python 2 `print` isn't a function. There no way to give yourself a `debug` statement that works exactly like `print` (`print 1,`, `print 1 >> sys.stderr` etc.). Best you can do is write a wrapper around the `print` statement: ``` def debug(s): print s ``` You...
How to perform custom build steps in setup.py?
14,441,955
7
2013-01-21T15:31:26Z
21,196,195
7
2014-01-17T21:25:35Z
[ "python", "setuptools", "distutils" ]
The `distutils` module allows to include and install resource files together with Python modules. How to properly include them if resource files should be generated during a building process? For example, the project is a web application which contains CoffeeScript sources that should be compiled into JavaScript and i...
I spent a fair while figuring this out, the various suggestions out there are broken in various ways - they break installation of dependencies, or they don't work in pip, etc. Here's my solution: in setup.py: ``` from setuptools import setup, find_packages from setuptools.command.install import install from distutils...
How to handle IncompleteRead: in python
14,442,222
8
2013-01-21T15:45:43Z
14,442,358
10
2013-01-21T15:53:31Z
[ "python", "python-2.7", "web-scraping", "beautifulsoup", "mechanize" ]
I am trying to fetch some data from a website. However it returns me `incomplete read`. The data I am trying to get is a huge set of nested links. I did some research online and found that this might be due to a server error (A chunked transfer encoding finishing before reaching the expected size). I also found a worka...
The [link](http://bobrochel.blogspot.in/2010/11/bad-servers-chunked-encoding-and.html?showComment=1358777800048) you included in your question is simply a wrapper that executes urllib's read() function, which catches any incomplete read exceptions for you. If you don't want to implement this entire patch, you could alw...
How can I check if a checkbox is checked in Selenium Python Webdriver?
14,442,636
20
2013-01-21T16:09:53Z
14,442,938
33
2013-01-21T16:25:03Z
[ "python", "selenium-webdriver", "pyunit" ]
I'm searching a week how check if a checkbox is checked in selenium webdriver with python, but I find only algoritms from JAVA. I readed the webdriver docs and it dont have a answer for that. Anyone have a solution?
There is a WebElement property called `is_selected()`, and for a check box this indicates whether or not it is checked. Therefore you can verify if it is checked/unchecked by doing something like this: ``` driver.find_element_by_name('<check_box_name>').is_selected() ``` or ``` driver.find_element_by_id('<check_box_...
Two forward slashes in Python
14,444,520
19
2013-01-21T17:56:40Z
14,444,545
27
2013-01-21T17:57:55Z
[ "python" ]
I came across this sample of code from a [radix sort](http://en.wikipedia.org/wiki/Radix_sort#Example_in_Python): ``` def getDigit(num, base, digit_num): # pulls the selected digit return (num // base ** digit_num) % base ``` What does the '`//`' do in Python?
`//` is the integer division operator. In Python 3 the ordinary `/` division operator returns floating point values even if both operands are integers, so a different operator is needed for integer division. This is different from Python 2 where `/` performed integer division if both operands where integers and floati...
web.py - specify address and port
14,444,913
9
2013-01-21T18:26:19Z
14,444,965
8
2013-01-21T18:29:42Z
[ "python", "web.py" ]
How to specify listening address and port in [web.py](http://webpy.org/)? Something like: ``` web.application( urls, host="33.44.55.66", port=8080 ) ``` **Edit** I would like to avoid using the default web.py command line parsing
If you're using web.py's built-in webserver, you can just append the port to the command: ``` python app.py 8080 ``` I haven't tried ever with the listening address, but perhaps it will accept 1.2.3.4:8080 as the format.
web.py - specify address and port
14,444,913
9
2013-01-21T18:26:19Z
14,445,064
9
2013-01-21T18:36:22Z
[ "python", "web.py" ]
How to specify listening address and port in [web.py](http://webpy.org/)? Something like: ``` web.application( urls, host="33.44.55.66", port=8080 ) ``` **Edit** I would like to avoid using the default web.py command line parsing
From API docmentation of [web.py](http://webpy.org/docs/0.3/api#web.httpserver): ``` module web.httpserver function runsimple(func,server_address=('0.0.0.0', 8080)) ``` Runs CherryPy WSGI server hosting WSGI app func. The directory static/ is hosted statically. **Example code** ``` import web class MyApplicat...
Alias for dictionary operation in Python
14,445,206
7
2013-01-21T18:46:40Z
14,445,246
13
2013-01-21T18:50:07Z
[ "python" ]
I want to do something like this: ``` f[frozenset((1,3,4))] = 5 f[frozenset((1,))] = 3 ``` but it's just painful to type these all the time, is there anyway to have alias for this? I know in C++ it's possible to have a helper function which return a reference so you can just type: ``` F(1,3,4) = 5 F(1) = 3 ``` with...
I think that this can really only be achieved via a subclass: ``` class FrozenSetDict(dict): def __setitem__(self,idx,value): try: dict.__setitem__(self,frozenset(idx),value) except TypeError: dict.__setitem__(self,frozenset((idx,)),value) d = FrozenSetDict() d[1,2,3] = 4 d...
Python - append VS extend efficiency
14,446,128
4
2013-01-21T19:50:39Z
14,446,207
14
2013-01-21T19:56:31Z
[ "python", "performance" ]
Here is some code that I wrote using Python: ``` from math import sqrt abundant_list = [] for i in range(12,28123+1): dividor_list = [1] for j in range(2, int(sqrt(i))+1): if i%j == 0: dividor_list.extend([i/j,j]) if sum(dividor_list) > i: abundant_list.append(i) print abundan...
``` import timeit def append2x(foo): foo.append(1) foo.append(1) def extend_lst(foo): foo.extend([1,1]) def extend_tup(foo): foo.extend((1,1)) l1 = [] l2 = [] l3 = [] print timeit.timeit('append2x(l1)',setup = 'from __main__ import append2x,l1') print timeit.timeit('extend_lst(l2)',setup = 'from _...
using icanhazip.com to find IP with mechanize in python, output not what I expected
14,446,132
2
2013-01-21T19:50:47Z
14,459,489
16
2013-01-22T13:18:21Z
[ "python", "networking", "mechanize" ]
I am using icanhazip.com to find my ip address. When I go to that site with a browser, my ip is output in a way I usually see it: 174.xx.xx.xx When I use python and mechanize to get my ip from icanhazip.com, I get this result: 2001:4800:7810:512:13b2:ccd5:ff04:c5f4 I'm sure it's just a representation of the ip addres...
I'm the operator of icanhazip.com and I get this question a lot. I have two additional DNS records that will help you get the result you want. If you want to force an IPv4 lookup, use [ipv4.icanhazip.com](http://ipv4.icanhazip.com). For IPv6, use [ipv6.icanhazip.com](http://ipv6.icanhazip.com). If you access just [ica...
What is a good replacement for paramiko in python 3 ? Or is there a port of paramiko for python 3?
14,446,499
6
2013-01-21T20:17:32Z
19,760,304
7
2013-11-04T01:21:43Z
[ "python", "ssh", "python-3.x", "paramiko" ]
I have python 2.7 code based on the paramiko module that I would like to port to python 3.3 but I cannot seem to find a version of paramiko that would work or a proper replacement. I need the module to work on Windows, Linux and Mac. Anyone got pointers on this ?
I have a full port done that passes all tests on Py2.6, 2.7, 3.2 and 3.3. Needs testing. You can find it in [pull request #236](https://github.com/paramiko/paramiko/pull/236) on the main github repo.
How to vectorize this python code?
14,447,442
11
2013-01-21T21:22:19Z
14,447,750
8
2013-01-21T21:41:34Z
[ "python", "numpy", "vectorization" ]
I am trying to use NumPy and vectorization operations to make a section of code run faster. I appear to have a misunderstanding of how to vectorize this code, however (probably due to an incomplete understanding of vectorization). Here's the working code with loops (A and B are 2D arrays of a set size, already initial...
Usually you want to vectorize code because you think it is running too slow. If your code is too slow, then I can tell you that proper indexing will make it faster. Instead of `A[i][j]` you should write `A[i, j]` -- this avoids a transient copy of a (sub)array. Since you do this in the inner-most loop of your cod...
How to vectorize this python code?
14,447,442
11
2013-01-21T21:22:19Z
14,448,432
7
2013-01-21T22:33:58Z
[ "python", "numpy", "vectorization" ]
I am trying to use NumPy and vectorization operations to make a section of code run faster. I appear to have a misunderstanding of how to vectorize this code, however (probably due to an incomplete understanding of vectorization). Here's the working code with loops (A and B are 2D arrays of a set size, already initial...
The problem is caused by array broadcasting in the line: ``` A = numpy.minimum(B, B[:,k] + B[k,:]) ``` B is size 6 by 6, B[:,k] is an array with 6 elements, B[k,:] is an array with 6 elements. (Because you are using the numpy array type, both B[:,k] and B[k,:] return a rank-1 array of shape N) Numpy automatically c...
Replacing a RegEx with a string of characters with the same length
14,447,818
2
2013-01-21T21:45:45Z
14,447,851
8
2013-01-21T21:49:09Z
[ "python", "regex" ]
I want to replace XML tags, with a sequence of repeated characters that has the same number of characters of the tag. For example: ``` <o:LastSaved>2013-01-21T21:15:00Z</o:LastSaved> ``` I want to replace it with: ``` #############2013-01-21T21:15:00Z############## ``` How can we use RegEx for this?
[`re.sub`](http://docs.python.org/2/library/re.html#re.sub) accepts a function as replacement: > ``` > re.sub(pattern, repl, string, count=0, flags=0) > ``` > > If `repl` is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the repl...
Running a Python script within shell script - Check status
14,447,997
4
2013-01-21T21:58:50Z
14,448,063
12
2013-01-21T22:02:42Z
[ "python", "bash", "shell", "debian" ]
Within my shell script I run this command: ``` python script.py ``` I was wondering, as a two part question: 1. How can I program my python script to pass a status back to the shell script that ran it depending on what happens in the python script. For example if something goes wrong in the python script have it exi...
First, you can pass the desired exit code as an argument to `sys.exit` in your python script. Second, the exit code of the most recently exited process can be found in the `bash` parameter `$?`. However, you may not need to check it explicitly: ``` if python script.py; then echo "Exit code of 0, success" else ...
find the maximum number in a list using a loop
14,448,692
3
2013-01-21T22:54:48Z
14,448,718
8
2013-01-21T22:56:54Z
[ "python", "list", "variables", "loops", "max" ]
So I have this list and variables: ``` nums = [14, 8, 9, 16, 3, 11, 5] big = nums[0] spot = 0 ``` I'm confused on how to actually do it. Please help! I'm new to Python and I want to use this exercise to give me a starter. I want to start with "repeat length of list" like in Scratch or BYOB, but how do I do that on ...
Here you go... ``` nums = [14, 8, 9, 16, 3, 11, 5] big = max(nums) spot = nums.index(big) ``` This would be the Pythonic way of achieving this. If you want to use a loop, then loop with the current max value and check if each element is larger, and if so, assign to the current max.
find the maximum number in a list using a loop
14,448,692
3
2013-01-21T22:54:48Z
14,448,729
10
2013-01-21T22:58:02Z
[ "python", "list", "variables", "loops", "max" ]
So I have this list and variables: ``` nums = [14, 8, 9, 16, 3, 11, 5] big = nums[0] spot = 0 ``` I'm confused on how to actually do it. Please help! I'm new to Python and I want to use this exercise to give me a starter. I want to start with "repeat length of list" like in Scratch or BYOB, but how do I do that on ...
Usually, you could just use ``` max(nums) ``` If you explicitly want to use a loop, try: ``` max_value = None for n in nums: if n > max_value: max_value = n ```
find the maximum number in a list using a loop
14,448,692
3
2013-01-21T22:54:48Z
14,448,742
9
2013-01-21T22:59:22Z
[ "python", "list", "variables", "loops", "max" ]
So I have this list and variables: ``` nums = [14, 8, 9, 16, 3, 11, 5] big = nums[0] spot = 0 ``` I'm confused on how to actually do it. Please help! I'm new to Python and I want to use this exercise to give me a starter. I want to start with "repeat length of list" like in Scratch or BYOB, but how do I do that on ...
``` nums = [14, 8, 9, 16, 3, 11, 5] big = None spot = None for i, v in enumerate(nums): if big is None or v > big: big = v spot = i ```
Make longer subplot tick marks in matplotlib?
14,449,753
16
2013-01-22T00:42:13Z
14,450,056
16
2013-01-22T01:18:21Z
[ "python", "matplotlib", "subplot" ]
I am trying to alter the tick marks along the axes of a python multipanel subplot. I have two panels that share a common x-axis. I have made the border around the plot thicker as well as making all of the tick marks along the axes thicker. I have two questions: How can I make all tick marks (both axes) longer so they ...
Try the following: ``` #example figure1 ax1.plot(range(2),range(2),linewidth=2) ax1.minorticks_on() ax1.tick_params('both', length=20, width=2, which='major') ax1.tick_params('both', length=10, width=1, which='minor') ``` You can repeat the same for `ax2`. Does this work for you?
Python: loop through list item x times?
14,450,966
6
2013-01-22T03:11:17Z
14,451,020
17
2013-01-22T03:18:36Z
[ "python", "python-2.7" ]
I am using Python2.7 and I would like to loop through a list x times. ``` a=['string1','string2','string3','string4','string5'] for item in a: print item ``` The above code will print all five items in the list, What if I just want to print the first 3 items? I searched over the internet but couldn't find an answer...
[Sequence Slicing](http://docs.python.org/release/2.3.5/whatsnew/section-slices.html) is what you are looking for. In this case, you need to slice the sequence to the first three elements to get them printed. ``` a=['string1','string2','string3','string4','string5'] for item in a[:3]: print item ``` Even, you d...
Python: loop through list item x times?
14,450,966
6
2013-01-22T03:11:17Z
14,451,035
7
2013-01-22T03:20:21Z
[ "python", "python-2.7" ]
I am using Python2.7 and I would like to loop through a list x times. ``` a=['string1','string2','string3','string4','string5'] for item in a: print item ``` The above code will print all five items in the list, What if I just want to print the first 3 items? I searched over the internet but couldn't find an answer...
I think this would be considered *pythonic*: ``` for item in a[:3]: print item ``` **Edit**: since a matter of seconds made this answer redundant, I will try to provide some background information: **Array slicing** allows for quick selection in sequences like Lists of Strings. A subsequence of a one-dimensional...
Better binning in pandas
14,451,185
13
2013-01-22T03:37:04Z
14,451,264
23
2013-01-22T03:46:12Z
[ "python", "pandas", "binning" ]
I've got a data frame and want to filter or bin by a range of values and then get the counts of values in each bin. Currently, I'm doing this: ``` x = 5 y = 17 z = 33 filter_values = [x, y, z] filtered_a = df[df.filtercol <= x] a_count = filtered_a.filtercol.count() filtered_b = df[df.filtercol > x] filtered_b = fil...
Perhaps you are looking for [pandas.cut](http://pandas-docs.github.io/pandas-docs-travis/generated/pandas.cut.html): ``` import pandas as pd import numpy as np df = pd.DataFrame(range(50), columns = ['filtercol']) w = 0 x = 5 y = 17 z = 33 filter_values = [w, x, y, z] out = pd.cut(df.filtercol, bins = filter_values)...
How to measure time taken between lines of code in python?
14,452,145
14
2013-01-22T05:31:40Z
14,452,178
23
2013-01-22T05:34:22Z
[ "python", "time", "profiling", "measure" ]
So in Java, we can do [How to measure time taken by a function to execute](http://stackoverflow.com/questions/313893/how-to-measure-time-taken-by-a-function-to-execute) But how is it done in python? To measure the time start and end time between lines of codes? Something that does this: ``` import some_time_library ...
You can use `time.clock` for that. ``` import time start = time.clock() #your code here print time.clock() - start ``` First call turns the timer on, and second call tells how many seconds has elapsed. There are better profiling tools like `timeit` and `profile`, however this one will measure the time and this i...
How can I save an image with PIL?
14,452,824
31
2013-01-22T06:30:28Z
14,453,043
9
2013-01-22T06:48:02Z
[ "python", "save", "python-imaging-library" ]
I have just done some image processing using the Python image library (PIL) using a post I found earlier to perform fourier transforms of images and I can't get the save function to work. The whole code works fine but it just wont save the resulting image: ``` from PIL import Image import numpy as np i = Image.open("...
You should be able to simply let PIL get the filetype from extension, i.e. use: ``` j.save("C:/Users/User/Desktop/mesh_trans.bmp") ```
How can I save an image with PIL?
14,452,824
31
2013-01-22T06:30:28Z
14,472,089
33
2013-01-23T03:42:52Z
[ "python", "save", "python-imaging-library" ]
I have just done some image processing using the Python image library (PIL) using a post I found earlier to perform fourier transforms of images and I can't get the save function to work. The whole code works fine but it just wont save the resulting image: ``` from PIL import Image import numpy as np i = Image.open("...
The error regarding the file extension has been handled, you either use `bmp` (without the dot), or pass the output name with the extension already. Now to handle the error you need to properly modify your data in frequency domain to be saved as an integer image, `PIL` is telling you that it doesn't accept float data t...
Python subprocess and user interaction
14,457,303
6
2013-01-22T11:13:46Z
14,458,956
7
2013-01-22T12:49:29Z
[ "python", "command-line", "subprocess", "popen", "frontend" ]
I'm working on a GUI front end in Python 2.6 and usually it's fairly simple: you use subprocess.call() or subprocess.Popen() to issue the command and wait for it to finish or react to an error. What do you do if you have a program that stops and waits for user interaction? For example, the program might stop and ask th...
Check out the [subprocess](http://docs.python.org/2/library/subprocess.html) manual. You have options with `subprocess` to be able to redirect the `stdin`, `stdout`, and `stderr` of the process you're calling to your own. ``` from subprocess import Popen, PIPE, STDOUT p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE,...
Using matplotlib in GAE
14,459,320
9
2013-01-22T13:08:52Z
14,463,227
7
2013-01-22T16:23:58Z
[ "python", "google-app-engine", "matplotlib" ]
My tags and title quite clearly state my problem. I want to use matplotlib to create real-time plots in Google App Engine. I've read the [documentation](https://developers.google.com/appengine/docs/python/tools/libraries27) and searched on SO and Google. I found a post, pointing to [this working demo](http://gae-matplo...
I'm not familiar with sys module. To give an answer to the question I prefer using webapp2. This is a working handler: ``` import webapp2 import StringIO import numpy as np import matplotlib.pyplot as plt class MainPage(webapp2.RequestHandler): def get(self): plt.plot(np.random.random((20))) sio ...
gaussian fit with scipy.optimize.curve_fit in python with wrong results
14,459,340
5
2013-01-22T13:10:18Z
14,460,456
12
2013-01-22T14:07:40Z
[ "python", "scipy", "curve-fitting" ]
I am having some trouble to fit a gaussian to data. I think the problem is that most of the elements are close to zero, and there not many points to actually be fitted. But in any case, I think they make a good dataset to fit, and I don't get what is confussing python. Here is the program, I have also added a line to p...
Your problem is with the initial parameters of the curve\_fit. By default, if no other information is given, it will start with an array of 1, but this obviously lead to a radically wrong result. This can be corrected simply by giving a reasonable starting vector. To do this, I start from the estimated mean and standar...