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
In Python, what is the underscore in front of the instance variable?
6,700,826
9
2011-07-14T22:41:47Z
6,700,879
8
2011-07-14T22:45:59Z
[ "python", "oop" ]
What convention is it? ``` class IndexedText(object): def __init__(self, stemmer, text): self._text = text self._stemmer = stemmer self._index = nltk.Index((self._stem(word), i) for (i, word) in enumerate(text)) ```
According to [PEP 8](http://www.python.org/dev/peps/pep-0008/): > In addition, the following special forms using leading or trailing > underscores are recognized (these can generally be combined with any case > convention): > > * \_single\_leading\_underscore: weak "internal use" indicator. E.g. "from M > import \*"...
How do I merge dictionaries together, using weights?
6,701,358
2
2011-07-15T00:01:14Z
6,701,747
7
2011-07-15T01:15:54Z
[ "python", "dictionary", "computer-science" ]
``` d1 = {'weight':1, 'data': { 'apples': 8, 'oranges': 7 } } d2 = {'weight':3, 'data': { 'apples': 4, 'bananas': 3 } } all_dictionaries = [d1, d2, ... ] def mergeDictionariesWithWeight(all_dictionaries) ``` How do I merge these dictionaries together (if overlap, multiple value with the weight) The function would re...
``` >>> from collections import defaultdict >>> d=defaultdict(lambda:(0,0)) >>> for D in all_dictionaries: ... weight = D['weight'] ... for k,v in D['data'].items(): ... d[k]=d[k][0]+weight*v,d[k][1]+weight ... >>> dict((k,v[0]/v[1]) for k,v in d.items()) {'apples': 5, 'oranges': 7, 'bananas': 3} ``` If you n...
Numpy - Replace a number with NaN
6,701,714
10
2011-07-15T01:08:59Z
6,701,756
22
2011-07-15T01:17:28Z
[ "python", "arrays", "numpy", null, "gdal" ]
I am looking to replace a number with NaN in numpy and am looking for a function like numpy.nan\_to\_num, except in reverse. The number is likely to change as different arrays are processed because each can have a uniquely define NoDataValue. I have see people using dictionaries, but the arrays are large and filled wi...
``` A[A==NDV]=numpy.nan ``` A==NDV will produce a boolean array that can be used as an index for A
Parentheses pairing ({}[]()<>) issue
6,701,853
6
2011-07-15T01:36:33Z
6,701,927
11
2011-07-15T01:54:41Z
[ "python", "parentheses", "syntax-checking" ]
I want to be able to pair up all parentheses in a string, if they aren't paired then then they get their index number and False. It seems like it is repeating some values over and over, i.e cl == pop[1]. I have tried to see where the problem is but I can't see it no matter how hard I try. So I'm asking if anyone help m...
You can adapt my code to a similar question: ``` def Evaluate(str): stack = [] pushChars, popChars = "<({[", ">)}]" for c in str : if c in pushChars : stack.append(c) elif c in popChars : if not len(stack) : return False else : stackTop = stack.pop() balancingBra...
Python ZeroMQ PUSH/PULL -- Lost Messages?
6,702,187
8
2011-07-15T02:47:07Z
6,704,128
14
2011-07-15T07:59:51Z
[ "python", "zeromq" ]
I am trying to use `python` with `zeroMQ` in `PUSH / PULL` mode, sending messages of size **4[MB]** every few seconds. For some reason, while it looks like all the messages are sent, ONLY SOME of them appear to have been received by the server. What am I missing here? Here's the code for the client -- `client.py` ``...
The problem is that when the program exits, the socket gets closed immediately and garbage collected with an effective LINGER of 0 (i.e. it throws any unsent messages away). This is a problem for larger messages because they take longer to send than it takes for the socket to be garbage collected. You can avoid this b...
How can I detect double click events in matplotlib?
6,703,242
3
2011-07-15T05:58:00Z
17,753,195
9
2013-07-19T18:34:54Z
[ "python", "events", "double-click", "matplotlib" ]
``` import matplotlib.pyplot as plt def onclick(event): print event.button fig = plt.figure() connection_id = fig.canvas.mpl_connect('button_press_event', onclick) plt.show() ``` With a construct like this, I have the problem of double-clicks hitting `onclick()` handler *three* times. I guess that it is receivin...
When i had matplotlib version 1.1rc, i was not able to catch dblclick event. Later, I wrote code for matplotlib 1.2 and that is ok ``` import matplotlib.pyplot as plt fig = plt.figure() def onclick(event): if event.dblclick: print event.button connection_id = fig.canvas.mpl_connect('button_press_event', ...
How do I do a get_or_create in pymongo (python mongodb)?
6,703,330
5
2011-07-15T06:10:58Z
6,703,404
9
2011-07-15T06:21:21Z
[ "python", "mongodb", "pymongo" ]
First, find if a document matching query exists. If so, update that document with the new data. Otherwise, insert a new document into the database.
You can use "upsert" equal to true. Then the update query you run with "upsert" as true will do exactly what you want. * update if exists. * insert new if it does not exist. From MongoDb documentation: ``` db.collection.update( criteria, objNew, upsert, multi ) Arguments: criteria - query which selects the rec...
Limit the queryset of entries displayed for a django admin Inline
6,703,652
9
2011-07-15T07:04:57Z
6,741,937
13
2011-07-19T03:18:49Z
[ "python", "django", "django-admin" ]
In django admin, using django 1.2, i'm trying to add a InlineModelAdmin to apply a comment on save when a change is made to an entry. (An entry is expected to have a "ChangeComment" for every edit). I don't want to show previous entries, so I am trying to force the *ChangeCommentInline*'s formset.queryset to be empty,...
As benjaoming mentioned in the comments, it was necessary to override the `get_queryset()` method in the `InlineModelAdmin`. It was not necessary to override and attach a new formset to the `InlineModelAdmin` definition as I initially thought. Here is the resulting implementation: ``` class ChangeCommentInline(admin....
Deleting certain files using python
6,703,668
5
2011-07-15T07:06:31Z
6,703,696
12
2011-07-15T07:11:10Z
[ "python" ]
I have a py script that processes files with extension '.hgx'.Example : test.hgx ( there are many such files with extension hgx) The script processes the test.hgx and creates a new test\_bac.hgx and on re-run it creates test\_bac\_bac.hgx. So everytime running the script creates a file with **'\_bac'.** Is there some...
``` import os import glob for hgx in glob.glob("*_bac.hgx"): os.remove(hgx) ```
Is there an easy way to write this in Python?
6,703,993
2
2011-07-15T07:43:30Z
6,704,040
10
2011-07-15T07:48:17Z
[ "python", "numbers", "max", "min" ]
``` if(i-words < 0): start_point = 0 else: start_point = i - words ``` Or is this the easiest way using min/max? This is for lists splicing. I want start\_point to always be 0 or above.
Better is to make the limiting more obvious ``` start_point = max(i - words, 0) ``` This way, anyone reading can see that you're limiting a value. Using any form of `if` has the disadvantage that you compute twice `i - words`. Using a temporary for this will make more code bloat. So, use `max` and `min` in these ca...
Python equivalent of Ruby's 'method_missing'
6,704,151
17
2011-07-15T08:03:28Z
6,704,345
23
2011-07-15T08:22:26Z
[ "python", "ruby", "oop", "metaprogramming" ]
What is Python's equivalent of Ruby's `method_missing` method? I tried using `__getattr__` but this hook applies to fields too. I only want to intercept the method invocations. What is the Python way to do it?
There is no difference in Python between properties and methods. A method is just a property, whose type is just `instancemethod`, that happens to be callable (supports `__call__`). If you want to implement this, your `__getattr__` method should return a function (a `lambda` or a regular `def`, whatever suite your nee...
Best way to do conditional assignment in python
6,704,711
13
2011-07-15T08:55:45Z
6,704,736
29
2011-07-15T08:58:32Z
[ "python" ]
I tend to use this a lot, but it's ugly: ``` a = (lambda x: x if x else y)(get_something()) ``` So I wrote this function: ``` def either(val, alt): if val: return val else: return alt ``` So you can do: ``` a = either(get_something(), y) ``` Is there a built-in function for this (similar t...
The `or` operator does what you want: ``` get_something() or y ``` In fact, it's chainable, like `COALESCE` (and unlike `ISNULL`). The following expression evaluates to the left-most argument that converts to True. ``` A or B or C ```
epydoc AttributeError: 'Text' object has no attribute 'data'
6,704,770
5
2011-07-15T09:01:26Z
6,705,529
7
2011-07-15T10:14:25Z
[ "python", "epydoc" ]
I've not used epydoc in the last 2 years but I found it very handy to take track of my classes and methods with a very little effort. Today I installed latest version `3.0.1` but I get this error and searching around seems no solutions are provided. ``` Traceback (most recent call last):-] Parsing docstrings: pyramid...
I found a patch on epydoc tracker, it was outdated anyway this part solves the problem: ``` markup/restructuredtext.py 307c307,310 < m = self._SUMMARY_RE.match(child.data) --- > try: > m = self._SUMMARY_RE.match(child.data) > except AttributeError: > ...
rotating xticks causes the ticks partially hidden in matplotlib
6,705,581
11
2011-07-15T10:19:21Z
6,715,540
15
2011-07-16T05:26:05Z
[ "python", "matplotlib", "rotation", "label" ]
I am creating a plot with names on x axis and time values(minutes) on y axis.The names on x axis are like ``` ['cooking']18:15:27 ,['study']18:09:19,['travel']18:21:34` etc .. ``` where as the y values are 5,1,1 etc.I have given xlabel as 'categories' and ylabel as 'durations in minutes'. Since the xticks were stri...
One good option is to rotate the tick labels. In your specific case, you might find it convenient to use `figure.autofmt_xdate()` (Which will rotate the x-axis labels among other things). Alternatively, you could do `plt.setp(plt.xticks()[1], rotation=30)` (or various other ways of doing the same thing). Also, as a ...
rotating xticks causes the ticks partially hidden in matplotlib
6,705,581
11
2011-07-15T10:19:21Z
21,122,190
10
2014-01-14T19:25:12Z
[ "python", "matplotlib", "rotation", "label" ]
I am creating a plot with names on x axis and time values(minutes) on y axis.The names on x axis are like ``` ['cooking']18:15:27 ,['study']18:09:19,['travel']18:21:34` etc .. ``` where as the y values are 5,1,1 etc.I have given xlabel as 'categories' and ylabel as 'durations in minutes'. Since the xticks were stri...
``` plt.tight_layout() ``` But be sure to add this command *after* `plt.plot()` or `plt.bar()`
datetime in defining database using sqlalchemy
6,706,161
13
2011-07-15T11:11:17Z
6,706,726
20
2011-07-15T12:07:30Z
[ "python", "sqlalchemy" ]
Should I use () with datetime.now in defining tables? What code wrong 1 or 2? 1: ``` Base = declarative_base() class T(Base): __tablename__ = 't' created = Column(DateTime, default=datetime.now) ``` 2: ``` Base = declarative_base() class T(Base): __tablename__ = 't' created = Column(DateTime, defa...
You want the first case. What you're doing is telling SqlAlchemy than whenever a row is inserted, run this function (callable) to get the default value. That can be any callable function or a string value. This way the function is called exactly at insert time and you get the correct date that it was inserted. If you...
Fetching datetime from float and vice versa in python
6,706,231
5
2011-07-15T11:16:54Z
6,706,556
15
2011-07-15T11:48:31Z
[ "python" ]
Could any tell me how to get the datetime from float in python? For e.g i have float number as let's say 43111.0,now i want to get the datetime for this.
Looks like an Excel datetime format, called [serial date](http://www.cpearson.com/excel/datetime.htm). Quick and dirty way to convert it: ``` >>> import datetime >>> serial = 43111.0 >>> seconds = (serial - 25569) * 86400.0 >>> datetime.datetime.utcfromtimestamp(seconds) datetime.datetime(2018, 1, 11, 0, 0) ```
How come Python's dict doesn't have .iter()?
6,706,318
3
2011-07-15T11:25:05Z
6,706,336
12
2011-07-15T11:26:35Z
[ "python" ]
``` def complicated_dot(v, w): dot = 0 for (v_i, w_i) in zip(v, w): for x in v_i.iter(): if x in w_i: dot += v_i[x] + w_i[x] return float(dot) ``` I'm getting an error that says: ``` AttributeError: 'dict' object has no attribute 'iter' ```
[It has `iter`](http://docs.python.org/library/functions.html#iter). But you can just write ``` for x in v_i: ```
How come Python's dict doesn't have .iter()?
6,706,318
3
2011-07-15T11:25:05Z
6,706,337
8
2011-07-15T11:26:38Z
[ "python" ]
``` def complicated_dot(v, w): dot = 0 for (v_i, w_i) in zip(v, w): for x in v_i.iter(): if x in w_i: dot += v_i[x] + w_i[x] return float(dot) ``` I'm getting an error that says: ``` AttributeError: 'dict' object has no attribute 'iter' ```
``` v_i.itervalues() ``` You have [`iterkeys`](http://docs.python.org/library/stdtypes.html#dict.iterkeys), [`iteritems`](http://docs.python.org/library/stdtypes.html#dict.iteritems) and [`itervalues`](http://docs.python.org/library/stdtypes.html#dict.itervalues). Choose one.
How come Python's dict doesn't have .iter()?
6,706,318
3
2011-07-15T11:25:05Z
6,714,079
16
2011-07-15T23:06:56Z
[ "python" ]
``` def complicated_dot(v, w): dot = 0 for (v_i, w_i) in zip(v, w): for x in v_i.iter(): if x in w_i: dot += v_i[x] + w_i[x] return float(dot) ``` I'm getting an error that says: ``` AttributeError: 'dict' object has no attribute 'iter' ```
Considering the following [`dict`](http://www.python.org/doc//current/library/stdtypes.html#dict): ``` >>> d {'a': 1, 'c': 3, 'b': 2} ``` You can just iterate over the keys like so: ``` >>> for k in d: ... print(k, d[k]) ... ('a', 1) ('c', 3) ('b', 2) ``` This implicitly calls the special method [`__iter__()`]...
Python - using subprocess to call sed?
6,706,953
4
2011-07-15T12:29:15Z
6,707,003
8
2011-07-15T12:33:30Z
[ "python", "sed", "subprocess" ]
I wish to call **sed** from python using subprocess. The script I tried using is below. however, this pipes the sed output to the standard terminal. It seems that the '>' operator is not recognised from within my subprocess.call statement. Any suggestions? ``` import sys import os import subprocess files = os.listd...
Use ``` out_file = open(outp, "w") sub = subprocess.call(['sed', 's/\"//g', inp], stdout=out_file ) ```
Python - detect charset and convert to utf-8
6,707,657
21
2011-07-15T13:24:14Z
6,707,677
29
2011-07-15T13:25:30Z
[ "python", "utf-8", "python-2.x" ]
Is there any universal method to detect string charset? I user IPTC tags and have no known encoding. I need to detect it and then change them to utf-8. Anybody can help?
You want to use [`chardet`](http://pypi.python.org/pypi/chardet), an encoding detector
Python - detect charset and convert to utf-8
6,707,657
21
2011-07-15T13:24:14Z
9,137,199
12
2012-02-04T00:12:57Z
[ "python", "utf-8", "python-2.x" ]
Is there any universal method to detect string charset? I user IPTC tags and have no known encoding. I need to detect it and then change them to utf-8. Anybody can help?
It's a bit late, but there is also another solution: try to use [pyicu](http://pypi.python.org/pypi/PyICU/0.8.1). An example: ``` import icu def convert_encoding(data, new_coding='UTF-8'): coding = icu.CharsetDetector(data).detect().getName() if new_coding.upper() != coding.upper(): data = unicode(dat...
Python - detect charset and convert to utf-8
6,707,657
21
2011-07-15T13:24:14Z
26,382,720
7
2014-10-15T12:32:59Z
[ "python", "utf-8", "python-2.x" ]
Is there any universal method to detect string charset? I user IPTC tags and have no known encoding. I need to detect it and then change them to utf-8. Anybody can help?
If you want to do it with cchardet, you can use this function. ``` import cchardet def convert_encoding(data, new_coding = 'UTF-8'): encoding = cchardet.detect(data)['encoding'] if new_coding.upper() != encoding.upper(): data = data.decode(encoding, data).encode(new_coding) return data ```
How to call a python function from another file
6,708,125
14
2011-07-15T14:00:15Z
6,708,174
10
2011-07-15T14:04:04Z
[ "python" ]
I have this class in my parser.py file ``` class HostInfo(object): def __init__(self, host_id): self.osclass = [] self.osmatch = [] self.osfingerprint = [] self.portused = [] self.ports = [] self.extraports = [] self.tcpsequence = {} self.hostnames = [] self.tcptssequence = {} s...
``` from parser import HostInfo obj = HostInfo(<whatever host_id you need here>) obj.get_id ``` this is the way, how are you actually doing it?
Remove one column for a numpy array
6,710,684
17
2011-07-15T17:07:40Z
6,710,726
23
2011-07-15T17:10:41Z
[ "python", "arrays", "numpy" ]
I have a numpy array of dimension (48, 366, 3) and I want to remove the last column from the array to make it (48, 365, 3). What is the best way to do that? (All the entries are integers. I'm using Python v2.6)
You could try `numpy.delete`: <http://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.html> or just get the slice of the array you want and write it to a new array. For example: ``` a = np.random.randint(0,2,size=(48,366,3)) b = np.delete(a,np.s_[-1:],1) print b.shape # <--- (48,365,3) ``` or equivalentl...
Iterating over list or single element in python
6,710,834
14
2011-07-15T17:20:12Z
6,711,233
19
2011-07-15T17:56:33Z
[ "python" ]
I would like to iterate over the outputs of an unknown function. Unfortunately I do not know whether the function returns a single item or a tuple. This must be a standard problem and there must be a standard way of dealing with this -- what I have now is quite ugly. ``` x = UnknownFunction() if islist(x): iterato...
The most general solution to this problem is to use `isinstance` with the abstract base class `collections.Iterable`. ``` import collections def get_iterable(x): if isinstance(x, collections.Iterable): return x else: return (x,) ``` You might also want to test for `basestring` as well, as [Ki...
python - same instruction, different outcome
6,711,311
7
2011-07-15T18:03:45Z
6,711,326
14
2011-07-15T18:05:20Z
[ "python", "python-3.x" ]
Could someone help me understand what is going on in the following Python code (python 3.2)? I'm really clueless here. ``` import sys u = sys.stdin.readline() # try entering the string "1 2 3" r = map(lambda t: int(t.strip()),u.split()) print(sum(r)) # prints 6 print(sum(r)) # prints 0 ? ``` Thank you.
`map()` in Python 3.x returns an iterator, not a list. Putting it through `sum()` the first time consumes it, leaving nothing for the second time.
How to use python regex to replace using captured group?
6,711,567
20
2011-07-15T18:25:10Z
6,711,631
30
2011-07-15T18:31:25Z
[ "python", "regex", "sed", "replace" ]
Suppose I want to change `the blue dog and blue cat wore blue hats` to `the gray dog and gray cat wore blue hats`. With `sed` I could accomplish this as follows: ``` $ echo 'the blue dog and blue cat wore blue hats' | sed 's/blue \(dog\|cat\)/gray \1/g' ``` How can I do a similar replacement in Python? I've tried: ...
You need to escape your backslash: ``` p.sub('gray \\1', s) ``` alternatively you can use a raw string as you already did for the regex: ``` p.sub(r'gray \1', s) ```
How to use python regex to replace using captured group?
6,711,567
20
2011-07-15T18:25:10Z
24,514,054
7
2014-07-01T15:29:16Z
[ "python", "regex", "sed", "replace" ]
Suppose I want to change `the blue dog and blue cat wore blue hats` to `the gray dog and gray cat wore blue hats`. With `sed` I could accomplish this as follows: ``` $ echo 'the blue dog and blue cat wore blue hats' | sed 's/blue \(dog\|cat\)/gray \1/g' ``` How can I do a similar replacement in Python? I've tried: ...
As I was looking for a similar answer; but wanting using named groups within the replace, I thought I'd add the code for others: ``` p = re.compile(r'blue (?P<animal>dog|cat)') p.sub(r'gray \g<animal>',s) ```
what's the alternative to nested classes in Python
6,712,442
2
2011-07-15T19:53:22Z
6,712,482
7
2011-07-15T19:56:55Z
[ "python", "multithreading", "nested-class" ]
I read a post stating that 'nested classes wasn't pythonic' what's the alternative please forgive me, this isn't the best example but it's the basic concept. a nested class for performing a task. I'm basically having to connect to a service in multiple threads. ``` import threading, imporedlib class Mother(threading...
You want to use composition: ``` import threading, importedlib class Child: def __init__(self, parent): self.parent=parent def run(self): importedlib.runajob(parent.VAL1, parent.VAL2) class Mother(threading.Thread): def __init__(self,val1,val2): self.VAL1 = val1 self.VA...
Converting from a C double transferred in two hex strings
6,713,569
8
2011-07-15T21:52:38Z
6,713,636
9
2011-07-15T22:00:11Z
[ "python", "string", "floating-point", "hex", "double" ]
my very first day with Python. I like to filter on a trace file generated by C. Each double from C is formatted in the file by two hex strings representing 32 bit of the 64 double. e.g. 1234567890.3 (C double) inside file: ``` 0xb4933333 0x41d26580 ``` How can I parse and combine it to further work with a Python ...
You can use `struct`, using the 'd' modifier for 'double': ``` >>> import struct >>> num1 = '0xb4933333' >>> num2 = '0x41d26580' >>> struct.unpack('!d', (num2[2:]+num1[2:]).decode('hex'))[0] 1234567890.3 ``` Be careful what order you append the doubles in, the above assumes a big-endian machine. Also, I stripped `0x`...
setuptools: data files included with `bdist` but not with `sdist`
6,714,145
8
2011-07-15T23:17:26Z
6,714,408
10
2011-07-16T00:12:51Z
[ "python", "setuptools", "setup.py" ]
I've got a `setup.py` file which looks like this: ``` #!/usr/bin/env python from setuptools import setup, find_packages setup( name="foo", version="1.0", packages=find_packages(), include_package_data=True, package_data={ "": ["*"], }, ) ``` And a package `foo` which looks like this: ...
There are different sources for selecting those files. The package\_data is used for installing from the source tree. The build a source package you also need a MANIFEST.in file. It should contain something like `recursive-include *.txt`, or whatever you need.
"TypeError: string indices must be integers" when trying to make 2D array in python
6,714,527
6
2011-07-16T00:48:36Z
6,714,549
20
2011-07-16T00:53:55Z
[ "python", "arrays", "2d" ]
I'm so kind of new to python (and coding) and I just want to create a board (for a console game) based on the player desire. Basically it's this... ``` import array print("What size do you want the board?") Boardsize = input() Tablero = array('b' [Boardsize, Boardsize]) for w in Boardsize: for h in Boardsize: ...
**What's going on** `input()` returns a string (the characters you typed in, e.g. "123"), but you are getting a `TypeError` because you are passing a string to something that expects a number (e.g. 123, without the quotes). --- **Solution** The fix is convert the string to a number by passing it through the `int(.....
How can I determine the byte length of a utf-8 encoded string in Python?
6,714,826
18
2011-07-16T02:10:33Z
6,714,866
33
2011-07-16T02:24:20Z
[ "python", "unicode", "utf-8" ]
I am working with Amazon S3 uploads and am having trouble with key names being too long. S3 limits the length of the key by bytes, not characters. From the docs: > The name for a key is a sequence of Unicode characters whose UTF-8 encoding is at most 1024 bytes long. I also attempt to embed metadata in the file name...
``` def utf8len(s): return len(s.encode('utf-8')) ``` Works fine in Python 2 and 3.
How to avoid getting billed on EC2 for unused time?
6,714,988
4
2011-07-16T02:58:56Z
7,586,527
7
2011-09-28T16:35:58Z
[ "python", "amazon-ec2", "distributed" ]
I have a periodic task that I need to run on the EC2. This task will not take more than 10 minutes to run and I do not want to end up paying for the other 50 minutes that this task will be idle for. From my understanding, if I start an instance and run this task, no matter whether I use any resources or not, I will be ...
Try [picloud](http://www.picloud.com/) and pay per second.
How to add Matplotlib Colorbar Ticks
6,715,442
6
2011-07-16T05:00:00Z
6,715,666
11
2011-07-16T05:57:53Z
[ "python", "matplotlib", "colorbar" ]
There are many matplotlib colorbar questions on stack overflow, but I can't make sense of them in order to solve my problem. How do I set the yticklabels on the colorbar? Here is some example code: ``` from pylab import * from matplotlib.colors import LogNorm import matplotlib.pyplot as plt f = np.arange(0,101) ...
Update the ticks and the tick labels: ``` cbar.set_ticks([mn,md,mx]) cbar.set_ticklabels([mn,md,mx]) ```
Non-blocking socket in Python?
6,715,944
7
2011-07-16T07:06:45Z
6,718,824
8
2011-07-16T16:46:56Z
[ "python", "sockets" ]
Is it me, or can I not find a good tutorial on non-blocking sockets in python? I'm not sure how to exactly work the `.recv` and the `.send` in it. According to the python docs, (my understanding of it, at least) the `recv`'ed or `send`'ed data might be only partial data. So does that mean I have to somehow concatenate...
It doesn't really matter if your socket is in non-blocking mode or not, recv/send work pretty much the same; the only difference is that non-blocking socket throws 'Resource temporarily unavailable' error instead of waiting for data/socket. **recv** method returns numbers of bytes received, which is told to be less or...
Conditionally show and hide a form field and set the field value
6,717,249
3
2011-07-16T12:09:21Z
6,717,408
8
2011-07-16T12:37:34Z
[ "python", "django", "django-forms", "form-fields" ]
I have a form in my Django that looks something like this: ``` class PersonnelForm(forms.Form): """ Form for creating a new personnel. """ username = forms.RegexField( required=True, max_length=30, label=_("Name") ) is_manager = forms.BooleanField( required=True, label=_("Is Man...
You could use the form's `__init__` method to hide (or delete) the field, i.e. ``` class PersonnelForm(forms.Form): """ Form for creating a new personnel. """ username = forms.RegexField( required=True, max_length=30, label=_("Name") ) is_manager = forms.BooleanField( required=T...
Python: Determine prefix from a set of (similar) strings
6,718,196
43
2011-07-16T15:03:31Z
6,718,435
75
2011-07-16T15:45:23Z
[ "python", "string", "prefix" ]
I have a set of strings, e.g. ``` my_prefix_what_ever my_prefix_what_so_ever my_prefix_doesnt_matter ``` I simply want to find the longest common portion of these strings, here the prefix. In the above the result should be ``` my_prefix_ ``` The strings ``` my_prefix_what_ever my_prefix_what_so_ever my_doesnt_matt...
Never rewrite what is provided to you: [`os.path.commonprefix`](https://docs.python.org/3/library/os.path.html#os.path.commonprefix) does exactly this: > Return the longest path prefix (taken > character-by-character) that is a prefix of all paths in list. If list > is empty, return the empty string (`''`). Note that ...
Python: Determine prefix from a set of (similar) strings
6,718,196
43
2011-07-16T15:03:31Z
6,719,272
11
2011-07-16T18:12:44Z
[ "python", "string", "prefix" ]
I have a set of strings, e.g. ``` my_prefix_what_ever my_prefix_what_so_ever my_prefix_doesnt_matter ``` I simply want to find the longest common portion of these strings, here the prefix. In the above the result should be ``` my_prefix_ ``` The strings ``` my_prefix_what_ever my_prefix_what_so_ever my_doesnt_matt...
[Ned Batchelder](http://stackoverflow.com/questions/6718196/python-determine-prefix-from-a-set-of-similar-strings/6718435#6718435) is probably right. But for the fun of it, here's a more efficient version of [phimuemue](http://stackoverflow.com/questions/6718196/python-determine-prefix-from-a-set-of-similar-strings/671...
Python: Yield Dict Elements in Producing Coroutines?
6,718,324
13
2011-07-16T15:24:56Z
6,718,392
14
2011-07-16T15:37:19Z
[ "python", "dictionary", "generator", "coroutine", "list-comprehension" ]
Before I say a word, let me thank the community for being *the* authoritative location for my programming queries as of recent. And pretend those compliments weren't expressed using words. Anyway, the law of probability dictated that I stumble across something I couldn't find using the versatile search bar, so I've dec...
Dict comprehensions do work like list/set comprehensions and generator expressions - an X comprehension with a "body" of `expr for vars in iterable` is pretty much equivalent to `X(expr for vars in iterable)` - and you already know how to turn a generator expression into a generator. But note the "pretty much" bit, as ...
Python regular expression again - match url
6,718,633
3
2011-07-16T16:13:19Z
6,718,683
7
2011-07-16T16:22:12Z
[ "python", "regex" ]
I have such regexp: ``` re.compile(r"((https?):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)", re.MULTILINE|re.UNICODE) ``` But that doesn't include hashbangs `(#!)`. What I need to change, to get it working? I know I can add ! to group with `#@%` etc, but that will select something like ``` Check this out: http://ex...
Don't try to make your own regular expression for matching URLs, use someone else's who has already solved such problems, like [this one](http://daringfireball.net/2010/07/improved_regex_for_matching_urls). There's one toward the bottom of the page for matching just HTTP and HTTPS URIs, which is probably the one you wa...
Python Psych Experiment needs (simple) database: please advise
6,718,872
5
2011-07-16T16:58:02Z
6,718,913
12
2011-07-16T17:04:18Z
[ "python", "database", "web-applications" ]
I am coding a psychology experiment in Python. I need to store user information and scores somewhere, and I need it to work as a web application (and be secure). Don't know much about this - I'm considering XML databases, BerkleyDB, sqlite, an openoffice spreadsheet, or I'm very interested in the python "shelve" libra...
SQLite can certainly handle those amount of data, it has a very large userbase with a few [very well known users](http://www.sqlite.org/famous.html) on all the major platforms, it's fast, light, and there are [awesome GUI clients](https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/) that allows you to browse...
Why CherryPy session does not require a secret key?
6,719,036
7
2011-07-16T17:28:26Z
7,061,520
18
2011-08-15T03:41:52Z
[ "python", "pylons", "web-frameworks", "cherrypy" ]
I noticed that cherrypy session does not require a secret key configuration. On the contrary, Pylons session does: <http://docs.pylonsproject.org/projects/pylons_framework/dev/sessions.html> I'm concerned about security issues if I'm using session to remember user authentication. Any one can explain why cherrypy sess...
There are basically two different ways of maintaining session state: on the server or on the client. With the server-side approach, you keep the session data in files, a database, or in memory on the server and assign an id to it. This session id is then sent to the client and usually stored in a cookie (although they...
Python distributions and environments for scientific computing
6,719,309
19
2011-07-16T18:20:38Z
6,719,391
27
2011-07-16T18:38:34Z
[ "python", "scientific-computing" ]
I apologize upfront if this question is too broad. I come from the MATLAB world and have relatively little experience with Python. After having spent some time reading about several Python-based environments and distributions for scientific computing, I feel that I still don't fully understand the landscape of solutio...
Scientific computing with Python is taking a plain vanilla language and bolting on a bunch of modules, each of which implement some aspect of the functionality of MATLAB. As such the experience with Python scientific programming is a little incohesive c.f. MATLAB. However Python as a language is much cleaner. So it goe...
how do I get django runserver to show me DeprecationWarnings and other useful messages?
6,719,513
13
2011-07-16T18:57:30Z
9,025,008
21
2012-01-26T20:40:00Z
[ "python", "django" ]
I've recently updated my django installation from 1.2 to 1.3. On my developer system I didn't get any warnings about deprecated calls. But once I moved the code onto my production apache server, I saw many 'DeprecationWarning' messages in my apache logs. So how do I have to call runserver to these these messages too? ...
[Python 2.7 disables the display of DeprecationWarning by default](http://docs.python.org/dev/whatsnew/2.7.html) To re-enable it, set environment variable PYTHONWARNINGS to "d": ``` export PYTHONWARNINGS="d"; ./manage.py runserver ```
passing bash variables to python script
6,719,549
9
2011-07-16T19:02:49Z
6,719,626
12
2011-07-16T19:15:59Z
[ "python", "bash" ]
What's the best way to pass bash variables to a python script. I'd like to do something like the following: ``` $cat test.sh #!/bin/bash foo="hi" python -c 'import test; test.printfoo($foo)' $cat test.py #!/bin/python def printfoo(str): print str ``` When I try running the bash script, I get a syntax error: `...
You can use [`os.getenv`](http://docs.python.org/library/os.html#os.getenv) to access environment variables from Python: ``` import os import test test.printfoo(os.getenv('foo')) ``` However, in order for environment variables to be passed from Bash to any processes it creates, you need to export them with the [`expo...
passing bash variables to python script
6,719,549
9
2011-07-16T19:02:49Z
6,719,629
7
2011-07-16T19:16:31Z
[ "python", "bash" ]
What's the best way to pass bash variables to a python script. I'd like to do something like the following: ``` $cat test.sh #!/bin/bash foo="hi" python -c 'import test; test.printfoo($foo)' $cat test.py #!/bin/python def printfoo(str): print str ``` When I try running the bash script, I get a syntax error: `...
In short, this works: ``` ... python -c "import test; test.printfoo('$foo')" ... ``` **Update:** If you think the string may contain single quotes(`'`) as said by @Gordon in the comment below, You can escape those single quotes pretty easily in bash. Here's a alternative solution in that case: ``` ... python -c "im...
What's the difference between a twistd plugin and a twistd service?
6,720,021
7
2011-07-16T20:27:40Z
6,720,425
7
2011-07-16T21:41:10Z
[ "python", "twisted", "twistd" ]
Apparently you can create services that are run with Twisted's twistd in two different ways. On the one hand you can create services using the [Twisted Application Infrastructure](http://twistedmatrix.com/documents/current/core/howto/application.html) and in the other you can create a service using the [Twisted Plugin ...
Looks like I found the answer: <http://twistedmatrix.com/pipermail/twisted-python/2009-September/020346.html> > > Which is the recommended or preferred way to deploy an app that will > > leverage twistd: designing the app as a twistd plugin or creating a > > Service and using a .tac file? > > A plugin is nicer in tha...
Setting exit code in Python when an exception is raised
6,720,119
14
2011-07-16T20:43:29Z
6,720,174
26
2011-07-16T20:52:41Z
[ "python", "exception", "exit-code" ]
``` $ cat e.py raise Exception $ python e.py Traceback (most recent call last): File "e.py", line 1, in <module> raise Exception Exception $ echo $? 1 ``` I would like to change this exit code from 1 to 3 while still dumping the full stack trace. What's the best way to do this?
Take a look at the [`traceback`](https://docs.python.org/2/library/traceback.html) module. You could do the following: ``` import sys, traceback try: raise Exception() except: traceback.print_exc() sys.exit(3) ``` This will write traceback to standard error and exit with code 3.
List comprehension in pure BASH?
6,720,660
4
2011-07-16T22:28:03Z
6,721,137
8
2011-07-17T00:21:12Z
[ "python", "bash", "list-comprehension" ]
Is it possible to do LC like in python and other languages but only using BASH constructs? What I would like to be able to do, as an example is this: ``` function ignoreSpecialFiles() { for options in "-L" "-e" "-b" "-c" "-p" "-S" "! -r" "! -w"; do if [[ $options "$1" -o $options "$2" ]];then ...
A loop in a command substitution looks like a list comprehension if you squint. Your second example could be written as: ``` M=$(for x in $S; do if [ $(( x % 2 )) == 0 ]; then echo $x; fi done) ```
Get all __slots__ of derived class
6,720,747
11
2011-07-16T22:46:39Z
6,720,815
7
2011-07-16T22:59:25Z
[ "python", "inheritance", "slots" ]
I need to initialise all slots of an instance with None. How do I get all slots of a derived class? Example (which does not work): ``` class A(object): __slots__ = "a" def __init__(self): # this does not work for inherited classes for slot in type(self).__slots__: setattr(self, sl...
First of all, it's ``` class A(object): __slots__ = ('a',) class B(A): __slots__ = ('b',) ``` Making a list that contains all elements contained by `__slots__` of B or any of its parent classes would be: ``` from itertools import chain slots = chain.from_iterable(getattr(cls, '__slots__', []) for cls in B._...
How to monkey patch Django?
6,720,858
8
2011-07-16T23:08:37Z
24,668,215
8
2014-07-10T03:55:21Z
[ "python", "django", "django-models", "monkeypatching" ]
I came upon this [post](http://www.alrond.com/en/2008/may/03/monkey-patching-in-django/) on monkey patching Django: ``` from django.contrib.auth.models import User User.add_to_class('openid', models.CharField(max_length=250,blank=True)) def get_user_name(self): if self.first_name or self.last_name: retur...
put the file `monkey_patching.py` in any of your `apps` and import it in app's `__init__.py` file. ie: **app/monkey\_patching.py** ``` #app/monkey_patching.py from django.contrib.auth.models import User User.add_to_class('openid', models.CharField(max_length=250,blank=True)) def get_user_name(self): if self.fir...
"or die()" in Python
6,722,210
29
2011-07-17T06:05:17Z
6,722,239
10
2011-07-17T06:14:13Z
[ "python" ]
Is anyone using anything like this in Python: ``` def die(error_message): raise Exception(error_message) ... check_something() or die('Incorrect data') ``` I think this kind of style is used in PHP and Perl. Do you find any (dis)advantages in this [style]?
While that style is common in PHP and Perl, it's very un-Pythonic and I'd encourage you not to write Python that way. You should follow the conventions in the language you're using, and write something like this: ``` if not check_something(): raise Exception('Incorrect data') ``` FWIW, doing the "or die(...)" way...
"or die()" in Python
6,722,210
29
2011-07-17T06:05:17Z
6,722,262
43
2011-07-17T06:19:49Z
[ "python" ]
Is anyone using anything like this in Python: ``` def die(error_message): raise Exception(error_message) ... check_something() or die('Incorrect data') ``` I think this kind of style is used in PHP and Perl. Do you find any (dis)advantages in this [style]?
Well, first, [`sys.exit([arg])`](http://docs.python.org/library/sys.html#sys.exit) is more common, and if you really wanted something equivalent to `die` in PHP, you should use that, raise a [SystemExit](http://docs.python.org/library/exceptions.html#exceptions.SystemExit) error, or call [os.\_exit](http://docs.python....
"or die()" in Python
6,722,210
29
2011-07-17T06:05:17Z
6,722,835
21
2011-07-17T09:01:30Z
[ "python" ]
Is anyone using anything like this in Python: ``` def die(error_message): raise Exception(error_message) ... check_something() or die('Incorrect data') ``` I think this kind of style is used in PHP and Perl. Do you find any (dis)advantages in this [style]?
Lot's of good answers, but no-one has yet suggested the obvious way to write this in Python: ``` assert check_something(), "Incorrect data" ``` Just be aware that it won't do the check if you turn on optimisation, not that anyone ever does.
Python argparse: Make at least one argument required
6,722,936
46
2011-07-17T09:24:12Z
6,723,066
46
2011-07-17T09:51:37Z
[ "python", "argparse" ]
I've been using `argparse` for a Python program that can `-prepare`, `-upload` or both: ``` parser = argparse.ArgumentParser(description='Log archiver arguments.') parser.add_argument('-process', action='store_true') parser.add_argument('-upload', action='store_true') args = parser.parse_args() ``` The program is me...
``` if not (args.process or args.upload): parser.error('No action requested, add -process or -upload') ```
Python argparse: Make at least one argument required
6,722,936
46
2011-07-17T09:24:12Z
6,723,073
12
2011-07-17T09:52:42Z
[ "python", "argparse" ]
I've been using `argparse` for a Python program that can `-prepare`, `-upload` or both: ``` parser = argparse.ArgumentParser(description='Log archiver arguments.') parser.add_argument('-process', action='store_true') parser.add_argument('-upload', action='store_true') args = parser.parse_args() ``` The program is me...
If not the 'or both' part (I have initially missed this) you could use something like this: ``` parser = argparse.ArgumentParser(description='Log archiver arguments.') parser.add_argument('--process', action='store_const', const='process', dest='mode') parser.add_argument('--upload', action='store_const', const='uplo...
Python argparse: Make at least one argument required
6,722,936
46
2011-07-17T09:24:12Z
15,175,314
14
2013-03-02T13:59:23Z
[ "python", "argparse" ]
I've been using `argparse` for a Python program that can `-prepare`, `-upload` or both: ``` parser = argparse.ArgumentParser(description='Log archiver arguments.') parser.add_argument('-process', action='store_true') parser.add_argument('-upload', action='store_true') args = parser.parse_args() ``` The program is me...
``` args = vars(parser.parse_args()) if not any(args.values()): parser.error('No arguments provided.') ```
Fastest way in Python to find a 'startswith' substring in a long sorted list of strings
6,722,985
18
2011-07-17T09:34:22Z
6,723,093
13
2011-07-17T09:59:32Z
[ "python", "sorting", "performance" ]
I've done a lot of Googling, but haven't found anything, so I'm really sorry if I'm just searching for the wrong things. I am writing an implementation of the [Ghost](https://secure.wikimedia.org/wikipedia/en/wiki/Ghost_%28game%29) for [MIT Introduction to Programming, assignment 5](http://ocw.mit.edu/courses/electric...
Generator expressions are evaluated lazily, so if you only need to determine whether or not your word is valid, I would expect the following to be more efficient since it doesn't necessarily force it to build the full list once it finds a match: ``` def word_exists(wordlist, word_fragment): return any(w.startswith...
Python integer infinity for slicing
6,723,009
15
2011-07-17T09:39:08Z
6,723,022
22
2011-07-17T09:41:53Z
[ "python", "integer", "infinity" ]
I have defined a slicing parameter in a config file: ``` max_items = 10 ``` My class slices a list according to this parameter: ``` items=l[:config.max_itmes] ``` When `max_items = 0`, I want all items to be taken from `l`. The quick and dirty way is: ``` config.max_items=config.max_items if config.max_items>0 els...
There is no "infinity integer constant" in Python, but using `None` in a slice will cause it to use the default for the given position, which are the beginning, the end, and each item in sequence, for each of the three parts of a slice. ``` >>> 'abc'[:None] 'abc' ```
Getting PySide to work with matplotlib
6,723,527
20
2011-07-17T11:28:57Z
8,292,957
30
2011-11-28T08:05:25Z
[ "python", "matplotlib", "pyside" ]
I have tried running the [example code on the SciPy website](http://www.scipy.org/Cookbook/Matplotlib/PySide), but I get this error: ``` Traceback (most recent call last): File ".\matplotlibPySide.py", line 24, in <module> win.setCentralWidget(canvas) TypeError: 'PySide.QtGui.QMainWindow.setCentralWidget' called...
The example that you mention: <http://www.scipy.org/Cookbook/Matplotlib/PySide> works, but you might need to suggest the use of PySide: ``` ... matplotlib.use('Qt4Agg') matplotlib.rcParams['backend.qt4']='PySide' import pylab ... ```
python: How to debug multiprocess? (using eclipse+pydev)
6,724,149
6
2011-07-17T13:34:39Z
6,724,182
9
2011-07-17T13:38:40Z
[ "python", "eclipse", "debugging", "pydev", "multiprocess" ]
I've seen a couple of questions on the topic but I didn't get a full answer... My code is basically: ``` from multiprocessing import Process p = Process(target=f).start() p.join() def f(): print 'break!' ``` And I want to put a breakpoint on the `print`. I'm using pydev+eclipse (on Ubuntu).
Because the new process itself is not controlled by PyDev, you need to make PyDev debugger manually aware of through Remote Debugging facilities. <http://pydev.org/manual_adv_remote_debugger.html> Use pydevd.set\_trace() - notice that your breakpoints won't work (not sure if this has changed recent PyDev versions), b...
Python autocompletion on object instances in VIM
6,724,619
17
2011-07-17T14:54:34Z
6,765,623
14
2011-07-20T17:00:56Z
[ "python", "vim", "autocomplete" ]
I have found a strange behavior in VIM when I attempt to use autocompletion on objects: If I instantiate the objects on a module level, the VIM autocompletion will work on the instance I create: ![working completion](http://i.stack.imgur.com/ZAx5Q.png) If I try the same when in a function or class it is not longer w...
Even though it does not use Vim's omnicompletion plugin, by using rope, ropemode and ropevim it is possible to get autocompletion in methods: ![enter image description here](http://i.stack.imgur.com/DKS4i.png) Even though not really exactly what I wanted it works pretty well. I got it working like this: I installed ...
How can I close an image shown to the user with the Python Imaging Library?
6,725,099
7
2011-07-17T16:08:32Z
6,725,171
11
2011-07-17T16:22:59Z
[ "python", "python-imaging-library" ]
I have several images which I would like to show the user with Python. The user should enter some description and then the next image should be shown. This is my code: ``` #!/usr/bin/python # -*- coding: utf-8 -*- import os, glob from PIL import Image path = '/home/moose/my/path/' for infile in glob.glob( os.path.j...
The `show` method "is mainly intended for debugging purposes" and spawns an external process for which you don't get a handle, so you can't kill it in a proper way. With PIL, you may want to use one of its GUI modules , such as [`ImageTk`](http://www.pythonware.com/library/pil/handbook/imagetk.htm), [`ImageQt`](http:/...
How do I achieve the effect of the === operator in Python?
6,725,559
9
2011-07-17T17:37:36Z
6,725,569
15
2011-07-17T17:38:55Z
[ "python", "comparison", "identity-operator" ]
How do I achieve the effect of the `===` operator in Python? For example, I don't want `False == 0` to be `True`.
Try `variable is False`. `False is 0` returns `False`,
How do I achieve the effect of the === operator in Python?
6,725,559
9
2011-07-17T17:37:36Z
6,725,582
37
2011-07-17T17:40:25Z
[ "python", "comparison", "identity-operator" ]
How do I achieve the effect of the `===` operator in Python? For example, I don't want `False == 0` to be `True`.
If you want to check that the value and type are the same use: ``` x == y and type(x) == type(y) ``` In Python, explicit type comparisons like this are usually avoided, but because booleans are a subclass of integers it's the only choice here. --- `x is y` compares identity—whether two names refer to the same obj...
Generics/templates in python?
6,725,868
29
2011-07-17T18:30:43Z
6,725,913
35
2011-07-17T18:38:34Z
[ "python", "templates", "generic-programming" ]
How does python handle generic/template type scenarios? Say I want to create an external file "BinaryTree.py" and have it handle binary trees, but for any data type. So I could pass it the type of a custom object and have a binary tree of that object. How is this done in python?
Python uses [duck typing](http://en.wikipedia.org/wiki/Duck_typing), so it doesn't need special syntax to handle multiple types. If you're from a C++ background, you'll remember that, as long as the operations used in the template function/class are defined on some type `T` (at the syntax level), you can use that type...
Solving for unknown in bit-wise algebra
6,725,881
2
2011-07-17T18:32:36Z
6,725,911
7
2011-07-17T18:38:12Z
[ "python", "bitwise-xor" ]
Suppose I have 3 bytes, X Y and Z. X XOR Y results in Z. I know what X and Z are, but I don't know what Y is, so I'm writing a quick script to figure this out. Though, I don't know how I would even begin. I did a couple of them by hand and it was simply a matter of comparing each bit one by one, but how can I do thi...
If `x ^ y == z`, then `x ^ z == y`. You can verify this in Python with ``` >>> X = range(256) # all byte values >>> Y = range(256) >>> all(x ^ z == y for x in X for y in Y for z in [x^y]) ```
scipy stats geometric mean returns NaN
6,726,297
3
2011-07-17T19:42:40Z
6,726,333
9
2011-07-17T19:47:01Z
[ "python", "statistics", "numpy", "scipy", "mean" ]
I am using scipy's gmean() function to determine the geometric mean of a numpy array that contains voltage outputs. The range of the numbers is between -80.0 and 30.0. Currently, the numpy array is two dimensional, giving the voltage for two different measurements. ``` array([[-60.0924, -60.0882], [-80. , -8...
The geometric mean cannot be applied to negative values.
splitting and concatenating a string
6,726,636
5
2011-07-17T20:39:57Z
6,726,645
10
2011-07-17T20:41:36Z
[ "python", "string", "split", "append" ]
I was wondering if python had a built in function similar to ``` string->list ``` and `list->string` in scheme. So for example I would like to turn 'abc' into `['a','b','c']` and vice versa using a built in function.
String to list: ``` >>> list('abc') ['a', 'b', 'c'] ``` List to string: ``` >>> ''.join(['a', 'b', 'c']) 'abc' ```
Open the file in universal-newline mode using the CSV Django module
6,726,953
73
2011-07-17T21:37:56Z
6,739,807
124
2011-07-18T21:41:51Z
[ "python", "django", "osx", "csv", "newline" ]
I am trying to access a `model.filefield` in Django to parse a [CSV](http://en.wikipedia.org/wiki/Comma-separated_values) file in Python using the `csv` module. It's working on Windows, but on Mac it gave me this: ``` Exception Type: Error Exception Value: new-line character seen in unquoted field - do you need to op...
I finally found the solution: ``` mypath = customerbulk.objects.get(pk=1).fileup.path o = open(mypath,'rU') mydata = csv.reader(o) ```
Python: creating dictionary from a bunch of "key: value" strings?
6,727,394
2
2011-07-17T23:10:23Z
6,727,416
7
2011-07-17T23:13:50Z
[ "python", "list", "dictionary" ]
Suppose I have loaded this into a list: ``` info = ['apple: 1', 'orange: 2', 'grape: 3'] ``` How can I turn that into something like ``` info = {line[0]: line[1] for line.split(': ') in info} ``` So that I actually have a dict?
You're very close! ``` >>> info = ['apple: 1', 'orange: 2', 'grape: 3'] >>> info = dict(line.split(': ') for line in info) >>> info {'orange': '2', 'grape': '3', 'apple': '1'} ``` You could do it the way you tried to in Python 2.7+, but you'd have to split the lines separately, so using `dict` is better. Here's what...
How do I find the MD5 hash of an ISO file using Python?
6,727,926
3
2011-07-18T01:27:30Z
6,727,938
8
2011-07-18T01:30:15Z
[ "python", "md5", "iso", "hashlib" ]
I am writing a simple tool that allows me to quickly check MD5 hash values of downloaded ISO files. Here is my algorithm: ``` import sys import hashlib def main(): filename = sys.argv[1] # Takes the ISO 'file' as an argument in the command line testFile = open(filename, "r") # Opens and reads the ISO 'file' ...
The object created by `hashlib.md5` doesn't take a file object. You need to feed it data a piece at a time, and then request the hash digest. ``` import hashlib testFile = open(filename, "rb") hash = hashlib.md5() while True: piece = testFile.read(1024) if piece: hash.update(piece) else: # we're...
Explanation for argparse python modul behaviour: Where do the capital placeholders come from?
6,728,019
4
2011-07-18T01:50:47Z
6,728,027
7
2011-07-18T01:52:43Z
[ "python", "argparse" ]
I am trying to write a command line interface (for the first time) and after reading up about `argparse`, `optparse` and `getopt` I chose `argparse` because of several recommendations here on SO and elswhere in the net. Adapting a little of the [advice of Mr. van Rossum](http://www.artima.com/weblogs/viewpost.jsp?threa...
The capital letter items are just value placeholders; they're taken from the destination of the option. You can specify alternative placeholders via the `metavar=` param of `add_argument`: <http://docs.python.org/dev/library/argparse.html#metavar>
Convert Python str/unicode object to binary/hex blob
6,728,077
8
2011-07-18T02:06:09Z
6,728,094
15
2011-07-18T02:10:53Z
[ "python", "string", "unicode", "binary" ]
Is there an easy way to get some str/unicode object represented as a big binary number (or an hex one)? I've been reading some answers to related questions but none of them works for my scenario. I tried using the [struct](http://docs.python.org/library/struct.html) module from the **STL** but it didn't work as expec...
You could try [`bitarray`](http://pypi.python.org/pypi/bitarray): ``` >>> import bitarray >>> b = bitarray.bitarray() >>> b.fromstring('a') >>> b bitarray('01100001') >>> b.to01() '01100001' >>> b.fromstring('pples') >>> b.tostring() 'apples' >>> b.to01() '011000010111000001110000011011000110010101110011' ```
Exception thrown in multiprocessing Pool not detected
6,728,236
37
2011-07-18T02:46:12Z
7,678,125
16
2011-10-06T17:23:57Z
[ "python", "exception", "multiprocessing" ]
It seems that when an exception is raised from a multiprocessing.Pool process, there is no stack trace or any other indication that it has failed. Example: ``` from multiprocessing import Pool def go(): print(1) raise Exception() print(2) p = Pool() p.apply_async(go) p.close() p.join() ``` prints 1 and...
I have a reasonable solution for the problem, at least for debugging purposes. I do not currently have a solution that will raise the exception back in the main processes. My first thought was to use a decorator, but you can only pickle [functions defined at the top level of a module](http://docs.python.org/library/pic...
Exception thrown in multiprocessing Pool not detected
6,728,236
37
2011-07-18T02:46:12Z
8,708,806
30
2012-01-03T06:41:14Z
[ "python", "exception", "multiprocessing" ]
It seems that when an exception is raised from a multiprocessing.Pool process, there is no stack trace or any other indication that it has failed. Example: ``` from multiprocessing import Pool def go(): print(1) raise Exception() print(2) p = Pool() p.apply_async(go) p.close() p.join() ``` prints 1 and...
Maybe I'm missing something, but isn't that what the `get` method of the Result object returns? See [Process Pools](http://docs.python.org/library/multiprocessing.html#module-multiprocessing.pool). > class multiprocessing.pool.AsyncResult > > The class of the result returned by Pool.apply\_async() and Pool.map\_async(...
Exception thrown in multiprocessing Pool not detected
6,728,236
37
2011-07-18T02:46:12Z
28,660,669
8
2015-02-22T17:09:31Z
[ "python", "exception", "multiprocessing" ]
It seems that when an exception is raised from a multiprocessing.Pool process, there is no stack trace or any other indication that it has failed. Example: ``` from multiprocessing import Pool def go(): print(1) raise Exception() print(2) p = Pool() p.apply_async(go) p.close() p.join() ``` prints 1 and...
The solution with the most votes at the time of writing has a problem: ``` from multiprocessing import Pool def go(): print(1) raise Exception("foobar") print(2) p = Pool() x = p.apply_async(go) x.get() ## waiting here for go() to complete... p.close() p.join() ``` As @dfrankow noted, it will wait on `...
Paging output from python
6,728,661
15
2011-07-18T04:34:50Z
18,234,081
21
2013-08-14T14:10:19Z
[ "python" ]
I'm trying to implement something similar to `git log`, which will only page the output if the log is of a certain length. If you're not familiar with git, I'm essentially trying to achieve this: ``` python some_script.py | less ``` With some help from the paging implementation in python2.6/pydoc.py, I was able to co...
How about this: ``` import pydoc text = '... some text ... ' pydoc.pager(text) ``` This (on my opensuse linux box) sends the text to a pager ('less' in my case), and works the same as calling "help(... python command...)" within the Python interpreter.
How do I make this list function faster?
6,728,719
7
2011-07-18T04:49:56Z
6,732,222
15
2011-07-18T11:31:08Z
[ "python", "algorithm", "list", "optimization", "dictionary" ]
``` def removeDuplicatesFromList(seq): # Not order preserving keys = {} for e in seq: keys[e] = 1 return keys.keys() def countWordDistances(li): ''' If li = ['that','sank','into','the','ocean'] This function would return: { that:1, sank:2, into:3, the:4, ocean:5 } However,...
``` import collections def countWordDistances(li): wordmap = collections.defaultdict(list) for i, w in enumerate(li, 1): wordmap[w].append(i) for k, v in wordmap.iteritems(): wordmap[k] = sum(v)/float(len(v)) return wordmap ``` This makes only one pass through the list, and keeps opera...
Solr: best documented, easy to use, stable Python APIs
6,728,944
9
2011-07-18T05:33:35Z
7,787,789
13
2011-10-16T22:26:20Z
[ "python", "solr" ]
I want to use Lucene Solr in Python. There seems to be multiple APIs for this purpose. They seem to suffer dependency hell and stability issues, and Solr doesnt ship with python bindings anymore. And I **cant find any documentation for the user who is not familiar with Solr**. I am leaning on Sunburnt over pysolr and ...
**Always** know Solr independently of any client library like Sunburnt, pysolr, solrpy, etc. Just as you have to know relational databases before using any ORM. Moreover, no ORM documentation will teach you relational databases, and no one would expect it to do so.
decoding shift-jis: "illeagal multibyte sequence"
6,729,016
4
2011-07-18T05:44:06Z
6,729,130
7
2011-07-18T06:02:05Z
[ "python", "encoding", "hex", "decode", "shift-jis" ]
I'm trying to decode a shift-jis string, like this: ``` string.decode('shift-jis').encode('utf-8') ``` to be able to view it in my program. When I come across 2 shift-jis characters, in hex "0x87 0x54" and "0x87 0x55", I get this error: ``` UnicodeDecodeError: 'shift_jis' codec can't decode bytes in position 12-13: ...
Multiple versions of Shift JIS exist. The `shift_jis` codec is [JIS X 0208](http://en.wikipedia.org/wiki/JIS_X_0208), whereas that table is [JIS X 0213](http://en.wikipedia.org/wiki/JIS_X_0213), corresponding to the `shift_jisx0213` codec. ``` >>> u'⑲⑳Ⅰ'.encode('shift_jisx0213') '\x87R\x87S\x87T' ```
Python Logging - Messages appearing twice
6,729,268
23
2011-07-18T06:24:53Z
6,729,713
40
2011-07-18T07:17:11Z
[ "python", "logging" ]
I'm using Python logging, and for some reason, all of my messages are appearing twice. I have a module to configure logging: ``` # BUG: It's outputting logging messages twice - not sure why - it's not the propagate setting. def configure_logging(self, logging_file): self.logger = logging.getLogger("my_logger") ...
You are calling `configure_logging` twice (maybe in the `__init__` method of `Boy`) : `getLogger` will return the same object, but `addHandler` does not check if a similar handler has already been added to the logger. Try tracing calls to that method and eliminating one of these. Or set up a flag `logging_initialized`...
Why do these two Python imports work differently?
6,730,632
7
2011-07-18T09:02:45Z
6,730,749
8
2011-07-18T09:13:17Z
[ "python", "import", "module", "package" ]
Assume the following code structure: ``` #### 1/hhh/__init__.py: empty #### 1/hhh/foo/__init__.py: from hhh.foo.baz import * #### 1/hhh/foo/bar.py: xyzzy = 4 #### 1/hhh/foo/baz.py: import hhh.foo.bar as bar qux = bar.xyzzy + 10 ``` I run `python` inside `1/` and do `import hhh.foo.baz`. It fails: ``` Traceback (m...
When you write `from hhh.foo.bar import xyzzy` Python interpreter will try to load `xyzzy` from module `hhh.foo.bar`. But if you write `import hhh.foo.bar as bar` it will try first to find `bar` in `hhh.foo` module. So it evaluates `hhh.foo`, doing `from hhh.foo.baz import *`. `hhh.foo.baz` tries to evaluate `hhh.foo`,...
How-to import constants in many files
6,731,345
2
2011-07-18T10:09:54Z
6,731,481
7
2011-07-18T10:21:27Z
[ "python", "import", "package" ]
I have a package containing many modules. Each module uses constants that I have defined independently in each file. However, all these constants have to be constistent with each other. So I try to define them in a single file and import it in each file. When I run it I have errors for constants not found. Is their a ...
You can declare all your constants in one file, say `constants.py` and then import them into others. Here is an example: ``` # constants.py FOO = 'foo' PI = 3.14 # main.py import constants print constants.PI ```
Redirecting stdout to "nothing" in python
6,735,917
69
2011-07-18T16:12:28Z
6,735,958
124
2011-07-18T16:16:02Z
[ "python", "python-2.7" ]
I have a large project consisting of sufficiently large number of modules, each printing something to the standard output. Now as the project has grown in size, there are large no. of `print` statements printing a lot on the std out which has made the program considerably slower. So, I now want to decide at *runtime* ...
Cross-platform: ``` import os import sys f = open(os.devnull, 'w') sys.stdout = f ``` On Windows: ``` f = open('nul', 'w') sys.stdout = f ``` On Linux: ``` f = open('/dev/null', 'w') sys.stdout = f ```
Redirecting stdout to "nothing" in python
6,735,917
69
2011-07-18T16:12:28Z
13,944,391
8
2012-12-19T01:45:08Z
[ "python", "python-2.7" ]
I have a large project consisting of sufficiently large number of modules, each printing something to the standard output. Now as the project has grown in size, there are large no. of `print` statements printing a lot on the std out which has made the program considerably slower. So, I now want to decide at *runtime* ...
(at least on my system) it appears that writing to os.devnull is about 5x faster than writing to a DontPrint class, i.e. ``` #!/usr/bin/python import os import sys import datetime ITER = 10000000 def printlots(out, it, st="abcdefghijklmnopqrstuvwxyz1234567890"): temp = sys.stdout sys.stdout = out i = 0 st...
Is a Fuzzy C-Means algorithm available for Python?
6,736,347
9
2011-07-18T16:47:13Z
6,736,526
7
2011-07-18T17:03:14Z
[ "python", "cluster-analysis" ]
I have some dots in a 3 dimensional space and would like to cluster them. I know Pythons module "cluster", but it has only K-Means. Do you know a module which has FCM (Fuzzy C-Means)? (If you know some other python modules which are related to clustering you could name them as a bonus. But the important question is th...
PEACH will provide some Fuzzy C-Means functionality: <http://code.google.com/p/peach/> However there doesn't seem to be any usable documentation as the wiki is empty. An [example for using FCM with PEACH](http://peach.googlecode.com/svn/trunk/tutorial/fuzzy-logic/fuzzy-c-means.py) can be found on its website.
Fast check for NaN in NumPy
6,736,590
62
2011-07-18T17:10:05Z
6,736,673
18
2011-07-18T17:17:18Z
[ "python", "numpy", null ]
I'm looking for the fastest way to check for the occurrence of NaN (`np.nan`) in a NumPy array `X`. `np.isnan(X)` is out of the question, since it builds a boolean array of shape `X.shape`, which is potentially gigantic. I tried `np.nan in X`, but that seems not to work because `np.nan != np.nan`. Is there a fast and ...
I think `np.isnan(np.min(X))` should do what you want.
Fast check for NaN in NumPy
6,736,590
62
2011-07-18T17:10:05Z
6,736,970
89
2011-07-18T17:42:55Z
[ "python", "numpy", null ]
I'm looking for the fastest way to check for the occurrence of NaN (`np.nan`) in a NumPy array `X`. `np.isnan(X)` is out of the question, since it builds a boolean array of shape `X.shape`, which is potentially gigantic. I tried `np.nan in X`, but that seems not to work because `np.nan != np.nan`. Is there a fast and ...
Ray's solution is good. However, on my machine it is about 2.5x faster to use [`numpy.sum`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html) in place of `numpy.min`: ``` In [13]: %timeit np.isnan(np.min(x)) 1000 loops, best of 3: 244 us per loop In [14]: %timeit np.isnan(np.sum(x)) 10000 loops, bes...
Fast check for NaN in NumPy
6,736,590
62
2011-07-18T17:10:05Z
6,739,580
15
2011-07-18T21:19:21Z
[ "python", "numpy", null ]
I'm looking for the fastest way to check for the occurrence of NaN (`np.nan`) in a NumPy array `X`. `np.isnan(X)` is out of the question, since it builds a boolean array of shape `X.shape`, which is potentially gigantic. I tried `np.nan in X`, but that seems not to work because `np.nan != np.nan`. Is there a fast and ...
Even there exist an accepted answer, I'll like to demonstrate the following (with Python 2.7.2 and Numpy 1.6.0 on Vista): ``` In []: x= rand(1e5) In []: %timeit isnan(x.min()) 10000 loops, best of 3: 200 us per loop In []: %timeit isnan(x.sum()) 10000 loops, best of 3: 169 us per loop In []: %timeit isnan(dot(x, x)) 1...
yaml in Google App Engine with index.html
6,736,751
6
2011-07-18T17:23:57Z
6,736,960
11
2011-07-18T17:42:02Z
[ "python", "google-app-engine" ]
I'm building a website, I have no index.py how to I ensure index.html comes up when I type in my <http://localhost:8080/>? I have in yaml ``` - url: / static_files: static/HTML upload: static/HTML/index.html ``` but this does not seem to work.
Your `static_files` directive needs to include the full path to the file: ``` static_files: static/HTML/index.html ```
How do python submodules share a scarce resource between them?
6,736,860
4
2011-07-18T17:33:53Z
6,736,983
8
2011-07-18T17:43:39Z
[ "python", "namespaces", "python-module" ]
I am breaking up a large monolothic python file into six separate submodules. Originally in onebigfile.py, I had ``` conn = MySqldb.connect() c = conn.cursor() ``` and then a function would use it as so: ``` def getFromDB(): c.execute(sql) ``` Now, I have restructured my module to ``` NewModule/ __init__.p...
You can certainly share the connection object between python modules, and your idea to have the connection be a module-scoped variable will accomplish this nicely (with a few exceptions, Python modules are singletons, so even if they are imported multiple times from different files, they are only loaded once). You prob...
Have Python 2.7 functions remember value and not reference? Closure Weirdness
6,737,112
3
2011-07-18T17:53:25Z
6,737,190
11
2011-07-18T17:58:27Z
[ "python", "functional-programming", "scope", "closures" ]
I'm trying to return from a function a list of functions, each of which uses variables from the outside scope. This isn't working. Here's an example which demonstrates what's happening: ``` a = [] for i in range(10): a.append(lambda x: x+i) a[1](1) # returns 10, where it seems it should return 2 ``` Why is this h...
The `i` refers to the same variable each time, so `i` is 9 in all of the lambdas because that's the value of `i` at the end of the loop. Simplest workaround involves a default argument: ``` lambda x, i=i: x+i ``` This binds the value of the loop's `i` to a local variable `i` at the lambda's definition time. Another ...
Python regex replace to create smiley faces
6,737,846
5
2011-07-18T18:54:15Z
6,737,901
8
2011-07-18T18:58:53Z
[ "python", "regex" ]
I'd like to create a regex string that would turn this text: ``` Hello this is a mighty fine day today ``` into ``` 8===D 8==D 8D D 8====D 8==D 8=D 8===D ``` is this possible with a python re.sub oneliner?
No need for regexes: ``` s = 'Hello this is a mighty fine day today' ' '.join('%s%sD'%('8' if len(w) > 1 else '', '='*(len(w)-2)) for w in s.split()) # '8===D 8==D 8D D 8====D 8==D 8=D 8===D' ``` Edit: debugged ;) Thanks for the pointer @tg
Why doesn't Python have a hybrid getattr + __getitem__ built in?
6,738,087
8
2011-07-18T19:14:28Z
6,738,724
14
2011-07-18T20:03:10Z
[ "python", "magic-methods", "getattr" ]
I have methods that accept dicts or other objects and the names of "fields" to fetch from those objects. If the object is a dict then the method uses `__getitem__` to retrieve the named key, or else it uses `getattr` to retrieve the named attribute. This is pretty common in web templating languages. For example, in a [...
I sort of half-read your question, wrote the below, and then reread your question and realized I had answered a subtly different question. But I think the below actually still provides an answer after a sort. If you don't think so, pretend instead that you had asked this more general question, which I think includes yo...
Do Python dictionaries have all memory freed when reassigned?
6,738,270
5
2011-07-18T19:26:56Z
6,738,400
8
2011-07-18T19:37:59Z
[ "python" ]
Working in Python. I have a function that reads from a queue and creates a dictionary based on some of the XML tags in the record read from the queue, and returns this dictionary. I call this function in a loop forever. The dictionary gets reassigned each time. Does the memory previously used by the dictionary get free...
The memory of an object will be freed if it can be proven (from the knowledge the language implementation has at runtime) that it cannot possibly be accessed any more and the garbage collector sees it fit to make a collection. That's the absolute minimum, and you shouldn't assume any more. And you usually shouldn't *ha...
Is factory pattern meaningless in Python?
6,738,309
5
2011-07-18T19:29:26Z
6,738,456
12
2011-07-18T19:41:58Z
[ "python", "factory-pattern" ]
Since Python is a duck-typed language is writing factory classes meaningless in Python? <http://en.wikipedia.org/wiki/Factory_method_pattern>
While there may be times when the factory pattern is unnecessary where it may be required in other languages, there are still times when it would be valid to use it - it might just be a way of making your API cleaner - for example as a way of preventing duplication of code that decides which of a series of subclasses t...