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
How to setup for development of plone products
6,065,614
3
2011-05-19T22:37:56Z
6,065,991
10
2011-05-19T23:32:49Z
[ "python", "plone", "buildout" ]
I want to develop a few products for a defined Plone install/version, which I cannot change (3.3.5). What is the best way to organize my source tree, so that I do not have to put a huge plone instance into source control that won't change anyway? I still want to use buildout for local checking, though... What do you ...
Generally speaking, this is done now-a-days with `mr.developer`. You can use a buildout like this: ``` [buildout] extends = https://raw.githubusercontent.com/plock/pins/master/plone-4-3 https://raw.githubusercontent.com/plock/pins/master/dev ``` And then add your sources to the `auto-checkout` parameter in t...
Python/Numpy - Quickly Find the Index in an Array Closest to Some Value
6,065,697
6
2011-05-19T22:49:04Z
6,066,135
7
2011-05-19T23:57:37Z
[ "python", "performance", "indexing", "numpy" ]
I have an array of values, t, that is always in increasing order (but not always uniformly spaced). I have another single value, x. I need to find the index in t such that t[index] is closest to x. The function must return zero for x < t.min() and the max index (or -1) for x > t.max(). I've written two functions to do...
This seems much quicker (for me, Python 3.2-win32, numpy 1.6.0): ``` from bisect import bisect_left def f3(t, x): i = bisect_left(t, x) if t[i] - x > 0.5: i-=1 return i ``` --- Output: ``` [ 10 11 12 ..., 99997 99998 99999] 37854.22200356027 37844 37844 37844 37854 37854 37854 f1 0.33272...
Python - good practice to catch errors
6,067,018
8
2011-05-20T02:58:59Z
6,067,036
14
2011-05-20T03:02:17Z
[ "python" ]
I have these files in my project: ``` - main.py - module1.py - module2.py ``` `main` is the main file that will be directly execute in console. `module1` will be imported into `main` and throws `Module1Exception`. `module2` will be imported into `module1`, throws `Module2Exception` and uses lib that throws `NormalE...
`main` should have the responsibility to terminate, not the modules. What if you wanted to import those modules into another project and you *didn't* want to terminate the application on an exception?
How does use_for_related_fields work in Django?
6,067,195
12
2011-05-20T03:36:06Z
6,072,088
31
2011-05-20T12:47:14Z
[ "python", "django", "django-models", "foreign-key-relationship", "django-managers" ]
I'm unable to grasp that from the docs. It's totally unclear to me, more specifically: * Is it a global setting? So if I specify this attribute it on one of the model managers, will it be used globally by all the model classes? * If it's not a global setting then which relationships exactly will be affected? * Is it p...
# Is it a global setting? So if I specify this attribute it on one of the model managers, will it be used globally by all the model classes? If I have understood what you mean by global, the answer is no. It will only be used for a class if the default manager (the first manager specified in the class) has it set. You...
Python Sockets: Enabling Promiscuous Mode in Linux
6,067,405
7
2011-05-20T04:16:13Z
6,072,625
11
2011-05-20T13:30:17Z
[ "python", "sockets", "networking" ]
We know that Python Allows enabling promiscuous mode under Windows through ``` s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) ``` However, The RCVALL\_\* and SIO\_\* is only available in windows. Using C socket api, in Linux, one can use : ``` ethreq.ifr_flags |= IFF_PROMISC; ioctl(sock, SIOCSIFFLAGS, &ethreq); ``` o...
Use an `AF_NETLINK` socket to issue a request to turn on `IFF_PROMISC`. Python can construct `AF_NETLINK` sockets on Linux: ``` >>> from socket import AF_NETLINK, SOCK_DGRAM, socket >>> s = socket(AF_NETLINK, SOCK_DGRAM) >>> ``` See the example at the end of the netlink(7) manual page for an example of how to issue ...
Basic Python Question on String operations: example: string.lowercase
6,067,692
2
2011-05-20T05:06:30Z
6,067,711
8
2011-05-20T05:10:08Z
[ "python", "string", "operations", "attributeerror" ]
So I'm trying to run this, but it errors out and I need help understanding what's wrong. I really appreciate any help, I'm taking the MIT opencourseware intro to programming: ``` words="GreatTimes" words.lowercase ``` And I get this error: ``` AttributeError: 'str' object has no attribute 'lowercase' ``` The issue ...
I'm a bit confused by what you are trying to do. This seems like a rather contrived exercise. * If you just want to use an instance method, `words.lower()` will return a lowercase version of the string `words`. * If you want to implement a lowercase function of your own using `string.lowercase` (which is just a consta...
Inclusion of external documentation into a Sphinx project
6,068,296
5
2011-05-20T06:36:03Z
6,119,065
8
2011-05-25T03:00:16Z
[ "python", "python-sphinx" ]
We maintain a fairly large documentation using Sphinx in SVN. As part of the generated output we would like to include the release notes of related Python modules as primary content (not as hyperlink!). The release notes of the external modules are also maintained in SVN. Is there some Sphinx-ish way to pull in the pa...
The two options I can think of are: 1. Add an `svn:externals` link to the remote project (which you already know about). 2. Extend Sphinx with a custom directive to include files from remote subversion repositories. I'm no expert on Sphinx internals but was able to cobble together a quick extension which embeds files...
TeX rendering, curly braces, and string formatting syntax in matplotlib
6,068,606
7
2011-05-20T07:08:57Z
6,068,661
11
2011-05-20T07:15:07Z
[ "python", "string", "matplotlib", "tex" ]
I have the following lines to render TeX annotations in my `matplotlib` plot: ``` import numpy as np import matplotlib.pyplot as plt from matplotlib import rc rc('text', usetex=True) rc('font', family='serif') voltage = 220 notes = r"\noindent $V_2 = {0:.5} V$".format(voltage) plt.annotate(notes, xy=(5,5), xytext=...
You have to double the braces to be treated literally: ``` r"\noindent $V_2 = {0:.5} \text{{V}}$".format(voltage) ``` BTW, you can also write ``` \text V ``` but the best is ``` \mathrm V ``` since a unit is not really a text symbol.
CherryPy : Is there a best way to split the project in multiple files?
6,068,645
7
2011-05-20T07:14:08Z
6,069,115
10
2011-05-20T08:06:16Z
[ "python", "cherrypy", "code-organization", "project-organization" ]
I'm new to CherryPy, coming from Django. I liked the way Django split the various parts of the project into many files, and I'd like to do the same in CherryPy, instead of having one big file. I think it would be great if I could split the project in these parts: * application.py : The core of CherryPy, where the ser...
Well, I'll answer myself on that one :p I found a [Google Groups post](http://groups.google.com/group/cherrypy-users/browse_thread/thread/2fb617643ff9e5e7) that poses the basics on how to structure your CherryPy application. In that post, there is a link to a [Bitbucket CherryPy application example](https://bitbucket...
Adding python modules to pydev in eclipse results in import error?
6,070,423
13
2011-05-20T10:12:38Z
6,076,903
20
2011-05-20T19:48:19Z
[ "python", "eclipse", "configuration", "import", "pydev" ]
I have a problem getting PyDev on eclipse to recognize already installed modules. Here is my detailed approach. The machine is a Mac (Snow Leopard). In terminal the command ``` python --version ``` shows *Python 2.6.6*. ``` import unidecode ``` and ``` from unidecode import unidecode ``` work both fine! I insta...
This is the solution to my problem: 1. Find out the path to the folder `../site-packages/` of your corresponding python version. ( For me it was `/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/` for python 2.6 on my Mac with Snoe Leopard.) 2. Open eclipse preferences and go to ...
Explanation of python code snippet >>numpy.nonzero(row == max(row))[0][0]<< from a script using numpy
6,070,542
4
2011-05-20T10:24:48Z
6,070,700
8
2011-05-20T10:38:27Z
[ "python", "numpy" ]
What does this peace of python code ``` row = R[i,] j = numpy.nonzero(row == max(row))[0][0] ``` do, assuming this output: ``` command # output of python ---------------------------------- R.shape # (224, 24) type(R) # <type 'numpy.ndarray'> type(row) # <type 'numpy.ndarray'> type(j) # <type 'numpy.int64'> `...
The two lines appear to be a roundabout way of saying `j = np.argmax(R[i])`, i.e. find the column index of the largest element in the `i`-th row of `R`, and store the result in `j`.
What is the correct way to extend a parent class method in modern Python
6,070,599
11
2011-05-20T10:29:51Z
6,070,685
14
2011-05-20T10:37:04Z
[ "python", "inheritance" ]
I frequently do this sort of thing: ``` class Person(object): def greet(self): print "Hello" class Waiter(Person): def greet(self): Person.greet(self) print "Would you like fries with that?" ``` The line Person.greet(self) doesn't seem right. If I ever change what class Waiter inherit...
You use [`super`](http://docs.python.org/library/functions.html#super): > Return a proxy object that delegates > method calls to a parent or sibling > class of type. This is useful for > accessing inherited methods that have > been overridden in a class. The search > order is same as that used by > `getattr()` except ...
Python: How to tell the for loop to continue from a function?
6,071,050
9
2011-05-20T11:08:52Z
6,071,174
8
2011-05-20T11:19:36Z
[ "python", "continue" ]
Sometimes I need the following pattern within a `for` loop. At times more than once in the same loop: ``` try: var = 'attempt to do something that may fail on a number of levels' except Exception, e: log(e) continue ``` Now I don't see a nice way to wrap this in a function as it can no...
Python already has a very nice construct for doing just this and it doesn't use `continue`: ``` for i in range(10): try: r = 1.0 / (i % 2) except Exception, e: print(e) else: print(r) ``` I wouldn't nest any more than this, though, or your code will soon get very ugly. In your cas...
Creating a Dictionary from a List of 2-Tuples
6,072,470
5
2011-05-20T13:17:59Z
6,072,492
18
2011-05-20T13:19:41Z
[ "python", "dictionary", "reduce" ]
I have a list of 2-tuples like this: ``` l = [('a', 1), ('b', 2)] ``` and I want to be able to map this onto a dictionary object, so that I can do something like ``` l.a #=> 1 ``` So I tried this, but why does it fail? ``` d = reduce(lambda y,x : y.update({x[0]:x[1]}),l,{}) ``` This gives the error: > AttributeE...
``` >>> l = [('a', 1), ('b', 2)] >>> d = dict(l) >>> d['a'] 1 ```
Python ctypes return values question
6,073,599
2
2011-05-20T14:45:03Z
6,073,671
12
2011-05-20T14:50:07Z
[ "python", "return-value", "ctypes", "dynamic-library" ]
Why if i have this simple code ``` void voidFunct() { printf("voidFunct called!!!\n"); } ``` I compile it as a dynamic library with ``` gcc -c LSB.c -o LSB.o gcc -shared -Wl -o libLSB.so.1 LSB.o ``` And i call function from a python interpreter, using ctypes ``` >>> from ctypes import * >>> dll = CDLL("./li...
From the docs: > ***class ctypes.CDLL(name, mode=DEFAULT\_MODE, handle=None, use\_errno=False, use\_last\_error=False)*** > > Instances of this class represent loaded shared libraries. Functions in these libraries use the standard C calling convention, and are **assumed to return int**. In short, you defined voidFunc...
Why does the expression 0 < 0 == 0 return False in Python?
6,074,018
112
2011-05-20T15:19:08Z
6,074,117
89
2011-05-20T15:25:47Z
[ "python" ]
Looking into Queue.py in Python 2.6, I found this construct that I found a bit strange: ``` def full(self): """Return True if the queue is full, False otherwise (not reliable!).""" self.mutex.acquire() n = 0 < self.maxsize == self._qsize() self.mutex.release() return n ``` If `maxsize` is 0 th...
I believe Python has special case handling for sequences of relational operators to make range comparisons easy to express. It's much nicer to be able to say `0 < x <= 5` than to say `(0 < x) and (x <= 5)`. These are called [chained comparisons](https://docs.python.org/2/reference/expressions.html#not-in). And that's ...
Why does the expression 0 < 0 == 0 return False in Python?
6,074,018
112
2011-05-20T15:19:08Z
6,074,148
17
2011-05-20T15:27:43Z
[ "python" ]
Looking into Queue.py in Python 2.6, I found this construct that I found a bit strange: ``` def full(self): """Return True if the queue is full, False otherwise (not reliable!).""" self.mutex.acquire() n = 0 < self.maxsize == self._qsize() self.mutex.release() return n ``` If `maxsize` is 0 th...
The strange behavior your experiencing comes from pythons ability to chain conditions. Since it finds 0 is not less than 0, it decides the entire expression evaluates to false. As soon as you break this apart into seperate conditions, you're changing the functionality. It initially is essentially testing that `a < b &&...
Why does the expression 0 < 0 == 0 return False in Python?
6,074,018
112
2011-05-20T15:19:08Z
6,074,162
38
2011-05-20T15:28:58Z
[ "python" ]
Looking into Queue.py in Python 2.6, I found this construct that I found a bit strange: ``` def full(self): """Return True if the queue is full, False otherwise (not reliable!).""" self.mutex.acquire() n = 0 < self.maxsize == self._qsize() self.mutex.release() return n ``` If `maxsize` is 0 th...
Because ``` (0 < 0) and (0 == 0) ``` is `False`. You can chain together comparison operators and they are automatically expanded out into the pairwise comparisons. --- EDIT -- clarification about True and False in Python In Python `True` and `False` are just instances of `bool`, which is a subclass of `int`. In ot...
Why does the expression 0 < 0 == 0 return False in Python?
6,074,018
112
2011-05-20T15:19:08Z
6,074,267
8
2011-05-20T15:37:12Z
[ "python" ]
Looking into Queue.py in Python 2.6, I found this construct that I found a bit strange: ``` def full(self): """Return True if the queue is full, False otherwise (not reliable!).""" self.mutex.acquire() n = 0 < self.maxsize == self._qsize() self.mutex.release() return n ``` If `maxsize` is 0 th...
``` >>> 0 < 0 == 0 False ``` This is a chained comparison. It returns true if each pairwise comparison in turn is true. It is the equivalent to `(0 < 0) and (0 == 0)` ``` >>> (0) < (0 == 0) True ``` This is equivalent to `0 < True` which evaluates to True. ``` >>> (0 < 0) == 0 True ``` This is equivalent to `False...
Make a list of a class's methods and dynamically call the methods on the class
6,074,122
4
2011-05-20T15:26:02Z
6,074,212
8
2011-05-20T15:32:16Z
[ "python", "class", "methods" ]
Is it possible to get a list of class's methods and then invoke the methods on an instance of the class? I have come across code that makes a list of a class's methods, but I haven't found an example that also invokes the methods on an instance of the class. Given the class: ``` class Test: def methodOne(self): ...
Use `getattr(a,methodname)` to access the actual method, given the string name, `methodname`: ``` import inspect import types class Test(object): def methodOne(self): print('one') def methodTwo(self): print('two') a = Test() methodList = [n for n, v in inspect.getmembers(a, inspect.ismethod) ...
Python: 'super' object has no attribute 'attribute_name'
6,075,758
3
2011-05-20T17:48:15Z
6,075,773
12
2011-05-20T17:50:04Z
[ "python", "attributes", "super" ]
I am trying to access a variable from the base class. Here's the parent class: ``` class Parent(object): def __init__(self, value): self.some_var = value ``` And here's the child class: ``` class Child(Parent): def __init__(self, value): super(Child, self).__init__(value) def doSomething...
After the base class's `__init__` ran, the derived object has the attributes set there (e.g. `some_var`) as it's the very same object as the `self` in the derived class' `__init__`. You can and should just use `self.some_var` everywhere. `super` is for accessing stuff from base classes, but instance variables are (as t...
Python file parsing: Build tree from text file
6,075,974
12
2011-05-20T18:08:25Z
6,076,821
10
2011-05-20T19:38:53Z
[ "python", "algorithm", "recursion", "tree" ]
I have an indented text file that will be used to build a tree. Each line represents a node, and indents represent depth as well as node the current node is a child of. For example, a file might look like ``` ROOT Node1 Node2 Node3 Node4 Node5 Node6 ``` Which indicates that ROOT c...
The big issue is the "lookahead" that I think caused the ugliness in question. It can be shortened slightly: ``` def _recurse_tree(parent, depth, source): last_line = source.readline().rstrip() while last_line: tabs = last_line.count('\t') if tabs < depth: break node = last_...
Python file parsing: Build tree from text file
6,075,974
12
2011-05-20T18:08:25Z
6,089,284
12
2011-05-22T16:37:37Z
[ "python", "algorithm", "recursion", "tree" ]
I have an indented text file that will be used to build a tree. Each line represents a node, and indents represent depth as well as node the current node is a child of. For example, a file might look like ``` ROOT Node1 Node2 Node3 Node4 Node5 Node6 ``` Which indicates that ROOT c...
If you don't insist on recursion, this works too: ``` from itertools import takewhile is_tab = '\t'.__eq__ def build_tree(lines): lines = iter(lines) stack = [] for line in lines: indent = len(list(takewhile(is_tab, line))) stack[indent:] = [line.lstrip()] print stack source = ''...
Implementing a multi-process server in Python, with Twisted
6,076,161
7
2011-05-20T18:28:22Z
6,076,528
9
2011-05-20T19:05:22Z
[ "python", "parallel-processing", "twisted" ]
I have to write a CPU-bound server in Python, to distribute workloads for many cores. I want to use Twisted as the server (requests coming in via TCP). Are there any better options - using Ampoule, perhaps? I also saw an article using Twisted's `pb` for communication, in conjunction with Popen - or perhaps combine it ...
[Ampoule](https://launchpad.net/ampoule) is a good building block for a multiprocess CPU-bound server. It uses the simpler AMP protocol, rather than PB (the complexity of which is usually not needed just to move job data into another process and then retrieve the results). It handles process creation, lifetime manageme...
Python: Lambda function in List Comprehensions
6,076,270
39
2011-05-20T18:39:00Z
6,076,304
94
2011-05-20T18:41:45Z
[ "python" ]
Why is the output of the following two list comprehensions different, even though f and the lambda function are the same ? ``` f = lambda x: x*x [f(x) for x in range(10)] ``` and ``` [lambda x: x*x for x in range(10)] ``` Mind you, both type(f) and type(lambda x: x\*x) return the same type.
The first one create a single lambda function and calls it ten times. The second one doesn't call the function. It creates 10 different lambda functions. It puts all of those in a list. To make it equivalent to the first you need: ``` [(lambda x: x*x)(x) for x in range(10)] ``` Or better yet: ``` [x*x for x in rang...
Python: Lambda function in List Comprehensions
6,076,270
39
2011-05-20T18:39:00Z
6,076,305
15
2011-05-20T18:41:46Z
[ "python" ]
Why is the output of the following two list comprehensions different, even though f and the lambda function are the same ? ``` f = lambda x: x*x [f(x) for x in range(10)] ``` and ``` [lambda x: x*x for x in range(10)] ``` Mind you, both type(f) and type(lambda x: x\*x) return the same type.
The big difference is that the first example actually invokes the lambda `f(x)`, while the second example doesn't. Your first example is equivalent to `[(lambda x: x*x)(x) for x in range(10)]` while your second example is equivalent to `[f for x in range(10)]`.
Python: Lambda function in List Comprehensions
6,076,270
39
2011-05-20T18:39:00Z
6,076,322
7
2011-05-20T18:42:43Z
[ "python" ]
Why is the output of the following two list comprehensions different, even though f and the lambda function are the same ? ``` f = lambda x: x*x [f(x) for x in range(10)] ``` and ``` [lambda x: x*x for x in range(10)] ``` Mind you, both type(f) and type(lambda x: x\*x) return the same type.
The first one ``` f = lambda x: x*x [f(x) for x in range(10)] ``` runs `f()` for each value in the range so it does `f(x)` for each value the second one ``` [lambda x: x*x for x in range(10)] ``` runs the lambda for each value in the list, so it generates all of those functions.
Python: Lambda function in List Comprehensions
6,076,270
39
2011-05-20T18:39:00Z
34,021,333
10
2015-12-01T13:14:07Z
[ "python" ]
Why is the output of the following two list comprehensions different, even though f and the lambda function are the same ? ``` f = lambda x: x*x [f(x) for x in range(10)] ``` and ``` [lambda x: x*x for x in range(10)] ``` Mind you, both type(f) and type(lambda x: x\*x) return the same type.
This question touches a very stinking part of the "famous" and "obvious" Python syntax - what takes precedence, the lambda, or the for of list comprehension. I don't think the purpose of the OP was to generate a list of squares from 0 to 9. If that was the case, we could give even more solutions: ``` squares = [] for...
Verbose level with argparse and multiple -v options
6,076,690
20
2011-05-20T19:24:54Z
6,076,779
13
2011-05-20T19:33:38Z
[ "python", "argparse" ]
I'd like to be able to specify different verbose level, by adding more -v options to the command line. For example: ``` $ myprogram.py $ myprogram.py -v $ myprogram.py -vv $ myprogram.py -v -v -v ``` would lead to verbose=0, verbose=1, verbose=2, and verbose=3 respectively. How can I achieve that using argparse? ...
You could do this with `nargs='?'` (to accept 0 or 1 arguments after the `-v` flag) and a custom action (to process the 0 or 1 arguments): ``` import argparse class VAction(argparse.Action): def __call__(self, parser, args, values, option_string=None): # print 'values: {v!r}'.format(v=values) if v...
Verbose level with argparse and multiple -v options
6,076,690
20
2011-05-20T19:24:54Z
6,076,862
7
2011-05-20T19:44:26Z
[ "python", "argparse" ]
I'd like to be able to specify different verbose level, by adding more -v options to the command line. For example: ``` $ myprogram.py $ myprogram.py -v $ myprogram.py -vv $ myprogram.py -v -v -v ``` would lead to verbose=0, verbose=1, verbose=2, and verbose=3 respectively. How can I achieve that using argparse? ...
You could handle the first part of your question with `append_const`. Otherwise, you're probably stuck writing a custom action, as suggested in the fine [answer by unutbu](http://stackoverflow.com/questions/6076690/verbose-level-with-argparse-and-multiple-v-options/6076779#6076779). ``` import argparse ap = argparse....
Verbose level with argparse and multiple -v options
6,076,690
20
2011-05-20T19:24:54Z
8,335,918
41
2011-12-01T02:35:34Z
[ "python", "argparse" ]
I'd like to be able to specify different verbose level, by adding more -v options to the command line. For example: ``` $ myprogram.py $ myprogram.py -v $ myprogram.py -vv $ myprogram.py -v -v -v ``` would lead to verbose=0, verbose=1, verbose=2, and verbose=3 respectively. How can I achieve that using argparse? ...
I had exactly this desire, and months ago implemented a custom action to do it, which I was getting sick of copying around to the scripts I keep writing. But I've only just now found out that argparse does in fact support `action='count'`, just as `optparse` did, even though this appears to be completely undocumented i...
Ignore ImportError when exec source code
6,076,770
3
2011-05-20T19:32:51Z
6,077,117
7
2011-05-20T20:11:27Z
[ "python" ]
I have an application that reads test scripts in python and sends them across the network for execution on a remote python instance. As the controlling program does not need to run these scripts I do not want to have all the modules the test scripts use installed on the controller's python environment. However the cont...
Write an import hook that catches the exception and returns a dummy module if the module doesn't exist. ``` import __builtin__ from types import ModuleType class DummyModule(ModuleType): def __getattr__(self, key): return None __all__ = [] # support wildcard imports def tryimport(name, globals={}, ...
How to display a volume with non-cubic voxels correctly in mayavi
6,076,827
8
2011-05-20T19:39:46Z
6,105,546
7
2011-05-24T04:00:59Z
[ "python", "scipy", "volume", "mayavi" ]
I'm using [mayavi](http://github.enthought.com/mayavi/mayavi/) (3.3.2) to display volume isosurfaces. Generally, my volumes do not have cubic voxels; for example, the sampling grid might be 1mm x 1mm in X and Y, but 1.4mm in the Z direction. How can I get such volumes to display with the correct spatial proportions u...
For this, it's easiest to explicitly create a `scalar_field` object from the input data. I actually do this quite frequently, as we like to put things in depth (where positive is downwards) in geology. That means that you need a negative increment in the z-direction. It would be nice if it was just an argument to the ...
How does the "magic lines(s)" in python work, when specifying encoding in python file?
6,077,479
9
2011-05-20T20:53:38Z
6,077,520
9
2011-05-20T20:57:45Z
[ "python", "encoding", "comments", "interpreter" ]
At the start of a python file (first line) sometimes I read ``` # -*- coding: utf-8 -*- ``` and sometimes I read ``` # encoding: utf-8 ``` Both lines seem to do the same thing: specifying utf8 as encoding for all the text put in the file. I have to questions: 1. Why does this even work? I thought the interpreter ...
The two forms are equivalent. The `-*-` version is a special kind of comment that Emacs understands. See [PEP 263](http://www.python.org/dev/peps/pep-0263/) for more information. If a comment like in either of these forms is one of the *first two lines* of a file, the interpreter will use the specified encoding to rea...
Why am I seeing "TypeError: string indices must be integers"?
6,077,675
44
2011-05-20T21:15:17Z
6,077,684
24
2011-05-20T21:16:53Z
[ "python", "json", "github" ]
I'm playing with both learning python and trying to get github issues into a readable form. Using the advice on [convert from json to csv using python](http://stackoverflow.com/questions/1871524/convert-from-json-to-csv-using-python) I came up with this: ``` import json import csv f=open('issues.json') data = json.lo...
`item` is most likely a string in your code; the string indices are the ones in the square brackets, e.g., `gravatar_id`. So I'd first check your `data` variable to see what you received there; I guess that `data` is a list of strings (or at least a list containing at least one string) while it should be a list of dict...
Why am I seeing "TypeError: string indices must be integers"?
6,077,675
44
2011-05-20T21:15:17Z
6,077,692
55
2011-05-20T21:18:04Z
[ "python", "json", "github" ]
I'm playing with both learning python and trying to get github issues into a readable form. Using the advice on [convert from json to csv using python](http://stackoverflow.com/questions/1871524/convert-from-json-to-csv-using-python) I came up with this: ``` import json import csv f=open('issues.json') data = json.lo...
The variable `item` is a string. An index looks like this: ``` >>> mystring = 'helloworld' >>> print mystring[0] 'h' ``` The above example uses the `0` index of the string to refer to the first character. Strings can't have string indices (like dictionaries can). So this won't work: ``` >>> mystring = 'helloworld' ...
Why am I seeing "TypeError: string indices must be integers"?
6,077,675
44
2011-05-20T21:15:17Z
6,078,422
9
2011-05-20T23:07:52Z
[ "python", "json", "github" ]
I'm playing with both learning python and trying to get github issues into a readable form. Using the advice on [convert from json to csv using python](http://stackoverflow.com/questions/1871524/convert-from-json-to-csv-using-python) I came up with this: ``` import json import csv f=open('issues.json') data = json.lo...
`data` is a `dict` object. So iterate over it like this: ``` for key, value in data.iteritems(): print key, value ```
ast.literal_eval() support for set literals in Python 2.7?
6,078,262
9
2011-05-20T22:38:21Z
6,078,298
9
2011-05-20T22:46:54Z
[ "python", "set", "literals", "abstract-syntax-tree" ]
In the [What’s New in Python 2.7](http://docs.python.org/whatsnew/2.7.html#python-3-1-features) document it says that support for set literals was back-ported from Python 3.1. However it appears that this support was not extended to the `ast` module's `literal_eval()`function, as illustrated below. Was this intentio...
See <http://bugs.python.org/issue10091>
python - open() not working with path names
6,078,759
9
2011-05-21T00:15:17Z
6,078,771
11
2011-05-21T00:19:27Z
[ "python" ]
Python 2.7.1, using open(), and having trouble with append mode and pathname instead of filename. It says open() works as stdio fopen(), and that func when put into append ("a") says it's supposed to create the file if it doesn't exist. ``` # this works in python, creating file.txt if it doesnt exist >>> fp = open ("...
Check out [os.path.expanduser()](http://docs.python.org/2.7/library/os.path.html#os.path.expanduser): > ### os.path.expanduser(*path*) > > On Unix and Windows, return the argument with an initial component of > ~ or ~user replaced by that user‘s > home directory. A lot of things don't like `~` in paths and this wil...
Regex in Python to find words that follow pattern: vowel, consonant, vowel, consonant
6,080,008
6
2011-05-21T06:17:01Z
6,080,058
9
2011-05-21T06:30:06Z
[ "python", "regex" ]
Trying to learn Regex in Python to find words that have consecutive vowel-consonant or consonant-vowel combinations. How would I do this in regex? If it can't be done in Regex, is there an efficient way of doing this in Python?
I believe you should be able to use a regular expression like this: ``` r"([aeiou][bcdfghjklmnpqrstvwxz])+" ``` for matching vowel followed by consonant and: ``` r"([bcdfghjklmnpqrstvwxz][aeiou])+" ``` for matching consonant followed by vowel. For reference, the + means it will match the largest repetition of this ...
How to get the size of tar.gz in (MB) file in python
6,080,477
4
2011-05-21T08:10:12Z
6,080,504
16
2011-05-21T08:17:26Z
[ "python", "linux", "file-io" ]
I am doing backups in python script but i need to get the size of tar.gz file created in MB How can i get the size in MB of that file
It's not clear from your question whether you want to the compressed or uncompressed size of the file, but in the former case, it's easy with the `os.path.getsize` function [from the os module](http://docs.python.org/library/os.path.html#os.path.getsize) ``` >>> import os >>> os.path.getsize('flickrapi-1.2.tar.gz') 35...
install_requires in setup.py depending on installed Python version
6,080,646
5
2011-05-21T08:45:59Z
6,080,922
12
2011-05-21T09:43:46Z
[ "python", "setuptools" ]
My setup.py looks something like this: ``` from distutils.core import setup setup( [...] install_requires=['gevent', 'ssl', 'configobj', 'simplejson', 'mechanize'], [...] ) ``` Under Python 2.6 (or higher) the installation of the ssl module fails with: ``` ValueError: This extension should not be used w...
It's just a list, so somewhere above you have to conditionally build a list. Something like to following is commonly done. ``` import sys if sys.version_info < (2 , 6): REQUIRES = ['gevent', 'ssl', 'configobj', 'simplejson', 'mechanize'], else: REQUIRES = ['gevent', 'configobj', 'simplejson', 'mechanize'], s...
Dump a NumPy array into a csv file
6,081,008
172
2011-05-21T10:01:16Z
6,081,043
290
2011-05-21T10:10:15Z
[ "python", "arrays", "csv", "numpy" ]
Is there a way to dump a NumPy array into a CSV file? I have a 2D NumPy array and need to dump it in human-readable format.
[numpy.savetxt](http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html) saves an array to a text file. ``` import numpy a = numpy.asarray([ [1,2,3], [4,5,6], [7,8,9] ]) numpy.savetxt("foo.csv", a, delimiter=",") ```
Dump a NumPy array into a csv file
6,081,008
172
2011-05-21T10:01:16Z
6,081,051
12
2011-05-21T10:11:55Z
[ "python", "arrays", "csv", "numpy" ]
Is there a way to dump a NumPy array into a CSV file? I have a 2D NumPy array and need to dump it in human-readable format.
[savetxt](http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html) may just be sufficient.
Dump a NumPy array into a csv file
6,081,008
172
2011-05-21T10:01:16Z
30,189,734
10
2015-05-12T11:37:44Z
[ "python", "arrays", "csv", "numpy" ]
Is there a way to dump a NumPy array into a CSV file? I have a 2D NumPy array and need to dump it in human-readable format.
[`tofile`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tofile.html) is a convenient function to do this: ``` import numpy as np a = np.asarray([ [1,2,3], [4,5,6], [7,8,9] ]) a.tofile('foo.csv',sep=',',format='%10.5f') ``` The man page has some useful notes: > This is a convenience function for ...
TeX in matplotlib on Mac OS X and TeX Live
6,082,126
9
2011-05-21T13:46:35Z
6,082,265
10
2011-05-21T14:11:10Z
[ "python", "osx", "matplotlib", "tex" ]
I have the following Hello World code to try out TeX rendering with matplotlib on my Mac. ``` import matplotlib.pyplot as plt from matplotlib import rc rc('text', usetex=True) rc('font', family='serif') plt.text(2,2,r"Hello World!") plt.show() ``` With that code, I'd get the following error: ``` sh: latex: command...
In future you might want to mention that you're running the code from NetBeans. The Python path is not `$PATH`, instead it's `sys.path`, the path from which Python code is loaded. You need to set `os.environ['PATH']` in your Python code; with TeX Live the preferred way to reference the current TeX installation is `/usr...
Order of keys in Python dictionary
6,083,531
27
2011-05-21T18:11:52Z
6,083,538
37
2011-05-21T18:13:18Z
[ "python", "dictionary", "order" ]
I have a dictionary ``` {'a': 'first', 'b': 'second'} ``` However, I need the dictionary in a different order: ``` {'b': 'second', 'a': 'first'} ``` What is the best way to do this?
Dictionaries are **not ordered**. So there is no way to do it. If you have python2.7+, you can use `collections.OrderedDict` - in this case you could retrieve the item list using `.items()` and then reverse it and create a new `OrderedDict` from the reversed list: ``` >>> od = OrderedDict((('a', 'first'), ('b', 'seco...
PyTables vs. SQLite3 insertion speed
6,083,713
10
2011-05-21T18:41:54Z
6,411,903
8
2011-06-20T13:28:44Z
[ "python", "sqlite3", "pytables" ]
I bought Kibot's stock data and it is enormous. I have about 125,000,000 rows to load (1000 stocks \* 125k rows/stock [1-minute bar data since 2010-01-01], each stock in a CSV file whose fields are Date,Time,Open,High,Low,Close,Volume). I'm totally new to python (I chose it because it's free and well-supported by a com...
1. Back in 2003, a [scientific paper](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.112.7164&rep=rep1&type=pdf) on the comparison of PyTables and Sqlite was written by F. Altec, the author of PyTables. This shows that PyTables is usually faster, but not always. 2. On your point that PyTables feels 'bare bone...
Python- What word can have the most consecutive letters removed and still be a dictionary-valid word?
6,084,795
12
2011-05-21T22:18:21Z
6,084,856
10
2011-05-21T22:31:19Z
[ "python", "algorithm", "performance", "word" ]
I used this hideous and inefficient implementation to find the word that can have the most consecutive last letters removed and still be a word. Rodeo, for example, is a well-known one: Rodeo, Rode, Rod, Ro. The program found 'composers': Composers, Composer, Compose, Compos, Comp I was wondering how I should go abou...
``` for each english word W: for each letter you can remove: remove the letter if the result W' is also word: draw a line W->W' for each english word W: connect ROOT-> each english word W use a graph search algorithm to find the longest path starting at ROOT (specifically, the wo...
Python- What word can have the most consecutive letters removed and still be a dictionary-valid word?
6,084,795
12
2011-05-21T22:18:21Z
6,084,917
8
2011-05-21T22:45:29Z
[ "python", "algorithm", "performance", "word" ]
I used this hideous and inefficient implementation to find the word that can have the most consecutive last letters removed and still be a word. Rodeo, for example, is a well-known one: Rodeo, Rode, Rod, Ro. The program found 'composers': Composers, Composer, Compose, Compos, Comp I was wondering how I should go abou...
Here's an implementation I just wrote up. It runs in about five seconds with my ~235k word list. The output doesn't show the whole chain, but you can easily reassemble it from the output. ``` # Load the words into a dictionary words = dict((x.strip(), set()) for x in open("/usr/share/dict/words")) # For each word, re...
How to use raw python code in a Django template?
6,085,373
7
2011-05-22T00:53:41Z
6,085,381
11
2011-05-22T00:56:19Z
[ "python", "django" ]
In smarty templates you can use raw PHP code in a template by placing it within the "literal" template tag: ``` {literal} echo 'hello world'; {/literal} ``` How can you use raw python code in a Django template?
You can't, that's why you have to create custom template tag which runs the functionality. Here's more information on how to do that: <http://docs.djangoproject.com/en/dev/howto/custom-template-tags/>
Python min function with a list of objects
6,085,467
15
2011-05-22T01:26:07Z
6,085,478
18
2011-05-22T01:29:11Z
[ "python" ]
How can use the `key` argument for the `min` function to compare a list of objects's 1 attribute? Example ``` class SpecialNumber: def __init__(self, i): self.number = i li = [SpecialNumber(1), SpecialNumber(3), SpecialNumber(2)] ```
It's: ``` min(li, key=lambda x: x.number) ``` you need a function that accepts a `SpecialNumber` and returns its element.
Python min function with a list of objects
6,085,467
15
2011-05-22T01:26:07Z
6,085,482
26
2011-05-22T01:30:09Z
[ "python" ]
How can use the `key` argument for the `min` function to compare a list of objects's 1 attribute? Example ``` class SpecialNumber: def __init__(self, i): self.number = i li = [SpecialNumber(1), SpecialNumber(3), SpecialNumber(2)] ```
<http://docs.python.org/library/operator.html#operator.attrgetter> ``` from operator import attrgetter min_num = min(li,key=attrgetter('number')) ``` Sample interactive session: ``` >>> li = [SpecialNumber(1), SpecialNumber(3), SpecialNumber(2)] >>> [i.number for i in li] [1, 3, 2] >>> min_num = min(li,key=attrgette...
Python min function with a list of objects
6,085,467
15
2011-05-22T01:26:07Z
6,085,507
12
2011-05-22T01:38:30Z
[ "python" ]
How can use the `key` argument for the `min` function to compare a list of objects's 1 attribute? Example ``` class SpecialNumber: def __init__(self, i): self.number = i li = [SpecialNumber(1), SpecialNumber(3), SpecialNumber(2)] ```
I'd do it by overriding [`__cmp__`](http://docs.python.org/reference/datamodel.html#object.__cmp__) ``` class SpecialNumber: def __init__(self, i): self.number = i def __repr__(self): return '<SpecialNumber(%d)>' % self.number def __cmp__(self, other): return cmp(self.number, othe...
Python 3- How to retrieve an image from the web and display in a GUI using TKINTER?
6,086,262
4
2011-05-22T05:37:12Z
6,088,442
8
2011-05-22T14:11:29Z
[ "python", "user-interface", "tkinter", "urllib" ]
I want a function that, when a button is clicked, it will take an image from the web using URLLIB and display it in a GUI using TKINTER. I'm new to both URLLIB and TKINTER, so I'm having an incredibly difficult time doing this. Tried this, but it obviously doesn't work because it uses a textbox and only will display...
I don't use python 3, but I can give an answer that works in python 2.5+. I assume the code will work nearly identically on python 3. Before we get started, we need to import Tkinter and create the root window: ``` import Tkinter as tk root = tk.Tk() ``` Next, to download the image using urllib: ``` import urllib U...
Statement: with and tarfile
6,086,603
12
2011-05-22T07:19:38Z
6,086,722
9
2011-05-22T07:49:25Z
[ "python" ]
I try to use `with` statement and tarfile module... ``` with tarfile.open('/dir/dir/dir.tar.gz', 'w:gz') as fl: fl.add('/dir/dir/dir/', arcname = '/') ``` So it shows the next: ``` Traceback (most recent call last): File "", line 1, in AttributeError: 'TarFile' object has no attribute '__exit__' ``` I try to cr...
You can use [contextlib.closing](http://www.python.org/doc//current/library/contextlib.html#contextlib.closing), e.g.: ``` from contextlib import closing with closing(tarfile.open('/dir/dir/dir.tar.gz', 'w:gz')) as fl: fl.add('/dir/dir/dir/', arcname = '/') ``` From docs: > Even if an error occurs, `page.close()...
How to reduce an image size in image processing (scipy/numpy/python)
6,086,621
4
2011-05-22T07:23:36Z
6,089,599
9
2011-05-22T17:32:52Z
[ "python", "image", "image-processing", "numpy", "scipy" ]
Hello I have an image ( 1024 x 1024) and I used "fromfile" command in numpy to put every pixel of that image into a matrix. How can I reduce the size of the image ( ex. to 512 x 512) by modify that matrix a? ``` a = numpy.fromfile(( - path - ,'uint8').reshape((1024,1024)) ``` I have no idea how to modify the matrix ...
Use the zoom function from scipy: <http://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.zoom.html#scipy.ndimage.zoom> ``` from scipy.ndimage.interpolation import zoom a = np.ones((1024, 1024)) small_a = zoom(a, 0.5) ```
Is there a Python equivalent to Ruby's respond_to?
6,086,820
11
2011-05-22T08:22:49Z
6,086,869
8
2011-05-22T08:37:37Z
[ "python", "ruby", "class" ]
Is a way to see if a class responds to a method in Python? like in ruby: ``` class Fun def hello puts 'Hello' end end fun = Fun.new puts fun.respond_to? 'hello' # true ``` Also is there a way to see how many arguments the method requires?
Has method: ``` func = getattr(Fun, "hello", None) if callable(func): ... ``` Arity: ``` import inspect args, varargs, varkw, defaults = inspect.getargspec(Fun.hello) arity = len(args) ``` Note that arity can be pretty much anything if you have `varargs` and/or `varkw` not None.
Is there a Python equivalent to Ruby's respond_to?
6,086,820
11
2011-05-22T08:22:49Z
6,086,877
14
2011-05-22T08:39:03Z
[ "python", "ruby", "class" ]
Is a way to see if a class responds to a method in Python? like in ruby: ``` class Fun def hello puts 'Hello' end end fun = Fun.new puts fun.respond_to? 'hello' # true ``` Also is there a way to see how many arguments the method requires?
Hmmm .... I'd think that `hasattr` and `callable` would be the easiest way to accomplish the same goal: ``` class Fun: def hello(self): print 'Hello' hasattr(Fun, 'hello') # -> True callable(Fun.hello) # -> True ``` You could, of course, call `callable(Fun.hello)` from within an exception handling ...
How to get a complete exception stack trace in Python
6,086,976
19
2011-05-22T09:05:42Z
12,539,332
14
2012-09-21T23:21:35Z
[ "python", "exception", "exception-handling", "traceback" ]
The following snippet: ``` import traceback def a(): b() def b(): try: c() except: traceback.print_exc() def c(): assert False a() ``` Produces this output: ``` Traceback (most recent call last): File "test.py", line 8, in b c() File "test.py", line 13, in c assert Fal...
I don't know if there is a better way, but here's what I did: ``` import traceback import sys def format_exception(e): exception_list = traceback.format_stack() exception_list = exception_list[:-2] exception_list.extend(traceback.format_tb(sys.exc_info()[2])) exception_list.extend(traceback.format_exc...
How to get a complete exception stack trace in Python
6,086,976
19
2011-05-22T09:05:42Z
16,589,622
13
2013-05-16T14:04:47Z
[ "python", "exception", "exception-handling", "traceback" ]
The following snippet: ``` import traceback def a(): b() def b(): try: c() except: traceback.print_exc() def c(): assert False a() ``` Produces this output: ``` Traceback (most recent call last): File "test.py", line 8, in b c() File "test.py", line 13, in c assert Fal...
Here's a function based on [this answer](http://stackoverflow.com/a/3925311/321973). It will also work when no exception is present: ``` def full_stack(): import traceback, sys exc = sys.exc_info()[0] stack = traceback.extract_stack()[:-1] # last one would be full_stack() if not exc is None: # i.e. i...
How to capture pygame screen?
6,087,484
5
2011-05-22T11:01:36Z
6,087,515
16
2011-05-22T11:09:11Z
[ "python", "video-capture", "pygame" ]
How can I capture and save a sequence of images or a video of a pygame screen? Basically I want to share my game video on youtube. Also, want to make a tutorial. The game is rendered mainly in a loop: ``` def main(): while True: GetInput() Move() Shift() Draw() ``` With the `Dr...
Use `pygame.image.save` on your screen surface: ``` window = pygame.display.set_mode(...) ... pygame.image.save(window, "screenshot.jpeg") ``` Note that this will slow down your program tremendously. If it is time-based, you may wish to fake the framerate when doing a capture.
import C++ module, if fail: import Python version?
6,087,530
2
2011-05-22T11:12:47Z
6,087,546
7
2011-05-22T11:16:52Z
[ "c++", "python", "module", "import", "pyd" ]
I have a Python pyd module written in C++. I also have a Python version of the module (which is much slower). My question is, as I want the program to run on multiple OSs, can I try to import the C++ version in the program and import the slower Python version if that one fails (other OS, architecture)?
Yes, you can import some thing like this: ``` try: import CppModule as Module except ImportError: import PurePythonModule as Module ```
Comprehensive list of Python protocols/interfaces
6,087,731
15
2011-05-22T11:49:25Z
6,087,799
13
2011-05-22T12:02:52Z
[ "python", "interface", "protocols" ]
Lately, I was looking at some Python idioms. I found many descriptions of protocols used in Python, such as the ordering (`__cmp__`, ...) or generators. Besides, there are also methods like `__hash__` which are defined for every object (I suppose). After some search on the internet, I haven't found a comprehensive lis...
Your best reference is always going to be the [Python Online Documentation](https://docs.python.org/2/contents.html), specifically the section on [Special method names](https://docs.python.org/2/reference/datamodel.html#special-method-names). The interactive Python interpretor is a very useful tool, too. Try some of t...
How to get a random number between a float range? (Python)
6,088,077
125
2011-05-22T13:00:50Z
6,088,092
208
2011-05-22T13:04:33Z
[ "python", "random", "floating-point" ]
randrange(start, stop) only takes integer arguments... So how would I get a random number between two float values?
Use [random.uniform(a, b)](http://docs.python.org/library/random.html#random.uniform): ``` >>> random.uniform(1.5, 1.9) 1.8733202628557872 ```
How to get a random number between a float range? (Python)
6,088,077
125
2011-05-22T13:00:50Z
6,088,096
33
2011-05-22T13:04:40Z
[ "python", "random", "floating-point" ]
randrange(start, stop) only takes integer arguments... So how would I get a random number between two float values?
`random.uniform(a, b)` appears to be what your looking for. From the docs: > Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a. See [here](http://docs.python.org/library/random.html#random.uniform).
How to get a random number between a float range? (Python)
6,088,077
125
2011-05-22T13:00:50Z
30,008,586
18
2015-05-02T23:25:08Z
[ "python", "random", "floating-point" ]
randrange(start, stop) only takes integer arguments... So how would I get a random number between two float values?
Use `random.uniform` and don't forget to import random ``` import random random.uniform(0.1, 2.7) ```
how to send data with twisted protocol via factory
6,088,280
5
2011-05-22T13:39:43Z
6,088,673
10
2011-05-22T14:49:22Z
[ "python", "network-programming", "twisted" ]
I'm writing a client implementing a custom protocol, and have a factory for it. My problem is the following: my client has bi-dir communication, and sometimes I want to tell it "send this data". But all I have is the factory object: ``` class MyFactory(ClientFactory): protocol = MyProtocol def __init__(self, ...
You have access to all of the objects you want. The factory is responsible for creating protocol instances, so if you want to keep the protocol instance around where the factory can use it, override `buildProtocol` and save the instance: ``` class MyFactory(ClientFactory): protocol = MyProtocol ... def b...
What's your folder layout for a Flask app divided in modules?
6,089,020
14
2011-05-22T15:47:32Z
6,089,919
13
2011-05-22T18:34:44Z
[ "python", "flask", "flask-sqlalchemy" ]
I am experimenting with Flask coming from Django and I really like it. There is just one problem that I ran into. I read the flask docs and the part about big applications or something like that and it explains a way to divide your project in packages, each one with its own static and templates folder as well as its ow...
While I'm not ready to announce because I'm still actively working on refining the samples, you would probably benefit from the [flask-skeleton](https://github.com/sean-/flask-skeleton/) project that I'm developing. I got tired of reinventing the wheel with regards to bootstrapping Flask websites so I started to a comp...
Problem with inserting into MySQL database from Python
6,089,743
4
2011-05-22T18:00:18Z
6,089,897
9
2011-05-22T18:29:58Z
[ "python", "mysql", "osx", "terminal" ]
I am having trouble inserting a record into a MySQL database from python. This is what I am doing. ``` def testMain2(): conn = MySQLdb.connect(charset='utf8', host="localhost", user="root", passwd="root", db="epf") cursor = conn.cursor() tableName = "test_table" columnsDef = "(export_...
You haven't committed the transaction. ``` conn.commit() ``` (The MySQLdb library sets `autocommit` to False when connecting to MySQL. This means that you need to manually call commit or your changes will never make it into the database.)
How can I get the full file path of an icon name?
6,090,241
7
2011-05-22T19:33:39Z
6,090,294
10
2011-05-22T19:44:24Z
[ "python", "gtk", "icons", "gnome" ]
How can I get the full file path from an icon name in GNOME?
``` import gtk icon_theme = gtk.icon_theme_get_default() icon_info = icon_theme.lookup_icon("my-icon-name", 48, 0) print icon_info.get_filename() ```
Get HOG image features from OpenCV + Python?
6,090,399
12
2011-05-22T19:59:48Z
25,119,903
48
2014-08-04T13:31:37Z
[ "python", "image-processing", "opencv" ]
I've read this post about how to use OpenCV's HOG-based pedestrian detector: [How can I detect and track people using OpenCV?](http://stackoverflow.com/questions/2188646/how-can-i-detect-and-track-people-using-opencv) I want to use HOG for detecting other types of objects in images (not just pedestrians). However, the...
In python opencv you can compute hog like this: ``` import cv2 hog = cv2.HOGDescriptor() im = cv2.imread(sample) h = hog.compute(im) ```
Get HOG image features from OpenCV + Python?
6,090,399
12
2011-05-22T19:59:48Z
31,042,366
9
2015-06-25T06:03:44Z
[ "python", "image-processing", "opencv" ]
I've read this post about how to use OpenCV's HOG-based pedestrian detector: [How can I detect and track people using OpenCV?](http://stackoverflow.com/questions/2188646/how-can-i-detect-and-track-people-using-opencv) I want to use HOG for detecting other types of objects in images (not just pedestrians). However, the...
**1. Get Inbuilt Documentation:** Following command on your python console will help you know the structure of class HOGDescriptor: ``` import cv2; help(cv2.HOGDescriptor()) ``` **2. Example Code:** Here is a snippet of code to initialize an cv2.HOGDescriptor with different parameters (The terms I used here are st...
Detect last iteration over dictionary.iteritems() in python
6,090,417
9
2011-05-22T20:02:13Z
6,090,467
10
2011-05-22T20:08:11Z
[ "python", "dictionary" ]
Is there a simple way to detect the last iteration while iterating over a dictionary using `iteritems()`?
There is an ugly way to do this: ``` for i, (k, v) in enumerate(your_dict.iteritems()): if i == len(your_dict)-1: # do special stuff here ``` But you should really consider if you need this. I am almost certain that there is another way.
In Python why does a tuple of integers take up less space than distinct integers?
6,091,992
3
2011-05-23T01:28:33Z
6,092,016
13
2011-05-23T01:32:22Z
[ "python", "sizeof", "tuples" ]
Here's an example with random integers: ``` a, b, c, d = 79412623, 56529819571, 10431, 30461 t = (79412623, 56529819571, 10431, 30461) ``` And their sizes: ``` import sys sys.getsizeof(t) # 88 aa, bb, cc, dd = sys.getsizeof(a), sys.getsizeof(b), sys.getsizeof(c), sys.getsizeof(d) sum([aa,bb,cc,dd]) # 96 ``` Why doe...
The number returned by `sys.getsizeof` doesn't include the size of the objects contained by a container. ``` >>> sys.getsizeof({1:2}) 280 >>> sys.getsizeof({'a_really_long_string_that_takes_up_lots_of_space':'foo'}) 280 ```
Adding 2 matrix and Multiplying 2 matrix in python by using scipy/numpy
6,092,388
6
2011-05-23T02:53:21Z
6,092,399
9
2011-05-23T02:55:00Z
[ "python", "math", "matrix", "numpy", "scipy" ]
I am trying to use scipy and numpy to perform matrix addition and multiplication. I have 2 matrix "a" and "b". my goal is to add "a" and "b" together and store the result into a matrix "c" Also I want to multiply "a" and "b" and store into a matrix "d". Are there any function perform like that in Scipy/Numpy? Thank...
Matrix multiplication: ``` a = numpy.matrix(a) b = numpy.matrix(b) c = a+b d = a*b ``` Array multiplication (map operator.mul): ``` a = numpy.array(a) b = numpy.array(b) c = a+b d = a*b ```
Problem of loading mod_wsgi module into apache on Windows 64-bit
6,093,727
8
2011-05-23T06:44:24Z
10,553,087
7
2012-05-11T14:14:01Z
[ "python", "windows", "apache2", "mod-wsgi", "x86-64" ]
I'm trying to install mod\_wsgi module followed this [instruction](http://code.google.com/p/modwsgi/wiki/InstallationOnWindows). I've downloaded mod\_wsgi.so from [this source](http://www.lfd.uci.edu/~gohlke/pythonlibs/). It seems like apache cannot restart services properly and the page cannot be loaded after I added ...
I was faced with this situation as well, and Apache would run on windows 64bit, but won't if mod\_wsgi is loaded. I found a solution which is pretty simple: 1. Download and install a 64-bit version of Apache which is easily handled if you download and install from [http://wampserver.com/](http://www.wampserver.com...
Simple Gnome Panel Applet in Python
6,094,506
13
2011-05-23T08:12:00Z
6,188,423
11
2011-05-31T13:36:21Z
[ "python", "panel", "gnome" ]
When I'm on the train to work I connect my netbook to my Nexus One's wifi hotspot. As I go through a tunnel my phone obviously loses it's 3G connection and takes a while to re-establish once the train emerges. But the netbook wifi logo stays constant as it's still connected to the phone itself. I've written a little p...
Check out [this simple applet I made](https://gitorious.org/tomate#more). It has an icon that changes depending on events. Simply replace the logic with your logic and it should do the trick. Even better, it should be compatible with all freedesktop-compatible environments.
High Pass Filter for image processing in python by using scipy/numpy
6,094,957
10
2011-05-23T08:55:21Z
6,117,387
29
2011-05-24T21:53:02Z
[ "python", "image-processing", "numpy", "scipy" ]
I am currently studying image processing. In Scipy, I know there is one median filter in Scipy.signal. Can anyone tell me if there is one filter similar to high pass filter? Thank you
"High pass filter" is a very generic term. There are an infinite number of different "highpass filters" that do very different things (e.g. an edge dectection filter, as mentioned earlier, is technically a highpass (most are actually a bandpass) filter, but has a very different effect from what you probably had in mind...
In-place way to apply a permutation to a list? (inverse of sorting-by-key)
6,098,250
8
2011-05-23T14:01:40Z
6,098,304
10
2011-05-23T14:05:37Z
[ "python", "list", "sorting" ]
Here's a example of what I want to do ``` spam_list = ["We", "are", "the", "knights", "who", "say", "Ni"] spam_order = [0,1,2,4,5,6,3] spam_list.magical_sort(spam_order) print(spam_list) ["We", "are", "the", "who", "say", "Ni", "knights"] ``` I can do it with `enumerate`, `list` and so on, but I would like to direct...
You can give a special `key` to the sort function: ``` order = dict(zip(spam_list, spam_order)) spam_list.sort(key=order.get) ``` **Edit:** As @ninjagecko points out in [his answer](http://stackoverflow.com/questions/6098250/is-there-a-nice-way-to-sort-a-list-using-a-list-of-indices/6098383#6098383), this is not real...
In-place way to apply a permutation to a list? (inverse of sorting-by-key)
6,098,250
8
2011-05-23T14:01:40Z
6,098,306
17
2011-05-23T14:05:52Z
[ "python", "list", "sorting" ]
Here's a example of what I want to do ``` spam_list = ["We", "are", "the", "knights", "who", "say", "Ni"] spam_order = [0,1,2,4,5,6,3] spam_list.magical_sort(spam_order) print(spam_list) ["We", "are", "the", "who", "say", "Ni", "knights"] ``` I can do it with `enumerate`, `list` and so on, but I would like to direct...
You could try: ``` spam_list = [spam_list[i] for i in spam_order] ```
Are Mixin class __init__ functions not automatically called in python?
6,098,970
30
2011-05-23T14:57:38Z
6,099,026
18
2011-05-23T15:01:16Z
[ "python", "inheritance", "multiple-inheritance", "mixins" ]
I'd like to use a Mixin to always add some init functionality to my child classes which each inherit from different API base classes. Specifically, I'd like to make multiple different child classes that inherit from one of these different API-supplied base classes and the one Mixin, which will always have the Mixin ini...
Have the base class invoke `super().__init__()` even though it is a subclass of `object`. That way all the `__init__()` methods will be run. ``` class BaseClassOne(object): def __init__(self, *args, **kwargs): super(BaseClassOne, self).__init__(*args, **kwargs) print (" base ") ```
Are Mixin class __init__ functions not automatically called in python?
6,098,970
30
2011-05-23T14:57:38Z
6,100,595
8
2011-05-23T17:19:35Z
[ "python", "inheritance", "multiple-inheritance", "mixins" ]
I'd like to use a Mixin to always add some init functionality to my child classes which each inherit from different API base classes. Specifically, I'd like to make multiple different child classes that inherit from one of these different API-supplied base classes and the one Mixin, which will always have the Mixin ini...
Python performs no implicit calls to the `__init__` methods of a class's super-class(es) — but it's possible to make it happen automatically. One way is by defining a metaclass for your mixed class(es) that creates or extends the mixed class's `__init__` method so that it calls to all the listed bases' `__init__` fun...
Are Mixin class __init__ functions not automatically called in python?
6,098,970
30
2011-05-23T14:57:38Z
9,115,283
26
2012-02-02T15:48:14Z
[ "python", "inheritance", "multiple-inheritance", "mixins" ]
I'd like to use a Mixin to always add some init functionality to my child classes which each inherit from different API base classes. Specifically, I'd like to make multiple different child classes that inherit from one of these different API-supplied base classes and the one Mixin, which will always have the Mixin ini...
Sorry I saw this so late, but ``` class MixedClass2(SomeMixin, MyClass): pass >>> m = MixedClass2() mixin before base mixin after ``` The pattern @Ignacio is talking about is called cooperative multiple inheritance, and it's great. But if a base class isn't interested in cooperating, make it the second base...
Django - template context processors - breaking my app
6,099,330
13
2011-05-23T15:25:15Z
6,099,401
20
2011-05-23T15:31:16Z
[ "python", "django", "django-templates", "django-settings" ]
I was trying to set up a template context processor like [this article mentions](http://www.b-list.org/weblog/2006/jun/14/django-tips-template-context-processors/) so that I could provide information to every template. I wrote this function in views.py: ``` def items_in_cart(request): """Used by settings.TEMPLATE...
Django has a default set of TEMPLATE\_CONTEXT\_PROCESSORS, which you need to manually add when adding your own. <http://docs.djangoproject.com/en/1.3/ref/settings/#template-context-processors> Depending on your Django version these are different, however if using Django 1.3 you might have something as follows ``` TEM...
Why is 'True == not False' a syntax error in Python?
6,100,305
27
2011-05-23T16:45:19Z
6,100,328
42
2011-05-23T16:47:17Z
[ "python", "boolean" ]
Comparing boolean values with `==` works in Python. But when I apply the boolean `not` operator, the result is a syntax error: ``` Python 2.7 (r27:82500, Sep 16 2010, 18:02:00) [GCC 4.5.1 20100907 (Red Hat 4.5.1-3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> True == True True...
It has to do with [operator precedence in Python](http://docs.python.org/reference/expressions.html#operator-precedence) (the interpreter thinks you're comparing True to not, since `==` has a higher precedence than `not`). You need some parentheses to clarify the order of operations: ``` True == (not False) ``` In ge...
Why is 'True == not False' a syntax error in Python?
6,100,305
27
2011-05-23T16:45:19Z
6,100,331
9
2011-05-23T16:47:36Z
[ "python", "boolean" ]
Comparing boolean values with `==` works in Python. But when I apply the boolean `not` operator, the result is a syntax error: ``` Python 2.7 (r27:82500, Sep 16 2010, 18:02:00) [GCC 4.5.1 20100907 (Red Hat 4.5.1-3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> True == True True...
It's just a matter of operator precedence. Try: ``` >>> True == (not False) True ``` Have a look in [this table of operator precedences](https://docs.python.org/reference/expressions.html#operator-precedence), you'll find that `==` binds tigher than `not`, and thus `True == not False` is parsed as `(True == not) Fal...
Python: Alternating functions every x minutes
6,100,441
10
2011-05-23T17:00:28Z
6,100,517
10
2011-05-23T17:11:15Z
[ "python", "multithreading", "function", "timer", "alternate" ]
Say if I have four functions as below: ``` def foo(): subprocess.Popen('start /B someprogramA.exe', shell=True) def bar(): subprocess.Popen('start /B someprogramB.exe', shell=True) def foo_kill(): subprocess.Popen('taskkill /IM someprogramA.exe') def bar_kill(): subprocess.Popen('taskkill /IM somepr...
Remember that functions are first-class objects in Python. That means you can store them in variables and containers! One way to do it would be: ``` funcs = [(foo, foo_kill), (bar, bar_kill)] def run(self): counter = self.runTime for sec in range(self.runTime): runner, killer = funcs[counter % 2] #...
Creating a back-up list in python
6,100,719
5
2011-05-23T17:31:41Z
6,100,734
17
2011-05-23T17:32:54Z
[ "python", "list" ]
I want to create a back-up list of another list in python. Here is an example of the code. ``` x = [1,2,3] y = x x.pop(0) print y ``` This however yields the result `y = [2,3]` when I want it to yield `[1,2,3]`. How would I go about making the y list independent of the x list?
A common idiom for this is `y = x[:]`. This makes a shallow copy of `x` and stores it in `y`. Note that if `x` contains references to objects, `y` will also contain references to the same objects. This may or may not be what you want. If it isn't, take a look at [`copy.deepcopy()`](http://docs.python.org/library/copy....
Are python's file write() and urlopen() methods asynchronous?
6,100,934
6
2011-05-23T17:52:30Z
6,100,976
7
2011-05-23T17:56:44Z
[ "python", "file-io", "urllib" ]
As asked in the title, are `open('...','w').write('...')` and `urllib.urlopen('..')` asynchronous calls?
No. If you need them to be asynchronous then consider looking at event frameworks such as Twisted, glib, or Qt.
Dynamic use of templates in Jinja2
6,101,864
18
2011-05-23T19:20:57Z
6,106,769
38
2011-05-24T06:54:53Z
[ "python", "templates", "jinja2", "flask" ]
I have to following scenario: a python list of python dictionaries `l = [a,b,c,...,n]` each element of the list is a python dictionary that looks something like this: ``` d = {} d['type'] = 5 d['content'] = 'somestring' ``` Now i want all dictionaries as a list in in a main template. However each dictionary's conten...
If anyone needs it: ``` {% for d in dicts %} {% set template = d.type + '.html' %} {% include template %} {% endfor %} ``` then in the template you can access the content like so: ``` {{ d.content }} ``` Thanks to donri from the #pocoo channel on freenode !
Type of compiled regex object in python
6,102,019
30
2011-05-23T19:34:33Z
6,102,100
18
2011-05-23T19:41:23Z
[ "python", "regex", "types" ]
What is the type of the compiled regular expression in python? In particular, I want to evaluate ``` isinstance(re.compile(''), ???) ``` to be true, for introspection purposes. One solution I had was, have some global constant `REGEX_TYPE = type(re.compile(''))`, but it doesn't seem very elegant. **EDIT:** The rea...
When the type of something isn't well specified, there's nothing wrong with using the `type` builtin to discover the answer at runtime: ``` >>> import re >>> retype = type(re.compile('hello, world')) >>> isinstance(re.compile('goodbye'), retype) True >>> isinstance(12, retype) False >>> ``` Discovering the type at ru...
Type of compiled regex object in python
6,102,019
30
2011-05-23T19:34:33Z
6,102,556
11
2011-05-23T20:19:45Z
[ "python", "regex", "types" ]
What is the type of the compiled regular expression in python? In particular, I want to evaluate ``` isinstance(re.compile(''), ???) ``` to be true, for introspection purposes. One solution I had was, have some global constant `REGEX_TYPE = type(re.compile(''))`, but it doesn't seem very elegant. **EDIT:** The rea...
Prevention is better than cure. Don't create such a heterogeneous list in the first place. Have a **set** of allowed strings and a list of compiled regex objects. This should make your checking code look better and run faster: ``` if input in allowed_strings: ignored = False else: for allowed in allowed_regexe...
Type of compiled regex object in python
6,102,019
30
2011-05-23T19:34:33Z
7,054,512
13
2011-08-14T01:58:55Z
[ "python", "regex", "types" ]
What is the type of the compiled regular expression in python? In particular, I want to evaluate ``` isinstance(re.compile(''), ???) ``` to be true, for introspection purposes. One solution I had was, have some global constant `REGEX_TYPE = type(re.compile(''))`, but it doesn't seem very elegant. **EDIT:** The rea...
***Disclaimer:** This isn't intended as a direct answer for your specific needs, but rather something that may be useful as an alternative approach* --- You can keep with the ideals of duck typing, and use `hasattr` to determine if the object has certain properties that you want to utilize. For example, you could do ...
Type of compiled regex object in python
6,102,019
30
2011-05-23T19:34:33Z
30,943,547
8
2015-06-19T17:03:21Z
[ "python", "regex", "types" ]
What is the type of the compiled regular expression in python? In particular, I want to evaluate ``` isinstance(re.compile(''), ???) ``` to be true, for introspection purposes. One solution I had was, have some global constant `REGEX_TYPE = type(re.compile(''))`, but it doesn't seem very elegant. **EDIT:** The rea...
It is possible to compare a compiled regular expression with 're.\_pattern\_type' ``` import re pattern = r'aa' compiled_re = re.compile(pattern) print isinstance(compiled_re, re._pattern_type) >>True ``` Gives True, at least in version 2.7
Using MongoEngine Document class methods for custom validation and pre-save hooks
6,102,103
12
2011-05-23T19:41:45Z
6,602,255
13
2011-07-06T20:06:59Z
[ "python", "validation", "mongodb", "mongoengine" ]
I am currently exploring the possibilities of the MongoEngine "object document mapper". What is currently not clear to me is to what extent I can move my validation and object creation logic to the Document objects themselves. I have the impression that it should not be a problem, but I'm not finding a lot of examples...
You can override `save()`, with the usual caveat that you must call the parent class's method. If you find that you want to add validation hooks to all your models, you might consider creating a custom child class of `Document` something like: ``` class MyDocument(mongoengine.Document): def save(self, *args, **k...
Using MongoEngine Document class methods for custom validation and pre-save hooks
6,102,103
12
2011-05-23T19:41:45Z
18,790,842
16
2013-09-13T16:15:42Z
[ "python", "validation", "mongodb", "mongoengine" ]
I am currently exploring the possibilities of the MongoEngine "object document mapper". What is currently not clear to me is to what extent I can move my validation and object creation logic to the Document objects themselves. I have the impression that it should not be a problem, but I'm not finding a lot of examples...
Custom validation should now be done by [implementing the `clean()` method on a model](http://docs.mongoengine.org/en/latest/guide/document-instances.html?highlight=validate#pre-save-data-validation-and-cleaning). ``` class Essay(Document): status = StringField(choices=('Published', 'Draft'), required=True) pu...
Checking if property is settable/deletable in Python
6,102,747
14
2011-05-23T20:37:30Z
6,103,041
8
2011-05-23T21:06:19Z
[ "python", "properties" ]
How do I check if a property is settable or deletable in Python? The best I've found so far is ``` type(obj).__dict__["prop_name"].fset is not None ```
This is a good case when you should subscribe to "It's Easier to Ask for Forgiveness than Permission" philosophy, and just handle the exception in case property is *not* settable/deletable. ``` try: x.prop = 42 except AttributeError: pass ```
How do I get IntelliJ to recognize common Python modules?
6,102,908
94
2011-05-23T20:53:57Z
6,103,029
61
2011-05-23T21:05:09Z
[ "python", "intellij-idea" ]
I'm using IntelliJ 10 IDEA Ultimate Edition. I've created a new file Test.py, and IntelliJ has correctly switched to Python parsing mode. (I can confirm this by typing "d", it pops up "def" as a suggestion, and hitting tab correctly gives me "def :") However, when I try this code... ``` import os cwd = os.getcw <Ct...
Have you set up a python interpreter facet? Open Project Structure `CTRL`+`ALT`+`SHIFT`+`S` Project settings -> Facets -> expand Python click on child -> Python Interpreter Then: Project settings -> Modules -> Expand module -> Python -> Dependencies -> select python module sdk
How do I get IntelliJ to recognize common Python modules?
6,102,908
94
2011-05-23T20:53:57Z
6,105,873
11
2011-05-24T05:01:40Z
[ "python", "intellij-idea" ]
I'm using IntelliJ 10 IDEA Ultimate Edition. I've created a new file Test.py, and IntelliJ has correctly switched to Python parsing mode. (I can confirm this by typing "d", it pops up "def" as a suggestion, and hitting tab correctly gives me "def :") However, when I try this code... ``` import os cwd = os.getcw <Ct...
Here's what I had to do. (And I probably forgot an important aspect of my problem, which is that this wasn't set up as a Python project originally, but a Java project, with some python files in them.) Project Settings -> Modules -> Plus button (add a module) -> Python Then, click the "..." button next to Python Inter...