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 do I get all the keys that are stored in the Cassandra column family with pycassa?
2,430,539
6
2010-03-12T04:39:38Z
2,540,908
11
2010-03-29T20:08:44Z
[ "python", "cassandra", "pycassa" ]
Is anyone having experience working with [pycassa](http://github.com/vomjom/pycassa) I have a doubt with it. How do I get all the keys that are stored in the database? well in this small snippet we need to give the keys in order to get the associated columns (here the keys are 'foo' and 'bar'),that is fine but my requ...
try: ``` list(cf.get_range().get_keys()) ``` more good stuff here: <http://github.com/vomjom/pycassa>
Scapy install issues. Nothing seems to actually be installed?
2,430,573
10
2010-03-12T04:50:29Z
2,949,268
10
2010-06-01T11:19:14Z
[ "python", "installation", "scapy" ]
I have an apple computer running Leopard with python 2.6. I downloaded the latest version of scapy and ran "`python setup.py install`". All went according to plan. Now, when I try to run it in interactive mode by just typing "scapy", it throws a bunch of errors. What gives! Just in case, here is the FULL error message...
Follow these instructions from scapy website. There are dependencies that you must resolve before doing the install. It worked like a charm for me on a Windows machine. <http://www.secdev.org/projects/scapy/doc/installation.html#mac-os-x>
Scapy install issues. Nothing seems to actually be installed?
2,430,573
10
2010-03-12T04:50:29Z
20,714,575
7
2013-12-21T01:51:27Z
[ "python", "installation", "scapy" ]
I have an apple computer running Leopard with python 2.6. I downloaded the latest version of scapy and ran "`python setup.py install`". All went according to plan. Now, when I try to run it in interactive mode by just typing "scapy", it throws a bunch of errors. What gives! Just in case, here is the FULL error message...
I've also had lots of issues getting Scapy and its dependencies properly installed on my Mac, finally I found Homebrew Python GitHub page <https://github.com/Homebrew/homebrew-python> it contains lots of helpful/useful brew formula including one for Scapy that worked like a charm for me. ``` brew tap Homebrew/python b...
Text to a PNG on App Engine (Python)
2,431,345
24
2010-03-12T08:28:44Z
2,432,992
29
2010-03-12T13:28:27Z
[ "python", "image", "google-app-engine", "unicode" ]
*Note: I am cross-posting this from App Engine group because I got no answers there.* As part of my site about Japan, I have a feature where the user can get a large PNG for use as desktop background that shows the user's name in Japanese. After switching my site hosting entirely to App Engine, I removed this particul...
### Solution #1. Pure Python image library. You can try to bundle [PyPNG](http://packages.python.org/pypng/) with your application. PyPNG is a pure Python library to create PNG images. It depends on zlib module, which is allowed on AppEngine, so PyPNG should work on AppEngine. Just use StringIO objects instead of file...
Text to a PNG on App Engine (Python)
2,431,345
24
2010-03-12T08:28:44Z
2,436,549
9
2010-03-12T23:28:49Z
[ "python", "image", "google-app-engine", "unicode" ]
*Note: I am cross-posting this from App Engine group because I got no answers there.* As part of my site about Japan, I have a feature where the user can get a large PNG for use as desktop background that shows the user's name in Japanese. After switching my site hosting entirely to App Engine, I removed this particul...
I ran into this same problem with writing text to an image. The issue at hand is that any imaging libraries used on google app engine must be pure python, which rules out PIL. ## PyBMP [PyBMP](http://code.google.com/p/pybmp/) is a pure-python library that can do simple text rendering. From there you can use google's ...
Python: Lits containg tuples and long int
2,432,402
2
2010-03-12T11:37:47Z
2,432,406
8
2010-03-12T11:38:57Z
[ "python", "list", "tuples" ]
I have a list containing a tuples and long integers the list looks like this: ``` table = [(1L,), (1L,), (1L,), (2L,), (2L,), (2L,), (3L,), (3L,)] ``` How do i convert the table to look like a formal list? so the output would be: ``` table = ['1','1','1','2','2','2','3','3'] ``` For information purposes the dat...
``` >>> table = [(1L,), (1L,), (1L,), (2L,), (2L,), (2L,), (3L,), (3L,)] >>> [int(e[0]) for e in table] [1, 1, 1, 2, 2, 2, 3, 3] >>> [str(e[0]) for e in table] ['1', '1', '1', '2', '2', '2', '3', '3'] ```
A RAM error of big array
2,432,521
2
2010-03-12T12:05:22Z
2,432,565
7
2010-03-12T12:11:20Z
[ "python" ]
I need to get the numbers of one line randomly, and put each line in other array, then get the numbers of one col. I have a big file, more than 400M. In that file, there are 13496\*13496 number, means 13496 rows and 13496 cols. I want to read them to a array. This is my code: ``` _L1 = [[0 for col in range(13496)] fo...
you might want to approach your problem in another way. Process the file line by line. I don't see a need to store the whole big file into array. Otherwise, you might want to tell us what you are actually trying to do. ``` for line in open("400MB_file"): # do something with line. ``` Or ``` f=open("file") for l...
Can someone here explain constructors and destructors in python - simple explanation required - new to programming
2,433,130
2
2010-03-12T13:53:05Z
2,433,847
9
2010-03-12T15:44:57Z
[ "python", "class", "destructor" ]
i will try to see if it makes sense :- ``` class Person: '''Represents a person ''' population = 0 def __init__(self,name): //some statements and population += 1 def __del__(self): //some statements and population -= 1 def sayHi(self): '''grettings from person''' ...
Here is a slightly opinionated answer. Don't use `__del__`. This is not C++ or a language built for destructors. The `__del__` method really should be gone in Python 3.x, though I'm sure someone will find a use case that makes sense. If you need to use `__del __`, be aware of the basic limitations per <http://docs.pyt...
Python optimization
2,433,167
2
2010-03-12T13:58:54Z
2,436,616
8
2010-03-12T23:54:23Z
[ "python", "optimization" ]
``` f = open('wl4.txt', 'w') hh = 0 ###################################### for n in range(1,5): for l in range(33,127): if n==1: b = chr(l) + '\n' f.write(b) hh += 1 elif n==2: for s0 in range(33, 127): b = chr(l) + chr(s0) ...
**Further significant improvements are possible.** The following script file demonstrates these, using (for brevity) only the size 4 loop (which takes up well over 90% of the time). method 0: the OP's original code method 1: John Kugleman's solution method 2: (1) and move some string concatenation out of inner loop...
Python to MATLAB: exporting list of strings using scipy.io
2,433,924
11
2010-03-12T15:57:26Z
2,434,258
10
2010-03-12T16:45:43Z
[ "python", "string", "matlab", "scipy", "mat-file" ]
I am trying to export a list of text strings from Python to MATLAB using scipy.io. I would like to use scipy.io because my desired .mat file should include both numerical matrices (which I learned to do [here](http://stackoverflow.com/questions/1095265/matrix-from-python-to-matlab)) and text cell arrays. I tried: ```...
You need to make my\_list an array of numpy objects: ``` import scipy.io import numpy as np my_list = np.zeros((3,), dtype=np.object) my_list[:] = ['abc', 'def', 'ghi'] scipy.io.savemat('test.mat', mdict={'my_list': my_list}) ``` Then it will be saved in a cell format. There might be a better way of putting it into a...
How i can convert integer in to 'binary' in python
2,434,806
2
2010-03-12T18:09:33Z
2,434,817
7
2010-03-12T18:11:57Z
[ "python", "ruby" ]
In Ruby i do so ``` asd = 123 asd = '%b' % asd # => "1111011" ```
in Python >= 2.6 with [`bin()`](http://docs.python.org/library/functions.html): ``` asd = bin(123) # => '0b1111011' ``` To remove the leading `0b` you can just take the substring `bin(123)[2:]`. > **bin(x)** > Convert an integer number to a binary string. The result is a valid Python expression. If `x` is not a Py...
How i can convert integer in to 'binary' in python
2,434,806
2
2010-03-12T18:09:33Z
2,434,836
7
2010-03-12T18:16:18Z
[ "python", "ruby" ]
In Ruby i do so ``` asd = 123 asd = '%b' % asd # => "1111011" ```
you can also do string formatting, which doesn't contain `'0b'`: ``` >>> '{:b}'.format(123) #{0:b} in python 2.6 '1111011' ```
Python - Why use anything other than uuid4() for unique strings?
2,434,931
24
2010-03-12T18:35:41Z
2,434,951
11
2010-03-12T18:38:06Z
[ "python", "unique", "uuid" ]
I see quit a few implementations of unique string generation for things like uploaded image names, session IDs, et al, and many of them employ the usage of hashes like SHA1, or others. I'm not questioning the legitimacy of using custom methods like this, but rather just the reason. If I want a unique string, I just sa...
Well, sometimes you want collisions. If someone uploads the same exact image twice, maybe you'd rather tell them it's a duplicate rather than just make another copy with a new name.
Python - Why use anything other than uuid4() for unique strings?
2,434,931
24
2010-03-12T18:35:41Z
12,360,168
17
2012-09-10T22:12:33Z
[ "python", "unique", "uuid" ]
I see quit a few implementations of unique string generation for things like uploaded image names, session IDs, et al, and many of them employ the usage of hashes like SHA1, or others. I'm not questioning the legitimacy of using custom methods like this, but rather just the reason. If I want a unique string, I just sa...
Using a hash to uniquely identify a resource allows you to generate a 'unique' reference from the object. For instance, Git uses SHA hashing to make a unique hash that represents the exact changeset of a single a commit. Since hashing is deterministic, you'll get the same hash for the same file every time. Two people ...
What is the new way of checking "callable" methods in python 3.x?
2,435,066
5
2010-03-12T18:59:01Z
5,876,453
13
2011-05-03T22:26:31Z
[ "python", "python-3.x", "introspection" ]
I was studying introspection in Python, and as I was getting through basic examples, I found out that the `callable` built-in function is no longer available in Python 3.1. How can I check if a method is callable now? Thank you
The callable() builtin function from Py2.x was resurrected in python3.2.
Trying to get django app to work with mod_wsgi on CentOS 5
2,435,125
7
2010-03-12T19:09:54Z
2,436,341
7
2010-03-12T22:34:17Z
[ "python", "django", "mod-wsgi", "centos5" ]
I'm running CentOS 5, and am trying to get a django application working with mod\_wsgi. I'm using .wsgi settings I got working on Ubuntu. I'm also using an alternate installation of python (/opt/python2.6/) since my django application needs >2.5 and the OS uses 2.3 Here is the error: ``` [Thu Mar 04 10:52:15 2010] [e...
`SystemError: dynamic module not initialized properly` is the exception that is thrown when a dll (or .so) that is being loaded cannot be properly initialized. In function `_PyImport_LoadDynamicModule` of `Python/importdl.c` in case anyone is interested. Now, the dll/so in question (the *dynamic module* in Python parl...
using DES/3DES with python
2,435,283
8
2010-03-12T19:33:11Z
2,438,609
14
2010-03-13T14:09:32Z
[ "python", "cryptography", "3des" ]
what is the best module /package in python to use des /3des for encryption /decryption. could someone provide example to encrypt data with des/3des on python.
[**pyDes**](http://twhiteman.netfirms.com/des.html) can be used for both, DES and 3DES. Sample usage: ``` from pyDes import * data = "Please encrypt my data" k = des("DESCRYPT", CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5) d = k.encrypt(data) print "Encrypted: %r" % d print "Decrypted: %r" % k.decrypt(d) ass...
pdf viewer for pyqt4 application?
2,435,470
8
2010-03-12T19:59:36Z
2,435,514
8
2010-03-12T20:05:44Z
[ "python", "pdf", "qt4", "pyqt4" ]
I'm writing a Python+Qt4 application that would ideally need to pop up a window every once in a while, to display pdf documents and allow very basic operations, namely scrolling through the different pages and printing the document. I've found the reportLab to create pdf files, but nothing about pdf viewers. Does anyo...
you can use [Poppler](http://doc.trolltech.com/qq/qq27-poppler.html) for that.
How do I do advanced Python hash autovivification?
2,435,989
9
2010-03-12T21:24:17Z
2,436,002
15
2010-03-12T21:26:17Z
[ "python", "data-structures", "autovivification" ]
This question is about implementing the full Perl autovivification in Python. I know similar questions were asked before and so far the best answer is in "[What is the best way to implement nested dictionaries in Python?](http://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries-in...
``` a = collections.defaultdict(lambda: collections.defaultdict(list)) ```
When to use weak references in Python?
2,436,302
23
2010-03-12T22:25:20Z
2,436,352
15
2010-03-12T22:36:56Z
[ "python", "weak-references" ]
Can anyone explain usage of weak references? The [documentation](http://docs.python.org/library/weakref.html) doesn't explain it precisely, it just says that the GC can destroy the object linked to via a weak reference at any time. Then what's the point of having an object that can disappear at any time? What if I nee...
The typical use for weak references is if A has a reference to B and B has a reference to A. Without a proper cycle-detecting garbage collector, those two objects would never get GC'd even if there are no references to either from the "outside". However if one of the references is "weak", the objects will get properly ...
When to use weak references in Python?
2,436,302
23
2010-03-12T22:25:20Z
14,922,132
15
2013-02-17T14:30:33Z
[ "python", "weak-references" ]
Can anyone explain usage of weak references? The [documentation](http://docs.python.org/library/weakref.html) doesn't explain it precisely, it just says that the GC can destroy the object linked to via a weak reference at any time. Then what's the point of having an object that can disappear at any time? What if I nee...
Events are a common scenario for weak references. --- # Problem Consider a pair of objects: Emitter and Receiver. The receiver has shorter lifetime than the emitter. You could try an implementation like this: ``` class Emitter(object): def __init__(self): self.listeners = set() def emit(self): ...
Why do we have callable objects in python?
2,436,578
8
2010-03-12T23:39:42Z
2,436,614
12
2010-03-12T23:53:37Z
[ "python", "callable" ]
What is the purpose of a callable object? What problems do they solve?
Many kinds of objects are callable in Python, and they can serve many purposes: * functions are callable, and they may carry along a "closure" from an outer function * classes are callable, and calling a class gets you an instance of that class * methods are callable, for function-like behavior specifically pertaining...
How to use re match objects in a list comprehension
2,436,607
30
2010-03-12T23:51:02Z
2,436,623
55
2010-03-12T23:56:25Z
[ "python", "regex", "list-comprehension" ]
I have a function to pick out lumps from a list of strings and return them as another list: ``` def filterPick(lines,regex): result = [] for l in lines: match = re.search(regex,l) if match: result += [match.group(1)] return result ``` Is there a way to reformulate this as a lis...
``` [m.group(1) for l in lines for m in [regex.search(l)] if m] ``` The "trick" is the `for m in [regex.search(l)]` part -- that's how you "assign" a value that you need to use more than once, within a list comprehension -- add just such a clause, where the object "iterates" over a single-item list containing the one ...
How to use re match objects in a list comprehension
2,436,607
30
2010-03-12T23:51:02Z
2,436,626
8
2010-03-12T23:56:41Z
[ "python", "regex", "list-comprehension" ]
I have a function to pick out lumps from a list of strings and return them as another list: ``` def filterPick(lines,regex): result = [] for l in lines: match = re.search(regex,l) if match: result += [match.group(1)] return result ``` Is there a way to reformulate this as a lis...
``` return [m.group(1) for m in (re.search(regex, l) for l in lines) if m] ```
Does Python have a package/module management system?
2,436,731
110
2010-03-13T00:29:17Z
2,436,746
60
2010-03-13T00:33:40Z
[ "python", "module" ]
Does Python have a package/module management system, similar to how Ruby has rubygems where you can do `gem install packagename`? On *[Installing Python Modules](http://docs.python.org/install/index.html)*, I only see references to `python setup.py install`, but that requires you to find the package first.
And just to provide a contrast, there's also [pip](http://pypi.python.org/pypi/pip).
Does Python have a package/module management system?
2,436,731
110
2010-03-13T00:29:17Z
2,436,747
10
2010-03-13T00:34:03Z
[ "python", "module" ]
Does Python have a package/module management system, similar to how Ruby has rubygems where you can do `gem install packagename`? On *[Installing Python Modules](http://docs.python.org/install/index.html)*, I only see references to `python setup.py install`, but that requires you to find the package first.
There are at least two, [easy\_install](http://peak.telecommunity.com/DevCenter/EasyInstall) and its successor [pip](http://pypi.python.org/pypi/pip).
Does Python have a package/module management system?
2,436,731
110
2010-03-13T00:29:17Z
2,436,904
19
2010-03-13T01:31:21Z
[ "python", "module" ]
Does Python have a package/module management system, similar to how Ruby has rubygems where you can do `gem install packagename`? On *[Installing Python Modules](http://docs.python.org/install/index.html)*, I only see references to `python setup.py install`, but that requires you to find the package first.
As a Ruby and Perl developer and learning-Python guy, I haven't found easy\_install or pip to be the equivalent to RubyGems or CPAN. I tend to keep my development systems running the latest versions of modules as the developers update them, and freeze my production systems at set versions. Both RubyGems and CPAN make ...
Does Python have a package/module management system?
2,436,731
110
2010-03-13T00:29:17Z
12,234,724
54
2012-09-02T09:13:00Z
[ "python", "module" ]
Does Python have a package/module management system, similar to how Ruby has rubygems where you can do `gem install packagename`? On *[Installing Python Modules](http://docs.python.org/install/index.html)*, I only see references to `python setup.py install`, but that requires you to find the package first.
**The Python Package Index (PyPI)** seems to be standard: * To **install** a package: `pip install MyProject` * To **update** a package `pip install --upgrade MyProject` * To **fix a version** of a package `pip install MyProject==1.0` You can install the package manager as follows: ``` curl -O http://python-dist...
Does Python have a package/module management system?
2,436,731
110
2010-03-13T00:29:17Z
13,445,719
169
2012-11-18T23:27:38Z
[ "python", "module" ]
Does Python have a package/module management system, similar to how Ruby has rubygems where you can do `gem install packagename`? On *[Installing Python Modules](http://docs.python.org/install/index.html)*, I only see references to `python setup.py install`, but that requires you to find the package first.
# Recent progress **March 2014**: Good news! [Python 3.4](https://docs.python.org/3/whatsnew/3.4.html) ships with Pip. Pip has long been Python's de-facto standard package manager. You can install [a package](https://pypi.python.org/pypi/httpie) like this: ``` pip install httpie ``` Wahey! This is the best feature o...
How to calculate next Friday at 3am?
2,436,840
11
2010-03-13T01:02:16Z
2,436,868
9
2010-03-13T01:16:46Z
[ "python", "date-arithmetic" ]
How can you calculate the following Friday at 3am as a `datetime` object? **Clarification:** i.e., the calculated date should always be greater than 7 days away, and less than or equal to 14. --- Going with a slightly modified version of [Mark's solution](http://stackoverflow.com/questions/2436840/how-to-calculate-t...
If you install [dateutil](http://labix.org/python-dateutil), then you could do something like this: ``` import datetime import dateutil.relativedelta as reldate def following_friday(dt): rd=reldate.relativedelta( weekday=reldate.FR(+2), hours=+21) rd2=reldate.relativedelta( hour=3,m...
In plain English, what are Django generic views?
2,437,468
19
2010-03-13T06:09:35Z
2,437,486
18
2010-03-13T06:18:57Z
[ "python", "django", "django-generic-views" ]
The first two paragraphs of this page explain that generic views are supposed to make my life easier, less monotonous, and make me more attractive to women (I made up that last one): <https://docs.djangoproject.com/en/1.4/topics/generic-views/> I'm all for improving my life, but what do generic views actually do? It ...
Django generic views are just view functions (regular old python functions) that do things that are very common in web applications. Depending on the type of app you are building, they can save you from writing a lot of very simple views. For example, the `direct_to_template` generic view simply renders a template wi...
Limiting the size of a python dictionary
2,437,617
39
2010-03-13T07:19:49Z
2,437,645
27
2010-03-13T07:32:35Z
[ "python", "caching", "dictionary", "lru" ]
I'd like to work with a dict in python, but limit the number of key/value pairs to X. In other words, if the dict is currently storing X key/value pairs and I perform an insertion, I would like one of the existing pairs to be dropped. It would be nice if it was the least recently inserted/accesses key but that's not co...
Python 2.7 and 3.1 have [OrderedDict](http://docs.python.org/py3k/library/collections.html#ordereddict-objects) and there are pure-Python implementations for earlier Pythons. ``` from collections import OrderedDict class LimitedSizeDict(OrderedDict): def __init__(self, *args, **kwds): self.size_limit = kwds.pop...
Limiting the size of a python dictionary
2,437,617
39
2010-03-13T07:19:49Z
2,438,926
8
2010-03-13T15:45:44Z
[ "python", "caching", "dictionary", "lru" ]
I'd like to work with a dict in python, but limit the number of key/value pairs to X. In other words, if the dict is currently storing X key/value pairs and I perform an insertion, I would like one of the existing pairs to be dropped. It would be nice if it was the least recently inserted/accesses key but that's not co...
Here's a simple, no-LRU Python 2.6+ solution (in older Pythons you could do something similar with `UserDict.DictMixin`, but in 2.6 and better that's not recommended, and the ABCs from `collections` are preferable anyway...): ``` import collections class MyDict(collections.MutableMapping): def __init__(self, maxlen...
Limiting the size of a python dictionary
2,437,617
39
2010-03-13T07:19:49Z
28,270,649
7
2015-02-02T03:15:36Z
[ "python", "caching", "dictionary", "lru" ]
I'd like to work with a dict in python, but limit the number of key/value pairs to X. In other words, if the dict is currently storing X key/value pairs and I perform an insertion, I would like one of the existing pairs to be dropped. It would be nice if it was the least recently inserted/accesses key but that's not co...
[cachetools](https://pypi.python.org/pypi/cachetools) will provide you nice implementation of Mapping Hashes that does this (and it works on python 2 and 3). Excerpt of the documentation: > For the purpose of this module, a cache is a mutable mapping of a fixed > maximum size. When the cache is full, i.e. by adding a...
Reading Python Documentation for 3rd party modules
2,437,857
4
2010-03-13T09:30:01Z
2,437,872
9
2010-03-13T09:37:08Z
[ "python", "documentation", "pydoc", "imdbpy" ]
I recently downloaded IMDbpy module.. When I do, ``` import imdb help(imdb) ``` i dont get the full documentation.. I have to do ``` im = imdb.IMDb() help(im) ``` to see the available methods. I dont like this console interface. Is there any better way of reading the doc. I mean all the doc related to **module imdb...
Use [pydoc](http://docs.python.org/library/pydoc.html) ``` pydoc -w imdb ``` This will generate imdb.html in the same directory. --- `pydoc -p 9090` will start a HTTP server on port 9090, and you will be able to browse all documentation at <http://localhost:9090/>
What is the advantage of using static methods in Python?
2,438,473
33
2010-03-13T13:19:52Z
2,438,541
7
2010-03-13T13:46:23Z
[ "python" ]
I ran into unbound method error in python with the code ``` class Sample(object): '''This class defines various methods related to the sample''' def drawSample(samplesize,List): sample=random.sample(List,samplesize) return sample Choices=range(100) print Sample.drawSample(5,Choices) ``` After re...
**Why one would want to define static methods**? Suppose we have a `class` called `Math` then nobody will want to create object of `class Math` and then invoke methods like `ceil` and `floor` and `fabs` on it. So we make them `static`. For example doing ``` >> Math.floor(3.14) ``` is much better than ``` >> m...
What is the advantage of using static methods in Python?
2,438,473
33
2010-03-13T13:19:52Z
2,438,559
8
2010-03-13T13:51:12Z
[ "python" ]
I ran into unbound method error in python with the code ``` class Sample(object): '''This class defines various methods related to the sample''' def drawSample(samplesize,List): sample=random.sample(List,samplesize) return sample Choices=range(100) print Sample.drawSample(5,Choices) ``` After re...
When you call a function object from an object instance, it becomes a 'bound method' and gets the instance object itself is passed in as a first argument. When you call a `classmethod` object (which wraps a function object) on an object instance, the class of the instance object gets passed in as a first argument. Wh...
What is the advantage of using static methods in Python?
2,438,473
33
2010-03-13T13:19:52Z
2,438,627
42
2010-03-13T14:14:41Z
[ "python" ]
I ran into unbound method error in python with the code ``` class Sample(object): '''This class defines various methods related to the sample''' def drawSample(samplesize,List): sample=random.sample(List,samplesize) return sample Choices=range(100) print Sample.drawSample(5,Choices) ``` After re...
Static methods have limited use, because they don't have access to the attributes of an instance of a class (like a regular method does), and they don't have access to the attributes of the class itself (like a class method does). So they aren't useful for day-to-day methods. However, they can be useful to group some...
What is the advantage of using static methods in Python?
2,438,473
33
2010-03-13T13:19:52Z
2,438,925
12
2010-03-13T15:45:24Z
[ "python" ]
I ran into unbound method error in python with the code ``` class Sample(object): '''This class defines various methods related to the sample''' def drawSample(samplesize,List): sample=random.sample(List,samplesize) return sample Choices=range(100) print Sample.drawSample(5,Choices) ``` After re...
This is not quite to the point of your actual question, but since you've said you are a python newbie perhaps it will be helpful, and no one else has quite come out and said it explicitly. I would never have fixed the above code by making the method a static method. I would either have ditched the class and just writt...
What is the advantage of using static methods in Python?
2,438,473
33
2010-03-13T13:19:52Z
22,589,883
30
2014-03-23T10:54:03Z
[ "python" ]
I ran into unbound method error in python with the code ``` class Sample(object): '''This class defines various methods related to the sample''' def drawSample(samplesize,List): sample=random.sample(List,samplesize) return sample Choices=range(100) print Sample.drawSample(5,Choices) ``` After re...
See [this article](http://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods) for detailed explanation. **TL;DR** 1.It eliminates the use of `self` argument. 2.It reduces memory usage because Python doesn't have to instantiate a [bound-method](http://stackoverflow.com/questions/114214/class-meth...
What is the semantics of 'is' operator in Python?
2,438,667
10
2010-03-13T14:28:49Z
2,438,679
12
2010-03-13T14:33:51Z
[ "python" ]
How does `is` operator determine if two objects are the same? How does it work? I can't find it documented.
From the [documentation](http://docs.python.org/reference/datamodel.html): > Every object has an identity, a type > and a value. An object’s identity > never changes once it has been > created; you may think of it as the > object’s address in memory. The ‘is‘ > operator compares the identity of two > objects; ...
What is the semantics of 'is' operator in Python?
2,438,667
10
2010-03-13T14:28:49Z
2,438,691
12
2010-03-13T14:36:17Z
[ "python" ]
How does `is` operator determine if two objects are the same? How does it work? I can't find it documented.
[Comparison Operators](http://docs.python.org/reference/expressions.html#notin) Is works by comparing the object referenced to see if the operands point to the same object. ``` >>> a = [1, 2] >>> b = a >>> a is b True >>> c = [1, 2] >>> a is c False ``` `c` is not the same list as `a` therefore the `is` relation is ...
Set serial port pin high using python
2,438,848
3
2010-03-13T15:23:55Z
4,697,687
9
2011-01-15T02:57:25Z
[ "python", "serial-port" ]
Is it possible to set one pin of the serial port continuously high using python (or C)? If yes, how?
Using the pyserial methods `setRTS(level=True)` and `setDTR(level=True)` you can control the RTS and DTR lines at will. For instance, the following code will toggle the RTS pin of the first serial port. (See the pyserial documentation for the details). ``` import time import serial ser = serial.Serial(0) ser.setRTS(F...
Python Copy Through Assignment?
2,438,938
23
2010-03-13T15:47:48Z
2,438,943
20
2010-03-13T15:49:08Z
[ "python" ]
I would expect that the following code would just initialise the `dict_a`, `dict_b` and `dict_c` dictionaries. But it seams to have a copy through effect: ``` dict_a = dict_b = dict_c = {} dict_c['hello'] = 'goodbye' print dict_a print dict_b print dict_c ``` As you can see the result is as follows: ``` {'hello': '...
This is because in Python, variables (names) are just references to individual objects. When you assign `dict_a = dict_b`, you are really copying a memory address (or pointer, if you will) from `dict_b` to `dict_a`. There is still one instance of that dictionary. To get the desired behavior, use either the `dict.copy`...
Python Copy Through Assignment?
2,438,938
23
2010-03-13T15:47:48Z
2,445,989
7
2010-03-15T09:11:02Z
[ "python" ]
I would expect that the following code would just initialise the `dict_a`, `dict_b` and `dict_c` dictionaries. But it seams to have a copy through effect: ``` dict_a = dict_b = dict_c = {} dict_c['hello'] = 'goodbye' print dict_a print dict_b print dict_c ``` As you can see the result is as follows: ``` {'hello': '...
Even though ``` >>> dict_a, dict_b, dict_c = {}, {}, {} ``` is the right way to go in most cases, when it get more than 3 it looks weird Imagine ``` >>> a, b, c, d, e, f = {}, {}, {}, {}, {}, {} ``` In cases where I wanna initialize more than 3 things, I use ``` >>> a, b, c, d, e, f, = [dict() for x in range(6)] ...
Python: inserting double or single quotes around a string
2,439,027
3
2010-03-13T16:20:20Z
2,439,048
10
2010-03-13T16:24:25Z
[ "python", "sql", "quotes" ]
Im using python to access a MySQL database and im getting a unknown column in field due to quotes not being around the variable. code below: ``` cur = x.cnx.cursor() cur.execute('insert into tempPDBcode (PDBcode) values (%s);' % (s)) rows = cur.fetchall() ``` How do i manually insert double or single quotes around ...
You shouldn't use Python's string functions to build the SQL statement. You run the risk of leaving an SQL injection vulnerability. You should do this instead: ``` cur.execute('insert into tempPDBcode (PDBcode) values (%s);', s) ``` Note the comma.
Is it possible to use re2 from Python?
2,439,345
20
2010-03-13T17:51:26Z
2,457,569
12
2010-03-16T19:47:36Z
[ "python", "regex", "re2" ]
i just discovered <http://code.google.com/p/re2>, a promising library that uses a long-neglected way ([Thompson NFA](http://swtch.com/~rsc/regexp/regexp1.html)) to implement a regular expression engine that can be orders of magnitudes faster than the available engines of awk, Perl, or Python. so i downloaded the code ...
David Reiss has put together a Python wrapper for re2. It doesn't have all of the functionality of Python's re module, but it's a start. It's available here: <http://github.com/facebook/pyre2>.
Check if a MediaWiki page exists (Python)
2,439,824
2
2010-03-13T19:59:31Z
2,495,799
7
2010-03-22T21:13:21Z
[ "python", "mediawiki" ]
I'm working on a Python script that transforms this: ``` foo bar ``` Into this: ``` [[Component foo]] [[bar]] ``` The script checks (per input line) if the page "Component foo" exists. If it exists then a link to that page is created, if it doesn't exist then a direct link is created. The problem is that I need a ...
You can definitely use the API to check if a page exists: ``` #Assuming words is a list of words you wish to query for import urllib # replace en.wikipedia.org with the address of the wiki you want to access query = "http://en.wikipedia.org/w/api?action=query&titles=%s&format=xml" % "|".join(words) pages = urllib.url...
Python 3: Most efficient way to create a [func(i) for i in range(N)] list comprehension
2,439,986
7
2010-03-13T20:54:43Z
2,440,583
7
2010-03-13T23:54:40Z
[ "python", "list-comprehension" ]
Say I have a function func(i) that creates an object for an integer i, and N is some nonnegative integer. Then what's the fastest way to create a list (not a range) equal to this list ``` mylist = [func(i) for i in range(N)] ``` without resorting to advanced methods like creating a function in C? My main concern with...
Somebody wrote: """Python is smart enough. As long as the object you're iterating over has a `__len__` or `__length_hint__` method, Python will call it to determine the size and preallocate the array.""" As far as I can tell, **there is no preallocation in a list comprehension**. Python has no way of telling from the ...
How to check the existence of a row in SQLite with Python?
2,440,147
24
2010-03-13T21:42:37Z
2,440,179
51
2010-03-13T21:51:46Z
[ "python", "sql", "sqlite", "sqlite3" ]
I have the cursor with the query statement as follows: ``` cursor.execute("select rowid from components where name = ?", (name,)) ``` I want to check for the existence of the components: name and return to a python variable. How do I do that?
Since the `name`s are unique, I really favor your (the OP's) method of using `fetchone` or Alex Martelli's method of using `SELECT count(*)` over my initial suggestion of using `fetchall`. `fetchall` wraps the results (typically multiple rows of data) in a list. Since the `name`s are unique, `fetchall` returns either ...
How to check the existence of a row in SQLite with Python?
2,440,147
24
2010-03-13T21:42:37Z
2,440,185
10
2010-03-13T21:54:26Z
[ "python", "sql", "sqlite", "sqlite3" ]
I have the cursor with the query statement as follows: ``` cursor.execute("select rowid from components where name = ?", (name,)) ``` I want to check for the existence of the components: name and return to a python variable. How do I do that?
Ooops, I have found the answer ``` exist = cursor.fetchone() if exist is None: #not exists else: #exists ```
Getting CPU temperature using Python?
2,440,511
20
2010-03-13T23:35:19Z
2,440,544
8
2010-03-13T23:42:04Z
[ "python", "cpu", "temperature" ]
How do I retrieve the temperature of my CPU using Python? (Assuming I'm on Linux)
If your Linux supports ACPI, reading pseudo-file `/proc/acpi/thermal_zone/THM0/temperature` (the path may differ, I know it's `/proc/acpi/thermal_zone/THRM/temperature` in some systems) should do it. But I don't think there's a way that works in *every* Linux system in the world, so you'll have to be more specific abou...
Getting CPU temperature using Python?
2,440,511
20
2010-03-13T23:35:19Z
15,213,255
9
2013-03-04T23:40:35Z
[ "python", "cpu", "temperature" ]
How do I retrieve the temperature of my CPU using Python? (Assuming I'm on Linux)
There is a [newer API](http://shallowsky.com/blog/linux/kernel/sysfs-thermal-zone.html) (see also [LWN article](http://lwn.net/Articles/268958/) and [Linux kernel doc](http://www.mjmwired.net/kernel/Documentation/thermal/sysfs-api.txt)) showing temperatures under e.g. ``` /sys/class/thermal/thermal_zone0/temp ``` Rea...
How do I find the length of media with gstreamer?
2,440,554
12
2010-03-13T23:44:29Z
2,441,373
17
2010-03-14T06:16:05Z
[ "python", "video", "media", "gstreamer" ]
How do I find the playback time of media with gstreamer?
Here's a simple Python script to get the duration of anything gstreamer can decode. Note that all times in gstreamer are in nanoseconds. # duration.py: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division import sys import gobject gobject.threads_init() import pygst pygst.require("0.10")...
Formatting floats in Python without superfluous zeros
2,440,692
57
2010-03-14T00:27:39Z
2,440,708
67
2010-03-14T00:34:31Z
[ "python", "formatting", "floating-point", "pretty-print" ]
How to format a float so it does not containt the remaing zeros? In other words, I want the resulting string to be as short as possible..? Like: ``` 3 -> "3" 3. -> "3" 3.0 -> "3" 3.1 -> "3.1" 3.14 -> "3.14" 3.140 -> "3.14" ```
You could use `%g` to achieve this: ``` '%g'%(3.140) ``` or, for Python 2.6 or better: ``` '{0:g}'.format(3.140) ``` From the [docs for `format`](http://docs.python.org/library/string.html#format-specification-mini-language): `g` causes (among other things) > insignificant trailing zeros [to be] > removed from the...
Formatting floats in Python without superfluous zeros
2,440,692
57
2010-03-14T00:27:39Z
2,440,786
72
2010-03-14T01:11:24Z
[ "python", "formatting", "floating-point", "pretty-print" ]
How to format a float so it does not containt the remaing zeros? In other words, I want the resulting string to be as short as possible..? Like: ``` 3 -> "3" 3. -> "3" 3.0 -> "3" 3.1 -> "3.1" 3.14 -> "3.14" 3.140 -> "3.14" ```
Me, I'd do `('%f' % x).rstrip('0').rstrip('.')` -- guarantees fixed-point formatting rather than scientific notation, etc etc. Yeah, not as slick and elegant as `%g`, but, it works (and I don't know how to force `%g` to never use scientific notation;-).
What is the relationship between docutils and Sphinx?
2,441,078
16
2010-03-14T03:24:05Z
2,441,159
20
2010-03-14T04:15:48Z
[ "python", "documentation-generation", "python-sphinx", "epydoc" ]
There seems to be a plethora of documentation tools for Python. Another one that I've run across is epydoc. It seems like Sphinx is the de facto standard, because it's used to generate the official Python docs. Can someone please sort out the current state of Python's documentation tools for me?
[epydoc](http://epydoc.sourceforge.net/) and [Sphinx](http://sphinx.pocoo.org/) are different types of tools. They are the same in that they: * Both use [ReST](http://en.wikipedia.org/wiki/ReStructuredText) via [docutils](http://docutils.sourceforge.net/). * Both are very Pythonic in their focus * Both can generate H...
Embed python interpreter in a python application
2,441,172
7
2010-03-14T04:24:12Z
2,441,184
9
2010-03-14T04:28:23Z
[ "python", "interpreter", "embedding" ]
i'm looking for a way to ship the python interpreter with my application (also written in python), so that it doesn't need to have python installed on the machine. I searched google and found a bunch of results about how to embed the python interpreter in applications written in various languages, but nothing for appl...
For distribution on Windows machines, look into [**py2exe**](http://www.py2exe.org/) ``` py2exe is a Python Distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation ``` For the MacIntosh, there is [**py2app**](http://svn.pythonmac.org/py...
How do you use pip, virtualenv and Fabric to handle deployment?
2,441,704
66
2010-03-14T09:23:20Z
2,448,744
78
2010-03-15T16:31:48Z
[ "python", "deployment", "virtualenv", "fabric", "pip" ]
What are your settings, your tricks, and above all, your workflow? These tools are great but there are still no best practices attached to their usage, so I don't know what is the most efficient way to use them. * Do you use [pip](http://pypi.python.org/pypi/pip) bundles or always download? * Do you set up Apache/C...
"Best practices" are very context-dependent, so I won't claim my practices are best, just that they work for me. I work on mostly small sites, so no multiple-server deployments, CDNs etc. I do need to support Webfaction shared hosting deployment, as some clients need the cheapest hosting they can find. I do often have ...
How do you use pip, virtualenv and Fabric to handle deployment?
2,441,704
66
2010-03-14T09:23:20Z
3,310,647
9
2010-07-22T15:38:30Z
[ "python", "deployment", "virtualenv", "fabric", "pip" ]
What are your settings, your tricks, and above all, your workflow? These tools are great but there are still no best practices attached to their usage, so I don't know what is the most efficient way to use them. * Do you use [pip](http://pypi.python.org/pypi/pip) bundles or always download? * Do you set up Apache/C...
I use fabric to build and deploy my code and assume a system already set up for that. I think that a tool like [puppet](http://www.puppetlabs.com/) is more appropriate to automate the installation of things like apache and mysql, though I have yet to really include it in my workflow. Also, I usually have a different v...
How to discover table properties from SQLAlchemy mapped object
2,441,796
14
2010-03-14T10:11:10Z
2,448,930
34
2010-03-15T16:58:44Z
[ "python", "sqlite", "sqlalchemy", "instrumentation" ]
I have a class mapped with a table, in my case in a declarative way, and I want to "discover" table properties, columns, names, relations, from this class: ``` engine = create_engine('sqlite:///' + databasePath, echo=True) # setting up root class for declarative declaration Base = declarative_base(bind=engine) class...
Information you need you can get from [Table](http://www.sqlalchemy.org/docs/reference/sqlalchemy/schema.html?highlight=table#sqlalchemy.schema.Table) object: * `Ship.__table__.columns` will provide you with columns information * `Ship.__table__.foreign_keys` will list foreign keys * `Ship.__table__.constraints`, `Shi...
matplotlib: how to refresh figure.canvas
2,441,906
10
2010-03-14T11:00:53Z
2,463,844
7
2010-03-17T16:05:58Z
[ "python", "wxpython", "matplotlib" ]
I can't understand how to refresh FigureCanvasWxAgg instance. Here is the example: ``` import wx import matplotlib from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas from matplotlib.figure import Figure class MainFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, N...
As I said in the comments, I don't think that the figure canvas refresh is your problem, in fact I think it's doing exactly what it's supposed to (redrawing itself based on it's last state [ie as it was in your subplot]). I think your problem is more that the wxFrame is not refreshing. The easiest way to fix that woul...
How to delete an element from a list while iterating it in Python?
2,442,651
2
2010-03-14T15:36:38Z
2,442,655
11
2010-03-14T15:37:48Z
[ "python" ]
Suppose I have a list of numbers: ``` L = [1, 2, 3, 4, 5] ``` How do I delete an element, let's say 3, from the list while I iterate it? I tried the following code but it didn't do it: ``` for el in L: if el == 3: del el ``` Any ideas? Thanks, Boda Cydo.
Best is usually to proceed constructively -- build the new list of the items you want instead of removing those you don't. E.g.: ``` L[:] = [el for el in L if el != 3] ``` the list comprehension builds the desired list and the assignment to the "whole-list slice", `L[:]`, ensure you're **not** just rebinding a name, ...
Concatenate generator and item
2,443,252
25
2010-03-14T18:39:25Z
2,443,260
36
2010-03-14T18:41:00Z
[ "python", "iterator", "generator", "list-comprehension" ]
I have a generator (numbers) and a value (number). I would like to iterate over these as if they were one sequence: ``` i for i in tuple(my_generator) + (my_value,) ``` The problem is, as far as I undestand, this creates 3 tuples only to immediately discard them and also copies items in "my\_generator" once. Better ...
[`itertools.chain`](http://docs.python.org/library/itertools.html#itertools.chain) treats several sequences as a single sequence. So you could use it as: ``` import itertools def my_generator(): yield 1 yield 2 for i in itertools.chain(my_generator(), [5]): print i ``` which would output: ``` 1 2 5 ``...
Problem running python/matplotlib in background after ending ssh session
2,443,702
15
2010-03-14T20:43:33Z
2,443,957
13
2010-03-14T22:04:47Z
[ "python", "ssh", "background", "matplotlib", "tkinter" ]
I have to VPN and then ssh from home to my work server and want to run a python script in the background, then log out of the ssh session. My script makes several histogram plots using matplotlib, and as long as I keep the connection open everything is fine, but if I log out I keep getting an error message in the log f...
I believe your matplotlib backend requires X11. Look in your matplotlibrc file to determine what your default is (from the error, I'm betting TkAgg). To run without X11, use the Agg backend. Either set it globally in the matplotlibrc file or on a script by script by adding this to the python program: ``` import matplo...
Problem running python/matplotlib in background after ending ssh session
2,443,702
15
2010-03-14T20:43:33Z
2,444,638
9
2010-03-15T01:53:49Z
[ "python", "ssh", "background", "matplotlib", "tkinter" ]
I have to VPN and then ssh from home to my work server and want to run a python script in the background, then log out of the ssh session. My script makes several histogram plots using matplotlib, and as long as I keep the connection open everything is fine, but if I log out I keep getting an error message in the log f...
It looks like you're running in interactive mode by default, so matplotlib wants to plot everything to the screen first, which of course it can't do. Try putting ``` ioff() ``` at the top of your script, along with making the backend change. reference: <http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotl...
How to make socket.listen(1) work for some time and then continue rest of code?
2,444,178
2
2010-03-14T22:59:56Z
2,444,219
12
2010-03-14T23:10:58Z
[ "python", "sockets", "ports" ]
I'm making server that make a tcp socket and work over port range, with each port it will listen on that port for some time, then continue the rest of the code. like this:: ``` import socket sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sck.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) msg ='' por...
You can [settimeout](http://docs.python.org/library/socket.html?highlight=socket.send#socket.socket.settimeout) on the socket to the maximum amount of time you want to wait on it each time (call it again before every `listen` to the time you want to wait *this* time around) -- you'll get an exception, [socket.timeout](...
Python sock.listen(...)
2,444,459
4
2010-03-15T00:38:14Z
2,444,483
7
2010-03-15T00:45:18Z
[ "python", "concurrency", "sockets", "multithreading" ]
All the examples I've seen of `sock.listen(5)` in the python documentation suggest I should set the max backlog number to be `5`. This is causing a problem for my app since I'm expecting some very high volume (many concurrent connections). I set it to 200 and haven't seen any problems on my system, but was wondering ho...
The doc say this > `socket.listen(backlog)` Listen for > connections made to the socket. The > backlog argument specifies the maximum > number of queued connections and > should be at least 1; the maximum > value is system-dependent (usually 5). Obviously the system value is more than 5 on your system. I don't see wh...
Python sock.listen(...)
2,444,459
4
2010-03-15T00:38:14Z
2,444,491
12
2010-03-15T00:49:41Z
[ "python", "concurrency", "sockets", "multithreading" ]
All the examples I've seen of `sock.listen(5)` in the python documentation suggest I should set the max backlog number to be `5`. This is causing a problem for my app since I'm expecting some very high volume (many concurrent connections). I set it to 200 and haven't seen any problems on my system, but was wondering ho...
You don't need to adjust the parameter to `listen()` to a larger number than 5. The parameter controls how many non-`accept()`-ed connections are allowed to be outstanding. The `listen()` parameter has no bearing on the number of concurrently connected sockets, only on the number of concurrent connections which have n...
Go to a specific line in Python?
2,444,538
20
2010-03-15T01:11:25Z
2,444,559
56
2010-03-15T01:21:35Z
[ "python" ]
I want to go to line 34 in a .txt file and read it. How would you do that in Python?
Use Python Standard Library's [linecache](http://docs.python.org/library/linecache.html?highlight=linecache#module-linecache) module: ``` line = linecache.getline(thefilename, 33) ``` should do exactly what you want. You don't even need to open the file -- `linecache` does it all for you!
Unpacking tuples/arrays/lists as indices for Numpy Arrays
2,444,923
8
2010-03-15T03:26:57Z
2,444,929
8
2010-03-15T03:30:37Z
[ "python", "numpy" ]
I would love to be able to do ``` >>> A = numpy.array(((1,2),(3,4))) >>> idx = (0,0) >>> A[*idx] ``` and get ``` 1 ``` however this is not valid syntax. Is there a way of doing this without explicitly writing out ``` >>> A[idx[0], idx[1]] ``` ? EDIT: Thanks for the replies. In my program I was indexing with a Nu...
Try ``` A[tuple(idx)] ``` Unless you have a more complex use case that's not as simple as this example, the above should work for all arrays.
Unpacking tuples/arrays/lists as indices for Numpy Arrays
2,444,923
8
2010-03-15T03:26:57Z
2,444,942
9
2010-03-15T03:35:13Z
[ "python", "numpy" ]
I would love to be able to do ``` >>> A = numpy.array(((1,2),(3,4))) >>> idx = (0,0) >>> A[*idx] ``` and get ``` 1 ``` however this is not valid syntax. Is there a way of doing this without explicitly writing out ``` >>> A[idx[0], idx[1]] ``` ? EDIT: Thanks for the replies. In my program I was indexing with a Nu...
It's easier than you think: ``` >>> import numpy >>> A = numpy.array(((1,2),(3,4))) >>> idx = (0,0) >>> A[idx] 1 ```
How does Python differentiate between the different data types?
2,445,193
5
2010-03-15T05:04:45Z
2,445,233
13
2010-03-15T05:15:45Z
[ "python" ]
Sorry if this is quite noobish to you, but I'm just starting out to learn Python after learning C++ & Java, and I am wondering how in the world I could just declare variables like `id = 0` and `name = 'John'` without any `int`'s or `string`'s in front! I figured out that perhaps it's because there are no `'`'s in a num...
The literal objects you mention carry (pointers to;-) their own types with them of course, so when a name's bound to that object the problem of type doesn't arise -- the object always has a type, the name doesn't -- just delegates that to the object it's bound to. There's no "figuring out" in `def increase(first, seco...
How does Python differentiate between the different data types?
2,445,193
5
2010-03-15T05:04:45Z
2,445,239
7
2010-03-15T05:16:34Z
[ "python" ]
Sorry if this is quite noobish to you, but I'm just starting out to learn Python after learning C++ & Java, and I am wondering how in the world I could just declare variables like `id = 0` and `name = 'John'` without any `int`'s or `string`'s in front! I figured out that perhaps it's because there are no `'`'s in a num...
Python is *dynamically typed*: all variables can refer to an object of any type. `id` and `name` can be anything, but the actual objects are of types like `int` and `str`. `0` is a literal that is parsed to make an `int` object, and `'John'` a literal that makes a `str` object. Many object types do not have literals an...
monkey patching time.time() in python
2,446,987
4
2010-03-15T12:22:39Z
2,447,007
14
2010-03-15T12:25:56Z
[ "python", "ruby", "datetime", "time", "monkeypatching" ]
I've an application where, for testing, I need to replace the time.time() call with a specific timestamp, I've done that in the past using ruby (code available here: <http://github.com/zemariamm/Back-to-Future/blob/master/back_to_future.rb> ) However I do not know how to do this using Python. Any hints ? Cheers, Ze ...
You can simply set time.time to point to your new time function, like this: ``` import time def my_time(): return 0.0 old_time = time.time time.time = my_time ```
Programming in Python vs. programming in Java
2,447,118
28
2010-03-15T12:45:02Z
2,447,198
20
2010-03-15T12:56:46Z
[ "java", "python" ]
I've been writing Java for the last couple of years , and now I've started to write in python (in addition). The problem is that when I look at my Python code it looks like someone tried to hammer Java code into a python format , and it comes out crappy because - well , python ain't Java. Any tips on how to escape th...
You might consider immersing yourself in the Python paradigms. The best way is to first know what they are then explore the best practices by reading some literature and reviewing some code samples. I recommend [Learning Python](http://rads.stackoverflow.com/amzn/click/0596158068) by Mark Lutz; great for beginners and ...
does close() imply flush() in Python?
2,447,143
21
2010-03-15T12:48:51Z
2,447,160
20
2010-03-15T12:50:59Z
[ "python", "operating-system", "flush" ]
In Python, and in general - does a `close()` operation on a file object imply a `flush()` operation?
Yes. It uses the underlying `close()` function which does that for you ([source](https://hg.python.org/cpython/file/default/Modules/_io/fileio.c)).
does close() imply flush() in Python?
2,447,143
21
2010-03-15T12:48:51Z
2,447,205
9
2010-03-15T12:57:18Z
[ "python", "operating-system", "flush" ]
In Python, and in general - does a `close()` operation on a file object imply a `flush()` operation?
NB: `close()` and `flush()` won't ensure that the data is actually secure on the disk. It just ensures that the OS has the data == that it isn't buffered inside the process. You can try sync or fsync to get the data written to the disk.
__getattr__ on a module
2,447,353
81
2010-03-15T13:20:08Z
2,447,383
36
2010-03-15T13:24:22Z
[ "python", "module", "python-3.x", "getattr", "attributeerror" ]
How can implement the equivalent of a `__getattr__` on a class, on a module? ## Example When calling a function that does not exist in a module's statically defined attributes, I wish to create an instance of a class in that module, and invoke the method on it with the same name as failed in the attribute lookup on t...
This is a hack, but you can wrap the module with a class: ``` class Wrapper(object): def __init__(self, wrapped): self.wrapped = wrapped def __getattr__(self, name): # Perform custom logic here try: return getattr(self.wrapped, name) except AttributeError: return 'default' # Some sensib...
__getattr__ on a module
2,447,353
81
2010-03-15T13:20:08Z
2,447,391
17
2010-03-15T13:25:57Z
[ "python", "module", "python-3.x", "getattr", "attributeerror" ]
How can implement the equivalent of a `__getattr__` on a class, on a module? ## Example When calling a function that does not exist in a module's statically defined attributes, I wish to create an instance of a class in that module, and invoke the method on it with the same name as failed in the attribute lookup on t...
We don't usually do it that way. What we do is this. ``` class A(object): .... # The implicit global instance a= A() def salutation( *arg, **kw ): a.salutation( *arg, **kw ) ``` Why? So that the implicit global instance is visible. For examples, look at the `random` module, which creates an implicit global in...
__getattr__ on a module
2,447,353
81
2010-03-15T13:20:08Z
2,448,064
11
2010-03-15T15:02:49Z
[ "python", "module", "python-3.x", "getattr", "attributeerror" ]
How can implement the equivalent of a `__getattr__` on a class, on a module? ## Example When calling a function that does not exist in a module's statically defined attributes, I wish to create an instance of a class in that module, and invoke the method on it with the same name as failed in the attribute lookup on t...
Similar to what @HÃ¥vard S proposed, in a case where I needed to implement some magic on a module (like `__getattr__`), I would define a new class that inherits from `types.ModuleType` and put that in `sys.modules` (probably replacing the module where my custom `ModuleType` was defined). See the main [`__init__.py`](h...
__getattr__ on a module
2,447,353
81
2010-03-15T13:20:08Z
7,668,273
80
2011-10-05T21:59:51Z
[ "python", "module", "python-3.x", "getattr", "attributeerror" ]
How can implement the equivalent of a `__getattr__` on a class, on a module? ## Example When calling a function that does not exist in a module's statically defined attributes, I wish to create an instance of a class in that module, and invoke the method on it with the same name as failed in the attribute lookup on t...
There are two basic problems you are running into here: 1. `__xxx__` methods are only looked up on the class 2. `TypeError: can't set attributes of built-in/extension type 'module'` (1) means any solution would have to also keep track of which module was being examined, otherwise *every* module would then have the in...
Converting python objects for rpy2
2,447,454
23
2010-03-15T13:35:44Z
2,447,474
31
2010-03-15T13:38:19Z
[ "python", "rpy2" ]
The following code is supposed to create a heatmap in rpy2 ``` import numpy as np from rpy2.robjects import r data = np.random.random((10,10)) r.heatmap(data) ``` However, it results in the following error ``` Traceback (most recent call last): File "z.py", line 8, in <module> labRow=rowNames, labCol=colNames)...
You need to add ``` import rpy2.robjects.numpy2ri rpy2.robjects.numpy2ri.activate() ``` See <http://rpy.sourceforge.net/rpy2/doc-2.2/html/numpy.html>: > That import alone is sufficient to > switch an automatic conversion of > numpy objects into rpy2 objects. > > Why make this an optional import, > while it could hav...
Converting python objects for rpy2
2,447,454
23
2010-03-15T13:35:44Z
8,261,291
10
2011-11-24T18:29:13Z
[ "python", "rpy2" ]
The following code is supposed to create a heatmap in rpy2 ``` import numpy as np from rpy2.robjects import r data = np.random.random((10,10)) r.heatmap(data) ``` However, it results in the following error ``` Traceback (most recent call last): File "z.py", line 8, in <module> labRow=rowNames, labCol=colNames)...
For rpy2 2.2.4 I had to add: ``` import rpy2.robjects.numpy2ri rpy2.robjects.numpy2ri.activate() ```
duplicate each member in a list - python
2,449,077
10
2010-03-15T17:21:36Z
2,449,087
9
2010-03-15T17:23:23Z
[ "python", "list" ]
Hi I want to write a function that revives a list `[1,5,3,6,...]` and gives `[1,1,5,5,3,3,6,6,...]` any idea how to do it? thanks
``` >>> a = [1, 2, 3] >>> b = [] >>> for i in a: b.extend([i, i]) >>> b [1, 1, 2, 2, 3, 3] ``` or ``` >>> [a[i//2] for i in range(len(a)*2)] [1, 1, 2, 2, 3, 3] ```
duplicate each member in a list - python
2,449,077
10
2010-03-15T17:21:36Z
2,449,125
27
2010-03-15T17:30:05Z
[ "python", "list" ]
Hi I want to write a function that revives a list `[1,5,3,6,...]` and gives `[1,1,5,5,3,3,6,6,...]` any idea how to do it? thanks
``` >>> a = range(10) >>> [val for val in a for _ in (0, 1)] [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9] ``` N.B. `_` is traditionally used as a placeholder variable name where you do not want to do anything with the contents of the variable. In this case it is just used to generate two values for eve...
Any way to assign terminal output to variable with python?
2,449,250
7
2010-03-15T17:49:08Z
2,449,301
14
2010-03-15T17:58:28Z
[ "python", "redirect", "terminal", "ffmpeg" ]
I need to grab the duration of a video file via python as part of a larger script. I know I can use ffmpeg to grab the duration, but I need to be able to save that output as a variable back in python. I thought this would work, but it's giving me a value of 0: ``` cmd = 'ffmpeg -i %s 2>&1 | grep "Duration" | cut -d \'...
`os.system` returns a return value indicating the success or failure of the command. It does not return the output from stdout or stderr. To grab the output from stdout (or stderr), use `subprocess.Popen`. ``` import subprocess proc=subprocess.Popen('echo "to stdout"', shell=True, stdout=subprocess.PIPE, ) output=proc...
Scale 2D coordinates and keep their relative euclidean distances intact?
2,450,035
5
2010-03-15T19:53:27Z
2,450,075
9
2010-03-15T19:59:25Z
[ "python", "math", "coordinates", "scale" ]
I have a set of points like: pointA(3302.34,9392.32), pointB(34322.32,11102.03), etc. I need to scale these so each x- and y-coordinate is in the range (0.0 - 1.0). I tried doing this by first finding the largest x value in the data set (maximum\_x\_value), and the largest y value in the set (minimum\_y\_value). I the...
You need to scale the `x` values and the `y` values by the same amount! I would suggest scaling by the larger of the two ranges (either `x` or `y`). In pseudocode, you'd have something like ``` scale = max(maximum_x_value - minimum_x_value, maximum_y_value - minimum_y_value) ``` Then all the distances bet...
Python Bitstream implementations
2,450,208
7
2010-03-15T20:22:37Z
2,450,735
9
2010-03-15T21:49:28Z
[ "python", "bitstream" ]
I am writing a [huffman](http://en.wikipedia.org/wiki/Huffman_coding) implementation in Python as a learning exercise. I have got to the point of writing out my variable length huffman codes to a buffer (or file). Only to find there does not seem to be a bitstream class implemented by Python! I have had a look at the [...
You're right that there's nothing in the standard library, but have you tried the [bitstring](http://python-bitstring.googlecode.com) module? It's pretty much designed for this kind of application, is stable and [well documented](http://python-bitstring.googlecode.com/svn/tags/bitstring-1.3.0/doc/html/index.html), so I...
Creating a Colormap Legend in Matplotlib
2,451,264
13
2010-03-15T23:47:26Z
2,451,365
21
2010-03-16T00:15:41Z
[ "python", "matplotlib" ]
I am using imshow() in matplotlib like so: ``` import numpy as np import matplotlib.pyplot as plt mat = '''SOME MATRIX''' plt.imshow(mat, origin="lower", cmap='gray', interpolation='nearest') plt.show() ``` How do I add a legend showing the numeric value for the different shades of gray. Sadly, my googling has not un...
There's a builtin [colorbar() function](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.colorbar) in pyplot.
can't figure out serving static images in django dev environment
2,451,352
2
2010-03-16T00:12:30Z
2,451,473
10
2010-03-16T00:51:42Z
[ "python", "django", "image" ]
I've read [the article](http://docs.djangoproject.com/en/dev/howto/static-files/) (and few others on the subject), but still can't figure out how to show an image unless a link to a file existing on a web-service is hard-coded into the html template. I've got in **urls.py**: ``` ... (r'^galleries/(landscapes)...
This is a long post, basically summarizing all the things I learned about Django in order to get static files to work (it took me a while to understand how all the different parts fit together). To serve static images in your development server (and later, your real server), you're going to have to do a few things (no...
What does the caret operator (^) in Python do?
2,451,386
48
2010-03-16T00:21:41Z
2,451,392
12
2010-03-16T00:23:37Z
[ "python", "operators", "caret" ]
I ran across the caret operator in python today and trying it out, I got the following output: ``` >>> 8^3 11 >>> 8^4 12 >>> 8^1 9 >>> 8^0 8 >>> 7^1 6 >>> 7^2 5 >>> 7^7 0 >>> 7^8 15 >>> 9^1 8 >>> 16^1 17 >>> 15^1 14 >>> ``` It seems to be based on 8, so I'm guessing some sort of byte operation? I can't seem to find m...
It's a bit-by-bit exclusive-or. Binary bitwise operators are documented in [chapter 5 of the Python Language Reference](https://docs.python.org/2/reference/expressions.html#binary-bitwise-operations).
What does the caret operator (^) in Python do?
2,451,386
48
2010-03-16T00:21:41Z
2,451,393
77
2010-03-16T00:23:59Z
[ "python", "operators", "caret" ]
I ran across the caret operator in python today and trying it out, I got the following output: ``` >>> 8^3 11 >>> 8^4 12 >>> 8^1 9 >>> 8^0 8 >>> 7^1 6 >>> 7^2 5 >>> 7^7 0 >>> 7^8 15 >>> 9^1 8 >>> 16^1 17 >>> 15^1 14 >>> ``` It seems to be based on 8, so I'm guessing some sort of byte operation? I can't seem to find m...
It's a bitwise [XOR](http://en.wikipedia.org/wiki/Exclusive_or) (exclusive OR). It results to true if **one** (and only one) of the operands (evaluates to) true. To demonstrate: ``` >>> 0^0 0 >>> 1^1 0 >>> 1^0 1 >>> 0^1 1 ``` To explain one of your own examples: ``` >>> 8^3 11 ``` Think about it this way: ``` 10...
What does the caret operator (^) in Python do?
2,451,386
48
2010-03-16T00:21:41Z
2,451,434
31
2010-03-16T00:37:06Z
[ "python", "operators", "caret" ]
I ran across the caret operator in python today and trying it out, I got the following output: ``` >>> 8^3 11 >>> 8^4 12 >>> 8^1 9 >>> 8^0 8 >>> 7^1 6 >>> 7^2 5 >>> 7^7 0 >>> 7^8 15 >>> 9^1 8 >>> 16^1 17 >>> 15^1 14 >>> ``` It seems to be based on 8, so I'm guessing some sort of byte operation? I can't seem to find m...
It invokes the `__xor__()` or `__rxor__()` method of the object as needed, which for integer types does a bitwise exclusive-or.
What does the caret operator (^) in Python do?
2,451,386
48
2010-03-16T00:21:41Z
19,451,108
7
2013-10-18T13:37:07Z
[ "python", "operators", "caret" ]
I ran across the caret operator in python today and trying it out, I got the following output: ``` >>> 8^3 11 >>> 8^4 12 >>> 8^1 9 >>> 8^0 8 >>> 7^1 6 >>> 7^2 5 >>> 7^7 0 >>> 7^8 15 >>> 9^1 8 >>> 16^1 17 >>> 15^1 14 >>> ``` It seems to be based on 8, so I'm guessing some sort of byte operation? I can't seem to find m...
Generally speaking, the symbol `^` is an [infix](https://en.wikipedia.org/wiki/Infix_notation) version of the `__xor__` or `__rxor__` methods. Whatever data types are placed to the right and left of the symbol must implement this function in a compatible way. For integers, it is the common `XOR` operation, but for exam...
How do I handle an UnresolvedImport Eclipse (Python)
2,451,682
9
2010-03-16T02:03:54Z
2,452,084
9
2010-03-16T04:18:34Z
[ "python", "eclipse", "import" ]
When I write `import MySQLdb` in Eclipse using the PyDev plugin, I get an unresolved import. However, the program runs without error. I can add an annotation to get the error to go away, but what is the right way to handle this? How can I help Eclipse know that MySQLdb is there?
It sounds like `MySQLdb` is somewhere on your `sys.path`, but not on your Eclipse project's `PYTHONPATH`; in other words, Eclipse thinks you're going to get an import error at runtime because you haven't fully configured it. Google seems to say that you can alter this setting in `Window->Preferences->Preferences->PyDev...
How do I handle an UnresolvedImport Eclipse (Python)
2,451,682
9
2010-03-16T02:03:54Z
12,980,991
9
2012-10-19T19:17:30Z
[ "python", "eclipse", "import" ]
When I write `import MySQLdb` in Eclipse using the PyDev plugin, I get an unresolved import. However, the program runs without error. I can add an annotation to get the error to go away, but what is the right way to handle this? How can I help Eclipse know that MySQLdb is there?
cdleary above provided the reason two years ago, but this may be easier. Basically, one reinstalls the interpreter. 1. Select Window - > Preferences -> PyDev -> Interpreter - Python 2. Select the python interpreter in the upper pane 3. Click on Remove 4. Click on Auto Config 5. Agree to everything. This works on Fedo...
How is it that json serialization is so much faster than yaml serialization in Python?
2,451,732
35
2010-03-16T02:23:12Z
2,452,043
39
2010-03-16T04:03:56Z
[ "python", "json", "serialization", "yaml" ]
I have code that relies heavily on yaml for cross-language serialization and while working on speeding some stuff up I noticed that yaml was insanely slow compared to other serialization methods (e.g., pickle, json). So what really blows my mind is that json is so much faster that yaml when the output is nearly identi...
In general, it's not the complexity of the output that determines the speed of parsing, but the complexity of the accepted input. The JSON grammar is [very concise](http://www.ietf.org/rfc/rfc4627.txt). The YAML parsers are [comparatively complex](http://yaml.org/spec/1.2/spec.html#id2763452), leading to increased over...
How is it that json serialization is so much faster than yaml serialization in Python?
2,451,732
35
2010-03-16T02:23:12Z
2,452,625
13
2010-03-16T07:07:52Z
[ "python", "json", "serialization", "yaml" ]
I have code that relies heavily on yaml for cross-language serialization and while working on speeding some stuff up I noticed that yaml was insanely slow compared to other serialization methods (e.g., pickle, json). So what really blows my mind is that json is so much faster that yaml when the output is nearly identi...
A cursory look at python-yaml suggests its design is much more complex than cjson's: ``` >>> dir(cjson) ['DecodeError', 'EncodeError', 'Error', '__doc__', '__file__', '__name__', '__package__', '__version__', 'decode', 'encode'] >>> dir(yaml) ['AliasEvent', 'AliasToken', 'AnchorToken', 'BaseDumper', 'BaseLoader', 'B...
How is it that json serialization is so much faster than yaml serialization in Python?
2,451,732
35
2010-03-16T02:23:12Z
2,457,207
12
2010-03-16T18:53:32Z
[ "python", "json", "serialization", "yaml" ]
I have code that relies heavily on yaml for cross-language serialization and while working on speeding some stuff up I noticed that yaml was insanely slow compared to other serialization methods (e.g., pickle, json). So what really blows my mind is that json is so much faster that yaml when the output is nearly identi...
Speaking about efficiency, I used YAML for a time and felt attracted by the simplicity that some name/value assignments take on in this language. However, in the process I tripped so and so often about one of YAML’s finesses, subtle variations in the grammar that allow you to write special cases in a more concise sty...