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
Function doesn't stop after "return(False)"
13,904,460
3
2012-12-16T18:54:10Z
13,904,558
8
2012-12-16T19:05:02Z
[ "python", "python-3.x" ]
I am trying to write a function which is supposed to compare list structures (the values are indifferent). The problem is that I have two lists which are unequal but the function still returns `True` even though it actually goes into the `else` part. I don't understand why and what I did wrong. Here is my code: ``` de...
The problem is that when your function calls itself recursively: ``` ListeIsomorf(i,j) ``` it ignores the returned value. Thus the comparisons that take place at the second level of recursion have no effect on what the top level returns. Changing the above to: ``` if not ListeIsomorf(i,j): ...
Is the behaviour of Python's list += iterable documented anywhere?
13,904,493
24
2012-12-16T18:58:00Z
13,904,692
14
2012-12-16T19:22:45Z
[ "python", "operators", "containers" ]
It would appear that in Python 2, `list += x` works for any iterable `x`: ``` In [6]: l = [] In [7]: l += [1] In [8]: l += (2, 3) In [9]: l += xrange(5) In [10]: l Out[10]: [1, 2, 3, 0, 1, 2, 3, 4] ``` Is this behaviour documented anywhere? To contrast this with `list + x`, the latter only works if `x` is also a...
From [Guido van Rossum](https://plus.google.com/118069851186709403898/posts/YoNDMKjTuJh): > It works the same way as `.extend()` except that it also returns `self`. I > can't find docs explaining this. :-( Here is the relevant source code taken from [`listobject.c`](http://hg.python.org/cpython/file/2d2d4807a3ed/Obje...
ZeroMQ and multiple subscribe filters in Python
13,904,626
10
2012-12-16T19:14:14Z
13,905,459
15
2012-12-16T21:03:09Z
[ "python", "zeromq" ]
I'd like to subscribe to multiple filters with ZeroMQ in Python, using one socket. ``` sock.setsockopt(zmq.SUBSCRIBE, 'first.filter') sock.setsockopt(zmq.SUBSCRIBE, 'second.filter') ``` But this doesn't work. Only the first one is taken in account. However I read this on [zeromq site](http://api.zeromq.org/2-2%3azmq...
This works: ``` import time import zmq ctx = zmq.Context() pub = ctx.socket(zmq.PUB) sub = ctx.socket(zmq.SUB) url = "tcp://127.0.0.1:5555" pub.bind(url) sub.connect(url) # subscribe to 'a' and 'b' sub.setsockopt(zmq.SUBSCRIBE, b'a') sub.setsockopt(zmq.SUBSCRIBE, b'b') time.sleep(1) for word in [ 'alpha', 'beta',...
Why must Python list addition be homogenous?
13,905,008
23
2012-12-16T20:04:24Z
13,905,379
11
2012-12-16T20:53:52Z
[ "python", "language-design", "language-implementation", "python-internals" ]
Can anyone familiar with Python's internals (CPython, or other implementations) explain why list addition is required to be homogenous: ``` In [1]: x = [1] In [2]: x+"foo" --------------------------------------------------------------------------- TypeError Traceback (most recent call ...
From the Zen of Python: > In the face of ambiguity, refuse the temptation to guess. Let's look at what happens here: ``` x + y ``` This gives us a value, but of what type? When we add things in real life, we expect the type to be the same as the input types, but what if they are disparate? Well, in the real world, ...
Why must Python list addition be homogenous?
13,905,008
23
2012-12-16T20:04:24Z
13,915,436
8
2012-12-17T13:50:22Z
[ "python", "language-design", "language-implementation", "python-internals" ]
Can anyone familiar with Python's internals (CPython, or other implementations) explain why list addition is required to be homogenous: ``` In [1]: x = [1] In [2]: x+"foo" --------------------------------------------------------------------------- TypeError Traceback (most recent call ...
These bug reports suggest that this design quirk was a mistake. [Issue12318](http://bugs.python.org/issue12318): > Yes, this is the expected behavior and yes, it is inconsistent. > > It's been that way for a long while and Guido said he wouldn't do it again (it's in his list of regrets). However, we're not going to b...
Difference between union() and union_update() in sets, and others?
13,905,640
3
2012-12-16T21:27:47Z
13,905,662
10
2012-12-16T21:29:37Z
[ "python", "set", "set-operations" ]
Python sets have these methods: ``` s.union(t) s | t new set with elements from both s and t s.update(t) s |= t return set s with elements added from t ``` Likewise, there's also these: ``` s.intersection_update(t) s &= t return set s keeping only elements also found in t s.intersection(t) s & t new se...
They are *very* different. One set changes the set *in place*, while the other leaves the original set alone, and returns a *copy* instead. ``` >>> s = {1, 2, 3} >>> news = s | {4} >>> s set([1, 2, 3]) >>> news set([1, 2, 3, 4]) ``` Note how `s` has remained unchanged. ``` >>> s.update({4}) >>> s set([1, 2, 3, 4]) `...
Accessing class variables from a list comprehension in the class definition
13,905,741
62
2012-12-16T21:42:22Z
13,913,933
91
2012-12-17T12:11:56Z
[ "python", "python-3.x", "scope", "list-comprehension", "python-internals" ]
How do you access other class variables from a list comprehension within the class definition? The following works in Python 2 but fails in Python 3: ``` class Foo: x = 5 y = [x for i in range(1)] ``` Python 3.2 gives the error: ``` NameError: global name 'x' is not defined ``` Trying `Foo.x` doesn't work e...
*Class scope and list, set or dictionary comprehensions, as well as generator expressions do not mix.* ## The why; or, the official word on this In Python 3, list comprehensions were given a proper scope (local namespace) of their own, to prevent their local variables bleeding over into the surrounding scope (see [Py...
converting integer to list in python
13,905,936
14
2012-12-16T22:06:02Z
13,905,946
37
2012-12-16T22:07:10Z
[ "python", "list", "integer", "type-conversion" ]
What is the quickest and cleanest way to convert an `integer` into a `list`? For example, change `132` into `[1,3,2]` and `23` into `[2,3]`. I have a variable which is an `int`, and I want to be able to compare the individual digits so I thought making it into a list would be best, since I can just do `int(number[0])`...
Convert the integer to string first, and then use `map` to apply `int` on it: ``` >>> num = 132 >>> map(int, str(num)) #note, This will return a map object in python 3. [1, 3, 2] ``` or using a list comprehension: ``` >>> [int(x) for x in str(num)] [1, 3, 2] ```
installing/using cx_freeze
13,906,343
7
2012-12-16T23:03:45Z
16,759,159
13
2013-05-26T12:20:00Z
[ "python", "windows", "cx-freeze" ]
I am trying to compile a python program and I am using python 3.2. So I downloaded **cx\_freeze** and installed it. When I try to run the **setup.py** in cmd it says: ``` "importerror: no module named cx_freeze" ``` I have removed **cx\_freeze** and tried to re-install it, this time however, in the **"select the loca...
Finally found the solution to this problem! Been trying for two days and a programmer friend helped me (I'm not a programmer myself). So, when you type in "python setup.py build" to cmd, what it tries to do is look for python.exe in the folder you are in, and if it doesn't find it there then looks to system paths (whi...
Using pickle.dump - TypeError: must be str, not bytes
13,906,623
62
2012-12-16T23:42:03Z
13,906,715
116
2012-12-16T23:56:24Z
[ "python", "python-3.x", "pickle" ]
I'm using python3.3 and I'm having a cryptic error when trying to pickle a simple dictionary. Here is the code: ``` import os import pickle from pickle import * os.chdir('c:/Python26/progfiles/') def storvars(vdict): f = open('varstor.txt','w') pickle.dump(vdict,f,) f.close() return mydict = {...
The output file needs to be opened in binary mode: ``` f = open('varstor.txt','w') ``` needs to be: ``` f = open('varstor.txt','wb') ```
TypeError: 'NoneType' object has no attribute '__getitem__'
13,907,949
10
2012-12-17T03:33:28Z
13,908,294
15
2012-12-17T04:32:56Z
[ "python", "typeerror" ]
I'm having an issue and I have no idea why this is happening and how to fix it, I'm working developing a Videogame with python and pygame and I'm getting this error: ``` File "/home/matt/Smoking-Games/sg-project00/project00/GameModel.py", line 15, in Update self.imageDef=self.values[2] TypeError: 'NoneType' objec...
BrenBarn is correct. The error means you tried to do something like `None[5]`. In the backtrace, it says `self.imageDef=self.values[2]`, which means that your `self.values` is `None`. You should go through all the functions that update `self.values` and make sure you account for all the corner cases.
How to pass pointer back in ctypes?
13,908,226
6
2012-12-17T04:22:28Z
13,909,517
7
2012-12-17T06:46:55Z
[ "python", "pointers", "dll", "char", "ctypes" ]
Don't know much about ctypes, just recently began working with it. I have a simple function in C-like dll which returns a pointer to the dynamically generated string. It is working fine, but, because i manually allocated memory for the string, i should free it after use. I have something like this: ``` extern "C" ...
Normally each function you use in `ctypes` should have its arguments and return type declared so Python can check for the correct number and type of arguments and convert Python object arguments to the correct C data objects. Unfortunately in this case, the normal return value for `func` would be `c_char_p`, but `ctype...
How run two different threads simultaneously in pyqt
13,909,195
2
2012-12-17T06:14:13Z
13,909,749
7
2012-12-17T07:07:14Z
[ "python", "multithreading", "qt", "pyqt", "pyqt4" ]
I have a situation where i need to start two threads one after the other. I tried the following code snippet, here i could able to start the Thread12 but not able to start Thread2. How can i start both....? How to start 2 threads one ofter the other...? **Code snippet** ``` class Thread1(QtCore.QThread): Thread1...
You will be using `QRunnable` and `QThreadPool`, something like this: ``` import sys from PyQt4.QtGui import QApplication from PyQt4.QtCore import QThreadPool, QObject, QRunnable, pyqtSignal class WorkerSignals(QObject): result = pyqtSignal(int) class Worker(QRunnable): def __init__(self, task): sup...
Progress of Python requests post
13,909,900
7
2012-12-17T07:21:18Z
13,911,048
11
2012-12-17T09:01:14Z
[ "python", "python-requests" ]
I am uploading a large file using the Python requests package, and I can't find any way to give data back about the progress of the upload. I have seen a number of progress meters for downloading a file, but these will not work for a file upload. The ideal solution would be some sort of callback method such as: ``` d...
`requests` [doesn't support](https://github.com/kennethreitz/requests/issues/295) [upload](https://github.com/kennethreitz/requests/issues/952) [streaming](https://github.com/shazow/urllib3/issues/51) e.g.: ``` import os import sys import requests # pip install requests class upload_in_chunks(object): def __init...
Progress of Python requests post
13,909,900
7
2012-12-17T07:21:18Z
14,953,090
8
2013-02-19T08:38:41Z
[ "python", "python-requests" ]
I am uploading a large file using the Python requests package, and I can't find any way to give data back about the progress of the upload. I have seen a number of progress meters for downloading a file, but these will not work for a file upload. The ideal solution would be some sort of callback method such as: ``` d...
I got it working with the code from here: [Simple file upload progressbar in PyQt](http://foobarnbaz.com/2012/12/31/file-upload-progressbar-in-pyqt/). I changed it a bit, to use BytesIO instead of StringIO. ``` class CancelledError(Exception): def __init__(self, msg): self.msg = msg Exception.__ini...
list with infinite elments
13,910,259
3
2012-12-17T07:55:46Z
13,910,291
10
2012-12-17T07:58:25Z
[ "python" ]
I need to operate on two separate **infinite list** of numbers, but could not find a way to generate, store and operate on it in python. Can any one please suggest me a way to handle infinite Arithmetic Progession or any series and how to operate on them considering the fact the minimal use of memory and time. Thanks...
You are looking for a [python generator](http://wiki.python.org/moin/Generators) instead: ``` def infinitenumbers(): count = 0 while True: yield count count += 1 ``` The `itertools` package comes with a pre-built [`count` generator](http://docs.python.org/2/library/itertools.html#itertools.cou...
How can i use multiple requests and pass items in between them in scrapy python
13,910,357
29
2012-12-17T08:04:00Z
13,911,764
17
2012-12-17T09:51:04Z
[ "python", "scrapy" ]
I have the `item` object and i need to pass that along many pages to store data in single item LIke my item is ``` class DmozItem(Item): title = Field() description1 = Field() description2 = Field() description3 = Field() ``` Now those three description are in three separate pages. i want to do somre...
No problem. Instead of ``` def page_parser(self, response): sites = hxs.select('//div[@class="row"]') items = [] request = Request("http://www.example.com/lin1.cpp", callback =self.parseDescription1) request.meta['item'] = item request = Request("http://www.example.com/lin1.cpp", cal...
How can i use multiple requests and pass items in between them in scrapy python
13,910,357
29
2012-12-17T08:04:00Z
16,177,544
12
2013-04-23T19:22:44Z
[ "python", "scrapy" ]
I have the `item` object and i need to pass that along many pages to store data in single item LIke my item is ``` class DmozItem(Item): title = Field() description1 = Field() description2 = Field() description3 = Field() ``` Now those three description are in three separate pages. i want to do somre...
In order to guarantee an ordering of the requests/callbacks and that only one item is ultimately returned you need to chain your requests using a form like: ``` def page_parser(self, response): sites = hxs.select('//div[@class="row"]') items = [] request = Request("http://www.example.com/lin...
How can i use multiple requests and pass items in between them in scrapy python
13,910,357
29
2012-12-17T08:04:00Z
25,571,270
9
2014-08-29T15:16:55Z
[ "python", "scrapy" ]
I have the `item` object and i need to pass that along many pages to store data in single item LIke my item is ``` class DmozItem(Item): title = Field() description1 = Field() description2 = Field() description3 = Field() ``` Now those three description are in three separate pages. i want to do somre...
The accepted answer returns a total of three items [with desc(i) set for i=1,2,3]. If you want to return a single item, Dave McLain's item does work, however it requires `parseDescription1`, `parseDescription2`, and `parseDescription3` to succeed and run without errors in order to return the item. For my use case, so...
Implementing sitemaps in Django
13,911,594
8
2012-12-17T09:39:15Z
16,729,873
12
2013-05-24T07:35:03Z
[ "python", "django", "sitemap" ]
I'm having a problem implementing the sitemaps in my application. I'm using Virtualenv, django 1.4 and Python 2.7. I would appreciate if you can help me resolve this. This is what I have done: 1. In my urls.py ``` from sitemap import JobPostSitemap sitemaps = { 'jobs': JobPostSitemap, } ... #...
I had similar error. I changed urls.py definition like that: ``` from sitemap import JobPostSitemap from django.contrib.sitemaps.views import sitemap sitemaps = { 'jobs': JobPostSitemap, } ... # Removed other urls url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}), ``` and It worked for me. I don't know wh...
Python Sqlite3 Get Sqlite Connection path
13,912,731
4
2012-12-17T10:52:58Z
14,505,973
8
2013-01-24T16:22:32Z
[ "python", "sqlite3" ]
Given an sqlite3 connection object, how can retrieve the file path to the sqlite3 file?
We can use the PRAGMA database\_list command. ``` cur = con.cursor() cur.execute("PRAGMA database_list") rows = cur.fetchall() for row in rows: print row[0], row[1], row[2] ``` The third parameter (row[2]) is the file name of the database. Note that there could be more databases attached to SQLite engine. ``` $...
Why do I get "UserWarning: Module dap was already imported from None ..."
13,915,269
12
2012-12-17T13:39:52Z
13,924,658
24
2012-12-18T00:41:37Z
[ "python", "python-2.7", "matplotlib", "matplotlib-basemap" ]
I have `python-matplotlib` and `python-mpltoolkits.basemap` installed from Ubuntu packages. Installing `python-mpltoolkits.basemap` also installs `python-dap` as a dependency. When I import basemap, I get this warning: ``` >>> import mpl_toolkits.basemap /usr/lib/pymodules/python2.7/mpl_toolkits/__init__.py:2: UserWa...
I can't really say that I'd understand the details, but apparently whenever the package `python-dap` is installed, then trying to `import pkg_resources` gives this warning. [Here](https://bitbucket.org/tarek/distribute/issue/217/userwarning-module-paste-was-already) is some discussion. Following advice from [here](htt...
How to correctly return a list of class instances in Python
13,916,357
2
2012-12-17T14:48:44Z
13,916,404
9
2012-12-17T14:51:30Z
[ "python", "list", "class" ]
``` class ligne(): def __init__ (self, stops): ##stops = a list of instances of Ligne1Stop class self.stops = stops def returnAllStopsOnLigne(self): return self.stops ``` When I call the method returnAllStopsOnLigne() I get a list of ``` "<__main__.ligne1Stop instance at 0x1418828"> ``...
You are looking at the `repr()` representation output of your classes. `repr()` will call the [`__repr__()` hook](http://docs.python.org/2/reference/datamodel.html#object.__repr__) if defined on your custom classes: ``` def __repr__(self): return '<linge1Stop: name={0}>'.format(self.name) ```
Multiple many-to-many relations to the same model in Django
13,918,968
12
2012-12-17T17:26:15Z
13,919,198
17
2012-12-17T17:41:30Z
[ "python", "django", "django-models" ]
Given the following model with two many-to-many relations: ``` class Child(models.Model): name = models.CharField(max_length=80) class Foo(models.Model): bar = models.ManyToManyField(Child) baz = models.ManyToManyField(Child) ``` This gives the error: ``` accounts.foo: Accessor for m2m field 'bar' clash...
I think you need to just give the two fields different related\_names: ``` class Child(models.Model): name = models.CharField(max_length=80) class Foo(models.Model): bar = models.ManyToManyField(Child, related_name="bar") baz = models.ManyToManyField(Child, related_name="baz") ``` If you don't give a related n...
Multiple many-to-many relations to the same model in Django
13,918,968
12
2012-12-17T17:26:15Z
13,919,252
10
2012-12-17T17:44:50Z
[ "python", "django", "django-models" ]
Given the following model with two many-to-many relations: ``` class Child(models.Model): name = models.CharField(max_length=80) class Foo(models.Model): bar = models.ManyToManyField(Child) baz = models.ManyToManyField(Child) ``` This gives the error: ``` accounts.foo: Accessor for m2m field 'bar' clash...
You haven't read Django's documentation carefully enough. [Here](https://docs.djangoproject.com/en/1.4/ref/models/fields/#django.db.models.ManyToManyField.related_name) it says: > If you have more than one ManyToManyField pointing to the same model and want to suppress the backwards relations, set each related\_name t...
Generating a 10000 bit random sequence
13,919,481
5
2012-12-17T17:59:15Z
13,922,797
9
2012-12-17T21:51:04Z
[ "python", "binary" ]
Is there a more efficient way to generate a 10 kBit (10,000 bits) random binary sequence in Python than appending 0s and 1s in a loop?
If you want a random binary sequence then it's probably quickest just to generate a random integer in the appropriate range: ``` import random s = random.randint(0, 2**10000 - 1) ``` After this it really depends on what you want to do with your binary sequence. You can query individual bits using bitwise operations: ...
In python is there a way to know if an object "implements an interface" before I pass it to a function?
13,919,772
10
2012-12-17T18:19:48Z
13,919,820
9
2012-12-17T18:23:07Z
[ "python", "exception", "object", "introspection" ]
I know this may sound like a stupid question, especially to someone who knows python's nature, but I was just wondering, **is there a way to know if an object "implements an interface" so as to say?** To give an example of what I want to say: let's say I have this function: ``` def get_counts(sequence): counts ...
Python (since 2.6) has [abstract base classes](http://docs.python.org/2/glossary.html#term-abstract-base-class) (aka virtual interfaces), which are [more flexible](http://www.python.org/dev/peps/pep-3119/#rationale) than Java or C# interfaces. To check whether an object is iterable, use [`collections.Iterable`](http://...
Update a PyPi package
13,919,830
16
2012-12-17T18:24:01Z
13,919,964
32
2012-12-17T18:32:31Z
[ "python", "pypi" ]
Is there a way to update a PyPi package without changing the version number? Imagine, for a second, that I've found a small bug in a package I recently uploaded to PyPi. Is there a way to edit/re-upload the code without incrementing the version number? **UPDATE** I guess I should clarify that by "bug" I mean the vers...
When you encountered a bug, *always* upload a *new* release. Increase the version number, include a changelog, call it a brown-bag release (it wasn't me, it was someone wearing a brown bag over their heads, really, honestly). You never know whom already may have downloaded a copy of the release (on a mirror, directly...
Not possible to set content-type to application/json using urllib2
13,920,211
9
2012-12-17T18:48:49Z
13,920,427
11
2012-12-17T19:03:36Z
[ "python", "json", "post", "urllib2" ]
This little baby: ``` import urllib2 import simplejson as json opener = urllib2.build_opener() opener.addheaders.append(('Content-Type', 'application/json')) response = opener.open('http://localhost:8000',json.dumps({'a': 'b'})) ``` Produces the following request (as seen with ngrep): ``` sudo ngrep -q -d lo '^POST...
If you want to set custom headers you should use a `Request` object: ``` import urllib2 import simplejson as json opener = urllib2.build_opener() req = urllib2.Request('http://localhost:8000', data=json.dumps({'a': 'b'}), headers={'Content-Type': 'application/json'}) response = opener.open(req) ```
Python: While loop will not terminate
13,920,978
3
2012-12-17T19:40:42Z
13,920,995
9
2012-12-17T19:41:59Z
[ "python", "loops", "while-loop" ]
I have read a lot of topics regarding while loops and I can't find one that tells me what I have done wrong with my own code. I am doing the Learn Python the Hard Way and I wrote this code in order to satisfy the study drill #1 for exercise 33. I cannot figure out why the loop won't terminate when I put in my raw data....
`raw_input` returns a string. when you pass it to your function, you're comparing an integer and a string. Note that this behavior was deprecated in python3.x. You can't compare integers with strings in python 3.x in this way. (It'll raise a `TypeError`). You can remedy this quite easily: ``` number_uno(int(z)) ``` ...
Python one-liner to convert float to string
13,921,067
3
2012-12-17T19:46:43Z
13,921,156
10
2012-12-17T19:51:34Z
[ "python" ]
I want to convert a float between 0.0 and 39.9 into a string. Replace the tens digit with an L, T or Y if it's a 1, 2 or 3 respectively. And append an M if it's in the ones. For example, 22.3 would return T2.3 and 8.1 would return M8.1 and so forth. Otherwise, return the float. This code works of course, but I wonderi...
How about: ``` def specType(SpT): return '{}{}'.format('MLTY'[int(SpT//10)], SpT % 10) if 0.0 <= SpT <= 39.9 else SpT ``` which gives ``` >>> specType(0.0) 'M0.0' >>> specType(8.1) 'M8.1' >>> specType(14.5) 'L4.5' >>> specType(22.3) 'T2.3' >>> specType(34.7) 'Y4.7' ``` [As noted in the comments, you'll want to ...
Trying to figure out the except statement in Python
13,921,219
3
2012-12-17T19:56:21Z
13,921,244
14
2012-12-17T19:58:07Z
[ "python", "except" ]
I am having some trouble understanding ways to use the "except" statement in Python. I am a horrendous coder right now, so my apologies in advance. Here is the small code I am trying to run: ``` def mathWorks(): print " Answer the following: 5 + x = 10" x = int(raw_input("Please type your answer: ")) if...
`except` has to come after a `try` block. This signals the section of code that should have the exception handled: ``` try: x = int(raw_input("Please type your answer: ")) except ValueError: print "That is not an integer!" ``` Read it as 'try this, then do this if it fails'. Note it's good practice to do as l...
Python - Dimension of Data Frame
13,921,647
34
2012-12-17T20:27:52Z
13,921,674
62
2012-12-17T20:29:56Z
[ "python", "pandas" ]
New to Python. In R, you can get the dimension of a matrix using dim(...). What is the corresponding function in Python Pandas for their data frame?
`df.shape`, where `df` is your DataFrame.
Python urllib2: Receive JSON response from url
13,921,910
51
2012-12-17T20:46:07Z
13,921,930
119
2012-12-17T20:47:46Z
[ "python", "json", "urllib2" ]
I am trying to GET a URL using Python and the response is JSON. However, when I run ``` import urllib2 response = urllib2.urlopen('https://api.instagram.com/v1/tags/pizza/media/XXXXXX') html=response.read() print html ``` The html is of type str and I am expecting a JSON. Is there any way I can capture the response a...
If the URL is returning valid JSON-encoded data, use the [`json` library](http://docs.python.org/2/library/json.html) to decode that: ``` import urllib2 import json response = urllib2.urlopen('https://api.instagram.com/v1/tags/pizza/media/XXXXXX') data = json.load(response) print data ```
Python urllib2: Receive JSON response from url
13,921,910
51
2012-12-17T20:46:07Z
22,530,527
20
2014-03-20T10:47:05Z
[ "python", "json", "urllib2" ]
I am trying to GET a URL using Python and the response is JSON. However, when I run ``` import urllib2 response = urllib2.urlopen('https://api.instagram.com/v1/tags/pizza/media/XXXXXX') html=response.read() print html ``` The html is of type str and I am expecting a JSON. Is there any way I can capture the response a...
``` import json import urllib url = 'http://example.com/file.json' r = urllib.request.urlopen(url) data = json.loads(r.read().decode(r.info().get_param('charset') or 'utf-8')) print data ``` [urllib](https://docs.python.org/3.4/library/urllib.html), for Python 3.4 [HTTPMessage](https://docs.python.org/3.4/library/e...
multiprocessing.freeze_support()
13,922,597
13
2012-12-17T21:37:10Z
18,195,951
12
2013-08-12T20:17:38Z
[ "python", "multiprocessing", "py2exe", "pyinstaller", "cx-freeze" ]
Why does the multiprocessing module need to call a specific [function](http://docs.python.org/dev/library/multiprocessing.html#multiprocessing.freeze_support) to work when being "frozen" to produce a windows executable?
The reason is lack of `fork()` on Windows (which is [not](http://stackoverflow.com/q/4243880/95735) entirely true). Because of this, on Windows the fork is *simulated* by creating a **new** process in which code, which on Linux is being run in child process, is being run. As the code is to be run in technically unrelat...
How do you do a python 'eval' only within an object context?
13,923,091
7
2012-12-17T22:10:43Z
13,923,430
8
2012-12-17T22:39:36Z
[ "python", "eval", "abstract-syntax-tree" ]
Is it possible to do something like ``` c = MyObj() c.eval("func1(42)+func2(24)") ``` in Python..i.e. have func1() and func2() be evaluated within the scope of the object 'c' (if they were member functions within that class definition)? I can't do a simple parsing, since for my application the eval strings can become...
You almost certainly don't want to do this, but you *can*. The context for [`eval`](http://docs.python.org/library/functions.html#eval) is the globals and locals dictionaries that you want to evaluate your code in. The most common cases are probably `eval(expr, globals(), mycontext)` and `eval(expr, mycontext)`, which...
setup.py: restrict the allowable version of the python interpreter
13,924,931
16
2012-12-18T01:19:27Z
13,925,176
13
2012-12-18T01:53:06Z
[ "python", "pip", "easy-install", "setup.py" ]
I have a python library. Unfortunately I have not updated it to work with python 3 yet. in its setup.py, I added ``` install_requires=['python<3'], ``` My intent was to not allow this package to be installed / used under python 3, because I know it doesn't (yet) work. I don't think this is the right way to do it, be...
a possible solution is to *test* for the python version, since pip can't *satisfy* the python version except for the version it's currently running in (it installs in the current python environment): ``` import sys if not sys.version_info[0] == 2: sys.exit("Sorry, Python 3 is not supported (yet)") setup(... ```
Updating pandas DataFrame by key
13,924,972
5
2012-12-18T01:24:53Z
13,925,150
10
2012-12-18T01:49:55Z
[ "python", "pandas" ]
I have a dataframe of historical stock trades. The frame has columns like ['ticker', 'date', 'cusip', 'profit', 'security\_type']. Initially: ``` trades['cusip'] = np.nan trades['security_type'] = np.nan ``` I have historical config files that I can load into frames that have columns like ['ticker', 'cusip', 'date', ...
Suppose you have this setup: ``` import pandas as pd import numpy as np import datetime as DT nan = np.nan trades = pd.DataFrame({'ticker' : ['IBM', 'MSFT', 'GOOG', 'AAPL'], 'date' : pd.date_range('1/1/2000', periods = 4), 'cusip' : [nan, nan, 100, nan] ...
Can params passed to pytest fixture be passed in as a variable?
13,925,366
8
2012-12-18T02:18:52Z
13,934,840
13
2012-12-18T14:13:53Z
[ "python", "py.test" ]
I have two simple test setups and I'm trying to group them in one fixture and want the test function to pass in the 'params' to the fixture. Here's a contrived example, to explain my question. Say I have the following pytest fixture: ``` @pytest.fixture(scope="module", params=['param1','param2']) def myFixture(reques...
If i understand your question correctly, you basically want to select one instance of a parametrized fixture for executing with a test, by providing some info with the test. It's not possible although we could probably think about a mechanism. I am not sure if the following solution maps to your whole problem, but here...
Login to website using urllib2 - Python 2.7
13,925,983
26
2012-12-18T03:51:05Z
13,955,538
35
2012-12-19T15:23:17Z
[ "python", "python-2.7", "login", "urllib2" ]
Okay, so I am using this for a reddit bot, but I want to be able to figure out HOW to log in to any website. If that makes sense.... I realise that different websites use different login forms etc. So how do I figure out how to optimise it for each website? I'm assuming I need to look for something in the html file bu...
I'll preface this by saying I haven't done logging in in this way for a while, so I could be missing some of the more 'accepted' ways to do it. I'm not sure if this is what you're after, but without a library like `mechanize` or a more robust framework like `selenium`, in the basic case you just look at the form itsel...
Selecting columns from pandas.HDFStore table
13,926,089
14
2012-12-18T04:08:09Z
13,977,244
10
2012-12-20T17:16:15Z
[ "python", "pandas", "hdfs" ]
How can I retrieve specific columns from a pandas HDFStore? I regularly work with very large data sets that are too big to manipulate in memory. I would like to read in a csv file iteratively, append each chunk into HDFStore object, and then work with subsets of the data. I have read in a simple csv file and loaded it ...
You can store the dataframe with an index of the columns as follows: ``` import pandas as pd import numpy as np from pandas.io.pytables import Term index = pd.date_range('1/1/2000', periods=8) df = pd.DataFrame( np.random.randn(8,3), index=index, columns=list('ABC')) store = pd.HDFStore('mydata.h5') store.append('...
Selecting columns from pandas.HDFStore table
13,926,089
14
2012-12-18T04:08:09Z
13,999,234
8
2012-12-22T01:27:49Z
[ "python", "pandas", "hdfs" ]
How can I retrieve specific columns from a pandas HDFStore? I regularly work with very large data sets that are too big to manipulate in memory. I would like to read in a csv file iteratively, append each chunk into HDFStore object, and then work with subsets of the data. I have read in a simple csv file and loaded it ...
The way HDFStore records tables, the columns are stored by type as single numpy arrays. You always get back all of the columns, you can filter on them, so you will be returned for what you ask. In 0.10.0 you can pass a Term that involves columns. ``` store.select('df', [ Term('index', '>', Timestamp('20010105')), ...
Python & ttk Using labelFrames to clean up a frame
13,926,789
5
2012-12-18T05:23:29Z
13,982,722
9
2012-12-21T00:36:46Z
[ "python", "tkinter", "ttk" ]
I'm trying to build a basic GUI using ttk / Tkinter. I have a plotted out a basic GUI that has the right basic components, but when I try and prettify it / space it out, I'm reach my limit of getting ttk containers to play nicely... Examples: ``` from Tkinter import * import ttk class MakeGUI(object): def __ini...
There are many places that require adjustments, let us comment on them (I will probably forget about something, so be sure to check the code at bottom). First of all, applying weights to columns/rows in the frame alone is not going to make it expand as you resize the window. You need to do it in `root`. After that you...
Show non printable characters in a string
13,927,889
8
2012-12-18T07:00:13Z
13,935,582
10
2012-12-18T14:55:15Z
[ "python", "python-3.x", "escaping" ]
Is it possible to visualize non-printable characters in a python string with its hex values? e.g. If I have a string with a newline inside I would like to replace it with `\x0a`. I know there is `repr()` which will give me ...`\n`, but I'm looking for the hex version.
I don't know of any built-in method, but it's fairly easy to do using a comprehension: ``` import string printable = string.ascii_letters + string.digits + string.punctuation + ' ' def hex_escape(s): return ''.join(c if c in printable else r'\x{0:02x}'.format(ord(c)) for c in s) ```
Pythonic way of handling multiple possible file locations? (Without using nested trys)
13,928,163
5
2012-12-18T07:19:00Z
13,928,198
10
2012-12-18T07:22:22Z
[ "python", "exception-handling" ]
I have a Python script that needs to look for a certain file. I could use os.path.isafile(), but I've heard that's bad Python, so I'm trying to catch the exception instead. However, there's two locations I could possibly look for the file. I could use nested trys to handle this: ``` try: keyfile = 'location1' ...
``` for location in locations: try: try_to_connect(location) break except IOError: continue else: # this else is optional # executes some code if none of the locations is valid # for example raise an Error as suggested @eumiro ``` Also you can add an `else` clause to the for...
Python Filter List Items Relative to Each Other
13,928,641
3
2012-12-18T07:58:50Z
13,928,694
8
2012-12-18T08:03:38Z
[ "python", "list", "filter", "filtering" ]
Let's say I have a list of tuples: ``` fruits = [('apple','red',23), ('apple','green',12), ('orange','small',12), ('orange','large',1)] ``` How can I quickly and cleanly create a new list with the tuples that have the largest numbers but unique to fruit name. So the ideal result would be...
If your `fruits` list is already sorted by fruit, use `itertools.groupby`: ``` from itertools import groupby from operator import itemgetter def fruitfilter(fruits): for fruit, group in groupby(fruits, key=itemgetter(0)): yield max(group, key=itemgetter(2)) fruits = list(fruitfilter(fruits)) ``` Or in s...
How can a Flask decorator have arguments?
13,931,633
9
2012-12-18T11:09:44Z
13,932,942
17
2012-12-18T12:24:04Z
[ "python", "decorator", "flask" ]
I implemented a decorator in the same way as here [How to make a python decorator function in Flask with arguments (for authorization)](http://stackoverflow.com/questions/13896650/how-to-make-a-python-decorator-function-in-flask-with-arguments-for-authorizati) but problem still unsolved... I have this function with de...
Decorators are executed at import time, they're essentially syntactic sugar: ``` @foo(bar) def baz(): return 'w00t!' ``` is equivalent to ``` def baz(): return 'w00t!' baz = foo(bar)(baz) ``` So in the example above variable `bar` must exist in the global scope of this module before it is passed to the decor...
python threading app error to many arguments
13,932,747
3
2012-12-18T12:13:28Z
13,941,704
12
2012-12-18T21:21:53Z
[ "python", "multithreading", "python-2.7" ]
What is wrong with this python source code? ``` import threading import subprocess as sub def ben(fil): pr = sub.Popen(fil,stdout=sub.PIPE,stderr=sub.PIPE) output, errors = pr.communicate() print output theapp = '''blender blender-softwaregl'''.split() print theapp for u in theapp: print...
The `args` argument to `threading.Thread` expects a sequence, but you're providing a string. This is causing it to interpret each letter of the strings as an individual argument, resulting in too many arguments for your target function. You're very close to having the right code. You just need to fix your tuple syntax...
How to execute python file in linux
13,933,169
14
2012-12-18T12:36:17Z
13,933,226
25
2012-12-18T12:39:27Z
[ "python", "linux" ]
I am using linux mint, and to run a python file I have to type in the terminal: `python [file path]`, so is there way to make the file executable, and make it run the `python` command automatically when I doublr click it? And since I stopped dealing with windows ages ago, I wonder if the .py files there are also autom...
You have to add a shebang. A shebang is the first line of the file. Its what the system is looking for in order to execute a file. It should look like that : ``` #!/usr/bin/env python ``` or the real path ``` #!/usr/bin/python ``` You should also check the file have the right to be execute. `chmod +x file.py` As ...
How to execute python file in linux
13,933,169
14
2012-12-18T12:36:17Z
13,933,323
8
2012-12-18T12:44:08Z
[ "python", "linux" ]
I am using linux mint, and to run a python file I have to type in the terminal: `python [file path]`, so is there way to make the file executable, and make it run the `python` command automatically when I doublr click it? And since I stopped dealing with windows ages ago, I wonder if the .py files there are also autom...
I suggest that you add ``` #!/usr/bin/env python ``` instead of `#!/usr/bin/python` at the top of the file. The reason for this is that the python installation may be in different folders in different distros or different computers. By using `env` you make sure that the system finds python and delegates the script's ...
Python: Quick and dirty datatypes (DTO)
13,933,419
11
2012-12-18T12:49:35Z
13,933,470
17
2012-12-18T12:52:22Z
[ "python" ]
Very often, I find myself coding trivial datatypes like ``` def Pruefer: def __init__(self, ident, maxNum=float('inf'), name=""): self.ident = ident self.maxNum = maxNum self.name = name ``` While this is very useful (Clearly I don't want to replace the above with anonymous 3-tuples), i...
``` >>> from collections import namedtuple >>> Pruefer = namedtuple("Pruefer", "ident maxNum name") >>> pr = Pruefer(1,2,3) >>> pr.ident 1 >>> pr.maxNum 2 >>> pr.name 3 >>> hash(pr) 2528502973977326415 ``` To provide default values, you need to do little bit more... Simple solution is to write subclass with redefiniti...
iterator for dates in python
13,933,678
3
2012-12-18T13:03:35Z
13,933,731
10
2012-12-18T13:06:54Z
[ "python", "date", "iterator" ]
I have a begin\_date `datetime.date(2012, 9, 1)` and an end\_date `datetime.date(2012, 9, 30)` I would like get a iterator or a list which includes dates 2012/9/1 to 2012/9/30. Is any way other then a loop do make that iterator or list
Use a generator: ``` from datetime import date, timedelta def dategenerator(start, end): current = start while current <= end: yield current current += timedelta(days=1) ``` Demo: ``` >>> for dt in dategenerator(date(2012, 9, 1), date(2012, 9, 30)): ... print dt ... 2012-09-01 2012-09-0...
supervisord logs don't show my ouput
13,934,801
12
2012-12-18T14:11:51Z
13,956,136
17
2012-12-19T15:54:01Z
[ "python", "logging", "supervisord" ]
I have a [program:x] running and it prints / sys.stdout.writes a lot of things. None of which comes up in either in the AUTO childlogdir of [supervisord] or in stdout\_logfile of [program:x] Am I missing something? How do I capture all that is printed or stdout-ed from [program:x] ? In my program I am explicitly doin...
Python output is buffered, make sure you flush the `sys.stdout` handler to see log messages sooner: ``` sys.stdout.flush() ``` On python 3.3 and up, you can add the `flush=True` parameter to have the function do this for you: ``` print(something, flush=True) ```
supervisord logs don't show my ouput
13,934,801
12
2012-12-18T14:11:51Z
17,961,520
27
2013-07-31T04:19:52Z
[ "python", "logging", "supervisord" ]
I have a [program:x] running and it prints / sys.stdout.writes a lot of things. None of which comes up in either in the AUTO childlogdir of [supervisord] or in stdout\_logfile of [program:x] Am I missing something? How do I capture all that is printed or stdout-ed from [program:x] ? In my program I am explicitly doin...
You can run your program like this: ``` python -u file.py ``` this will produce unbuffered output
SQLite foreign key examples
13,934,994
11
2012-12-18T14:23:16Z
13,936,863
36
2012-12-18T16:02:08Z
[ "python", "sql", "sqlite", "insert", "foreign-keys" ]
I am not an expert in sql / sqlite.. suppose we have two tables: ``` CREATE TABLE child ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, ); CREATE TABLE MyTableB( dog TEXT, FOREIGN KEY(dogList) REFERENCES child(id) ); ``` how will the INSERT? is correct my createTable operations? I would like to have...
# Many-To-Many In order to support a child having zero or more dogs and a dog belonging to zero or more children, your database table structure needs to support a **Many-To-Many** relationship. This requires three tables: ``` CREATE TABLE child ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT ); CREATE TAB...
Simple toy example using multiprocessing module crashes computer
13,935,283
5
2012-12-18T14:40:05Z
13,935,303
8
2012-12-18T14:41:18Z
[ "python" ]
Trying the very simple following example causes my computer to grind to a halt, so that I have to restart. Checking task manager shows hundreds of "python.exe" tasks: ``` import math from multiprocessing import Pool pool = Pool(processes=2) print pool.map(math.sqrt, [1,4,9,16]) ``` I am using a dual core cpu (i5 246...
I had the same problem the first time I played around with `multiprocessing`. Wrap the pool generation code in a `if __name__ == '__main__'` block. ``` import math from multiprocessing import Pool if __name__ == '__main__': pool = Pool(processes=2) print pool.map(math.sqrt, [1,4,9,16]) ``` What's happening i...
split python string on multiple string delimiters efficiently
13,935,454
3
2012-12-18T14:49:00Z
13,935,721
11
2012-12-18T15:03:07Z
[ "python", "string", "split", "delimiter" ]
Suppose I have a string such as `"Let's split this string into many small ones"` and I want to split it on `this`, `into` and `ones` such that the output looks something like this: ``` ["Let's split", "this string", "into many small", "ones"] ``` What is the most efficient way to do it?
With a lookahead. ``` >>> re.split(r'\s(?=(?:this|into|ones)\b)', "Let's split this string into many small ones") ["Let's split", 'this string', 'into many small', 'ones'] ```
Python's enumerate in Ruby?
13,936,922
12
2012-12-18T16:05:42Z
13,937,000
10
2012-12-18T16:10:13Z
[ "python", "ruby", "arrays", "enumerate" ]
``` def enumerate(arr): (0..arr.length - 1).to_a.zip(arr) ``` Is something built in for this? It doesn't need to have it's members immutable, it just needs to be in the standard library. I don't want to be the guy who subclasses the Array class to add a Python feature to a project. Does it have a different name i...
Something like this in Python: ``` a = ['do', 're', 'mi', 'fa'] for i, s in enumerate(a): print('%s at index %d' % (s, i)) ``` becomes this in Ruby: ``` a = %w(do re mi fa) a.each_with_index do |s,i| puts "#{s} at index #{i}" end ```
Using pandas to select rows using two different columns from dataframe?
13,937,022
8
2012-12-18T16:11:22Z
13,937,141
15
2012-12-18T16:18:48Z
[ "python", "pandas" ]
Q is similar to this: [use a list of values to select rows from a pandas dataframe](http://stackoverflow.com/questions/12096252/use-a-list-of-values-to-select-rows-from-a-pandas-dataframe) I want to dataframe if either value in two columns are in a list. Return both columns (combine results of #1 and #4. ``` import n...
You nearly had it, but you have to use the ["bitwise or"](http://docs.scipy.org/doc/numpy/reference/generated/numpy.bitwise_or.html#numpy.bitwise_or) operator: ``` In [6]: df[(df.one == 1) | (df.two == 7)] Out[6]: one three two 0 1 9 5 2 3 17 7 In [7]: df[(df.one.isin(checkList)) | (df.two....
Nicing a running python process?
13,937,199
4
2012-12-18T16:20:53Z
13,937,252
7
2012-12-18T16:24:13Z
[ "python", "nice" ]
When my longer-running programm starts, I want to lower its priority so it does not consume all resources avaiable on the machine it runs. Circumstances make it necessary that the programm limits itself. Is there a nice-like python-command I could use so that the programm does not utilize the full capacity of the comp...
you can always run the process with `nice pythonscript`, but if you want to set the nice-level within the script you can do: ``` import os os.nice(20) ``` You could progressively increment the nice level the longer the script is running, so it uses less and less resources over time, which is a simple matter of integ...
Inherit a parent class docstring as __doc__ attribute
13,937,500
7
2012-12-18T16:38:49Z
13,937,525
10
2012-12-18T16:40:16Z
[ "python", "docstring", "django-rest-framework" ]
There is a question about [Inherit docstrings in Python class inheritance](http://stackoverflow.com/questions/2025562/inherit-docstrings-in-python-class-inheritance), but the answers there deal with method docstrings. My question is how to inherit a docstring of a parent class as the `__doc__` attribute. The usecase i...
Since you cannot assign a new `__doc__` docstring to a class (in CPython at least), you'll have to use a metaclass: ``` import inspect def inheritdocstring(name, bases, attrs): if not '__doc__' in attrs: # create a temporary 'parent' to (greatly) simplify the MRO search temp = type('temporaryclass...
Python's range() analog in Common Lisp
13,937,520
20
2012-12-18T16:39:41Z
13,937,652
27
2012-12-18T16:47:51Z
[ "python", "common-lisp", "number-sequence" ]
**How to create a list of consecutive numbers in Common Lisp?** In other words, what is the equivalent of Python's `range` function in Common Lisp? In Python `range(2, 10, 2)` returns `[2, 4, 6, 8]`, with first and last arguments being optional. I couldn't find the idiomatic way to create a sequence of numbers, thoug...
There is no built-in way of generating a sequence of numbers, the canonical way of doing so is to do one of: * Use `loop` * Write a utility function that uses `loop` An example implementation would be (this only accepts counting "from low" to "high"): ``` (defun range (max &key (min 0) (step 1)) (loop for n from ...
Python's range() analog in Common Lisp
13,937,520
20
2012-12-18T16:39:41Z
14,054,026
11
2012-12-27T11:35:39Z
[ "python", "common-lisp", "number-sequence" ]
**How to create a list of consecutive numbers in Common Lisp?** In other words, what is the equivalent of Python's `range` function in Common Lisp? In Python `range(2, 10, 2)` returns `[2, 4, 6, 8]`, with first and last arguments being optional. I couldn't find the idiomatic way to create a sequence of numbers, thoug...
alexandria implements scheme's iota: ``` (ql:quickload :alexandria) (alexandria:iota 4 :start 2 :step 2) ;; (2 4 6 8) ```
Why doesn't "class" start a new scope like "def" does?
13,937,637
15
2012-12-18T16:46:44Z
13,939,981
11
2012-12-18T19:21:22Z
[ "python" ]
I'm not entirely sure this is for stackoverflow, so please correct me if not. i.e. say we have t.py with contents: ``` class A(object): pass print("A:", A) class B(object): print("From B: A:", A) class OuterClass(object): class AA(object): pass print("AA:", AA) class BB(object): ...
As Wooble noted in a comment, the class block *does* create a new scope. The problem is that names in a class block scope are not accessible to scopes nested within that scope. This is mentioned in [the documentation](http://docs.python.org/release/3.1.3/reference/executionmodel.html#naming-and-binding): > The scope o...
Python: JSON string to list of dictionaries - Getting error when iterating
13,938,183
5
2012-12-18T17:17:51Z
13,938,219
8
2012-12-18T17:20:15Z
[ "python", "json" ]
I am sending a JSON string from Obj-C to Python. Then I want to break contents of the string into a Python list. I am trying to iterate over a string (any string for now), and I get this error: *Exception Error: 'list' object has no attribute 'iterates'*. Why? ``` import json s = '[{"i":"imap.gmail.com","p":"...
Your JSON data is a list of dictionaries, so after `json.loads(s)` you will have `jdata` as a list, not a dictionary. Try something like the following: ``` import json s = '[{"i":"imap.gmail.com","p":"someP@ss"},{"i":"imap.aol.com","p":"anoterPass"}]' jdata = json.loads(s) for d in jdata: for key, value in d.ite...
Django url parameter and reverse URL
13,938,605
2
2012-12-18T17:48:10Z
13,938,700
7
2012-12-18T17:53:58Z
[ "python", "django", "django-templates", "django-views", "django-urls" ]
I have a view that looks like this: ``` def selectCity(request, the_city): request.session["ciudad"] = the_city city = request.session["ciudad"] return HttpResponse('Ciudad has been set' + ": " + city) ``` And a URL that looks like this: ``` url(r'^set/$', views.selectCity, {'the_city': 'gye'}, name='ciu...
You can pass the relevant arguments in url tag, if your url (in `urls.py`) has any capturing group. ``` url(r'^set/(?P<the_city>\w+)/$', views.selectCity, {'the_city': 'gye'}, name='ciudad'), ``` Then in template: ``` <a tabindex="-1" href="{% url ciudad the_city='gye' %}">Guayaquil</a> ```
Apply function on Pandas dataframe
13,938,704
11
2012-12-18T17:54:06Z
13,938,831
13
2012-12-18T18:03:13Z
[ "python", "pandas" ]
I'm a newbie to pandas dataframe, and I wanted to apply a function to each column so that it computes for each element x, x/max of column. I referenced this question, but am having trouble accessing the maximum of each column. Thanks in advance [Pandas DataFrame: apply function to all columns](http://stackoverflow.com...
Something like this should work: ``` >>> from pandas import DataFrame >>> >>> df = DataFrame({"A": [8,9,5,4], "B": [3,4,4,8], "C": [5,0,3,5], "D": [8,4,8,1]}) >>> df.max() A 9 B 8 C 5 D 8 >>> (df * 1.0)/df.max() A B C D 0 0.888889 0.375 1.0 1.000 1 1.000000 0.500 0.0 0.500 2...
Common Lisp: all or any elements are true in a list
13,940,111
12
2012-12-18T19:30:07Z
13,940,166
23
2012-12-18T19:34:49Z
[ "python", "list", "lisp", "common-lisp" ]
In Python there are functions [`all`](http://docs.python.org/3/library/functions.html#all) and [`any`](http://docs.python.org/3/library/functions.html#any) they return true if all or some elements of a list are true respectively. Are there equivalent functions in Common Lisp? If not, what is the most succinct and idiom...
In Common Lisp, use [every](http://www.lispworks.com/documentation/HyperSpec/Body/f_everyc.htm#every) (that's the equivalent of `all`) and [some](http://www.lispworks.com/documentation/HyperSpec/Body/f_everyc.htm#some) (that's the equivalent of `any`).
Python: json.loads returns items prefixing with 'u'
13,940,272
39
2012-12-18T19:40:28Z
13,940,335
48
2012-12-18T19:44:46Z
[ "python", "json" ]
I'll be receiving a JSON encoded string form Obj-C, and I am decoding a dummy string (for now) like the code below. My output comes out with character 'u' prefixing each item: `[{u'i': u'imap.gmail.com', u'p': u'aaaa'}, {u'i': u'333imap.com', u'p': u'bbbb'}...` How is JSON adding this unicode char? What's the best way ...
The u- prefix just means that you have a Unicode string. When you really use the string, it won't appear in your data. Don't be thrown by the printed output. For example, try this: ``` print mail_accounts[0]["i"] ``` You won't see a u.
Python: json.loads returns items prefixing with 'u'
13,940,272
39
2012-12-18T19:40:28Z
13,940,346
58
2012-12-18T19:45:07Z
[ "python", "json" ]
I'll be receiving a JSON encoded string form Obj-C, and I am decoding a dummy string (for now) like the code below. My output comes out with character 'u' prefixing each item: `[{u'i': u'imap.gmail.com', u'p': u'aaaa'}, {u'i': u'333imap.com', u'p': u'bbbb'}...` How is JSON adding this unicode char? What's the best way ...
Everything is cool, man. The 'u' is a good thing, it indicates that the string is of type Unicode in python 2.x. <http://docs.python.org/2/howto/unicode.html#the-unicode-type>
Python: json.loads returns items prefixing with 'u'
13,940,272
39
2012-12-18T19:40:28Z
34,479,722
8
2015-12-27T10:56:42Z
[ "python", "json" ]
I'll be receiving a JSON encoded string form Obj-C, and I am decoding a dummy string (for now) like the code below. My output comes out with character 'u' prefixing each item: `[{u'i': u'imap.gmail.com', u'p': u'aaaa'}, {u'i': u'333imap.com', u'p': u'bbbb'}...` How is JSON adding this unicode char? What's the best way ...
I believe that the **`d3`** print below is the one you were looking for (which is the combination of dumps and loads) :) **Having:** ``` import json d = """{"Aa": 1, "BB": "blabla", "cc": "False"}""" d1 = json.loads(d) # Produces a dictionary out of the given string d2 = json.dumps(d) # Pr...
Find root of path
13,940,319
4
2012-12-18T19:43:55Z
20,449,089
12
2013-12-08T02:17:09Z
[ "python", "regex" ]
I have a path: ``` path = foo/bar/baz ``` and I would like to determine what the base is. In this example it should return *"foo"*. There are a few ways I have tried: ``` root = re.search('(.+?)/(.+)', path).group(1) paths = path.split('/')[0] root = paths[0] if paths[0] or len(paths) <= 1 else '/'.join(paths[0:2]...
``` >>> import os >>> path = '/foo/bar/baz' >>> path = path.lstrip(os.sep) # Get rid of leading "/" if any >>> root = path[:path.index(os.sep)] if os.sep in path else path >>> root 'foo' ```
Defining a list in Python using the multiply operator
13,941,124
4
2012-12-18T20:39:38Z
13,941,175
7
2012-12-18T20:43:08Z
[ "python", "list", "append" ]
Recently in Python I have encountered this statement: ``` board.append([' '] * 8) ``` I have tried to search the Internet with Google to find some more information about this type of statement, but I can't. I know *what* the statement does, but I do not understand *how*, in what manner is doing, that. This is the f...
> Can you please refer me to a place where I can find some more information about this type of statements. Most of the relevant operators and methods are defined here: [Sequence Types](http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange). Specifically `s * n` i...
Why can I not catch a Queue.Empty exception from a multiprocessing Queue?
13,941,562
5
2012-12-18T21:10:22Z
13,941,865
10
2012-12-18T21:34:59Z
[ "python", "exception-handling", "python-2.7" ]
I'm trying to catch a Queue.Empty exception that is raised if a multiprocessing.Queue is empty. The following does not work: ``` import multiprocessing f = multiprocessing.Queue() try: f.get(True,0.1) except Queue.Empty: print 'foo' ``` This gives me a name error: NameError: name 'Queue' is not defined r...
The `Empty` exception you're looking for isn't available directly in the `multiprocessing` module, because `multiprocessing` borrows it from the `Queue` module (renamed `queue` in Python 3). To make your code work, just do an `import Queue` at the top: Try this: ``` import multiprocessing import Queue # or queue in P...
Can you speed up "for " loop in python with sorting ?
13,941,585
2
2012-12-18T21:11:54Z
13,941,691
7
2012-12-18T21:20:45Z
[ "python", "list" ]
If I have a long unsorted list of 300k elements, will sorting this list first and then do a "for" loop on list speed up code? I need to do a "for loop" regardless, cant use list comprehension. ``` sortedL=[list].sort() for i in sortedL: (if i is somenumber) "do some work" ``` How could I signal to python tha...
It would appear that you're considering sorting the list so that you could then quickly look for `somenumber`. Whether the sorting will be worth it depends on whether you are going to search once, or repeatedly: * If you're only searching once, sorting the list will not speed things up. Just iterate over the list loo...
How to pass an array from C to an embedded python script
13,942,128
7
2012-12-18T21:55:30Z
13,942,236
9
2012-12-18T22:04:23Z
[ "python", "embedding", "python-c-api" ]
I am running to some problems and would like some help. I have a piece code, which is used to embed a python script. This python script contains a function which will expect to receive an array as an argument (in this case I am using numpy array within the python script). I would like to know how can I pass an array fr...
Really, the best answer here is probably to use `numpy` arrays exclusively, even from your C code. But if that's not possible, then you have the same problem as any code that shares data between C types and Python types. In general, there are at least five options for sharing data between C and Python: 1. Create a Py...
Given boundaries, find interval
13,942,698
2
2012-12-18T22:41:50Z
13,942,715
12
2012-12-18T22:44:19Z
[ "python", "algorithm", "python-3.x" ]
Having a list like this ``` [207, 357, 470, 497, 537] ``` where each number denotes the boundary of an interval (`0` being implicit at the beginning of the list), what is **a pythonic way** of finding out to which interval a given number `n` belongs to? So the intervals are ``` 0: (0, 207) 1: (208, 357) 2: (358, 49...
Using the [`bisect` module](http://docs.python.org/3/library/bisect.html) of course: ``` >>> import bisect >>> lst = [207, 357, 470, 497, 537] >>> bisect.bisect_left(lst, 0) 0 >>> bisect.bisect_left(lst, 360) 2 ```
Prepare data for text classification using Scikit Learn SVM
13,942,744
7
2012-12-18T22:46:14Z
13,942,900
18
2012-12-18T22:59:58Z
[ "python", "svm", "scikit-learn" ]
I'm trying to apply SVM from Scikit learn to classify the tweets I collected. So, there will be two categories, name them A and B. For now, I have all the tweets categorized in two text file, 'A.txt' and 'B.txt'. However, I'm not sure what type of data inputs the Scikit Learn SVM is asking for. I have a dictionary with...
Have a look at the documentation on [text feature extraction](http://scikit-learn.org/stable/modules/feature_extraction.html#text-feature-extraction). Also have a look at the [text classification example](http://scikit-learn.org/stable/auto_examples/text/document_classification_20newsgroups.html). There is also a tut...
How to flatten a numpy array of dtype object
13,942,794
4
2012-12-18T22:51:08Z
13,942,845
7
2012-12-18T22:55:41Z
[ "python", "numpy" ]
I'm taking ndarray slices with different length and I want my result to be flat. For example: ``` a = np.array(((np.array((1,2)), np.array((1,2,3))), (np.array((1,2)), np.array((1,2,3,4,5,6,7,8))))) ``` Is there any straight way to make this array flat by using numpy functionalities (without loop)?
How about: ``` In [23]: np.hstack(a.flat) Out[23]: array([1, 2, 1, 2, 3, 1, 2, 1, 2, 3, 4, 5, 6, 7, 8]) ```
Extract day of year and Julian day from a string date in python
13,943,062
14
2012-12-18T23:12:36Z
13,943,108
23
2012-12-18T23:17:12Z
[ "python", "date", "datetime", "julian" ]
I have a string "2012.11.07" in python. I need to convert it to date object and then get an integer value of *day of year* and also *Julian day*. Is it possible?
First, you can convert it to a [`datetime.datetime`](http://docs.python.org/library/datetime.html#datetime-objects) object like this: ``` >>> import datetime >>> fmt = '%Y.%m.%d' >>> s = '2012.11.07' >>> dt = datetime.datetime.strptime(s, fmt) >>> dt datetime.datetime(2012, 11, 7, 0, 0) ``` Then you can use the metho...
Why is cURL returning "additional stuff not fine"?
13,943,181
23
2012-12-18T23:25:09Z
13,943,440
25
2012-12-18T23:52:50Z
[ "python", "curl" ]
I am writing a Python application that queries social media APIs via cURL. Most of the different servers I query (Google+, Reddit, Twitter, Facebook, others) have cURL complaining: > additional stuff not fine transfer.c:1037: 0 0 The unusual thing is that when the application first starts, each service's response wil...
I'm 99.99% sure this is not actually in any HTTP headers, but is rather being printed to `stderr` by `libcurl`. Possibly this happens in the middle of you logging the headers, which is why you were confused. Anyway, a quick search for `"additional stuff not fine" curl transfer.c` turned up [a recent change in the sour...
How to add colorbars to scatterplots created like this?
13,943,217
6
2012-12-18T23:29:08Z
13,945,998
8
2012-12-19T05:21:57Z
[ "python", "matplotlib" ]
I create scatterplots with code that, in essence, goes like this ``` cmap = (matplotlib.color.LinearSegmentedColormap. from_list('blueWhiteRed', ['blue', 'white', 'red'])) fig = matplotlib.figure.Figure(figsize=(4, 4), dpi=72) ax = fig.gca() for record in data: level = record.level # a float in [0.0, 1.0...
If you have to use a different marker for each set, you have to do a bit of extra work and force all of the `clims` to be the same (otherwise they default to scaling from the min/max of the `c` data per scatter plot). ``` from pylab import * import matplotlib.lines as mlines import itertools fig = gcf() ax = fig.gca()...
Printing from 2 lists on one line
13,943,801
2
2012-12-19T00:35:46Z
13,943,872
7
2012-12-19T00:44:55Z
[ "python" ]
What I have so far: ``` def balance_equation(species,coeff): data=zip(coeff,species) positive=[] negative=[] for (mul,el) in data: if int(mul)<0: negative.append((el,mul)) if int(mul)>0: positive.append((el,mul)) ``` I know this does not print anything. What I have is a function that takes...
Try this: ``` species = ["H2O", "CO2", "O2"] coeff = ['1', '-4', '3'] pos = [c + s for c, s in zip(coeff, species) if int(c) > 0] neg = [c[1:] + s for c, s in zip(coeff, species) if int(c) < 0] print ("+".join(pos))+"="+("+".join(neg)) ``` **EDIT**: I took out the spaces. **2nd EDIT**: `coeff` is a list of strings. ...
passing variables from python to bash shell script via os.system
13,944,076
8
2012-12-19T01:06:58Z
13,944,140
10
2012-12-19T01:14:01Z
[ "python", "bash" ]
In the following code, I construct a variable $probe1 that I want to then pass to a bash script. I the toy example below, the output is blank, i.e. $probe1 is not recognized the the bash shell script within the os.system call. What needs to be done? ``` for line1 in datfile: datmat=datmat+[line1.rstrip('\n').split...
Seems like this is what you are trying to do: ``` In [2]: os.environ['probe1'] = 'hello' In [3]: os.system('echo $probe1') hello ``` But I have no idea why you would like to do this ...
How to suppress "unused variable" warnings in Eclipse/PyDev
13,944,234
14
2012-12-19T01:24:00Z
13,944,314
27
2012-12-19T01:32:51Z
[ "python", "eclipse", "variable-assignment", "pydev" ]
How to suppress "unused variable" warnings in Eclipse/PyDev When I'm working with functions that return tuples, I often only need one of the values, but still want to assign to multiple variables. I would like to be able to temporarily turn this warning off so I can zero in on more serious issues. Then, I can turn it ...
If you don't need the value of a variable, assign it to the special variable `_`. As far as Python is concerned, there is actually nothing special about `_`; it's just another legal identifier name like any other. However, for most "lint"-style tools (hopefully including PyDev)—and, more importantly, human readersâ...
How to suppress "unused variable" warnings in Eclipse/PyDev
13,944,234
14
2012-12-19T01:24:00Z
14,591,913
18
2013-01-29T20:45:42Z
[ "python", "eclipse", "variable-assignment", "pydev" ]
How to suppress "unused variable" warnings in Eclipse/PyDev When I'm working with functions that return tuples, I often only need one of the values, but still want to assign to multiple variables. I would like to be able to temporarily turn this warning off so I can zero in on more serious issues. Then, I can turn it ...
Add the comment `#@UnusedVariable` to the end of the line. Every warning in eclipse has a similar deactivation comment. Use Quick Fix to discover them (place the cursor in the warning and press Ctrl+1)
why use os.path.join over string concatenation
13,944,387
18
2012-12-19T01:44:39Z
13,944,874
20
2012-12-19T02:59:27Z
[ "python" ]
I'm not able to see the bigger picture here I think; but basically I have no idea why you would use `os.path.join` instead of just normal string concatenation? I have mainly used VBScript so I don't understand the point of this function.
## Portable Write filepath manipulations *once* and it works across many different platforms, for free. The delimiting character is abstracted away, making your job easier. ## Smart You no longer need to worry if that directory path had a [trailing slash or not](http://stackoverflow.com/questions/980255/should-a-dir...
dateutil and pytz give different results
13,944,688
16
2012-12-19T02:27:42Z
13,944,824
14
2012-12-19T02:49:18Z
[ "python", "datetime", "timezone" ]
I have an issue comparing outputs with `dateutil` and `pytz`. I'm creating a aware datetime object (UTC) and then converting to a given time zone, but I get different answers. I suspect that dateutil sometimes gives wrong results because it has problems taking into account daylight saving time (at least, I read a comme...
**Edit:** The discrepancy discussed below no longer exists when using ``` >>> dateutil.__version__ '1.5' >>> pytz.__version__ '2012c' ``` --- The pytz module [warns](http://pytz.sourceforge.net/#introduction), > this library differs from the documented Python API for tzinfo > implementations; if you want to create...
*args, **kwargs in jinja2 macros
13,944,751
41
2012-12-19T02:35:51Z
13,944,920
47
2012-12-19T03:05:18Z
[ "python", "macros", "jinja2", "jinja" ]
How are extra args & kwargs handled for a Jinja2 macro? The documentation isn't exactly clear offhand. For example, this is clearly wrong: ``` {% macro example_1(one, two, **kwargs) %} do macro stuff {% endmacro %} ``` which results in ``` jinja2.exceptions.TemplateSyntaxError TemplateSyntaxError: expected tok...
The trick is that `kwargs` has to be **accessed at least once** in any macro that should accept them. That is to say, you must call `{{ kwargs }}` once in macro body *without* declaring it in macro argument list. The same is true for `{{ varargs }}`. This will not work ``` {% macro example_2(one, two) %} * {{one}...
Pyramid catch-all friendly exception handling
13,944,852
10
2012-12-19T02:55:10Z
13,945,131
10
2012-12-19T03:35:54Z
[ "python", "exception-handling", "pyramid" ]
Is there a way that I can handle some sort of "catch-all" error handling in a Pyramid web app? I currently have implemented exception logging to a database (via the docs at <http://docs.pylonsproject.org/projects/pyramid_cookbook/en/latest/logging/sqlalchemy_logger.html>) and I'll return messages to my views to put a "...
You can set up an [exception view](http://docs.pylonsproject.org/projects/pyramid_cookbook/en/latest/pylons/exceptions.html). For example: ``` @view_config(context=Exception) def error_view(exc, request): #log or do other stuff to exc... return Response("Sorry there was an error") ```
Dynamic refresh printing of multiprocessing or multithreading in Python
13,944,959
8
2012-12-19T03:11:57Z
13,946,863
20
2012-12-19T06:41:18Z
[ "python", "multithreading", "download" ]
I have implemented a multiprocessing downloader. How can I print the status bar (complete rate, download speed) which can refresh automatically in different part on the terminal. Like this: ``` 499712 [6.79%] 68k/s // keep refreshing 122712 [16.79%] 42k/s // different process/thread 99712 [...
Below is a demo that has implemented both multi-processing and multi-threading. To try one or the other just uncomment the import lines at the top of the code. If you have a progress bar on a single line then you can use the technique that you have of printing '\r' to move the cursor back to the start of the line. But ...
String Formatting in Python 3
13,945,749
59
2012-12-19T04:53:32Z
13,945,764
8
2012-12-19T04:55:21Z
[ "python", "python-3.x" ]
``` "(%d goals, $%d)" % (self.goals, self.penalties) ``` ^ I know how to do this in Python 2 What is the Python 3 version of this? I tried searching for examples online but I kept getting Python 2 versions
That line works as-is in Python 3. ``` >>> sys.version '3.2 (r32:88445, Oct 20 2012, 14:09:29) \n[GCC 4.5.2]' >>> "(%d goals, $%d)" % (self.goals, self.penalties) '(1 goals, $2)' ```
String Formatting in Python 3
13,945,749
59
2012-12-19T04:53:32Z
13,945,777
96
2012-12-19T04:56:59Z
[ "python", "python-3.x" ]
``` "(%d goals, $%d)" % (self.goals, self.penalties) ``` ^ I know how to do this in Python 2 What is the Python 3 version of this? I tried searching for examples online but I kept getting Python 2 versions
Here are [the docs](http://docs.python.org/2/library/string.html#format-string-syntax) about the "new" format syntax. An example would be: ``` "({:d} goals, ${:d})".format(self.goals, self.penalties) ``` If both `goals` and `penalties` are integers (i.e. their default format is ok), it could be shortened to: ``` "({...
PyInstaller 2.0 bundle file as --onefile
13,946,650
12
2012-12-19T06:23:37Z
13,963,480
18
2012-12-20T00:27:47Z
[ "python", "pyinstaller" ]
I'm trying to bundle my py script as an .exe using PyInstaller 2.0. I am able to bundle the script, but in my script, I need to open a file that should be bundled in the exe (so it's portable). I'm having trouble doing this.. In my .py, I have ``` filename = 'C:\path\to\my\file\doc.docx' data = open(filename,'rb') ``...
OMG! This PyInstaller really confused me for a bit. If my previous post sounds a little "ranty", sorry about that.. Anyways, for anyone trying to include a file in a --onefile PyInstaller package this worked for me: Include this in your .py script: ``` filename = 'myfilesname.type' if hasattr(sys, '_MEIPASS'): # ...
Python Regex Negative Lookbehind
13,947,933
6
2012-12-19T08:05:10Z
13,948,002
7
2012-12-19T08:10:49Z
[ "python", "regex", "pcre", "negative-lookbehind" ]
The pattern `(?<!(asp|php|jsp))\?.*` works in PCRE, but it doesn't work in Python. So what can I do to get this regex working in Python? (Python 2.7)
It works perfectly fine for me. Are you maybe using it wrong? Make sure to use `re.search` instead of `re.match`: ``` >>> import re >>> s = 'somestring.asp?1=123' >>> re.search(r"(?<!(asp|php|jsp))\?.*", s) >>> s = 'somestring.xml?1=123' >>> re.search(r"(?<!(asp|php|jsp))\?.*", s) <_sre.SRE_Match object at 0x000000000...
How to update json file with python
13,949,637
10
2012-12-19T09:53:21Z
13,949,836
14
2012-12-19T10:04:17Z
[ "python", "json" ]
I'm trying to update existing Json file, but from some reason, the requested value is not being changed but the entire set of values (with the new value) is being appended to the original file ``` jsonFile = open("replayScript.json", "r+") data = json.load(jsonFile) tmp = data["location"] data["location"] = "NewPath...
``` def updateJsonFile(): jsonFile = open("replayScript.json", "r") data = json.load(jsonFile) jsonFile.close() tmp = data["location"] data["location"] = path data["mode"] = "replay" jsonFile = open("replayScript.json", "w+") jsonFile.write(json.dumps(data)) jsonFile.close() ```
How to update json file with python
13,949,637
10
2012-12-19T09:53:21Z
13,949,837
13
2012-12-19T10:04:40Z
[ "python", "json" ]
I'm trying to update existing Json file, but from some reason, the requested value is not being changed but the entire set of values (with the new value) is being appended to the original file ``` jsonFile = open("replayScript.json", "r+") data = json.load(jsonFile) tmp = data["location"] data["location"] = "NewPath...
The issue here is that you've opened a file and read its contents so the cursor is at the end of the file. By writing to the same file handle, you're essentially appending to the file. The easiest solution would be to close the file after you've read it in, then reopen it for writing. ``` with open("replayScript.json...
Django/Python: generate pdf with the proper language
13,950,874
14
2012-12-19T11:00:15Z
13,956,762
7
2012-12-19T16:26:57Z
[ "python", "django", "pdf-generation", "pisa", "xhtml2pdf" ]
I use [Pisa/xhtml2pdf](http://www.xhtml2pdf.com/) in my Django apps to generate pdf from an HTML source. That is: 1. I generate the HTML file formatted with all 'printing' stuffs (e.g. page-breaks, header, footer, etc.) 2. I convert this HTML into pdf using Pisa This process is ok but it is slow (expecially when deal...
WeasyPrint author here. The point of using HTML/CSS to generate PDF (vs. using a lower-level PDF library directly.) is to get automatic layout. It lets you specify high-level constraints like `h1 { page-break-after: avoid }` and let the layout engine figure it out, rather than specifying the absolute position of everyt...
Daemonizing a python script in debian
13,953,268
3
2012-12-19T13:16:56Z
13,955,696
8
2012-12-19T15:30:31Z
[ "python", "debian", "daemon", "raspberry-pi", "init.d" ]
I have a python script that i want to run in the background on startup. This is the script: ``` #!/usr/bin/python from Adafruit_CharLCD import Adafruit_CharLCD from subprocess import * from time import sleep, strftime from datetime import datetime from datetime import timedelta from os import system from os import ge...
Assuming you may want to manage more than one daemon in the future, let me recommend [Supervisord](http://supervisord.org/running.html#adding-a-program). It's much simpler than writing and managing your own init.d scripts. For example, starting your script would be as easy as including this in the conf: ``` [program:...