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
loop through kwargs in python
8,899,129
8
2012-01-17T17:38:21Z
24,947,368
7
2014-07-25T03:05:45Z
[ "python" ]
I am trying to write things the python way but not sure how to get it right. In the code below, I want to read obj.subject and place it into var subject, also read obj.body and place it into body. First I want to read the kwargs variables and search for keywords within the string to replace, if none exists then move on...
Just a quick note for those upgrading to Python 3. In Python 3 it's almost the same: ``` subject = obj.subject body = obj.body for key, value in kwargs.items(): subject = subject.replace('[{0}]'.format(key.toupper()), value) body = body.replace('[{0}]'.format(key.toupper()), value) return (subject, body, obj...
module has no attribute
8,899,198
12
2012-01-17T17:44:20Z
8,899,345
18
2012-01-17T17:56:14Z
[ "python" ]
I have a directory with a number of `.py` files in it. each file defines some classes. I also have an empty `__init__.py` in the directory. For example: ``` myproject __init__.py mymodule __init__.py api.py models.py views.py ``` I am trying to import `mymodule` and access the...
The problem is submodules are not automatically imported. You have to explicitly import the `api` module: ``` import myproject.mymodule.api print myproject.mymodule.api.MyClass ``` If you really insist on `api` being available when importing `myproject.mymodule` you can put this in `myproject/mymodule/__init__.py`: ...
Matrix Multiplication in Clojure vs Numpy
8,899,773
38
2012-01-17T18:31:01Z
8,900,188
30
2012-01-17T19:04:20Z
[ "python", "matrix", "numpy", "clojure" ]
I'm working on an application in Clojure that needs to multiply large matrices and am running into some large performance issues compared to an identical Numpy version. Numpy seems to be able to multiply a 1,000,000x23 matrix by its transpose in under a second, while the equivalent clojure code takes over six minutes. ...
The Python version is compiling down to a loop in C while the Clojure version is building a new intermediate sequence for each of the calls to map in this code. It is likely that the performance difference you see is coming from the difference of data structures. To get better than this you could play with a library l...
Matrix Multiplication in Clojure vs Numpy
8,899,773
38
2012-01-17T18:31:01Z
8,900,805
11
2012-01-17T19:51:34Z
[ "python", "matrix", "numpy", "clojure" ]
I'm working on an application in Clojure that needs to multiply large matrices and am running into some large performance issues compared to an identical Numpy version. Numpy seems to be able to multiply a 1,000,000x23 matrix by its transpose in under a second, while the equivalent clojure code takes over six minutes. ...
Numpy code uses built-in libraries, written in Fortran over the last few decades and optimized by the authors, your CPU vendor, and you OS distributor (as well as the Numpy people) for maximal performance. You just did the completely direct, obvious approach to matrix multiplication. It's not surprise, really, that per...
Matrix Multiplication in Clojure vs Numpy
8,899,773
38
2012-01-17T18:31:01Z
8,900,982
23
2012-01-17T20:05:29Z
[ "python", "matrix", "numpy", "clojure" ]
I'm working on an application in Clojure that needs to multiply large matrices and am running into some large performance issues compared to an identical Numpy version. Numpy seems to be able to multiply a 1,000,000x23 matrix by its transpose in under a second, while the equivalent clojure code takes over six minutes. ...
Numpy is linking to BLAS/Lapack routines that have been optimized for decades at the level of machine architecture while the Clojure is a implementing the multiplication in the most straightforward and naive manner. Any time you have non-trivial matrix/vector operations to perform, you should probably link to BLAS/LAP...
Matrix Multiplication in Clojure vs Numpy
8,899,773
38
2012-01-17T18:31:01Z
8,902,524
9
2012-01-17T22:18:37Z
[ "python", "matrix", "numpy", "clojure" ]
I'm working on an application in Clojure that needs to multiply large matrices and am running into some large performance issues compared to an identical Numpy version. Numpy seems to be able to multiply a 1,000,000x23 matrix by its transpose in under a second, while the equivalent clojure code takes over six minutes. ...
As @littleidea and others have pointed out your numpy version is using LAPACK/BLAS/ATLAS which will be much faster than anything you do in clojure since it has been finely tuned for years. :) That said the biggest problem with the Clojure code is that it is using Doubles, as in boxed doubles. I call this the "lazy Dou...
Matrix Multiplication in Clojure vs Numpy
8,899,773
38
2012-01-17T18:31:01Z
8,919,944
14
2012-01-19T01:26:47Z
[ "python", "matrix", "numpy", "clojure" ]
I'm working on an application in Clojure that needs to multiply large matrices and am running into some large performance issues compared to an identical Numpy version. Numpy seems to be able to multiply a 1,000,000x23 matrix by its transpose in under a second, while the equivalent clojure code takes over six minutes. ...
I've just staged a small shootout between [Incanter](http://incanter.org) 1.3 and [jBLAS](http://jblas.org) 1.2.1. Here's the code: ``` (ns ml-class.experiments.mmult [:use [incanter core]] [:import [org.jblas DoubleMatrix]]) (defn -main [m] (let [n 23 m (Integer/parseInt m) ai (matrix (vec (double-arra...
Count number of occurrences of a given substring in a string
8,899,905
70
2012-01-17T18:42:33Z
8,900,059
142
2012-01-17T18:54:13Z
[ "python", "string" ]
> **Possible Duplicate:** > [Basic indexing recurrences of a substring within a string (python)](http://stackoverflow.com/questions/6987702/basic-indexing-recurrences-of-a-substring-within-a-string-python) How can I count the number of times a given substring is present within a string in Python? For example: ``` ...
`string.count(substring)`, like in: ``` >>> "abcdabcva".count("ab") 2 ``` **update**: as pointed up in the comments, this is the way to do it for non overlapping occurrences. If you need to count overlapping ocurrences, you'd better check the answers at: "[Python regex find all overlapping matches?](http://stackoverf...
Count number of occurrences of a given substring in a string
8,899,905
70
2012-01-17T18:42:33Z
8,900,078
9
2012-01-17T18:56:20Z
[ "python", "string" ]
> **Possible Duplicate:** > [Basic indexing recurrences of a substring within a string (python)](http://stackoverflow.com/questions/6987702/basic-indexing-recurrences-of-a-substring-within-a-string-python) How can I count the number of times a given substring is present within a string in Python? For example: ``` ...
Depending what you really mean, i propose the following solutions: 1)You mean a list of space seperated sub-strings, and want to know whats the substring position-number among all substrings: ``` s = 'sub1 sub2 sub3' s.split().index('sub2') >>> 1 ``` 2)You mean the Char-position of the substring in the string: ``` ...
Webdriver Screenshot
8,900,073
17
2012-01-17T18:55:46Z
8,900,173
31
2012-01-17T19:03:05Z
[ "python", "selenium", "webdriver" ]
When taking a screenshot using Selenium Webdriver on windows with python, the screenshot is saved directly to the path of the program, is there a way to save the .png file to a specific directory?
Use `driver.save_screenshot('/path/to/file')` or `driver.get_screenshot_as_file('/path/to/file')`: ``` import selenium.webdriver as webdriver import contextlib @contextlib.contextmanager def quitting(thing): yield thing thing.quit() with quitting(webdriver.Firefox()) as driver: driver.implicitly_wait(10)...
Webdriver Screenshot
8,900,073
17
2012-01-17T18:55:46Z
20,610,895
9
2013-12-16T12:23:47Z
[ "python", "selenium", "webdriver" ]
When taking a screenshot using Selenium Webdriver on windows with python, the screenshot is saved directly to the path of the program, is there a way to save the .png file to a specific directory?
Inspired from this thread (same question for Java): [Take a screenshot with Selenium WebDriver](http://stackoverflow.com/questions/3422262/take-a-screenshot-using-selenium-webdriver-with-java) ``` from selenium import webdriver browser = webdriver.Firefox() browser.get('http://www.google.com/') browser.save_screensho...
What's the difference between lists enclosed by square brackets and parentheses in Python?
8,900,166
72
2012-01-17T19:02:34Z
8,900,189
138
2012-01-17T19:04:21Z
[ "python", "list" ]
``` >>> x=[1,2] >>> x[1] 2 >>> x=(1,2) >>> x[1] 2 ``` Are they both valid? Is one preferred for some reason?
Square brackets are [lists](http://docs.python.org/tutorial/datastructures.html#more-on-lists) while parentheses are [tuples](http://docs.python.org/library/functions.html#tuple). A list is mutable, meaning you can change its contents: ``` >>> x = [1,2] >>> x.append(3) >>> x [1, 2, 3] ``` while tuples are not: ``` ...
Function with dependent preset arguments
8,900,284
6
2012-01-17T19:12:15Z
8,900,299
11
2012-01-17T19:13:18Z
[ "python" ]
Please consider simple function: ``` def fun(x, y, param1=10, param2=param1/3): do something ``` Where `param1` and `param2` should not be required but can be set by user. If `param2` is not set, value is dependant on `param1` in some way. Above example will raise `NameError: name 'param1' is not defined` Is th...
One way is to emulate this inside the function: ``` def fun(x, y, param1=10, param2=None): if param2 is None: param2 = param1/3 # do something ``` If `param2=None` is a valid input into `fun()`, the following might be a better alternative: ``` default = object() def fun(x, y, param1=10, param2=defau...
What's the best way to access columns of an array in Python?
8,900,288
3
2012-01-17T19:12:40Z
8,900,502
10
2012-01-17T19:27:23Z
[ "python", "arrays" ]
In Matlab, one can access a column of an array with `:`: ``` >> array=[1 2 3; 4 5 6] array = 1 2 3 4 5 6 >> array(:,2) ans = 2 5 ``` How to do this in Python? ``` >>> array=[[1,2,3],[4,5,6]] >>> array[:,2] Traceback (most recent call last): File "<stdin>", line 1, in <modu...
Use [Numpy](http://numpy.scipy.org/). ``` >>> import numpy as np >>> >>> a = np.array([[1,2,3],[4,5,6]]) >>> a[:, 2] array([3, 6]) ``` If you come from Matlab, this should be of interest: <http://www.scipy.org/NumPy_for_Matlab_Users>
cProfile for Python does not recognize Function name
8,900,899
11
2012-01-17T20:00:23Z
8,901,520
17
2012-01-17T20:46:52Z
[ "python", "profiling", "cprofile" ]
I have a function in an app called email which I want to profile. When I try to do something like this, it blows up ``` from django.core.management import BaseCommand import cProfile class Command(BaseCommand): def handle(self, *args, **options): from email.modname import send_email ...
The problem is that you imported `send_email` inside your method definition. I suggest you to use `runctx`: ``` cProfile.runctx('send_email()', None, locals()) ``` From [the official documentation](http://docs.python.org/library/profile.html#cProfile.runctx): ``` cProfile.runctx(command, globals, locals, filename=N...
Store exception body in variable
8,901,236
6
2012-01-17T20:24:32Z
8,901,259
9
2012-01-17T20:26:01Z
[ "python", "exception", "try-catch" ]
Is there a way to execute a `try` statement and return the error body as a variable? i.e. ``` var = '' try: error generating code except: var = exception_body ```
Yes, use the `as` syntax of `except`: ``` try: raise Exception("hello world") except Exception as x: print(x) ``` In earlier versions of Python, this would be written `except Exception, x:` which you may see from time to time.
subprocess.Popen() IO redirect
8,902,206
5
2012-01-17T21:49:44Z
8,902,496
7
2012-01-17T22:15:38Z
[ "python", "popen" ]
Trying to redirect a subprocess' output to a file. server.py: ``` while 1: print "Count " + str(count) sys.stdout.flush() count = count + 1 time.sleep(1) ``` Laucher: ``` cmd = './server.py >temp.txt' args = shlex.split(cmd) server = subprocess.Popen( args ) ``` The output appear on screen, `temp.t...
Altenatively, you can use the `stdout` parameter with a file object: ``` with open('temp.txt', 'w') as output: server = subprocess.Popen('./server.py', stdout=output) server.communicate() ``` As explained in the [documentation](http://docs.python.org/library/subprocess.html#popen-constructor): > stdin, stdou...
Python list to bitwise operations
8,903,128
8
2012-01-17T23:25:47Z
8,903,346
16
2012-01-17T23:52:35Z
[ "python", "django", "bitwise-operators" ]
Is there a way to take a list of django query expresses (e.g. `Q(first_name="Jordan")`, where `Q` is `django.db.models.Q`) and bitwise OR them together? In other words, I have something like this: ``` search_string = "various search terms" ``` And I want to do this: ``` search_params = [Q(description__icontains=ter...
You probably want ``` import operator from functools import reduce # Python 3 search_params = reduce(operator.or_, search_params, Q()) ``` This will place a bit-wise or (`|`) between all the items in `search_params`, starting with an empty condition `Q()`.
Scrapy start_urls
8,903,730
5
2012-01-18T00:39:34Z
8,906,080
14
2012-01-18T06:29:19Z
[ "python", "scrapy" ]
[The script](https://github.com/scrapy/dirbot/blob/master/dirbot/spiders/dmoz.py) (below) from [this](http://doc.scrapy.org/en/latest/intro/tutorial.html) tutorial contains two `start_urls`. ``` from scrapy.spider import Spider from scrapy.selector import Selector from dirbot.items import Website class DmozSpider(Sp...
`start_urls` class attribute contains start urls - nothing more. If you have extracted urls of other pages you want to scrape - yield from `parse` callback corresponding requests with [another] callback: ``` class Spider(BaseSpider): name = 'my_spider' start_urls = [ 'http://www.domain.com/' ...
How can I send anything other than strings through Python sock.send()
8,904,092
6
2012-01-18T01:35:10Z
8,904,144
11
2012-01-18T01:44:30Z
[ "python", "sockets", "hex" ]
I'm very very new to programming in Python, but out of necessity I had to hack something together very quick. I am trying to send some data over UDP, and I have everything working except for the fact that when I do socket.send(), I have to enter the data in string form. Here is my program so you can see what I am doin...
Are you using Python 2.7 or 3.2? In 3.2 you could do: ``` data = bytes.fromhex('01AF23') s.send(data) ``` Data would then be equal to: ``` b'\x01\xAF\x23' ``` In 2.7 the same could be accomplished with: ``` data = '01AF23'.decode('hex') ```
In Python, is it possible to unpack a list of strings and put a single character from each string into a generator?
8,904,271
2
2012-01-18T02:07:18Z
8,904,300
8
2012-01-18T02:11:43Z
[ "python" ]
I'm using Python 2.7. Let's say I have a list like so: ``` string_list = ['hello', 'apple', 'green', 'paint', 'sting'] ``` Where each string in the list is the same length. I want to create a generator that would be doing something like the following code: ``` for i in xrange(len(string_list)): my_gen = (ch fo...
Just use the built-in function `zip` - like in ``` for letters in zip('hello', 'apple', 'green', 'paint', 'sting'): print letters ``` zip is a built-in that does just that: combine one element of each iterable in a tuple, for each iteration. Running the above example, you have: ``` >>> for letters in zip('hel...
How to normalize a 2-dimensional numpy array in python less verbose?
8,904,694
42
2012-01-18T03:12:41Z
8,904,762
59
2012-01-18T03:21:58Z
[ "python", "arrays", "syntax", "numpy", "normalization" ]
Given a 3 times 3 numpy array ``` a = numpy.arange(0,27,3).reshape(3,3) # array([[ 0, 3, 6], # [ 9, 12, 15], # [18, 21, 24]]) ``` To normalize the rows of the 2-dimensional array I thought of ``` row_sums = a.sum(axis=1) # array([ 9, 36, 63]) new_matrix = numpy.zeros((3,3)) for i, (row, row_sum) in ...
Broadcasting is really good for this: ``` row_sums = a.sum(axis=1) new_matrix = a / row_sums[:, numpy.newaxis] ``` `row_sums[:, numpy.newaxis]` reshapes row\_sums from being `(3,)` to being `(3, 1)`. When you do `a / b`, `a` and `b` are broadcast against each other. You can learn more about **broadcasting** [**here*...
How to normalize a 2-dimensional numpy array in python less verbose?
8,904,694
42
2012-01-18T03:12:41Z
22,546,877
28
2014-03-20T22:54:35Z
[ "python", "arrays", "syntax", "numpy", "normalization" ]
Given a 3 times 3 numpy array ``` a = numpy.arange(0,27,3).reshape(3,3) # array([[ 0, 3, 6], # [ 9, 12, 15], # [18, 21, 24]]) ``` To normalize the rows of the 2-dimensional array I thought of ``` row_sums = a.sum(axis=1) # array([ 9, 36, 63]) new_matrix = numpy.zeros((3,3)) for i, (row, row_sum) in ...
Scikit-learn has a normalize function that lets you apply various normalizations. The "make it sum to 1" is the L1 norm, and to take that do: ``` from sklearn.preprocessing import normalize matrix = numpy.arange(0,27,3).reshape(3,3).astype(numpy.float64) #array([[ 0., 3., 6.], # [ 9., 12., 15.], # [ 18., ...
Is there an inverted version of numpy.all()?
8,905,291
2
2012-01-18T04:43:28Z
8,905,368
11
2012-01-18T04:53:32Z
[ "python", "numpy" ]
As stated in the [docs for `numpy.all()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.all.html): > `numpy.all()` tests whether all array elements along a given axis **evaluate to True**. Is there a function, that does the opposite: Check whether all array elements along a given axis (I need the diagonal...
First, to extract the diagonal, you can use `mymatrix.diagonal()`. There are quite a few ways to do what you want. To test whether it is zero everywhere you can do `numpy.all(mymatrix.diagonal() == 0)`. Alternatively, "everything is equal to zero (False)" is the same as "nothing equal to True", so you could also use...
extract upper/lower triangular part of a numpy matrix?
8,905,501
20
2012-01-18T05:13:11Z
8,905,529
26
2012-01-18T05:15:34Z
[ "python", "numpy" ]
I have a matrix `A` and I want 2 matrices `U` and `L` such that `U` contains the upper triangular elements of A (all elements above and not including diagonal) and similarly for `L`(all elements below and not including diagonal). Is there a `numpy` method to do this? e.g ``` A = array([[ 4., 9., -3.], [ 2...
Try [`numpy.triu`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.triu.html) (triangle-upper) and [`numpy.tril`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.tril.html) (triangle-lower).
URL encoding in python
8,905,864
14
2012-01-18T06:03:57Z
8,905,900
23
2012-01-18T06:07:49Z
[ "python", "string", "http", "url", "ascii" ]
Is there a simple method I'm missing in `urllib` or other library for this task? URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits. Here's an example of an input and my expected output: ``` Mozilla/5.0 (Linux; U; Android 4.0; xx-xx; Galaxy Nexus Build/IFL10C) AppleWebKit/534....
For Python 2.x, use [urllib.quote](http://docs.python.org/library/urllib.html#urllib.quote) > Replace special characters in string using the %xx escape. Letters, digits, and the characters '\_.-' are never quoted. By default, this function is intended for quoting the path section of the URL. The optional safe paramete...
How to operate elementwise on a matrix of type scipy.sparse.csr_matrix?
8,906,506
4
2012-01-18T07:18:27Z
8,907,707
9
2012-01-18T09:18:21Z
[ "python", "numpy", "scipy", "operation" ]
In numpy if you want to calculate the sinus of each entry of a matrix (elementise) then ``` a = numpy.arange(0,27,3).reshape(3,3) numpy.sin(a) ``` will get the job done! If you want the power let's say to 2 of each entry ``` a**2 ``` will do it. But if you have a sparse matrix things seem more difficult. At least ...
The following trick works for any operation which maps zero to zero, and only for those operations, because it only touches the non-zero elements. I.e., it will work for `sin` and `sqrt` but not for `cos`. Let `X` be some CSR matrix... ``` >>> from scipy.sparse import csr_matrix >>> X = csr_matrix(np.arange(10).resha...
formatting python timedelta objects
8,906,926
13
2012-01-18T08:03:13Z
8,907,269
29
2012-01-18T08:39:27Z
[ "python", "datetime", "formatting" ]
I am rather new to python. I have two datetime objects. I need to calculate the timedelta between them and then show the output in a spcific format. ``` Alpha_TimeObj = datetime.datetime(int(AlphaTime.strftime('%Y')), int(AlphaTime.strftime('%m')), int(AlphaTime.strftime('%d')), int(AlphaTime.strftime('%H')), int(Alph...
> but i was wondering if I can do it in a single line using any date time function like strftime. As far as I can tell, there isn't a built-in method to `timedelta` that does that. If you're doing it often, you can create your own function, e.g. ``` def strfdelta(tdelta, fmt): d = {"days": tdelta.days} d["hou...
formatting python timedelta objects
8,906,926
13
2012-01-18T08:03:13Z
8,907,407
9
2012-01-18T08:53:01Z
[ "python", "datetime", "formatting" ]
I am rather new to python. I have two datetime objects. I need to calculate the timedelta between them and then show the output in a spcific format. ``` Alpha_TimeObj = datetime.datetime(int(AlphaTime.strftime('%Y')), int(AlphaTime.strftime('%m')), int(AlphaTime.strftime('%d')), int(AlphaTime.strftime('%H')), int(Alph...
In Python2.7 or newer, you could use the [total\_seconds](http://docs.python.org/library/datetime.html#datetime.timedelta.total_seconds) method: ``` import datetime as dt turnaround = dt.timedelta(days = 1, hours = 3, minutes = 42, seconds = 54) total_seconds = int(turnaround.total_seconds()) hours, remainder = divm...
del MyClass doesn't call object.__del__()
8,907,905
5
2012-01-18T09:34:55Z
8,908,090
7
2012-01-18T09:49:33Z
[ "python", "destructor" ]
I have a class that opens a file for writing. In my destructor, I call the function that closes the file: ``` class MyClass: def __del__(self): self.close() def close(self): if self.__fileHandle__ is not None: self.__fileHandle__.close() ``` but when I delete the object with c...
That's not what `del` does. It's unfortunate that `__del__` has the same name as `del`, because they are not related to each other. In modern terminology, the `__del__` method would be called a *finalizer*, not a *destructor* and the difference is important. The short difference is that it's easy to guarantee when a d...
del MyClass doesn't call object.__del__()
8,907,905
5
2012-01-18T09:34:55Z
8,908,094
8
2012-01-18T09:49:50Z
[ "python", "destructor" ]
I have a class that opens a file for writing. In my destructor, I call the function that closes the file: ``` class MyClass: def __del__(self): self.close() def close(self): if self.__fileHandle__ is not None: self.__fileHandle__.close() ``` but when I delete the object with c...
Are you sure you want to use `__del__`? There are [issues](http://docs.python.org/reference/datamodel.html#object.__del__) with `__del__` and garbage collection. You could make MyClass a [context manager](http://docs.python.org/reference/datamodel.html#context-managers) instead: ``` class MyClass(object): def __e...
Base64 encoding in Python 3
8,908,287
52
2012-01-18T10:04:30Z
8,908,304
10
2012-01-18T10:05:37Z
[ "python", "python-3.x", "base64" ]
Following this [python example](http://docs.python.org/release/3.1.3/library/base64.html) , I do: ``` >>> import base64 >>> encoded = base64.b64encode(b'data to be encoded') >>> encoded b'ZGF0YSB0byBiZSBlbmNvZGVk' ``` But, if I leave out the leading `b` and do: ``` >>> encoded = base64.b64encode('data to be encoded'...
There is all you need: ``` expected bytes, not str ``` The leading `b` makes your string binary. What version of Python do you use? 2.x or 3.x? **Edit:** See <http://docs.python.org/release/3.0.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit> for the gory details of strings in Python 3.x
Base64 encoding in Python 3
8,908,287
52
2012-01-18T10:04:30Z
8,909,233
80
2012-01-18T11:22:51Z
[ "python", "python-3.x", "base64" ]
Following this [python example](http://docs.python.org/release/3.1.3/library/base64.html) , I do: ``` >>> import base64 >>> encoded = base64.b64encode(b'data to be encoded') >>> encoded b'ZGF0YSB0byBiZSBlbmNvZGVk' ``` But, if I leave out the leading `b` and do: ``` >>> encoded = base64.b64encode('data to be encoded'...
`base64` encoding takes 8-bit binary byte data and encodes it using only the characters A-Z, a-z and 0-9, so it can be transmitted over channels that does not preserve all 8-bits of data, such as email. Hence, it wants a string of 8-bit bytes. You create those in Python 3 with the `b''` syntax. If you remove the b, i...
Base64 encoding in Python 3
8,908,287
52
2012-01-18T10:04:30Z
19,915,017
18
2013-11-11T20:11:35Z
[ "python", "python-3.x", "base64" ]
Following this [python example](http://docs.python.org/release/3.1.3/library/base64.html) , I do: ``` >>> import base64 >>> encoded = base64.b64encode(b'data to be encoded') >>> encoded b'ZGF0YSB0byBiZSBlbmNvZGVk' ``` But, if I leave out the leading `b` and do: ``` >>> encoded = base64.b64encode('data to be encoded'...
If the data to be encoded contains "exotic" characters, I think you have to encode in "UTF-8" ``` encoded = base64.b64encode (bytes('data to be encoded', "utf-8")) ```
Python xlrd : how to convert an extracted value?
8,909,342
2
2012-01-18T11:29:22Z
8,909,963
8
2012-01-18T12:16:48Z
[ "python", "xlrd" ]
Well i have a question that i feel i've been answered several times, from what i found here. However, as a newbie, i can't really understand how to perform a really basic operation. Here's the thing : * i have an `.xls` and when i use xlrd to get a value i'm just using `sh.cell(0,0)` (assuming that sh is my sheet);...
sh.cell(x, y) returns an instance of the class Cell. When you print sh.cell(x,y) you are returning the **repr** function of the class (so it prints type:value). you should try: ``` cell = sh.cell(x,y) print(cell.value) ``` I cannot test this since I don't have xlrd but, I think it will work given the documentation: ...
Python idiom for creating a given number of elements in a list
8,911,644
2
2012-01-18T14:18:57Z
8,911,769
7
2012-01-18T14:27:15Z
[ "python" ]
Often when I'm using Python I'll find myself writing list comprehensions that look something like this: ``` num_foobars = 10 foobars = [create_foobar() for idx in xrange(num_foobars)] ``` Obviously that works just fine, but it still feels a little awkward to me to creating a range and iterating dummy index across it,...
Here is the itertools way: ``` list(starmap(create_foobar, repeat((), 10))) ``` The itertools way is short and fast. That said, I prefer the list comprehension :-)
How to catch IndentationError
8,911,735
7
2012-01-18T14:25:46Z
8,911,799
10
2012-01-18T14:28:47Z
[ "python", "exception-handling", "indentation" ]
First of all - I don't have a problem with bad-indentated code and I have an idea of how does this exception works like. I ask, if there is any way to catch IndentationError in code with a try/except block? For example, let's say I'm writing a test for a function written by someone else. I want to run it in try/except...
Yes, this can be done. However, the function under test would have to live in a different module: ``` # test1.py try: import test2 except IndentationError as ex: print ex # test2.py def f(): pass pass # error ``` When run, this correctly catches the exception. It is worth nothing that the checkin...
Is there a way to avoid the linear search on this?
8,912,820
7
2012-01-18T15:31:36Z
8,912,962
8
2012-01-18T15:42:23Z
[ "python", "algorithm" ]
I have a large pool of objects with starting number and ending number. For example: ``` (999, 2333, data) (0, 128, data) (235, 865, data) ... ``` Assuming that the intervals don't overlap with each other. And I am writing a function that takes a number and locate the object that (low, high) contains it. Say given 3...
Think if it worth sorting the data. If you only want to search a few times, then it doesn't - and you cannot avoid linear search. total complexity of your searches will be `O(n*k)`, where `n` is the number of elements and `k` is the number of searches. If you want to search a lot of times, then you should first sor...
List copy not working?
8,913,026
7
2012-01-18T15:46:43Z
8,913,060
7
2012-01-18T15:49:16Z
[ "python", "list" ]
I got something with Python that I can't understand. I have a list of lists, called data: ``` data = [[75], [95, 64], [17, 47, 82], [18, 35, 87, 10], [20, 4, 82, 47, 65], [19, 1, 23, 75, 3, 34], [88, 2, 77, 73, 7, 63, 67], [99, 65, 4, 28, 6, 16, 70, 92], [41, 41, 26, 56, 83, 40, 80, 70, 33], [41, 48, 72, 33, 47, 32, 3...
use [copy.deepcopy](http://docs.python.org/library/copy.html#copy.deepcopy) to copy nested mutable objects. ``` import copy rev_data = copy.deepcopy(data) .....................  ``` That is: ``` >>> import copy >>> data = [[75], [95, 64], [17, 47, 82], [18, 35, 87, 10], [20, 4, 82, 47, 65], [19, 1, 23, 75, 3, 34], ...
List copy not working?
8,913,026
7
2012-01-18T15:46:43Z
8,913,061
14
2012-01-18T15:49:24Z
[ "python", "list" ]
I got something with Python that I can't understand. I have a list of lists, called data: ``` data = [[75], [95, 64], [17, 47, 82], [18, 35, 87, 10], [20, 4, 82, 47, 65], [19, 1, 23, 75, 3, 34], [88, 2, 77, 73, 7, 63, 67], [99, 65, 4, 28, 6, 16, 70, 92], [41, 41, 26, 56, 83, 40, 80, 70, 33], [41, 48, 72, 33, 47, 32, 3...
`data[:]` creates a **shallow** copy of the list `data`. Since this is a list of lists, and you also want to copy the inner lists, you need a **deep** copy instead: ``` rev_data = copy.deepcopy(data) ``` or ``` rev_data = [x[:] for x in data] ```
Parse 4th capital letter of line in Python?
8,913,639
4
2012-01-18T16:25:24Z
8,913,706
9
2012-01-18T16:29:55Z
[ "python" ]
How can I parse lines of text from the 4th occurrence of a capital letter onward? For example given the lines: ``` adsgasdlkgasYasdgjaUUalsdkjgaZsdalkjgalsdkjTlaksdjfgasdkgj oiwuewHsajlkjfasNasldjgalskjgasdIasdllksjdgaPlsdakjfsldgjQ ``` I would like to capture: ``` `ZsdalkjgalsdkjTlaksdjfgasdkgj` `PlsdakjfsldgjQ` ``...
I present two approaches. **Approach 1: all-out regex** ``` In [1]: import re In [2]: s = 'adsgasdlkgasYasdgjaUUalsdkjgaZsdalkjgalsdkjTlaksdjfgasdkgj' In [3]: re.match(r'(?:.*?[A-Z]){3}.*?([A-Z].*)', s).group(1) Out[3]: 'ZsdalkjgalsdkjTlaksdjfgasdkgj' ``` The `.*?[A-Z]` consumes characters up to, and including, th...
Finding the nearest value and return the index of array in Python
8,914,491
18
2012-01-18T17:25:41Z
8,914,573
15
2012-01-18T17:30:52Z
[ "python", "numpy", "python-3.x" ]
I found this post: [Python: finding an element in an array](http://stackoverflow.com/questions/604802/python-finding-an-element-in-an-array) and it's about returning the index of an array through matching the values. On the other hand, what I am thinking of doing is similar but different. I would like to find the nea...
The corresponding Numpy code is almost the same, except you use [`numpy.argmin`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmin.html#numpy.argmin) to find the minimum index. ``` idx = numpy.argmin(numpy.abs(A - target)) ```
Finding the nearest value and return the index of array in Python
8,914,491
18
2012-01-18T17:25:41Z
8,929,827
22
2012-01-19T16:42:11Z
[ "python", "numpy", "python-3.x" ]
I found this post: [Python: finding an element in an array](http://stackoverflow.com/questions/604802/python-finding-an-element-in-an-array) and it's about returning the index of an array through matching the values. On the other hand, what I am thinking of doing is similar but different. I would like to find the nea...
This is similar to using bisect\_left, but it'll allow you to pass in an array of targets ``` def find_closest(A, target): #A must be sorted idx = A.searchsorted(target) idx = np.clip(idx, 1, len(A)-1) left = A[idx-1] right = A[idx] idx -= target - left < right - target return idx ``` Some...
Python 3 builtin types __init__ doesn't call super().__init__?
8,914,868
14
2012-01-18T17:51:08Z
8,915,529
9
2012-01-18T18:42:07Z
[ "python", "python-3.x", "constructor", "method-resolution-order" ]
When deriving from a builtin type as well as from some other class, it seems that the builtin type's constructor doesn't call the super class constructor. This results in \_\_init\_\_ methods not being called for types that come after the builtin in the MRO. Example: ``` class A: def __init__(self, *args, **kwarg...
The correct usage of `super()` is rather subtle and requires some care if the collaborating methods don't all have the same signature. The usual pattern for `__init__()` methods is the following: ``` class A(object): def __init__(self, param_a, **kwargs): self.param_a = param_a super(A, self).__ini...
Sort (hex) colors to match rainbow
8,915,113
5
2012-01-18T18:09:23Z
8,915,267
11
2012-01-18T18:22:02Z
[ "python", "algorithm", "sorting", "colors" ]
I have a list of colors represented in hex - I need to sort them to match the order of colors in a rainbow. - I could hardcode a sort order - but I feel there's a cleaner way.
Here's a function that, given a color specification in hex RGB, returns its HSV color: ``` import colorsys def get_hsv(hexrgb): hexrgb = hexrgb.lstrip("#") # in case you have Web color specs r, g, b = (int(hexrgb[i:i+2], 16) / 255.0 for i in xrange(0,5,2)) return colorsys.rgb_to_hsv(r, g, b) ``` Now yo...
Python Image Library fails with message "decoder JPEG not available" - PIL
8,915,296
258
2012-01-18T18:24:19Z
10,109,941
421
2012-04-11T16:22:59Z
[ "python", "jpeg", "python-imaging-library", "pillow" ]
PIL does support JPEG in my system. Whenever I do an upload, my code is failing with: ``` File "PIL/Image.py", line 375, in _getdecoder raise IOError("decoder %s not available" % decoder_name) IOError: decoder jpeg not available ``` How can I resolve this?
libjpeg-dev is required to be able to process jpegs with pillow (or PIL), so you need to install it and then recompile pillow. It also seems that libjpeg8-dev is needed on Ubuntu 14.04 If you're still using PIL then you should really be using pillow these days though, so first `pip uninstall PIL` before following thes...
Python Image Library fails with message "decoder JPEG not available" - PIL
8,915,296
258
2012-01-18T18:24:19Z
13,143,571
63
2012-10-30T16:32:25Z
[ "python", "jpeg", "python-imaging-library", "pillow" ]
PIL does support JPEG in my system. Whenever I do an upload, my code is failing with: ``` File "PIL/Image.py", line 375, in _getdecoder raise IOError("decoder %s not available" % decoder_name) IOError: decoder jpeg not available ``` How can I resolve this?
For those on OSX, I used the following binary to get libpng and libjpeg installed systemwide: [libpng & libjpeg for OSX](http://ethan.tira-thompson.com/Mac_OS_X_Ports.html) Because I already had PIL installed (via pip on a virtualenv), I ran: ``` pip uninstall PIL pip install PIL --upgrade ``` This resolved the `de...
Python Image Library fails with message "decoder JPEG not available" - PIL
8,915,296
258
2012-01-18T18:24:19Z
14,675,219
16
2013-02-03T17:35:30Z
[ "python", "jpeg", "python-imaging-library", "pillow" ]
PIL does support JPEG in my system. Whenever I do an upload, my code is failing with: ``` File "PIL/Image.py", line 375, in _getdecoder raise IOError("decoder %s not available" % decoder_name) IOError: decoder jpeg not available ``` How can I resolve this?
On Fedora 17 I had to install `libjpeg-devel` and afterwards reinstall `PIL`: ``` sudo yum install --assumeyes libjpeg-devel sudo pip-python install --upgrade PIL ```
Python Image Library fails with message "decoder JPEG not available" - PIL
8,915,296
258
2012-01-18T18:24:19Z
16,908,700
20
2013-06-04T02:03:19Z
[ "python", "jpeg", "python-imaging-library", "pillow" ]
PIL does support JPEG in my system. Whenever I do an upload, my code is failing with: ``` File "PIL/Image.py", line 375, in _getdecoder raise IOError("decoder %s not available" % decoder_name) IOError: decoder jpeg not available ``` How can I resolve this?
The followed works on ubuntu 12.04: ``` pip uninstall PIL apt-get install libjpeg-dev apt-get install libfreetype6-dev apt-get install zlib1g-dev apt-get install libpng12-dev pip install PIL --upgrade ``` when your see "-- JPEG support avaliable" that means it works. But, if it still doesn't work when your edit your...
Python Image Library fails with message "decoder JPEG not available" - PIL
8,915,296
258
2012-01-18T18:24:19Z
16,916,799
28
2013-06-04T11:36:37Z
[ "python", "jpeg", "python-imaging-library", "pillow" ]
PIL does support JPEG in my system. Whenever I do an upload, my code is failing with: ``` File "PIL/Image.py", line 375, in _getdecoder raise IOError("decoder %s not available" % decoder_name) IOError: decoder jpeg not available ``` How can I resolve this?
This is the only way that worked for me. Installing packages and reinstalling PIL didn't work. On ubuntu, install the required package: ``` sudo apt-get install libjpeg-dev ``` (you may also want to install `libfreetype6 libfreetype6-dev zlib1g-dev` to enable other decoders). Then replace PIL with pillow: ``` pip ...
Python Image Library fails with message "decoder JPEG not available" - PIL
8,915,296
258
2012-01-18T18:24:19Z
24,069,466
10
2014-06-05T20:16:19Z
[ "python", "jpeg", "python-imaging-library", "pillow" ]
PIL does support JPEG in my system. Whenever I do an upload, my code is failing with: ``` File "PIL/Image.py", line 375, in _getdecoder raise IOError("decoder %s not available" % decoder_name) IOError: decoder jpeg not available ``` How can I resolve this?
On Mac OS X Mavericks (10.9.3), I solved this by doing the follows: Install libjpeg by **brew** (package management system) > brew install libjpeg reinstall pillow (I use pillow instead of PIL) > pip install -I pillow
Python Image Library fails with message "decoder JPEG not available" - PIL
8,915,296
258
2012-01-18T18:24:19Z
25,406,160
8
2014-08-20T13:34:07Z
[ "python", "jpeg", "python-imaging-library", "pillow" ]
PIL does support JPEG in my system. Whenever I do an upload, my code is failing with: ``` File "PIL/Image.py", line 375, in _getdecoder raise IOError("decoder %s not available" % decoder_name) IOError: decoder jpeg not available ``` How can I resolve this?
I was already using `Pillow` and got the same error. Tried installing `libjpeg` or `libjpeg-dev` as suggested by others but was told that a (newer) version was already installed. In the end all it took was reinstalling `Pillow`: ``` sudo pip uninstall Pillow sudo pip install Pillow ```
Python Image Library fails with message "decoder JPEG not available" - PIL
8,915,296
258
2012-01-18T18:24:19Z
26,755,710
9
2014-11-05T11:09:25Z
[ "python", "jpeg", "python-imaging-library", "pillow" ]
PIL does support JPEG in my system. Whenever I do an upload, my code is failing with: ``` File "PIL/Image.py", line 375, in _getdecoder raise IOError("decoder %s not available" % decoder_name) IOError: decoder jpeg not available ``` How can I resolve this?
``` apt-get install libjpeg-dev apt-get install libfreetype6-dev apt-get install zlib1g-dev apt-get install libpng12-dev ``` Install these and be sure to install PIL with pip because I compiled it from source and for some reason it didn't work
Python Image Library fails with message "decoder JPEG not available" - PIL
8,915,296
258
2012-01-18T18:24:19Z
30,822,006
13
2015-06-13T18:16:02Z
[ "python", "jpeg", "python-imaging-library", "pillow" ]
PIL does support JPEG in my system. Whenever I do an upload, my code is failing with: ``` File "PIL/Image.py", line 375, in _getdecoder raise IOError("decoder %s not available" % decoder_name) IOError: decoder jpeg not available ``` How can I resolve this?
Rolo's answer is excellent, however I had to reinstall Pillow by bypassing pip cache (introduced with pip 7) otherwise it won't get properly recompiled!!! The command is: ``` pip install -I --no-cache-dir -v Pillow ``` and you can see if Pillow has been properly configured by reading in the logs this: ``` PIL SETUP ...
Creating a colour bar for a plot made with plt.fill
8,915,902
7
2012-01-18T19:12:33Z
8,916,668
7
2012-01-18T20:06:16Z
[ "python", "matplotlib", "colorbar" ]
I'm new to Python (was an IDL user before hand) so I hope that I'm asking this in an understandable way. I've been trying to create a polar plot with x number of bins where the data in the bin is averaged and given a colour associated with that value. This seems to work fine while using the plt.fill command where I can...
`colorbar` needs things to be an instance of `ScalarMappable` in order to make a colorbar from them. Because you're manually setting each tile, there's nothing that essentially has a colorbar. There are a number of ways to fake it from your colormap, but in this case there's a much simpler solution. `pcolormesh` doe...
selecting across multiple columns with python pandas?
8,916,302
22
2012-01-18T19:41:27Z
8,916,746
32
2012-01-18T20:12:06Z
[ "python", "csv", "numpy", "tab-delimited", "pandas" ]
I have a dataframe df in pandas that was built using `pandas.read_table` from a csv file. The dataframe has several columns and it is indexed by one of the columns (which is unique, in that each row has a unique value for that column used for indexing.) How can I select rows of my dataframe based on a "complex" filter...
I encourage you to pose these questions on the [mailing list](http://groups.google.com/group/pystatsmodels), but in any case, it's still a very much low level affair working with the underlying NumPy arrays. For example, to select rows where the value in any column exceed, say, 1.5 in this example: ``` In [11]: df Out...
finding a value in dict?
8,917,068
2
2012-01-18T20:40:29Z
8,917,088
10
2012-01-18T20:42:37Z
[ "python", "dictionary", "find" ]
I am trying to print out a message. If a word in dictionary is not found then it should print out a message instead of giving an error. What I thought is ``` if bool(bool(dictionary[word])) == True: return dictionary[word] else: print 'wrong' ``` but it does not work when I write something that is not in dict...
You need to use the `in` operator to test whether or not a key is in the dictionary. With your variable names this becomes: ``` if word in dictionary: ``` If you wish to check for the presence of the key and retrieve the value in one go you can use the [`get()`](http://docs.python.org/library/stdtypes.html#dict.get) ...
Easiest way to build [0, 0, ..., 0] (with n zeroes)
8,917,300
2
2012-01-18T20:58:05Z
8,917,311
15
2012-01-18T20:58:38Z
[ "python" ]
How can I build `[0, 0, ..., 0]`, a list with `n` zeroes? I've tried ``` for i in range(0, n): a[i] = 0 ``` but that throws an error.
``` [0] * n ``` If you want `n` mutable objects instead of `n` zeros, use a list comprehension, e.g.: ``` [[] for dummy in range(n)] ```
Center of mass of a numpy array, how to make less verbose?
8,917,478
3
2012-01-18T21:12:20Z
8,917,508
8
2012-01-18T21:14:14Z
[ "python", "numpy" ]
From what I know of numpy, [it's a bad idea](http://stackoverflow.com/questions/6559463/why-is-numpy-array-so-slow) to apply an operation to each row of an array one at a time. Broadcasting is clearly the prefered method. Given that, how do I take data with a shape `(N,3)` and translate it to the center of mass? Below ...
Try ``` R -= R.sum(0) / len(R) ``` instead. Broadcasting will automatically do The Right Thing.
Center of mass of a numpy array, how to make less verbose?
8,917,478
3
2012-01-18T21:12:20Z
8,917,713
8
2012-01-18T21:29:24Z
[ "python", "numpy" ]
From what I know of numpy, [it's a bad idea](http://stackoverflow.com/questions/6559463/why-is-numpy-array-so-slow) to apply an operation to each row of an array one at a time. Broadcasting is clearly the prefered method. Given that, how do I take data with a shape `(N,3)` and translate it to the center of mass? Below ...
As you've defined it, you can simplify your center of mass calculation as: ``` R -= R.mean(axis=0) ``` If the different elements of your array have different masses defined in `mass`, I would then use: ``` R -= np.average(R,axis=0,weights=mass) ``` See <http://docs.scipy.org/doc/numpy/reference/generated/numpy.aver...
Which version of Python do I have installed?
8,917,885
151
2012-01-18T21:43:13Z
8,917,907
230
2012-01-18T21:45:51Z
[ "python", "version", "windows-server" ]
I have to run a Python script on a Windows server. How can I know which version of Python I have, and does it even really matter? I was thinking of updating to latest version of Python.
``` python -V ``` <http://docs.python.org/using/cmdline.html#generic-options> `--version` may also work (introduced in version 2.5)
Which version of Python do I have installed?
8,917,885
151
2012-01-18T21:43:13Z
8,917,909
73
2012-01-18T21:45:52Z
[ "python", "version", "windows-server" ]
I have to run a Python script on a Windows server. How can I know which version of Python I have, and does it even really matter? I was thinking of updating to latest version of Python.
Python 2.5+: ``` python --version ``` Python 2.4-: ``` python -c 'import sys; print(sys.version)' ```
Which version of Python do I have installed?
8,917,885
151
2012-01-18T21:43:13Z
8,917,910
22
2012-01-18T21:45:54Z
[ "python", "version", "windows-server" ]
I have to run a Python script on a Windows server. How can I know which version of Python I have, and does it even really matter? I was thinking of updating to latest version of Python.
At a command prompt type: ``` python -V ```
Which version of Python do I have installed?
8,917,885
151
2012-01-18T21:43:13Z
8,917,940
19
2012-01-18T21:47:31Z
[ "python", "version", "windows-server" ]
I have to run a Python script on a Windows server. How can I know which version of Python I have, and does it even really matter? I was thinking of updating to latest version of Python.
When I open `Python (command line)` the first thing it tells me is the version.
Which version of Python do I have installed?
8,917,885
151
2012-01-18T21:43:13Z
20,896,732
31
2014-01-03T04:47:53Z
[ "python", "version", "windows-server" ]
I have to run a Python script on a Windows server. How can I know which version of Python I have, and does it even really matter? I was thinking of updating to latest version of Python.
in a Python IDE just copy and paste in the following code and run it (the version will come up in the output area) ``` import sys print(sys.version) ```
Which version of Python do I have installed?
8,917,885
151
2012-01-18T21:43:13Z
30,556,752
11
2015-05-31T11:17:35Z
[ "python", "version", "windows-server" ]
I have to run a Python script on a Windows server. How can I know which version of Python I have, and does it even really matter? I was thinking of updating to latest version of Python.
Although the question is "which version am I using?", this may not actually be everything you need to know. You may have other versions installed and this can cause problems, particularly when installing additional modules. This is my rough-and-ready approach to finding out what versions are installed: ``` updatedb ...
Installing lapack for numpy
8,917,977
23
2012-01-18T21:50:16Z
8,943,520
9
2012-01-20T15:12:09Z
[ "python", "numpy", "installation", "lapack" ]
Running Ubuntu 11.10 + python2.7...built numpy from source and installed it, but when I go to install it, I get ``` ImportError: /usr/lib/liblapack.so.3gf: undefined symbol: ATL_chemv ``` when it tries to import lapack\_lite from numpy.linalg. I tried to rebuild lapack from scratch, but it seems to just make ``` /us...
According to some bugreports I see around, you may have more than one provider of BLAS/ATLAS/LAPACK installed, like ATLAS and OpenBLAS/GotoBLAS, that conflict with each other. Have a look on this: ``` $ ls -l /etc/alternatives/*.so.3gf ``` and check that all them correspond to the same package (eg. they all point int...
Installing lapack for numpy
8,917,977
23
2012-01-18T21:50:16Z
9,713,071
50
2012-03-15T02:11:10Z
[ "python", "numpy", "installation", "lapack" ]
Running Ubuntu 11.10 + python2.7...built numpy from source and installed it, but when I go to install it, I get ``` ImportError: /usr/lib/liblapack.so.3gf: undefined symbol: ATL_chemv ``` when it tries to import lapack\_lite from numpy.linalg. I tried to rebuild lapack from scratch, but it seems to just make ``` /us...
I was having the same problem and removing the package libopenblas-base did the trick: ``` sudo apt-get remove libopenblas-base ``` As already explained by others, several packages provide incompatible versions of liblapack.so.3gf.
Getting a raw, unparsed HTTP response
8,918,350
8
2012-01-18T22:18:48Z
8,918,484
13
2012-01-18T22:29:31Z
[ "python", "http-headers", "http-request" ]
Are there any straightforward ways to make a HTTP request and get at the raw, unparsed response (specifically the headers)?
Using the [socket](http://docs.python.org/library/socket.html) module directly: ``` import socket CRLF = "\r\n" request = [ "GET / HTTP/1.1", "Host: www.example.com", "Connection: Close", "", "", ] # Connect to the server s = socket.socket() s.connect(('www.example.com', 80)) # Send an HTTP req...
Most Pythonic Way to Generate Random Strings of Fixed Length From Given Characters
8,919,351
3
2012-01-19T00:04:27Z
8,919,404
9
2012-01-19T00:10:49Z
[ "string", "random", "python" ]
This is a spin-off of [one of my earlier questions](http://stackoverflow.com/questions/8919080/built-in-method-to-generate-random-strings-of-fixed-length-from-given-characters) Problem statement: Given a number `N` and an arbitrary (but non-empty) `set`/`string`/`list` of characters `E`, return a random string of leng...
``` ''.join(random.sample(E*N, N)) ``` although that won't work with sets, come to think of it. But frankly, ``` ''.join(random.choice(E) for i in xrange(N)) ``` is already pretty Pythonic -- it's simple, clear, and expressive. The pythonicness that needs hours of thought is not the true pythonicness.
financial python library that has xirr and xnpv function?
8,919,718
5
2012-01-19T00:52:37Z
11,503,492
7
2012-07-16T11:39:08Z
[ "python", "financial" ]
numpy has irr and npv function, but I need xirr and xnpv function. this link points out that xirr and xnpv will be coming soon. <http://www.projectdirigible.com/documentation/spreadsheet-functions.html#coming-soon> Is there any python library that has those two functions? tks.
With the help of various implementations I found in the net, I came up with a python implementation: ``` def xirr(transactions): years = [(ta[0] - transactions[0][0]).days / 365.0 for ta in transactions] residual = 1 step = 0.05 guess = 0.05 epsilon = 0.0001 limit = 10000 while abs(residual...
Python practices: Is there a better way to check constructor parameters?
8,919,952
4
2012-01-19T01:28:08Z
8,920,168
9
2012-01-19T01:59:04Z
[ "exception", "python" ]
I find myself trying to convert constructor parameters to their right types very often in my Python programs. So far I've been using code similar to this, so I don't have to repeat the exception arguments: ``` class ClassWithThreads(object): def __init__(self, num_threads): try: self.num_thread...
When I have a question like this, I go hunting in the standard library for code that I can model my code after. [multiprocessing/pool.py](http://hg.python.org/cpython/file/a08e9e84f33f/Lib/multiprocessing/pool.py#l107) has a class somewhat close to yours: ``` class Pool(object): def __init__(self, processes=None,...
improved sprintf for PHP
8,920,139
4
2012-01-19T01:55:48Z
8,920,180
8
2012-01-19T02:01:17Z
[ "php", "python", "printf" ]
Does anyone know a better implementation of **sprintf** in *PHP*? I was looking for something like the string formatting we have in python: ``` print "Hello %(name)s. Your %(name)s has just been created!" % { 'name' : 'world' } # prints::: Hello world. Your world has just been created! ``` This is pretty handy to avo...
You can use positional (but not named) arguments to do this, for example ``` printf('Hello %1$s. Your %1$s has just been created!', 'world'); ``` A word of caution here: you must use *single* quotes, otherwise the dollar signs will cause PHP to try to substitute `$s` with the value of this variable (which does not ex...
Finding a list of all double-underscore variables?
8,920,341
9
2012-01-19T02:30:31Z
8,920,369
9
2012-01-19T02:35:48Z
[ "python", "metadata", "convention" ]
Related: [What is the common header format of Python files?](http://stackoverflow.com/questions/1523427/python-what-is-the-common-header-format) **Where can I find a list of all double-underscore variables/keywords that are commonly used in Python?** In Python, variables starting and ending with double underscores ar...
The complete list used by Python is given in the [Python Language Reference section 3, "Data model"](http://docs.python.org/reference/datamodel.html). Every other one is non-standard or used by third-party modules and is documented separately.
Finding a list of all double-underscore variables?
8,920,341
9
2012-01-19T02:30:31Z
8,920,403
15
2012-01-19T02:40:18Z
[ "python", "metadata", "convention" ]
Related: [What is the common header format of Python files?](http://stackoverflow.com/questions/1523427/python-what-is-the-common-header-format) **Where can I find a list of all double-underscore variables/keywords that are commonly used in Python?** In Python, variables starting and ending with double underscores ar...
If you want to see magic names whether documented or not, go to the Lib directory and run: ``` egrep -oh '__[A-Za-z_][A-Za-z_0-9]*__' *.py | sort | uniq ``` That produces: ``` '__all__' '__args__' '__author__' '__bases__' '__builtin__' '__builtins__' '__cached__' '__call__' '__class__' '__copy__' '__credits__' '__da...
Cancel an already executing task with Celery?
8,920,643
50
2012-01-19T03:21:23Z
8,924,116
87
2012-01-19T10:02:45Z
[ "python", "django", "celery", "message-passing" ]
I have been reading the doc and searching but cannot seem to find a straight answer: Can you cancel an already executing task? (as in the task has started, takes a while, and half way through it needs to be cancelled) I found this from the doc at [Celery FAQ](http://docs.celeryproject.org/en/latest/faq.html#can-i-can...
*revoke* cancels the task execution. If a task is revoked, the workers ignore the task and do not execute it. If you don't use persistent revokes your task can be executed after worker's restart. <http://docs.celeryproject.org/en/latest/userguide/workers.html#worker-persistent-revokes> revoke has an terminate option ...
Cancel an already executing task with Celery?
8,920,643
50
2012-01-19T03:21:23Z
25,561,389
8
2014-08-29T03:44:43Z
[ "python", "django", "celery", "message-passing" ]
I have been reading the doc and searching but cannot seem to find a straight answer: Can you cancel an already executing task? (as in the task has started, takes a while, and half way through it needs to be cancelled) I found this from the doc at [Celery FAQ](http://docs.celeryproject.org/en/latest/faq.html#can-i-can...
In Celery 3.1, the [API of revoking tasks](http://celery.readthedocs.org/en/latest/userguide/workers.html#revoke-revoking-tasks) is changed. According to the [Celery FAQ](http://celery.readthedocs.org/en/latest/faq.html#can-i-cancel-the-execution-of-a-task), you should use result.revoke: ``` >>> result = add.apply_as...
Issue with virtualenv - cannot activate
8,921,188
23
2012-01-19T04:54:37Z
8,921,211
74
2012-01-19T04:57:50Z
[ "python", "virtualenv" ]
I created a virtualenv around my project, but when I try to activate it I cannot. It might just be syntax or folder location, but I am stumped right now. You can see below, I create the virtualenv and call it venv. Everything looks good, then I try to activate it by running `source venv/bin/activate` I'm thinking it ...
`source` is a shell command designed for users running on Linux (or any Posix, but whatever, not Windows). On Windows, virtualenv creates a batch file, so you should run `venv\Scripts\activate.bat` instead (per the virtualenv [documentation on the activate script](http://pypi.python.org/pypi/virtualenv#activate-script...
How do I plot a step function with Matplotlib in Python?
8,921,296
21
2012-01-19T05:07:55Z
8,921,565
31
2012-01-19T05:41:45Z
[ "python", "plot", "matplotlib" ]
This should be easy but I have just started toying with matplotlib and python. I can do a line or a scatter plot but i am not sure how to do a simple step function. Any help is much appreciated. ``` x = 1,2,3,4 y = 0.002871972681775004, 0.00514787917410944, 0.00863476098280219, 0.012003316194034325 ```
It seems like you want [`step`](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.step). E.g. ``` import matplotlib.pyplot as plt x = [1,2,3,4] y = [0.002871972681775004, 0.00514787917410944, 0.00863476098280219, 0.012003316194034325] plt.step(x, y) plt.show() ``` ![enter image descrip...
How do I plot a step function with Matplotlib in Python?
8,921,296
21
2012-01-19T05:07:55Z
28,343,910
7
2015-02-05T12:24:29Z
[ "python", "plot", "matplotlib" ]
This should be easy but I have just started toying with matplotlib and python. I can do a line or a scatter plot but i am not sure how to do a simple step function. Any help is much appreciated. ``` x = 1,2,3,4 y = 0.002871972681775004, 0.00514787917410944, 0.00863476098280219, 0.012003316194034325 ```
If you have non-uniformly spaced data points, you can use the [`drawstyle`](http://matplotlib.org/api/lines_api.html#matplotlib.lines.Line2D.set_drawstyle) keyword argument for `plot`: ``` x = [1,2.5,3.5,4] y = [0.002871972681775004, 0.00514787917410944, 0.00863476098280219, 0.012003316194034325] plt.plot(x, y...
In Python, how to list all characters matched by POSIX extended regex `[:space:]`?
8,921,365
10
2012-01-19T05:16:58Z
8,922,773
17
2012-01-19T08:04:22Z
[ "python", "regex", "unicode" ]
In Python, how to list all characters matched by POSIX extended regex `[:space:]`? Is there a programmatic way of extracting the Unicode code points covered by `[:space:]`?
Using a generator instead of a list comprehension, and `xrange` instead of `range`: ``` >>> s = u''.join(unichr(c) for c in xrange(0x10ffff+1)) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <genexpr> ValueError: unichr() arg not in range(0x10000) (narrow Python b...
How to trace the path in a Breadth-First Search?
8,922,060
44
2012-01-19T06:45:18Z
8,922,151
90
2012-01-19T06:56:03Z
[ "python", "algorithm", "graph", "breadth-first-search" ]
How do you trace the path of a Breadth-First Search, such that in the following example: ![](http://upload.wikimedia.org/wikipedia/commons/thumb/3/33/Breadth-first-tree.svg/300px-Breadth-first-tree.svg.png) If searching for key `11`, return the **shortest** list connecting 1 to 11. ``` [1, 4, 7, 11] ```
You should have look at <http://en.wikipedia.org/wiki/Breadth-first_search> first. --- Below is a quick implementation, in which I used a list of list to represent the queue of paths. ``` # graph is in adjacent list representation graph = { '1': ['2', '3', '4'], '2': ['5', '6'], '5': ['9', '1...
How to trace the path in a Breadth-First Search?
8,922,060
44
2012-01-19T06:45:18Z
25,583,948
9
2014-08-30T15:26:26Z
[ "python", "algorithm", "graph", "breadth-first-search" ]
How do you trace the path of a Breadth-First Search, such that in the following example: ![](http://upload.wikimedia.org/wikipedia/commons/thumb/3/33/Breadth-first-tree.svg/300px-Breadth-first-tree.svg.png) If searching for key `11`, return the **shortest** list connecting 1 to 11. ``` [1, 4, 7, 11] ```
I liked qiao's first answer very much! The only thing missing here is to mark the vertexes as visited. Why we need to do it? Lets imagine that there is another node number 13 connected from node 11. Now our goal is to find node 13. After a little bit of a run the queue will look like this: ``` [[1, 2, 6], [1,...
Adding values to a list in a list in Python
8,922,076
3
2012-01-19T06:47:22Z
8,922,105
7
2012-01-19T06:50:22Z
[ "python", "list", "append" ]
I'm so new to Python that the only way I can code so far is by blindly waving my keyboard around. So I'm sure there's an excellent reason why the following doesn't work: ``` l = [] grouping = compactlist.index(namelist[n]) l[grouping].append(start[n]) l[grouping].append(end[n]) ``` So what I'm trying to do is take a...
You could initiate l like `l = [[], []]`, but it actually sounds more like you want to use a defaultdict as your data structure. This can create your lists on the fly, e.g. ``` >>> import collections >>> thing = collections.defaultdict(list) >>> thing[0].append('spam') >>> thing[1].append('eggs') >>> print thing defau...
string to list conversion in python?
8,923,484
7
2012-01-19T09:11:42Z
8,923,523
12
2012-01-19T09:16:18Z
[ "python", "regex" ]
I have a string like : ``` searchString = "u:sads asdas asdsad n:sadasda as:adds sdasd dasd a:sed eee" ``` what I want is list : ``` ["u:sads asdas asdsad","n:sadasda","as:adds sdasd dasd","a:sed eee"] ``` What I have done is : ``` values = re.split('\s', searchString) mylist = [] word = '' for elem in values: i...
Use regular expressions: ``` import re mylist= re.split('\s+(?=\w+:)', searchString) ``` This splits the string everywhere there's a space followed by one or more letters and a colon. The look-ahead (`(?=` part) makes it split on the whitespace while keeping the `\w+:` parts
Matching only a unicode letter in Python re
8,923,949
19
2012-01-19T09:49:58Z
8,923,988
36
2012-01-19T09:52:59Z
[ "python", "regex", "unicode", "character-properties" ]
I have a string from which i want to extract 3 groups: ``` '19 janvier 2012' -> '19', 'janvier', '2012' ``` Month name could contain non ASCII characters, so `[A-Za-z]` does not work for me: ``` >>> import re >>> re.search(ur'(\d{,2}) ([A-Za-z]+) (\d{4})', u'20 janvier 2012', re.UNICODE).groups() (u'20', u'janvier',...
You can construct a new character class: ``` [^\W\d_] ``` instead of `\w`. Translated into English, it means "Any character that is not a non-alphanumeric character (`[^\W]` is the same as `\w`), but that is also not a digit and not an underscore". Therefore, it will only allow Unicode letters (if you use the `re.UN...
How do I print bold text in Python?
8,924,173
41
2012-01-19T10:06:01Z
8,924,337
7
2012-01-19T10:17:44Z
[ "python" ]
How do I print bold text in Python? For example: ``` print "hello" ``` What should I do so that the text “hello” is displayed in bold?
There is a very useful [module](http://nadiana.com/python-curses-terminal-controller) for formatting text (bold, underline, colors..) in Python. It uses `curses` lib but it's very straight-forward to use. An example: ``` from terminal import render print render('%(BG_YELLOW)s%(RED)s%(BOLD)sHey this is a test%(NORMAL)...
How do I print bold text in Python?
8,924,173
41
2012-01-19T10:06:01Z
8,925,939
7
2012-01-19T12:21:37Z
[ "python" ]
How do I print bold text in Python? For example: ``` print "hello" ``` What should I do so that the text “hello” is displayed in bold?
Check out [colorama](http://pypi.python.org/pypi/colorama). It doesn't necessarily help with bolding... but you can do colorized output on both Windows and Linux, and control the brightness: ``` from colorama import * init(autoreset=True) print Fore.RED + 'some red text' print Style.BRIGHT + Fore.RED + 'some bright re...
How do I print bold text in Python?
8,924,173
41
2012-01-19T10:06:01Z
8,930,747
10
2012-01-19T17:44:29Z
[ "python" ]
How do I print bold text in Python? For example: ``` print "hello" ``` What should I do so that the text “hello” is displayed in bold?
In straight-up computer programming, there is no such thing as "printing bold text". Let's back up a bit and understand that your text is a string of bytes and bytes are just bundles of bits. To the computer, here's your "hello" text, in [binary](http://en.wikipedia.org/wiki/Binary_numeral_system). ``` 011010000110010...
How do I print bold text in Python?
8,924,173
41
2012-01-19T10:06:01Z
11,784,589
20
2012-08-02T19:37:15Z
[ "python" ]
How do I print bold text in Python? For example: ``` print "hello" ``` What should I do so that the text “hello” is displayed in bold?
Use this: ``` print '\033[1m' + 'Hello' ``` And to change back to normal: ``` print '\033[0m' ``` [This page](http://ascii-table.com/ansi-escape-sequences.php) is a good reference for printing in colors and font-weights. Go to the section that says 'Set graphics mode:' And note this won't work on all operating sys...
How do I print bold text in Python?
8,924,173
41
2012-01-19T10:06:01Z
17,303,428
97
2013-06-25T17:10:12Z
[ "python" ]
How do I print bold text in Python? For example: ``` print "hello" ``` What should I do so that the text “hello” is displayed in bold?
``` class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' print color.BOLD + 'Hello World !' + color.END ```
How can I change a Django form field value before saving?
8,924,993
16
2012-01-19T11:06:14Z
8,928,758
22
2012-01-19T15:31:57Z
[ "python", "django", "forms", "model", "save" ]
``` if request.method == 'POST': userf = UsersModelForm(request.POST) username = userf.data['username'] password = userf.data['password'] passwordrepeat = userf.data['passwordrepeat'] email = userf.data['email'] ``` I tried this: ``` tempSalt = bcrypt.gensalt() password = bcrypt.hashpw(pas...
If you need to do something to the data before saving, just create a function like: ``` def clean_nameofdata(self): data = self.cleaned_data['nameofdata'] # do some stuff return data ``` All you need is to create a function with the name \*\*clean\_\*\*\*nameofdata\* where *nameofdata* is the name of the ...
Convert base-2 binary number string to int
8,928,240
119
2012-01-19T15:01:45Z
8,928,256
192
2012-01-19T15:02:39Z
[ "python" ]
I'd simply like to convert a base-2 binary number string into an int, something like this: ``` >>> '11111111'.fromBinaryToInt() 255 ``` Is there a way to do this in Python?
You use the built-in `[int()` function][1], and pass it the base of the input number, i.e. `2` for a binary number: ``` >>> int('11111111', 2) 255 ``` **Update**: I removed the use of `print` so the above "code" is now compatible with either, as pointed out in a comment. The documentation link is also just to the cur...
Convert base-2 binary number string to int
8,928,240
119
2012-01-19T15:01:45Z
8,928,333
16
2012-01-19T15:06:51Z
[ "python" ]
I'd simply like to convert a base-2 binary number string into an int, something like this: ``` >>> '11111111'.fromBinaryToInt() 255 ``` Is there a way to do this in Python?
Another way to do this is by using the [`bitstring`](http://packages.python.org/bitstring/index.html#) module: ``` >>> from bitstring import BitArray >>> b = BitArray(bin='11111111') >>> b.uint 255 ``` Note that the unsigned integer is different from the signed integer: ``` >>> b.int -1 ``` The `bitstring` module i...
Convert base-2 binary number string to int
8,928,240
119
2012-01-19T15:01:45Z
28,163,012
9
2015-01-27T04:00:03Z
[ "python" ]
I'd simply like to convert a base-2 binary number string into an int, something like this: ``` >>> '11111111'.fromBinaryToInt() 255 ``` Is there a way to do this in Python?
Just type **0b11111111** in python interactive interface: ``` >>> 0b11111111 255 ```
Python: splitting string by all space characters
8,928,557
26
2012-01-19T15:20:14Z
8,928,710
17
2012-01-19T15:28:40Z
[ "python", "whitespace" ]
To split strings by spaces in python, one usually uses `split` method of the string without parameters: ``` >>> 'a\tb c\nd'.split() ['a', 'b', 'c', 'd'] ``` But yesterday I ran across a string that used [ZERO WIDTH SPACE](http://en.wikipedia.org/wiki/Zero-width_space) between words as well. Having turned my new knowl...
**Edit** It turns out that \u200b is not technically defined as whitespace , and so python does not recognize it as matching \s even with the unicode flag on. So it must be treated as an non-whitespace character. <http://en.wikipedia.org/wiki/Whitespace_character#Unicode> <http://bugs.python.org/issue13391> ``` imp...
Processing HTTP GET input parameter on server side in python
8,928,730
5
2012-01-19T15:29:37Z
8,929,395
7
2012-01-19T16:14:02Z
[ "python", "http", "get", "webserver" ]
I wrote a simple HTTP client and server in python for experienmenting. The first code snippet below shows how I send an HTTP get request with a parameter namely imsi. In the second code snippet I show my doGet function implementation in the server side. My question is how I can extract the imsi parameter in the server ...
You can parse the query of a GET request using urlparse, then split the query string. ``` from urlparse import urlparse query = urlparse(self.path).query query_components = dict(qc.split("=") for qc in query.split("&")) imsi = query_components["imsi"] # query_components = { "imsi" : "Hello" } # Or use the parse_qs me...
Unittest (sometimes) fails because floating-point imprecision
8,929,005
25
2012-01-19T15:49:13Z
8,929,183
47
2012-01-19T16:00:07Z
[ "python", "unit-testing", "floating-point" ]
I have a class *Vector* that represents a point in 3-dimensional space. This vector has a method `normalize(self, length = 1)` which scales the vector down/up to be `length == vec.normalize(length).length`. The unittest for this method **sometimes** fails because of the imprecision of floating-point numbers. My questi...
### 1) How can I make sure the test works? Use `assertAlmostEqual`, `assertNotAlmostEqual`. From the [official documentation](http://docs.python.org/library/unittest.html#unittest.TestCase.assertAlmostEqual): ``` assertAlmostEqual(first, second, places=7, msg=None, delta=None) ``` *Test that first and second are ap...
What makes sets faster than lists in python?
8,929,284
7
2012-01-19T16:06:25Z
8,929,320
11
2012-01-19T16:08:27Z
[ "python" ]
The python wiki says: "Membership testing with sets and dictionaries is much faster, O(1), than searching sequences, O(n). When testing "a in b", b should be a set or dictionary instead of a list or tuple." I've been using sets in place of lists whenever speed is important in my code, but lately I've been wondering wh...
Sets are implemented using [hash tables](http://en.wikipedia.org/wiki/Hash_table). Whenever you add an object to a set, the position within the memory of the `set` object is determined using the hash of the object to be added. When testing for membership, all that needs to be done is basically to look if the object is ...
What makes sets faster than lists in python?
8,929,284
7
2012-01-19T16:06:25Z
8,929,445
18
2012-01-19T16:17:53Z
[ "python" ]
The python wiki says: "Membership testing with sets and dictionaries is much faster, O(1), than searching sequences, O(n). When testing "a in b", b should be a set or dictionary instead of a list or tuple." I've been using sets in place of lists whenever speed is important in my code, but lately I've been wondering wh...
**`list`**: Imagine you are looking for your socks in your closet, but you don't know in which drawer your socks are, so you have to search drawer by drawer until you find them (or maybe you never do). That's what we call `O(n)`, because in the worst scenario, you will look in all your drawers (where `n` is the number ...