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
Create a colormap with white centered around zero
11,647,261
5
2012-07-25T10:00:30Z
11,659,600
9
2012-07-25T22:26:32Z
[ "python", "matplotlib", "scipy" ]
I must admit, understanding how to create or manipulate matplotlib's colormaps is not an easy thing. Therefore I'm seeking a little help in explaining and setting up a colormap that goes from blue (negative) to red (positive) and has white centered tightly around zero. I would then like to use this cmap in `contourf`: ...
Rather than using a stock cmap, I will walk thorough the production of your own. As you have already spotted, in order to have absolute control of the colors (without passing a colors array) when using cmaps, the number of colors in a cmap should be equal to the number of levels - 1. We can easily demonstrate this wi...
How to invert a permutation array in numpy
11,649,577
14
2012-07-25T12:20:28Z
11,649,931
17
2012-07-25T12:40:25Z
[ "python", "algorithm", "numpy", "vectorization" ]
Given a self-indexing (not sure if this is the correct term) numpy array, for example: ``` a = np.array([3, 2, 0, 1]) ``` This represents this [permutation](http://en.wikipedia.org/wiki/Permutation#Notation) (`=>` is an arrow): ``` 0 => 3 1 => 2 2 => 0 3 => 1 ``` I'm trying to make an array representing the inverse...
The inverse of a permutation `p` of `np.arange(n)` is the array of indices `s` that sort `p`, i.e. ``` p[s] == np.arange(n) ``` must be all true. Such an `s` is exactly what [`np.argsort`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html) returns: ``` >>> p = np.array([3, 2, 0, 1]) >>> np.argso...
How to invert a permutation array in numpy
11,649,577
14
2012-07-25T12:20:28Z
11,651,305
7
2012-07-25T13:52:06Z
[ "python", "algorithm", "numpy", "vectorization" ]
Given a self-indexing (not sure if this is the correct term) numpy array, for example: ``` a = np.array([3, 2, 0, 1]) ``` This represents this [permutation](http://en.wikipedia.org/wiki/Permutation#Notation) (`=>` is an arrow): ``` 0 => 3 1 => 2 2 => 0 3 => 1 ``` I'm trying to make an array representing the inverse...
I'd like to offer a tiny bit more background to larsmans correct answer. The *reason* why `argsort` is correct can be found when you use the representation of a [permutation by a matrix](http://en.wikipedia.org/wiki/Permutation_matrix). The mathematical advantage to a permutation *matrix* `P` is that the matrix "operat...
How to invert a permutation array in numpy
11,649,577
14
2012-07-25T12:20:28Z
25,535,723
10
2014-08-27T19:42:59Z
[ "python", "algorithm", "numpy", "vectorization" ]
Given a self-indexing (not sure if this is the correct term) numpy array, for example: ``` a = np.array([3, 2, 0, 1]) ``` This represents this [permutation](http://en.wikipedia.org/wiki/Permutation#Notation) (`=>` is an arrow): ``` 0 => 3 1 => 2 2 => 0 3 => 1 ``` I'm trying to make an array representing the inverse...
**Sorting is an overkill here.** This is just a single-pass, linear time algorithm with constant memory requirement: ``` import numpy as np if __name__ == '__main__': p = np.array([3, 2, 0, 1]) s = np.empty(p.size, dtype=int) for i in xrange(p.size): s[p[i]] = i print 's = %s' % s ``` The abo...
ISO 8859-1 filename not decoding
11,649,601
3
2012-07-25T12:21:47Z
11,650,034
7
2012-07-25T12:45:18Z
[ "python", "unicode", "mime", "iso", "latin1" ]
I'm extracting files from MIME messages in a python milter and am running across issues with files named as such: =?ISO-8859-1?Q?Certificado=5FZonificaci=F3n=5F2010=2Epdf?= I can't seem to decode this name into UTF. In order to solve a prior ISO-8859-1 issue, I started passing all filenames to this function: ``` def...
Your string is encoded using the [Quoted-printable](https://en.wikipedia.org/wiki/Quoted-printable) format for MIME headers. The [`email.header` module](http://docs.python.org/library/email.header.html) handles this for you: ``` >>> from email.header import decode_header >>> bytes, encoding = decode_header('=?ISO-8859...
Call methods by string
11,649,848
6
2012-07-25T12:35:49Z
11,649,920
9
2012-07-25T12:39:47Z
[ "python", "python-2.5" ]
I have the following class. ``` func_list= ["function1", "function2", "function3"] class doit(object): def __init__(self): for item in func_list: if item == "function1": self.function1() elif item == "function2": self.function2() elif ite...
``` func_list= ["function1", "function2", "function3"] class doit(object): def __init__(self): for item in func_list: getattr(self, item)() def function1(self): print "f1" def function2(self): print "f2" def function3(self): print "f3" >>> doit() f1 f2 f3 ...
Why do I need to assign a variable to f.readlines() in order to get its length?
11,651,670
5
2012-07-25T14:09:05Z
11,651,697
7
2012-07-25T14:10:29Z
[ "python", "list" ]
If I do: ``` os.chdir(path) f = open(file,"r") lines = f.readlines() print "without assignment " + str(len(f.readlines())) print "with assignment " + str(len(lines)) ``` I would expect the output the be the same, but it's not: ``` without assignment 0 with assigment 1268 ``` Why is this?
The file object `f` is an iterator over the lines of the file. `f.readlines()` moves the file cursor to the end but saves the lines in `lines` which is why the second example works for you. The first example doesn't work because you have reached the end of the file and there are no lines left to read. You could use `f....
import next() python 2.5
11,652,404
6
2012-07-25T14:46:50Z
11,652,442
10
2012-07-25T14:48:48Z
[ "python", "next" ]
I'm using a slightly altered version of the pairwise recipe from itertools which looks like this ``` def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) return zip(a, b) ``` Now it turns out I need to run the code with **python 2.5** where the next() funct...
You can easily provide a definition of this function yourself: ``` _sentinel = object() def next(it, default=_sentinel): try: return it.next() except StopIteration: if default is _sentinel: raise return default ```
csv.write skipping lines when writing to csv
11,652,806
5
2012-07-25T15:06:00Z
11,652,964
10
2012-07-25T15:14:29Z
[ "python", "csv" ]
I am trying to write to a csv file via the following ``` file = open('P:\test.csv', 'a') fieldnames = ('ItemID', 'Factor', 'FixedAmount') wr = csv.DictWriter(file, fieldnames=fieldnames) headers = dict((n, n) for n in fieldnames) wr.writerow(headers) wr.writerow({'ItemID':1, 'Factor': 2, 'FixedAmount':3}) ``` Howe...
Solution is to specify the "lineterminator" parameter in the constructor: ``` file = open('P:\test.csv', 'w') fields = ('ItemID', 'Factor', 'FixedAmount') wr = csv.DictWriter(file, fieldnames=fields, lineterminator = '\n') wr.writeheader() wr.writerow({'ItemID':1, 'Factor': 2, 'FixedAmount':3}) file.close() ```
Python Easiest Way to Sum List Intersection of List of Tuples
11,653,917
7
2012-07-25T16:03:19Z
11,654,020
14
2012-07-25T16:08:37Z
[ "python", "list", "set", "intersection" ]
Let's say I have the following two lists of tuples ``` myList = [(1, 7), (3, 3), (5, 9)] otherList = [(2, 4), (3, 5), (5, 2), (7, 8)] returns => [(1, 7), (2, 4), (3, 8), (5, 11), (7, 8)] ``` I would like to design a merge operation that merges these two lists by checking for any intersections on the first element of...
Use a dictionary for the result: ``` result = {} for k, v in my_list + other_list: result[k] = result.get(k, 0) + v ``` If you want a list of tuples, you can get it via `result.items()`. The resulting list will be in arbitrary order, but of course you can sort it if desired. (Note that I renamed your lists to co...
Issue building cx_Oracle - libclntsh.so.11.1 => not found
11,654,090
24
2012-07-25T16:12:08Z
11,654,364
21
2012-07-25T16:27:09Z
[ "python", "oracle", "build", "cx-oracle" ]
I'm trying to build cx\_Oracle for a Python 2.7.2 and Oracle 11g installation but the built cx\_Oracle.so cannot find libclntsh.so.11.1 so importing cx\_Oracle in Python fails. ``` /mypath/cx_Oracle-5.1.1/build/lib.linux-x86_64-2.7-11g]$ ldd cx_Oracle.so libclntsh.so.11.1 => not found libpthread.so.0 => /lib64...
Add `/apps/oracle/client/11.2.0.1/home1/lib/` to your `LD_LIBRARY_PATH` environment variable execute the command below in the terminal before running python or add it into your `.bashrc` ``` export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/apps/oracle/client/11.2.0.1/home1/lib/ ```
How to setup APScheduler in a Django project?
11,654,353
11
2012-07-25T16:26:27Z
15,929,907
11
2013-04-10T15:18:13Z
[ "python", "django" ]
Specifically, how to * Setup [APScheduler](http://pythonhosted.org/APScheduler/) in a Django project * Start running * Write to Django ORM
Well, I'll have a go. Assuming you have installed apscheduler (or put it in your Python path) The [basic documentation for APS](http://pythonhosted.org/APScheduler/) lists the following code for starting up a job: ``` from apscheduler.scheduler import Scheduler sched = Scheduler() @sched.interval_schedule(hours=3) d...
Python Minidom - how to iterate through attributes, and get their name and value
11,654,669
5
2012-07-25T16:47:10Z
13,382,277
8
2012-11-14T15:52:53Z
[ "python", "python-3.x", "minidom" ]
I want to iterate through all attributes of a dom node and get the name and value I tried something like this (docs were not very verbose on this so I guessed a little): ``` for attr in element.attributes: attrName = attr.name attrValue = attr.value ``` 1. the for loop doesn't even start 2. how do I get the ...
There is a short and efficient (and pythonic ?) way to do it easily ``` #since items() is a tUple list, you can go as follows : for attrName, attrValue in element.attributes.items(): #do whatever you'd like print "attribute %s = %s" % (attrName, attrValue) ``` If what you are trying to achieve is to transfer ...
Improving OCR performance on multi-paragraph scans
11,655,645
20
2012-07-25T17:50:51Z
11,678,889
12
2012-07-26T22:20:28Z
[ "python", "ocr", "tesseract" ]
I'm working on a project that involves extracting text scientific papers stored in PDF format. For most papers, this is accomplished quite easily using PDFMiner, but some older papers store their text as large images. In essence, a paper is scanned and that image file (typically PNG or JPEG) comprises the entire page. ...
Tesseract is very good on clean input text (like your example) if you tinker a bit. some suggestions: * Before automating, start with tesseract at the command line * Restrict your character set if possible (e.g. take a look in /usr/local/share/tessdata/configs at ./digits - configure it for English characters upper/lo...
Pycrypto: Incrementing CTR Mode
11,656,045
4
2012-07-25T18:15:38Z
11,659,333
14
2012-07-25T22:04:03Z
[ "python", "aes", "encryption", "pycrypto" ]
Still can't quite get this to work. My question is about how to make the decryption line work. Here is what I have written: ``` class IVCounter(object): @staticmethod def incrIV(self): temp = hex(int(self, 16)+1)[2:34] return array.array('B', temp.decode("hex")).tostring() def decryptCTR(key,...
In Python, it is perfectly valid to treat functions as objects. It is also perfectly valid to treat any object that defines `__call__(self, ...)` as a function. So what you want might something like this: ``` class IVCounter(object): def __init__(self, start=1L): self.value = long(start) def __call__(...
Decode python base64 String
11,656,115
9
2012-07-25T18:21:16Z
11,657,454
7
2012-07-25T19:46:42Z
[ "python", "base64", "decode" ]
I have extracted base64 string of forecolor, texture and edgemap values of images, I have a list with following structure: ``` forecolor=AgCEAg4DUQQCBQQGARMBFQE1AmUB edge=AfCAFg5iIATCPwTAEIiBFggBDw forecolor=AgAsAQ0CJAMcDRgOGg8DHQYeBzYBPQ4-DU0ETgNtBm4CfQI ``` I am trying to decode these values, but I am getting Incor...
You are trying to decode a Base64 String which does not have padding. Although many flavors of Base64 do not have padding, Python requires padding for standard base64 decoding. This StackOverflow question has a more in-depth explanation: [Python: Ignore 'Incorrect padding' error when base64 decoding](http://stackoverfl...
Would like to use PubNub to send real-time updates to the user's web browser
11,656,117
4
2012-07-25T18:21:19Z
11,662,583
10
2012-07-26T04:57:34Z
[ "python", "django", "heroku", "real-time-updates", "pubnub" ]
Looking in to using PubNub to send real-time updates to the user's web browser. I looked over their website and materials. It looks like they have a few different options. We would like to use it for sending real time updates to a web page that a user is looking at. The information is simple stuff like "You just rece...
# PubNub Facebook Notification This is an example of a Facebook-like Window Box that notifies your user with a custom message via PubNub. You can send updates to your users on their Mobile Phone or Browser. This will show your user a notification; any notification you. Using PubNub allows Data Push via WebSockets, BO...
Would like to use PubNub to send real-time updates to the user's web browser
11,656,117
4
2012-07-25T18:21:19Z
13,962,219
8
2012-12-19T22:19:22Z
[ "python", "django", "heroku", "real-time-updates", "pubnub" ]
Looking in to using PubNub to send real-time updates to the user's web browser. I looked over their website and materials. It looks like they have a few different options. We would like to use it for sending real time updates to a web page that a user is looking at. The information is simple stuff like "You just rece...
For something a bit less generic, employing signals triggered by even an API served by Django and very strong channel security , check out <https://github.com/sivang/django-pubnub> (straight from the oven ;)).
How to take the log of all elements of a list
11,656,767
7
2012-07-25T19:04:27Z
11,656,802
18
2012-07-25T19:06:32Z
[ "python", "arrays" ]
I have an array ``` x = [1500, 1049.8, 34, 351, etc] ``` How can I take log\_10() of the entire array?
[numpy](http://docs.scipy.org/doc/numpy/reference/generated/numpy.log10.html) will do that for you. ``` import numpy numpy.log10(mat) ``` **Note** `mat` does not have to be a numpy array for this to work, and `numpy` should be faster than using a list comprehension as other answers suggest.
How to take the log of all elements of a list
11,656,767
7
2012-07-25T19:04:27Z
11,656,819
7
2012-07-25T19:07:19Z
[ "python", "arrays" ]
I have an array ``` x = [1500, 1049.8, 34, 351, etc] ``` How can I take log\_10() of the entire array?
The simpliest way is to use a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) --- **Example:** ``` >>> x = [1500, 1049.8, 34, 351] >>> import math >>> [math.log10(i) for i in x] [3.1760912590556813, 3.021106568432122, 1.5314789170422551, 2.545307116465824] >>> ``` Anoth...
Django: Error when calling the metaclass bases
11,657,532
6
2012-07-25T19:51:54Z
11,657,781
9
2012-07-25T20:07:11Z
[ "python", "django", "metaclass" ]
Here is the error > TypeError: Error when calling the metaclass bases > metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases The class in question within my models.py ``` class Business(models.Model, forms.Form): name = models.CharField(max_leng...
This is the problem: ``` class Business(models.Model, forms.Form): ``` You're trying to inherit from Model and Form. You can't, and you shouldn't. You can't because the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases. Form has a metaclass: ``` __metaclass__ = Declara...
Django admin interface: using horizontal_filter with inline ManyToMany field
11,657,682
12
2012-07-25T20:00:57Z
11,658,199
27
2012-07-25T20:36:40Z
[ "python", "django", "django-admin" ]
I have a Django model field that I'd like to inline. The field is a many-to-many relationship. So there are "Projects" and "User profiles". Each user profile can select any number of projects. Currently, I've got the "tabular" inline view working. Is there a way to have a "horizontal filter" so that I can easily add a...
The problem isn't from having inlines; it's from the way `ModelForm`s work, in general. They only build form fields for actual fields on the model, not related manager attributes. However, you can add this functionality to the form: ``` from django.contrib.admin.widgets import FilteredSelectMultiple class ProjectAdmi...
Sleep for exact time in python
11,657,734
4
2012-07-25T20:04:08Z
11,657,808
8
2012-07-25T20:08:47Z
[ "python", "windows", "sleep" ]
I need to wait for about 25ms in one of my functions. Sometimes this function is called when the processor is occupied with other things and other times it has the processor all to itself. I've tried `time.sleep(.25)` but sometimes its actually 25ms and other times it takes much longer. Is there a way to sleep for an ...
Because you're working with a [preemptive](http://en.wikipedia.org/wiki/Preemption_%28computing%29) operating system, there's no way you can guarantee that your process will be able to have control of the CPU in 25ms. If you'd still like to try, it would be better to have a busy loop that polls until 25ms has passed. ...
Pickling dynamically generated classes?
11,658,511
22
2012-07-25T20:57:51Z
11,770,528
12
2012-08-02T03:11:10Z
[ "python", "class", "dynamic", "metaprogramming" ]
I'm using `type()` to dynamically generate classes that will ultimately be pickled. The problem is that the un-pickling process needs the definition of the class in order to re-construct the object that has been pickled. This is where I'm stuck. I don't know how to somehow *provide* the unpickler a way to generate an ...
When the Pickler encounters an object of a type it knows nothing about, it looks for a [reduce method](http://docs.python.org/library/pickle.html#object.__reduce__). Defining this method when you build your custom class using type should solve the problem of pickling. If you provide initial args then in addition you m...
Create and download an AWS ec2 keypair using python boto
11,658,578
4
2012-07-25T21:02:35Z
11,658,766
9
2012-07-25T21:15:47Z
[ "python", "amazon-ec2", "boto" ]
I'm having difficulty figuring out a way (if possible) to create a new AWS keypair with the Python Boto library and then download that keypair.
The Key object returned by the create\_keypair method in boto has a "save" method. So, basically you can do something like this: ``` >>> import boto >>> ec2 = boto.connect_ec2() >>> key = ec2.create_key_pair('mynewkey') >>> key.save('/path/to/keypair/dir') ``` If you want a more detailed example, check out <https://g...
Python - Overwriting Folder If It Already Exists
11,660,605
8
2012-07-26T00:18:01Z
11,660,641
11
2012-07-26T00:22:39Z
[ "python", "folder", "text-files", "overwrite" ]
``` dir = 'C:\Users\Shankar\Documents\Other' if not os.path.exists(dir): os.makedirs(dir) ``` Here is some code I found that allows me to create a directory if it does not already exist. The folder will be used by a program to write text files into that folder. But I want to start with a brand new, empty folder ne...
Would this work: ``` dir = 'C:\Users\Shankar\Documents\Other' if os.path.exists(dir): shutil.rmtree(dir) os.makedirs(dir) ```
Python app import error in Django with WSGI gunicorn
11,660,627
5
2012-07-26T00:20:54Z
11,660,940
10
2012-07-26T01:02:27Z
[ "python", "django", "import", "wsgi", "gunicorn" ]
I'm trying to deploy a Django app with gunicorn on Heroku and I've run into a few hitches. When I began my project my Django version was 1.3 and didn't contain the standard wsgi.py module, so I added the standard wsgi module as top/wsgi.py (top being my project name, turk being my app name, topturk being the containin...
Figured out my problem. Needed to add the project directory to Python path, not the app directory - i.e., topturk/top instead of topturk/top/turk in order to import turk directory modules. ``` python top/manage.py run_gunicorn ``` and ``` python top/manage.py runserver ``` were working just fine because as per Pyth...
Django Caching for Authenticated Users Only
11,661,503
12
2012-07-26T02:34:50Z
11,703,958
13
2012-07-28T19:22:25Z
[ "python", "django", "caching", "heroku", "memcached" ]
# Question In Django, how can create a single cached version of a page (same for all users) that's only visible to authenticated users? ## Setup The pages I wish to cache are only available to authenticated users (they use `@login_required` on the view). These pages are the same for all authenticated users (e.g. no ...
The default `cache_page` decorator accepts a variable called `key_prefix`. However, it can be passed as a string parameter only. So you can write your own decorator, that will dynamically modify this `prefix_key` based on the `is_authenticated` value. Here is an example: ``` from django.views.decorators.cache import c...
Raw input across multiple lines in Python
11,664,443
33
2012-07-26T07:29:29Z
11,664,675
43
2012-07-26T07:47:56Z
[ "python", "input" ]
Does anyone know how to create a raw input that will take multiple lines ?
``` sentinel = '' # ends when this string is seen for line in iter(raw_input, sentinel): pass # do things here ``` To get every line as a string you can do: ``` '\n'.join(iter(raw_input, sentinel)) ``` --- Python 3: ``` '\n'.join(iter(input, sentinel)) ```
Jinja - Is there any built-in variable to get current HTML page name?
11,665,401
14
2012-07-26T08:35:00Z
11,665,879
28
2012-07-26T09:04:04Z
[ "python", "html", "templates", "jinja" ]
i'm very new to Jinja and Flask I want to set different background color in the navigation bar to indicate the current page. Is there any built-in Jinja variable or method that returns current HTML pages? If possible, I want the code that doesn't need to communicate with the Python file. So if i'm currently in `inde...
There is a trick in jinja2 document for your problem: <http://jinja.pocoo.org/docs/tricks/> If your list is simple enough, just using request object, something like that: ``` <li {% if request.endpoint == item.endpoint %} class='active' {% endif %}> <a href="{{url_for(endpoint)}}">{{item.text}}</a> </li> ``` Nor...
Why do the sys.stdout.encoding differ when output is piped (in Python2.x)?
11,666,251
4
2012-07-26T09:25:28Z
11,666,325
7
2012-07-26T09:29:05Z
[ "python", "python-2.x" ]
When I run the same code with different piping, why output is different? ``` % python2.7 -c 'import sys; print sys.stdout.encoding' UTF-8 % python2.7 -c 'import sys; print sys.stdout.encoding' | cat None ```
Because when you use `cat` (or any pipe), you unbind the process from terminal. Python derives information about encoding from terminal settings. You can force the encoding using enironment variable: ``` export PYTHONIOENCODING=utf-8 ```
Python, how to decode Binary coded decimal (BCD)
11,668,969
5
2012-07-26T12:08:59Z
11,669,177
9
2012-07-26T12:21:09Z
[ "python", "struct", "binary", "decode", "bcd" ]
Description of the binary field is: > Caller number, expressed with compressed BCD code, and the surplus bits are filled with “0xF” I have tried to print with struct format `'16c'` and I get: `('3', '\x00', '\x02', '\x05', '\x15', '\x13', 'G', 'O', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff')` ...
BCD codes work with 4 bits per number, and normally encode only the digits 0 - 9. So each byte in your sequence contains 2 numbers, 1 per 4 bits of information. The following method uses a generator to produce those digits; I am assuming that a 0xF value means there are no more digits to follow: ``` def bcdDigits(cha...
How to create an array of bits in Python?
11,669,178
21
2012-07-26T12:21:09Z
11,669,249
26
2012-07-26T12:25:04Z
[ "python", "arrays", "bit" ]
How can I declare a bit array of a very large size, say 6 million bits?
``` from bitarray import bitarray a = bitarray(2**20) ``` You can check out more info about this module at <http://pypi.python.org/pypi/bitarray/>
How to create an array of bits in Python?
11,669,178
21
2012-07-26T12:21:09Z
11,917,815
17
2012-08-11T21:28:53Z
[ "python", "arrays", "bit" ]
How can I declare a bit array of a very large size, say 6 million bits?
The [bitstring](http://code.google.com/p/python-bitstring/) module may help: ``` from bitstring import BitArray a = BitArray(6000000) ``` This will take less than a megabyte of memory, and it's easy to set, read, slice and interpret bits. Unlike the bitarray module it's pure Python, plus it works for Python 3. See [...
Undefined global in list generator expression using python3, works with python2, what changes are needed?
11,669,379
9
2012-07-26T12:32:55Z
11,670,273
12
2012-07-26T13:22:54Z
[ "python", "python-3.x" ]
``` class Some(object): tokens = [ ... list of strings ... ] untokenized = [tokens.index(a) for a in [... some other list of strings ...]] ... etc ... some = Some() ``` This works fine with Python2.7. However python3 says: ``` Traceback (most recent call last): File "./test.py", line 17, in <module> c...
As Wooble says, the issue is that classes don't have a lexical scope (actually, in either [Python 2](http://docs.python.org/reference/compound_stmts.html#class-definitions) or [Python 3](http://docs.python.org/dev/reference/compound_stmts.html#class-definitions)). Instead, they have a local *namespace* that does not co...
Python Bottle how to read request parameters
11,671,154
6
2012-07-26T14:10:28Z
11,671,217
10
2012-07-26T14:13:59Z
[ "python", "bottle", "http-request" ]
I am using <http://dingyonglaw.github.com/bootstrap-multiselect-dropdown/#forms> to display a dropdown with multiple check boxes. ``` <li> <label> <input type="checkbox" name="filters" value="first value"> <span>First Value</span> </label> </li> <li> <label> <input type="checkbox" name="filters" val...
Use the [`request.query.getall` method](http://bottlepy.org/docs/dev/api.html#bottle.MultiDict.getall) instead. > FormsDict is a subclass of MultiDict and can store more than one value per key. The standard dictionary access methods will only return a single value, but the MultiDict.getall() method returns a (possibly...
Open a file for input and output in Python
11,672,453
2
2012-07-26T15:12:29Z
11,672,478
7
2012-07-26T15:14:20Z
[ "python", "file", "python-3.x" ]
I have the following code which is intended to remove specific lines of a file. When I run it, it prints the two filenames that live in the directory, then deletes all information in them. What am I doing wrong? I'm using Python 3.2 under Windows. ``` import os files = [file for file in os.listdir() if file.split("."...
`open(file, 'w')` wipes the file. To prevent that, open it in `r+` mode (read+write/don't wipe), then read it all at once, filter the lines, and write them back out again. Something like ``` with open(file, "r+") as f: lines = f.readlines() # read entire file into memory f.seek(0) ...
Need to understand Python generator object
11,672,706
5
2012-07-26T15:27:37Z
11,672,766
12
2012-07-26T15:30:02Z
[ "python", "generator", "generator-expression" ]
In the following: ``` name = 'TODD' chars = set('AEIOU') for ii in range(-1, int(math.copysign(len(name) + 1, -1)), -1): if any((cc in chars) for cc in name[ii]): print 'Found' else: print 'Not Found' ``` I understand that what's inside any(...) is a generator object. What I don't understand i...
The parenthesis can be omitted when used in function calls with only one argument, the [generator expression syntax](http://docs.python.org/reference/expressions.html#generator-expressions) specifically allows for it. > The parentheses can be omitted on calls with only one argument. See section [Calls](http://docs.pyt...
Macros in python
11,675,569
2
2012-07-26T18:21:02Z
11,675,738
7
2012-07-26T18:30:22Z
[ "python", "macros", "code-generation", "macropy" ]
in my project I have to repeat often such part of code: ``` class SimplePhysicObject(Object): def __init__(self): super(Object, self).__init__('SimplePhysicObject') ``` But instead of `SimplePhysicObject` there is new string each time. Are there any ways to write some macro to make this work easier? Somet...
I don't see a reason why `Object` should need the actual class name as a parameter. You can access the actual class name in `Object` via `self.__class__.__name__`: ``` class Object(object): def __init__(self): self.name = self.__class__.__name__ class SimplePhysicObject(Object): pass a = SimplePhysic...
python class properties
11,675,840
10
2012-07-26T18:35:43Z
11,676,610
8
2012-07-26T19:26:06Z
[ "python", "class", "variables" ]
I'm trying to find the best way to extend a class variable. Hopefully an example of the method I've come up with so far will make this clear. ``` class A(object): foo = ['thing', 'another thing'] class B(A): foo = A.foo + ['stuff', 'more stuff'] ``` So I'm trying to make the subclass inherit and extend the p...
Could use a metaclass: ``` class AutoExtendingFoo(type): def __new__(cls, name, bases, attrs): foo = [] for base in bases: try: foo.extend(getattr(base, 'foo')) except AttributeError: pass try: foo.extend(attrs.pop('foo_additi...
combine lists to make one list that has each element a sum of the individual elements
11,676,125
2
2012-07-26T18:53:16Z
11,676,147
10
2012-07-26T18:54:36Z
[ "python" ]
I have 3 lists: ``` ['1','2'] ['a','b','c'] ['X','Y'] ``` and the result I am looking to get: ``` ['1aX','1bX','1cX','2aX','2bX','2cX','1aY','1bY','1cY','2aY','2bY','2cY'] ``` is there a way to set this up quickly?
You can use `itertools.product()`: ``` map("".join, itertools.product(list1, list2, list3)) ```
I am struggling to understand sessions in CherryPy
11,676,624
2
2012-07-26T19:26:54Z
11,677,491
7
2012-07-26T20:27:08Z
[ "python", "cherrypy" ]
I recently began a project to migrate our web app from apache + Mod\_python to just cherry-py. There is still a good deal of stuff I still need to do, but for now, it is CherryPy's sessions that are giving me a bit of a headache. My first question is how do they work? In Mod\_python, we do something like this: ``` ...
Try this to end a session. ``` sess = cherrypy.session sess['_cp_username'] = None ``` and try this to create a session... ``` cherrypy.session.regenerate() cherrypy.session['_cp_username'] = cherrypy.request.login ``` I used this example to handle most of my session activity. <http://tools.cherrypy.org/wiki/Authe...
Python: hex conversion always two digits
11,676,864
4
2012-07-26T19:44:47Z
11,676,894
7
2012-07-26T19:46:30Z
[ "python" ]
Does anyone know how to get a chr to hex conversion where the output is always two digits? for example, if my conversion yields 0x1, I need to convert that to `0x01`, since I am concatenating a long hex string. The code that I am using is: `hexStr += hex(ord(byteStr[i]))[2:]` Thanks.
You can use the format function: ``` >>> format(10, '02x') '0a' ``` You won't need to remove the `0x` part with that (like you did with the `[2:]`)
Python: hex conversion always two digits
11,676,864
4
2012-07-26T19:44:47Z
11,676,895
11
2012-07-26T19:46:35Z
[ "python" ]
Does anyone know how to get a chr to hex conversion where the output is always two digits? for example, if my conversion yields 0x1, I need to convert that to `0x01`, since I am concatenating a long hex string. The code that I am using is: `hexStr += hex(ord(byteStr[i]))[2:]` Thanks.
You can use string formatting for this purpose: ``` >>> "0x{:02x}".format(13) '0x0d' >>> "0x{:02x}".format(131) '0x83' ``` **Edit**: Your code suggests that you are trying to convert a string to a hexstring representation. There is a much easier way to do this (Python2.x): ``` >>> "abcd".encode("hex") '61626364' ``...
PySide Qt: Auto vertical growth for TextEdit Widget, and spacing between widgets in a vertical layout
11,677,499
9
2012-07-26T20:27:59Z
11,764,475
10
2012-08-01T17:29:57Z
[ "python", "qt", "qt4", "pyqt", "pyside" ]
![enter image description here](http://i.stack.imgur.com/PgiSJ.png) I need to Solve two problems With my widget above. 1. I'd like to be able to define the amount of space put between the post widgets shown in the image (they look fine as is, but I wanna know it's done). 2. I'd like to grow the text edits vertically ...
## 1) Layouts The other answer on here is very unclear and possibly off about how layout margins work. Its actually very straightforward. 1. Layouts have content margins 2. Widgets have content margins Both of these define a padding around what they contain. A margin setting of 2 on a layout means 2 pixels of paddin...
Updating Pyqt Status Bar widget
11,677,604
3
2012-07-26T20:34:51Z
11,683,626
7
2012-07-27T07:51:02Z
[ "python", "qt", "pyqt" ]
How can I update the status bar widget? Also How can i use signals and threads instead of a button? Thanks! Can someone help me out, my code is not working, when i press the button nothing comes up, i also get an error: ``` Error: self.a = QtGui.QStatusBar.showMessage("System Status | Normal") TypeError: QStat...
You have this code: ``` self.a = QtGui.QStatusBar.showMessage("System Status | Normal") ver.addWidget(self.a) ``` `showMessage` is not a class method, you need a `QStatusBar` instance for it. I think you wanted to do this: ``` self.a = QtGui.QStatusBar(self) ver.addWidget(self.a) self.a.showMessa...
Subtract values in one list from corresponding values in another list - Python
11,677,860
10
2012-07-26T20:52:29Z
11,677,882
29
2012-07-26T20:53:51Z
[ "python", "list" ]
I have two lists: ``` A = [2, 4, 6, 8, 10] B = [1, 3, 5, 7, 9] ``` How do I subtract each value in one list from the corresponding value in the other list and create a list such that: ``` C = [1, 1, 1, 1, 1] ``` Thanks.
The easiest way is to use a list comprehension ``` C = [a - b for a, b in zip(A, B)] ``` or `map()`: ``` from operator import sub C = map(sub, A, B) ```
SQL Server, Python, and OS X
11,678,696
9
2012-07-26T22:00:45Z
27,239,553
18
2014-12-01T23:54:06Z
[ "python", "sql-server", "osx", "pyodbc" ]
What's a good way to interface Python running on OS X with a cloud-based SQL Server database? EDIT: With pyodbc I'm getting this error: ``` >>> import pyodbc >>> cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=adsf.com;DATABASE=asdf;UID=asdf;PWD=asdf') Traceback (most recent call last): File "<stdin>", line 1, i...
**Summary** I'm using a Mac on Yosemite Version 10.10.1 trying to connect to a MS SQL Server database. I searched and couldn't find an updated detailed answer so here's a writeup that is mostly from this amazing article [here](http://www.cerebralmastication.com/2013/01/installing-debugging-odbc-on-mac-os-x/). I'm addi...
using gen.task with Tornado for a simple function
11,679,040
8
2012-07-26T22:35:40Z
11,683,014
17
2012-07-27T07:07:55Z
[ "python", "asynchronous", "web", "tornado" ]
Just trying to use the async functions of Tornado - I want to invoke a method from my handler but it keeps telling me that it "got an unexpected keyword argument 'callback'". ``` class MyHandler(tornado.web.RequestHandler): @asynchronous @gen.engine def get(self): response = yield gen.Task(self.do...
Non-blocking function requires callback, where it pass result. ``` class MyHandler(tornado.web.RequestHandler): @asynchronous @gen.engine def get(self): response = yield gen.Task(self.dosomething, 'argument') self.write(response) self.finish() def dosomething(self, myargument,...
Python subprocess arguments
11,679,936
4
2012-07-27T00:29:38Z
11,680,512
9
2012-07-27T02:03:08Z
[ "python", "subprocess", "command-line-arguments" ]
For example I am using `ffplay` and want to run this command `-bufsize[:stream_specifier] integer (output,audio,video)` At the moment I have this: ``` subprocess.call(["ffplay", "-vn", "-nodisp","-bufsize 4096", "%s" % url]) ``` But this says it is invalid.
As JBernardo mentioned in a comment, separate the `"-bufsize 4096"` argument into two, `"-bufsize", "4096"`. Each argument needs to be separated when `subprocess.call` is used with `shell=False` (the default). You can also specify `shell=True` and give the whole command as a single string, but this is not recommended d...
Twitter Bootstrap Website Deployed with GAE
11,681,557
7
2012-07-27T04:42:27Z
11,681,624
19
2012-07-27T04:50:13Z
[ "python", "google-app-engine", "twitter-bootstrap", "blogs" ]
So I'm a programming noob. I have been following many of the Udacity classes and I am slowly learning to code. Alright so here's my question. I have built the basic HTML files of my blog using Twitter Bootstrap as it is so simple to use. Now what I would like to do is to combine the great template's that Bootstrap pro...
It is perfectly possible. Download bootstrap to a separate folder and in your app.yaml file, have your handler which is a `static_dir` for /bootstrap ``` application: application-name version: 1 runtime: python api_version: 1 handlers: - url: /stylesheets static_dir: stylesheets - url: /bootstrap static_dir: boo...
Twitter Bootstrap Website Deployed with GAE
11,681,557
7
2012-07-27T04:42:27Z
11,681,641
10
2012-07-27T04:52:10Z
[ "python", "google-app-engine", "twitter-bootstrap", "blogs" ]
So I'm a programming noob. I have been following many of the Udacity classes and I am slowly learning to code. Alright so here's my question. I have built the basic HTML files of my blog using Twitter Bootstrap as it is so simple to use. Now what I would like to do is to combine the great template's that Bootstrap pro...
Have a look at gae-boilerplate. Its based on webapp2 and twitter bootstrap. * Docs <https://github.com/coto/gae-boilerplate> * demo <http://appengine.beecoss.com/> It does pretty much what you want out of the box along with a bunch of other features you may well want.
Convert integer to hex in Python
11,683,294
2
2012-07-27T07:30:08Z
11,683,317
8
2012-07-27T07:31:24Z
[ "python", "integer", "hex" ]
In Python I want to tranform the integer `3892` into a hexcode with the given format and the result `\x00\x00\x0F\x34`. How can this be achieved?
You are converting to a binary representation of the number, not so much a hex representation (although Python will display the bytes as hex). Use the [`struct` module](http://docs.python.org/library/struct.html) for such conversions. Demonstration: ``` >>> struct.pack('>I', 3892) '\x00\x00\x0f4' >>> struct.pack('>I'...
Django: How to test for 'HttpResponsePermanentRedirect'
11,683,347
4
2012-07-27T07:33:24Z
11,683,427
12
2012-07-27T07:38:04Z
[ "python", "django", "http" ]
I'm writing some tests for my django app.In my view,it redirects to some other url using 'HttpResponseRedirect'.So how can I test that?
``` from django.http import HttpResponsePermanentRedirect from django.test.client import Client class MyTestClass(unittest.TestCase): def test_my_method(self): client = Client() response = client.post('/some_url/') self.assertEqual(response.status_code, 301) self.assertTrue(isins...
Django: How to test for 'HttpResponsePermanentRedirect'
11,683,347
4
2012-07-27T07:33:24Z
11,684,751
13
2012-07-27T09:07:05Z
[ "python", "django", "http" ]
I'm writing some tests for my django app.In my view,it redirects to some other url using 'HttpResponseRedirect'.So how can I test that?
The Django `TestCase` class has a method [`assertRedirects`](https://docs.djangoproject.com/en/1.6/topics/testing/overview/#django.test.SimpleTestCase.assertRedirects) that you can use. ``` from django.test import TestCase class MyTestCase(TestCase): def test_my_redirect(self): """Tests that /my-url/ pe...
Django STATIC_URL is not working
11,683,748
13
2012-07-27T08:00:45Z
11,684,482
21
2012-07-27T08:50:48Z
[ "python", "django", "web", "django-staticfiles" ]
Django version is 1.4. I had read the `official document`, and googled my problem. first I had followed the official document [Managing static files](https://docs.djangoproject.com/en/1.4/howto/static-files/) added this in `settings.py`: ``` TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.debug', ...
Change ``` return render_to_response('register.html', 'errors':errors) ``` to ``` return render_to_response('register.html', {'errors': errors}, RequestContext(request)) ```
Python 2.7 print() error
11,685,359
4
2012-07-27T09:48:34Z
11,685,379
10
2012-07-27T09:50:04Z
[ "python", "linux", "python-2.7", "opensuse" ]
I have a strange error using `sep`, `file`, (etc.) arguments of python's `print()` function. I tried to google it out, dag around stackoverflow, and read [python's documentation](http://docs.python.org/library/functions.html) but I came up with nothing. I have attached a simple snippet, I would deeply appreciate any he...
Try: ``` from __future__ import print_function ``` first
How to extract chains from a PDB file?
11,685,716
3
2012-07-27T10:09:49Z
11,686,524
10
2012-07-27T11:05:36Z
[ "python", "bash", "bioinformatics", "biopython" ]
I would like to extract chains from pdb files. I have a file named pdb.txt which contains pdb IDs as shown below. The first four characters represent PDB IDs and last character is the chain IDs. ``` 1B68A 1BZ4B 4FUTA ``` I would like to 1) read the file line by line 2) download the atomic coordinates of each chain f...
The following BioPython code should suit your needs well. It uses `PDB.Select` to only select the desired chains (in your case, one chain) and `PDBIO()` to create a structure containing just the chain. ``` import os from Bio import PDB class ChainSplitter: def __init__(self, out_dir=None): """ Create pa...
Python AttributeError: Object has no attribute
11,685,936
15
2012-07-27T10:24:10Z
11,686,212
35
2012-07-27T10:41:22Z
[ "python" ]
I have a class MyThread. In that I have a method sample. I am trying to run it from withing the same object context. Please have a look at the code: ``` class myThread (threading.Thread): def __init__(self, threadID, name, counter, redisOpsObj): threading.Thread.__init__(self) self.threadID = threa...
Your indentation is goofed, and you've mixed tabs and spaces. Run the script with `python -tt` to verify.
Python RegExp global flag
11,686,516
5
2012-07-27T11:05:06Z
11,686,930
12
2012-07-27T11:33:06Z
[ "python", "regex", "global", "flags" ]
Is there a flag or some special key in python to use pattern multiple times. I used to test <http://gskinner.com/RegExr/> my RegExp, it worked correctly in it. But when testing in correct enviorment match only returns *None*. ``` import re pattern = r"(?P<date>--\d\d-\w+:\d\d)[ \t]+(?P<user>\w+)[ \t]+(?P<method>[\w ]+...
`re.match` tries to match the pattern at the start of the string. You are looking for `re.search`, `re.findall` or `re.finditer`
Is there a numpy builtin to reject outliers from a list
11,686,720
33
2012-07-27T11:19:17Z
11,686,764
44
2012-07-27T11:22:30Z
[ "python", "numpy" ]
Is there a numpy builtin to do something like the following? That is, take a list `d` and return a list `filtered_d` with any outlying elements removed based on some assumed distribution of the points in `d`. ``` import numpy as np def reject_outliers(data): m = 2 u = np.mean(data) s = np.std(data) fi...
This method is almost identical to yours, just more numpyst (also working on numpy arrays only): ``` def reject_outliers(data, m=2): return data[abs(data - np.mean(data)) < m * np.std(data)] ```
Is there a numpy builtin to reject outliers from a list
11,686,720
33
2012-07-27T11:19:17Z
16,562,028
58
2013-05-15T09:58:26Z
[ "python", "numpy" ]
Is there a numpy builtin to do something like the following? That is, take a list `d` and return a list `filtered_d` with any outlying elements removed based on some assumed distribution of the points in `d`. ``` import numpy as np def reject_outliers(data): m = 2 u = np.mean(data) s = np.std(data) fi...
Something important when dealing with outliers is that one should try to use estimators as robust as possible. The mean of a distribution will be biased by outliers but e.g. the median will be much less. Building on eumiro's answer: ``` def reject_outliers(data, m = 2.): d = np.abs(data - np.median(data)) mde...
More efficient to convert string to int or inverse?
11,687,183
3
2012-07-27T11:49:41Z
11,687,256
9
2012-07-27T11:53:54Z
[ "python", "string", "int", "type-conversion", "performance" ]
I'm currently writing a script, which at some point needs to compare numbers provided to the script by two different sources/inputs. One source provides the numbers as integers and one source provides them as strings. I need to compare them, so I need to use either `str()` on the integers or `int()` on the strings. As...
``` $ python -m timeit "int('92184') == 92184" 1000000 loops, best of 3: 0.482 usec per loop $ python -m timeit "str(92184) == '92184'" 1000000 loops, best of 3: 0.241 usec per loop ``` There you go, you should convert ints to strings and compare. Note that this just works if you want to see if they're *equal*. If you...
PyCharm not recognizing Python files
11,687,302
27
2012-07-27T11:56:48Z
11,687,851
40
2012-07-27T12:34:12Z
[ "python", "pycharm" ]
My PyCharm is no longer recognizing python files (attached screenshot) The interpreter path is correctly set. ![Screen shot](http://i.stack.imgur.com/sml3Y.jpg)
Please check `Settings` | `File Types`, ensure that file name or extension is not listed in **Text files**. To fix the problem remove it from the **Text files** and double check that `.py` extension is associated with **Python files**.
PyCharm not recognizing Python files
11,687,302
27
2012-07-27T11:56:48Z
11,689,682
7
2012-07-27T14:17:32Z
[ "python", "pycharm" ]
My PyCharm is no longer recognizing python files (attached screenshot) The interpreter path is correctly set. ![Screen shot](http://i.stack.imgur.com/sml3Y.jpg)
Got it to work finally! I had this same problem. I tried removing the pycharm caches in the ~/Library folders to no avail. Kept saying in the log that "Some skeletons failed to generate..." So, here is what worked. 1. Go into **preferences** 2. In the project settings click **project interpreters** and then **Config...
PyCharm not recognizing Python files
11,687,302
27
2012-07-27T11:56:48Z
12,697,112
19
2012-10-02T19:39:57Z
[ "python", "pycharm" ]
My PyCharm is no longer recognizing python files (attached screenshot) The interpreter path is correctly set. ![Screen shot](http://i.stack.imgur.com/sml3Y.jpg)
I had a similar problem where certain `.py` files were showing up as regular text files after completion, thus rendering the code without syntax coloring, tab completion features, etc. Through using this post as a starting point for debugging the issue, I found the following: 1. (from OSX): PyCharm → Preferences →...
Convert a filename to a file:// URL
11,687,478
22
2012-07-27T12:08:18Z
14,298,190
26
2013-01-12T21:38:56Z
[ "python", "url", "filenames" ]
In WeasyPrint’s public API I accept filenames (among other types) for the HTML inputs. Any filename that works with the built-in `open()` should work, but I need to convert it to an URL in the `file://` scheme that will later be passed to `urllib.urlopen()`. (Everything is in URL form internally. I need to have a "b...
I'm not sure the docs are rigorous enough to guarantee it, but I think this works in practice: ``` import urlparse, urllib def path2url(path): return urlparse.urljoin( 'file:', urllib.pathname2url(path)) ```
Convert a filename to a file:// URL
11,687,478
22
2012-07-27T12:08:18Z
31,905,972
19
2015-08-09T15:43:25Z
[ "python", "url", "filenames" ]
In WeasyPrint’s public API I accept filenames (among other types) for the HTML inputs. Any filename that works with the built-in `open()` should work, but I need to convert it to an URL in the `file://` scheme that will later be passed to `urllib.urlopen()`. (Everything is in URL form internally. I need to have a "b...
For completeness, in Python 3.4+, you should do: ``` import pathlib pathlib.Path(absolute_path_string).as_uri() ```
Operations on rows in scipy sparse matrix of csr format
11,687,953
2
2012-07-27T12:40:19Z
11,689,726
10
2012-07-27T14:19:55Z
[ "python", "numpy", "scipy" ]
I would like to multiply single rows of a csr matrix with a scalar. In numpy I would do ``` matrix[indices,:] = x * matrix[indices,:] ``` For csr this raises an exception in scipy. Is there a way to do this similarily with csr matrixes?
No, there's no way to this directly, because although you can compute `row * x`, you can't assign to a row in a CSR matrix. You can either convert to DOK format and back, or work on the innards of the CSR matrix directly. The `i`'th row of a CSR matrix `X` is the slice ``` X.data[X.indptr[i] : X.indptr[i + 1]] ``` wh...
How to show continuous real time updates like facebook ticker, meetup.com home page does?
11,688,397
6
2012-07-27T13:08:46Z
11,691,276
16
2012-07-27T15:46:47Z
[ "php", "python", "node.js", "asynchronous", "real-time" ]
How to show continuous real time updates in browser like facebook ticker, meetup.com home page does? In python, PHP, node.js and what would be the performance impact at the server side ? Also how could we achieve the same update thing if the page is cached by an CDN like akamai?
You have two options (that others have detailed above). In case you are not familiar with some of the conceptual ideas behind each option, I figured I'd give a line or two about them. Note that I'm presenting these concepts at a very, very high-level. Your three options are: 1. Short-Polling 2. Web Socket 3. Comet / ...
python creates everything from heap?
11,688,647
6
2012-07-27T13:23:57Z
11,688,685
10
2012-07-27T13:25:48Z
[ "python", "variables" ]
in c/c++, you have variables in stack when you create a local variable inside a function. <http://effbot.org/zone/call-by-object.htm> > CLU objects exist independently of procedure activations. Space > for objects is allocated from a dynamic storage area /.../ In > theory, all objects continue to exist forever. In pr...
Yes, all Python objects live on the heap (at least on CPython.) They are reference-counted: they are de-allocated when the last reference to the object disappear. (CPython also has a garbage collector to break cycles.) In CPython your first list disappears as soon as the function returns since you did not bind the ret...
TypeError: function() argument after * must be a sequence, not generator
11,689,862
6
2012-07-27T14:27:25Z
11,689,944
8
2012-07-27T14:32:34Z
[ "python", "typeerror" ]
While trying to write a tiny, obfuscated type checker, an unacceptable code pattern was discovered. However, it inconsistently fails to work properly. This is the code that was initally written to test it with. ``` def statictypes(a): def b(a, b, c): if b in a and not isinstance(c, a[b]): raise TypeError('...
1. Because `isinstance`, like a couple of other screwy standard library functions, does a different thing when you give it a tuple than other sequences. Namely, it works, and checks that the type is any of the ones given. 2. Because it isn't. See the [sequence protocol definition](http://docs.python.org/library/collect...
python byRef // copy
11,690,220
5
2012-07-27T14:48:46Z
11,690,298
10
2012-07-27T14:52:23Z
[ "python" ]
I am new to Python (and dont know much about programming anyway), but I remember reading that python generally does not copy values so any statement a = b makes b point to a. If I run ``` a = 1 b = a a = 2 print(b) ``` gives the result 1. Should that not be 2?
No, the result should be 1. Think of the assignment operator ( `=` ) as the assignment of a reference. ``` a = 1 #a references the integer object 1 b = a #b and a reference the same object a = 2 #a now references a new object (2) print b # prints 1 because you changed what a references, not b ``` This whole distinct...
Is it possible to return two lists from a function in python
11,690,333
7
2012-07-27T14:54:34Z
11,690,343
22
2012-07-27T14:55:14Z
[ "python", "python-2.7" ]
I am new to python programming and need your help for the following: I want to return two lists from a function in python. How can i do that. And how to read them in the main program. Examples and illustrations would be very helpful. Thanks in advance.
You can return a tuple of lists, an use sequence unpacking to assign them to two different names when calling the function: ``` def f(): return [1, 2, 3], ["a", "b", "c"] list1, list2 = f() ```
There is a class matplotlib.axes.AxesSubplot, but the module matplotlib.axes has no attribute AxesSubplot
11,690,597
14
2012-07-27T15:08:17Z
11,690,800
16
2012-07-27T15:19:13Z
[ "python", "matplotlib" ]
The code ``` import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) print type(ax) ``` gives the output ``` <class 'matplotlib.axes.AxesSubplot'> ``` Then the code ``` import matplotlib.axes matplotlib.axes.AxesSubplot ``` raises the exception ``` AttributeError: 'module' object has no attr...
Heh. That's because there *is* no `AxesSubplot` class.. until one is needed, when one is built from `SubplotBase`. This is done by some magic in `axes.py`: ``` def subplot_class_factory(axes_class=None): # This makes a new class that inherits from SubplotBase and the # given axes_class (which is assumed to be ...
Python beautifulsoup - getting input value
11,691,271
6
2012-07-27T15:46:15Z
25,284,165
8
2014-08-13T10:48:09Z
[ "python", "beautifulsoup" ]
I've got many table rows like this: ``` <tr> <td>100</td> <td>200</td> <td><input type="radio" value="123599"></td> </tr> ``` Iterate with: ``` table = BeautifulSoup(response).find(id="sometable") # Make soup. for row in table.find_all("tr")[1:]: # Find rows. cells = row.find_all("td") # Find cells....
``` soup = BeautifulSoup(html) try: value = soup.find('input', {'id': 'xyz'}).get('value') except: pass ```
Matlab VS Python - eig(A,B) VS sc.linalg.eig(A,B)
11,691,981
3
2012-07-27T16:34:01Z
11,692,290
9
2012-07-27T16:56:40Z
[ "python", "matlab", "numpy", "scipy", "eigenvalue" ]
I have the following matrices sigma and sigmad: sigma: ``` 1.9958 0.7250 0.7250 1.3167 ``` sigmad: ``` 4.8889 1.1944 1.1944 4.2361 ``` If I try to solve the generalized eigenvalue problem in python I obtain: ``` d,V = sc.linalg.eig(matrix(sigmad),matrix(sigma)) ``` V: ``` -1 ...
Any (nonzero) scalar multiple of an eigenvector will also be an eigenvector; only the direction is meaningful, not the overall normalization. Different routines use different conventions -- often you'll see the magnitude set to 1, or the maximum value set to 1 or -1 -- and some routines don't even bother being internal...
string.translate() with unicode data in python
11,692,199
16
2012-07-27T16:49:09Z
11,693,937
25
2012-07-27T18:50:26Z
[ "python", "unicode", "dictionary" ]
I have 3 API's that return json data to 3 dictionary variables. I am taking some of the values from the dictionary to process them. I read the specific values that I want to the list `valuelist`. One of the steps is to remove the punctuation from them. I normally use `string.translate(None, string.punctuation)` for thi...
The translate method work differently on Unicode objects than on byte-string objects: ``` >>> help(unicode.translate) S.translate(table) -> unicode Return a copy of the string S, where all characters have been mapped through the given translation table, which must be a mapping of Unicode ordinals to Unicode ordinals...
Python - sum values in dictionary
11,692,613
16
2012-07-27T17:21:44Z
11,692,630
48
2012-07-27T17:22:53Z
[ "python", "list", "dictionary" ]
I have got pretty simple list: ``` example_list = [ {'points': 400, 'gold': 2480}, {'points': 100, 'gold': 610}, {'points': 100, 'gold': 620}, {'points': 100, 'gold': 620} ] ``` How can I sum all *gold* values? I'm looking for nice oneliner. Now I'm using this code (but it's not the best solution): ...
``` sum(item['gold'] for item in myLIst) ```
How to create a DLL with SWIG from Visual Studio 2010
11,693,047
13
2012-07-27T17:50:27Z
11,732,619
34
2012-07-31T03:20:04Z
[ "c++", "python", "visual-studio-2010", "swig" ]
I've been trying for weeks to get Microsoft Visual Studio 2010 to create a DLL for me with SWIG. If you have already gone through this process, would you be so kind as to give a thoughtful step-by-step process explanation? I've looked everywhere online and have spent many many hours trying to do this; but all of the tu...
Step-by-step instructions. This assumes you have the source and are building a single DLL extension that links the source directly into it. I didn't go back through it after creating a working project, so I may have missed something. Comment on this post if you get stuck on a step. If you have an existing DLL and want ...
Understanding recursion in Python
11,693,819
3
2012-07-27T18:43:09Z
11,693,942
9
2012-07-27T18:50:38Z
[ "python", "algorithm", "python-2.7", "recurrence", "induction" ]
I'm really trying to wrap my brain around how recursion works and understand recursive algorithms. For example, the code below returns 120 when I enter 5, excuse my ignorance, and I'm just not seeing why? ``` def fact(n): if n == 0: return 1 else: return n * fact(n-1) answer = int (raw_input('...
Break the problem down into its execution steps. ``` fact(5) | 5 * fact(4) || 5 * (4 * fact(3)) ||| 5 * (4 * (3 * fact(2)) |||| 5 * (4 * (3 * (2 * fact(1)))) ||||| 5 * (4 * (3 * (2 * (1 * fact(0))))) |||||| 5 * 4 * 3 * 2 * 1 * 1 120 ``` Your function simply calls itself, just as any other function can call it. In th...
Understanding recursion in Python
11,693,819
3
2012-07-27T18:43:09Z
11,693,973
9
2012-07-27T18:52:34Z
[ "python", "algorithm", "python-2.7", "recurrence", "induction" ]
I'm really trying to wrap my brain around how recursion works and understand recursive algorithms. For example, the code below returns 120 when I enter 5, excuse my ignorance, and I'm just not seeing why? ``` def fact(n): if n == 0: return 1 else: return n * fact(n-1) answer = int (raw_input('...
lets walk through the execution. ``` fact(5): 5 is not 0, so fact(5) = 5 * fact(4) what is fact(4)? fact(4): 4 is not 0, so fact(4) = 4 * fact(3) what is fact(3)? fact(3): 3 is not 0, so fact(3) = 3 * fact(2) what is fact(2)? fact(2): 2 is not 0, so fact(2) = 2 * fact(1) what is fact(1)? fact(1...
tornado write a Jsonp object
11,694,124
8
2012-07-27T19:04:31Z
11,697,002
19
2012-07-27T23:49:53Z
[ "python", "json", "tornado" ]
any idea how to output a JSON object in python using Tornado. Any good examples, tutorial,libraries or one line code which outputs a JSONP object.
Tornado provides `tornado.escape.json_encode`, which simply wraps `json` on Python 2.6+ or `simplejson` on Python 2.5. It's simple to use: ``` from tornado.escape import json_encode obj = { 'foo': 'bar', '1': 2, 'false': True } self.write(json_encode(obj)) ``` outputs: ``` {"1": 2, "foo": "bar", ...
Tornado: Identify / track connections of websockets?
11,695,375
14
2012-07-27T20:41:55Z
11,697,191
19
2012-07-28T00:25:00Z
[ "python", "websocket", "tornado" ]
I have a basic Tornado websocket test: ``` import tornado.httpserver import tornado.websocket import tornado.ioloop import tornado.web class WSHandler(tornado.websocket.WebSocketHandler): def open(self): print 'new connection' self.write_message("Hello World") def on_message(self, message): ...
The simplest method is just to keep a list or dict of WSHandler instances: ``` class WSHandler(tornado.websocket.WebSocketHandler): clients = [] def open(self): self.clients.append(self) print 'new connection' self.write_message("Hello World") def on_message(self, message): ...
Tornado: Identify / track connections of websockets?
11,695,375
14
2012-07-27T20:41:55Z
11,707,348
18
2012-07-29T07:01:02Z
[ "python", "websocket", "tornado" ]
I have a basic Tornado websocket test: ``` import tornado.httpserver import tornado.websocket import tornado.ioloop import tornado.web class WSHandler(tornado.websocket.WebSocketHandler): def open(self): print 'new connection' self.write_message("Hello World") def on_message(self, message): ...
Cole Maclean asnwer is good as simple solution, when you just need list of all connections. However, if you want something more complex, that can be monitored outside of `WSHandler` instance - be brave do it like this: ``` class WSHandler(tornado.websocket.WebSocketHandler): def open(self): self.id = uuid...
Python: ValueError: unsupported format character ''' (0x27) at index 1
11,695,801
7
2012-07-27T21:20:50Z
11,696,152
19
2012-07-27T21:54:05Z
[ "python", "mysql", "mysql-python" ]
I'm trying to execute a query to search 3 tables in a database using MySQL through Python. Every time I try and execute the following string as a query, it gives me an error about concatenation in the string. ``` "SELECT fileid FROM files WHERE description LIKE '%" + search + "%' OR filename LIKE '%" + search + "%' OR...
It looks like python is interpreting the % as a printf-like format character. Try using %%? ``` "SELECT fileid FROM files WHERE description LIKE '%%%s%%' OR filename LIKE '%%%s%%' OR uploader LIKE '%%%s%%' ORDER BY fileid DESC" % (search, search, search) ```
Python - converting a list of tuples to a list of strings
11,696,078
3
2012-07-27T21:48:18Z
11,696,095
11
2012-07-27T21:49:53Z
[ "python" ]
I have a list of tuples that looks like this: ``` [('this', 'is'), ('is', 'the'), ('the', 'first'), ('first', 'document'), ('document', '.')] ``` What is the most pythonic and efficient way to convert into this where each token is separated by a space: ``` ['this is', 'is the', 'the first', 'first document', 'docume...
Very simple: ``` [ "%s %s" % x for x in l ] ```
seek() function?
11,696,472
35
2012-07-27T22:28:47Z
11,696,525
26
2012-07-27T22:34:39Z
[ "python" ]
Please excuse my confusion here but I have read the documentation regarding the seek() function in python (after having to use it) and although it helped me I am still a bit confused on the actual meaning of what it does, any explanations are much appreciated, thank you.
When you open a file, the system points to the beginning of the file. Any read or write you do will happen from the beginning. A seek() operation moves that pointer to some other part of the file so you can read or write at that place. So, if you want to read the whole file but skip the first 20 bytes, open the file, ...
seek() function?
11,696,472
35
2012-07-27T22:28:47Z
11,696,554
64
2012-07-27T22:38:48Z
[ "python" ]
Please excuse my confusion here but I have read the documentation regarding the seek() function in python (after having to use it) and although it helped me I am still a bit confused on the actual meaning of what it does, any explanations are much appreciated, thank you.
Regarding `seek()` there's not too much to worry about. First of all, it is useful when operating over an open file. It's important to note that its syntax is as follows: ``` fp.seek(offset, from_what) ``` where `fp` is the file pointer you're working with; `offset` means how many positions you will move; `from_wha...
Google Cloud Messaging HTTP Error 400: Bad Request
11,697,096
10
2012-07-28T00:04:28Z
12,036,928
9
2012-08-20T11:36:16Z
[ "python", "google-cloud-messaging" ]
I am trying to send a message through GCM (Google Cloud Messaging). I have registered through Google APIs, I can send a regID to my website (which is a Google App Engine Backend) from multiple Android test phones. However, I can't send anything to GCM from Google App Engine. Here is what I am trying to use. ``` re...
What are data2 and data3 used for ? The data you are posting was not proper json so you need to use json.dumps(data).Code should be like this : ``` json_data = {"collapse_key" : "Food-Promo", "data" : { "Category" : "FOOD", "Type": "VEG", }, "registration_ids": [regId], } u...
Iterate over numpy matrix of unknown dimension
11,697,274
2
2012-07-28T00:44:08Z
11,697,303
7
2012-07-28T00:49:20Z
[ "python", "matrix", "numpy", "enumerate" ]
I have a multidimensional numpy array I'd like to iterate over. I want to be able to access not only the values, but also their indices. Unfortunately, ``` for idx,val in enumerate(my_array): ``` doesn't seem to work when my\_array is multidimensional. (I'd like idx to be a tuple). Nested for loops might work, but I ...
I think you want [ndenumerate](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndenumerate.html): ``` >>> import numpy >>> a = numpy.arange(6).reshape(1,2,3) >>> a array([[[0, 1, 2], [3, 4, 5]]]) >>> list(numpy.ndenumerate(a)) [((0, 0, 0), 0), ((0, 0, 1), 1), ((0, 0, 2), 2), ((0, 1, 0), 3), ((0, 1, 1...
Python sys.modules contains a module which is not yet imported
11,697,633
7
2012-07-28T02:00:38Z
11,697,953
8
2012-07-28T03:14:22Z
[ "python" ]
I'm trying to understand the difference between a loaded module vs. an imported module, if there is any. I'm working in Python 2.7.3, and am just running Python from the command line. If I execute: ``` import sys sys.modules ``` I get a list which includes `os`, for example. The documentation says that `sys.modules...
The difference between a module being imported and being loaded is what is placed into your current module's namespace. A module will only get loaded once (in ordinary situations), but can be imported many times, from many different places. A loaded module may not be accessible in a given namespace, if it hasn't been i...
Comparing two lists in Python
11,697,709
4
2012-07-28T02:19:23Z
11,697,720
9
2012-07-28T02:21:41Z
[ "python", "string", "list", "variables", "comparison" ]
So to give a rough example without any code written for it yet, I'm curious on how I would be able to figure out what both lists have in common. Example: ``` listA = ['a', 'b', 'c'] listB = ['a', 'h', 'c'] ``` I'd like to be able to return: ``` ['a', 'c'] ``` How so? Possibly with variable strings like: ``` john...
Use set intersection for this: ``` list(set(listA) & set(listB)) ``` gives: ``` ['a', 'c'] ``` Note that since we are dealing with *sets* this may *not* preserve order: ``` ' '.join(list(set(john.split()) & set(mary.split()))) 'I and love yellow' ``` using `join()` to convert the resulting list into a string. --...
Converting Django QuerySet to pandas DataFrame
11,697,887
33
2012-07-28T02:59:02Z
16,271,849
21
2013-04-29T05:39:15Z
[ "python", "django", "pandas" ]
I am going to convert a Django QuerySet to a pandas DataFrame as follows: ``` qs = SomeModel.objects.select_related().filter(date__year=2012) q = qs.values('date', 'OtherField') df = pd.DataFrame.from_records(q) ``` It works, but is there a more efficient way?
``` import pandas as pd import datetime from myapp.models import BlogPost df = pd.DataFrame(list(BlogPost.objects.all().values())) df = pd.DataFrame(list(BlogPost.objects.filter(date__gte=datetime.datetime(2012, 5, 1)).values())) # limit which fields df = pd.DataFrame(list(BlogPost.objects.all().values('author', 'dat...
project structure for wrapping many c++ classes in cython to a single shared object
11,698,482
19
2012-07-28T05:13:55Z
11,804,020
19
2012-08-03T22:15:33Z
[ "c++", "python", "design-patterns", "cython" ]
I have found partial answers between the docs, mailing lists, and [this question here](http://stackoverflow.com/questions/10300660/cython-and-distutils), but I wanted to get a more direct answer addressing my specifics... I'm learning cython by trying to wrap small parts, little by little, of a library that I am alrea...
While waiting for a definitive answer, I kept playing around with organizing my code. The including of `pyx` files into a single `pyx` for compilation has been working so far. My `setup.py` is simple like: ``` ext_modules = [ Extension( "openni", ["src/openni.pyx"], language="c++", ...
Two Python modules require each other's contents - can that work?
11,698,530
19
2012-07-28T05:22:55Z
11,698,542
24
2012-07-28T05:25:48Z
[ "python", "python-module" ]
I have a Bottle webserver module with the following line: ``` from foobar.formtools import auto_process_form_insert ``` And the `foobar.formtools` module contains this line: ``` from foobar.webserver import redirect, redirect_back ``` Of course, both result in the following errors (respectively): > ImportError: ca...
Modules *can* import each other cyclically, but there's a catch. In the simple case, it should work by moving the `import` statements to the bottom of the file or not using the `from` syntax. Here's why that works: When you import a module, Python first checks `sys.modules`. If it's in there, it just imports from the...
Two Python modules require each other's contents - can that work?
11,698,530
19
2012-07-28T05:22:55Z
11,698,590
7
2012-07-28T05:37:47Z
[ "python", "python-module" ]
I have a Bottle webserver module with the following line: ``` from foobar.formtools import auto_process_form_insert ``` And the `foobar.formtools` module contains this line: ``` from foobar.webserver import redirect, redirect_back ``` Of course, both result in the following errors (respectively): > ImportError: ca...
Don't do `from ... import ...`. Just do `import ...` and reference its objects using the module name.
OpenCV 2.4 VideoCapture not working on Windows
11,699,298
32
2012-07-28T07:55:28Z
11,703,998
49
2012-07-28T19:28:35Z
[ "python", "windows", "opencv" ]
I'm using Python bindings to OpenCV 2.4 installed with following [instructions](http://opencvpython.blogspot.com/2012/05/install-opencv-in-windows-for-python.html). My problem is similar to [this one](http://stackoverflow.com/questions/11444926/videocapture-is-not-working-in-opencv-2-4-2), but I need Windows machine s...
Add `C:\OpenCV\3rdparty\ffmpeg\` to the Windows PATH environment variable or copy `opencv_ffmpeg.dll` from that directory to `C:\Python27\` or to a directory that is in the PATH. Alternatively, use the OpenCV binaries from <http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv>.
OpenCV 2.4 VideoCapture not working on Windows
11,699,298
32
2012-07-28T07:55:28Z
17,672,734
25
2013-07-16T09:25:51Z
[ "python", "windows", "opencv" ]
I'm using Python bindings to OpenCV 2.4 installed with following [instructions](http://opencvpython.blogspot.com/2012/05/install-opencv-in-windows-for-python.html). My problem is similar to [this one](http://stackoverflow.com/questions/11444926/videocapture-is-not-working-in-opencv-2-4-2), but I need Windows machine s...
Copying **opencv\_ffmpeg.dll** wasn't enough for me - I had to rename it to **opencv\_ffmpeg246.dll**, when I used OpenCV 2.4.6 with Python 2.7.5
OpenCV 2.4 VideoCapture not working on Windows
11,699,298
32
2012-07-28T07:55:28Z
22,559,572
7
2014-03-21T13:02:20Z
[ "python", "windows", "opencv" ]
I'm using Python bindings to OpenCV 2.4 installed with following [instructions](http://opencvpython.blogspot.com/2012/05/install-opencv-in-windows-for-python.html). My problem is similar to [this one](http://stackoverflow.com/questions/11444926/videocapture-is-not-working-in-opencv-2-4-2), but I need Windows machine s...
I first tried copying, then changing the Path environment of windows.. it didn't work until i changed the name to opencv\_ffmpeg245.dll for my openCV version 2.4.5 and python 2.7. (notice \*\*245.dll is from opencv version 2.4.5)