content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Looking for production quality Hash table/ unordered map implementation to learn?
Looking for good source code either in C or C++ or Python to understand how a hash function is implemented and also how a hash table is implemented using it.
Very good material on how hash fn and hash table implementation works.
Thanks in advance.
A:
Hashtables are central to Python, both as the 'dict' type and for the implementation of classes and namespaces, so the implementation has been refined and optimised over the years. You can see the C source for the dict object here.
Each Python type implements its own hash function - browse the source for the other objects to see their implementations.
A:
When you want to learn, I suggest you look at the Java implementation of java.util.HashMap. It's clear code, well-documented and comparably short. Admitted, it's neither C, nor C++, nor Python, but you probably don't want to read the GNU libc++'s upcoming implementation of a hashtable, which above all consists of the complexity of the C++ standard template library.
To begin with, you should read the definition of the java.util.Map interface. Then you can jump directly into the details of the java.util.HashMap. And everything that's missing you will find in java.util.AbstractMap.
The implementation of a good hash function is independent of the programming language. The basic task of it is to map an arbitrarily large value set onto a small value set (usually some kind of integer type), so that the resulting values are evenly distributed.
A:
There is a problem with your question: there are as many types of hash map as there are uses.
There are many strategies to deal with hash collision and reallocation, depending on the constraints you have. You may find an average solution, of course, that will mostly fit, but if I were you I would look at wikipedia (like Dennis suggested) to have an idea of the various implementations subtleties.
As I said, you can mostly think of the strategies in two ways:
Handling Hash Collision: Bucket, which kind ? Open Addressing ? Double Hash ? ...
Reallocation: freeze the map or amortized linear ?
Also, do you want baked in multi-threading support ? Using atomic operations it's possible to get lock-free multithreaded hashmaps as has been proven in Java by Cliff Click (Google Tech Talk)
As you can see, there is no one size fits them all. I would consider learning the principles first, then going down to the implementation details.
C++ std::unordered_map use a linked-list bucket and freeze the map strategies, no concern is given to proper synchronization as usual with the STL.
Python dict is the base of the language, I don't know of the strategies they elected
| Looking for production quality Hash table/ unordered map implementation to learn? |
Looking for good source code either in C or C++ or Python to understand how a hash function is implemented and also how a hash table is implemented using it.
Very good material on how hash fn and hash table implementation works.
Thanks in advance.
| [
"Hashtables are central to Python, both as the 'dict' type and for the implementation of classes and namespaces, so the implementation has been refined and optimised over the years. You can see the C source for the dict object here.\nEach Python type implements its own hash function - browse the source for the other objects to see their implementations.\n",
"When you want to learn, I suggest you look at the Java implementation of java.util.HashMap. It's clear code, well-documented and comparably short. Admitted, it's neither C, nor C++, nor Python, but you probably don't want to read the GNU libc++'s upcoming implementation of a hashtable, which above all consists of the complexity of the C++ standard template library.\nTo begin with, you should read the definition of the java.util.Map interface. Then you can jump directly into the details of the java.util.HashMap. And everything that's missing you will find in java.util.AbstractMap.\nThe implementation of a good hash function is independent of the programming language. The basic task of it is to map an arbitrarily large value set onto a small value set (usually some kind of integer type), so that the resulting values are evenly distributed.\n",
"There is a problem with your question: there are as many types of hash map as there are uses.\nThere are many strategies to deal with hash collision and reallocation, depending on the constraints you have. You may find an average solution, of course, that will mostly fit, but if I were you I would look at wikipedia (like Dennis suggested) to have an idea of the various implementations subtleties.\nAs I said, you can mostly think of the strategies in two ways:\n\nHandling Hash Collision: Bucket, which kind ? Open Addressing ? Double Hash ? ...\nReallocation: freeze the map or amortized linear ?\n\nAlso, do you want baked in multi-threading support ? Using atomic operations it's possible to get lock-free multithreaded hashmaps as has been proven in Java by Cliff Click (Google Tech Talk)\nAs you can see, there is no one size fits them all. I would consider learning the principles first, then going down to the implementation details.\n\nC++ std::unordered_map use a linked-list bucket and freeze the map strategies, no concern is given to proper synchronization as usual with the STL.\nPython dict is the base of the language, I don't know of the strategies they elected\n\n"
] | [
3,
1,
1
] | [] | [] | [
"c",
"c++",
"hash",
"hashtable",
"python"
] | stackoverflow_0003031358_c_c++_hash_hashtable_python.txt |
Q:
Python module being reloaded for each request with django and mod_wsgi
I have a variable in init of a module which get loaded from the database and takes about 15 seconds.
For django development server everything is working fine but looks like with apache2 and mod_wsgi the module is loaded with every request (taking 15 seconds).
Any idea about this behavior?
Update: I have enabled daemon mode in mod wsgi, looks like its not reloading the modules now! needs more testing and I will update.
A:
You were likely ignoring the fact that in embedded mode of mod_wsgi or with mod_python, the application is multiprocess. Thus requests may go to different processes and you will see a delay the first time a process which hasn't been hit before is encountered. In mod_wsgi daemon mode the default has only a single process. That or as someone else mentioned you had MaxRequestsPerChild set to 1, which is a really bad idea.
A:
I guess, you had a value of 1 for MaxClients / MaxRequestsPerChild and/or ThreadsPerChild in your Apache settings. So Apache had to startup Django for every mod_python call. That's why it took so long. If you have a wsgi-daemon, then a restart takes only place if you "touch" the wsgi script.
| Python module being reloaded for each request with django and mod_wsgi | I have a variable in init of a module which get loaded from the database and takes about 15 seconds.
For django development server everything is working fine but looks like with apache2 and mod_wsgi the module is loaded with every request (taking 15 seconds).
Any idea about this behavior?
Update: I have enabled daemon mode in mod wsgi, looks like its not reloading the modules now! needs more testing and I will update.
| [
"You were likely ignoring the fact that in embedded mode of mod_wsgi or with mod_python, the application is multiprocess. Thus requests may go to different processes and you will see a delay the first time a process which hasn't been hit before is encountered. In mod_wsgi daemon mode the default has only a single process. That or as someone else mentioned you had MaxRequestsPerChild set to 1, which is a really bad idea.\n",
"I guess, you had a value of 1 for MaxClients / MaxRequestsPerChild and/or ThreadsPerChild in your Apache settings. So Apache had to startup Django for every mod_python call. That's why it took so long. If you have a wsgi-daemon, then a restart takes only place if you \"touch\" the wsgi script.\n"
] | [
3,
1
] | [] | [] | [
"apache",
"django",
"mod_wsgi",
"python"
] | stackoverflow_0003025378_apache_django_mod_wsgi_python.txt |
Q:
How do I make a defaultdict safe for unexpecting clients?
Several times (even several in a row) I've been bitten by the defaultdict bug: forgetting that something is actually a defaultdict and treating it like a regular dictionary.
d = defaultdict(list)
...
try:
v = d["key"]
except KeyError:
print "Sorry, no dice!"
For those who have been bitten too, the problem is evident: when d has no key 'key', the v = d["key"] magically creates an empty list and assigns it to both d["key"] and v instead of raising an exception. Which can be quite a pain to track down if d comes from some module whose details one doesn't remember very well.
I'm looking for a way to take the sting out of this bug. For me, the best solution would be to somehow disable a defaultdict's magic before returning it to the client.
A:
You may still convert it to an normal dict.
d = collections.defaultdict(list)
d = dict(d)
A:
use different idiom:
if 'key' not in d:
print "Sorry, no dice!"
A:
You can prevent creation of default values by assigning d.default_factory = None. However, I don't quite like the idea of object suddenly changing behavior. I'd prefer copying values to the new dict unless it imposes severe performance penalty.
A:
That is exactly the behavior you want from a defaultdict and not a bug. If you dont't want it, dont use a defaultdict.
If you keep forgetting what type variables have, then name them appropriately - for example suffix your defaultdict names with "_ddict".
A:
Using rkhayrov's idea of resetting self.default_factory, here is a toggleable subclass of defaultdict:
class ToggleableDefaultdict(collections.defaultdict):
def __init__(self,default_factory):
self._default_factory=default_factory
super(ToggleableDefaultdict,self).__init__(default_factory)
def off(self):
self.default_factory=None
def on(self):
self.default_factory=self._default_factory
For example:
d=ToggleableDefaultdict(list)
d['key'].append(1)
print(d)
# defaultdict(<type 'list'>, {'key': [1]})
d.off()
d['newkey'].append(2)
# KeyError: 'newkey'
d.on()
d['newkey'].append(2)
# defaultdict(<type 'list'>, {'newkey': [2], 'key': [1]})
| How do I make a defaultdict safe for unexpecting clients? | Several times (even several in a row) I've been bitten by the defaultdict bug: forgetting that something is actually a defaultdict and treating it like a regular dictionary.
d = defaultdict(list)
...
try:
v = d["key"]
except KeyError:
print "Sorry, no dice!"
For those who have been bitten too, the problem is evident: when d has no key 'key', the v = d["key"] magically creates an empty list and assigns it to both d["key"] and v instead of raising an exception. Which can be quite a pain to track down if d comes from some module whose details one doesn't remember very well.
I'm looking for a way to take the sting out of this bug. For me, the best solution would be to somehow disable a defaultdict's magic before returning it to the client.
| [
"You may still convert it to an normal dict.\nd = collections.defaultdict(list)\nd = dict(d)\n\n",
"use different idiom:\nif 'key' not in d:\n print \"Sorry, no dice!\"\n\n",
"You can prevent creation of default values by assigning d.default_factory = None. However, I don't quite like the idea of object suddenly changing behavior. I'd prefer copying values to the new dict unless it imposes severe performance penalty.\n",
"That is exactly the behavior you want from a defaultdict and not a bug. If you dont't want it, dont use a defaultdict.\nIf you keep forgetting what type variables have, then name them appropriately - for example suffix your defaultdict names with \"_ddict\".\n",
"Using rkhayrov's idea of resetting self.default_factory, here is a toggleable subclass of defaultdict:\nclass ToggleableDefaultdict(collections.defaultdict):\n def __init__(self,default_factory):\n self._default_factory=default_factory\n super(ToggleableDefaultdict,self).__init__(default_factory)\n def off(self):\n self.default_factory=None\n def on(self):\n self.default_factory=self._default_factory\n\nFor example:\nd=ToggleableDefaultdict(list)\nd['key'].append(1)\nprint(d)\n# defaultdict(<type 'list'>, {'key': [1]})\n\nd.off()\nd['newkey'].append(2)\n# KeyError: 'newkey'\n\nd.on()\nd['newkey'].append(2)\n# defaultdict(<type 'list'>, {'newkey': [2], 'key': [1]})\n\n"
] | [
14,
7,
5,
2,
1
] | [] | [] | [
"default_value",
"python"
] | stackoverflow_0003031817_default_value_python.txt |
Q:
Best way in Python to determine all possible intersections in a matrix?
So if I have a matrix (list of lists) where each column represents a unique word, each row represents a distinct document, and every entry is a 1 or 0, indicating whether or not the word for a given column exists in the document for a given row.
What I'd like to know is how to determine all the possible combinations of words and documents where more than one word is in common with more than one document. The result might look something like:
[ [[Docid_3, Docid_5], ['word1', 'word17', 'word23']],
[[Docid_3, Docid_9, Docid_334], ['word2', 'word7', 'word23', 'word68', 'word982']],
...
and so on for each possible combination. Would love a solution that provides the complete set of combinations and one that yields only the combinations that are not a subset of another, so from the example, not [[Docid_3, Docid_5], ['word1', 'word17']] since it's a complete subset of the first example.
I feel like there is an elegant solution that just isn't coming to mind and the beer isn't helping.
Thanks.
A:
Normalize the text. You only want strings made of string.lowercase. Split/strip on everything else.
Make sets out of this.
Use something like this to get all possible groupings of all sizes:
def get_all_lengths_combinations_of(elements):
for no_of_items in range(2, len(elements)+1):
for items in itertools.combinations(elements, no_of_items)
yield items
I'm sure the real itertools wizards will come up with something better, possibly involving izip().
Remember you should be able to use the set.intersection() method like this:
set.intersection(*list_of_sets_to_intersect)
A:
First, build a mapping from document ID to set of words -- your matrix of 0 and 1 is quite an unwieldy structure to process directly. If I read you correctly, the "column headings" (words) are the first list in the matrix (minus presumably the first item) and the "row headings" (docids) are the first items of each row (minus presumably the first row). Then (assuming Python 2.6 or better):
def makemap(matrix):
im = iter(matrix)
words = next(im)[1:]
themap = {}
for row in im:
mapent = set()
docid = row[0]
for w, bit in zip(words, row[1:]):
try:
if bit: mapent.add(w)
except:
print 'w is %r' % (w,)
raise
themap[docid] = mapent
return themap
Now you need to check all feasible subsets of documents -- the total number of subsets is huge so you really want to prune that search tree as much as you can, and brute-force generation of all subsets (e.g. by looping on itertools.combinations for various lengths) will not perform any pruning of course.
I would start with all 2-combinations (all pairs of docids -- itertools.combinations is fine for this of course) and make the first batch (those pairs which have 2+ words in commons) of "feasible 2-length subsets". That can go in another mapping with tuples or frozensets of docids as the keys.
Then, to make the feasible (N+1)-length subsets, I would only try to extend existing feasible N-length subsets by one more docid each (checking the total intersection is still 2+ long of course). This at least does some pruning rather than blindly trying all the 2**N subsets (or even just the 2**N - N - 1 subsets of length at least two;-).
It might perhaps be possible to do even better by recording all docids that proved unable to extend a certain N-length subset -- no point in trying those against any of the (N+1)-length subsets derived from it. This is worth trying as a second level of pruning/optimization.
There may be further tweaks yet you might do for further pruning but offhand none immediately comes to mind, so that's where I'd start from. (For readability, I'm not bothering below with using microoptimizations such as iteritems in lieu of items, frozensets in lieu of tuples, etc -- they're probably marginal given those sequences are all O(N) vs the exponential size of computed structures, although of course worth trying in the tuning/optimizing phase).
def allfeasiblesubsets(matrix):
mapping = makemap(matrix)
docids = sorted(mapping.keys())
feasible_len2 = {}
dont_bother = dict((d, set([d])) for d in docids)
for d1, d2 in itertools.combinations(docids, 2):
commonw = mapping[d1].intersection(mapping[d2])
if len(commonw) >= 2:
feasible_len2[d1, d2] = commonw
else:
dont_bother[d1].add(d2)
dont_bother[d2].add(d1)
all_feasible = [feasible_len2]
while all_feasible[-1]:
feasible_Np1 = {}
for ds, ws in all_feasible[-1].items():
md = max(ds)
for d, w in mapping.items():
if d <= md or any(d in dont_bother[d1] for d1 in ds):
continue
commonw = w.intersection(ws)
if len(commonw) >= 2:
feasible_Np1[ds+(d,)] = commonw
all_feasible.append(feasible_Np1)
return all_feasible[:-1]
You'll notice I've applied only a mild form of my suggested "further pruning" -- dont_bother only records "incompatibilities" (<2 words in common) between one docid and others -- this may help if there are several pairs of such "incompatible docids", and is simple and reasonably unobtrusive, but is not as powerful in pruning as the harder "full" alternative. I'm also trying to keep all keys in the feasible* dicts as sorted tuples of docids (as the itertools.combinations originally provides for the pairs) to avoid duplications and therefore redundant work.
Here's the small example I've tried (in the same file as these functions after, of course, the import for itertools and collections):
mat = [ ['doc']+'tanto va la gatta al lardo che ci lascia lo zampino'.split(),
['uno', 0, 0, 0, 1, 0, 1, 0, 0, 0, 1],
['due', 1, 0, 0, 0, 0, 1, 0, 1, 0, 1],
['tre', 1, 0, 0, 0, 0, 0, 0, 1, 0, 1],
['qua', 0, 0, 0, 1, 0, 1, 0, 1, 0, 1]]
mm = makemap(mat)
print mm
afs = allfeasiblesubsets(mat)
print afs
The results, which appear OK, are:
{'qua': set(['gatta', 'lo', 'ci', 'lardo']), 'tre': set(['lo', 'ci', 'tanto']), 'due': set(['lo', 'ci', 'lardo', 'tanto']), 'uno': set(['gatta', 'lo', 'lardo'])}
[{('due', 'tre'): set(['lo', 'ci', 'tanto']), ('due', 'uno'): set(['lo', 'lardo']), ('qua', 'uno'): set(['gatta', 'lo', 'lardo']), ('due', 'qua'): set(['lo', 'ci', 'lardo']), ('qua', 'tre'): set(['lo', 'ci'])}, {('due', 'qua', 'tre'): set(['lo', 'ci']), ('due', 'qua', 'uno'): set(['lo', 'lardo'])}]
but of course there might still be bugs lurking since I haven't tested it thoroughly. BTW, I hope it's clear that the result as supplied here (a list of dicts for various increasing lengths, each dict having the ordered tuple forms of the docids-sets as keys and the sets of their common words as values) can easily be post-processed into any other form you might prefer, such as nested lists.
(Not that it matters, but the text I'm using in the example is an old Italian proverb;-).
A:
Take a look at
SO what-tried-and-true-algorithms-for-suggesting-related-articles-are-out-there
For real problem sizes, say > 100 docs, 10000 words,
get the nice bitarray module
(which says, by the way,
"the same algorithm in Python ... is about 20 times slower than in C").
On "only the combinations that are not a subset of another":
define a hit22 as a 2x2 submatrix with 11 11,
a hit23 as a 2x3 submatrix with 111 111 (2 docs, 3 words in common), and so on.
A given hit22 may be in many hit2n s — 2 docs, n words,
and also in many hitn2 s — n docs, 2 words. Looks fun.
Added Monday 14Jun: little functions using bitarray.
(Intro / python modules for real doc classification ? Dunno.)
""" docs-words with bitarray, randombits """
# google "document classification" (tutorial | python) ...
# https://stackoverflow.com/questions/1254627/what-tried-and-true-algorithms-for-suggesting-related-articles-are-out-there
from __future__ import division
import random
import sys
from bitarray import bitarray # http://pypi.python.org/pypi/bitarray
__date__ = "14jun 2010 denis"
ndoc = 100
nbits = 1000
exec "\n".join( sys.argv[1:] ) # run this.py ndoc= ...
random.seed(1)
me = __file__.split('/') [-1]
print "%s ndoc=%d nbits=%d" % (me, ndoc, nbits)
# bitarray stuff --
def bitslist( bits ):
""" 011001 -> [1,2,5] """
return [ j for j in range(len(bits)) if bits[j] ]
hex_01 = {
"0": "0000", "1": "0001", "2": "0010", "3": "0011",
"4": "0100", "5": "0101", "6": "0110", "7": "0111",
"8": "1000", "9": "1001", "a": "1010", "b": "1011",
"c": "1100", "d": "1101", "e": "1110", "f": "1111",
}
def to01( x, len_ ):
x = "%x" % x
s = "".join( hex_01[c] for c in x )
return (len_ - len(s)) * "0" + s
def randombits( nbits ):
""" -> bitarray 1/16 1, 15/16 0 """
hibit = 1 << (nbits - 1)
r = (random.randint( 0, hibit - 1 )
& random.randint( 0, hibit - 1 )
& random.randint( 0, hibit - 1 )
& random.randint( 0, hibit - 1 )) # prob 1/16
return bitarray( to01( r, nbits ))
#...............................................................................
doc = [ randombits(nbits) for j in range(ndoc) ] # ndoc x nbits
def mostsimilarpair():
""" -> (sim, j, k) most similar pair of docs """
mostsim = (-1,-1,-1)
for j in range(ndoc):
for k in range(j+1, ndoc):
# allpairs[j,k] -> scipy.cluster.hier ?
sim = (doc[j] & doc[k]).count() # nr bits (words) in common, crude
mostsim = max( mostsim, (sim,j,k) )
return mostsim
sim, jdoc, kdoc = mostsimilarpair()
print "The 2 most similar docs:" ,
print "doc %d has %d words," % ( jdoc, doc[jdoc].count() ) ,
print "doc %d has %d," % ( kdoc, doc[kdoc].count() )
print "%d words in common: %s" % ( sim, bitslist( doc[jdoc] & doc[kdoc] ))
print ""
#...............................................................................
def docslike( jdoc, thresh ):
""" -> (doc index, sim >= thresh) ... """
for j in range(ndoc):
if j == jdoc: continue
sim = (doc[j] & doc[jdoc]).count()
if sim >= thresh:
yield (j, sim)
thresh = sim // 2
print "Docs like %d, with >= %d words in common:" % (jdoc, thresh)
for j, sim in docslike( jdoc, thresh ):
print "%3d %s" % ( j, bitslist( doc[j] & doc[jdoc] ))
"""
The 2 most similar docs: doc 72 has 66 words, doc 84 has 60,
12 words in common: [11, 51, 119, 154, 162, 438, 592, 696, 800, 858, 860, 872]
Docs like 72, with >= 6 words in common:
2 [3, 171, 258, 309, 592, 962]
...
"""
A:
How many documents? How many unique words? How much RAM do you have?
What do you want to produce in the following scenario: document A has words 1, 2, 3; B has 1, 2; C has 2, 3
| Best way in Python to determine all possible intersections in a matrix? | So if I have a matrix (list of lists) where each column represents a unique word, each row represents a distinct document, and every entry is a 1 or 0, indicating whether or not the word for a given column exists in the document for a given row.
What I'd like to know is how to determine all the possible combinations of words and documents where more than one word is in common with more than one document. The result might look something like:
[ [[Docid_3, Docid_5], ['word1', 'word17', 'word23']],
[[Docid_3, Docid_9, Docid_334], ['word2', 'word7', 'word23', 'word68', 'word982']],
...
and so on for each possible combination. Would love a solution that provides the complete set of combinations and one that yields only the combinations that are not a subset of another, so from the example, not [[Docid_3, Docid_5], ['word1', 'word17']] since it's a complete subset of the first example.
I feel like there is an elegant solution that just isn't coming to mind and the beer isn't helping.
Thanks.
| [
"\nNormalize the text. You only want strings made of string.lowercase. Split/strip on everything else.\nMake sets out of this.\nUse something like this to get all possible groupings of all sizes:\ndef get_all_lengths_combinations_of(elements):\n for no_of_items in range(2, len(elements)+1):\n for items in itertools.combinations(elements, no_of_items)\n yield items \n\nI'm sure the real itertools wizards will come up with something better, possibly involving izip().\nRemember you should be able to use the set.intersection() method like this:\nset.intersection(*list_of_sets_to_intersect)\n\n\n",
"First, build a mapping from document ID to set of words -- your matrix of 0 and 1 is quite an unwieldy structure to process directly. If I read you correctly, the \"column headings\" (words) are the first list in the matrix (minus presumably the first item) and the \"row headings\" (docids) are the first items of each row (minus presumably the first row). Then (assuming Python 2.6 or better):\ndef makemap(matrix):\n im = iter(matrix)\n words = next(im)[1:]\n themap = {}\n for row in im:\n mapent = set()\n docid = row[0]\n for w, bit in zip(words, row[1:]):\n try:\n if bit: mapent.add(w)\n except:\n print 'w is %r' % (w,)\n raise\n themap[docid] = mapent\n return themap\n\nNow you need to check all feasible subsets of documents -- the total number of subsets is huge so you really want to prune that search tree as much as you can, and brute-force generation of all subsets (e.g. by looping on itertools.combinations for various lengths) will not perform any pruning of course.\nI would start with all 2-combinations (all pairs of docids -- itertools.combinations is fine for this of course) and make the first batch (those pairs which have 2+ words in commons) of \"feasible 2-length subsets\". That can go in another mapping with tuples or frozensets of docids as the keys.\nThen, to make the feasible (N+1)-length subsets, I would only try to extend existing feasible N-length subsets by one more docid each (checking the total intersection is still 2+ long of course). This at least does some pruning rather than blindly trying all the 2**N subsets (or even just the 2**N - N - 1 subsets of length at least two;-).\nIt might perhaps be possible to do even better by recording all docids that proved unable to extend a certain N-length subset -- no point in trying those against any of the (N+1)-length subsets derived from it. This is worth trying as a second level of pruning/optimization.\nThere may be further tweaks yet you might do for further pruning but offhand none immediately comes to mind, so that's where I'd start from. (For readability, I'm not bothering below with using microoptimizations such as iteritems in lieu of items, frozensets in lieu of tuples, etc -- they're probably marginal given those sequences are all O(N) vs the exponential size of computed structures, although of course worth trying in the tuning/optimizing phase).\ndef allfeasiblesubsets(matrix):\n mapping = makemap(matrix)\n docids = sorted(mapping.keys())\n feasible_len2 = {}\n dont_bother = dict((d, set([d])) for d in docids)\n for d1, d2 in itertools.combinations(docids, 2):\n commonw = mapping[d1].intersection(mapping[d2])\n if len(commonw) >= 2:\n feasible_len2[d1, d2] = commonw\n else:\n dont_bother[d1].add(d2)\n dont_bother[d2].add(d1)\n all_feasible = [feasible_len2]\n while all_feasible[-1]:\n feasible_Np1 = {}\n for ds, ws in all_feasible[-1].items(): \n md = max(ds) \n for d, w in mapping.items():\n if d <= md or any(d in dont_bother[d1] for d1 in ds):\n continue\n commonw = w.intersection(ws)\n if len(commonw) >= 2:\n feasible_Np1[ds+(d,)] = commonw\n all_feasible.append(feasible_Np1)\n return all_feasible[:-1]\n\nYou'll notice I've applied only a mild form of my suggested \"further pruning\" -- dont_bother only records \"incompatibilities\" (<2 words in common) between one docid and others -- this may help if there are several pairs of such \"incompatible docids\", and is simple and reasonably unobtrusive, but is not as powerful in pruning as the harder \"full\" alternative. I'm also trying to keep all keys in the feasible* dicts as sorted tuples of docids (as the itertools.combinations originally provides for the pairs) to avoid duplications and therefore redundant work.\nHere's the small example I've tried (in the same file as these functions after, of course, the import for itertools and collections):\nmat = [ ['doc']+'tanto va la gatta al lardo che ci lascia lo zampino'.split(),\n ['uno', 0, 0, 0, 1, 0, 1, 0, 0, 0, 1],\n ['due', 1, 0, 0, 0, 0, 1, 0, 1, 0, 1],\n ['tre', 1, 0, 0, 0, 0, 0, 0, 1, 0, 1],\n ['qua', 0, 0, 0, 1, 0, 1, 0, 1, 0, 1]]\n\nmm = makemap(mat)\nprint mm\nafs = allfeasiblesubsets(mat)\nprint afs\n\nThe results, which appear OK, are:\n{'qua': set(['gatta', 'lo', 'ci', 'lardo']), 'tre': set(['lo', 'ci', 'tanto']), 'due': set(['lo', 'ci', 'lardo', 'tanto']), 'uno': set(['gatta', 'lo', 'lardo'])}\n[{('due', 'tre'): set(['lo', 'ci', 'tanto']), ('due', 'uno'): set(['lo', 'lardo']), ('qua', 'uno'): set(['gatta', 'lo', 'lardo']), ('due', 'qua'): set(['lo', 'ci', 'lardo']), ('qua', 'tre'): set(['lo', 'ci'])}, {('due', 'qua', 'tre'): set(['lo', 'ci']), ('due', 'qua', 'uno'): set(['lo', 'lardo'])}]\n\nbut of course there might still be bugs lurking since I haven't tested it thoroughly. BTW, I hope it's clear that the result as supplied here (a list of dicts for various increasing lengths, each dict having the ordered tuple forms of the docids-sets as keys and the sets of their common words as values) can easily be post-processed into any other form you might prefer, such as nested lists.\n(Not that it matters, but the text I'm using in the example is an old Italian proverb;-).\n",
"Take a look at \nSO what-tried-and-true-algorithms-for-suggesting-related-articles-are-out-there \nFor real problem sizes, say > 100 docs, 10000 words,\nget the nice bitarray module\n(which says, by the way,\n\"the same algorithm in Python ... is about 20 times slower than in C\"). \nOn \"only the combinations that are not a subset of another\":\ndefine a hit22 as a 2x2 submatrix with 11 11,\na hit23 as a 2x3 submatrix with 111 111 (2 docs, 3 words in common), and so on.\nA given hit22 may be in many hit2n s — 2 docs, n words,\nand also in many hitn2 s — n docs, 2 words. Looks fun.\nAdded Monday 14Jun: little functions using bitarray.\n(Intro / python modules for real doc classification ? Dunno.)\n\"\"\" docs-words with bitarray, randombits \"\"\"\n# google \"document classification\" (tutorial | python) ...\n# https://stackoverflow.com/questions/1254627/what-tried-and-true-algorithms-for-suggesting-related-articles-are-out-there\n\nfrom __future__ import division\nimport random\nimport sys\nfrom bitarray import bitarray # http://pypi.python.org/pypi/bitarray\n\n__date__ = \"14jun 2010 denis\"\n\nndoc = 100\nnbits = 1000\n\nexec \"\\n\".join( sys.argv[1:] ) # run this.py ndoc= ...\nrandom.seed(1)\nme = __file__.split('/') [-1]\nprint \"%s ndoc=%d nbits=%d\" % (me, ndoc, nbits)\n\n # bitarray stuff --\n\ndef bitslist( bits ):\n \"\"\" 011001 -> [1,2,5] \"\"\"\n return [ j for j in range(len(bits)) if bits[j] ]\n\nhex_01 = {\n \"0\": \"0000\", \"1\": \"0001\", \"2\": \"0010\", \"3\": \"0011\",\n \"4\": \"0100\", \"5\": \"0101\", \"6\": \"0110\", \"7\": \"0111\",\n \"8\": \"1000\", \"9\": \"1001\", \"a\": \"1010\", \"b\": \"1011\",\n \"c\": \"1100\", \"d\": \"1101\", \"e\": \"1110\", \"f\": \"1111\",\n}\n\ndef to01( x, len_ ):\n x = \"%x\" % x\n s = \"\".join( hex_01[c] for c in x )\n return (len_ - len(s)) * \"0\" + s\n\ndef randombits( nbits ):\n \"\"\" -> bitarray 1/16 1, 15/16 0 \"\"\"\n hibit = 1 << (nbits - 1)\n r = (random.randint( 0, hibit - 1 )\n & random.randint( 0, hibit - 1 )\n & random.randint( 0, hibit - 1 )\n & random.randint( 0, hibit - 1 )) # prob 1/16\n return bitarray( to01( r, nbits ))\n\n#...............................................................................\ndoc = [ randombits(nbits) for j in range(ndoc) ] # ndoc x nbits\n\ndef mostsimilarpair():\n \"\"\" -> (sim, j, k) most similar pair of docs \"\"\"\n mostsim = (-1,-1,-1)\n for j in range(ndoc):\n for k in range(j+1, ndoc):\n # allpairs[j,k] -> scipy.cluster.hier ?\n sim = (doc[j] & doc[k]).count() # nr bits (words) in common, crude\n mostsim = max( mostsim, (sim,j,k) )\n return mostsim\n\nsim, jdoc, kdoc = mostsimilarpair()\nprint \"The 2 most similar docs:\" ,\nprint \"doc %d has %d words,\" % ( jdoc, doc[jdoc].count() ) ,\nprint \"doc %d has %d,\" % ( kdoc, doc[kdoc].count() )\nprint \"%d words in common: %s\" % ( sim, bitslist( doc[jdoc] & doc[kdoc] ))\nprint \"\"\n\n#...............................................................................\ndef docslike( jdoc, thresh ):\n \"\"\" -> (doc index, sim >= thresh) ... \"\"\"\n for j in range(ndoc):\n if j == jdoc: continue\n sim = (doc[j] & doc[jdoc]).count()\n if sim >= thresh:\n yield (j, sim)\n\nthresh = sim // 2\nprint \"Docs like %d, with >= %d words in common:\" % (jdoc, thresh)\nfor j, sim in docslike( jdoc, thresh ):\n print \"%3d %s\" % ( j, bitslist( doc[j] & doc[jdoc] ))\n\n\"\"\"\nThe 2 most similar docs: doc 72 has 66 words, doc 84 has 60,\n12 words in common: [11, 51, 119, 154, 162, 438, 592, 696, 800, 858, 860, 872]\n\nDocs like 72, with >= 6 words in common:\n 2 [3, 171, 258, 309, 592, 962]\n...\n\"\"\"\n\n",
"How many documents? How many unique words? How much RAM do you have?\nWhat do you want to produce in the following scenario: document A has words 1, 2, 3; B has 1, 2; C has 2, 3\n"
] | [
3,
3,
1,
0
] | [] | [] | [
"matrix",
"numpy",
"python",
"vector"
] | stackoverflow_0003027925_matrix_numpy_python_vector.txt |
Q:
Detecting and interacting with long running process
I want a script to start and interact with a long running process. The process is started first time the script is executed, after that the script can be executed repeatedly, but will detect that the process is already running. The script should be able to interact with the process. I would like this to work on Unix and Windows.
I am unsure how I do this. Specifically how do I detect if the process is already running and open a pipe to it? Should I use sockets (e.g. registering the server process on a known port and then check if it responds) or should I use "named pipes"? Or is there some easier way?
A:
Sockets are easier to make portable between Windows and any other OS, so that's what I would recommend it over named pipes (that's why e.g. IDLE uses sockets rather than named pipes -- the latter require platform-dependent code on Windows, e.g. via ctypes [[or third-party win32all or cython &c]], while sockets just work).
A:
Well here is an idea...
place a status somewhere else, that
can be polled/queried.
when the process starts, post the
'running' status.
have the script check here to see if the process is running.
I would also use a seperate place to
post control values. e.g. set a
value to the 'control set' and have
the process look for those values
whenever it gets to decision points
in its runtime behavior.
| Detecting and interacting with long running process | I want a script to start and interact with a long running process. The process is started first time the script is executed, after that the script can be executed repeatedly, but will detect that the process is already running. The script should be able to interact with the process. I would like this to work on Unix and Windows.
I am unsure how I do this. Specifically how do I detect if the process is already running and open a pipe to it? Should I use sockets (e.g. registering the server process on a known port and then check if it responds) or should I use "named pipes"? Or is there some easier way?
| [
"Sockets are easier to make portable between Windows and any other OS, so that's what I would recommend it over named pipes (that's why e.g. IDLE uses sockets rather than named pipes -- the latter require platform-dependent code on Windows, e.g. via ctypes [[or third-party win32all or cython &c]], while sockets just work).\n",
"Well here is an idea...\n\nplace a status somewhere else, that\ncan be polled/queried. \nwhen the process starts, post the\n'running' status.\nhave the script check here to see if the process is running.\nI would also use a seperate place to\npost control values. e.g. set a\nvalue to the 'control set' and have\nthe process look for those values\nwhenever it gets to decision points\nin its runtime behavior.\n\n"
] | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003032378_python.txt |
Q:
Strip text except from the contents of a tag
The opposite may be achieved using pyparsing as follows:
from pyparsing import Suppress, replaceWith, makeHTMLTags, SkipTo
#...
removeText = replaceWith("")
scriptOpen, scriptClose = makeHTMLTags("script")
scriptBody = scriptOpen + SkipTo(scriptClose) + scriptClose
scriptBody.setParseAction(removeText)
data = (scriptBody).transformString(data)
How could I keep the contents of the tag "table"?
UPDATE 0:
I tried:
# keep only the tables
tableOpen, tableClose = makeHTMLTags("table")
tableBody = tableOpen + SkipTo(tableClose) + tableClose
f = replaceWith(tableBody)
tableBody.setParseAction(f)
data = (tableBody).transformString(data)
print data
and I get something like this...
garbages
<input type="hidden" name="cassstx" value="en_US:frontend"></form></td></tr></table></span></td></tr></table>
{<"table"> SkipTo:(</"table">) </"table">}
<div id="asbnav" style="padding-bottom: 10px;">{<"table"> SkipTo:(</"table">) </"table">}
</div>
even more garbages
UPDATE 2:
Thanks Martelli. What I need is:
from pyparsing import Suppress, replaceWith, makeHTMLTags, SkipTo
#...
data = 'before<script>ciao<table>buh</table>bye</script>after'
tableOpen, tableClose = makeHTMLTags("table")
tableBody = tableOpen + SkipTo(tableClose) + tableClose
thetable = (tableBody).searchString(data)[0][2]
print thetable
A:
You could first extract the table (similarly to the way you're now extracting the script but without the removal of course;-), obtaining a thetable string; then, you extract the script, replaceWith(thetable) instead of replaceWith(''). Alternatively, you could prepare a more elaborate parse action, but the simple two-phase approach looks more straightforward to me. E.g. (to preserve specifically the contents of the table, not the table tags):
from pyparsing import Suppress, replaceWith, makeHTMLTags, SkipTo
#...
data = 'before<script>ciao<table>buh</table>bye</script>after'
tableOpen, tableClose = makeHTMLTags("table")
tableBody = tableOpen + SkipTo(tableClose) + tableClose
thetable = (tableBody).searchString(data)[0][2]
removeText = replaceWith(thetable)
scriptOpen, scriptClose = makeHTMLTags("script")
scriptBody = scriptOpen + SkipTo(scriptClose) + scriptClose
scriptBody.setParseAction(removeText)
data = (scriptBody).transformString(data)
print data
This prints beforebuhafter (what's outside the script tag, with the contents of the table tag sandwiched inside), hopefully "as desired".
| Strip text except from the contents of a tag | The opposite may be achieved using pyparsing as follows:
from pyparsing import Suppress, replaceWith, makeHTMLTags, SkipTo
#...
removeText = replaceWith("")
scriptOpen, scriptClose = makeHTMLTags("script")
scriptBody = scriptOpen + SkipTo(scriptClose) + scriptClose
scriptBody.setParseAction(removeText)
data = (scriptBody).transformString(data)
How could I keep the contents of the tag "table"?
UPDATE 0:
I tried:
# keep only the tables
tableOpen, tableClose = makeHTMLTags("table")
tableBody = tableOpen + SkipTo(tableClose) + tableClose
f = replaceWith(tableBody)
tableBody.setParseAction(f)
data = (tableBody).transformString(data)
print data
and I get something like this...
garbages
<input type="hidden" name="cassstx" value="en_US:frontend"></form></td></tr></table></span></td></tr></table>
{<"table"> SkipTo:(</"table">) </"table">}
<div id="asbnav" style="padding-bottom: 10px;">{<"table"> SkipTo:(</"table">) </"table">}
</div>
even more garbages
UPDATE 2:
Thanks Martelli. What I need is:
from pyparsing import Suppress, replaceWith, makeHTMLTags, SkipTo
#...
data = 'before<script>ciao<table>buh</table>bye</script>after'
tableOpen, tableClose = makeHTMLTags("table")
tableBody = tableOpen + SkipTo(tableClose) + tableClose
thetable = (tableBody).searchString(data)[0][2]
print thetable
| [
"You could first extract the table (similarly to the way you're now extracting the script but without the removal of course;-), obtaining a thetable string; then, you extract the script, replaceWith(thetable) instead of replaceWith(''). Alternatively, you could prepare a more elaborate parse action, but the simple two-phase approach looks more straightforward to me. E.g. (to preserve specifically the contents of the table, not the table tags):\nfrom pyparsing import Suppress, replaceWith, makeHTMLTags, SkipTo\n#...\ndata = 'before<script>ciao<table>buh</table>bye</script>after'\n\ntableOpen, tableClose = makeHTMLTags(\"table\")\ntableBody = tableOpen + SkipTo(tableClose) + tableClose\nthetable = (tableBody).searchString(data)[0][2]\n\nremoveText = replaceWith(thetable)\nscriptOpen, scriptClose = makeHTMLTags(\"script\")\nscriptBody = scriptOpen + SkipTo(scriptClose) + scriptClose\nscriptBody.setParseAction(removeText)\ndata = (scriptBody).transformString(data)\n\nprint data\n\nThis prints beforebuhafter (what's outside the script tag, with the contents of the table tag sandwiched inside), hopefully \"as desired\".\n"
] | [
1
] | [] | [] | [
"parsing",
"pyparsing",
"python"
] | stackoverflow_0003032532_parsing_pyparsing_python.txt |
Q:
How to access non-first matches with xpath in Selenium RC?
I have 20 labels in my page:
In [85]: sel.get_xpath_count("//label")
Out[85]: u'20'
And I can get the first one be default:
In [86]: sel.get_text("xpath=//label")
Out[86]: u'First label:'
But, unlike the xpath docs I've found, I'm getting an error trying to subscript the xpath to get to the second label's text:
In [87]: sel.get_text("xpath=//label[2]")
ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (216, 0))
ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (1186, 0))
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
/Users/me/<ipython console> in <module>()
/Users/me/selenium.pyc in get_text(self, locator)
1187 'locator' is an element locator
1188 """
-> 1189 return self.get_string("getText", [locator,])
1190
1191
/Users/me/selenium.pyc in get_string(self, verb, args)
217
218 def get_string(self, verb, args):
--> 219 result = self.do_command(verb, args)
220 return result[3:]
221
/Users/me/selenium.pyc in do_command(self, verb, args)
213 #print "Selenium Result: " + repr(data) + "\n\n"
214 if (not data.startswith('OK')):
--> 215 raise Exception, data
216 return data
217
Exception: ERROR: Element xpath=//label[2] not found
What gives?
A:
Use:
(//label)[2]
The XPath expression you are currently using:
//label[2]
means:
Select every label element in the document that is the second label child of its parent. Chances are that every label in the document is just the first and only label child of its parent. In such a case the above expression selects nothing.
| How to access non-first matches with xpath in Selenium RC? | I have 20 labels in my page:
In [85]: sel.get_xpath_count("//label")
Out[85]: u'20'
And I can get the first one be default:
In [86]: sel.get_text("xpath=//label")
Out[86]: u'First label:'
But, unlike the xpath docs I've found, I'm getting an error trying to subscript the xpath to get to the second label's text:
In [87]: sel.get_text("xpath=//label[2]")
ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (216, 0))
ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (1186, 0))
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
/Users/me/<ipython console> in <module>()
/Users/me/selenium.pyc in get_text(self, locator)
1187 'locator' is an element locator
1188 """
-> 1189 return self.get_string("getText", [locator,])
1190
1191
/Users/me/selenium.pyc in get_string(self, verb, args)
217
218 def get_string(self, verb, args):
--> 219 result = self.do_command(verb, args)
220 return result[3:]
221
/Users/me/selenium.pyc in do_command(self, verb, args)
213 #print "Selenium Result: " + repr(data) + "\n\n"
214 if (not data.startswith('OK')):
--> 215 raise Exception, data
216 return data
217
Exception: ERROR: Element xpath=//label[2] not found
What gives?
| [
"Use:\n(//label)[2]\nThe XPath expression you are currently using:\n\n//label[2]\n\nmeans:\nSelect every label element in the document that is the second label child of its parent. Chances are that every label in the document is just the first and only label child of its parent. In such a case the above expression selects nothing.\n"
] | [
2
] | [] | [] | [
"python",
"selenium",
"selenium_rc",
"xpath"
] | stackoverflow_0003031299_python_selenium_selenium_rc_xpath.txt |
Q:
Named keywords in decorators?
I've been playing around in depth with attempting to write my own version of a memoizing decorator before I go looking at other people's code. It's more of an exercise in fun, honestly. However, in the course of playing around I've found I can't do something I want with decorators.
def addValue( func, val ):
def add( x ):
return func( x ) + val
return add
@addValue( val=4 )
def computeSomething( x ):
#function gets defined
If I want to do that I have to do this:
def addTwo( func ):
return addValue( func, 2 )
@addTwo
def computeSomething( x ):
#function gets defined
Why can't I use keyword arguments with decorators in this manner? What am I doing wrong and can you show me how I should be doing it?
A:
You need to define a function that returns a decorator:
def addValue(val):
def decorator(func):
def add(x):
return func(x) + val
return add
return decorator
When you write @addTwo, the value of addTwo is directly used as a decorator. However, when you write @addValue(4), first addValue(4) is evaluated by calling the addValue function. Then the result is used as a decorator.
A:
You want to partially apply the function addValue - give the val argument, but not func. There are generally two ways to do this:
The first one is called currying and used in interjay's answer: instead of a function with two arguments, f(a,b) -> res, you write a function of the first arg that returns another function that takes the 2nd arg g(a) -> (h(b) -> res)
The other way is a functools.partial object. It uses inspection on the function to figure out what arguments a function needs to run (func and val in your case ). You can add extra arguments when creating a partial and once you call the partial, it uses all the extra arguments given.
from functools import partial
@partial(addValue, val=2 ) # you can call this addTwo
def computeSomething( x ):
return x
Partials are usually a much simpler solution for this partial application problem, especially with more than one argument.
A:
Decorators with any kinds of arguments -- named/keyword ones, unnamed/positional ones, or some of each -- essentially, ones you call on the @name line rather than just mention there -- need a double level of nesting (while the decorators you just mention have a single level of nesting). That goes even for argument-less ones if you want to call them in the @ line -- here's the simplest, do-nothing, double-nested decorator:
def double():
def middling():
def inner(f):
return f
return inner
return middling
You'd use this as
@double()
def whatever ...
note the parentheses (empty in this case since there are no arguments needed nor wanted): they mean you're calling double, which returns middling, which decorates whatever.
Once you've seen the difference between "calling" and "just mentioning", adding (e.g. optional) named args is not hard:
def doublet(foo=23):
def middling():
def inner(f):
return f
return inner
return middling
usable either as:
@doublet()
def whatever ...
or as:
@doublet(foo=45)
def whatever ...
or equivalently as:
@doublet(45)
def whatever ...
| Named keywords in decorators? | I've been playing around in depth with attempting to write my own version of a memoizing decorator before I go looking at other people's code. It's more of an exercise in fun, honestly. However, in the course of playing around I've found I can't do something I want with decorators.
def addValue( func, val ):
def add( x ):
return func( x ) + val
return add
@addValue( val=4 )
def computeSomething( x ):
#function gets defined
If I want to do that I have to do this:
def addTwo( func ):
return addValue( func, 2 )
@addTwo
def computeSomething( x ):
#function gets defined
Why can't I use keyword arguments with decorators in this manner? What am I doing wrong and can you show me how I should be doing it?
| [
"You need to define a function that returns a decorator:\ndef addValue(val):\n def decorator(func):\n def add(x):\n return func(x) + val\n return add\n return decorator\n\nWhen you write @addTwo, the value of addTwo is directly used as a decorator. However, when you write @addValue(4), first addValue(4) is evaluated by calling the addValue function. Then the result is used as a decorator.\n",
"You want to partially apply the function addValue - give the val argument, but not func. There are generally two ways to do this: \nThe first one is called currying and used in interjay's answer: instead of a function with two arguments, f(a,b) -> res, you write a function of the first arg that returns another function that takes the 2nd arg g(a) -> (h(b) -> res)\nThe other way is a functools.partial object. It uses inspection on the function to figure out what arguments a function needs to run (func and val in your case ). You can add extra arguments when creating a partial and once you call the partial, it uses all the extra arguments given.\nfrom functools import partial\n@partial(addValue, val=2 ) # you can call this addTwo\ndef computeSomething( x ): \n return x\n\nPartials are usually a much simpler solution for this partial application problem, especially with more than one argument.\n",
"Decorators with any kinds of arguments -- named/keyword ones, unnamed/positional ones, or some of each -- essentially, ones you call on the @name line rather than just mention there -- need a double level of nesting (while the decorators you just mention have a single level of nesting). That goes even for argument-less ones if you want to call them in the @ line -- here's the simplest, do-nothing, double-nested decorator:\ndef double():\n def middling():\n def inner(f):\n return f\n return inner\n return middling\n\nYou'd use this as\n@double()\ndef whatever ...\n\nnote the parentheses (empty in this case since there are no arguments needed nor wanted): they mean you're calling double, which returns middling, which decorates whatever.\nOnce you've seen the difference between \"calling\" and \"just mentioning\", adding (e.g. optional) named args is not hard:\ndef doublet(foo=23):\n def middling():\n def inner(f):\n return f\n return inner\n return middling\n\nusable either as:\n@doublet()\ndef whatever ...\n\nor as:\n@doublet(foo=45)\ndef whatever ...\n\nor equivalently as:\n@doublet(45)\ndef whatever ...\n\n"
] | [
5,
5,
3
] | [] | [] | [
"decorator",
"keyword",
"named_parameters",
"python"
] | stackoverflow_0003032579_decorator_keyword_named_parameters_python.txt |
Q:
wsgi-served page does not refresh
I recently got my first app to work in uWSGI with Cherokee. I used the following code taken from the uWSGI docs:
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/plain')])
yield 'Hello World\n'
The page correctly reads Hello World. When I change that text to New Thing and refresh, nothing changes. What am I forgetting?
What I've tried:
clearing browser history and cache
stopping and starting Cherokee
Edit: To clarify, I change Hello World to New Thing in the Python code. Then I stop Cherokee, refresh, and I obviously see an error message. I restart Cherokee, refresh, and I see Hello World.
A:
So the way this works is that Cherokee is managing a running uwsgi instance in the back ground for you. What I've noticed so far, and I've not finished looking at, is that if you shut down Cherokee it doesn't seem to also shut down running uwsgi instances.
Try this:
sudo service cherokee start
ps aux | grep uwsgi
# you should see nothing from this ps command
# now hit your web app
sudo service cherokee stop
ps aux | grep uwsgi
# you should see the instance of uwsgi that cherokee started
So your app code is actually run via uwsgi and Cherokee is more like a proxy server. In order to update the app code you need to send the HUP signal to uwsgi, not Cherkee.
sudo killall -HUP uwsgi
That should cause uwsgi to update to your app changes regardless of Cherokee.
| wsgi-served page does not refresh | I recently got my first app to work in uWSGI with Cherokee. I used the following code taken from the uWSGI docs:
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/plain')])
yield 'Hello World\n'
The page correctly reads Hello World. When I change that text to New Thing and refresh, nothing changes. What am I forgetting?
What I've tried:
clearing browser history and cache
stopping and starting Cherokee
Edit: To clarify, I change Hello World to New Thing in the Python code. Then I stop Cherokee, refresh, and I obviously see an error message. I restart Cherokee, refresh, and I see Hello World.
| [
"So the way this works is that Cherokee is managing a running uwsgi instance in the back ground for you. What I've noticed so far, and I've not finished looking at, is that if you shut down Cherokee it doesn't seem to also shut down running uwsgi instances. \nTry this:\nsudo service cherokee start\nps aux | grep uwsgi \n# you should see nothing from this ps command\n\n# now hit your web app\nsudo service cherokee stop\nps aux | grep uwsgi\n# you should see the instance of uwsgi that cherokee started\n\nSo your app code is actually run via uwsgi and Cherokee is more like a proxy server. In order to update the app code you need to send the HUP signal to uwsgi, not Cherkee. \nsudo killall -HUP uwsgi\n\nThat should cause uwsgi to update to your app changes regardless of Cherokee. \n"
] | [
2
] | [] | [] | [
"cherokee",
"python",
"uwsgi",
"wsgi"
] | stackoverflow_0003031265_cherokee_python_uwsgi_wsgi.txt |
Q:
Is a python dictionary the best data structure to solve this problem?
I have a number of processes running which are controlled by remote clients. A tcp server controls access to these processes, only one client per process. The processes are given an id number in the range of 0 -> n-1. Were 'n' is the number of processes. I use a dictionary to map this id to the client sockets file descriptor. On startup I populate the dictionary with the ids as keys and socket fd of 'None' for the values, i.e no clients and all pocesses are available
When a client connects, I map the id to the sockets fd. When a client disconnects I set the value for this id to None, i.e. process is available. So everytime a client connects I have to check each entry in the dictionary for a process which has a socket fd entry of None. If there are then the client is allowed to connect.
This solution does not seem very elegant, are there other data structures which would be more suitable for solving this?
Thanks
A:
You can keep that idea but add a list or whatever to hold unused socked fd, so that you have no to iterate the dictionary to find the first usable "None". When you pick the first (or last) free process from the "not busy" list, you remove from it. E.g.
# d is the dictionary
# notbusy is a list
d[ notbusy.pop() ] = ... # init the socket
of course you have to check that notbusy is not empty (or try-catch if you prefer); if it is, there are no free usable "slot" and is not possible to connect. When an used slot is "freed", you set to None and add its key to the list notbusy.
A:
Why not just use a list? Python lists are arrays behind the scenes, with O(1) access.
sockets = n * [None]
Then once you learn the socket for a given process id:
sockets[id] = socket;
A:
"Premature optimization is the root of all evil," as C.A.R. Hoare said.
Rather than ask if this implementation is efficient, perhaps you should ask if this implementation is efficient enough. If it meets your performance requirements and the code is easy to understand, perhaps you should leave it be.
If your code is not giving you the performance you need, I'd suggest Shin's answer. It seems to be the simplest way of getting additional performance.
| Is a python dictionary the best data structure to solve this problem? | I have a number of processes running which are controlled by remote clients. A tcp server controls access to these processes, only one client per process. The processes are given an id number in the range of 0 -> n-1. Were 'n' is the number of processes. I use a dictionary to map this id to the client sockets file descriptor. On startup I populate the dictionary with the ids as keys and socket fd of 'None' for the values, i.e no clients and all pocesses are available
When a client connects, I map the id to the sockets fd. When a client disconnects I set the value for this id to None, i.e. process is available. So everytime a client connects I have to check each entry in the dictionary for a process which has a socket fd entry of None. If there are then the client is allowed to connect.
This solution does not seem very elegant, are there other data structures which would be more suitable for solving this?
Thanks
| [
"You can keep that idea but add a list or whatever to hold unused socked fd, so that you have no to iterate the dictionary to find the first usable \"None\". When you pick the first (or last) free process from the \"not busy\" list, you remove from it. E.g.\n# d is the dictionary\n# notbusy is a list\nd[ notbusy.pop() ] = ... # init the socket\n\nof course you have to check that notbusy is not empty (or try-catch if you prefer); if it is, there are no free usable \"slot\" and is not possible to connect. When an used slot is \"freed\", you set to None and add its key to the list notbusy.\n",
"Why not just use a list? Python lists are arrays behind the scenes, with O(1) access.\nsockets = n * [None]\n\nThen once you learn the socket for a given process id:\nsockets[id] = socket;\n\n",
"\"Premature optimization is the root of all evil,\" as C.A.R. Hoare said.\nRather than ask if this implementation is efficient, perhaps you should ask if this implementation is efficient enough. If it meets your performance requirements and the code is easy to understand, perhaps you should leave it be.\nIf your code is not giving you the performance you need, I'd suggest Shin's answer. It seems to be the simplest way of getting additional performance.\n"
] | [
2,
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003032207_dictionary_python.txt |
Q:
Custom Django tag & jQuery
I'm new to Django. Today I created some Django custom tags which is not that hard. But now I wonder what is the best way to include some jQuery or some Javascript code packed into my custom tag definition. What is the regular way to include a custom library into my code? For example:
{% faceboxify item %}
So assume that it'll create a specific HTML output for Facebox plugin. I just want to learn some elegant way to import this plugin into my code. I want the above definition to be enough for all functionality. Is there any way to do it? I couldn't find any example. Maybe I'm missing something..
A:
From the documentation you can see that writing template tags involves writing a target function and a renderer. So I'm assuming your current code looks like this:
def my_tag(parser, token):
# ... some code
return MyNode(...)
class MyNode(template.Node):
def render(self, context):
# here is where you write your <script> tags
So essentially what you have to do is to hang a variable under the context so you can know if for that specific request you've already included the code to load all your needed scripts.
class MyNode(template.Node):
def render(self, context):
if '_included_faceboxify_deps' in context:
# render your <script> dependency includes
context['_included_faceboxify_deps'] = True
# render your <script>s that are specific for this call
This should do the trick. It's not as elegant as including your dependencies in the top of the page, but it's enough not to include them for every time you need to call them.
A:
You can have your custom tag apply "class" values for your Javascript to look for. Include your Javascript as a regular .js <script> import, and have it use a load-time function to find your elements and manipulate them as necessary.
So for example if your tag creates a <div>, you can have it do this:
<div class='faceboxify'>
<!-- whatever -->
</div>
Your Javascript can then do this:
$(function() {
$('div.faceboxify').each(function() {
// ... stuff to be done to your "faceboxify" divs
});
});
| Custom Django tag & jQuery | I'm new to Django. Today I created some Django custom tags which is not that hard. But now I wonder what is the best way to include some jQuery or some Javascript code packed into my custom tag definition. What is the regular way to include a custom library into my code? For example:
{% faceboxify item %}
So assume that it'll create a specific HTML output for Facebox plugin. I just want to learn some elegant way to import this plugin into my code. I want the above definition to be enough for all functionality. Is there any way to do it? I couldn't find any example. Maybe I'm missing something..
| [
"From the documentation you can see that writing template tags involves writing a target function and a renderer. So I'm assuming your current code looks like this:\ndef my_tag(parser, token):\n # ... some code\n return MyNode(...)\n\nclass MyNode(template.Node):\n def render(self, context):\n # here is where you write your <script> tags\n\nSo essentially what you have to do is to hang a variable under the context so you can know if for that specific request you've already included the code to load all your needed scripts.\nclass MyNode(template.Node):\n def render(self, context):\n if '_included_faceboxify_deps' in context:\n # render your <script> dependency includes\n context['_included_faceboxify_deps'] = True\n # render your <script>s that are specific for this call\n\nThis should do the trick. It's not as elegant as including your dependencies in the top of the page, but it's enough not to include them for every time you need to call them.\n",
"You can have your custom tag apply \"class\" values for your Javascript to look for. Include your Javascript as a regular .js <script> import, and have it use a load-time function to find your elements and manipulate them as necessary.\nSo for example if your tag creates a <div>, you can have it do this:\n<div class='faceboxify'>\n <!-- whatever -->\n</div>\n\nYour Javascript can then do this:\n$(function() {\n $('div.faceboxify').each(function() {\n // ... stuff to be done to your \"faceboxify\" divs\n });\n});\n\n"
] | [
2,
0
] | [] | [] | [
"django",
"django_custom_tags",
"jquery",
"python"
] | stackoverflow_0003032783_django_django_custom_tags_jquery_python.txt |
Q:
I need a dictionary text file with meanings
I need a text file in the form:
aardvark : animal
atlas : collection of maps
.
.
.
.
.
and so on.
I want to use this text file to create my own dictionary like Artha or Wordweb.It will be Python based with Tkinter for GUI.
Where can I obtain such a file.
A:
Project Gutenberg has a few variants (including the unabridged Webster's). Not exactly the format you're looking for, but you should be able to parse it to remove parts of speech, etc.
A:
Natural Language Toolkit.
Yes, this is a large complex library because the task is actually complex. aardvark: animal is easy; given hit: what do you put after it? Do you mean the noun, the verb, or the adjective? Which sense of the noun? Did the baseball player make a hit? Did the pop star have a hit? Did the hit baseball player hit the hit with his bat?
added:
#!/bin/sh
# tersify - returns the most terse definition for its input
#
# examples: echo "aardvark" | tersify
# tersify < /usr/share/dict/words > ~/my_dict
while read word ; do
echo "$word: $word"
done
'tis a joke, take thee not offense
| I need a dictionary text file with meanings | I need a text file in the form:
aardvark : animal
atlas : collection of maps
.
.
.
.
.
and so on.
I want to use this text file to create my own dictionary like Artha or Wordweb.It will be Python based with Tkinter for GUI.
Where can I obtain such a file.
| [
"Project Gutenberg has a few variants (including the unabridged Webster's). Not exactly the format you're looking for, but you should be able to parse it to remove parts of speech, etc.\n",
"Natural Language Toolkit. \nYes, this is a large complex library because the task is actually complex. aardvark: animal is easy; given hit: what do you put after it? Do you mean the noun, the verb, or the adjective? Which sense of the noun? Did the baseball player make a hit? Did the pop star have a hit? Did the hit baseball player hit the hit with his bat?\nadded:\n#!/bin/sh\n# tersify - returns the most terse definition for its input\n#\n# examples: echo \"aardvark\" | tersify\n# tersify < /usr/share/dict/words > ~/my_dict\n\nwhile read word ; do\n echo \"$word: $word\"\ndone\n\n'tis a joke, take thee not offense\n"
] | [
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003032955_dictionary_python.txt |
Q:
Python execute a function for X seconds
I'm looking for a way for a function to take actions based on how long it has been executing. For example, my function would loop continuously until 5 seconds has elapsed, in which case it returns immediately. Any suggestions?
A:
Have you looked at time.clock() ?
time.clock()
On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms.
On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.
Using 'time.clock()' to measure time on Windows:
>>> import time
>>> def measure():
... t0 = time.clock()
... time.sleep(3)
... return time.clock() - t0
...
>>> measure()
2.9976609581514113
>>>
A:
Another option is to use signal.alarm() with an appropriate signal handler, documented at http://docs.python.org/library/signal.html. A particular advantage to this approach is not having to check the time every time you loop, which may add significant overhead for small, tight loops.
| Python execute a function for X seconds | I'm looking for a way for a function to take actions based on how long it has been executing. For example, my function would loop continuously until 5 seconds has elapsed, in which case it returns immediately. Any suggestions?
| [
"Have you looked at time.clock() ?\n\ntime.clock()\nOn Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms.\nOn Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.\n\nUsing 'time.clock()' to measure time on Windows:\n>>> import time\n>>> def measure():\n... t0 = time.clock()\n... time.sleep(3)\n... return time.clock() - t0\n... \n>>> measure()\n2.9976609581514113\n>>> \n\n",
"Another option is to use signal.alarm() with an appropriate signal handler, documented at http://docs.python.org/library/signal.html. A particular advantage to this approach is not having to check the time every time you loop, which may add significant overhead for small, tight loops.\n"
] | [
5,
4
] | [] | [] | [
"python"
] | stackoverflow_0003033005_python.txt |
Q:
Need help understanding some Python code with @, *args and **kwargs
I'm new to Python, and stumped by this piece of code from the Boto project:
class SubdomainCallingFormat(_CallingFormat):
@assert_case_insensitive
def get_bucket_server(self, server, bucket):
return '%s.%s' % (bucket, server)
def assert_case_insensitive(f):
def wrapper(*args, **kwargs):
if len(args) == 3 and not (args[2].islower() or args[2].isalnum()):
raise BotoClientError("Bucket names cannot contain upper-case " \
"characters when using either the sub-domain or virtual " \
"hosting calling format.")
return f(*args, **kwargs)
return wrapper
Trying to understand what's going on here.
What is the '@' symbol in @assert_case_sensitive ?
What do the args *args, **kwargs mean?
What does 'f' represent?
Thanks!
A:
The @ symbol is used to indicate the application of a decorator.
And those asterisks indicate the parameters are excess positional/keyword arguments put into a list/dictionary.
The "f" represents the function passed in, as a first-class object, into the decorator. When someone writes
@decorate
def whizbang(): pass
it's really equivalent to
def whizbang(): pass
whizbang = decorate(whizbang)
The manual goes into more detail, but decorators are basically a way to surround an existing piece of code with more code that can execute before and after it without having to modify the code you're decorating. All with the magic of first-class functions.
A:
What is the '@' symbol in @assert_case_sensitive ?
@ is decorator syntax, basically:
@decor
def func(arg):
pass
is equivalent to:
def func(arg):
pass
func = decor(func)
What do the args *args, **kwargs mean?
The *args and **kwargs are argument unpacking. It is similar to C's varargs, in that any excess unnamed arguments will go to *args tuple, and unrecognized named arguments will go to **kwargs dict.
def foo(a, *arg, **kwarg):
print a # prints 1
print arg # prints (2, 3)
print kwarg # prints {'foo': 4}
foo(1, 2, 3, foo=4)
What does 'f' represent?
It is python's higher-level function. Basically in python, everything is an object including functions. Since function is an object, you can pass function as an argument to another function. If this is C, it's similar to passing a function pointer.
A:
In this particular case assert_case_sensitive is a function wrapping function, otherwise known as a decorator.
A decorator takes an existing function and returns a different function. Usually it returns a new function that calls the original function in some way. In this case assert_case_insensitive always returns wrapper which is a function that's defined within it who's name is only known inside assert_case_insensitive.
When a function is declared in the body of another like that, the enclosed function is sort of created anew every time the outer function is called. This means the inner function has access to the variables from the function it was in.
This technique is called a closure, and Python's support of closures is incomplete because the variables from the enclosing scopes cannot be modified. But that's not terribly relevant to this question.
The goal of assert_case_insensitive is to enforce some conditions on the arguments to the functions it's passed. It returns a new function that enforces those conditions and calls the original function. In order for assert_case_insensitive to be able to be used to wrap any function, it needs to work for functions with different numbers of arguments, and functions that have keyword arguments. This is where *args and **kargs come in.
An argument of the form *something gets a tuple of any remaining non-keyword (aka positional) arguments that are not accounted for by the previous positional arguments. An argument of the form **something gets a dictionary any remaining keyword arguments that are not accounted for by the previous positional arguments. Arguments of the form *something or **something must occur after all other arguments.
A similar syntax is used for calling functions with argument lists that aren't know. An argument of the form *(iterable sequence) is turned into a series of positional arguments, and an argument of the form **(dictionary) is turned into a set of keyword arguments.
So wrapper is using these constructs so it can work very generally for any function. Decorators in general are expected to work for any function, so doing something like this is highly recommended when writing them.
A:
For @assert_case_sensitive here's the explanation of decorators from wikipedia:
A decorator is a Python object that can be called with a single argument, and that modifies functions or methods. Python decorators were inspired in part by Java annotations, and have a similar syntax; the decorator syntax is pure syntactic sugar, using @ as the keyword:
@viking_chorus
def menu_item():
print "spam"
is equivalent to
def menu_item():
print "spam"
menu_item = viking_chorus(menu_item)
| Need help understanding some Python code with @, *args and **kwargs | I'm new to Python, and stumped by this piece of code from the Boto project:
class SubdomainCallingFormat(_CallingFormat):
@assert_case_insensitive
def get_bucket_server(self, server, bucket):
return '%s.%s' % (bucket, server)
def assert_case_insensitive(f):
def wrapper(*args, **kwargs):
if len(args) == 3 and not (args[2].islower() or args[2].isalnum()):
raise BotoClientError("Bucket names cannot contain upper-case " \
"characters when using either the sub-domain or virtual " \
"hosting calling format.")
return f(*args, **kwargs)
return wrapper
Trying to understand what's going on here.
What is the '@' symbol in @assert_case_sensitive ?
What do the args *args, **kwargs mean?
What does 'f' represent?
Thanks!
| [
"The @ symbol is used to indicate the application of a decorator.\nAnd those asterisks indicate the parameters are excess positional/keyword arguments put into a list/dictionary.\nThe \"f\" represents the function passed in, as a first-class object, into the decorator. When someone writes\n@decorate\ndef whizbang(): pass\n\nit's really equivalent to\ndef whizbang(): pass\nwhizbang = decorate(whizbang)\n\nThe manual goes into more detail, but decorators are basically a way to surround an existing piece of code with more code that can execute before and after it without having to modify the code you're decorating. All with the magic of first-class functions.\n",
"What is the '@' symbol in @assert_case_sensitive ?\n@ is decorator syntax, basically:\n@decor\ndef func(arg):\n pass\n\nis equivalent to:\ndef func(arg):\n pass\nfunc = decor(func)\n\n\nWhat do the args *args, **kwargs mean?\nThe *args and **kwargs are argument unpacking. It is similar to C's varargs, in that any excess unnamed arguments will go to *args tuple, and unrecognized named arguments will go to **kwargs dict.\ndef foo(a, *arg, **kwarg):\n print a # prints 1\n print arg # prints (2, 3)\n print kwarg # prints {'foo': 4}\n\nfoo(1, 2, 3, foo=4)\n\n\nWhat does 'f' represent?\nIt is python's higher-level function. Basically in python, everything is an object including functions. Since function is an object, you can pass function as an argument to another function. If this is C, it's similar to passing a function pointer.\n",
"In this particular case assert_case_sensitive is a function wrapping function, otherwise known as a decorator.\nA decorator takes an existing function and returns a different function. Usually it returns a new function that calls the original function in some way. In this case assert_case_insensitive always returns wrapper which is a function that's defined within it who's name is only known inside assert_case_insensitive.\nWhen a function is declared in the body of another like that, the enclosed function is sort of created anew every time the outer function is called. This means the inner function has access to the variables from the function it was in.\nThis technique is called a closure, and Python's support of closures is incomplete because the variables from the enclosing scopes cannot be modified. But that's not terribly relevant to this question.\nThe goal of assert_case_insensitive is to enforce some conditions on the arguments to the functions it's passed. It returns a new function that enforces those conditions and calls the original function. In order for assert_case_insensitive to be able to be used to wrap any function, it needs to work for functions with different numbers of arguments, and functions that have keyword arguments. This is where *args and **kargs come in.\nAn argument of the form *something gets a tuple of any remaining non-keyword (aka positional) arguments that are not accounted for by the previous positional arguments. An argument of the form **something gets a dictionary any remaining keyword arguments that are not accounted for by the previous positional arguments. Arguments of the form *something or **something must occur after all other arguments.\nA similar syntax is used for calling functions with argument lists that aren't know. An argument of the form *(iterable sequence) is turned into a series of positional arguments, and an argument of the form **(dictionary) is turned into a set of keyword arguments. \nSo wrapper is using these constructs so it can work very generally for any function. Decorators in general are expected to work for any function, so doing something like this is highly recommended when writing them.\n",
"For @assert_case_sensitive here's the explanation of decorators from wikipedia:\nA decorator is a Python object that can be called with a single argument, and that modifies functions or methods. Python decorators were inspired in part by Java annotations, and have a similar syntax; the decorator syntax is pure syntactic sugar, using @ as the keyword:\n@viking_chorus\ndef menu_item():\n print \"spam\"\n\nis equivalent to\ndef menu_item():\n print \"spam\"\nmenu_item = viking_chorus(menu_item)\n\n"
] | [
6,
4,
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0003033133_python.txt |
Q:
Python sorting problem
Possible Duplicate:
Python analog of natsort function (sort a list using a “natural order” algorithm)
I'm sure this is simple but I can't figure it out. I have a list of strings like this(after using sorted on it):
Season 2, Episode 1: A Flight to Remember
Season 2, Episode 20: Anthology of Interest I
Season 2, Episode 2: Mars University
Season 2, Episode 3: When Aliens Attack
....
Season 3, Episode 10: The Luck of the Fryrish
Season 3, Episode 11: The Cyber House Rules
Season 3, Episode 12: Insane in the Mainframe
Season 3, Episode 1: The Honking
Season 3, Episode 2: War Is the H-Word
How can I make them sort out properly? (by season then episode #, ascending)
A:
Use the key parameter to the sort function to specify the key you would like to use for sorting.
def get_sort_key(s):
m = re.match('Season ([0-9]+), Episode ([0-9]+): .*', s)
return (int(m.group(1)), int(m.group(2)))
my_list.sort(key=get_sort_key)
A:
There are two ways to approach this:
Define your own sorting function cmp(x, y), where x and y are strings, and you return 1 if the second one is greater than the first, -1 if the first is greater, and 0 if they're the same. Then pass this function as the "cmp" argument to the built-in sort() function.
Convert all of the strings into a format where the "natural" sorting order is exactly what you want. For example you could just zero-pad them like "Season 03, Episode 07". Then you can sort them using sort().
Either way, I'd suggest using a simple regular expression to get the season and episode out of the string, something like:
m = re.match('Season ([0-9]+), Episode ([0-9]+): .*', s)
(season, episode) = (int(m.group(1)), int(m.group(2)))
A:
Since you're sorting by strings, "1" comes before "10", so your intended episodes will not be in proper order. The solution is to pull apart the string into its constituent parts, namely get the season and episodes as integers, place them in an associative data structure then sort by the relevant integers. For pulling apart the string into its parts, check out Python's Regular Expressions, cast the season number and episode numbers as integers, then pick a data structure you like and associate the integer keys with the strings. Sort by the keys, and you're done.
| Python sorting problem |
Possible Duplicate:
Python analog of natsort function (sort a list using a “natural order” algorithm)
I'm sure this is simple but I can't figure it out. I have a list of strings like this(after using sorted on it):
Season 2, Episode 1: A Flight to Remember
Season 2, Episode 20: Anthology of Interest I
Season 2, Episode 2: Mars University
Season 2, Episode 3: When Aliens Attack
....
Season 3, Episode 10: The Luck of the Fryrish
Season 3, Episode 11: The Cyber House Rules
Season 3, Episode 12: Insane in the Mainframe
Season 3, Episode 1: The Honking
Season 3, Episode 2: War Is the H-Word
How can I make them sort out properly? (by season then episode #, ascending)
| [
"Use the key parameter to the sort function to specify the key you would like to use for sorting.\ndef get_sort_key(s):\n m = re.match('Season ([0-9]+), Episode ([0-9]+): .*', s)\n return (int(m.group(1)), int(m.group(2)))\n\nmy_list.sort(key=get_sort_key)\n\n",
"There are two ways to approach this:\n\nDefine your own sorting function cmp(x, y), where x and y are strings, and you return 1 if the second one is greater than the first, -1 if the first is greater, and 0 if they're the same. Then pass this function as the \"cmp\" argument to the built-in sort() function.\nConvert all of the strings into a format where the \"natural\" sorting order is exactly what you want. For example you could just zero-pad them like \"Season 03, Episode 07\". Then you can sort them using sort().\n\nEither way, I'd suggest using a simple regular expression to get the season and episode out of the string, something like:\nm = re.match('Season ([0-9]+), Episode ([0-9]+): .*', s)\n(season, episode) = (int(m.group(1)), int(m.group(2)))\n\n",
"Since you're sorting by strings, \"1\" comes before \"10\", so your intended episodes will not be in proper order. The solution is to pull apart the string into its constituent parts, namely get the season and episodes as integers, place them in an associative data structure then sort by the relevant integers. For pulling apart the string into its parts, check out Python's Regular Expressions, cast the season number and episode numbers as integers, then pick a data structure you like and associate the integer keys with the strings. Sort by the keys, and you're done.\n"
] | [
3,
1,
1
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0003033271_python_sorting.txt |
Q:
What is the best way to implement a 'last seen' function in a django web app?
I have a running django/apache2 + memcached app (ubuntu) and would like to keep track of logged in users that are online.
What would be the best way to track this?
I would prefer not writing to the database each time a logged in user loads a page; but what other options are there?
A:
An approach might be:
you create a middleware that does the following on process_response:
check for a cookie called 'online', but only if the user is authenticated
if the cookie is not there,
set a cookie called 'online' with value '1'
set the lifespan of the cookie to 10 minutes
update the 'last_login' field of auth.User for this user with the current datetime
now you have all currently logged in users in your auth.User table. All Users that have a last_login newer than datetime.now()-interval(15minutes) might be considered "online".
The database will be written for every logged in user about every 10 minutes. Adjust the values "10" and "15" to your needs.
The advantage here is that database writes are rare (according to your two numeric settings 10/15). And for speed optimization make sure that last_login is indexed, so a filter on this field including Count is really fast.
Hope this helps.
A:
A hashmap or a queue in memory with a task running every hour or so to persist it.
A:
You need to persist the info server-side, integrity isn't critical, throughput and latency are important. That means you should use some sort of key-value store.
Memcached and redis have keys that expire. You probably have memcached already installed, so use that.
You can reset expiry time of the user:last-seen:$username key every visit, or you can use mawimawi's cookie technique and have expiry = 4 * cookie-lifetime.
A:
You can't do that in django without using a database/persistent-storage because of the same reason why django sessions are stored in database: There can be multiple instances of your applications running and the must synchronize their states+data through a single persistence source [1]
Alternatively, you might want to write this information in a folder in a file named with user id and then check its create/modified date to find the required information.
| What is the best way to implement a 'last seen' function in a django web app? | I have a running django/apache2 + memcached app (ubuntu) and would like to keep track of logged in users that are online.
What would be the best way to track this?
I would prefer not writing to the database each time a logged in user loads a page; but what other options are there?
| [
"An approach might be:\nyou create a middleware that does the following on process_response:\n\ncheck for a cookie called 'online', but only if the user is authenticated\nif the cookie is not there,\n\n\nset a cookie called 'online' with value '1'\nset the lifespan of the cookie to 10 minutes\nupdate the 'last_login' field of auth.User for this user with the current datetime\n\n\nnow you have all currently logged in users in your auth.User table. All Users that have a last_login newer than datetime.now()-interval(15minutes) might be considered \"online\".\nThe database will be written for every logged in user about every 10 minutes. Adjust the values \"10\" and \"15\" to your needs.\nThe advantage here is that database writes are rare (according to your two numeric settings 10/15). And for speed optimization make sure that last_login is indexed, so a filter on this field including Count is really fast.\nHope this helps.\n",
"A hashmap or a queue in memory with a task running every hour or so to persist it.\n",
"You need to persist the info server-side, integrity isn't critical, throughput and latency are important. That means you should use some sort of key-value store.\nMemcached and redis have keys that expire. You probably have memcached already installed, so use that.\nYou can reset expiry time of the user:last-seen:$username key every visit, or you can use mawimawi's cookie technique and have expiry = 4 * cookie-lifetime.\n",
"You can't do that in django without using a database/persistent-storage because of the same reason why django sessions are stored in database: There can be multiple instances of your applications running and the must synchronize their states+data through a single persistence source [1]\nAlternatively, you might want to write this information in a folder in a file named with user id and then check its create/modified date to find the required information.\n"
] | [
4,
1,
1,
0
] | [] | [] | [
"apache2",
"django",
"python"
] | stackoverflow_0003027973_apache2_django_python.txt |
Q:
Script to install and compile Python, Django, Virtualenv, Mercurial, Git, LessCSS, etc... on Dreamhost
The Story
After cleaning up my Dreamhost shared server's home folder from all the cruft accumulated over time, I decided to start afresh and compile/reinstall Python.
All tutorials and snippets I found seemed overly simplistic, assuming (or ignoring) a bunch of dependencies needed by Python to compile all modules correctly. So, starting from http://andrew.io/weblog/2010/02/installing-python-2-6-virtualenv-and-virtualenvwrapper-on-dreamhost/ (so far the best guide I found), I decided to write a set-and-forget Bash script to automate this painful process, including along the way a bunch of other things I am planning to use.
The Script
I am hosting the script on http://bitbucket.org/tmslnz/python-dreamhost-batch/src/
The TODOs
So far it runs fine, and does all it needs to do in about 900 seconds, giving me at the end of the process a fully functional Python / Mercurial / etc... setup without even needing to log out and back in.
I though this might be of use for others too, but there are a few things that I think it's missing and I am not quite sure how to go for it, what's the best way to do it, or if this just doesn't make any sense at all.
Check for errors and break
Check for minor version bumps of the packages and give warnings
Check for known dependencies
Use arguments to install only some of the packages instead of commenting out lines
Organise the code in a manner that's easy to update
Optionally make the installers and compiling silent, with error logging to file
failproof .bashrc modification to prevent breaking ssh logins and having to log back via FTP to fix it
EDIT: The implied question is: can anyone, more bashful than me, offer general advice on the worthiness of the above points or highlight any problems they see with this approach? (see my answer to Ry4an's comment below)
The Gist
I am no UNIX or Bash or compiler expert, and this has been built iteratively, by trial and error. It is somehow going towards apt-get (well, 1% of it...), but since Dreamhost and others obviously cannot give root access on shared servers, this looks to me like a potentially very useful workaround; particularly so with some community work involved.
A:
One way to streamline this would be to make it work with one of: capistrano/fabric, puppet/chef, jhbuild, or buildout+minitage (and a lot of cmmi tasks). There are some opportunities for factoring in common code, especially with something more high-level than bash. You will run into bootstrapping issues, however, so maybe leave good enough alone.
If you want to look into userland package managers, there is autopackage (bootstraps well), nix (quickstart), and stow (simple but helps with isolation).
A:
Honestly, I would just build packages with a name prefix for all of the pieces and have them install under /opt so that they're out of the way. That way it only takes the download time and a bit of install time to do.
| Script to install and compile Python, Django, Virtualenv, Mercurial, Git, LessCSS, etc... on Dreamhost | The Story
After cleaning up my Dreamhost shared server's home folder from all the cruft accumulated over time, I decided to start afresh and compile/reinstall Python.
All tutorials and snippets I found seemed overly simplistic, assuming (or ignoring) a bunch of dependencies needed by Python to compile all modules correctly. So, starting from http://andrew.io/weblog/2010/02/installing-python-2-6-virtualenv-and-virtualenvwrapper-on-dreamhost/ (so far the best guide I found), I decided to write a set-and-forget Bash script to automate this painful process, including along the way a bunch of other things I am planning to use.
The Script
I am hosting the script on http://bitbucket.org/tmslnz/python-dreamhost-batch/src/
The TODOs
So far it runs fine, and does all it needs to do in about 900 seconds, giving me at the end of the process a fully functional Python / Mercurial / etc... setup without even needing to log out and back in.
I though this might be of use for others too, but there are a few things that I think it's missing and I am not quite sure how to go for it, what's the best way to do it, or if this just doesn't make any sense at all.
Check for errors and break
Check for minor version bumps of the packages and give warnings
Check for known dependencies
Use arguments to install only some of the packages instead of commenting out lines
Organise the code in a manner that's easy to update
Optionally make the installers and compiling silent, with error logging to file
failproof .bashrc modification to prevent breaking ssh logins and having to log back via FTP to fix it
EDIT: The implied question is: can anyone, more bashful than me, offer general advice on the worthiness of the above points or highlight any problems they see with this approach? (see my answer to Ry4an's comment below)
The Gist
I am no UNIX or Bash or compiler expert, and this has been built iteratively, by trial and error. It is somehow going towards apt-get (well, 1% of it...), but since Dreamhost and others obviously cannot give root access on shared servers, this looks to me like a potentially very useful workaround; particularly so with some community work involved.
| [
"One way to streamline this would be to make it work with one of: capistrano/fabric, puppet/chef, jhbuild, or buildout+minitage (and a lot of cmmi tasks). There are some opportunities for factoring in common code, especially with something more high-level than bash. You will run into bootstrapping issues, however, so maybe leave good enough alone.\nIf you want to look into userland package managers, there is autopackage (bootstraps well), nix (quickstart), and stow (simple but helps with isolation). \n",
"Honestly, I would just build packages with a name prefix for all of the pieces and have them install under /opt so that they're out of the way. That way it only takes the download time and a bit of install time to do.\n"
] | [
2,
1
] | [] | [] | [
"dreamhost",
"git",
"installation",
"mercurial",
"python"
] | stackoverflow_0002913913_dreamhost_git_installation_mercurial_python.txt |
Q:
In plain English, what are 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 seems like lots of buzzwords are being thrown around, which confuse more than they explain.
Are generic views similar to scaffolding in Ruby on Rails? The last bullet point in the intro seems to indicate this. Is that an accurate statement?
A:
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 with the RequestContext (which means the template has access to information on the request, like the current user, etc).
As a simple example, you can go from writing things like this:
# urls.py
url('^some-url/$', some_view)
# views.py
def some_view(request):
return render_to_response('template_name.html', context_instance=RequestContext(request))
To just this:
# urls.py
url('^some-url/$', direct_to_template, {'template': 'template_name.html'})
# views.py doesn't need any code for this view anymore
There are also more complicated generic views for common actions such as "showing a list of models", or "adding a model to the db".
Also, because generic views are just functions, you can call them within your own view functions to do "most of the work", when you need something that is a bit different from the generic cases.
A:
Generic views allow you to write much shorter code.
Compare:
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response, get_object_or_404, redirect
from myapp.models import Context
def edit(request, item_id):
object = get_object_or_404(Context, pk=item_id)
if request.method == 'POST':
form = ContextForm(request.POST, instance=object)
if form.is_valid():
form.save()
return redirect('myapp-context-index')
else:
form = ContextForm(instance=object)
return render_to_response("myapp/context/edit.html", {'object': object, 'form': form})
with:
from django.core import urlresolvers
from django.views.generic.create_update import update_object
from myapp.models import Context
def edit(request, item_id):
return update_object(request,
object_id=item_id,
form_class=ContextForm,
template_name="myapp/context/edit.html",
post_save_redirect=urlresolvers.reverse("myapp-context-index")
)
Like your normal views, they are just normal functions. It is possible to configure the view completely in the URLconf if you like, through I find this usage above a bit more clear.
As a BONUS, you also get:
Login authentication checks (pass login_required=True)
Success status message from django.contrib.messages.
Less code to check for errors.
A default ModelForm when you provide a model parameter instead of form_class.
The template_name has a default of "appname/model_form.html", but that's a bit too much for me.
Here is the form class they both share:
class ContextForm(forms.ModelForm):
"""The form for a context"""
class Meta:
model = Context
exclude = ('collection',)
def save(self, commit=True):
"""Overwritten save to force collection_id to a value"""
model = super(ContextForm, self).save(commit=False)
model.collection_id = 1
if commit:
model.save()
return model
A:
To answer your second question: no, generic views are not related to scaffolding in RoR. Scaffolding, as the name indicates, is akin to code generation. Generic views are something else.
My main usage of generic view is as a higher level replacement of the very basic render_to_response functions. This is how you could write a simple view with render_to_response:
def my_view(request):
return render_to_response('my_template.html')
But this is very basic! For example the template will not have access to the request context, unless you pass it on explicitly.
I thus prefer to use a generic view instead:
def my_view(request):
return direct_to_template(request, template='my_template.html')
Now the request context will be passed on! And that's just a start. Generic views come in handy when you want to display lists, or detail views, for instance. They will manage querying the database, and messaging the user, among other.
So generic views are high level functions to help you creating a response from a view.
| In plain English, what are 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 seems like lots of buzzwords are being thrown around, which confuse more than they explain.
Are generic views similar to scaffolding in Ruby on Rails? The last bullet point in the intro seems to indicate this. Is that an accurate statement?
| [
"Django generic views are just view functions (regular old python functions) that do things that are very common in web applications.\nDepending on the type of app you are building, they can save you from writing a lot of very simple views.\nFor example, the direct_to_template generic view simply renders a template with the RequestContext (which means the template has access to information on the request, like the current user, etc).\nAs a simple example, you can go from writing things like this:\n# urls.py\nurl('^some-url/$', some_view)\n\n# views.py\ndef some_view(request):\n return render_to_response('template_name.html', context_instance=RequestContext(request))\n\nTo just this:\n# urls.py\nurl('^some-url/$', direct_to_template, {'template': 'template_name.html'})\n\n# views.py doesn't need any code for this view anymore\n\nThere are also more complicated generic views for common actions such as \"showing a list of models\", or \"adding a model to the db\".\nAlso, because generic views are just functions, you can call them within your own view functions to do \"most of the work\", when you need something that is a bit different from the generic cases.\n",
"Generic views allow you to write much shorter code.\nCompare:\nfrom django.http import HttpResponse, HttpResponseRedirect, Http404\nfrom django.shortcuts import render_to_response, get_object_or_404, redirect\nfrom myapp.models import Context\n\ndef edit(request, item_id):\n object = get_object_or_404(Context, pk=item_id)\n\n if request.method == 'POST':\n form = ContextForm(request.POST, instance=object)\n if form.is_valid():\n form.save()\n return redirect('myapp-context-index')\n else:\n form = ContextForm(instance=object)\n\n return render_to_response(\"myapp/context/edit.html\", {'object': object, 'form': form})\n\nwith:\nfrom django.core import urlresolvers\nfrom django.views.generic.create_update import update_object\nfrom myapp.models import Context\n\ndef edit(request, item_id): \n return update_object(request,\n object_id=item_id, \n form_class=ContextForm, \n template_name=\"myapp/context/edit.html\",\n post_save_redirect=urlresolvers.reverse(\"myapp-context-index\")\n )\n\nLike your normal views, they are just normal functions. It is possible to configure the view completely in the URLconf if you like, through I find this usage above a bit more clear.\nAs a BONUS, you also get:\n\nLogin authentication checks (pass login_required=True)\nSuccess status message from django.contrib.messages.\nLess code to check for errors.\nA default ModelForm when you provide a model parameter instead of form_class.\n\nThe template_name has a default of \"appname/model_form.html\", but that's a bit too much for me.\n\nHere is the form class they both share:\nclass ContextForm(forms.ModelForm): \n \"\"\"The form for a context\"\"\"\n class Meta:\n model = Context\n exclude = ('collection',)\n\n def save(self, commit=True):\n \"\"\"Overwritten save to force collection_id to a value\"\"\"\n model = super(ContextForm, self).save(commit=False)\n model.collection_id = 1\n if commit:\n model.save()\n return model\n\n",
"To answer your second question: no, generic views are not related to scaffolding in RoR. Scaffolding, as the name indicates, is akin to code generation. Generic views are something else.\nMy main usage of generic view is as a higher level replacement of the very basic render_to_response functions. This is how you could write a simple view with render_to_response:\ndef my_view(request):\n return render_to_response('my_template.html')\n\nBut this is very basic! For example the template will not have access to the request context, unless you pass it on explicitly.\nI thus prefer to use a generic view instead:\ndef my_view(request):\n return direct_to_template(request, template='my_template.html')\n\nNow the request context will be passed on! And that's just a start. Generic views come in handy when you want to display lists, or detail views, for instance. They will manage querying the database, and messaging the user, among other.\nSo generic views are high level functions to help you creating a response from a view.\n"
] | [
20,
5,
2
] | [] | [] | [
"django",
"django_generic_views",
"python"
] | stackoverflow_0002437468_django_django_generic_views_python.txt |
Q:
How to build 64-bit Python on OS X 10.6 -- ONLY 64 bit, no Universal nonsense
I just want to build this on my development machine -- the binary install from Python.org is still 32 bits and installing extensions (MySQLdb, for example) is driving me nuts with trying to figure out the proper flags for each and every extension.
Clarification: I did NOT replace the system Python, I just installed the Python.org binary into its normal place at /Library/..., not /System/Library/....
Everything else seems to build 64 bit by default, and the default Python 2.6.1 was 64 bit (before I replaced it with the Python.org build figuring it was a direct replacement)`
I just want a 64 bit only build that will run on my one machine without any cruft.
Does anyone have a simple answer?
Thanks much, ssteinerX@gmail.com
A:
If you happen to be using MacPorts, it's as simple as specifying the variant that tells it not to compile Universal, like so:
sudo port install python26 -universal
You can view available variants using the variants command:
% port variants python26
python26 has the variants:
darwin: Platform variant, selected automatically
no_tkinter: Disable Tkinter support, which will break IDLE
ucs4: Enable support for UCS4
universal: Build for multiple architectures
As you can see, by default on 10.6 it builds the darwin variant, which builds ONLY x86_64:
% cd /opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin/
% file python2.6
python2.6: Mach-O 64-bit executable x86_64
Compare to default python binary, which is Universal:
% file /usr/bin/python
/usr/bin/python: Mach-O universal binary with 3 architectures
/usr/bin/python (for architecture x86_64): Mach-O 64-bit executable x86_64
/usr/bin/python (for architecture i386): Mach-O executable i386
/usr/bin/python (for architecture ppc7400): Mach-O executable ppc
If you're not using MacPorts, I suggest you consider it. It saves a lot of time and heartache having to manually configure and compile everything, and there is an excellent GUI interface called Porticus. All free and open source, of course!
p.s. Never replace or rename the original system binaries! As suggested in the comments by Ned Daily:
"Either manage access to the intended
python instance by changing the search
order in the PATH environment variable
or, if necessary, use an absolute path
like /opt/local/bin/python2.6".
A:
The simplest solution is pull everything you need from MacPorts:
$ sudo port selfupdate
$ sudo port install python26 +no_tkinter -universal py26-mysqldb -universal
That will install python2.6, the MySQLdb adapter, and the necessary MySQL client libraries. I suggest adding the no_tkinter variant unless you really need tkinter; there were some issues with the MacPorts version of Tk on 10.6.
EDIT: Note, the MacPorts Python will be installed as /opt/local/bin/python2.6. You may need to adjust your shell $PATH to ensure /opt/local/bin is on it before /usr/local/bin and /usr/bin. If you want /opt/local/bin/python to refer to the MacPorts python2.6, do the above and:
$ sudo port install python_select
$ sudo python_select python26
A:
Always macports... sheesh
This is what I did:
~: wget http://python.org/ftp/python/2.6.5/Python-2.6.5.tar.bz2
~: tar xjf Python-2.6.5.tar.bz2
~: cd Python-2.6.5
~: ./configure ./configure MACOSX_DEPLOYMENT_TARGET=10.6 --enable-framework --with-universal-archs="64-bit" CFLAGS="-arch x86_64" LDFLAGS="-arch x86_64"
~: make -j6
~: sudo make install
Might be a little redundant on the FLAGS stuff, but it worked.
A:
Once you do get 64-bit Python setup using the methods outlined above above, I also found this blog post by Aaron Meurer helpful for verifying that Python is in fact installed as 64-bit. The post also talks about running 64-bit Python alongside a 32-bit installation, which I guess is useful for some purposes.
| How to build 64-bit Python on OS X 10.6 -- ONLY 64 bit, no Universal nonsense | I just want to build this on my development machine -- the binary install from Python.org is still 32 bits and installing extensions (MySQLdb, for example) is driving me nuts with trying to figure out the proper flags for each and every extension.
Clarification: I did NOT replace the system Python, I just installed the Python.org binary into its normal place at /Library/..., not /System/Library/....
Everything else seems to build 64 bit by default, and the default Python 2.6.1 was 64 bit (before I replaced it with the Python.org build figuring it was a direct replacement)`
I just want a 64 bit only build that will run on my one machine without any cruft.
Does anyone have a simple answer?
Thanks much, ssteinerX@gmail.com
| [
"If you happen to be using MacPorts, it's as simple as specifying the variant that tells it not to compile Universal, like so:\nsudo port install python26 -universal\n\nYou can view available variants using the variants command:\n% port variants python26 \npython26 has the variants:\n darwin: Platform variant, selected automatically\n no_tkinter: Disable Tkinter support, which will break IDLE\n ucs4: Enable support for UCS4\n universal: Build for multiple architectures\n\nAs you can see, by default on 10.6 it builds the darwin variant, which builds ONLY x86_64:\n% cd /opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin/\n% file python2.6\npython2.6: Mach-O 64-bit executable x86_64\n\nCompare to default python binary, which is Universal:\n% file /usr/bin/python\n/usr/bin/python: Mach-O universal binary with 3 architectures\n/usr/bin/python (for architecture x86_64): Mach-O 64-bit executable x86_64\n/usr/bin/python (for architecture i386): Mach-O executable i386\n/usr/bin/python (for architecture ppc7400): Mach-O executable ppc\n\nIf you're not using MacPorts, I suggest you consider it. It saves a lot of time and heartache having to manually configure and compile everything, and there is an excellent GUI interface called Porticus. All free and open source, of course!\np.s. Never replace or rename the original system binaries! As suggested in the comments by Ned Daily: \n\n\"Either manage access to the intended\n python instance by changing the search\n order in the PATH environment variable\n or, if necessary, use an absolute path\n like /opt/local/bin/python2.6\".\n\n",
"The simplest solution is pull everything you need from MacPorts:\n$ sudo port selfupdate\n$ sudo port install python26 +no_tkinter -universal py26-mysqldb -universal\n\nThat will install python2.6, the MySQLdb adapter, and the necessary MySQL client libraries. I suggest adding the no_tkinter variant unless you really need tkinter; there were some issues with the MacPorts version of Tk on 10.6.\nEDIT: Note, the MacPorts Python will be installed as /opt/local/bin/python2.6. You may need to adjust your shell $PATH to ensure /opt/local/bin is on it before /usr/local/bin and /usr/bin. If you want /opt/local/bin/python to refer to the MacPorts python2.6, do the above and:\n$ sudo port install python_select\n$ sudo python_select python26\n\n",
"Always macports... sheesh\nThis is what I did:\n~: wget http://python.org/ftp/python/2.6.5/Python-2.6.5.tar.bz2\n~: tar xjf Python-2.6.5.tar.bz2\n~: cd Python-2.6.5\n~: ./configure ./configure MACOSX_DEPLOYMENT_TARGET=10.6 --enable-framework --with-universal-archs=\"64-bit\" CFLAGS=\"-arch x86_64\" LDFLAGS=\"-arch x86_64\"\n~: make -j6\n~: sudo make install\n\nMight be a little redundant on the FLAGS stuff, but it worked.\n",
"Once you do get 64-bit Python setup using the methods outlined above above, I also found this blog post by Aaron Meurer helpful for verifying that Python is in fact installed as 64-bit. The post also talks about running 64-bit Python alongside a 32-bit installation, which I guess is useful for some purposes.\n"
] | [
11,
5,
5,
3
] | [] | [] | [
"64_bit",
"macos",
"osx_snow_leopard",
"python",
"x86_64"
] | stackoverflow_0002111283_64_bit_macos_osx_snow_leopard_python_x86_64.txt |
Q:
SQLAlchemy automatically converts str to unicode on commit
When inserting an object into a database with SQLAlchemy, all it's properties that correspond to String() columns are automatically transformed from <type 'str'> to <type 'unicode'>. Is there a way to prevent this behavior?
Here is the code:
from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData
from sqlalchemy.orm import mapper, sessionmaker
engine = create_engine('sqlite:///:memory:', echo=False)
metadata = MetaData()
table = Table('projects', metadata,
Column('id', Integer, primary_key=True),
Column('name', String(50))
)
class Project(object):
def __init__(self, name):
self.name = name
mapper(Project, table)
metadata.create_all(engine)
session = sessionmaker(bind=engine)()
project = Project("Lorem ipsum")
print(type(project.name))
session.add(project)
session.commit()
print(type(project.name))
And here is the output:
<type 'str'>
<type 'unicode'>
I know I should probably just work with unicode, but this would involve digging through some third-party code and I don't have the Python skills for that yet :)
A:
Actually, there is a way to do that. Just execute this line of code after creating engine:
engine.raw_connection().connection.text_factory = str
A:
Unfortunately, you are out of luck and this does not seem to work with sqlite. A quote from SQLAlchemy 0.6.2 Documentation - SQLite - Unicode:
In contrast to SQLAlchemy’s active
handling of date and time types for
pysqlite, pysqlite’s default behavior
regarding Unicode is that all strings
are returned as Python unicode objects
in all cases. So even if the Unicode
type is not used, you will still
always receive unicode data back from
a result set. It is strongly
recommended that you do use the
Unicode type to represent strings,
since it will raise a warning if a
non-unicode Python string is passed
from the user application. Mixing the
usage of non-unicode objects with
returned unicode objects can quickly
create confusion, particularly when
using the ORM as internal data is not
always represented by an actual
database result string.
| SQLAlchemy automatically converts str to unicode on commit | When inserting an object into a database with SQLAlchemy, all it's properties that correspond to String() columns are automatically transformed from <type 'str'> to <type 'unicode'>. Is there a way to prevent this behavior?
Here is the code:
from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData
from sqlalchemy.orm import mapper, sessionmaker
engine = create_engine('sqlite:///:memory:', echo=False)
metadata = MetaData()
table = Table('projects', metadata,
Column('id', Integer, primary_key=True),
Column('name', String(50))
)
class Project(object):
def __init__(self, name):
self.name = name
mapper(Project, table)
metadata.create_all(engine)
session = sessionmaker(bind=engine)()
project = Project("Lorem ipsum")
print(type(project.name))
session.add(project)
session.commit()
print(type(project.name))
And here is the output:
<type 'str'>
<type 'unicode'>
I know I should probably just work with unicode, but this would involve digging through some third-party code and I don't have the Python skills for that yet :)
| [
"Actually, there is a way to do that. Just execute this line of code after creating engine:\nengine.raw_connection().connection.text_factory = str\n",
"Unfortunately, you are out of luck and this does not seem to work with sqlite. A quote from SQLAlchemy 0.6.2 Documentation - SQLite - Unicode:\n\nIn contrast to SQLAlchemy’s active\n handling of date and time types for\n pysqlite, pysqlite’s default behavior\n regarding Unicode is that all strings\n are returned as Python unicode objects\n in all cases. So even if the Unicode \n type is not used, you will still\n always receive unicode data back from\n a result set. It is strongly\n recommended that you do use the\n Unicode type to represent strings,\n since it will raise a warning if a\n non-unicode Python string is passed\n from the user application. Mixing the\n usage of non-unicode objects with\n returned unicode objects can quickly\n create confusion, particularly when\n using the ORM as internal data is not\n always represented by an actual\n database result string.\n\n"
] | [
12,
6
] | [] | [] | [
"python",
"sqlalchemy",
"unicode"
] | stackoverflow_0003033741_python_sqlalchemy_unicode.txt |
Q:
Interpreter more strict
Today, i lost a lot of time fixing a stupid error in my code. Very simplified, the problem was this:
def f():
return 2
2 == f
I forgot to write the parenthesis in the sentence, so I compared a pointer function with a number.
Ok, my question:
Is there any way to change the interpreter to be more stricted with the code? Show more warnings for example...
Thanks ^^
A:
Python is a dynamic language, and the construct you have shown is completely valid (a function is not equal to 2). There is no strict mode.
A:
The interpreter shouldn't issue a warning. f could be reassigned to an integer and then the check would totally makes sense:
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
... return 2
...
>>> 2 == f
False
>>> f = 2
>>> 2 == f
True
A:
One of the disadvantages of working with a dynamically typed language is that the language environment has very little or no information about the types of things when it sees a statement, so it can issue no warning when it sees it, only when the statement is executed.
For various reasons it's very convenient for all types to be able to be compared to all others for equality. It makes heterogeneous containers much easier to write. So comparing a function to an integer is a defined thing to do, and since that can happen in so many useful cases, the interpreter can't really give you a warning about it at runtime. And while the construct is questionable, it can't give you a warning when it sees the statement (as opposed to executing it) because then it doesn't have the necessary type information to issue the warning.
A:
You are comparing a function to an integer, which is perfectly valid. In this case the condition will just always be False as it will compare the object identities. In Python, functions never know what types they are getting, and will just compare them blindly, this allows for polymorphic behaviour. There is no way to disable this, besides switching to a statically typed language.
| Interpreter more strict | Today, i lost a lot of time fixing a stupid error in my code. Very simplified, the problem was this:
def f():
return 2
2 == f
I forgot to write the parenthesis in the sentence, so I compared a pointer function with a number.
Ok, my question:
Is there any way to change the interpreter to be more stricted with the code? Show more warnings for example...
Thanks ^^
| [
"Python is a dynamic language, and the construct you have shown is completely valid (a function is not equal to 2). There is no strict mode.\n",
"The interpreter shouldn't issue a warning. f could be reassigned to an integer and then the check would totally makes sense:\nPython 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) \n[GCC 4.3.3] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> def f():\n... return 2\n... \n>>> 2 == f\nFalse\n>>> f = 2\n>>> 2 == f\nTrue\n\n",
"One of the disadvantages of working with a dynamically typed language is that the language environment has very little or no information about the types of things when it sees a statement, so it can issue no warning when it sees it, only when the statement is executed.\nFor various reasons it's very convenient for all types to be able to be compared to all others for equality. It makes heterogeneous containers much easier to write. So comparing a function to an integer is a defined thing to do, and since that can happen in so many useful cases, the interpreter can't really give you a warning about it at runtime. And while the construct is questionable, it can't give you a warning when it sees the statement (as opposed to executing it) because then it doesn't have the necessary type information to issue the warning.\n",
"You are comparing a function to an integer, which is perfectly valid. In this case the condition will just always be False as it will compare the object identities. In Python, functions never know what types they are getting, and will just compare them blindly, this allows for polymorphic behaviour. There is no way to disable this, besides switching to a statically typed language.\n"
] | [
5,
3,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003034008_python.txt |
Q:
Convert Python to Haskell / Lambda calculus
What is the Python code in Haskell and Lambda calculus?
def f1():
x = 77
def f2():
print x
f2
f1
My attempt in lambda calculus
\x. 77 (\x.x)
A:
In Haskell:
f1 = f2
where x = 77
f2 = print x
Refactoring, since IO just confuses the issue:
f1 = f2
where x = 77
f2 = x
Refactoring:
f1 = x
where x = 77
Refactoring, since you want the variable?
f1 = (\x -> x) 77
Beta reduce:
f1 = 77
And you have your program in Haskell.
Lambda calculus doesn't have numeric literals (unlike Haskell), so we must use Church numerals.
So compiling "77" to lambda calculus:
f1 = \f.\x. f (f (f (f ( ... ) x)))
And there's your Python program in Lambda Calculus.
A:
Haskell:
f1 :: IO ()
f1 = let x = 77
f2 = print x
in f2
main :: IO ()
main = f1
Or to be more like your lambda calculus:
f1 :: Int
f1 = let f2 = x
x = 77
in f2
main :: IO ()
main = print f1
A:
I don't know python, so I could be completely wrong, but this is my Haskell interpretation.
f1 = let x = 77 in show x
Or, since you've got a constant there
f1 = show 77
A:
In lambda calculus:
λprint. print 77
| Convert Python to Haskell / Lambda calculus | What is the Python code in Haskell and Lambda calculus?
def f1():
x = 77
def f2():
print x
f2
f1
My attempt in lambda calculus
\x. 77 (\x.x)
| [
"In Haskell:\nf1 = f2\n where x = 77\n f2 = print x\n\nRefactoring, since IO just confuses the issue:\nf1 = f2\n where x = 77\n f2 = x\n\nRefactoring:\nf1 = x\n where x = 77\n\nRefactoring, since you want the variable?\nf1 = (\\x -> x) 77\n\nBeta reduce:\nf1 = 77\n\nAnd you have your program in Haskell.\nLambda calculus doesn't have numeric literals (unlike Haskell), so we must use Church numerals.\nSo compiling \"77\" to lambda calculus:\nf1 = \\f.\\x. f (f (f (f ( ... ) x)))\n\nAnd there's your Python program in Lambda Calculus.\n",
"Haskell:\nf1 :: IO ()\nf1 = let x = 77\n f2 = print x\n in f2\n\nmain :: IO ()\nmain = f1\n\nOr to be more like your lambda calculus:\nf1 :: Int\nf1 = let f2 = x\n x = 77\n in f2\n\nmain :: IO ()\nmain = print f1\n\n",
"I don't know python, so I could be completely wrong, but this is my Haskell interpretation.\nf1 = let x = 77 in show x\n\nOr, since you've got a constant there\nf1 = show 77\n\n",
"In lambda calculus:\nλprint. print 77\n\n"
] | [
8,
3,
1,
1
] | [] | [] | [
"haskell",
"lambda",
"lambda_calculus",
"python"
] | stackoverflow_0001814061_haskell_lambda_lambda_calculus_python.txt |
Q:
Rapid spectral analysis of audio file using Python 2.6?
What I want to do is to have a subroutine that analyses every 200 milliseconds of a sound file which it is given and spits out the frequency intensity value (from 0 to 1 as a float) of a specific frequency range into an array which I later save. This value then goes on to be used as the opacity value for a graphic which is supposed to 'strobe' to the audio file.
The problem is, I have never ventured into audio analysis before and have no clue where to start. I have looked pymedia and scipy/numpy thinking I would be able to use FFT in order to achieve this, but I am not really sure how I would manipulate this data to end up with the desired result. The documentation on the SpectrAnalyzer class of pymedia is virtually non-existant and the examples on the website do not actually work with the latest release of the library - which isn't exactly making my life easier.
How would I go about starting this project? I am at a complete loss as to what libraries I should even be using.
A:
You will first need to understand how sampling works, then you should use Scipy FFT routines (they are pretty fast) in order spit out frequency intensity values, then you can use Matplotlib to plot such graphics.
See here for an article about using Python to analyze sound files and here is a similar question about FFT and Spectograms in Python.
| Rapid spectral analysis of audio file using Python 2.6? | What I want to do is to have a subroutine that analyses every 200 milliseconds of a sound file which it is given and spits out the frequency intensity value (from 0 to 1 as a float) of a specific frequency range into an array which I later save. This value then goes on to be used as the opacity value for a graphic which is supposed to 'strobe' to the audio file.
The problem is, I have never ventured into audio analysis before and have no clue where to start. I have looked pymedia and scipy/numpy thinking I would be able to use FFT in order to achieve this, but I am not really sure how I would manipulate this data to end up with the desired result. The documentation on the SpectrAnalyzer class of pymedia is virtually non-existant and the examples on the website do not actually work with the latest release of the library - which isn't exactly making my life easier.
How would I go about starting this project? I am at a complete loss as to what libraries I should even be using.
| [
"You will first need to understand how sampling works, then you should use Scipy FFT routines (they are pretty fast) in order spit out frequency intensity values, then you can use Matplotlib to plot such graphics.\nSee here for an article about using Python to analyze sound files and here is a similar question about FFT and Spectograms in Python.\n"
] | [
3
] | [] | [] | [
"audio_analysis",
"fft",
"python"
] | stackoverflow_0003032472_audio_analysis_fft_python.txt |
Q:
Accessing an image from a webpage in PyQt4 QtWebkit
If a page has fully loaded on a QWebView, how can I get the data for a certain image (probably through the dom?)
A:
I'll try taking a stab at this:
If you want to get the url of an image using jQuery you could use an approach like this:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
app = QApplication(sys.argv)
web = QWebView()
web.load(QUrl("http://google.com"))
frame = web.page().mainFrame()
web.show()
def loadFinished(ok):
print 'loaded'
frame.evaluateJavaScript("""
//this is a hack to load an external javascript script
//credit to Vincent Robert from http://stackoverflow.com/questions/756382/bookmarklet-wait-until-javascript-is-loaded
function loadScript(url, callback)
{
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = url;
// Attach handlers
var done = false;
script.onload = script.onreadystatechange = function()
{
if( !done && ( !this.readyState
|| this.readyState == "loaded"
|| this.readyState == "complete") )
{
done = true;
// Continue your code
callback();
}
};
head.appendChild(script);
}
// This code loads jQuery and executes some code when jQuery is loaded, using above trick
loadScript("http://code.jquery.com/jquery-latest.js", function(){
//we can inject an image into the page like this:
$(document.body).append('<img src="http://catsplanet.files.wordpress.com/2009/08/kitten_01.jpg" id="kitten"/>');
//you can get the url before the image loads like so:
//detectedKittenImageUrl = $('#kitten').attr('src');
//alert('detectedKittenImageUrl = ' + detectedKittenImageUrl);
//but this is how to get the url after it is loaded, by using jquery to bind to it's load function:
$('#kitten').bind('load',function(){
//the injected image has loaded
detectedKittenImageUrl = $('#kitten').attr('src');
alert('detectedKittenImageUrl = ' + detectedKittenImageUrl);
//Google's logo image url is provided by css as opposed to using an IMG tag:
//it has probabled loaded befor the kitten image which was injected after load
//we can get the url of Google's logo like so:
detectedGoogleLogoImageUrl = $('#logo').css('background-image');
alert('detectedGoogleLogoImageUrl = ' + detectedGoogleLogoImageUrl);
});
});
""")
app.connect(web, SIGNAL("loadFinished(bool)"), loadFinished)
sys.exit(app.exec_())
If you didn't want to load jquery from the web each time you could download jquery then inject like this:
jQuerySource = open('jquery.min.js').read()
frame.evaluateJavaScript(jQuerySource)
you could also not use jQuery at all, but it often makes manipulation easier, depending on what else you want to do.
If you want to get the image content as a bitmap not a url, it MAY be possible using a html canvas object, I'm not sure if you will run into cross-domain security problems.
Another approach would be to use pyQT to get the image as it appears. If you have a PNG with alpha-transparency, this would be more complex though, but for an opaque JPEG, for example it would be easier.
You could Google around for some webpage screenshot code for how to do that or you could download from the found url in Python.
Once you had the url variable in Javascript, you would probably have to use the cross-the-boarder technique featured on this great slideshow to get the variable into Python for downloading.
http://www.sivachandran.in/index.php/blogs/web-automation-using-pyqt4-and-jquery may be useful example code too.
| Accessing an image from a webpage in PyQt4 QtWebkit | If a page has fully loaded on a QWebView, how can I get the data for a certain image (probably through the dom?)
| [
"I'll try taking a stab at this:\nIf you want to get the url of an image using jQuery you could use an approach like this:\nimport sys\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtWebKit import *\napp = QApplication(sys.argv)\nweb = QWebView()\nweb.load(QUrl(\"http://google.com\"))\nframe = web.page().mainFrame()\n\nweb.show()\n\ndef loadFinished(ok):\n print 'loaded'\n frame.evaluateJavaScript(\"\"\"\n //this is a hack to load an external javascript script \n //credit to Vincent Robert from http://stackoverflow.com/questions/756382/bookmarklet-wait-until-javascript-is-loaded\n function loadScript(url, callback)\n{\n var head = document.getElementsByTagName(\"head\")[0];\n var script = document.createElement(\"script\");\n script.src = url;\n // Attach handlers\n var done = false;\n script.onload = script.onreadystatechange = function()\n {\n if( !done && ( !this.readyState \n || this.readyState == \"loaded\" \n || this.readyState == \"complete\") )\n {\n done = true;\n // Continue your code\n callback();\n }\n };\n\n head.appendChild(script);\n}\n\n// This code loads jQuery and executes some code when jQuery is loaded, using above trick\nloadScript(\"http://code.jquery.com/jquery-latest.js\", function(){\n //we can inject an image into the page like this:\n $(document.body).append('<img src=\"http://catsplanet.files.wordpress.com/2009/08/kitten_01.jpg\" id=\"kitten\"/>');\n //you can get the url before the image loads like so:\n //detectedKittenImageUrl = $('#kitten').attr('src');\n //alert('detectedKittenImageUrl = ' + detectedKittenImageUrl);\n //but this is how to get the url after it is loaded, by using jquery to bind to it's load function:\n $('#kitten').bind('load',function(){\n //the injected image has loaded\n detectedKittenImageUrl = $('#kitten').attr('src');\n alert('detectedKittenImageUrl = ' + detectedKittenImageUrl);\n //Google's logo image url is provided by css as opposed to using an IMG tag:\n //it has probabled loaded befor the kitten image which was injected after load\n //we can get the url of Google's logo like so:\n detectedGoogleLogoImageUrl = $('#logo').css('background-image');\n alert('detectedGoogleLogoImageUrl = ' + detectedGoogleLogoImageUrl);\n });\n\n});\n\n \"\"\") \n\napp.connect(web, SIGNAL(\"loadFinished(bool)\"), loadFinished)\n\nsys.exit(app.exec_())\n\nIf you didn't want to load jquery from the web each time you could download jquery then inject like this:\njQuerySource = open('jquery.min.js').read()\nframe.evaluateJavaScript(jQuerySource)\n\nyou could also not use jQuery at all, but it often makes manipulation easier, depending on what else you want to do.\nIf you want to get the image content as a bitmap not a url, it MAY be possible using a html canvas object, I'm not sure if you will run into cross-domain security problems. \nAnother approach would be to use pyQT to get the image as it appears. If you have a PNG with alpha-transparency, this would be more complex though, but for an opaque JPEG, for example it would be easier.\nYou could Google around for some webpage screenshot code for how to do that or you could download from the found url in Python.\nOnce you had the url variable in Javascript, you would probably have to use the cross-the-boarder technique featured on this great slideshow to get the variable into Python for downloading.\nhttp://www.sivachandran.in/index.php/blogs/web-automation-using-pyqt4-and-jquery may be useful example code too.\n"
] | [
1
] | [] | [] | [
"pyqt4",
"python",
"qtwebkit"
] | stackoverflow_0002793641_pyqt4_python_qtwebkit.txt |
Q:
Can a python view template be made to be 'safe/secure' if I make it user editable?
Say I need to have a templating system where a user can edit it online using an online editor.
So they can put if tags, looping tags etc., but ONLY for specific objects that I want to inject into the template.
Can this be made to be safe from security issues?
i.e. them somehow outputing sql connection string information or scripting things outside of the allowable tags and injected objects.
A:
Yes, use a template engine that has sandboxing features, like jinja2
| Can a python view template be made to be 'safe/secure' if I make it user editable? | Say I need to have a templating system where a user can edit it online using an online editor.
So they can put if tags, looping tags etc., but ONLY for specific objects that I want to inject into the template.
Can this be made to be safe from security issues?
i.e. them somehow outputing sql connection string information or scripting things outside of the allowable tags and injected objects.
| [
"Yes, use a template engine that has sandboxing features, like jinja2\n"
] | [
3
] | [] | [] | [
"django",
"python",
"security",
"templating"
] | stackoverflow_0003034133_django_python_security_templating.txt |
Q:
PyQt4 plugin in c++ application
How is it posible to load python script as plugin in qt based application?
The basic idea would be to make a class in c++
class b
{
virtual void method1();
virtual void method2();
}
and 'somehow' inherit it in python like
class c(b):
def method1:
#do something
def method2:
#do something
I need to be able to modify the gui from python( add buttons to some widgets made in c++ with qt ). Basicaly something similiar to (gedit, blender, etc) plugin architecture with qt
A:
I think you'll first need to expose your C++ methods using Python C API or by using Boost::Python or Swig and then embed Python into your application in order to execute customized Python scripts.
| PyQt4 plugin in c++ application | How is it posible to load python script as plugin in qt based application?
The basic idea would be to make a class in c++
class b
{
virtual void method1();
virtual void method2();
}
and 'somehow' inherit it in python like
class c(b):
def method1:
#do something
def method2:
#do something
I need to be able to modify the gui from python( add buttons to some widgets made in c++ with qt ). Basicaly something similiar to (gedit, blender, etc) plugin architecture with qt
| [
"I think you'll first need to expose your C++ methods using Python C API or by using Boost::Python or Swig and then embed Python into your application in order to execute customized Python scripts.\n"
] | [
1
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0003026309_c++_python.txt |
Q:
Python/YACC: Resolving a shift/reduce conflict
I'm using PLY. Here is one of my states from parser.out:
state 3
(5) course_data -> course .
(6) course_data -> course . course_list_tail
(3) or_phrase -> course . OR_CONJ COURSE_NUMBER
(7) course_list_tail -> . , COURSE_NUMBER
(8) course_list_tail -> . , COURSE_NUMBER course_list_tail
! shift/reduce conflict for OR_CONJ resolved as shift
$end reduce using rule 5 (course_data -> course .)
OR_CONJ shift and go to state 7
, shift and go to state 8
! OR_CONJ [ reduce using rule 5 (course_data -> course .) ]
course_list_tail shift and go to state 9
I want to resolve this as:
if OR_CONJ is followed by COURSE_NUMBER:
shift and go to state 7
else:
reduce using rule 5 (course_data -> course .)
How can I fix my parser file to reflect this? Do I need to handle a syntax error by backtracking and trying a different rule?
The documentation says:
These values are then used to attach a
numerical precedence value and
associativity direction to each
grammar rule. This is always
determined by looking at the
precedence of the right-most terminal
symbol.
What if the rule has no terminals?
UPDATE: The complete grammar:
Grammar
Rule 0 S' -> statement
Rule 1 statement -> course_data
Rule 2 or_phrase -> statement OR_CONJ statement
Rule 3 or_phrase -> course OR_CONJ COURSE_NUMBER
Rule 4 statement -> or_phrase
Rule 5 course_data -> course
Rule 6 course_data -> course course_list_tail
Rule 7 course_list_tail -> , COURSE_NUMBER
Rule 8 course_list_tail -> , COURSE_NUMBER course_list_tail
Rule 9 course -> DEPT_CODE COURSE_NUMBER
A:
Your basic problem is that you need two tokens of lookahead to do what you want -- when the input seen so far is a course and the lookahead is a OR_CONJ you don't know whether to reduce the course to a course_data or shift without looking ahead two tokens to the token after the OR_CONJ. There are a number of ways you can deal with this
use an LR(2) or LR(k) or GLR parser generator -- any can deal with this.
use a lexer hack to do the lookahead -- basically have the lexer return two different OR_CONJ tokens depending on whether the following token is a COURSE_NUMBER or not.
factor the grammar to get rid of the conflict, which may result in a grammar that parses something slightly different from what you want (need some extra post-parse checks to reject some invalid constructs) and will generally make the grammar much harder to understand.
Note that your grammar as given is also ambiguous related to which way three or more courses connected in a single statement associate. This is easily fixed by rewriting the grammar into a clearer left-recursive form:
Rule 1 statement -> course
Rule 2 statement -> statement OR_CONJ course
Rule 3 course -> DEPT_CODE course_list
Rule 4 course -> DEPT CODE course_list OR_CONJ COURSE_NUMBER
Rule 5 course_list -> COURSE_NUMBER
Rule 6 course_list -> course_list , COURSE_NUMBER
This could also be rewritten as right-recursive for an LL parser generator, but it still has the 2-token lookahead problem. One way of refactoring it to make that go away would be to make COURSE_NUMBER by itself a valid course and recombine it with the previous course in a post-pass (or give an error if its the first course in a statement). Then rule 4 becomes:
Rule 4 course -> COURSE_NUMBER
and you have no conflicts.
| Python/YACC: Resolving a shift/reduce conflict | I'm using PLY. Here is one of my states from parser.out:
state 3
(5) course_data -> course .
(6) course_data -> course . course_list_tail
(3) or_phrase -> course . OR_CONJ COURSE_NUMBER
(7) course_list_tail -> . , COURSE_NUMBER
(8) course_list_tail -> . , COURSE_NUMBER course_list_tail
! shift/reduce conflict for OR_CONJ resolved as shift
$end reduce using rule 5 (course_data -> course .)
OR_CONJ shift and go to state 7
, shift and go to state 8
! OR_CONJ [ reduce using rule 5 (course_data -> course .) ]
course_list_tail shift and go to state 9
I want to resolve this as:
if OR_CONJ is followed by COURSE_NUMBER:
shift and go to state 7
else:
reduce using rule 5 (course_data -> course .)
How can I fix my parser file to reflect this? Do I need to handle a syntax error by backtracking and trying a different rule?
The documentation says:
These values are then used to attach a
numerical precedence value and
associativity direction to each
grammar rule. This is always
determined by looking at the
precedence of the right-most terminal
symbol.
What if the rule has no terminals?
UPDATE: The complete grammar:
Grammar
Rule 0 S' -> statement
Rule 1 statement -> course_data
Rule 2 or_phrase -> statement OR_CONJ statement
Rule 3 or_phrase -> course OR_CONJ COURSE_NUMBER
Rule 4 statement -> or_phrase
Rule 5 course_data -> course
Rule 6 course_data -> course course_list_tail
Rule 7 course_list_tail -> , COURSE_NUMBER
Rule 8 course_list_tail -> , COURSE_NUMBER course_list_tail
Rule 9 course -> DEPT_CODE COURSE_NUMBER
| [
"Your basic problem is that you need two tokens of lookahead to do what you want -- when the input seen so far is a course and the lookahead is a OR_CONJ you don't know whether to reduce the course to a course_data or shift without looking ahead two tokens to the token after the OR_CONJ. There are a number of ways you can deal with this\n\nuse an LR(2) or LR(k) or GLR parser generator -- any can deal with this.\nuse a lexer hack to do the lookahead -- basically have the lexer return two different OR_CONJ tokens depending on whether the following token is a COURSE_NUMBER or not.\nfactor the grammar to get rid of the conflict, which may result in a grammar that parses something slightly different from what you want (need some extra post-parse checks to reject some invalid constructs) and will generally make the grammar much harder to understand.\n\nNote that your grammar as given is also ambiguous related to which way three or more courses connected in a single statement associate. This is easily fixed by rewriting the grammar into a clearer left-recursive form:\nRule 1 statement -> course\nRule 2 statement -> statement OR_CONJ course\nRule 3 course -> DEPT_CODE course_list\nRule 4 course -> DEPT CODE course_list OR_CONJ COURSE_NUMBER\nRule 5 course_list -> COURSE_NUMBER\nRule 6 course_list -> course_list , COURSE_NUMBER\n\nThis could also be rewritten as right-recursive for an LL parser generator, but it still has the 2-token lookahead problem. One way of refactoring it to make that go away would be to make COURSE_NUMBER by itself a valid course and recombine it with the previous course in a post-pass (or give an error if its the first course in a statement). Then rule 4 becomes:\nRule 4 course -> COURSE_NUMBER\n\nand you have no conflicts. \n"
] | [
4
] | [] | [] | [
"parsing",
"ply",
"python",
"yacc"
] | stackoverflow_0002939888_parsing_ply_python_yacc.txt |
Q:
Fastest python/C++ multimedia library
I'm using pyglet for my OpenGL based game but is it the fastest library out there which has a python wrapper? I could create a C++ extension and use any C++ multimedia library. Are there any C++ libraries that are worth investing time into or is it not worth the extra work?
Thank you.
A:
Pygame is a python wrapper for the SDL library, which is widely used in game developing and provides OpenGL, sound and input management. To my knowledge at least SDL is quite fast, and the wrapper just encapsulates the binary functionality for python usage. Depending on your usage you can accomplish high speed.
A:
I'd say (Py)SFML but I'm not sure of what your multimedia requirements are.
| Fastest python/C++ multimedia library | I'm using pyglet for my OpenGL based game but is it the fastest library out there which has a python wrapper? I could create a C++ extension and use any C++ multimedia library. Are there any C++ libraries that are worth investing time into or is it not worth the extra work?
Thank you.
| [
"Pygame is a python wrapper for the SDL library, which is widely used in game developing and provides OpenGL, sound and input management. To my knowledge at least SDL is quite fast, and the wrapper just encapsulates the binary functionality for python usage. Depending on your usage you can accomplish high speed.\n",
"I'd say (Py)SFML but I'm not sure of what your multimedia requirements are.\n"
] | [
1,
0
] | [] | [] | [
"c++",
"multimedia",
"opengl",
"python"
] | stackoverflow_0003033969_c++_multimedia_opengl_python.txt |
Q:
What's going on here? Repeating rows in random list of lists
I expected to get a grid of unique random numbers. Instead each row is the same sequence of numbers. What's going on here?
from pprint import pprint
from random import random
nrows, ncols = 5, 5
grid = [[0] * ncols] * nrows
for r in range(nrows):
for c in range(ncols):
grid[r][c] = int(random() * 100)
pprint(grid)
Example output:
[[64, 82, 90, 69, 36],
[64, 82, 90, 69, 36],
[64, 82, 90, 69, 36],
[64, 82, 90, 69, 36],
[64, 82, 90, 69, 36]]
A:
I think that this is because python uses a weak copy of the list when you call
grid = [...] * nrows
I tried hard coding the list and it worked correctly:
>>> grid = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]
>>> for r in range(nrows):
... for c in range(ncols):
... grid[r][c] = int(random() * 100)
...
>>> pprint(grid)
[[67, 40, 41, 50, 92],
[26, 42, 64, 77, 77],
[65, 67, 88, 77, 76],
[36, 21, 41, 29, 25],
[98, 77, 38, 40, 96]]
This tells me that when python copies the list 5 times, all it is doing is storing 5 pointers to your first list - then, when you change the values in that list, you are actually just changing the value in the first list and it gets reflected in all lists which point to that one.
Using your method, you can't update all the list independently.
Instead, I would suggest changing your list generation line to look more like this:
grid = [[0] * ncols for row in range(ncols)]
That should create 5 independent lists for you.
| What's going on here? Repeating rows in random list of lists | I expected to get a grid of unique random numbers. Instead each row is the same sequence of numbers. What's going on here?
from pprint import pprint
from random import random
nrows, ncols = 5, 5
grid = [[0] * ncols] * nrows
for r in range(nrows):
for c in range(ncols):
grid[r][c] = int(random() * 100)
pprint(grid)
Example output:
[[64, 82, 90, 69, 36],
[64, 82, 90, 69, 36],
[64, 82, 90, 69, 36],
[64, 82, 90, 69, 36],
[64, 82, 90, 69, 36]]
| [
"I think that this is because python uses a weak copy of the list when you call\ngrid = [...] * nrows\n\nI tried hard coding the list and it worked correctly:\n>>> grid = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]\n>>> for r in range(nrows):\n... for c in range(ncols):\n... grid[r][c] = int(random() * 100)\n... \n>>> pprint(grid)\n[[67, 40, 41, 50, 92],\n [26, 42, 64, 77, 77],\n [65, 67, 88, 77, 76],\n [36, 21, 41, 29, 25],\n [98, 77, 38, 40, 96]]\n\nThis tells me that when python copies the list 5 times, all it is doing is storing 5 pointers to your first list - then, when you change the values in that list, you are actually just changing the value in the first list and it gets reflected in all lists which point to that one.\nUsing your method, you can't update all the list independently.\nInstead, I would suggest changing your list generation line to look more like this:\ngrid = [[0] * ncols for row in range(ncols)]\n\nThat should create 5 independent lists for you.\n"
] | [
2
] | [] | [] | [
"multidimensional_array",
"python",
"random"
] | stackoverflow_0003034469_multidimensional_array_python_random.txt |
Q:
how to set a fixed color bar for pcolor in python matplotlib?
I am using pcolor with a custom color map to plot a matrix of values. I set my color map so that low values are white and high values are red, as shown below. All of my matrices have values between 0 and 20 (inclusive) and I'd like 20 to always be pure red and 0 to always be pure white, even if the matrix has values that don't span the entire range. For example, if my matrix only has values between 2 and 7, I don't want it to plot 2 as white and 7 as red, but rather color it as if the range is still 0 to 20. How can I do this? I tried using the "ticks=" option of colorbar but it did not work.
Here is my current code (assume "my_matrix" contains the values to be plotted):
cdict = {'red': ((0.0, 1.0, 1.0),
(0.5, 1.0, 1.0),
(1.0, 1.0, 1.0)),
'green': ((0.0, 1.0, 1.0),
(0.5, 1.0, 1.0),
(1.0, 0.0, 0.0)),
'blue': ((0.0, 1.0, 1.0),
(0.5, 1.0, 1.0),
(1.0, 0.0, 0.0))}
my_cmap = matplotlib.colors.LinearSegmentedColormap('my_colormap', cdict, 256)
colored_matrix = plt.pcolor(my_matrix, cmap=my_cmap)
plt.colorbar(colored_matrix, ticks=[0, 5, 10, 15, 20])
any idea how I can fix this to get the right result? thanks very much.
A:
A guess: Your colormap is probably fine. Try to adjust the vmin and vmax when plotting.
pylab.imshow(im, vmin=0, vmax=20)
| how to set a fixed color bar for pcolor in python matplotlib? | I am using pcolor with a custom color map to plot a matrix of values. I set my color map so that low values are white and high values are red, as shown below. All of my matrices have values between 0 and 20 (inclusive) and I'd like 20 to always be pure red and 0 to always be pure white, even if the matrix has values that don't span the entire range. For example, if my matrix only has values between 2 and 7, I don't want it to plot 2 as white and 7 as red, but rather color it as if the range is still 0 to 20. How can I do this? I tried using the "ticks=" option of colorbar but it did not work.
Here is my current code (assume "my_matrix" contains the values to be plotted):
cdict = {'red': ((0.0, 1.0, 1.0),
(0.5, 1.0, 1.0),
(1.0, 1.0, 1.0)),
'green': ((0.0, 1.0, 1.0),
(0.5, 1.0, 1.0),
(1.0, 0.0, 0.0)),
'blue': ((0.0, 1.0, 1.0),
(0.5, 1.0, 1.0),
(1.0, 0.0, 0.0))}
my_cmap = matplotlib.colors.LinearSegmentedColormap('my_colormap', cdict, 256)
colored_matrix = plt.pcolor(my_matrix, cmap=my_cmap)
plt.colorbar(colored_matrix, ticks=[0, 5, 10, 15, 20])
any idea how I can fix this to get the right result? thanks very much.
| [
"A guess: Your colormap is probably fine. Try to adjust the vmin and vmax when plotting.\npylab.imshow(im, vmin=0, vmax=20)\n\n"
] | [
2
] | [] | [] | [
"matplotlib",
"numpy",
"python",
"scipy"
] | stackoverflow_0003034525_matplotlib_numpy_python_scipy.txt |
Q:
Set a script to automatically detect character encoding in a plain-text-file in Python?
I've set up a script that basically does a large-scale find-and-replace on a plain text document.
At the moment it works fine with ASCII, UTF-8, and UTF-16 (and possibly others, but I've only tested these three) encoded documents so long as the encoding is specified inside the script (the example code below specifies UTF-16).
Is there a way to make the script automatically detect which of these character encodings is being used in the input file and automatically set the character encoding of the output file the same as the encoding used on the input file?
findreplace = [
('term1', 'term2'),
]
inF = open(infile,'rb')
s=unicode(inF.read(),'utf-16')
inF.close()
for couple in findreplace:
outtext=s.replace(couple[0],couple[1])
s=outtext
outF = open(outFile,'wb')
outF.write(outtext.encode('utf-16'))
outF.close()
Thanks!
A:
From the link J.F. Sebastian posted: try chardet.
Keep in mind that in general it's impossible to detect the character encoding of every input file 100% reliably - in other words, there are possible input files which could be interpreted equally well as any of several character encodings, and there may be no way to tell which one is actually being used. chardet uses some heuristic methods and gives you a confidence level indicating how "sure" it is that the character encoding it tells you is actually correct.
A:
Some observations and questions:
(1) ASCII is a subset of UTF-8 in the sense that if a file can be decoded successfully using ASCII, then it can be decoded successfully using UTF-8. So you can cross ASCII off your list.
(2) Are the two terms in findreplace ever going to include non-ASCII characters? Note that an answer of "yes" would indicate that the goal of writing an output file in the same character set as the input may be difficult/impossible to achieve.
(3) Why not write ALL output files in the SAME handle-all-Unicode-characters encoding e.g. UTF-8?
(4) Do the UTF-8 files have a BOM?
(5) What other character sets do you reasonably expect to need to handle?
(6) Which of the four possibilities (UTF-16LE / UTF-16BE) x (BOM / no BOM) are you calling UTF-16? Note that I'm deliberately not trying to infer anything from the presence of 'utf-16' in your code.
(7) Note that chardet doesn't detect UTF-16xE without a BOM. chardet has other blind-spots with non-*x and older charsets.
Update Here are some code snippets that you can use to determine what "ANSI" is, and try decoding using a restricted list of encodings. Note: this presumes a Windows environment.
# determine "ANSI"
import locale
ansi = locale.getdefaultlocale()[1] # produces 'cp1252' on my Windows box.
f = open("input_file_path", "rb")
data = f.read()
f.close()
if data.startswith("\xEF\xBB\xBF"): # UTF-8 "BOM"
encodings = ["utf-8-sig"]
elif data.startswith(("\xFF\xFE", "\xFE\xFF")): # UTF-16 BOMs
encodings = ["utf16"]
else:
encodings = ["utf8", ansi, "utf-16le"]
# ascii is a subset of both "ANSI" and "UTF-8", so you don't need it.
# ISO-8859-1 aka latin1 defines all 256 bytes as valid codepoints; so it will
# decode ANYTHING; so if you feel that you must include it, put it LAST.
# It is possible that a utf-16le file may be decoded without exception
# by the "ansi" codec, and vice versa.
# Checking that your input text makes sense, always a very good idea, is very
# important when you are guessing encodings.
for enc in encodings:
try:
udata = data.decode(enc)
break
except UnicodeDecodeError:
pass
else:
raise Exception("unknown encoding")
# udata is your file contents as a unicode object
# When writing the output file, use 'utf8-sig' as the encoding if you
# want a BOM at the start.
A:
No there isn't. You have to encode that knowledge inside the file itself or from an outside source.
There are some heuristics, that can guess the encoding of a file through statistical analysis of the byte order frequency; but I won't be using them for any mission critical data.
| Set a script to automatically detect character encoding in a plain-text-file in Python? | I've set up a script that basically does a large-scale find-and-replace on a plain text document.
At the moment it works fine with ASCII, UTF-8, and UTF-16 (and possibly others, but I've only tested these three) encoded documents so long as the encoding is specified inside the script (the example code below specifies UTF-16).
Is there a way to make the script automatically detect which of these character encodings is being used in the input file and automatically set the character encoding of the output file the same as the encoding used on the input file?
findreplace = [
('term1', 'term2'),
]
inF = open(infile,'rb')
s=unicode(inF.read(),'utf-16')
inF.close()
for couple in findreplace:
outtext=s.replace(couple[0],couple[1])
s=outtext
outF = open(outFile,'wb')
outF.write(outtext.encode('utf-16'))
outF.close()
Thanks!
| [
"From the link J.F. Sebastian posted: try chardet.\nKeep in mind that in general it's impossible to detect the character encoding of every input file 100% reliably - in other words, there are possible input files which could be interpreted equally well as any of several character encodings, and there may be no way to tell which one is actually being used. chardet uses some heuristic methods and gives you a confidence level indicating how \"sure\" it is that the character encoding it tells you is actually correct.\n",
"Some observations and questions:\n(1) ASCII is a subset of UTF-8 in the sense that if a file can be decoded successfully using ASCII, then it can be decoded successfully using UTF-8. So you can cross ASCII off your list.\n(2) Are the two terms in findreplace ever going to include non-ASCII characters? Note that an answer of \"yes\" would indicate that the goal of writing an output file in the same character set as the input may be difficult/impossible to achieve.\n(3) Why not write ALL output files in the SAME handle-all-Unicode-characters encoding e.g. UTF-8?\n(4) Do the UTF-8 files have a BOM?\n(5) What other character sets do you reasonably expect to need to handle?\n(6) Which of the four possibilities (UTF-16LE / UTF-16BE) x (BOM / no BOM) are you calling UTF-16? Note that I'm deliberately not trying to infer anything from the presence of 'utf-16' in your code. \n(7) Note that chardet doesn't detect UTF-16xE without a BOM. chardet has other blind-spots with non-*x and older charsets.\nUpdate Here are some code snippets that you can use to determine what \"ANSI\" is, and try decoding using a restricted list of encodings. Note: this presumes a Windows environment.\n# determine \"ANSI\"\nimport locale\nansi = locale.getdefaultlocale()[1] # produces 'cp1252' on my Windows box.\n\nf = open(\"input_file_path\", \"rb\")\ndata = f.read()\nf.close()\n\nif data.startswith(\"\\xEF\\xBB\\xBF\"): # UTF-8 \"BOM\"\n encodings = [\"utf-8-sig\"]\nelif data.startswith((\"\\xFF\\xFE\", \"\\xFE\\xFF\")): # UTF-16 BOMs\n encodings = [\"utf16\"]\nelse:\n encodings = [\"utf8\", ansi, \"utf-16le\"]\n# ascii is a subset of both \"ANSI\" and \"UTF-8\", so you don't need it.\n# ISO-8859-1 aka latin1 defines all 256 bytes as valid codepoints; so it will\n# decode ANYTHING; so if you feel that you must include it, put it LAST.\n# It is possible that a utf-16le file may be decoded without exception\n# by the \"ansi\" codec, and vice versa.\n# Checking that your input text makes sense, always a very good idea, is very \n# important when you are guessing encodings.\n\nfor enc in encodings:\n try:\n udata = data.decode(enc)\n break\n except UnicodeDecodeError:\n pass\nelse:\n raise Exception(\"unknown encoding\")\n\n# udata is your file contents as a unicode object\n# When writing the output file, use 'utf8-sig' as the encoding if you\n# want a BOM at the start. \n\n",
"No there isn't. You have to encode that knowledge inside the file itself or from an outside source.\nThere are some heuristics, that can guess the encoding of a file through statistical analysis of the byte order frequency; but I won't be using them for any mission critical data.\n"
] | [
4,
3,
1
] | [] | [] | [
"character_encoding",
"python",
"replace"
] | stackoverflow_0003034714_character_encoding_python_replace.txt |
Q:
Handling TclErrors in Python
In the following code I'll get the following error if I right click the window that pops up. Then go down to the very bottom entry widget then delete it's contents. It seems to be giving me a TclError. How do I go about handeling such an error?
The Error
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python26\Lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "C:\Python26\CPUDEMO.py", line 503, in I
TL.sclS.set(S1)
File "C:\Python26\Lib\lib-tk\Tkinter.py", line 2765, in set
self.tk.call(self._w, 'set', value)
TclError: expected floating-point number but got ""
The Code
#F
#PIthon.py
# Import/Setup
import Tkinter
import psutil,time
import re
from PIL import Image, ImageTk
from time import sleep
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
# Widgets
self.menu = Tkinter.Menu(self, tearoff = 0 )
M = [ "Options...", "Exit"]
self.selectedM = Tkinter.StringVar()
self.menu.add_radiobutton( label = 'Hide', variable = self.selectedM, command = self.E )
self.menu.add_radiobutton( label = 'Bump', variable = self.selectedM, command = self.E )
self.menu.add_separator()
self.menu.add_radiobutton( label = 'Options...', variable = self.selectedM, command = self.E )
self.menu.add_separator()
self.menu.add_radiobutton( label = 'Exit', variable = self.selectedM, command = self.E )
self.frame1 = Tkinter.Frame(self,bg='grey15',relief='ridge',borderwidth=4,width=185, height=39)
self.frame1.grid()
self.frame1.grid_propagate(0)
self.frame1.bind( "<Button-3><ButtonRelease-3>", self.D )
self.frame1.bind( "<Button-2><ButtonRelease-2>", self.C )
self.frame1.bind( "<Double-Button-1>", self.C )
self.labelVariable = Tkinter.StringVar()
self.label = Tkinter.Label(self.frame1,textvariable=self.labelVariable,fg="lightgreen",bg="grey15",borderwidth=1,font=('arial', 10, 'bold'))
self.label.grid(column=1,row=0,columnspan=1,sticky='nsew')
self.label.bind( "<Button-3><ButtonRelease-3>", self.D )
self.label.bind( "<Button-2><ButtonRelease-2>", self.C )
self.label.bind( "<Double-Button-1>", self.C )
self.F()
self.overrideredirect(1)
self.wm_attributes("-topmost", 1)
global TL1
TL1 = Tkinter.Toplevel(self)
TL1.wm_geometry("+0+5000")
TL1.overrideredirect(1)
TL1.button = Tkinter.Button(TL1,text="? CPU",fg="lightgreen",bg="grey15",activeforeground="lightgreen", activebackground='grey15',borderwidth=4,font=('Arial', 8, 'bold'),command=self.J)
TL1.button.pack(ipadx=1)
# Events
def Reset(self):
self.label.configure(font=('arial', 10, 'bold'),fg='Lightgreen',bg='grey15',borderwidth=0)
self.labela.configure(font=('arial', 8, 'bold'),fg='Lightgreen',bg='grey15',borderwidth=0)
self.frame1.configure(bg='grey15',relief='ridge',borderwidth=4,width=224, height=50)
self.label.pack(ipadx=38)
def helpmenu(self):
t2 = Tkinter.Toplevel(self)
Tkinter.Label(t2, text='This is a help menu',
anchor="w",justify="left",fg="darkgreen",bg="grey90",relief="ridge",borderwidth=5,font=('Arial', 10)).pack(fill='both', expand=1)
t2.resizable(False,False)
t2.title('Help')
menu = Tkinter.Menu(self)
t2.config(menu=menu)
filemenu = Tkinter.Menu(menu)
menu.add_cascade(label="| Exit |", menu=filemenu)
filemenu.add_command(label="Exit", command=t2.destroy)
def aboutmenu(self):
t1 = Tkinter.Toplevel(self)
Tkinter.Label(t1, text=' About:\n\n CPU Usage v1.0\n\n Publisher: Drew French\n Date: 05/09/10\n Email: crawfish141@yahoo.com \n\n\n\n\n\n\n Written in Python 2.6.4',
anchor="w",justify="left",fg="darkgreen",bg="grey90",relief="sunken",borderwidth=5,font=('Arial', 10)).pack(fill='both', expand=1)
t1.resizable(False,False)
t1.title('About')
menu = Tkinter.Menu(self)
t1.config(menu=menu)
filemenu = Tkinter.Menu(menu)
menu.add_cascade(label="| Exit |", menu=filemenu)
filemenu.add_command(label="Exit", command=t1.destroy)
def A (self,event):
TL.entryVariable1.set(TL.sclY.get())
TL.entryVariable2.set(TL.sclX.get())
Y = TL.sclY.get()
X = TL.sclX.get()
self.wm_geometry("+" + str(X) + "+" + str(Y))
def B(self,event):
Y1 = TL.entryVariable1.get()
X1 = TL.entryVariable2.get()
self.wm_geometry("+" + str(X1) + "+" + str(Y1))
TL.sclY.set(Y1)
TL.sclX.set(X1)
def C(self,event):
s = self.wm_geometry()
geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)")
m = geomPatt.search(s)
X3 = m.group(4)
Y3 = m.group(6)
M = int(Y3) - 150
P = M + 150
while Y3 > M:
sleep(0.0009)
Y3 = int(Y3) - 1
self.update_idletasks()
self.wm_geometry("+" + str(X3) + "+" + str(Y3))
sleep(2.00)
while Y3 < P:
sleep(0.0009)
Y3 = int(Y3) + 1
self.update_idletasks()
self.wm_geometry("+" + str(X3) + "+" + str(Y3))
def D(self, event=None):
self.menu.post( event.x_root, event.y_root )
def E(self):
if self.selectedM.get() =='Options...':
## Setup
global TL
TL = Tkinter.Toplevel(self)
menu = Tkinter.Menu(TL)
TL.config(menu=menu)
filemenu = Tkinter.Menu(menu)
menu.add_cascade(label="| Menu |", menu=filemenu)
filemenu.add_command(label="Instruction Manual...", command=self.helpmenu)
filemenu.add_command(label="About...", command=self.aboutmenu)
filemenu.add_separator()
filemenu.add_command(label="Exit Options", command=TL.destroy)
filemenu.add_command(label="Exit", command=self.destroy)
helpmenu = Tkinter.Menu(menu)
menu.add_cascade(label="| Help |", menu=helpmenu)
helpmenu.add_command(label="Instruction Manual...", command=self.helpmenu)
helpmenu.add_separator()
helpmenu.add_command(label="Quick Help...", command=self.helpmenu)
## Title
TL.label5 = Tkinter.Label(TL,text="CPU Usage: Options",anchor="center",fg="black",bg="lightgreen",relief="ridge",borderwidth=5,font=('Arial', 18, 'bold'))
TL.label5.pack(padx=15,ipadx=5)
## X Y scale
TL.separator = Tkinter.Frame(TL,height=7, bd=1, relief='ridge', bg='grey95')
TL.separator.pack(pady=5,padx=5)
#####
TL.sclX = Tkinter.Scale(TL.separator, from_=0, to=1500, orient='horizontal', resolution=1, command=self.A)
TL.sclX.grid(column=1,row=0,ipadx=27, sticky='w')
TL.label1 = Tkinter.Label(TL.separator,text="X",anchor="s",fg="black",bg="grey95",font=('Arial', 8 ,'bold'))
TL.label1.grid(column=0,row=0, pady=1, sticky='S')
TL.sclY = Tkinter.Scale(TL.separator, from_=0, to=1500, resolution=1, command=self.A)
TL.sclY.grid(column=2,row=1,rowspan=2,sticky='e', padx=4)
TL.label3 = Tkinter.Label(TL.separator,text="Y",fg="black",bg="grey95",font=('Arial', 8 ,'bold'))
TL.label3.grid(column=2,row=0, padx=10, sticky='e')
TL.entryVariable2 = Tkinter.StringVar()
TL.entry2 = Tkinter.Entry(TL.separator,textvariable=TL.entryVariable2,
fg="grey15",bg="grey90",relief="sunken",insertbackground="black",borderwidth=5,font=('Arial', 10))
TL.entry2.grid(column=1,row=1,ipadx=20, pady=10,sticky='EW')
TL.entry2.bind("<Return>", self.B)
TL.label2 = Tkinter.Label(TL.separator,text="X:",fg="black",bg="grey95",font=('Arial', 8 ,'bold'))
TL.label2.grid(column=0,row=1, ipadx=4, sticky='W')
TL.entryVariable1 = Tkinter.StringVar()
TL.entry1 = Tkinter.Entry(TL.separator,textvariable=TL.entryVariable1,
fg="grey15",bg="grey90",relief="sunken",insertbackground="black",borderwidth=5,font=('Arial', 10))
TL.entry1.grid(column=1,row=2,sticky='EW')
TL.entry1.bind("<Return>", self.B)
TL.label4 = Tkinter.Label(TL.separator,text="Y:", anchor="center",fg="black",bg="grey95",font=('Arial', 8 ,'bold'))
TL.label4.grid(column=0,row=2, ipadx=4, sticky='W')
TL.label7 = Tkinter.Label(TL.separator,text="Text Colour:",fg="black",bg="grey95",font=('Arial', 8 ,'bold'))
TL.label7.grid(column=1,row=3,stick="W",ipady=10)
TL.selectedP = Tkinter.StringVar()
TL.opt1 = Tkinter.OptionMenu(TL.separator, TL.selectedP,'Normal', 'White','Black', 'Blue', 'Steel Blue','Green','Light Green','Yellow','Orange' ,'Red',command=self.G)
TL.opt1.config(fg="black",bg="grey90",activebackground="grey90",activeforeground="black",
anchor="center",relief="raised",direction='right',font=('Arial', 10))
TL.opt1.grid(column=1,row=4,sticky='EW',padx=20,ipadx=20)
TL.selectedP.set('Normal')
TL.label7 = Tkinter.Label(TL.separator,text="Refresh Rate:",fg="black",bg="grey95",font=('Arial', 8 ,'bold'))
TL.label7.grid(column=1,row=5,stick="W",ipady=10)
TL.sclS = Tkinter.Scale(TL.separator, from_=10, to=2000, orient='horizontal', resolution=10, command=self.H)
TL.sclS.grid(column=1,row=6,ipadx=27, sticky='w')
TL.sclS.set(650)
TL.entryVariableS = Tkinter.StringVar()
TL.entryS = Tkinter.Entry(TL.separator,textvariable=TL.entryVariableS,
fg="grey15",bg="grey90",relief="sunken",insertbackground="black",borderwidth=5,font=('Arial', 10))
TL.entryS.grid(column=1,row=7,ipadx=20, pady=10,sticky='EW')
TL.entryS.bind("<Return>", self.I)
TL.entryVariableS.set(650)
##############
TL.resizable(False,False)
TL.title('Options')
geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)")
s = self.wm_geometry()
m = geomPatt.search(s)
X = m.group(4)
Y = m.group(6)
TL.sclY.set(Y)
TL.sclX.set(X)
if self.selectedM.get() == 'Exit':
self.destroy()
if self.selectedM.get() == 'Bump':
s = self.wm_geometry()
geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)")
m = geomPatt.search(s)
X3 = m.group(4)
Y3 = m.group(6)
M = int(Y3) - 150
P = M + 150
while Y3 > M:
sleep(0.0009)
Y3 = int(Y3) - 1
self.update_idletasks()
self.wm_geometry("+" + str(X3) + "+" + str(Y3))
sleep(2.00)
while Y3 < P:
sleep(0.0009)
Y3 = int(Y3) + 1
self.update_idletasks()
self.wm_geometry("+" + str(X3) + "+" + str(Y3))
if self.selectedM.get() == 'Hide':
s = self.wm_geometry()
geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)")
m = geomPatt.search(s)
X3 = m.group(4)
Y3 = m.group(6)
M = int(Y3) + 5000
self.update_idletasks()
self.wm_geometry("+" + str(X3) + "+" + str(M))
TL1.wm_geometry("+0+190")
def F (self):
G = round(psutil.cpu_percent(), 1)
G1 = str(G) + '%'
self.labelVariable.set(G1)
try:
S2 = TL.entryVariableS.get()
except ValueError, e:
S2 = 650
except NameError:
S2 = 650
self.after(int(S2), self.F)
def G (self,event):
if TL.selectedP.get() =='Normal':
self.label.config( fg = 'lightgreen' )
TL1.button.config( fg = 'lightgreen',activeforeground='lightgreen')
if TL.selectedP.get() =='Red':
self.label.config( fg = 'red' )
TL1.button.config( fg = 'red',activeforeground='red')
if TL.selectedP.get() =='Orange':
self.label.config( fg = 'orange')
TL1.button.config( fg = 'orange',activeforeground='orange')
if TL.selectedP.get() =='Yellow':
self.label.config( fg = 'yellow')
TL1.button.config( fg = 'yellow',activeforeground='yellow')
if TL.selectedP.get() =='Light Green':
self.label.config( fg = 'lightgreen' )
TL1.button.config( fg = 'lightgreen',activeforeground='lightgreen')
if TL.selectedP.get() =='Normal':
self.label.config( fg = 'lightgreen' )
TL1.button.config( fg = 'lightgreen',activeforeground='lightgreen')
if TL.selectedP.get() =='Steel Blue':
self.label.config( fg = 'steelblue1' )
TL1.button.config( fg = 'steelblue1',activeforeground='steelblue1')
if TL.selectedP.get() =='Blue':
self.label.config( fg = 'blue')
TL1.button.config( fg = 'blue',activeforeground='blue')
if TL.selectedP.get() =='Green':
self.label.config( fg = 'darkgreen' )
TL1.button.config( fg = 'darkgreen',activeforeground='darkgreen')
if TL.selectedP.get() =='White':
self.label.config( fg = 'white' )
TL1.button.config( fg = 'white',activeforeground='white')
if TL.selectedP.get() =='Black':
self.label.config( fg = 'black')
TL1.button.config( fg = 'black',activeforeground='black')
def H (self,event):
TL.entryVariableS.set(TL.sclS.get())
S = TL.sclS.get()
def I (self,event):
S1 = TL.entryVariableS.get()
TL.sclS.set(S1)
TL.sclS.set(TL.sclS.get())
S1 = TL.entryVariableS.get()
TL.sclS.set(S1)
def J (self):
s = self.wm_geometry()
geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)")
m = geomPatt.search(s)
X3 = m.group(4)
Y3 = m.group(6)
M = int(Y3) - 5000
self.update_idletasks()
self.wm_geometry("+" + str(X3) + "+" + str(M))
TL1.wm_geometry("+0+5000")
# Loop
if __name__ == "__main__":
app = simpleapp_tk(None)
app.mainloop()
A:
def I (self,event):
S1 = TL.entryVariableS.get()
TL.sclS.set(S1)
TL.sclS.set(TL.sclS.get())
S1 = TL.entryVariableS.get()
TL.sclS.set(S1)
TL.entryVariableS.get() is returning "" (empty string); you will need to check for that and handle them appropriately (either gives default value or complain to the user).
| Handling TclErrors in Python | In the following code I'll get the following error if I right click the window that pops up. Then go down to the very bottom entry widget then delete it's contents. It seems to be giving me a TclError. How do I go about handeling such an error?
The Error
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python26\Lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "C:\Python26\CPUDEMO.py", line 503, in I
TL.sclS.set(S1)
File "C:\Python26\Lib\lib-tk\Tkinter.py", line 2765, in set
self.tk.call(self._w, 'set', value)
TclError: expected floating-point number but got ""
The Code
#F
#PIthon.py
# Import/Setup
import Tkinter
import psutil,time
import re
from PIL import Image, ImageTk
from time import sleep
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
# Widgets
self.menu = Tkinter.Menu(self, tearoff = 0 )
M = [ "Options...", "Exit"]
self.selectedM = Tkinter.StringVar()
self.menu.add_radiobutton( label = 'Hide', variable = self.selectedM, command = self.E )
self.menu.add_radiobutton( label = 'Bump', variable = self.selectedM, command = self.E )
self.menu.add_separator()
self.menu.add_radiobutton( label = 'Options...', variable = self.selectedM, command = self.E )
self.menu.add_separator()
self.menu.add_radiobutton( label = 'Exit', variable = self.selectedM, command = self.E )
self.frame1 = Tkinter.Frame(self,bg='grey15',relief='ridge',borderwidth=4,width=185, height=39)
self.frame1.grid()
self.frame1.grid_propagate(0)
self.frame1.bind( "<Button-3><ButtonRelease-3>", self.D )
self.frame1.bind( "<Button-2><ButtonRelease-2>", self.C )
self.frame1.bind( "<Double-Button-1>", self.C )
self.labelVariable = Tkinter.StringVar()
self.label = Tkinter.Label(self.frame1,textvariable=self.labelVariable,fg="lightgreen",bg="grey15",borderwidth=1,font=('arial', 10, 'bold'))
self.label.grid(column=1,row=0,columnspan=1,sticky='nsew')
self.label.bind( "<Button-3><ButtonRelease-3>", self.D )
self.label.bind( "<Button-2><ButtonRelease-2>", self.C )
self.label.bind( "<Double-Button-1>", self.C )
self.F()
self.overrideredirect(1)
self.wm_attributes("-topmost", 1)
global TL1
TL1 = Tkinter.Toplevel(self)
TL1.wm_geometry("+0+5000")
TL1.overrideredirect(1)
TL1.button = Tkinter.Button(TL1,text="? CPU",fg="lightgreen",bg="grey15",activeforeground="lightgreen", activebackground='grey15',borderwidth=4,font=('Arial', 8, 'bold'),command=self.J)
TL1.button.pack(ipadx=1)
# Events
def Reset(self):
self.label.configure(font=('arial', 10, 'bold'),fg='Lightgreen',bg='grey15',borderwidth=0)
self.labela.configure(font=('arial', 8, 'bold'),fg='Lightgreen',bg='grey15',borderwidth=0)
self.frame1.configure(bg='grey15',relief='ridge',borderwidth=4,width=224, height=50)
self.label.pack(ipadx=38)
def helpmenu(self):
t2 = Tkinter.Toplevel(self)
Tkinter.Label(t2, text='This is a help menu',
anchor="w",justify="left",fg="darkgreen",bg="grey90",relief="ridge",borderwidth=5,font=('Arial', 10)).pack(fill='both', expand=1)
t2.resizable(False,False)
t2.title('Help')
menu = Tkinter.Menu(self)
t2.config(menu=menu)
filemenu = Tkinter.Menu(menu)
menu.add_cascade(label="| Exit |", menu=filemenu)
filemenu.add_command(label="Exit", command=t2.destroy)
def aboutmenu(self):
t1 = Tkinter.Toplevel(self)
Tkinter.Label(t1, text=' About:\n\n CPU Usage v1.0\n\n Publisher: Drew French\n Date: 05/09/10\n Email: crawfish141@yahoo.com \n\n\n\n\n\n\n Written in Python 2.6.4',
anchor="w",justify="left",fg="darkgreen",bg="grey90",relief="sunken",borderwidth=5,font=('Arial', 10)).pack(fill='both', expand=1)
t1.resizable(False,False)
t1.title('About')
menu = Tkinter.Menu(self)
t1.config(menu=menu)
filemenu = Tkinter.Menu(menu)
menu.add_cascade(label="| Exit |", menu=filemenu)
filemenu.add_command(label="Exit", command=t1.destroy)
def A (self,event):
TL.entryVariable1.set(TL.sclY.get())
TL.entryVariable2.set(TL.sclX.get())
Y = TL.sclY.get()
X = TL.sclX.get()
self.wm_geometry("+" + str(X) + "+" + str(Y))
def B(self,event):
Y1 = TL.entryVariable1.get()
X1 = TL.entryVariable2.get()
self.wm_geometry("+" + str(X1) + "+" + str(Y1))
TL.sclY.set(Y1)
TL.sclX.set(X1)
def C(self,event):
s = self.wm_geometry()
geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)")
m = geomPatt.search(s)
X3 = m.group(4)
Y3 = m.group(6)
M = int(Y3) - 150
P = M + 150
while Y3 > M:
sleep(0.0009)
Y3 = int(Y3) - 1
self.update_idletasks()
self.wm_geometry("+" + str(X3) + "+" + str(Y3))
sleep(2.00)
while Y3 < P:
sleep(0.0009)
Y3 = int(Y3) + 1
self.update_idletasks()
self.wm_geometry("+" + str(X3) + "+" + str(Y3))
def D(self, event=None):
self.menu.post( event.x_root, event.y_root )
def E(self):
if self.selectedM.get() =='Options...':
## Setup
global TL
TL = Tkinter.Toplevel(self)
menu = Tkinter.Menu(TL)
TL.config(menu=menu)
filemenu = Tkinter.Menu(menu)
menu.add_cascade(label="| Menu |", menu=filemenu)
filemenu.add_command(label="Instruction Manual...", command=self.helpmenu)
filemenu.add_command(label="About...", command=self.aboutmenu)
filemenu.add_separator()
filemenu.add_command(label="Exit Options", command=TL.destroy)
filemenu.add_command(label="Exit", command=self.destroy)
helpmenu = Tkinter.Menu(menu)
menu.add_cascade(label="| Help |", menu=helpmenu)
helpmenu.add_command(label="Instruction Manual...", command=self.helpmenu)
helpmenu.add_separator()
helpmenu.add_command(label="Quick Help...", command=self.helpmenu)
## Title
TL.label5 = Tkinter.Label(TL,text="CPU Usage: Options",anchor="center",fg="black",bg="lightgreen",relief="ridge",borderwidth=5,font=('Arial', 18, 'bold'))
TL.label5.pack(padx=15,ipadx=5)
## X Y scale
TL.separator = Tkinter.Frame(TL,height=7, bd=1, relief='ridge', bg='grey95')
TL.separator.pack(pady=5,padx=5)
#####
TL.sclX = Tkinter.Scale(TL.separator, from_=0, to=1500, orient='horizontal', resolution=1, command=self.A)
TL.sclX.grid(column=1,row=0,ipadx=27, sticky='w')
TL.label1 = Tkinter.Label(TL.separator,text="X",anchor="s",fg="black",bg="grey95",font=('Arial', 8 ,'bold'))
TL.label1.grid(column=0,row=0, pady=1, sticky='S')
TL.sclY = Tkinter.Scale(TL.separator, from_=0, to=1500, resolution=1, command=self.A)
TL.sclY.grid(column=2,row=1,rowspan=2,sticky='e', padx=4)
TL.label3 = Tkinter.Label(TL.separator,text="Y",fg="black",bg="grey95",font=('Arial', 8 ,'bold'))
TL.label3.grid(column=2,row=0, padx=10, sticky='e')
TL.entryVariable2 = Tkinter.StringVar()
TL.entry2 = Tkinter.Entry(TL.separator,textvariable=TL.entryVariable2,
fg="grey15",bg="grey90",relief="sunken",insertbackground="black",borderwidth=5,font=('Arial', 10))
TL.entry2.grid(column=1,row=1,ipadx=20, pady=10,sticky='EW')
TL.entry2.bind("<Return>", self.B)
TL.label2 = Tkinter.Label(TL.separator,text="X:",fg="black",bg="grey95",font=('Arial', 8 ,'bold'))
TL.label2.grid(column=0,row=1, ipadx=4, sticky='W')
TL.entryVariable1 = Tkinter.StringVar()
TL.entry1 = Tkinter.Entry(TL.separator,textvariable=TL.entryVariable1,
fg="grey15",bg="grey90",relief="sunken",insertbackground="black",borderwidth=5,font=('Arial', 10))
TL.entry1.grid(column=1,row=2,sticky='EW')
TL.entry1.bind("<Return>", self.B)
TL.label4 = Tkinter.Label(TL.separator,text="Y:", anchor="center",fg="black",bg="grey95",font=('Arial', 8 ,'bold'))
TL.label4.grid(column=0,row=2, ipadx=4, sticky='W')
TL.label7 = Tkinter.Label(TL.separator,text="Text Colour:",fg="black",bg="grey95",font=('Arial', 8 ,'bold'))
TL.label7.grid(column=1,row=3,stick="W",ipady=10)
TL.selectedP = Tkinter.StringVar()
TL.opt1 = Tkinter.OptionMenu(TL.separator, TL.selectedP,'Normal', 'White','Black', 'Blue', 'Steel Blue','Green','Light Green','Yellow','Orange' ,'Red',command=self.G)
TL.opt1.config(fg="black",bg="grey90",activebackground="grey90",activeforeground="black",
anchor="center",relief="raised",direction='right',font=('Arial', 10))
TL.opt1.grid(column=1,row=4,sticky='EW',padx=20,ipadx=20)
TL.selectedP.set('Normal')
TL.label7 = Tkinter.Label(TL.separator,text="Refresh Rate:",fg="black",bg="grey95",font=('Arial', 8 ,'bold'))
TL.label7.grid(column=1,row=5,stick="W",ipady=10)
TL.sclS = Tkinter.Scale(TL.separator, from_=10, to=2000, orient='horizontal', resolution=10, command=self.H)
TL.sclS.grid(column=1,row=6,ipadx=27, sticky='w')
TL.sclS.set(650)
TL.entryVariableS = Tkinter.StringVar()
TL.entryS = Tkinter.Entry(TL.separator,textvariable=TL.entryVariableS,
fg="grey15",bg="grey90",relief="sunken",insertbackground="black",borderwidth=5,font=('Arial', 10))
TL.entryS.grid(column=1,row=7,ipadx=20, pady=10,sticky='EW')
TL.entryS.bind("<Return>", self.I)
TL.entryVariableS.set(650)
##############
TL.resizable(False,False)
TL.title('Options')
geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)")
s = self.wm_geometry()
m = geomPatt.search(s)
X = m.group(4)
Y = m.group(6)
TL.sclY.set(Y)
TL.sclX.set(X)
if self.selectedM.get() == 'Exit':
self.destroy()
if self.selectedM.get() == 'Bump':
s = self.wm_geometry()
geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)")
m = geomPatt.search(s)
X3 = m.group(4)
Y3 = m.group(6)
M = int(Y3) - 150
P = M + 150
while Y3 > M:
sleep(0.0009)
Y3 = int(Y3) - 1
self.update_idletasks()
self.wm_geometry("+" + str(X3) + "+" + str(Y3))
sleep(2.00)
while Y3 < P:
sleep(0.0009)
Y3 = int(Y3) + 1
self.update_idletasks()
self.wm_geometry("+" + str(X3) + "+" + str(Y3))
if self.selectedM.get() == 'Hide':
s = self.wm_geometry()
geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)")
m = geomPatt.search(s)
X3 = m.group(4)
Y3 = m.group(6)
M = int(Y3) + 5000
self.update_idletasks()
self.wm_geometry("+" + str(X3) + "+" + str(M))
TL1.wm_geometry("+0+190")
def F (self):
G = round(psutil.cpu_percent(), 1)
G1 = str(G) + '%'
self.labelVariable.set(G1)
try:
S2 = TL.entryVariableS.get()
except ValueError, e:
S2 = 650
except NameError:
S2 = 650
self.after(int(S2), self.F)
def G (self,event):
if TL.selectedP.get() =='Normal':
self.label.config( fg = 'lightgreen' )
TL1.button.config( fg = 'lightgreen',activeforeground='lightgreen')
if TL.selectedP.get() =='Red':
self.label.config( fg = 'red' )
TL1.button.config( fg = 'red',activeforeground='red')
if TL.selectedP.get() =='Orange':
self.label.config( fg = 'orange')
TL1.button.config( fg = 'orange',activeforeground='orange')
if TL.selectedP.get() =='Yellow':
self.label.config( fg = 'yellow')
TL1.button.config( fg = 'yellow',activeforeground='yellow')
if TL.selectedP.get() =='Light Green':
self.label.config( fg = 'lightgreen' )
TL1.button.config( fg = 'lightgreen',activeforeground='lightgreen')
if TL.selectedP.get() =='Normal':
self.label.config( fg = 'lightgreen' )
TL1.button.config( fg = 'lightgreen',activeforeground='lightgreen')
if TL.selectedP.get() =='Steel Blue':
self.label.config( fg = 'steelblue1' )
TL1.button.config( fg = 'steelblue1',activeforeground='steelblue1')
if TL.selectedP.get() =='Blue':
self.label.config( fg = 'blue')
TL1.button.config( fg = 'blue',activeforeground='blue')
if TL.selectedP.get() =='Green':
self.label.config( fg = 'darkgreen' )
TL1.button.config( fg = 'darkgreen',activeforeground='darkgreen')
if TL.selectedP.get() =='White':
self.label.config( fg = 'white' )
TL1.button.config( fg = 'white',activeforeground='white')
if TL.selectedP.get() =='Black':
self.label.config( fg = 'black')
TL1.button.config( fg = 'black',activeforeground='black')
def H (self,event):
TL.entryVariableS.set(TL.sclS.get())
S = TL.sclS.get()
def I (self,event):
S1 = TL.entryVariableS.get()
TL.sclS.set(S1)
TL.sclS.set(TL.sclS.get())
S1 = TL.entryVariableS.get()
TL.sclS.set(S1)
def J (self):
s = self.wm_geometry()
geomPatt = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)")
m = geomPatt.search(s)
X3 = m.group(4)
Y3 = m.group(6)
M = int(Y3) - 5000
self.update_idletasks()
self.wm_geometry("+" + str(X3) + "+" + str(M))
TL1.wm_geometry("+0+5000")
# Loop
if __name__ == "__main__":
app = simpleapp_tk(None)
app.mainloop()
| [
"def I (self,event):\n S1 = TL.entryVariableS.get()\n TL.sclS.set(S1)\n TL.sclS.set(TL.sclS.get())\n S1 = TL.entryVariableS.get()\n TL.sclS.set(S1)\n\nTL.entryVariableS.get() is returning \"\" (empty string); you will need to check for that and handle them appropriately (either gives default value or complain to the user).\n"
] | [
0
] | [] | [] | [
"error_handling",
"python",
"tkinter"
] | stackoverflow_0003033749_error_handling_python_tkinter.txt |
Q:
How to make django test framework read from live database?
I realize there's a similar question here, but this one has a different approach: I have a django app that does queries over data indexed with djapian ; I'd like to write unit tests for this app's search component, and, obviously, I'd need the django settings module and all connections with the database active, so the test runner that django provides seems ideal. however, the django testing framework creates a dummy database and I'd hate to dump all my data to a fixture and then index it (the tests would take forever!);
My data isn't at risk because the tests would only read from the database, so, how could this be achieved? -I'm new at this whole unit testing thing, so the solution of writing a new test runner I read in that similar question doesn't enlighten me a bit, at least not without some details
A:
Reading the test cases for djapian I found something really interesting: what those guys do is use the setUp method for the TestCase class: they create an object and then use the update method for the indexer, so they effectively have a document to search for and a way to write controlled query tests!
For the curious, the method looks something like this:
def setUp(self):
p = Person.objects.create(name="Alex")
for i in range(self.num_entries):
Entry.objects.create(author=p, title="Entry with number %s" % i, text="foobar " * i)
Entry.indexer.update()
I think this would do, but we have to remember I'm testing a little search engine here, so this solution might be the easy way out; I can't come up with an objection, though, so if you guys have an answer that'll help define a strategy for testing this kind of webApps in python in general, it's more than welcome!
-I think I'll settle for something like this for now (I wanted to test the latency of the queries with a fully populated database also, but I think I could do that later with bench tests in Funkload)
EDIT: Ok, to be faithful to a solution for anyone interested, I ran into another issue: the xapian index (as stated in the comment). To solve it, I created a default test runner that changed the production xapian index for a test index (a smaller one, created with a management script). This runner is fairly simple:
def custom_run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]):
"""Set the test indices"""
settings.CATEGORY_CLASSIFIER_DATA = settings.TEST_CLASSIFIER_DATA
return run_tests(test_labels, verbosity, interactive, extra_tests)
And, to use it, I simply added a setting:
TEST_RUNNER = 'search.tests.custom_run_tests'
I dropped the aforementioned approach (creating the documents in the setUp) for performance and readability reasons: to test the database I needed a decent amount of documents with some text (a paragraph or two), so I ended up creating a fixture for that (I used a management command that created the documents in the real database, serialized them -writing them to a file- and then deleted 'em).
So, in the end, I didn't read from the live db at all and instead used test fixtures created with a somewhat hacky script and a custom runner, and it wasn't that hard :)
| How to make django test framework read from live database? | I realize there's a similar question here, but this one has a different approach: I have a django app that does queries over data indexed with djapian ; I'd like to write unit tests for this app's search component, and, obviously, I'd need the django settings module and all connections with the database active, so the test runner that django provides seems ideal. however, the django testing framework creates a dummy database and I'd hate to dump all my data to a fixture and then index it (the tests would take forever!);
My data isn't at risk because the tests would only read from the database, so, how could this be achieved? -I'm new at this whole unit testing thing, so the solution of writing a new test runner I read in that similar question doesn't enlighten me a bit, at least not without some details
| [
"Reading the test cases for djapian I found something really interesting: what those guys do is use the setUp method for the TestCase class: they create an object and then use the update method for the indexer, so they effectively have a document to search for and a way to write controlled query tests!\nFor the curious, the method looks something like this:\ndef setUp(self):\n p = Person.objects.create(name=\"Alex\")\n\n for i in range(self.num_entries):\n Entry.objects.create(author=p, title=\"Entry with number %s\" % i, text=\"foobar \" * i)\n\n Entry.indexer.update()\n\nI think this would do, but we have to remember I'm testing a little search engine here, so this solution might be the easy way out; I can't come up with an objection, though, so if you guys have an answer that'll help define a strategy for testing this kind of webApps in python in general, it's more than welcome!\n-I think I'll settle for something like this for now (I wanted to test the latency of the queries with a fully populated database also, but I think I could do that later with bench tests in Funkload)\nEDIT: Ok, to be faithful to a solution for anyone interested, I ran into another issue: the xapian index (as stated in the comment). To solve it, I created a default test runner that changed the production xapian index for a test index (a smaller one, created with a management script). This runner is fairly simple:\ndef custom_run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]):\n \"\"\"Set the test indices\"\"\"\n settings.CATEGORY_CLASSIFIER_DATA = settings.TEST_CLASSIFIER_DATA \n return run_tests(test_labels, verbosity, interactive, extra_tests)\n\nAnd, to use it, I simply added a setting:\nTEST_RUNNER = 'search.tests.custom_run_tests'\n\nI dropped the aforementioned approach (creating the documents in the setUp) for performance and readability reasons: to test the database I needed a decent amount of documents with some text (a paragraph or two), so I ended up creating a fixture for that (I used a management command that created the documents in the real database, serialized them -writing them to a file- and then deleted 'em).\nSo, in the end, I didn't read from the live db at all and instead used test fixtures created with a somewhat hacky script and a custom runner, and it wasn't that hard :)\n"
] | [
2
] | [] | [] | [
"django",
"python",
"xapian"
] | stackoverflow_0003034509_django_python_xapian.txt |
Q:
How to return a value when destroying/cleaning-up an object instance
When I initiate a class in Python, I give it some values. I then call method in the class which does something. Here's a snippet:
class TestClass():
def __init__(self):
self.counter = 0
def doSomething(self):
self.counter = self.counter + 1
print 'Hiya'
if __name__ == "__main__":
obj = TestClass()
obj.doSomething()
obj.doSomething()
obj.doSomething()
print obj.counter
As you can see, everytime I call the doSomething method, it prints some text and increments an internal variable i.e. counter. When I initiate the class, i set the counter variable to 0. When I destroy the object, I'd like to return the internal counter variable. What would be a good way of doing this? I wanted to know if there were other ways apart from doing stuff like:
accessing the variable directly. Like obj.counter.
creating a method like getCounter.
Thanks.
A:
Doing actions upon object destruction is generally frowned upon. Python offers a __del__ function, but it may not be called in certain instances.
If you were to do something with the counter variable, what would it be? Where would the data go?
| How to return a value when destroying/cleaning-up an object instance | When I initiate a class in Python, I give it some values. I then call method in the class which does something. Here's a snippet:
class TestClass():
def __init__(self):
self.counter = 0
def doSomething(self):
self.counter = self.counter + 1
print 'Hiya'
if __name__ == "__main__":
obj = TestClass()
obj.doSomething()
obj.doSomething()
obj.doSomething()
print obj.counter
As you can see, everytime I call the doSomething method, it prints some text and increments an internal variable i.e. counter. When I initiate the class, i set the counter variable to 0. When I destroy the object, I'd like to return the internal counter variable. What would be a good way of doing this? I wanted to know if there were other ways apart from doing stuff like:
accessing the variable directly. Like obj.counter.
creating a method like getCounter.
Thanks.
| [
"Doing actions upon object destruction is generally frowned upon. Python offers a __del__ function, but it may not be called in certain instances.\nIf you were to do something with the counter variable, what would it be? Where would the data go?\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0003035284_python.txt |
Q:
How to print string in this way
For every string, I need to print # each 6 characters.
For example:
example_string = "this is an example string. ok ????"
myfunction(example_string)
"this i#s an e#xample# strin#g. ok #????"
What is the most efficient way to do that ?
A:
How about this?
'#'.join( [example_string[a:a+6] for a in range(0,len(example_string),6)])
It runs pretty quickly, too. On my machine, five microseconds per 100-character string:
>>> import timeit
>>> timeit.Timer( "'#'.join([s[a:a+6] for a in range(0,len(s),6)])", "s='x'*100").timeit()
4.9556539058685303
A:
>>> str = "this is an example string. ok ????"
>>> import re
>>> re.sub("(.{6})", r"\1#", str)
'this i#s an e#xample# strin#g. ok #????'
Update:
Normally dot matches all characters except new-lines. Use re.S to make dot match all characters including new-line chars.
>>> pattern = re.compile("(.{6})", re.S)
>>> str = "this is an example string with\nmore than one line\nin it. It has three lines"
>>> print pattern.sub(r"\1#", str)
this i#s an e#xample# strin#g with#
more #than o#ne lin#e
in i#t. It #has th#ree li#nes
A:
import itertools
def every6(sin, c='#'):
r = itertools.izip_longest(*([iter(sin)] * 6 + [c * (len(sin) // 6)]))
return ''.join(''.join(y for y in x if y is not None) for x in r)
print every6(example_string)
| How to print string in this way | For every string, I need to print # each 6 characters.
For example:
example_string = "this is an example string. ok ????"
myfunction(example_string)
"this i#s an e#xample# strin#g. ok #????"
What is the most efficient way to do that ?
| [
"How about this?\n'#'.join( [example_string[a:a+6] for a in range(0,len(example_string),6)])\n\nIt runs pretty quickly, too. On my machine, five microseconds per 100-character string:\n>>> import timeit\n>>> timeit.Timer( \"'#'.join([s[a:a+6] for a in range(0,len(s),6)])\", \"s='x'*100\").timeit()\n4.9556539058685303\n\n",
">>> str = \"this is an example string. ok ????\"\n>>> import re\n>>> re.sub(\"(.{6})\", r\"\\1#\", str)\n'this i#s an e#xample# strin#g. ok #????'\n\nUpdate:\nNormally dot matches all characters except new-lines. Use re.S to make dot match all characters including new-line chars.\n>>> pattern = re.compile(\"(.{6})\", re.S)\n>>> str = \"this is an example string with\\nmore than one line\\nin it. It has three lines\"\n>>> print pattern.sub(r\"\\1#\", str)\n\n\nthis i#s an e#xample# strin#g with#\nmore #than o#ne lin#e\nin i#t. It #has th#ree li#nes\n\n",
"import itertools\n\ndef every6(sin, c='#'):\n r = itertools.izip_longest(*([iter(sin)] * 6 + [c * (len(sin) // 6)]))\n return ''.join(''.join(y for y in x if y is not None) for x in r)\n\nprint every6(example_string)\n\n"
] | [
9,
4,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003035239_python_regex.txt |
Q:
Keep history in django to draw graphs
I am looking for the best way to have an history of my models (interger & float fields) in Django.
I read Keeping a history of data changes in database and it seems that triggers are the best option.
My idea is to stay database agnostic if possible.
How do you approach this issues in your django code ?
TIA.
A:
If you're not going to go with Triggers, Signals do a similar job — it'll (probably) be less efficient than using a trigger, but you can attach a post_save signal to your models you want to track and do all the processing you need there.
A:
You should check out Django Reversion app. It's probably the easiest way to implement what you want in your project, especially if you'd also like to restore earlier versions of your model(s). If not, it might be a bit overkill.
Edit: You should also examine Django History. Might be more along the lines of what you really need. However it hasn't been updated in a long time, you might have to just use it as inspiration for your custom solution.
| Keep history in django to draw graphs | I am looking for the best way to have an history of my models (interger & float fields) in Django.
I read Keeping a history of data changes in database and it seems that triggers are the best option.
My idea is to stay database agnostic if possible.
How do you approach this issues in your django code ?
TIA.
| [
"If you're not going to go with Triggers, Signals do a similar job — it'll (probably) be less efficient than using a trigger, but you can attach a post_save signal to your models you want to track and do all the processing you need there.\n",
"You should check out Django Reversion app. It's probably the easiest way to implement what you want in your project, especially if you'd also like to restore earlier versions of your model(s). If not, it might be a bit overkill.\nEdit: You should also examine Django History. Might be more along the lines of what you really need. However it hasn't been updated in a long time, you might have to just use it as inspiration for your custom solution.\n"
] | [
0,
0
] | [] | [] | [
"django",
"python",
"sql"
] | stackoverflow_0003032337_django_python_sql.txt |
Q:
Plotting a cumulative graph of python datetimes
Say I have a list of datetimes, and we know each datetime to be the recorded time of an event happening.
Is it possible in matplotlib to graph the frequency of this event occurring over time, showing this data in a cumulative graph (so that each point is greater or equal to all of the points that went before it), without preprocessing this list? (e.g. passing datetime objects directly to some wonderful matplotlib function)
Or do I need to turn this list of datetimes into a list of dictionary items, such as:
{"year": 1998, "month": 12, "date": 15, "events": 92}
and then generate a graph from this list?
A:
This should work for you:
counts = arange(0, len(list_of_dates))
plot(list_of_dates, counts)
You can of course give any of the usual options to the plot call to make the graph look the way you want it. (I'll point out that matplotlib is very adept at handling dates and times.)
Another option would be the hist function - it has an option 'cumulative=True' that might be useful. You can create a cumulative histogram showing the number of events that have occurred as of any given date something like this:
from pyplot import hist
from matplotlib.dates import date2num
hist(date2num(list_of_dates), cumulative=True)
But this produces a bar chart, which might not be quite what you're looking for, and in any case making the date labels on the horizontal axis display properly will probably require some fudging.
EDIT: I'm getting the sense that what you really want is one point (or bar) per date, with the corresponding y-value being the number of events that have occurred up to (and including?) that date. In that case, I'd suggest doing something like this:
grouped_dates = [[d, len(list(g))] for d,g in itertools.groupby(list_of_dates, lambda k: k.date())]
dates, counts = grouped_dates.transpose()
counts = counts.cumsum()
step(dates, counts)
The groupby function from the itertools module will produce the kind of data you're looking for: only a single instance of each date, accompanied by a list (an iterator, actually) of all the datetime objects that have that date. As suggested by Jouni in the comments, the step function will give a graph that steps up at each day on which events occurred, so I'd suggest using that in place of plot.
(Hat tip to EOL for reminding me about cumsum)
If you want to have one point for every day, regardless of whether any events occurred on that day or not, you'll need to alter the above code a bit:
from matplotlib.dates import drange, num2date
date_dict = dict((d, len(list(g))) for d,g in itertools.groupby(list_of_dates, lambda k: k.date()))
dates = num2date(drange(min(list_of_dates).date(), max(list_of_dates).date() + timedelta(1), timedelta(1)))
counts = asarray([date_dict.get(d.date(), 0) for d in dates]).cumsum()
step(dates, counts)
I don't think it'll really make a difference for the plot produced by the step function though.
A:
So, you start with a list of dates that you want to histogram:
from datetime import datetime
list_of_datetime_datetime_objects = [datetime(2010, 6, 14), datetime(1974, 2, 8), datetime(1974, 2, 8)]
Matplotlib allows you to convert a datetime.datetime object into a simple number, as David mentioned:
from matplotlib.dates import date2num, num2date
num_dates = [date2num(d) for d in list_of_datetime_datetime_objects]
You can then calculate the histogram of your data (look at NumPy histogram docs for more options (number of bins, etc.)):
import numpy
histo = numpy.histogram(num_dates)
Since you want the cumulative histogram, you add individual counts together:
cumulative_histo_counts = histo[0].cumsum()
The histogram plot will need the bin size:
from matplotlib import pyplot
You can then plot the cumulative histogram:
bin_size = histo[1][1]-histo[1][0]
pyplot.bar(histo[1][:-1], cumulative_histo_counts, width=bin_size)
Alternatively, you might want a curve instead of an histogram:
# pyplot.plot(histo[1][1:], cumulative_histo_counts)
If you want dates on the x axis instead of numbers, you can convert the numbers back to dates and ask matplotlib to use date strings as ticks, instead of numbers:
from matplotlib import ticker
# The format for the x axis is set to the chosen string, as defined from a numerical date:
pyplot.gca().xaxis.set_major_formatter(ticker.FuncFormatter(lambda numdate, _: num2date(numdate).strftime('%Y-%d-%m')))
# The formatting proper is done:
pyplot.gcf().autofmt_xdate()
# To show the result:
pyplot.show() # or draw(), if you don't want to block
Here, gca() and gcf() return the current axis and figure, respectively.
Of course, you can adapt the way you display dates, in the call to strftime() above.
To go beyond your question, I would like to mention that Matplotlib's gallery is a very good source of information: you can generally quickly find what you need by just finding images that look like what you're trying to do, and looking at their source code.
| Plotting a cumulative graph of python datetimes | Say I have a list of datetimes, and we know each datetime to be the recorded time of an event happening.
Is it possible in matplotlib to graph the frequency of this event occurring over time, showing this data in a cumulative graph (so that each point is greater or equal to all of the points that went before it), without preprocessing this list? (e.g. passing datetime objects directly to some wonderful matplotlib function)
Or do I need to turn this list of datetimes into a list of dictionary items, such as:
{"year": 1998, "month": 12, "date": 15, "events": 92}
and then generate a graph from this list?
| [
"This should work for you:\ncounts = arange(0, len(list_of_dates))\nplot(list_of_dates, counts)\n\nYou can of course give any of the usual options to the plot call to make the graph look the way you want it. (I'll point out that matplotlib is very adept at handling dates and times.)\nAnother option would be the hist function - it has an option 'cumulative=True' that might be useful. You can create a cumulative histogram showing the number of events that have occurred as of any given date something like this:\nfrom pyplot import hist\nfrom matplotlib.dates import date2num\nhist(date2num(list_of_dates), cumulative=True)\n\nBut this produces a bar chart, which might not be quite what you're looking for, and in any case making the date labels on the horizontal axis display properly will probably require some fudging.\nEDIT: I'm getting the sense that what you really want is one point (or bar) per date, with the corresponding y-value being the number of events that have occurred up to (and including?) that date. In that case, I'd suggest doing something like this:\ngrouped_dates = [[d, len(list(g))] for d,g in itertools.groupby(list_of_dates, lambda k: k.date())]\ndates, counts = grouped_dates.transpose()\ncounts = counts.cumsum()\nstep(dates, counts)\n\nThe groupby function from the itertools module will produce the kind of data you're looking for: only a single instance of each date, accompanied by a list (an iterator, actually) of all the datetime objects that have that date. As suggested by Jouni in the comments, the step function will give a graph that steps up at each day on which events occurred, so I'd suggest using that in place of plot.\n(Hat tip to EOL for reminding me about cumsum)\nIf you want to have one point for every day, regardless of whether any events occurred on that day or not, you'll need to alter the above code a bit:\nfrom matplotlib.dates import drange, num2date\ndate_dict = dict((d, len(list(g))) for d,g in itertools.groupby(list_of_dates, lambda k: k.date()))\ndates = num2date(drange(min(list_of_dates).date(), max(list_of_dates).date() + timedelta(1), timedelta(1)))\ncounts = asarray([date_dict.get(d.date(), 0) for d in dates]).cumsum()\nstep(dates, counts)\n\nI don't think it'll really make a difference for the plot produced by the step function though.\n",
"So, you start with a list of dates that you want to histogram:\nfrom datetime import datetime\nlist_of_datetime_datetime_objects = [datetime(2010, 6, 14), datetime(1974, 2, 8), datetime(1974, 2, 8)]\n\nMatplotlib allows you to convert a datetime.datetime object into a simple number, as David mentioned:\nfrom matplotlib.dates import date2num, num2date\nnum_dates = [date2num(d) for d in list_of_datetime_datetime_objects]\n\nYou can then calculate the histogram of your data (look at NumPy histogram docs for more options (number of bins, etc.)):\nimport numpy\nhisto = numpy.histogram(num_dates)\n\nSince you want the cumulative histogram, you add individual counts together:\ncumulative_histo_counts = histo[0].cumsum()\n\nThe histogram plot will need the bin size:\nfrom matplotlib import pyplot\n\nYou can then plot the cumulative histogram:\nbin_size = histo[1][1]-histo[1][0]\npyplot.bar(histo[1][:-1], cumulative_histo_counts, width=bin_size)\n\nAlternatively, you might want a curve instead of an histogram:\n# pyplot.plot(histo[1][1:], cumulative_histo_counts)\n\nIf you want dates on the x axis instead of numbers, you can convert the numbers back to dates and ask matplotlib to use date strings as ticks, instead of numbers:\nfrom matplotlib import ticker\n\n# The format for the x axis is set to the chosen string, as defined from a numerical date:\npyplot.gca().xaxis.set_major_formatter(ticker.FuncFormatter(lambda numdate, _: num2date(numdate).strftime('%Y-%d-%m')))\n# The formatting proper is done:\npyplot.gcf().autofmt_xdate()\n# To show the result:\npyplot.show() # or draw(), if you don't want to block\n\nHere, gca() and gcf() return the current axis and figure, respectively.\nOf course, you can adapt the way you display dates, in the call to strftime() above.\nTo go beyond your question, I would like to mention that Matplotlib's gallery is a very good source of information: you can generally quickly find what you need by just finding images that look like what you're trying to do, and looking at their source code.\n\n"
] | [
13,
6
] | [
"I just use chart director from advanced software engineering. Really easy to deal with especially with dates. They have lots of examples too in python.\n"
] | [
-2
] | [
"datetime",
"graph",
"matplotlib",
"python"
] | stackoverflow_0003034162_datetime_graph_matplotlib_python.txt |
Q:
how to send F2 key to remote host using python
I have to send F2 key to telnet host. How do I send it using python...using getch() I found that the character < used for the F2 key but when sending >, its not working. I think there is a way to send special function keys but I am not able to find it. If somebody knows please help me. Thanks in advance
A:
Extended keys (non-alphanumeric or symbol) are composed of a sequence of single characters, with the sequence depending on the terminal you have told the telnet server you are using. You will need to send all characters in the sequence in order to make it work. Here, using od -c <<< 'CtrlVF2' I was able to see a sequence of \x1b0Q with the xterm terminal.
A:
First, as Ignacio pointed out, you have to determine the exact sequence of characters sent by F2. On my machine, this happens to be ^[OQ, where ^[ denotes an escape character with ASCII code 27. This is identical to what he got. You have to send the exact same byte sequence over telnet. Assuming that the correct sequence is the one I have shown above, it boils down to this:
import telnetlib
tn = telnetlib.Telnet(HOST, PORT)
tn.write(idpass)
tn.write("\x1b0Q")
tn.close()
In case you are wondering, \x1b stands for a character having ASCII code 27, since 27 in hexadecimal is 1b.
This works on my machine (tested by a simple echo server on the receiving end), so if it does not work for you, it means that the remote end expects something else in place of an F2 keypress.
| how to send F2 key to remote host using python | I have to send F2 key to telnet host. How do I send it using python...using getch() I found that the character < used for the F2 key but when sending >, its not working. I think there is a way to send special function keys but I am not able to find it. If somebody knows please help me. Thanks in advance
| [
"Extended keys (non-alphanumeric or symbol) are composed of a sequence of single characters, with the sequence depending on the terminal you have told the telnet server you are using. You will need to send all characters in the sequence in order to make it work. Here, using od -c <<< 'CtrlVF2' I was able to see a sequence of \\x1b0Q with the xterm terminal.\n",
"First, as Ignacio pointed out, you have to determine the exact sequence of characters sent by F2. On my machine, this happens to be ^[OQ, where ^[ denotes an escape character with ASCII code 27. This is identical to what he got. You have to send the exact same byte sequence over telnet. Assuming that the correct sequence is the one I have shown above, it boils down to this:\nimport telnetlib\n\ntn = telnetlib.Telnet(HOST, PORT)\ntn.write(idpass)\ntn.write(\"\\x1b0Q\")\ntn.close()\n\nIn case you are wondering, \\x1b stands for a character having ASCII code 27, since 27 in hexadecimal is 1b.\nThis works on my machine (tested by a simple echo server on the receiving end), so if it does not work for you, it means that the remote end expects something else in place of an F2 keypress.\n"
] | [
4,
3
] | [] | [] | [
"python",
"telnet"
] | stackoverflow_0003035390_python_telnet.txt |
Q:
Which programming language for compute-intensive trading portfolio simulation?
I am building a trading portfolio management system that is responsible for production, optimization, and simulation of non-high frequency trading portfolios (dealing with 1min or 3min bars of data, not tick data).
I plan on employing Amazon web services to take on the entire load of the application.
I have four choices that I am considering as language.
Java
C++
C#
Python
Here is the scope of the extremes of the project scope. This isn't how it will be, maybe ever, but it's within the scope of the requirements:
Weekly simulation of 10,000,000 trading systems.
(Each trading system is expected to have its own data mining methods, including feature selection algorithms which are extremely computationally-expensive. Imagine 500-5000 features using wrappers. These are not run often by any means, but it's still a consideration)
Real-time production of portfolio w/ 100,000 trading strategies
Taking in 1 min or 3 min data from every stock/futures market around the globe (approx 100,000)
Portfolio optimization of portfolios with up to 100,000 strategies. (rather intensive algorithm)
Speed is a concern, but I believe that Java can handle the load.
I just want to make sure that Java CAN handle the above requirements comfortably. I don't want to do the project in C++, but I will if it's required.
The reason C# is on there is because I thought it was a good alternative to Java, even though I don't like Windows at all and would prefer Java if all things are the same.
Python - I've read somethings on PyPy and pyscho that claim python can be optimized with JIT compiling to run at near C-like speeds... That's pretty much the only reason it is on this list, besides that fact that Python is a great language and would probably be the most enjoyable language to code in, which is not a factor at all for this project, but a perk.
To sum up:
real time production
weekly simulations of a large number of systems
weekly/monthly optimizations of portfolios
large numbers of connections to collect data from
There is no dealing with millisecond or even second based trades. The only consideration is if Java can possibly deal with this kind of load when spread out of a necessary amount of EC2 servers.
Thank you guys so much for your wisdom.
A:
Pick the language you are most familiar with. If you know them all equally and speed is a real concern, pick C.
A:
While I am a huge fan of Python and personaly I'm not a great lover of Java, in this case I have to concede that Java is the right way to go.
For many projects Python's performance just isn't a problem, but in your case even minor performance penalties will add up extremely quickly. I know this isn't a real-time simulation, but even for batch processing it's still a factor to take into consideration. If it turns out the load is too big for one virtual server, an implementation that's twice as fast will halve your virtual server costs.
For many projects I'd also argue that Python will allow you to develop a solution faster, but here I'm not sure that would be the case. Java has world-class development tools and top-drawer enterprise grade frameworks for parallell processing and cross-server deployment and while Python has solutions in this area, Java clearly has the edge. You also have architectural options with Java that Python can't match, such as Javaspaces.
I would argue that C and C++ impose too much of a development overhead for a project like this. They're viable inthat if you are very familiar with those languages I'm sure it would be doable, but other than the potential for higher performance, they have nothing else to bring to the table.
C# is just a rewrite of Java. That's not a bad thing if you're a Windows developer and if you prefer Windows I'd use C# rather than Java, but if you don't care about Windows there's no reason to care about C#.
A:
Write it in your preferred language. To me that sounds like python. When you start running the system you can profile it and see where the bottlenecks are. Once you do some basic optimisations if it's still not acceptable you can rewrite portions in C.
A consideration could be writing this in iron python to take advantage of the clr and dlr in .net. Then you can leverage .net 4 and parallel extensions. If anything will give you performance increases it'll be some flavour of threading which .net does extremely well.
Edit:
Just wanted to make this part clear. From the description, it sounds like parallel processing / multithreading is where the majority of the performance gains are going to come from.
A:
I would pick Java for this task. In terms of RAM, the difference between Java and C++ is that in Java, each Object has an overhead of 8 Bytes (using the Sun 32-bit JVM or the Sun 64-bit JVM with compressed pointers). So if you have millions of objects flying around, this can make a difference. In terms of speed, Java and C++ are almost equal at that scale.
So the more important thing for me is the development time. If you make a mistake in C++, you get a segmentation fault (and sometimes you don't even get that), while in Java you get a nice Exception with a stack trace. I have always preferred this.
In C++ you can have collections of primitive types, which Java hasn't. You would have to use external libraries to get them.
If you have real-time requirements, the Java garbage collector may be a nuisance, since it takes some minutes to collect a 20 GB heap, even on machines with 24 cores. But if you don't create too many temporary objects during runtime, that should be fine, too. It's just that your program can make that garbage collection pause whenever you don't expect it.
A:
Why only one language for your system? If I were you, I will build the entire system in Python, but C or C++ will be used for performance-critical components. In this way, you will have a very flexible and extendable system with fast-enough performance. You can find even tools to generate wrappers automatically (e.g. SWIG, Cython). Python and C/C++/Java/Fortran are not competing each other; they are complementing.
A:
It is useful to look at the inner loop of your numerical code. After all you will spend most of your CPU-time inside this loop.
If the inner loop is a matrix operation, then I suggest python and scipy, but of the inner loop if not a matrix operation, then I would worry about python being slow. (Or maybe I would wrap c++ in python using swig or boost::python)
The benefit of python is that it is easy to debug, and you save a lot of time by not having to compile all the time. This is especially useful for a project where you spend a lot of time programming deep internals.
| Which programming language for compute-intensive trading portfolio simulation? | I am building a trading portfolio management system that is responsible for production, optimization, and simulation of non-high frequency trading portfolios (dealing with 1min or 3min bars of data, not tick data).
I plan on employing Amazon web services to take on the entire load of the application.
I have four choices that I am considering as language.
Java
C++
C#
Python
Here is the scope of the extremes of the project scope. This isn't how it will be, maybe ever, but it's within the scope of the requirements:
Weekly simulation of 10,000,000 trading systems.
(Each trading system is expected to have its own data mining methods, including feature selection algorithms which are extremely computationally-expensive. Imagine 500-5000 features using wrappers. These are not run often by any means, but it's still a consideration)
Real-time production of portfolio w/ 100,000 trading strategies
Taking in 1 min or 3 min data from every stock/futures market around the globe (approx 100,000)
Portfolio optimization of portfolios with up to 100,000 strategies. (rather intensive algorithm)
Speed is a concern, but I believe that Java can handle the load.
I just want to make sure that Java CAN handle the above requirements comfortably. I don't want to do the project in C++, but I will if it's required.
The reason C# is on there is because I thought it was a good alternative to Java, even though I don't like Windows at all and would prefer Java if all things are the same.
Python - I've read somethings on PyPy and pyscho that claim python can be optimized with JIT compiling to run at near C-like speeds... That's pretty much the only reason it is on this list, besides that fact that Python is a great language and would probably be the most enjoyable language to code in, which is not a factor at all for this project, but a perk.
To sum up:
real time production
weekly simulations of a large number of systems
weekly/monthly optimizations of portfolios
large numbers of connections to collect data from
There is no dealing with millisecond or even second based trades. The only consideration is if Java can possibly deal with this kind of load when spread out of a necessary amount of EC2 servers.
Thank you guys so much for your wisdom.
| [
"Pick the language you are most familiar with. If you know them all equally and speed is a real concern, pick C. \n",
"While I am a huge fan of Python and personaly I'm not a great lover of Java, in this case I have to concede that Java is the right way to go.\nFor many projects Python's performance just isn't a problem, but in your case even minor performance penalties will add up extremely quickly. I know this isn't a real-time simulation, but even for batch processing it's still a factor to take into consideration. If it turns out the load is too big for one virtual server, an implementation that's twice as fast will halve your virtual server costs.\nFor many projects I'd also argue that Python will allow you to develop a solution faster, but here I'm not sure that would be the case. Java has world-class development tools and top-drawer enterprise grade frameworks for parallell processing and cross-server deployment and while Python has solutions in this area, Java clearly has the edge. You also have architectural options with Java that Python can't match, such as Javaspaces.\nI would argue that C and C++ impose too much of a development overhead for a project like this. They're viable inthat if you are very familiar with those languages I'm sure it would be doable, but other than the potential for higher performance, they have nothing else to bring to the table.\nC# is just a rewrite of Java. That's not a bad thing if you're a Windows developer and if you prefer Windows I'd use C# rather than Java, but if you don't care about Windows there's no reason to care about C#.\n",
"Write it in your preferred language. To me that sounds like python. When you start running the system you can profile it and see where the bottlenecks are. Once you do some basic optimisations if it's still not acceptable you can rewrite portions in C. \nA consideration could be writing this in iron python to take advantage of the clr and dlr in .net. Then you can leverage .net 4 and parallel extensions. If anything will give you performance increases it'll be some flavour of threading which .net does extremely well.\nEdit:\nJust wanted to make this part clear. From the description, it sounds like parallel processing / multithreading is where the majority of the performance gains are going to come from.\n",
"I would pick Java for this task. In terms of RAM, the difference between Java and C++ is that in Java, each Object has an overhead of 8 Bytes (using the Sun 32-bit JVM or the Sun 64-bit JVM with compressed pointers). So if you have millions of objects flying around, this can make a difference. In terms of speed, Java and C++ are almost equal at that scale.\nSo the more important thing for me is the development time. If you make a mistake in C++, you get a segmentation fault (and sometimes you don't even get that), while in Java you get a nice Exception with a stack trace. I have always preferred this.\nIn C++ you can have collections of primitive types, which Java hasn't. You would have to use external libraries to get them.\nIf you have real-time requirements, the Java garbage collector may be a nuisance, since it takes some minutes to collect a 20 GB heap, even on machines with 24 cores. But if you don't create too many temporary objects during runtime, that should be fine, too. It's just that your program can make that garbage collection pause whenever you don't expect it.\n",
"Why only one language for your system? If I were you, I will build the entire system in Python, but C or C++ will be used for performance-critical components. In this way, you will have a very flexible and extendable system with fast-enough performance. You can find even tools to generate wrappers automatically (e.g. SWIG, Cython). Python and C/C++/Java/Fortran are not competing each other; they are complementing. \n",
"It is useful to look at the inner loop of your numerical code. After all you will spend most of your CPU-time inside this loop. \nIf the inner loop is a matrix operation, then I suggest python and scipy, but of the inner loop if not a matrix operation, then I would worry about python being slow. (Or maybe I would wrap c++ in python using swig or boost::python)\nThe benefit of python is that it is easy to debug, and you save a lot of time by not having to compile all the time. This is especially useful for a project where you spend a lot of time programming deep internals.\n"
] | [
6,
5,
4,
4,
4,
0
] | [
"I would go with pypy. If not, http://lolcode.com/.\n"
] | [
-1
] | [
"java",
"python",
"trading"
] | stackoverflow_0003031225_java_python_trading.txt |
Q:
python global variable not working in apache
I am facing issue with the global variable, when i run in the django development server it works fine, but in apache it doesn't work
here is the code below:
red= "/project3/test/"
def showAddRecipe(request):
#global objc
if "userid" in request.session:
objc["ErrorMsgURL"]= ""
try:
urlList= request.POST
URL= str(urlList['url'])
URL= URL.strip('http://')
URL= "http://" + URL
recipe= __addRecipeUrl__(URL)
if (recipe == 'FailToOpenURL') or (recipe == 'Invalid-website-URL'):
#request.session["ErrorMsgURL"]= "Kindly check URL, Please enter a valid URL"
objc["ErrorMsgURL"]= "Kindly check URL, Please enter a valid URL"
print "here global_context =", objc
arurl= HttpResponseRedirect("/project3/add/import/")
arurl['ErrorMsgURL']= objc["ErrorMsgURL"]
#return HttpResponseRedirect("/project3/add/import/")
#return render_to_response('addRecipeUrl.html', objc, context_instance = RequestContext(request))
return (arurl)
else:
objc["recipe"] = recipe
return render_to_response('addRecipe.html',
objc,
context_instance = RequestContext(request))
except:
objc["recipe"] = ""
return render_to_response('addRecipe.html',
objc,
context_instance = RequestContext(request))
else:
global red
red= "/project3/add/"
return HttpResponseRedirect("/project3/login")
def showAddRecipeUrl(request):
if "userid" in request.session:
return render_to_response('addRecipeUrl.html',
objc,
context_instance = RequestContext(request))
else:
global red
red= "/project3/add/import/"
return HttpResponseRedirect("/project3/login")
def showLogin(request):
obj = {}
obj["error_message"] = ""
obj["registered"] = ""
if request.method == "POST":
if (red == "/project3/test"):
next= '/project3/recipes'
else:
next= red
try:
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
except:
user = authenticate(request=request)
if user is not None:
if user.is_active:
login(request, user)
request.session["userid"] = user.id
# Redirect to a success page.
return HttpResponseRedirect(next)
this code works fine in django development server, but in apache, the url is getting redirected to '/project3/recipes'
A:
I would guess that you use Apache's CGI capabilities. That means that with each request the script is started anew. Which means that the global variable is initialized with each call.
Apart from that it isn't really a good idea to use globals to store what is in essence session data (with a session, and thus state, per user). Globals are for all users the same, and sessions are per user, which is what you (should) want.
In your case that session's data should probably be stored in some database, as the python interpreter will end when your script is finished and a single page is rendered.
A:
As you have been told before, using global objects is a recipe for disaster in a multi-process environment like a live Apache site. You will have multiple users all accessing each others' variables, and this will never work as you want.
extraneon is correct that you should use sessions for this - that is what they are for. From your comment to his answer it is obvious that you have not read the sessions documentation - you should do so now.
A:
Hey guys thanks for the help, yes i know using global variables is an incorrect way of doing it, but i was not able to get it work, but now its working, here's the code below:
def showAddRecipe(request):
#global objc
if "userid" in request.session:
objc["ErrorMsgURL"]= ""
try:
urlList= request.POST
URL= str(urlList['url'])
URL= URL.strip('http://')
URL= "http://" + URL
recipe= __addRecipeUrl__(URL)
if (recipe == 'FailToOpenURL') or (recipe == 'Invalid-website-URL'):
#request.session["ErrorMsgURL"]= "Kindly check URL, Please enter a valid URL"
objc["ErrorMsgURL"]= "Kindly check URL, Please enter a valid URL"
print "here global_context =", objc
arurl= HttpResponseRedirect("/project3/add/import/")
arurl['ErrorMsgURL']= objc["ErrorMsgURL"]
#return HttpResponseRedirect("/project3/add/import/")
#return render_to_response('addRecipeUrl.html', objc, context_instance = RequestContext(request))
return (arurl)
else:
objc["recipe"] = recipe
return render_to_response('addRecipe.html',
objc,
context_instance = RequestContext(request))
except:
objc["recipe"] = ""
return render_to_response('addRecipe.html',
objc,
context_instance = RequestContext(request))
else:
request.session['red']= "/project3/add"
return HttpResponseRedirect("/project3/login")
def showAddRecipeUrl(request):
if "userid" in request.session:
return render_to_response('addRecipeUrl.html',
objc,
context_instance = RequestContext(request))
else:
request.session['red']= "/project3/add/import"
return HttpResponseRedirect("/project3/login")
def showLogin(request):
obj = {}
obj["error_message"] = ""
obj["registered"] = ""
if request.method == "POST":
if ('red' not in request.session) or (not request.session["red"]):
print "in if "
next= '/project3/recipes/'
else:
print "in else"
next= request.session["red"]
try:
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
except:
user = authenticate(request=request)
if user is not None:
if user.is_active:
login(request, user)
request.session["userid"] = user.id
# Redirect to a success page.
return HttpResponseRedirect(next)
| python global variable not working in apache | I am facing issue with the global variable, when i run in the django development server it works fine, but in apache it doesn't work
here is the code below:
red= "/project3/test/"
def showAddRecipe(request):
#global objc
if "userid" in request.session:
objc["ErrorMsgURL"]= ""
try:
urlList= request.POST
URL= str(urlList['url'])
URL= URL.strip('http://')
URL= "http://" + URL
recipe= __addRecipeUrl__(URL)
if (recipe == 'FailToOpenURL') or (recipe == 'Invalid-website-URL'):
#request.session["ErrorMsgURL"]= "Kindly check URL, Please enter a valid URL"
objc["ErrorMsgURL"]= "Kindly check URL, Please enter a valid URL"
print "here global_context =", objc
arurl= HttpResponseRedirect("/project3/add/import/")
arurl['ErrorMsgURL']= objc["ErrorMsgURL"]
#return HttpResponseRedirect("/project3/add/import/")
#return render_to_response('addRecipeUrl.html', objc, context_instance = RequestContext(request))
return (arurl)
else:
objc["recipe"] = recipe
return render_to_response('addRecipe.html',
objc,
context_instance = RequestContext(request))
except:
objc["recipe"] = ""
return render_to_response('addRecipe.html',
objc,
context_instance = RequestContext(request))
else:
global red
red= "/project3/add/"
return HttpResponseRedirect("/project3/login")
def showAddRecipeUrl(request):
if "userid" in request.session:
return render_to_response('addRecipeUrl.html',
objc,
context_instance = RequestContext(request))
else:
global red
red= "/project3/add/import/"
return HttpResponseRedirect("/project3/login")
def showLogin(request):
obj = {}
obj["error_message"] = ""
obj["registered"] = ""
if request.method == "POST":
if (red == "/project3/test"):
next= '/project3/recipes'
else:
next= red
try:
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
except:
user = authenticate(request=request)
if user is not None:
if user.is_active:
login(request, user)
request.session["userid"] = user.id
# Redirect to a success page.
return HttpResponseRedirect(next)
this code works fine in django development server, but in apache, the url is getting redirected to '/project3/recipes'
| [
"I would guess that you use Apache's CGI capabilities. That means that with each request the script is started anew. Which means that the global variable is initialized with each call.\nApart from that it isn't really a good idea to use globals to store what is in essence session data (with a session, and thus state, per user). Globals are for all users the same, and sessions are per user, which is what you (should) want. \nIn your case that session's data should probably be stored in some database, as the python interpreter will end when your script is finished and a single page is rendered.\n",
"As you have been told before, using global objects is a recipe for disaster in a multi-process environment like a live Apache site. You will have multiple users all accessing each others' variables, and this will never work as you want.\nextraneon is correct that you should use sessions for this - that is what they are for. From your comment to his answer it is obvious that you have not read the sessions documentation - you should do so now.\n",
"Hey guys thanks for the help, yes i know using global variables is an incorrect way of doing it, but i was not able to get it work, but now its working, here's the code below:\ndef showAddRecipe(request):\n #global objc\n if \"userid\" in request.session:\n objc[\"ErrorMsgURL\"]= \"\"\n try:\n urlList= request.POST\n URL= str(urlList['url'])\n URL= URL.strip('http://')\n URL= \"http://\" + URL\n\n recipe= __addRecipeUrl__(URL)\n\n if (recipe == 'FailToOpenURL') or (recipe == 'Invalid-website-URL'):\n #request.session[\"ErrorMsgURL\"]= \"Kindly check URL, Please enter a valid URL\"\n objc[\"ErrorMsgURL\"]= \"Kindly check URL, Please enter a valid URL\"\n print \"here global_context =\", objc\n arurl= HttpResponseRedirect(\"/project3/add/import/\")\n arurl['ErrorMsgURL']= objc[\"ErrorMsgURL\"]\n #return HttpResponseRedirect(\"/project3/add/import/\")\n #return render_to_response('addRecipeUrl.html', objc, context_instance = RequestContext(request))\n return (arurl)\n else:\n objc[\"recipe\"] = recipe\n return render_to_response('addRecipe.html',\n objc,\n context_instance = RequestContext(request))\n except:\n objc[\"recipe\"] = \"\"\n return render_to_response('addRecipe.html',\n objc,\n context_instance = RequestContext(request))\n else:\n request.session['red']= \"/project3/add\"\n return HttpResponseRedirect(\"/project3/login\")\n\n\n\ndef showAddRecipeUrl(request):\n if \"userid\" in request.session:\n return render_to_response('addRecipeUrl.html',\n objc, \n context_instance = RequestContext(request))\n else:\n request.session['red']= \"/project3/add/import\"\n return HttpResponseRedirect(\"/project3/login\")\n\n\ndef showLogin(request):\n obj = {}\n obj[\"error_message\"] = \"\"\n obj[\"registered\"] = \"\"\n\n if request.method == \"POST\":\n if ('red' not in request.session) or (not request.session[\"red\"]):\n print \"in if \"\n next= '/project3/recipes/'\n else:\n print \"in else\"\n next= request.session[\"red\"]\n\n try:\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(username=username, password=password)\n except:\n user = authenticate(request=request)\n\n if user is not None:\n if user.is_active:\n login(request, user)\n request.session[\"userid\"] = user.id\n\n # Redirect to a success page.\n return HttpResponseRedirect(next)\n\n"
] | [
3,
0,
0
] | [] | [] | [
"apache",
"django",
"global_variables",
"python"
] | stackoverflow_0003035776_apache_django_global_variables_python.txt |
Q:
Storing task state between multiple django processes
I am building a logging-bridge between rabbitmq messages and Django application to store background task state in the database for further investigation/review, also to make it possible to re-publish tasks via the Django admin interface.
I guess it's nothing fancy, just a standard Producer-Consumer pattern.
Web application publishes to message queue and inserts initial task state into the database
Consumer, which is a separate python process, handles the message and updates the task state depending on task output
The problem is, some tasks are missing in the db and therefore never executed.
I suspect it's because Consumer receives the message earlier than db commit is performed.
So basically, returning from Model.save() doesn't mean the transaction has ended and the whole communication breaks.
Is there any way I could fix this? Maybe some kind of post_transaction signal I could use?
Thank you in advance.
A:
This sounds brittle to me: You have a web app which posts to a queue and then inserts the initial state into the database. What happens if the consumer processes the message before the web app can commit the initial state?
What happens if the web app tries to insert the new state while the DB is locked by the consumer?
To fix this, the web app should add the initial state to the message and the consumer should be the only one ever writing to the DB.
[EDIT] And you might also have an issue with logging. Check that races between the web app and the consumer produce the appropriate errors in the log by putting a message to the queue without modifying the DB.
[EDIT2] Some ideas:
How about showing just the number of pending tasks? For this, the web app could write into table 1 and the consumer writes into table 2 and the admin if would show the difference.
Why can't the web app see the pending tasks which the consumer has in the queue? Maybe you should have two consumers. The first consumer just adds the task to the DB, commits and then sends a message to the second consumer with just the primary key of the new row. The admin iface could read the table while the second consumer writes to it.
Last idea: Commit the transaction before you enqueue the message. For this, you simply have to send "commit" to the database. It will feel odd (and I certainly don't recommend it for any case) but here, it might make sense to commit the new row manually (i.e. before you return to your framework which handles the normal transaction logic).
A:
Web application publishes to message queue and inserts initial task state into the database
Do not do this.
Web application publishes to the queue. Done. Present results via template and finish the web transaction.
A consumer fetches from the queue and does things. For example, it might append to a log to the database for presentation to the user. The consumer may also post additional status to the database as it executes things.
Indeed, many applications have multiple queues with multiple produce/consumer relationships. Each process might append things to a log.
The presentation must then summarize the log entries. Often, the last one is a sufficient summary, but sometimes you need a count or information from earlier entries.
| Storing task state between multiple django processes | I am building a logging-bridge between rabbitmq messages and Django application to store background task state in the database for further investigation/review, also to make it possible to re-publish tasks via the Django admin interface.
I guess it's nothing fancy, just a standard Producer-Consumer pattern.
Web application publishes to message queue and inserts initial task state into the database
Consumer, which is a separate python process, handles the message and updates the task state depending on task output
The problem is, some tasks are missing in the db and therefore never executed.
I suspect it's because Consumer receives the message earlier than db commit is performed.
So basically, returning from Model.save() doesn't mean the transaction has ended and the whole communication breaks.
Is there any way I could fix this? Maybe some kind of post_transaction signal I could use?
Thank you in advance.
| [
"This sounds brittle to me: You have a web app which posts to a queue and then inserts the initial state into the database. What happens if the consumer processes the message before the web app can commit the initial state?\nWhat happens if the web app tries to insert the new state while the DB is locked by the consumer?\nTo fix this, the web app should add the initial state to the message and the consumer should be the only one ever writing to the DB.\n[EDIT] And you might also have an issue with logging. Check that races between the web app and the consumer produce the appropriate errors in the log by putting a message to the queue without modifying the DB.\n[EDIT2] Some ideas: \nHow about showing just the number of pending tasks? For this, the web app could write into table 1 and the consumer writes into table 2 and the admin if would show the difference. \nWhy can't the web app see the pending tasks which the consumer has in the queue? Maybe you should have two consumers. The first consumer just adds the task to the DB, commits and then sends a message to the second consumer with just the primary key of the new row. The admin iface could read the table while the second consumer writes to it.\nLast idea: Commit the transaction before you enqueue the message. For this, you simply have to send \"commit\" to the database. It will feel odd (and I certainly don't recommend it for any case) but here, it might make sense to commit the new row manually (i.e. before you return to your framework which handles the normal transaction logic).\n",
"\nWeb application publishes to message queue and inserts initial task state into the database\n\nDo not do this.\nWeb application publishes to the queue. Done. Present results via template and finish the web transaction.\nA consumer fetches from the queue and does things. For example, it might append to a log to the database for presentation to the user. The consumer may also post additional status to the database as it executes things.\nIndeed, many applications have multiple queues with multiple produce/consumer relationships. Each process might append things to a log. \nThe presentation must then summarize the log entries. Often, the last one is a sufficient summary, but sometimes you need a count or information from earlier entries.\n"
] | [
0,
0
] | [] | [] | [
"django",
"multiprocessing",
"python",
"rabbitmq",
"transactions"
] | stackoverflow_0003036049_django_multiprocessing_python_rabbitmq_transactions.txt |
Q:
Emacs 23 hangs on python mode when typing string block """
My Emacs hangs (Ubuntu 9 + Emacs 23 + Pyflakes) when I type """ quotes for string blocks.
Anybody experienced the same problem? I think, it may not be an Emacs problem but some Python mode or Pyflakes which I use it for error checking.
Anybody got around the issue? It is a really frustrating experience.
A:
latest pyflakes in development mode fixed this problem for me. Thanks all
sudo easy_install -U pyflakes
A:
are you using the external python-mode (from package python-mode) or the internal python mode ? I use pyflakes with the internal emacs python mode without any problems and this is my configuration :
(when (load "flymake" t)
(defun flymake-pyflakes-init ()
(let* ((temp-file (flymake-init-create-temp-buffer-copy
'flymake-create-temp-inplace))
(local-file (file-relative-name
temp-file
(file-name-directory buffer-file-name))))
(list "pyflakes" (list local-file))))
(add-to-list 'flymake-allowed-file-name-masks
'("\\.py\\'" flymake-pyflakes-init)))
A:
This is the specific pyflakes bug that causes emacs to go nonlinear: http://divmod.org/trac/ticket/2821
| Emacs 23 hangs on python mode when typing string block """ | My Emacs hangs (Ubuntu 9 + Emacs 23 + Pyflakes) when I type """ quotes for string blocks.
Anybody experienced the same problem? I think, it may not be an Emacs problem but some Python mode or Pyflakes which I use it for error checking.
Anybody got around the issue? It is a really frustrating experience.
| [
"latest pyflakes in development mode fixed this problem for me. Thanks all\nsudo easy_install -U pyflakes\n",
"are you using the external python-mode (from package python-mode) or the internal python mode ? I use pyflakes with the internal emacs python mode without any problems and this is my configuration :\n(when (load \"flymake\" t)\n(defun flymake-pyflakes-init ()\n (let* ((temp-file (flymake-init-create-temp-buffer-copy\n 'flymake-create-temp-inplace))\n (local-file (file-relative-name\n temp-file\n (file-name-directory buffer-file-name))))\n (list \"pyflakes\" (list local-file))))\n(add-to-list 'flymake-allowed-file-name-masks\n '(\"\\\\.py\\\\'\" flymake-pyflakes-init)))\n\n",
"This is the specific pyflakes bug that causes emacs to go nonlinear: http://divmod.org/trac/ticket/2821\n"
] | [
3,
1,
0
] | [] | [] | [
"emacs",
"pyflakes",
"python"
] | stackoverflow_0001406213_emacs_pyflakes_python.txt |
Q:
python unit testing os.remove fails file system
Am doing a bit of unit testing on a function which attempts to open a new file, but should fail if the file already exists. when the function runs sucessfully, the new file is created, so i want to delete it after every test run, but it doesn't seem to be working:
class MyObject_Initialisation(unittest.TestCase):
def setUp(self):
if os.path.exists(TEMPORARY_FILE_NAME):
try:
os.remove(TEMPORARY_FILE_NAME)
except WindowsError:
#TODO: can't figure out how to fix this...
#time.sleep(3)
#self.setUp() #this just loops forever
pass
def tearDown(self):
self.setUp()
any thoughts? The Windows Error thrown seems to suggest the file is in use... could it be that the tests are run in parallel threads?
I've read elsewhere that it's 'bad practice' to use the filesystem in unit testing, but really? Surely there's a way around this that doesn't invole dummying the filesystem?
A:
If you're just looking for a temporary file, have a look at tempfile - this should handle the clean-up all on its own.
A:
Do you remember to explicitly close file handler that operates on TEMPORARY_FILE_NAME?
From Python Documentation:
On Windows, attempting to remove a
file that is in use causes an
exception to be raised;
| python unit testing os.remove fails file system | Am doing a bit of unit testing on a function which attempts to open a new file, but should fail if the file already exists. when the function runs sucessfully, the new file is created, so i want to delete it after every test run, but it doesn't seem to be working:
class MyObject_Initialisation(unittest.TestCase):
def setUp(self):
if os.path.exists(TEMPORARY_FILE_NAME):
try:
os.remove(TEMPORARY_FILE_NAME)
except WindowsError:
#TODO: can't figure out how to fix this...
#time.sleep(3)
#self.setUp() #this just loops forever
pass
def tearDown(self):
self.setUp()
any thoughts? The Windows Error thrown seems to suggest the file is in use... could it be that the tests are run in parallel threads?
I've read elsewhere that it's 'bad practice' to use the filesystem in unit testing, but really? Surely there's a way around this that doesn't invole dummying the filesystem?
| [
"If you're just looking for a temporary file, have a look at tempfile - this should handle the clean-up all on its own. \n",
"Do you remember to explicitly close file handler that operates on TEMPORARY_FILE_NAME?\nFrom Python Documentation:\n\nOn Windows, attempting to remove a\n file that is in use causes an\n exception to be raised;\n\n"
] | [
2,
2
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0003036487_python_unit_testing.txt |
Q:
Mailboxes with Stackless
In my stackless application I'd like to have Erlang style message box queues. Instead of mandating that sending tasklets are blocked until the receiving tasklet is ready to receive, I'd like to have the sending tasklet to queue up the message in the receiver's message box, and be able to wake the receiver if it's sleeping.
The sending tasklet should be able to send a message and then continue executing, regardless of the state of the receiving tasklet.
I'm sure there's a way to do this, I just haven't found it yet...
A:
This may not be exactly what you are looking for, but still worth a shot:
gevent is a Python library that provides high-level APIs over greenlets, which are similar to tasklets (actually, it's a spin-off of Stackless Python. There are some differences, though: you don't need a special interpreter and a few more).
gevent provides an API similar to Python's native Queue - i.e. you can put objects in it, read from it (blocking or non-blocking, with or without timeouts).
| Mailboxes with Stackless | In my stackless application I'd like to have Erlang style message box queues. Instead of mandating that sending tasklets are blocked until the receiving tasklet is ready to receive, I'd like to have the sending tasklet to queue up the message in the receiver's message box, and be able to wake the receiver if it's sleeping.
The sending tasklet should be able to send a message and then continue executing, regardless of the state of the receiving tasklet.
I'm sure there's a way to do this, I just haven't found it yet...
| [
"This may not be exactly what you are looking for, but still worth a shot:\ngevent is a Python library that provides high-level APIs over greenlets, which are similar to tasklets (actually, it's a spin-off of Stackless Python. There are some differences, though: you don't need a special interpreter and a few more).\ngevent provides an API similar to Python's native Queue - i.e. you can put objects in it, read from it (blocking or non-blocking, with or without timeouts).\n"
] | [
2
] | [] | [] | [
"python",
"stackless"
] | stackoverflow_0002976049_python_stackless.txt |
Q:
Regular expressions in a Python find-and-replace script? Update
I'm new to Python scripting, so please forgive me in advance if the answer to this question seems inherently obvious.
I'm trying to put together a large-scale find-and-replace script using Python. I'm using code similar to the following:
infile = sys.argv[1]
charenc = sys.argv[2]
outFile=infile+'.output'
findreplace = [
('term1', 'term2'),
]
inF = open(infile,'rb')
s=unicode(inF.read(),charenc)
inF.close()
for couple in findreplace:
outtext=s.replace(couple[0],couple[1])
s=outtext
outF = open(outFile,'wb')
outF.write(outtext.encode('utf-8'))
outF.close()
How would I go about having the script do a find and replace for regular expressions?
Specifically, I want it to find some information (metadata) specified at the top of a text file. Eg:
Title: This is the title
Author: This is the author
Date: This is the date
and convert it into LaTeX format. Eg:
\title{This is the title}
\author{This is the author}
\date{This is the date}
Maybe I'm tackling this the wrong way. If there's a better way than regular expressions please let me know!
Thanks!
Update: Thanks for posting some example code in your answers! I can get it to work so long as I replace the findreplace action, but I can't get both to work. The problem now is I can't integrate it properly into the code I've got. How would I go about having the script do multiple actions on 'outtext' in the below snippet?
for couple in findreplace:
outtext=s.replace(couple[0],couple[1])
s=outtext
A:
>>> import re
>>> s = """Title: This is the title
... Author: This is the author
... Date: This is the date"""
>>> p = re.compile(r'^(\w+):\s*(.+)$', re.M)
>>> print p.sub(r'\\\1{\2}', s)
\Title{This is the title}
\Author{This is the author}
\Date{This is the date}
To change the case, use a function as replace parameter:
def repl_cb(m):
return "\\%s{%s}" %(m.group(1).lower(), m.group(2))
p = re.compile(r'^(\w+):\s*(.+)$', re.M)
print p.sub(repl_cb, s)
\title{This is the title}
\author{This is the author}
\date{This is the date}
A:
See re.sub()
A:
The regular expression you want would probably be along the lines of this one:
^([^:]+): (.*)
and the replacement expression would be
\\\1{\2}
A:
>>> import re
>>> m = 'title', 'author', 'date'
>>> s = """Title: This is the title
Author: This is the author
Date: This is the date"""
>>> for i in m:
s = re.compile(i+': (.*)', re.I).sub(r'\\' + i + r'{\1}', s)
>>> print(s)
\title{This is the title}
\author{This is the author}
\date{This is the date}
| Regular expressions in a Python find-and-replace script? Update | I'm new to Python scripting, so please forgive me in advance if the answer to this question seems inherently obvious.
I'm trying to put together a large-scale find-and-replace script using Python. I'm using code similar to the following:
infile = sys.argv[1]
charenc = sys.argv[2]
outFile=infile+'.output'
findreplace = [
('term1', 'term2'),
]
inF = open(infile,'rb')
s=unicode(inF.read(),charenc)
inF.close()
for couple in findreplace:
outtext=s.replace(couple[0],couple[1])
s=outtext
outF = open(outFile,'wb')
outF.write(outtext.encode('utf-8'))
outF.close()
How would I go about having the script do a find and replace for regular expressions?
Specifically, I want it to find some information (metadata) specified at the top of a text file. Eg:
Title: This is the title
Author: This is the author
Date: This is the date
and convert it into LaTeX format. Eg:
\title{This is the title}
\author{This is the author}
\date{This is the date}
Maybe I'm tackling this the wrong way. If there's a better way than regular expressions please let me know!
Thanks!
Update: Thanks for posting some example code in your answers! I can get it to work so long as I replace the findreplace action, but I can't get both to work. The problem now is I can't integrate it properly into the code I've got. How would I go about having the script do multiple actions on 'outtext' in the below snippet?
for couple in findreplace:
outtext=s.replace(couple[0],couple[1])
s=outtext
| [
">>> import re\n>>> s = \"\"\"Title: This is the title\n... Author: This is the author\n... Date: This is the date\"\"\"\n>>> p = re.compile(r'^(\\w+):\\s*(.+)$', re.M)\n>>> print p.sub(r'\\\\\\1{\\2}', s)\n\\Title{This is the title}\n\\Author{This is the author}\n\\Date{This is the date}\n\nTo change the case, use a function as replace parameter:\ndef repl_cb(m):\n return \"\\\\%s{%s}\" %(m.group(1).lower(), m.group(2))\n\np = re.compile(r'^(\\w+):\\s*(.+)$', re.M)\nprint p.sub(repl_cb, s)\n\n\n\\title{This is the title}\n\\author{This is the author}\n\\date{This is the date}\n\n",
"See re.sub()\n",
"The regular expression you want would probably be along the lines of this one:\n^([^:]+): (.*)\n\nand the replacement expression would be\n\\\\\\1{\\2}\n\n",
">>> import re\n>>> m = 'title', 'author', 'date'\n>>> s = \"\"\"Title: This is the title\nAuthor: This is the author\nDate: This is the date\"\"\"\n>>> for i in m:\n s = re.compile(i+': (.*)', re.I).sub(r'\\\\' + i + r'{\\1}', s)\n\n\n>>> print(s)\n\\title{This is the title}\n\\author{This is the author}\n\\date{This is the date}\n\n"
] | [
5,
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003036706_python_regex.txt |
Q:
Using popen, but text looks weird - Python
I'm using os.popen() in order to run a few commands.
This is what "man ls" looks like:
Any ideas why the text is displayed as such. I tried both Arial and Consolas fonts.
Help would be amazing! Thanks
A:
Those are backspace characters: man is trying to backspace and reprint characters to get bolding, or underscores plus backspaces to get underlining.
The man man page says:
To get a plain text version of a man page, without backspaces and underscores, try
# man foo | col -b > foo.mantxt
You could also do a simple post-processing in Python:
s = re.sub(".\x08", "", s)
This removes any pair of characters where the second character is a backspace.
| Using popen, but text looks weird - Python | I'm using os.popen() in order to run a few commands.
This is what "man ls" looks like:
Any ideas why the text is displayed as such. I tried both Arial and Consolas fonts.
Help would be amazing! Thanks
| [
"Those are backspace characters: man is trying to backspace and reprint characters to get bolding, or underscores plus backspaces to get underlining.\nThe man man page says:\n\nTo get a plain text version of a man page, without backspaces and underscores, try\n# man foo | col -b > foo.mantxt \n\nYou could also do a simple post-processing in Python:\ns = re.sub(\".\\x08\", \"\", s)\n\nThis removes any pair of characters where the second character is a backspace.\n"
] | [
3
] | [] | [] | [
"command_line",
"popen",
"python"
] | stackoverflow_0003036822_command_line_popen_python.txt |
Q:
Magic Methods in Python
I'm kind of new to Python and I wonder if there is a way to create something like the magic methods in PHP (http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods)
My aim is to ease the access of child classes in my model. I basically have a parent class that has n child classes. These classes have three values, a language key, a translation key and a translation value. The are describing a kind of generic translation handling. The parent class can have translations for different translation key each in different languages. E.g. the key "title" can be translated into german and english and the key "description" too (and so far and so on)
I don't want to get the child classes and filter by the set values (at least I want but not explicitly, the concrete implementation behind the magic method would do this). I want to call
parent_class.title['de']
# or also possible maybe
parent_class.title('de')
for getting the translation of title in german (de).
So there has to be a magic method that takes the name of the called method and their params (as in PHP). As far as I dug into Python this is only possible with simple attributes (__getattr__, __setattr__) or with setting/getting directly within the class (__getitem__, __setitem__) which both do not fit my needs.
Maybe there is a solution for this? Please help!
Thanks in advance!
A:
Return an object for parent_class.title which has a __getitem__ method.
class parent_class:
def __init__(self):
self.title = multilang("hello world");
class multilang:
def __init__(self, text):
pass
def __getitem__(self, key):
if key == 'en':
return "hello world";
A:
You could could refactor your code to parent_class['de'].title. Then something like this would probaly work
from collections import defaultdict
class X(object):
def __init__(self, title = "", description = ""):
self.title = title
self.description = description
parent_class = defaultdict(X)
parent_class['en'] = X("title", "description")
parent_class['de'].title = "Titel"
| Magic Methods in Python | I'm kind of new to Python and I wonder if there is a way to create something like the magic methods in PHP (http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods)
My aim is to ease the access of child classes in my model. I basically have a parent class that has n child classes. These classes have three values, a language key, a translation key and a translation value. The are describing a kind of generic translation handling. The parent class can have translations for different translation key each in different languages. E.g. the key "title" can be translated into german and english and the key "description" too (and so far and so on)
I don't want to get the child classes and filter by the set values (at least I want but not explicitly, the concrete implementation behind the magic method would do this). I want to call
parent_class.title['de']
# or also possible maybe
parent_class.title('de')
for getting the translation of title in german (de).
So there has to be a magic method that takes the name of the called method and their params (as in PHP). As far as I dug into Python this is only possible with simple attributes (__getattr__, __setattr__) or with setting/getting directly within the class (__getitem__, __setitem__) which both do not fit my needs.
Maybe there is a solution for this? Please help!
Thanks in advance!
| [
"Return an object for parent_class.title which has a __getitem__ method.\nclass parent_class:\n def __init__(self):\n self.title = multilang(\"hello world\");\n\nclass multilang:\n def __init__(self, text):\n pass\n def __getitem__(self, key):\n if key == 'en':\n return \"hello world\";\n\n",
"You could could refactor your code to parent_class['de'].title. Then something like this would probaly work\nfrom collections import defaultdict\n\nclass X(object):\n def __init__(self, title = \"\", description = \"\"):\n self.title = title\n self.description = description\n\nparent_class = defaultdict(X)\n\nparent_class['en'] = X(\"title\", \"description\")\nparent_class['de'].title = \"Titel\"\n\n"
] | [
4,
1
] | [] | [] | [
"magic_methods",
"python"
] | stackoverflow_0003036895_magic_methods_python.txt |
Q:
problem installing mysqldb for python2.6
My mysql database is located on a remote machine... So i dont have any local copy of mysql on my local machine.. i get the registry key error... (file not found)...
serverKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, options['registry_key'])
WindowsError: [Error 2] The system cannot find the file specified
I think it requires to have a local copy of mysql... How do i install the mysqldb for database residing on another machine???
A:
You will indeed need a local copy of MySQL in order to compile the MySQL extension for Python. This page seems to contain a step-by-step guide for Windows.
However, you might have some luck with a pre-compiled MySQL module. This should work for Python 2.6.
| problem installing mysqldb for python2.6 | My mysql database is located on a remote machine... So i dont have any local copy of mysql on my local machine.. i get the registry key error... (file not found)...
serverKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, options['registry_key'])
WindowsError: [Error 2] The system cannot find the file specified
I think it requires to have a local copy of mysql... How do i install the mysqldb for database residing on another machine???
| [
"You will indeed need a local copy of MySQL in order to compile the MySQL extension for Python. This page seems to contain a step-by-step guide for Windows.\nHowever, you might have some luck with a pre-compiled MySQL module. This should work for Python 2.6.\n"
] | [
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003036845_mysql_python.txt |
Q:
syntax error in python:
I'm learning python. It gives syntax error in this script. I'm unable to figure out.
import exceptions
class FOUND(Exception): pass
x = [1,2,3,4,56,73,29,35,12,32,63,12,76,75,89]
while True:
try:
test = int(raw_input('Enter integer to be checked in list:'))
count = -1
for y in x:
count += 1
if y == test:
raise FOUND
except ValueError as e:
print "Not a valid integer (%s)"%(e)
except FOUND:
print "Found (%d) at (%d)"%(test,count)
else:
print "Not found ,Appending (%d) to list at location (%d)"%(test,count+1)
x.append(test)
finally:
print "The List:"
print x
print " "
Invalid syntax & it highlights closing double quote in this line: print "Not a valid integer (%s)"%(e)
A:
print without brackets is from python 2, if you are using python 3, you need to use print().
You can't format an exception as %d - %d is for integers.
A:
Try except ValueError as e:, the older syntax you use is invalid in Python 3.
A:
You need an empty line between the class ... and x = ...
A:
Your code (cut and pasted, no alterations) works fine for me (Python 2.5).
BTW, your test = int... line should be after the try (and indented appropriately) and the %d in "Not a valid integer (%d)" should be a %s.
Syntax for exception handling has been changed for Python 3: make sure any help/tutorials you are following are for the same major version of Python you have installed. There have been signficant changes from 2.x to 3.x.
| syntax error in python: | I'm learning python. It gives syntax error in this script. I'm unable to figure out.
import exceptions
class FOUND(Exception): pass
x = [1,2,3,4,56,73,29,35,12,32,63,12,76,75,89]
while True:
try:
test = int(raw_input('Enter integer to be checked in list:'))
count = -1
for y in x:
count += 1
if y == test:
raise FOUND
except ValueError as e:
print "Not a valid integer (%s)"%(e)
except FOUND:
print "Found (%d) at (%d)"%(test,count)
else:
print "Not found ,Appending (%d) to list at location (%d)"%(test,count+1)
x.append(test)
finally:
print "The List:"
print x
print " "
Invalid syntax & it highlights closing double quote in this line: print "Not a valid integer (%s)"%(e)
| [
"print without brackets is from python 2, if you are using python 3, you need to use print().\nYou can't format an exception as %d - %d is for integers.\n",
"Try except ValueError as e:, the older syntax you use is invalid in Python 3.\n",
"You need an empty line between the class ... and x = ...\n",
"Your code (cut and pasted, no alterations) works fine for me (Python 2.5).\nBTW, your test = int... line should be after the try (and indented appropriately) and the %d in \"Not a valid integer (%d)\" should be a %s.\nSyntax for exception handling has been changed for Python 3: make sure any help/tutorials you are following are for the same major version of Python you have installed. There have been signficant changes from 2.x to 3.x.\n"
] | [
5,
2,
1,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0003037014_python_python_3.x.txt |
Q:
Please help me optimize my Python code
Beginner here! Forgive me in advance for raising what is probably an incredibly simple problem.
I've been trying to put together a Python script that runs multiple find-and-replace actions and a few similar things on a specified plain-text file. It works, but from a programming perspective I doubt it works well. How would I best go about optimizing the actions made upon the 'outtext' variable? At the moment it's basically doing a very similar thing four times over...
import binascii
import re
import struct
import sys
infile = sys.argv[1]
charenc = sys.argv[2]
outFile=infile+'.tex'
findreplace = [
('TERM1', 'TERM2'),
('TERM3', 'TERM4'),
('TERM5', 'TERM6'),
]
inF = open(infile,'rb')
s=unicode(inF.read(),charenc)
inF.close()
# THIS IS VERY MESSY.
for couple in findreplace:
outtext=s.replace(couple[0],couple[1])
s=outtext
for couple in findreplace:
outtext=re.compile('Title: (.*)', re.I).sub(r'\\title'+ r'{\1}', s)
s=outtext
for couple in findreplace:
outtext=re.compile('Author: (.*)', re.I).sub(r'\\author'+ r'{\1}', s)
s=outtext
for couple in findreplace:
outtext=re.compile('Date: (.*)', re.I).sub(r'\\date'+ r'{\1}', s)
s=outtext
# END MESSY SECTION.
outF = open(outFile,'wb')
outF.write(outtext.encode('utf-8'))
outF.close()
A:
For the last three replacements, the for-loop seems to be unnecessary, since the loop body doesn't use the loop variable. Also it is not necessary to assign the result to a temporary outtext variable, it can be directly assigned to s.
These changes make the code much more concise:
for couple in findreplace:
s = s.replace(couple[0],couple[1])
s = re.compile('Title: (.*)', re.I).sub(r'\\title {\1}', s)
s = re.compile('Author: (.*)', re.I).sub(r'\\author {\1}', s)
s = re.compile('Date: (.*)', re.I).sub(r'\\date {\1}', s)
A:
Some possibilities:
Do the re.compile outside the loop.
Use only one loop and do all four things inside it.
Use one regex, which matches on either Title, Author or Date.
Don't do the last three replaces inside a loop, since they do not use the couple variable.
A:
your code is not so bad. If you want to optimise for speed then I would look into compiling your regex's at the start of the program.
Also, If you want to tidy up your code then chain all your subs together in one loop.
| Please help me optimize my Python code | Beginner here! Forgive me in advance for raising what is probably an incredibly simple problem.
I've been trying to put together a Python script that runs multiple find-and-replace actions and a few similar things on a specified plain-text file. It works, but from a programming perspective I doubt it works well. How would I best go about optimizing the actions made upon the 'outtext' variable? At the moment it's basically doing a very similar thing four times over...
import binascii
import re
import struct
import sys
infile = sys.argv[1]
charenc = sys.argv[2]
outFile=infile+'.tex'
findreplace = [
('TERM1', 'TERM2'),
('TERM3', 'TERM4'),
('TERM5', 'TERM6'),
]
inF = open(infile,'rb')
s=unicode(inF.read(),charenc)
inF.close()
# THIS IS VERY MESSY.
for couple in findreplace:
outtext=s.replace(couple[0],couple[1])
s=outtext
for couple in findreplace:
outtext=re.compile('Title: (.*)', re.I).sub(r'\\title'+ r'{\1}', s)
s=outtext
for couple in findreplace:
outtext=re.compile('Author: (.*)', re.I).sub(r'\\author'+ r'{\1}', s)
s=outtext
for couple in findreplace:
outtext=re.compile('Date: (.*)', re.I).sub(r'\\date'+ r'{\1}', s)
s=outtext
# END MESSY SECTION.
outF = open(outFile,'wb')
outF.write(outtext.encode('utf-8'))
outF.close()
| [
"For the last three replacements, the for-loop seems to be unnecessary, since the loop body doesn't use the loop variable. Also it is not necessary to assign the result to a temporary outtext variable, it can be directly assigned to s.\nThese changes make the code much more concise:\nfor couple in findreplace:\n s = s.replace(couple[0],couple[1])\n\ns = re.compile('Title: (.*)', re.I).sub(r'\\\\title {\\1}', s)\ns = re.compile('Author: (.*)', re.I).sub(r'\\\\author {\\1}', s)\ns = re.compile('Date: (.*)', re.I).sub(r'\\\\date {\\1}', s)\n\n",
"Some possibilities:\n\nDo the re.compile outside the loop.\nUse only one loop and do all four things inside it.\nUse one regex, which matches on either Title, Author or Date.\nDon't do the last three replaces inside a loop, since they do not use the couple variable.\n\n",
"your code is not so bad. If you want to optimise for speed then I would look into compiling your regex's at the start of the program. \nAlso, If you want to tidy up your code then chain all your subs together in one loop.\n"
] | [
4,
2,
0
] | [] | [] | [
"optimization",
"python"
] | stackoverflow_0003037112_optimization_python.txt |
Q:
Python Threading, loading one thread after another
I'm working on a media player and am able to load in a single .wav and play it. As seen in the code below.
foo = wx.FileDialog(self, message="Open a .wav file...", defaultDir=os.getcwd(), defaultFile="", style=wx.FD_MULTIPLE)
foo.ShowModal()
queue = foo.GetPaths()
self.playing_thread = threading.Thread(target=self.playFile, args=(queue[0], 'msg'))
self.playing_thread.start()
But the problem is, when I try to make the above code into a loop for multiple .wav files. Such that while playing_thread.isActive == True, create and .start() the thread. Then if .isActive == False, pop queue[0] and load the next .wav file. Problem is, my UI will lock up and I'll have to terminate the program. Any ideas would be appreciated.
A:
Since is using wx.python, use a Delayedresult, look at wx demos for a complete example.
Full minimal example:
import wx
import wx.lib.delayedresult as inbg
import time
class Player(wx.Frame):
def __init__(self):
self.titulo = "Music Player"
wx.Frame.__init__(self, None, -1, self.titulo,)
self.jobID = 0
self.Vb = wx.BoxSizer(wx.VERTICAL)
self.panel = wx.Panel(self,-1)
self.playlist = ['one','two']
self.abortEvent = inbg.AbortEvent()
self.msg = wx.StaticText(self.panel, -1, "...",pos=(30,-1))
self.msg.SetFont(wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD))
self.action = wx.Button(self.panel, -1,"Play Playlist")
self.Bind(wx.EVT_BUTTON, self.StartPlaying,self.action)
self.Vb.Add(self.msg, 0, wx.EXPAND|wx.ALL, 3)
self.Vb.Add(self.action, 0, wx.EXPAND|wx.ALL, 3)
self.panel.SetSizer(self.Vb)
self.Show()
def StartPlaying(self,evt):
self.BgProcess(self.Playme)
def Playme(self,jobID, abortEvent):
print "in bg"
list = self.getPlayList()
print list
for music in list:
self.msg.SetLabel('Playing: %s' % music)
stop = 100
while stop > 0:
print stop
stop -=1
self.msg.SetLabel('Playing: %s [%s ]' % (music,stop))
def _resultConsumer(self, inbg):
jobID = inbg.getJobID()
try:
result = inbg.get()
return result
except Exception, exc:
return False
def getPlayList(self):
return self.playlist
def setPlayList(self,music):
self.playlist.appdend(music)
def BgProcess(self,executar):
self.abortEvent.clear()
self.jobID += 1
inbg.startWorker(self._resultConsumer, executar, wargs=(self.jobID,self.abortEvent), jobID=self.jobID)
app = wx.App(False)
demo = Player()
app.MainLoop()
| Python Threading, loading one thread after another | I'm working on a media player and am able to load in a single .wav and play it. As seen in the code below.
foo = wx.FileDialog(self, message="Open a .wav file...", defaultDir=os.getcwd(), defaultFile="", style=wx.FD_MULTIPLE)
foo.ShowModal()
queue = foo.GetPaths()
self.playing_thread = threading.Thread(target=self.playFile, args=(queue[0], 'msg'))
self.playing_thread.start()
But the problem is, when I try to make the above code into a loop for multiple .wav files. Such that while playing_thread.isActive == True, create and .start() the thread. Then if .isActive == False, pop queue[0] and load the next .wav file. Problem is, my UI will lock up and I'll have to terminate the program. Any ideas would be appreciated.
| [
"Since is using wx.python, use a Delayedresult, look at wx demos for a complete example.\nFull minimal example:\nimport wx\nimport wx.lib.delayedresult as inbg\nimport time\n\nclass Player(wx.Frame):\n def __init__(self):\n\n\n self.titulo = \"Music Player\"\n wx.Frame.__init__(self, None, -1, self.titulo,)\n self.jobID = 0\n self.Vb = wx.BoxSizer(wx.VERTICAL)\n self.panel = wx.Panel(self,-1)\n self.playlist = ['one','two']\n self.abortEvent = inbg.AbortEvent()\n self.msg = wx.StaticText(self.panel, -1, \"...\",pos=(30,-1))\n self.msg.SetFont(wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD))\n self.action = wx.Button(self.panel, -1,\"Play Playlist\")\n self.Bind(wx.EVT_BUTTON, self.StartPlaying,self.action)\n\n self.Vb.Add(self.msg, 0, wx.EXPAND|wx.ALL, 3)\n self.Vb.Add(self.action, 0, wx.EXPAND|wx.ALL, 3)\n self.panel.SetSizer(self.Vb)\n self.Show()\n\n\ndef StartPlaying(self,evt):\n self.BgProcess(self.Playme)\n\n\ndef Playme(self,jobID, abortEvent):\n print \"in bg\"\n list = self.getPlayList()\n print list\n for music in list:\n\n self.msg.SetLabel('Playing: %s' % music)\n stop = 100\n while stop > 0:\n print stop\n stop -=1\n self.msg.SetLabel('Playing: %s [%s ]' % (music,stop))\n\n\n\n\n\n\ndef _resultConsumer(self, inbg):\n jobID = inbg.getJobID()\n try:\n result = inbg.get()\n return result\n except Exception, exc:\n return False\n\ndef getPlayList(self):\n return self.playlist\n\ndef setPlayList(self,music):\n self.playlist.appdend(music)\n\n\n\ndef BgProcess(self,executar):\n self.abortEvent.clear()\n self.jobID += 1\n inbg.startWorker(self._resultConsumer, executar, wargs=(self.jobID,self.abortEvent), jobID=self.jobID) \n\n\n\napp = wx.App(False)\ndemo = Player()\napp.MainLoop()\n\n"
] | [
0
] | [] | [] | [
"multithreading",
"python",
"wxpython"
] | stackoverflow_0003037150_multithreading_python_wxpython.txt |
Q:
Run a shell command from Django
I'm developing a web page in Django (using apache server) that needs to call a shell command to enable/dissable some daemons. I'm try to do it with
os.system(service httpd restart 1>$HOME/out 2>$HOME/error)
and this command doesn't return anything. Any idea how can i fix this?
A:
I'll skip the part where I strongly advise you about the implications of having a web application starting and stopping system processes and try to answer the question.
Your django application shouldn't run with root user, which should probably be needed to start and stop services. You can probably overcome this by:
creating a script that uses seteuid
give that file the set uid attribute
The script would be something like
#!/usr/bin/python <- or wherever your python interpreter is
import os
os.seteuid(0)
os.system("service httpd restart 1>$HOME/out 2>$HOME/error")
To allow setting the effective UID to root (0), you have to run, in a shell, as root:
chown root yourscript.py
chmod u+s yourscript.py
chmod a+x yourscript.py
That should do it. In your Django app you can now call os.system('yourscript.py') to run the command with root permissions.
Finally, I believe that the command you're passing to os.system() isn't what you're looking for, since you talk about enabling and disabling daemons and all you're doing is restarting apache... which in turn seems to be where your django is running, so in practice you'll be killing your own webapp.
A:
Try run the command in Shell:
import subprocess
r = subprocess.call("service httpd restart 1>$HOME/out 2>$HOME/error", shell=True)
A:
Here is the code I use for launching process from my one of my django app:
import subprocess
process = subprocess.Popen(['python', 'manage.py', 'some_command'])
In your case it would be:
import subprocess
process = subprocess.Popen(['service', 'httpd', 'restart'])
(also you need to handle stdout and stderr - not sure if adding '1>$HOME/out') would work with Popen. There is documentation for subprocess
| Run a shell command from Django | I'm developing a web page in Django (using apache server) that needs to call a shell command to enable/dissable some daemons. I'm try to do it with
os.system(service httpd restart 1>$HOME/out 2>$HOME/error)
and this command doesn't return anything. Any idea how can i fix this?
| [
"I'll skip the part where I strongly advise you about the implications of having a web application starting and stopping system processes and try to answer the question.\nYour django application shouldn't run with root user, which should probably be needed to start and stop services. You can probably overcome this by:\n\ncreating a script that uses seteuid\ngive that file the set uid attribute\n\nThe script would be something like\n#!/usr/bin/python <- or wherever your python interpreter is\nimport os\nos.seteuid(0)\nos.system(\"service httpd restart 1>$HOME/out 2>$HOME/error\")\n\nTo allow setting the effective UID to root (0), you have to run, in a shell, as root:\nchown root yourscript.py\nchmod u+s yourscript.py\nchmod a+x yourscript.py\n\nThat should do it. In your Django app you can now call os.system('yourscript.py') to run the command with root permissions.\nFinally, I believe that the command you're passing to os.system() isn't what you're looking for, since you talk about enabling and disabling daemons and all you're doing is restarting apache... which in turn seems to be where your django is running, so in practice you'll be killing your own webapp.\n",
"Try run the command in Shell:\nimport subprocess\nr = subprocess.call(\"service httpd restart 1>$HOME/out 2>$HOME/error\", shell=True)\n\n",
"Here is the code I use for launching process from my one of my django app:\n import subprocess\n process = subprocess.Popen(['python', 'manage.py', 'some_command'])\n\nIn your case it would be:\nimport subprocess \nprocess = subprocess.Popen(['service', 'httpd', 'restart'])\n\n(also you need to handle stdout and stderr - not sure if adding '1>$HOME/out') would work with Popen. There is documentation for subprocess\n"
] | [
10,
4,
3
] | [] | [] | [
"apache",
"django",
"python"
] | stackoverflow_0003037068_apache_django_python.txt |
Q:
Python - calculate multinomial probability density functions on large dataset?
I originally intended to use MATLAB to tackle this problem but the in-built function has limitations that do not suit my goal. The same limitation occurs in NumPy.
I have two tab-delimited files. The first is a file showing amino acid residue, frequency and count for an in-house database of protein structures, i.e.
A 0.25 1
S 0.25 1
T 0.25 1
P 0.25 1
The second file consists of quadruplets of amino acids and the number of times they occur, i.e.
ASTP 1
Note, there are >8,000 such quadruplets.
Based on the background frequency of occurence of each amino acid and the count of quadruplets, I aim to calculate the multinomial probability density function for each quadruplet and subsequently use it as the expected value in a maximum likelihood calculation.
The multinomial distribution is as follows:
f(x|n, p) = n!/(x1!*x2!*...*xk!)*((p1^x1)*(p2^x2)*...*(pk^xk))
where x is the number of each of k outcomes in n trials with fixed probabilities p. n is 4 four in all cases in my calculation.
I have created four functions to calculate this distribution.
# functions for multinomial distribution
def expected_quadruplets(x, y):
expected = x*y
return expected
# calculates the probabilities of occurence raised to the number of occurrences
def prod_prob(p1, a, p2, b, p3, c, p4, d):
prob_prod = (pow(p1, a))*(pow(p2, b))*(pow(p3, c))*(pow(p4, d))
return prob_prod
# factorial() and multinomial_coefficient() work in tandem to calculate C, the multinomial coefficient
def factorial(n):
if n <= 1:
return 1
return n*factorial(n-1)
def multinomial_coefficient(a, b, c, d):
n = 24.0
multi_coeff = (n/(factorial(a) * factorial(b) * factorial(c) * factorial(d)))
return multi_coeff
The problem is how best to structure the data in order to tackle the calculation most efficiently, in a manner that I can read (you guys write some cryptic code :-)) and that will not create an overflow or runtime error.
To date my data is represented as nested lists.
amino_acids = [['A', '0.25', '1'], ['S', '0.25', '1'], ['T', '0.25', '1'], ['P', '0.25', '1']]
quadruplets = [['ASTP', '1']]
I initially intended calling these functions within a nested for loop but this resulted in runtime errors or overflow errors. I know that I can reset the recursion limit but I would rather do this more elegantly.
I had the following:
for i in quadruplets:
quad = i[0].split(' ')
for j in amino_acids:
for k in quadruplets:
for v in k:
if j[0] == v:
multinomial_coefficient(int(j[2]), int(j[2]), int(j[2]), int(j[2]))
I haven'te really gotten to how to incorporate the other functions yet. I think that my current nested list arrangement is sub optimal.
I wish to compare each letter within the string 'ASTP' with the first component of each sub list in amino_acids. Where a match exists, I wish to pass the appropriate numeric values to the functions using indices.
Is their a better way? Can I append the appropriate numbers for each amino acid and quadruplet to a temporary data structure within a loop, pass this to the functions and clear it for the next iteration?
Thanks, S :-)
A:
This might be tangential to your original question, but I strongly advise against calculating factorials explicitly due to overflows. Instead, make use of the fact that factorial(n) = gamma(n+1), use the logarithm of the gamma function and use additions instead of multiplications, subtractions instead of divisions. scipy.special contains a function named gammaln, which gives you the logarithm of the gamma function.
from itertools import izip
from numpy import array, log, exp
from scipy.special import gammaln
def log_factorial(x):
"""Returns the logarithm of x!
Also accepts lists and NumPy arrays in place of x."""
return gammaln(array(x)+1)
def multinomial(xs, ps):
n = sum(xs)
xs, ps = array(xs), array(ps)
result = log_factorial(n) - sum(log_factorial(xs)) + sum(xs * log(ps))
return exp(result)
If you don't want to install SciPy just for the sake of gammaln, here is a replacement in pure Python (of course it is slower and it is not vectorized like the one in SciPy):
def gammaln(n):
"""Logarithm of Euler's gamma function for discrete values."""
if n < 1:
return float('inf')
if n < 3:
return 0.0
c = [76.18009172947146, -86.50532032941677, \
24.01409824083091, -1.231739572450155, \
0.001208650973866179, -0.5395239384953 * 0.00001]
x, y = float(n), float(n)
tm = x + 5.5
tm -= (x + 0.5) * log(tm)
se = 1.0000000000000190015
for j in range(6):
y += 1.0
se += c[j] / y
return -tm + log(2.5066282746310005 * se / x)
Another easy trick is to use a dict for amino_acids, indexed by the residue itself. Given your original amino_acids structure, you can do this:
amino_acid_dict = dict((amino_acid[0], amino_acid) for amino_acid in amino_acids)
print amino_acid_dict
{"A": ["A", 0.25, 1], "S": ["S", 0.25, 1], "T": ["T", 0.25, 1], "P": ["P", 0.25, 1]}
You can then look up the frequencies or counts by residue easier:
freq_A = amino_acid_dict["A"][1]
count_A = amino_acid_dict["A"][2]
This saves you some time in the main loop:
for quadruplet in quadruplets:
probs = [amino_acid_dict[aa][1] for aa in quadruplet]
counts = [amino_acid_dict[aa][2] for aa in quadruplet]
print quadruplet, multinomial(counts, probs)
| Python - calculate multinomial probability density functions on large dataset? | I originally intended to use MATLAB to tackle this problem but the in-built function has limitations that do not suit my goal. The same limitation occurs in NumPy.
I have two tab-delimited files. The first is a file showing amino acid residue, frequency and count for an in-house database of protein structures, i.e.
A 0.25 1
S 0.25 1
T 0.25 1
P 0.25 1
The second file consists of quadruplets of amino acids and the number of times they occur, i.e.
ASTP 1
Note, there are >8,000 such quadruplets.
Based on the background frequency of occurence of each amino acid and the count of quadruplets, I aim to calculate the multinomial probability density function for each quadruplet and subsequently use it as the expected value in a maximum likelihood calculation.
The multinomial distribution is as follows:
f(x|n, p) = n!/(x1!*x2!*...*xk!)*((p1^x1)*(p2^x2)*...*(pk^xk))
where x is the number of each of k outcomes in n trials with fixed probabilities p. n is 4 four in all cases in my calculation.
I have created four functions to calculate this distribution.
# functions for multinomial distribution
def expected_quadruplets(x, y):
expected = x*y
return expected
# calculates the probabilities of occurence raised to the number of occurrences
def prod_prob(p1, a, p2, b, p3, c, p4, d):
prob_prod = (pow(p1, a))*(pow(p2, b))*(pow(p3, c))*(pow(p4, d))
return prob_prod
# factorial() and multinomial_coefficient() work in tandem to calculate C, the multinomial coefficient
def factorial(n):
if n <= 1:
return 1
return n*factorial(n-1)
def multinomial_coefficient(a, b, c, d):
n = 24.0
multi_coeff = (n/(factorial(a) * factorial(b) * factorial(c) * factorial(d)))
return multi_coeff
The problem is how best to structure the data in order to tackle the calculation most efficiently, in a manner that I can read (you guys write some cryptic code :-)) and that will not create an overflow or runtime error.
To date my data is represented as nested lists.
amino_acids = [['A', '0.25', '1'], ['S', '0.25', '1'], ['T', '0.25', '1'], ['P', '0.25', '1']]
quadruplets = [['ASTP', '1']]
I initially intended calling these functions within a nested for loop but this resulted in runtime errors or overflow errors. I know that I can reset the recursion limit but I would rather do this more elegantly.
I had the following:
for i in quadruplets:
quad = i[0].split(' ')
for j in amino_acids:
for k in quadruplets:
for v in k:
if j[0] == v:
multinomial_coefficient(int(j[2]), int(j[2]), int(j[2]), int(j[2]))
I haven'te really gotten to how to incorporate the other functions yet. I think that my current nested list arrangement is sub optimal.
I wish to compare each letter within the string 'ASTP' with the first component of each sub list in amino_acids. Where a match exists, I wish to pass the appropriate numeric values to the functions using indices.
Is their a better way? Can I append the appropriate numbers for each amino acid and quadruplet to a temporary data structure within a loop, pass this to the functions and clear it for the next iteration?
Thanks, S :-)
| [
"This might be tangential to your original question, but I strongly advise against calculating factorials explicitly due to overflows. Instead, make use of the fact that factorial(n) = gamma(n+1), use the logarithm of the gamma function and use additions instead of multiplications, subtractions instead of divisions. scipy.special contains a function named gammaln, which gives you the logarithm of the gamma function.\nfrom itertools import izip\nfrom numpy import array, log, exp\nfrom scipy.special import gammaln\n\ndef log_factorial(x):\n \"\"\"Returns the logarithm of x!\n Also accepts lists and NumPy arrays in place of x.\"\"\"\n return gammaln(array(x)+1)\n\ndef multinomial(xs, ps):\n n = sum(xs)\n xs, ps = array(xs), array(ps)\n result = log_factorial(n) - sum(log_factorial(xs)) + sum(xs * log(ps))\n return exp(result)\n\nIf you don't want to install SciPy just for the sake of gammaln, here is a replacement in pure Python (of course it is slower and it is not vectorized like the one in SciPy):\ndef gammaln(n):\n \"\"\"Logarithm of Euler's gamma function for discrete values.\"\"\"\n if n < 1:\n return float('inf')\n if n < 3:\n return 0.0\n c = [76.18009172947146, -86.50532032941677, \\\n 24.01409824083091, -1.231739572450155, \\\n 0.001208650973866179, -0.5395239384953 * 0.00001]\n x, y = float(n), float(n)\n tm = x + 5.5\n tm -= (x + 0.5) * log(tm)\n se = 1.0000000000000190015\n for j in range(6):\n y += 1.0\n se += c[j] / y\n return -tm + log(2.5066282746310005 * se / x)\n\nAnother easy trick is to use a dict for amino_acids, indexed by the residue itself. Given your original amino_acids structure, you can do this:\namino_acid_dict = dict((amino_acid[0], amino_acid) for amino_acid in amino_acids)\nprint amino_acid_dict\n{\"A\": [\"A\", 0.25, 1], \"S\": [\"S\", 0.25, 1], \"T\": [\"T\", 0.25, 1], \"P\": [\"P\", 0.25, 1]}\n\nYou can then look up the frequencies or counts by residue easier:\nfreq_A = amino_acid_dict[\"A\"][1]\ncount_A = amino_acid_dict[\"A\"][2]\n\nThis saves you some time in the main loop:\nfor quadruplet in quadruplets:\n probs = [amino_acid_dict[aa][1] for aa in quadruplet]\n counts = [amino_acid_dict[aa][2] for aa in quadruplet]\n print quadruplet, multinomial(counts, probs)\n\n"
] | [
9
] | [] | [] | [
"data_structures",
"python"
] | stackoverflow_0003037113_data_structures_python.txt |
Q:
sorting words in python
Is it possible in python to sort a list of words not according to the english alphabet but according to a self created alphabet.
A:
You can normally define custom comparison methods so the sort is performed within your restrictions. I've never coded a line of Python in my life, but it's similar enough to Ruby for me to notice that the following excerpt from this page might help you:
alphabet = "zyxwvutsrqpomnlkjihgfedcba"
inputWords = ["england", "france", "spain", "italy", "greece", "portugal",
"canada", "usa", "mexico", "peru", "cuba", "chile", "argentina",
"zimbabwe", "uganda", "congo", "zambia", "namibia", "ghana"]
print sorted(inputWords, key=lambda word: [alphabet.index(c) for c in word])
You might also want to check out these articles. Good luck!
| sorting words in python | Is it possible in python to sort a list of words not according to the english alphabet but according to a self created alphabet.
| [
"You can normally define custom comparison methods so the sort is performed within your restrictions. I've never coded a line of Python in my life, but it's similar enough to Ruby for me to notice that the following excerpt from this page might help you:\nalphabet = \"zyxwvutsrqpomnlkjihgfedcba\"\n\ninputWords = [\"england\", \"france\", \"spain\", \"italy\", \"greece\", \"portugal\",\n \"canada\", \"usa\", \"mexico\", \"peru\", \"cuba\", \"chile\", \"argentina\",\n \"zimbabwe\", \"uganda\", \"congo\", \"zambia\", \"namibia\", \"ghana\"]\n\nprint sorted(inputWords, key=lambda word: [alphabet.index(c) for c in word])\n\nYou might also want to check out these articles. Good luck!\n"
] | [
13
] | [] | [] | [
"python"
] | stackoverflow_0003037407_python.txt |
Q:
How do I escape % from python mysql query
How do I escape the % from a mysql query in python.
For example
query = """SELECT DATE_FORMAT(date_time,'%Y-%m') AS dd
FROM some_table
WHERE some_col = %s
AND other_col = %s;"""
cur.execute(query, (pram1, pram2))
gives me a "ValueError: unsupported format character 'Y'" exception.
How do I get mysqldb to ignore the %? Can't see this in any of the docs.
A:
Literal escaping is recommended by the docs:
Note that any literal percent signs in the query string passed to execute() must be escaped, i.e. %%.
| How do I escape % from python mysql query | How do I escape the % from a mysql query in python.
For example
query = """SELECT DATE_FORMAT(date_time,'%Y-%m') AS dd
FROM some_table
WHERE some_col = %s
AND other_col = %s;"""
cur.execute(query, (pram1, pram2))
gives me a "ValueError: unsupported format character 'Y'" exception.
How do I get mysqldb to ignore the %? Can't see this in any of the docs.
| [
"Literal escaping is recommended by the docs:\n\nNote that any literal percent signs in the query string passed to execute() must be escaped, i.e. %%.\n\n"
] | [
45
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003037581_mysql_python.txt |
Q:
Convert sets to frozensets as values of a dictionary
I have dictionary that is built as part of the initialization of my object. I know that it will not change during the lifetime of the object. The dictionary maps keys to sets. I want to convert all the values from sets to frozensets, to make sure they do not get changed. Currently I do that like this:
for key in self.my_dict.iterkeys():
self.my_dict[key] = frozenset(self.my_dict[key])
Is there a simpler way to achieve this? I cannot build frozenset right away, because I do not how much items will be in each set until i have built the complete dictionary.
A:
Given, for instance,
>>> d = {'a': set([1, 2]), 'b': set([3, 4])}
>>> d
{'a': set([1, 2]), 'b': set([3, 4])}
You can do the conversion in place as
>>> d.update((k, frozenset(v)) for k, v in d.iteritems())
With the result
>>> d
{'a': frozenset([1, 2]), 'b': frozenset([3, 4])}
A:
If you have to do it in-place, probably this is the simplest way (almost the same as you posted):
for key, value in self.my_dict.iteritems():
self.my_dict[key] = frozenset(value)
This a variant which builds a temporary dict:
self.my_dict = dict(((key, frozenset(value)) \
for key, value in self.my_dict.iteritems()))
A:
In Python 3, you could use a dictionary comprehension:
d = {k: frozenset(v) for k, v in d.items()}
In Python 2, though, I don't know that there's anything shorter -- this at least feels less "redundant":
for k,v in d.iteritems():
d[k] = frozenset(v)
| Convert sets to frozensets as values of a dictionary | I have dictionary that is built as part of the initialization of my object. I know that it will not change during the lifetime of the object. The dictionary maps keys to sets. I want to convert all the values from sets to frozensets, to make sure they do not get changed. Currently I do that like this:
for key in self.my_dict.iterkeys():
self.my_dict[key] = frozenset(self.my_dict[key])
Is there a simpler way to achieve this? I cannot build frozenset right away, because I do not how much items will be in each set until i have built the complete dictionary.
| [
"Given, for instance,\n>>> d = {'a': set([1, 2]), 'b': set([3, 4])}\n>>> d\n{'a': set([1, 2]), 'b': set([3, 4])}\n\nYou can do the conversion in place as\n>>> d.update((k, frozenset(v)) for k, v in d.iteritems())\n\nWith the result\n>>> d\n{'a': frozenset([1, 2]), 'b': frozenset([3, 4])}\n\n",
"If you have to do it in-place, probably this is the simplest way (almost the same as you posted):\nfor key, value in self.my_dict.iteritems():\n self.my_dict[key] = frozenset(value)\n\nThis a variant which builds a temporary dict:\nself.my_dict = dict(((key, frozenset(value)) \\\n for key, value in self.my_dict.iteritems()))\n\n",
"In Python 3, you could use a dictionary comprehension:\nd = {k: frozenset(v) for k, v in d.items()}\n\nIn Python 2, though, I don't know that there's anything shorter -- this at least feels less \"redundant\":\nfor k,v in d.iteritems():\n d[k] = frozenset(v)\n\n"
] | [
6,
1,
1
] | [] | [] | [
"dictionary",
"python",
"set"
] | stackoverflow_0003037500_dictionary_python_set.txt |
Q:
Parsing logs using regex
I need to find all invocations of some logging macros in the code. The macro invocation is of the form:
DEBUG[1-5] ( "methodName: the logged message", arguments)
But the new versions of the macros are prepending the name of the method automatically, so my task is to write a Python script that will remove the duplicate function names specified already by the programmer.
I'm using the sub function from the re module. I plan to substitute the part indicated by || signs below :
||DEBUG[1-5] ("methodName: || the logged message", arguments) with simply DEBUG[1-5]("
The problem is following:
To find the expressions I want to substitute, I use the following regular expression:
((DEBUG | INFO | all other macros names )[1-5]*)\s*\(\"\w+:
But it doesn't match the whole expression ( from DEBUG right to the colon ), but only the macro name, that is for example DEBUG5.
Is my expression wrong or there is some quirk in the Python regex processing? ( maybe the fact that I use the DEBUG[1-5] as a subgroup has something to do with this? ) Help from anyone more knowledgable than me appreciated :).
A:
try this, written in java, but you can transform it to python
replaceAll("(DEBUG[1-5]\s*\\(\")\"[^:]+:\\s+([^;]+)", "$1$2");
| Parsing logs using regex | I need to find all invocations of some logging macros in the code. The macro invocation is of the form:
DEBUG[1-5] ( "methodName: the logged message", arguments)
But the new versions of the macros are prepending the name of the method automatically, so my task is to write a Python script that will remove the duplicate function names specified already by the programmer.
I'm using the sub function from the re module. I plan to substitute the part indicated by || signs below :
||DEBUG[1-5] ("methodName: || the logged message", arguments) with simply DEBUG[1-5]("
The problem is following:
To find the expressions I want to substitute, I use the following regular expression:
((DEBUG | INFO | all other macros names )[1-5]*)\s*\(\"\w+:
But it doesn't match the whole expression ( from DEBUG right to the colon ), but only the macro name, that is for example DEBUG5.
Is my expression wrong or there is some quirk in the Python regex processing? ( maybe the fact that I use the DEBUG[1-5] as a subgroup has something to do with this? ) Help from anyone more knowledgable than me appreciated :).
| [
"try this, written in java, but you can transform it to python\nreplaceAll(\"(DEBUG[1-5]\\s*\\\\(\\\")\\\"[^:]+:\\\\s+([^;]+)\", \"$1$2\");\n\n"
] | [
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003037932_python_regex.txt |
Q:
How to add wsse:Security, UsernameToken header to a SOAP request in ZSI, Python?
Is there a way to add the wsse:Security, UsernameToken header to the SOAP requests in ZSI, Python? I searched on the web, but couldn't find an answer.
A:
After searching further, I'm convinced and planning to use suds, https://fedorahosted.org/suds/, which seems to be user-friendly, feature-rich, and provides classes and methods to add the UsernameToken to the SOAP header.
Suds Documentation on WS-Security: https://fedorahosted.org/suds/wiki/Documentation#WS-SECURITY
| How to add wsse:Security, UsernameToken header to a SOAP request in ZSI, Python? | Is there a way to add the wsse:Security, UsernameToken header to the SOAP requests in ZSI, Python? I searched on the web, but couldn't find an answer.
| [
"After searching further, I'm convinced and planning to use suds, https://fedorahosted.org/suds/, which seems to be user-friendly, feature-rich, and provides classes and methods to add the UsernameToken to the SOAP header.\nSuds Documentation on WS-Security: https://fedorahosted.org/suds/wiki/Documentation#WS-SECURITY\n"
] | [
4
] | [] | [] | [
"python",
"usernametoken",
"ws_security",
"zsi"
] | stackoverflow_0003036881_python_usernametoken_ws_security_zsi.txt |
Q:
Command line tool in python in a fixed root directory
I would like to install my python application as a command line tool that should work entirelly inside the install directory (for example C:\Python26\Lib\site-packages\application)
The problem is I would like to reffer in runtime to the submodules and resources from within the application directory three. If I install the app with [console_scripts] option the default path is the current directory. Is there a elegant way to keep the current execution path of the application to the site-packages directory?
Thanks
A:
Not sure if this is what you're after but doing this might work.
import os
dir_of_current_module = os.path.dirname(__file__)
Once you know the dir, you can chdir() to it or do what you want. Remember: You might not always have permissions to do stuff there.
| Command line tool in python in a fixed root directory | I would like to install my python application as a command line tool that should work entirelly inside the install directory (for example C:\Python26\Lib\site-packages\application)
The problem is I would like to reffer in runtime to the submodules and resources from within the application directory three. If I install the app with [console_scripts] option the default path is the current directory. Is there a elegant way to keep the current execution path of the application to the site-packages directory?
Thanks
| [
"Not sure if this is what you're after but doing this might work.\nimport os\ndir_of_current_module = os.path.dirname(__file__)\n\nOnce you know the dir, you can chdir() to it or do what you want. Remember: You might not always have permissions to do stuff there.\n"
] | [
1
] | [] | [] | [
"command_line",
"installation",
"python"
] | stackoverflow_0003038338_command_line_installation_python.txt |
Q:
Environment variables
I use the module mechanize in order to log in a site. When I import twill.commands without any other apparent use, some debug messages [0] are displayed [1]. When I delete it, these messages disappear.
How can I see what is changed in the environment in order to emulate it and remove this dependency?
[0] Using the logging module.
[1] More specifically, I am interested in a Following HTTP-EQUIV=REFRESH message.
UPDATE: It turned out that there is a bug in twill.commands which was creating an error when trying to follow the HTTP-EQUIV=REFRESH header. After removing the import twill.commands and the ugly work around it, everything works smoothly.
A:
My guess - without digging in the libraries - is that twill is instantiating a logger, and mechanize is doing the Right Thing for a library, logging if logging has been turned on, not if not.
To enable the logging of mechanize configure a logging.basicConfig root in your application code.
A:
twill uses mechanize internally, you can log into a web site directly with twill.
To follow http-equiv redirection, just use the go command.
go <url> -- visit the given URL. The Python function returns the final URL visited, after all redirects.
To debug http-equiv redirects, enable the relevant debug level.
debug <what> <level> -- turn on or off debugging/tracing for
various functions. The first argument is either 'http' to show HTTP headers, 'equiv-refresh' to test HTTP EQUIV-REFRESH headers, or 'commands' to show twill commands. The second argument is '0' for off, '1' for on.
| Environment variables | I use the module mechanize in order to log in a site. When I import twill.commands without any other apparent use, some debug messages [0] are displayed [1]. When I delete it, these messages disappear.
How can I see what is changed in the environment in order to emulate it and remove this dependency?
[0] Using the logging module.
[1] More specifically, I am interested in a Following HTTP-EQUIV=REFRESH message.
UPDATE: It turned out that there is a bug in twill.commands which was creating an error when trying to follow the HTTP-EQUIV=REFRESH header. After removing the import twill.commands and the ugly work around it, everything works smoothly.
| [
"My guess - without digging in the libraries - is that twill is instantiating a logger, and mechanize is doing the Right Thing for a library, logging if logging has been turned on, not if not.\nTo enable the logging of mechanize configure a logging.basicConfig root in your application code.\n",
"twill uses mechanize internally, you can log into a web site directly with twill.\nTo follow http-equiv redirection, just use the go command.\n\ngo <url> -- visit the given URL. The Python function returns the final URL visited, after all redirects.\n\nTo debug http-equiv redirects, enable the relevant debug level.\n\ndebug <what> <level> -- turn on or off debugging/tracing for\n various functions. The first argument is either 'http' to show HTTP headers, 'equiv-refresh' to test HTTP EQUIV-REFRESH headers, or 'commands' to show twill commands. The second argument is '0' for off, '1' for on.\n\n"
] | [
1,
1
] | [] | [] | [
"logging",
"mechanize",
"python",
"twill"
] | stackoverflow_0003038483_logging_mechanize_python_twill.txt |
Q:
Python + Expat: Error on entities
I have written a small function, which uses ElementTree and xpath to extract the text contents of certain elements in an xml file:
#!/usr/bin/env python2.5
import doctest
from xml.etree import ElementTree
from StringIO import StringIO
def parse_xml_etree(sin, xpath):
"""
Takes as input a stream containing XML and an XPath expression.
Applies the XPath expression to the XML and returns a generator
yielding the text contents of each element returned.
>>> parse_xml_etree(
... StringIO('<test><elem1>one</elem1><elem2>two</elem2></test>'),
... '//elem1').next()
'one'
>>> parse_xml_etree(
... StringIO('<test><elem1>one</elem1><elem2>two</elem2></test>'),
... '//elem2').next()
'two'
>>> parse_xml_etree(
... StringIO('<test><null>�</null><elem3>three</elem3></test>'),
... '//elem2').next()
'three'
"""
tree = ElementTree.parse(sin)
for element in tree.findall(xpath):
yield element.text
if __name__ == '__main__':
doctest.testmod(verbose=True)
The third test fails with the following exception:
ExpatError: reference to invalid character number: line 1, column 13
Is the � entity illegal XML? Regardless whether it is or not, the files I want to parse contain it, and I need some way to parse them. Any suggestions for another parser than Expat, or settings for Expat, that would allow me to do that?
Update: I discovered BeautifulSoup just now, a tag soup parser as noted below in the answer comment, and for fun I went back to this problem and tried to use it as an XML-cleaner in front of ElementTree, but it dutifully converted the � into a just-as-invalid null byte. :-)
cleaned_s = StringIO(
BeautifulStoneSoup('<test><null>�</null><elem3>three</elem3></test>',
convertEntities=BeautifulStoneSoup.XML_ENTITIES
).renderContents()
)
tree = ElementTree.parse(cleaned_s)
... yields
xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 12
In my particular case though, I didn't really need the XPath parsing as such, I could have gone with BeautifulSoup itself and its quite simple node adressing style parsed_tree.test.elem1.contents[0].
A:
� is not in the legal character range defined by the XML spec. Alas, my Python skills are pretty rudimentary, so I'm not much help there.
A:
� is not a valid XML character. Ideally, you'd be able to get the creator of the file to change their process so that the file was not invalid like this.
If you must accept these files, you could pre-process them to turn � into something else. For example, pick @ as an escape character, turn "@" into "@@", and "�" into "@0".
Then as you get the text data from the parser, you can reverse the mapping. This is just an example, you can invent any escaping syntax you like.
| Python + Expat: Error on entities | I have written a small function, which uses ElementTree and xpath to extract the text contents of certain elements in an xml file:
#!/usr/bin/env python2.5
import doctest
from xml.etree import ElementTree
from StringIO import StringIO
def parse_xml_etree(sin, xpath):
"""
Takes as input a stream containing XML and an XPath expression.
Applies the XPath expression to the XML and returns a generator
yielding the text contents of each element returned.
>>> parse_xml_etree(
... StringIO('<test><elem1>one</elem1><elem2>two</elem2></test>'),
... '//elem1').next()
'one'
>>> parse_xml_etree(
... StringIO('<test><elem1>one</elem1><elem2>two</elem2></test>'),
... '//elem2').next()
'two'
>>> parse_xml_etree(
... StringIO('<test><null>�</null><elem3>three</elem3></test>'),
... '//elem2').next()
'three'
"""
tree = ElementTree.parse(sin)
for element in tree.findall(xpath):
yield element.text
if __name__ == '__main__':
doctest.testmod(verbose=True)
The third test fails with the following exception:
ExpatError: reference to invalid character number: line 1, column 13
Is the � entity illegal XML? Regardless whether it is or not, the files I want to parse contain it, and I need some way to parse them. Any suggestions for another parser than Expat, or settings for Expat, that would allow me to do that?
Update: I discovered BeautifulSoup just now, a tag soup parser as noted below in the answer comment, and for fun I went back to this problem and tried to use it as an XML-cleaner in front of ElementTree, but it dutifully converted the � into a just-as-invalid null byte. :-)
cleaned_s = StringIO(
BeautifulStoneSoup('<test><null>�</null><elem3>three</elem3></test>',
convertEntities=BeautifulStoneSoup.XML_ENTITIES
).renderContents()
)
tree = ElementTree.parse(cleaned_s)
... yields
xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 12
In my particular case though, I didn't really need the XPath parsing as such, I could have gone with BeautifulSoup itself and its quite simple node adressing style parsed_tree.test.elem1.contents[0].
| [
"� is not in the legal character range defined by the XML spec. Alas, my Python skills are pretty rudimentary, so I'm not much help there.\n",
"� is not a valid XML character. Ideally, you'd be able to get the creator of the file to change their process so that the file was not invalid like this.\nIf you must accept these files, you could pre-process them to turn � into something else. For example, pick @ as an escape character, turn \"@\" into \"@@\", and \"�\" into \"@0\".\nThen as you get the text data from the parser, you can reverse the mapping. This is just an example, you can invent any escaping syntax you like.\n"
] | [
6,
4
] | [] | [] | [
"elementtree",
"expat_parser",
"parsing",
"python",
"xml"
] | stackoverflow_0003038798_elementtree_expat_parser_parsing_python_xml.txt |
Q:
Download Videos from Youtube with Python
I am hoping to write a script that will allow for the detection of video on a url and provide a download link to a *flv for google chrome.
Anyone have any suggestions were to start and get a footing?
A:
if you don't want to reinvent the wheel: http://bitbucket.org/rg3/youtube-dl
| Download Videos from Youtube with Python | I am hoping to write a script that will allow for the detection of video on a url and provide a download link to a *flv for google chrome.
Anyone have any suggestions were to start and get a footing?
| [
"if you don't want to reinvent the wheel: http://bitbucket.org/rg3/youtube-dl\n"
] | [
4
] | [] | [] | [
"google_chrome",
"python",
"youtube"
] | stackoverflow_0003038979_google_chrome_python_youtube.txt |
Q:
unevenly centered subplots in matplotlib in Python?
I am plotting a simple pair of subplots in matplotlib that are for some reason unevenly centered. I plot them as follows:
plt.figure()
# first subplot
s1 = plt.subplot(2, 1, 1)
plt.bar([1, 2, 3], [4, 5, 6])
# second subplot
s2 = plt.subplot(2, 1, 2)
plt.pcolor(rand(5,5))
# add colorbar
plt.colorbar()
# square axes
axes_square(s1)
axes_square(s2)
where axes_square is simply:
def axes_square(plot_handle):
plot_handle.axes.set_aspect(1/plot_handle.axes.get_data_ratio())
The plot I get is attached. The top and bottom plots are unevenly centered. I'd like their yaxis to be aligned and their boxes to be aligned.
If I remove the plt.colorbar() call, the plots become centered. How can I have the plots centered while the colorbar of pcolor is still shown? I want the axes to be centered and have the colorbar be outside of that alignment, either to the left or to the right of the pcolor matrix.
image of plots link
thanks.
A:
Well, this probably isn't exactly what you want, but it'll work:
from numpy.random import rand
import matplotlib.pyplot as plt
plt.figure()
# first subplot
s1 = plt.subplot(2, 2, 2)
plt.bar([1, 2, 3], [4, 5, 6])
# second subplot
s2 = plt.subplot(2, 2, 4)
plt.pcolor(rand(5,5))
# square axes
axes_square(s1)
axes_square(s2)
s_fake = plt.subplot(2, 2, 3)
s_fake.set_axis_off()
# add colorbar
plt.colorbar()
It just makes a fake pair of cells on the left, and doesn't display anything in them. Not pretty, but it works. ;)
Also, I'm guessing that those two imports were implicit in your code ...
A:
Give a cax argument to colorbar to designate where you like the colorbar:
plt.colorbar(cax=plt.gcf().add_axes((0.75,0.1,0.05,0.3)))
| unevenly centered subplots in matplotlib in Python? | I am plotting a simple pair of subplots in matplotlib that are for some reason unevenly centered. I plot them as follows:
plt.figure()
# first subplot
s1 = plt.subplot(2, 1, 1)
plt.bar([1, 2, 3], [4, 5, 6])
# second subplot
s2 = plt.subplot(2, 1, 2)
plt.pcolor(rand(5,5))
# add colorbar
plt.colorbar()
# square axes
axes_square(s1)
axes_square(s2)
where axes_square is simply:
def axes_square(plot_handle):
plot_handle.axes.set_aspect(1/plot_handle.axes.get_data_ratio())
The plot I get is attached. The top and bottom plots are unevenly centered. I'd like their yaxis to be aligned and their boxes to be aligned.
If I remove the plt.colorbar() call, the plots become centered. How can I have the plots centered while the colorbar of pcolor is still shown? I want the axes to be centered and have the colorbar be outside of that alignment, either to the left or to the right of the pcolor matrix.
image of plots link
thanks.
| [
"Well, this probably isn't exactly what you want, but it'll work:\nfrom numpy.random import rand\nimport matplotlib.pyplot as plt\n\nplt.figure()\n# first subplot\ns1 = plt.subplot(2, 2, 2)\nplt.bar([1, 2, 3], [4, 5, 6])\n# second subplot\ns2 = plt.subplot(2, 2, 4)\nplt.pcolor(rand(5,5))\n\n# square axes\naxes_square(s1)\naxes_square(s2)\n\ns_fake = plt.subplot(2, 2, 3)\ns_fake.set_axis_off()\n# add colorbar\nplt.colorbar()\n\nIt just makes a fake pair of cells on the left, and doesn't display anything in them. Not pretty, but it works. ;)\nAlso, I'm guessing that those two imports were implicit in your code ... \n",
"Give a cax argument to colorbar to designate where you like the colorbar:\nplt.colorbar(cax=plt.gcf().add_axes((0.75,0.1,0.05,0.3)))\n\n"
] | [
2,
0
] | [] | [] | [
"matplotlib",
"numpy",
"python",
"scipy"
] | stackoverflow_0003034858_matplotlib_numpy_python_scipy.txt |
Q:
displaying a colored 2d array in matplotlib in Python
I'd like to plot a 2-d matrix from numpy as a colored matrix in Matplotlib. I have the following 9-by-9 array:
my_array = diag(ones(9))
# plot the array
pcolor(my_array)
I'd like to set the first three elements of the diagonal to be a certain color, the next three to be a different color, and the last three a different color. I'd like to specify the color by a hex code string, like "#FF8C00". How can I do this?
Also, how can I set the color of 0-valued elements for pcolor?
A:
To have the elements be different colors, assign them different values:
my_array = diag([1,1,1,2,2,2,3,3,3])
To specify the colors, try:
from matplotlib.colors import ListedColormap, NoNorm
cmap = ListedColormap(['#E0E0E0', '#FF8C00', '#8c00FF', '#00FF8C'])
pcolor(my_array,cmap=cmap,norm=NoNorm())
The norm=NoNorm() argument avoids any scaling of the matrix values, so that 0 gets the first color in the list, 1 the second, etc.
| displaying a colored 2d array in matplotlib in Python | I'd like to plot a 2-d matrix from numpy as a colored matrix in Matplotlib. I have the following 9-by-9 array:
my_array = diag(ones(9))
# plot the array
pcolor(my_array)
I'd like to set the first three elements of the diagonal to be a certain color, the next three to be a different color, and the last three a different color. I'd like to specify the color by a hex code string, like "#FF8C00". How can I do this?
Also, how can I set the color of 0-valued elements for pcolor?
| [
"To have the elements be different colors, assign them different values:\nmy_array = diag([1,1,1,2,2,2,3,3,3])\n\nTo specify the colors, try:\nfrom matplotlib.colors import ListedColormap, NoNorm\ncmap = ListedColormap(['#E0E0E0', '#FF8C00', '#8c00FF', '#00FF8C'])\npcolor(my_array,cmap=cmap,norm=NoNorm())\n\nThe norm=NoNorm() argument avoids any scaling of the matrix values, so that 0 gets the first color in the list, 1 the second, etc.\n"
] | [
2
] | [] | [] | [
"matplotlib",
"numpy",
"python",
"scipy"
] | stackoverflow_0003034363_matplotlib_numpy_python_scipy.txt |
Q:
drawing just half of a matrix in matplotlib with python
How can I draw only half of a matrix, e.g. the upper / lower part of a matrix, with pcolor for example?
Suppose I have a n x n matrix and I draw it using pcolor(my_matrix). I want only the lower half to be shown since other values are redundant. How can this be done?
thanks.
A:
Is it OK to plot zeros in the other half?
pcolor(mat*tri(*shape(mat)))
A:
Use set_ylim:
X = scipy.rand(10,10)
f = pylab.figure()
ax = f.add_subplot(1,1,1)
ax.pcolor(X)
ax.set_ylim([0,5])
f.show()
| drawing just half of a matrix in matplotlib with python | How can I draw only half of a matrix, e.g. the upper / lower part of a matrix, with pcolor for example?
Suppose I have a n x n matrix and I draw it using pcolor(my_matrix). I want only the lower half to be shown since other values are redundant. How can this be done?
thanks.
| [
"Is it OK to plot zeros in the other half?\npcolor(mat*tri(*shape(mat)))\n\n",
"Use set_ylim:\nX = scipy.rand(10,10)\nf = pylab.figure()\nax = f.add_subplot(1,1,1)\nax.pcolor(X)\nax.set_ylim([0,5])\nf.show()\n\n"
] | [
1,
0
] | [] | [] | [
"matplotlib",
"python",
"scipy"
] | stackoverflow_0003039088_matplotlib_python_scipy.txt |
Q:
Convert url for crawler
I'm working on a crawler. Usually, when i type url1 in my browser, browser converts it to url2.
How can i do this in Python?
url1: www.odevsitesi.com/ara.asp?kelime=doğanın dengesinin bozulması
url2: www.odevsitesi.com/ara.asp?kelime=do%F0an%FDn%20dengesinin%20bozulmas%FD
A:
You need to properly encode the URL (iso-8859-9 in your case), separate it into parts, urllib.quote the query part, and put it together again. I.e.:
>>> import urlparse
>>> import urllib
>>> x = u'http://www.odevsitesi.com/ara.asp?kelime=doğanın dengesinin bozulması'
>>> y = x.encode('iso-8859-9')
>>> # just to show what the split of y looks like (we can also handle it as a tuple):
>>> urlparse.urlsplit(y)
SplitResult(scheme='http', netloc='www.odevsitesi.com', path='/ara.asp', query='kelime=do\xf0an\xfdn dengesinin bozulmas\xfd', fragment='')
>>> z = urlparse.urlsplit(y)
>>> quoted = z[:3] + (urllib.quote(z.query), z.fragment)
>>> # now just to show you what the 'quoted' tuple looks like:
>>> quoted
('http', 'www.odevsitesi.com', '/ara.asp', 'kelime%3Ddo%F0an%FDn%20dengesinin%20bozulmas%FD', '')
>>> # and finally putting it back together:
>>> urlparse.urlunsplit(quoted)
'http://www.odevsitesi.com/ara.asp?kelime%3Ddo%F0an%FDn%20dengesinin%20bozulmas%FD'
A:
urllib.quote
http://docs.python.org/library/urllib.html#urllib.quote
Example: quote('/~connolly/') yields '/%7econnolly/'.
| Convert url for crawler | I'm working on a crawler. Usually, when i type url1 in my browser, browser converts it to url2.
How can i do this in Python?
url1: www.odevsitesi.com/ara.asp?kelime=doğanın dengesinin bozulması
url2: www.odevsitesi.com/ara.asp?kelime=do%F0an%FDn%20dengesinin%20bozulmas%FD
| [
"You need to properly encode the URL (iso-8859-9 in your case), separate it into parts, urllib.quote the query part, and put it together again. I.e.:\n>>> import urlparse\n>>> import urllib\n>>> x = u'http://www.odevsitesi.com/ara.asp?kelime=doğanın dengesinin bozulması' \n>>> y = x.encode('iso-8859-9')\n>>> # just to show what the split of y looks like (we can also handle it as a tuple):\n>>> urlparse.urlsplit(y)\nSplitResult(scheme='http', netloc='www.odevsitesi.com', path='/ara.asp', query='kelime=do\\xf0an\\xfdn dengesinin bozulmas\\xfd', fragment='')\n>>> z = urlparse.urlsplit(y)\n>>> quoted = z[:3] + (urllib.quote(z.query), z.fragment)\n>>> # now just to show you what the 'quoted' tuple looks like:\n>>> quoted\n('http', 'www.odevsitesi.com', '/ara.asp', 'kelime%3Ddo%F0an%FDn%20dengesinin%20bozulmas%FD', '')\n>>> # and finally putting it back together:\n>>> urlparse.urlunsplit(quoted)\n'http://www.odevsitesi.com/ara.asp?kelime%3Ddo%F0an%FDn%20dengesinin%20bozulmas%FD'\n\n",
"urllib.quote\nhttp://docs.python.org/library/urllib.html#urllib.quote\nExample: quote('/~connolly/') yields '/%7econnolly/'.\n"
] | [
5,
4
] | [] | [] | [
"python",
"url"
] | stackoverflow_0003039355_python_url.txt |
Q:
How can you print a string using raw_unicode_escape encoding in python 3?
The following code with fail in Python 3.x with TypeError: must be str, not bytes because now encode() returns bytes and print() expects only str.
#!/usr/bin/python
from __future__ import print_function
str2 = "some unicode text"
print(str2.encode('raw_unicode_escape'))
How can you print a Unicode string escaped representation using print()? I'm looking for a solution that will work with Python 2.6 or newer, including 3.x
Update
Below line will work with 3.x but it will not work with 2.6, generating AttributeError: 'file' object has no attribute 'buffer'
sys.stdout.buffer.write(str2.encode('raw_unicode_escape'))
A:
I'd just use:
print(str2.encode('raw_unicode_escape').decode('ascii'))
if you want identical code in Python 3 and Python 2.6 (otherwise you could use repr in 2.6 and ascii in Python 3, but that's not really "identical";-).
A:
I can't reproduce your issue, please see previous revisions of this answer for a log of my attempts (which explains my link in the comments).
However:
It seems like you are trying to force an encoding while writing to a file by doing all the legwork yourself. However in Python 3, open() accepts an encoding parameter that does all the magic for you.
badp@delta:~$ python3
Python 3.1.2 (r312:79147, Apr 15 2010, 12:35:07)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> foo = open("look mah, utf-32", "w", encoding="utf-32")
>>> foo.write("bar")
3
>>> foo.close()
>>> foo = open("look mah, utf-32", "rb")
>>> foo.read()
b'\xff\xfe\x00\x00b\x00\x00\x00a\x00\x00\x00r\x00\x00\x00'
If you are looking for a Python 2 equivalent, it seems like you really want to use io.open().
A:
http://docs.python.org/py3k/library/functions.html#ascii
As repr(), return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by repr() using \x, \u or \U escapes. This generates a string similar to that returned by repr() in Python 2.
And the resulting string will indeed be of type str rather than bytes.
Example:
>>> a = '''Ⴊ ⇠ ਐ ῼ இ ╁ ଠ ୭ ⅙ ㈣'''
>>> ascii(a)
"'\\u10aa \\u21e0 \\u0a10 \\u1ffc \\u0b87 \\u2541 \\u0b20 \\u0b6d \\u2159 \\u3223'"
>>> print(ascii(a))
'\u10aa \u21e0 \u0a10 \u1ffc \u0b87 \u2541 \u0b20 \u0b6d \u2159 \u3223'
And if you wanted to trim off the extra quotes, you could just do print(ascii(a)[1:-1]).
EDIT: As Alex states, you'd have to use repr in Python 2.6 instead of ascii. His solution does indeed work for both Python 2 and 3, but if you plan on doing the conversion a lot (and thus would prefer something easier to type multiple times), one possibility is to put a conditional at the start of your program as follows:
import sys
if sys.version_info[0] == 3:
unic = ascii
else:
unic = repr
And then you just use unic (or whatever you want to call it) wherever you'd use repr in Python 2 and ascii in Python 3.
...Though I suppose you could use elif sys.version_info[0] == 2: instead of else: if you wanted to be a bit more careful.
| How can you print a string using raw_unicode_escape encoding in python 3? | The following code with fail in Python 3.x with TypeError: must be str, not bytes because now encode() returns bytes and print() expects only str.
#!/usr/bin/python
from __future__ import print_function
str2 = "some unicode text"
print(str2.encode('raw_unicode_escape'))
How can you print a Unicode string escaped representation using print()? I'm looking for a solution that will work with Python 2.6 or newer, including 3.x
Update
Below line will work with 3.x but it will not work with 2.6, generating AttributeError: 'file' object has no attribute 'buffer'
sys.stdout.buffer.write(str2.encode('raw_unicode_escape'))
| [
"I'd just use:\nprint(str2.encode('raw_unicode_escape').decode('ascii'))\n\nif you want identical code in Python 3 and Python 2.6 (otherwise you could use repr in 2.6 and ascii in Python 3, but that's not really \"identical\";-).\n",
"I can't reproduce your issue, please see previous revisions of this answer for a log of my attempts (which explains my link in the comments).\nHowever:\nIt seems like you are trying to force an encoding while writing to a file by doing all the legwork yourself. However in Python 3, open() accepts an encoding parameter that does all the magic for you.\nbadp@delta:~$ python3\nPython 3.1.2 (r312:79147, Apr 15 2010, 12:35:07) \n[GCC 4.4.3] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> foo = open(\"look mah, utf-32\", \"w\", encoding=\"utf-32\")\n>>> foo.write(\"bar\")\n3\n>>> foo.close()\n>>> foo = open(\"look mah, utf-32\", \"rb\")\n>>> foo.read()\nb'\\xff\\xfe\\x00\\x00b\\x00\\x00\\x00a\\x00\\x00\\x00r\\x00\\x00\\x00'\n\nIf you are looking for a Python 2 equivalent, it seems like you really want to use io.open().\n",
"http://docs.python.org/py3k/library/functions.html#ascii\n\nAs repr(), return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by repr() using \\x, \\u or \\U escapes. This generates a string similar to that returned by repr() in Python 2.\n\nAnd the resulting string will indeed be of type str rather than bytes.\nExample:\n>>> a = '''Ⴊ ⇠ ਐ ῼ இ ╁ ଠ ୭ ⅙ ㈣'''\n>>> ascii(a)\n\"'\\\\u10aa \\\\u21e0 \\\\u0a10 \\\\u1ffc \\\\u0b87 \\\\u2541 \\\\u0b20 \\\\u0b6d \\\\u2159 \\\\u3223'\"\n>>> print(ascii(a))\n'\\u10aa \\u21e0 \\u0a10 \\u1ffc \\u0b87 \\u2541 \\u0b20 \\u0b6d \\u2159 \\u3223'\n\nAnd if you wanted to trim off the extra quotes, you could just do print(ascii(a)[1:-1]).\nEDIT: As Alex states, you'd have to use repr in Python 2.6 instead of ascii. His solution does indeed work for both Python 2 and 3, but if you plan on doing the conversion a lot (and thus would prefer something easier to type multiple times), one possibility is to put a conditional at the start of your program as follows:\nimport sys\nif sys.version_info[0] == 3:\n unic = ascii\nelse:\n unic = repr\n\nAnd then you just use unic (or whatever you want to call it) wherever you'd use repr in Python 2 and ascii in Python 3.\n...Though I suppose you could use elif sys.version_info[0] == 2: instead of else: if you wanted to be a bit more careful.\n"
] | [
5,
1,
0
] | [] | [] | [
"python",
"python_3.x",
"unicode"
] | stackoverflow_0003038618_python_python_3.x_unicode.txt |
Q:
How does Vista Recycle bin work?
I am trying to write a python module to move files to the 'Recycle Bin' on both Mac and PC.
Is there a way, only from the commandline (and yes, I mean using absloutly no C#/C++/etc) to move a file into the Recycle Bin, and have it appear as a file trashed by drag and drop (or deleted via SHFileOperation, etc).
A:
You should use the SHFileOperation function or, on Vista, the IFileOperation interface (as pointed out by gix below).
From the remarks on SHFileOperation:
When used to delete a file, SHFileOperation permanently deletes the file unless you set the FOF_ALLOWUNDO flag in the fFlags member of the SHFILEOPSTRUCT structure pointed to by lpFileOp. Setting that flag sends the file to the Recycle Bin. If you want to simply delete a file and guarantee that it is not placed in the Recycle Bin, use DeleteFile.
A:
Moving files to Windows' Recycle Bin is a Shell operation. Shell operations are run via COM. For older Windows versions there is the SHFileOperation interface. Since Vista there is the new IFileOperation interface.
A:
I have written a Python library that does precisely that. You might want to check it out.
| How does Vista Recycle bin work? | I am trying to write a python module to move files to the 'Recycle Bin' on both Mac and PC.
Is there a way, only from the commandline (and yes, I mean using absloutly no C#/C++/etc) to move a file into the Recycle Bin, and have it appear as a file trashed by drag and drop (or deleted via SHFileOperation, etc).
| [
"You should use the SHFileOperation function or, on Vista, the IFileOperation interface (as pointed out by gix below).\nFrom the remarks on SHFileOperation:\n\nWhen used to delete a file, SHFileOperation permanently deletes the file unless you set the FOF_ALLOWUNDO flag in the fFlags member of the SHFILEOPSTRUCT structure pointed to by lpFileOp. Setting that flag sends the file to the Recycle Bin. If you want to simply delete a file and guarantee that it is not placed in the Recycle Bin, use DeleteFile.\n\n",
"Moving files to Windows' Recycle Bin is a Shell operation. Shell operations are run via COM. For older Windows versions there is the SHFileOperation interface. Since Vista there is the new IFileOperation interface.\n",
"I have written a Python library that does precisely that. You might want to check it out.\n"
] | [
5,
5,
3
] | [
"It looks like this mailing list entry might help you.\n"
] | [
-1
] | [
"python",
"recycle_bin",
"windows_vista"
] | stackoverflow_0000613246_python_recycle_bin_windows_vista.txt |
Q:
can't use appcfg.py update gae
recently i want to upload GAppProxy to GAE.
but when i use the appcfg.py to update the files,there comes an error,it was:
urllib2.URLError: urlopen error [Errno 8] _ssl.c:480: EOF occurred in
violation of protocol
i don't know why
PS:i live in china,and may be because of the GFW.
and when i use the type :appengine.google.com and then input the password,i can't redict to the index page,there is an error too,which says:ssl error
A:
As per this SO question, the issue is discussed here and the solution is to set proxies, e.g. in Windows on the command line:
set HTTP_PROXY=http://google.cn:80
set HTTPS_PROXY=http://google.cn:80
(or however you set proxies for http and https on your platform, which you don't mention).
| can't use appcfg.py update gae | recently i want to upload GAppProxy to GAE.
but when i use the appcfg.py to update the files,there comes an error,it was:
urllib2.URLError: urlopen error [Errno 8] _ssl.c:480: EOF occurred in
violation of protocol
i don't know why
PS:i live in china,and may be because of the GFW.
and when i use the type :appengine.google.com and then input the password,i can't redict to the index page,there is an error too,which says:ssl error
| [
"As per this SO question, the issue is discussed here and the solution is to set proxies, e.g. in Windows on the command line:\nset HTTP_PROXY=http://google.cn:80 \nset HTTPS_PROXY=http://google.cn:80 \n\n(or however you set proxies for http and https on your platform, which you don't mention).\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0003038518_python.txt |
Q:
Python encoding for pipe.communicate
I'm calling pipe.communicate from Python's subprocess module from Python 2.6. I get the following error from this code:
from subprocess import Popen
pipe = Popen(cwd)
pipe.communicate( data )
For an arbitrary cwd, and where data that contains unicode (specifically 0xE9):
Exec. exception: 'ascii' codec can't encode character u'\xe9' in position 507: ordinal not in range(128)
Traceback (most recent call last):
... stdout, stderr = pipe.communicate( data )
File
"/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py",
line 671, in communicate
return self._communicate(input)
File
"/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py",
line 1177, in _communicate
bytes_written = os.write(self.stdin.fileno(), chunk)
This is happening, I presume, because pipe.communicate() is expecting ASCII encoded string, but data is unicode.
Is this the problem I'm encountering, and i sthere a way to pass unicode to pipe.communicate()?
Thank you for reading!
Brian
A:
I may have solved this by changing:
pipe.communicate( data )
to
pipe.communicate( data.encode('utf8') )
Though I stand to be corrected!
Brian
| Python encoding for pipe.communicate | I'm calling pipe.communicate from Python's subprocess module from Python 2.6. I get the following error from this code:
from subprocess import Popen
pipe = Popen(cwd)
pipe.communicate( data )
For an arbitrary cwd, and where data that contains unicode (specifically 0xE9):
Exec. exception: 'ascii' codec can't encode character u'\xe9' in position 507: ordinal not in range(128)
Traceback (most recent call last):
... stdout, stderr = pipe.communicate( data )
File
"/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py",
line 671, in communicate
return self._communicate(input)
File
"/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py",
line 1177, in _communicate
bytes_written = os.write(self.stdin.fileno(), chunk)
This is happening, I presume, because pipe.communicate() is expecting ASCII encoded string, but data is unicode.
Is this the problem I'm encountering, and i sthere a way to pass unicode to pipe.communicate()?
Thank you for reading!
Brian
| [
"I may have solved this by changing:\npipe.communicate( data )\n\nto \npipe.communicate( data.encode('utf8') )\n\nThough I stand to be corrected!\nBrian\n"
] | [
14
] | [] | [] | [
"encoding",
"popen",
"python",
"subprocess",
"unicode"
] | stackoverflow_0003040101_encoding_popen_python_subprocess_unicode.txt |
Q:
Cannot get variable.replace working properly
I am trying to replace a string with a new string in a python file and write the new string permanently to it. When I run the below script it removes part of the string and not all of it. The string in the file is:
self.id = "027FC8EBC2D1"
And the script I have to replace the string is:
def edit():
o = open("test.py","r+") #open
for line in open("test.py"):
line = line.replace("027FC8EBC2D1","NewValue")
o.write(line)
o.close()
edit()
Thanks for any help.
A:
You cannot safely do what you intend to do, unless the replacement value and the original value have exactly the same length. Unless this is guaranteed, I'd copy the file:
with open('input.txt', 'r') as in_file:
with open('output.txt', 'w') as out_file:
for line in in_file:
line = line.replace('027FC8EBC2D1', 'NewValue')
out_file.write(line)
EDIT (removed misleading information)
A:
Try something like this:
import fileinput
for line in fileinput.input('test.py', inplace=1):
line.replace("027FC8EBC2D1","NewValue")
That makes your call to fh.close() extraneous (the with handles it) and prevents you from having multiple copies of the file open at a time.
A:
The proper way to do (actually simulate;-) "in-place substitution" on text files with Python is the fileinput module:
import fileinput
for line in fileinput.input(['test.py'], inplace=True):
print line.replace('027FC8EBC2D1', 'NewValue'),
Note a couple of crucial details wrt the other answer that suggests the same module: input's first argument must be a list of filenames (not a string!), and, you do have to print every line that you want in the resulting file (fileinput redirects standard output to perform -- actually simulate -- the "overwrite in-place" effect).
A final small but not-negligible detail: the comma at the end of the print statement is to avoid adding another newline at the end (since each line already ends with a newline!-).
A:
You're opening the file as read-only and trying to write to it. And you've also got it open twice at once.
You'll want to reorganize it so that you've only got it open once, and that it is read-write.
A:
If you've got enough memory, compared to the size of your file, you can actually get away with this:
# Open the file for read/write access
f = open( 'test.py', 'r+' )
# Read the entire contents of the file into memory
data = f.read()
# Replace the old value with the new one
data.replace( '027FC8EBC2D1', 'NewValue' )
# Truncate the file (in case NewValue is shorter than OldValue)
f.truncate( 0 )
# Write all the data out again
f.write( data )
# Close the file
f.close()
I wouldn't recommend it for very large files, but it's going to be a faster solution than you might otherwise expect.
| Cannot get variable.replace working properly | I am trying to replace a string with a new string in a python file and write the new string permanently to it. When I run the below script it removes part of the string and not all of it. The string in the file is:
self.id = "027FC8EBC2D1"
And the script I have to replace the string is:
def edit():
o = open("test.py","r+") #open
for line in open("test.py"):
line = line.replace("027FC8EBC2D1","NewValue")
o.write(line)
o.close()
edit()
Thanks for any help.
| [
"You cannot safely do what you intend to do, unless the replacement value and the original value have exactly the same length. Unless this is guaranteed, I'd copy the file:\nwith open('input.txt', 'r') as in_file:\n with open('output.txt', 'w') as out_file:\n for line in in_file:\n line = line.replace('027FC8EBC2D1', 'NewValue')\n out_file.write(line)\n\nEDIT (removed misleading information)\n",
"Try something like this:\nimport fileinput\nfor line in fileinput.input('test.py', inplace=1):\n line.replace(\"027FC8EBC2D1\",\"NewValue\")\n\nThat makes your call to fh.close() extraneous (the with handles it) and prevents you from having multiple copies of the file open at a time.\n",
"The proper way to do (actually simulate;-) \"in-place substitution\" on text files with Python is the fileinput module:\nimport fileinput\n\nfor line in fileinput.input(['test.py'], inplace=True):\n print line.replace('027FC8EBC2D1', 'NewValue'),\n\nNote a couple of crucial details wrt the other answer that suggests the same module: input's first argument must be a list of filenames (not a string!), and, you do have to print every line that you want in the resulting file (fileinput redirects standard output to perform -- actually simulate -- the \"overwrite in-place\" effect).\nA final small but not-negligible detail: the comma at the end of the print statement is to avoid adding another newline at the end (since each line already ends with a newline!-).\n",
"You're opening the file as read-only and trying to write to it. And you've also got it open twice at once.\nYou'll want to reorganize it so that you've only got it open once, and that it is read-write.\n",
"If you've got enough memory, compared to the size of your file, you can actually get away with this:\n# Open the file for read/write access\nf = open( 'test.py', 'r+' )\n\n# Read the entire contents of the file into memory\ndata = f.read()\n\n# Replace the old value with the new one\ndata.replace( '027FC8EBC2D1', 'NewValue' )\n\n# Truncate the file (in case NewValue is shorter than OldValue)\nf.truncate( 0 )\n\n# Write all the data out again\nf.write( data )\n\n# Close the file\nf.close()\n\nI wouldn't recommend it for very large files, but it's going to be a faster solution than you might otherwise expect.\n"
] | [
5,
2,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003038706_python.txt |
Q:
Python timed file upload
I have a python script that accepts a file from the user and saves it.
Is it possible to not upload the file immediately but to que it up and when the server has less load to upload it then.
Can this be done by transferring the file to the browsers storage area or taking the file from the Harddrive and transferring to the User's RAM?
A:
There is no reliable way to do what you're asking, because fundamentally, your server has no control over the user's browser, computer, or internet connection. If you don't care about reliability, you might try writing a bunch of javascript to trigger the upload at a scheduled time, but it just wouldn't work if the user closed his browser, navigated away from your web page, turned off his computer, walked away from his wifi signal, etc.
If your web site is really so heavily loaded that it buckles when lots of users upload files at once, it might be time to profile your code, use multiple servers, or perhaps use a separate upload server to accept files and then schedule transfer to your main server later.
| Python timed file upload | I have a python script that accepts a file from the user and saves it.
Is it possible to not upload the file immediately but to que it up and when the server has less load to upload it then.
Can this be done by transferring the file to the browsers storage area or taking the file from the Harddrive and transferring to the User's RAM?
| [
"There is no reliable way to do what you're asking, because fundamentally, your server has no control over the user's browser, computer, or internet connection. If you don't care about reliability, you might try writing a bunch of javascript to trigger the upload at a scheduled time, but it just wouldn't work if the user closed his browser, navigated away from your web page, turned off his computer, walked away from his wifi signal, etc.\nIf your web site is really so heavily loaded that it buckles when lots of users upload files at once, it might be time to profile your code, use multiple servers, or perhaps use a separate upload server to accept files and then schedule transfer to your main server later.\n"
] | [
3
] | [] | [] | [
"architecture",
"file",
"file_upload",
"python"
] | stackoverflow_0003040290_architecture_file_file_upload_python.txt |
Q:
rename keys in a dictionary
i want to rename the keys of a dictionary are which are ints, and i need them to be ints with leading zeros's so that they sort correctly.
for example my keys are like:
'1','101','11'
and i need them to be:
'001','101','011'
this is what im doing now, but i know there is a better way
tmpDict = {}
for oldKey in aDict:
tmpDict['%04d'%int(oldKey)] = aDict[oldKey]
newDict = tmpDict
A:
You're going about it the wrong way. If you want to pull the entries from the dict in a sorted manner then you need to sort upon extraction.
for k in sorted(D, key=int):
print '%s: %r' % (k, D[k])
A:
You can sort with whatever key you want.
So, for example: sorted(mydict, key=int)
A:
aDict = dict((('%04d' % oldKey, oldValue) \
for (oldKey, oldValue) in aDict.iteritems()))
...or %03d if you need three digits as in your example.
| rename keys in a dictionary | i want to rename the keys of a dictionary are which are ints, and i need them to be ints with leading zeros's so that they sort correctly.
for example my keys are like:
'1','101','11'
and i need them to be:
'001','101','011'
this is what im doing now, but i know there is a better way
tmpDict = {}
for oldKey in aDict:
tmpDict['%04d'%int(oldKey)] = aDict[oldKey]
newDict = tmpDict
| [
"You're going about it the wrong way. If you want to pull the entries from the dict in a sorted manner then you need to sort upon extraction.\nfor k in sorted(D, key=int):\n print '%s: %r' % (k, D[k])\n\n",
"You can sort with whatever key you want.\nSo, for example: sorted(mydict, key=int)\n",
"aDict = dict((('%04d' % oldKey, oldValue) \\\n for (oldKey, oldValue) in aDict.iteritems()))\n\n...or %03d if you need three digits as in your example.\n"
] | [
7,
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003040727_dictionary_python.txt |
Q:
Union on ValuesQuerySet in django
I've been searching for a way to take the union of querysets in django. From what I read you can use query1 | query2 to take the union... This doesn't seem to work when using values() though. I'd skip using values until after taking the union but I need to use annotate to take the sum of a field and filter on it and since there's no way to do "group by" I have to use values(). The other suggestions I read were to use Q objects but I can't think of a way that would work.
Do I pretty much need to just use straight SQL or is there a django way of doing this?
What I want is:
q1 = mymodel.objects.filter(date__lt = '2010-06-11').values('field1','field2').annotate(volsum=Sum('volume')).exclude(volsum=0)
q2 = mymodel.objects.values('field1','field2').annotate(volsum=Sum('volume')).exclude(volsum=0)
query = q1|q2
But this doesn't work and as far as I know I need the "values" part because there's no other way for Sum to know how to act since it's a 15 column table.
A:
QuerySet.values() does not return a QuerySet, but rather a ValuesQuerySet, which does not support this operation. Convert them to lists then add them.
query = list(q1) + list(q2)
| Union on ValuesQuerySet in django | I've been searching for a way to take the union of querysets in django. From what I read you can use query1 | query2 to take the union... This doesn't seem to work when using values() though. I'd skip using values until after taking the union but I need to use annotate to take the sum of a field and filter on it and since there's no way to do "group by" I have to use values(). The other suggestions I read were to use Q objects but I can't think of a way that would work.
Do I pretty much need to just use straight SQL or is there a django way of doing this?
What I want is:
q1 = mymodel.objects.filter(date__lt = '2010-06-11').values('field1','field2').annotate(volsum=Sum('volume')).exclude(volsum=0)
q2 = mymodel.objects.values('field1','field2').annotate(volsum=Sum('volume')).exclude(volsum=0)
query = q1|q2
But this doesn't work and as far as I know I need the "values" part because there's no other way for Sum to know how to act since it's a 15 column table.
| [
"QuerySet.values() does not return a QuerySet, but rather a ValuesQuerySet, which does not support this operation. Convert them to lists then add them.\nquery = list(q1) + list(q2)\n\n"
] | [
2
] | [] | [] | [
"django",
"python",
"sql"
] | stackoverflow_0003041020_django_python_sql.txt |
Q:
Could random.randint(1,10) ever return 11?
When researching for this question and reading the sourcecode in random.py, I started wondering whether randrange and randint really behave as "advertised". I am very much inclined to believe so, but the way I read it, randrange is essentially implemented as
start + int(random.random()*(stop-start))
(assuming integer values for start and stop), so randrange(1, 10) should return a random number between 1 and 9.
randint(start, stop) is calling randrange(start, stop+1), thereby returning a number between 1 and 10.
My question is now:
If random() were ever to return 1.0, then randint(1,10) would return 11, wouldn't it?
A:
From random.py and the docs:
"""Get the next random number in the range [0.0, 1.0)."""
The ) indicates that the interval is exclusive 1.0. That is, it will never return 1.0.
This is a general convention in mathematics, [ and ] is inclusive, while ( and ) is exclusive, and the two types of parenthesis can be mixed as (a, b] or [a, b). Have a look at wikipedia: Interval (mathematics) for a formal explanation.
A:
Other answers have pointed out that the result of random() is always strictly less than 1.0; however, that's only half the story.
If you're computing randrange(n) as int(random() * n), you also need to know that for any Python float x satisfying 0.0 <= x < 1.0, and any positive integer n, it's true that 0.0 <= x * n < n, so that int(x * n) is strictly less than n.
There are two things that could go wrong here: first, when we compute x * n, n is implicitly converted to a float. For large enough n, that conversion might alter the value. But if you look at the Python source, you'll see that it only uses the int(random() * n) method for n smaller than 2**53 (here and below I'm assuming that the platform uses IEEE 754 doubles), which is the range where the conversion of n to a float is guaranteed not to lose information (because n can be represented exactly as a float).
The second thing that could go wrong is that the result of the multiplication x * n (which is now being performed as a product of floats, remember) probably won't be exactly representable, so there will be some rounding involved. If x is close enough to 1.0, it's conceivable that the rounding will round the result up to n itself.
To see that this can't happen, we only need to consider the largest possible value for x, which is (on almost all machines that Python runs on) 1 - 2**-53. So we need to show that (1 - 2**-53) * n < n for our positive integer n, since it'll always be true that random() * n <= (1 - 2**-53) * n.
Proof (Sketch) Let k be the unique integer k such that 2**(k-1) < n <= 2**k. Then the next float down from n is n - 2**(k-53). We need to show that n*(1-2**53) (i.e., the actual, unrounded, value of the product) is closer to n - 2**(k-53) than to n, so that it'll always be rounded down. But a little arithmetic shows that the distance from n*(1-2**-53) to n is 2**-53 * n, while the distance from n*(1-2**-53) to n - 2**(k-53) is (2**k - n) * 2**-53. But 2**k - n < n (because we chose k so that 2**(k-1) < n), so the product is closer to n - 2**(k-53), so it will get rounded down (assuming, that is, that the platform is doing some form of round-to-nearest).
So we're safe. Phew!
Addendum (2015-07-04): The above assumes IEEE 754 binary64 arithmetic, with round-ties-to-even rounding mode. On many machines, that assumption is fairly safe. However, on x86 machines that use the x87 FPU for floating-point (for example, various flavours of 32-bit Linux), there's a possibility of double rounding in the multiplication, and that makes it possible for random() * n to round up to n in the case where random() returns the largest possible value. The smallest such n for which this can happen is n = 2049. See the discussion at http://bugs.python.org/issue24546 for more.
A:
From Python documentation:
Almost all module functions depend on the basic function random(), which generates a random float uniformly in the semi-open range [0.0, 1.0).
Like almost every PRNG of float numbers..
| Could random.randint(1,10) ever return 11? | When researching for this question and reading the sourcecode in random.py, I started wondering whether randrange and randint really behave as "advertised". I am very much inclined to believe so, but the way I read it, randrange is essentially implemented as
start + int(random.random()*(stop-start))
(assuming integer values for start and stop), so randrange(1, 10) should return a random number between 1 and 9.
randint(start, stop) is calling randrange(start, stop+1), thereby returning a number between 1 and 10.
My question is now:
If random() were ever to return 1.0, then randint(1,10) would return 11, wouldn't it?
| [
"From random.py and the docs:\n\"\"\"Get the next random number in the range [0.0, 1.0).\"\"\"\n\nThe ) indicates that the interval is exclusive 1.0. That is, it will never return 1.0.\nThis is a general convention in mathematics, [ and ] is inclusive, while ( and ) is exclusive, and the two types of parenthesis can be mixed as (a, b] or [a, b). Have a look at wikipedia: Interval (mathematics) for a formal explanation.\n",
"Other answers have pointed out that the result of random() is always strictly less than 1.0; however, that's only half the story.\nIf you're computing randrange(n) as int(random() * n), you also need to know that for any Python float x satisfying 0.0 <= x < 1.0, and any positive integer n, it's true that 0.0 <= x * n < n, so that int(x * n) is strictly less than n.\nThere are two things that could go wrong here: first, when we compute x * n, n is implicitly converted to a float. For large enough n, that conversion might alter the value. But if you look at the Python source, you'll see that it only uses the int(random() * n) method for n smaller than 2**53 (here and below I'm assuming that the platform uses IEEE 754 doubles), which is the range where the conversion of n to a float is guaranteed not to lose information (because n can be represented exactly as a float).\nThe second thing that could go wrong is that the result of the multiplication x * n (which is now being performed as a product of floats, remember) probably won't be exactly representable, so there will be some rounding involved. If x is close enough to 1.0, it's conceivable that the rounding will round the result up to n itself.\nTo see that this can't happen, we only need to consider the largest possible value for x, which is (on almost all machines that Python runs on) 1 - 2**-53. So we need to show that (1 - 2**-53) * n < n for our positive integer n, since it'll always be true that random() * n <= (1 - 2**-53) * n.\nProof (Sketch) Let k be the unique integer k such that 2**(k-1) < n <= 2**k. Then the next float down from n is n - 2**(k-53). We need to show that n*(1-2**53) (i.e., the actual, unrounded, value of the product) is closer to n - 2**(k-53) than to n, so that it'll always be rounded down. But a little arithmetic shows that the distance from n*(1-2**-53) to n is 2**-53 * n, while the distance from n*(1-2**-53) to n - 2**(k-53) is (2**k - n) * 2**-53. But 2**k - n < n (because we chose k so that 2**(k-1) < n), so the product is closer to n - 2**(k-53), so it will get rounded down (assuming, that is, that the platform is doing some form of round-to-nearest).\nSo we're safe. Phew!\n\nAddendum (2015-07-04): The above assumes IEEE 754 binary64 arithmetic, with round-ties-to-even rounding mode. On many machines, that assumption is fairly safe. However, on x86 machines that use the x87 FPU for floating-point (for example, various flavours of 32-bit Linux), there's a possibility of double rounding in the multiplication, and that makes it possible for random() * n to round up to n in the case where random() returns the largest possible value. The smallest such n for which this can happen is n = 2049. See the discussion at http://bugs.python.org/issue24546 for more.\n",
"From Python documentation:\n\nAlmost all module functions depend on the basic function random(), which generates a random float uniformly in the semi-open range [0.0, 1.0).\n\nLike almost every PRNG of float numbers..\n"
] | [
27,
12,
3
] | [] | [] | [
"bounds",
"python",
"random"
] | stackoverflow_0003037952_bounds_python_random.txt |
Q:
IDL-like parser that turns a document definition into powerful classes?
I am looking for an IDL-like (or whatever) translator which turns a DOM- or JSON-like document definition into classes which
are accessible from both C++ and Python, within the same application
expose document properties as ints, floats, strings, binary blobs and compounds: array, string dict (both nestable) (basically the JSON type feature set)
allow changes to be tracked to refresh views of an editing UI
provide a change history to enable undo/redo operations
can be serialized to and from JSON (can also be some kind of binary format)
allow to keep large data chunks on disk, with parts only loaded on demand
provide non-blocking thread-safe read/write access to exchange data with realtime threads
allow multiple editors in different processes (or even on different machines) to view and modify the document
The thing that comes closest so far is the Blender 2.5 DNA/RNA system, but it's not available as a separate library, and badly documented.
I'm most of all trying to make sure that such a lib does not exist yet, so I know my time is not wasted when I start to design and write such a thing. It's supposed to provide a great foundation to write editing UI components.
A:
ICE is the closest product I could think of. I don't know if you can do serialization to disk with ICE, but I can't think of a reason why it wouldn't. Problem is it costs $$$. I haven't personally negotiated a license with them, but ICE is the biggest player I know of in this domain.
Then you have Pyro for python which is Distributed Objects only.
Distributed Objects in Objective-C (N/A for iPhone/iPad Dev, which sucks IMHO)
There are some C++ distributed objects libraries but they're mostly dead and unusable (CORBA comes to mind).
I can tell you that there would be a lot of demand for this type of technology. I've been delving into some serialization and remote object stuff since off-the-shelf solutions can be very expensive.
As for open-source frameworks to help you develop in-house, I recommend boost::asio's strands for async thread-safe read/write and boost::serialization for serialization. I'm not terribly well-read in JSON tech but this looks like an interesting read.
I wish something freely available already existed for this networking/serialization glue that so many projects could benefit from.
A:
SWIG doesn't meet all your requirements, but does make interfacing c++ <-> python a lot easier.
| IDL-like parser that turns a document definition into powerful classes? | I am looking for an IDL-like (or whatever) translator which turns a DOM- or JSON-like document definition into classes which
are accessible from both C++ and Python, within the same application
expose document properties as ints, floats, strings, binary blobs and compounds: array, string dict (both nestable) (basically the JSON type feature set)
allow changes to be tracked to refresh views of an editing UI
provide a change history to enable undo/redo operations
can be serialized to and from JSON (can also be some kind of binary format)
allow to keep large data chunks on disk, with parts only loaded on demand
provide non-blocking thread-safe read/write access to exchange data with realtime threads
allow multiple editors in different processes (or even on different machines) to view and modify the document
The thing that comes closest so far is the Blender 2.5 DNA/RNA system, but it's not available as a separate library, and badly documented.
I'm most of all trying to make sure that such a lib does not exist yet, so I know my time is not wasted when I start to design and write such a thing. It's supposed to provide a great foundation to write editing UI components.
| [
"ICE is the closest product I could think of. I don't know if you can do serialization to disk with ICE, but I can't think of a reason why it wouldn't. Problem is it costs $$$. I haven't personally negotiated a license with them, but ICE is the biggest player I know of in this domain.\nThen you have Pyro for python which is Distributed Objects only.\nDistributed Objects in Objective-C (N/A for iPhone/iPad Dev, which sucks IMHO)\nThere are some C++ distributed objects libraries but they're mostly dead and unusable (CORBA comes to mind).\nI can tell you that there would be a lot of demand for this type of technology. I've been delving into some serialization and remote object stuff since off-the-shelf solutions can be very expensive.\nAs for open-source frameworks to help you develop in-house, I recommend boost::asio's strands for async thread-safe read/write and boost::serialization for serialization. I'm not terribly well-read in JSON tech but this looks like an interesting read.\nI wish something freely available already existed for this networking/serialization glue that so many projects could benefit from.\n",
"SWIG doesn't meet all your requirements, but does make interfacing c++ <-> python a lot easier. \n"
] | [
1,
0
] | [] | [] | [
"c++",
"data_binding",
"json",
"python",
"serialization"
] | stackoverflow_0003040708_c++_data_binding_json_python_serialization.txt |
Q:
SyntaxError using gdata-python-client to access Google Book Search Data API
>>> import gdata.books.service
>>> service = gdata.books.service.BookService()
>>> results = service.search_by_keyword(isbn='0434003484')
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
results = service.search_by_keyword(isbn='0434003484')
... snip ...
File "C:\Python26\lib\site-packages\atom\__init__.py", line 127, in CreateClassFromXMLString
tree = ElementTree.fromstring(xml_string)
File "<string>", line 85, in XML
SyntaxError: syntax error: line 1, column 0
This is a minimal example -- in particular, the book service unit tests included in the package also fail with the exact same error. I've looked at the wiki and open issue tickets on Google Code to no avail (and this seems to me more apt to be a silly error on my end rather than a problem with the library). I'm not sure how to interpret the error message. If it matters, I'm using python 2.6.5 and the latest version of gdata, namely 2.0.10.
A:
I found I needed to disable SSL in the gdata client for it to work:
...
gd_client.ProgrammaticLogin()
gd_client.ssl = False
...
A:
sje397's answer is the correct one; in your example above, if you do:
service.ssl = False
before running the search_by_keyword method, the result is properly returned. If you don't set SSL to be false, then because the client hasn't properly authenticated, the request is redirected to the main Google homepage (hence what Alex Martelli was seeing errors in was the HTML you get when you go to http://www.google.com ... definitely not well-formed XML).
A:
Hacking around a bit to see the xml string, I notice it has a lowercase <!doctype html> at the start (should be uppercase DOCTYPE) which of course is making the XML parse fail -- definitely a bug in the book service which needs to be reported. As a temporary workaround you could hack the atom/__init__.xml to change line 127 to...:
tree = ElementTree.fromstring(xml_string.replace('doctype','DOCTYPE'))
but while that gets past this bug in the XML it reveals another at column 496 (I think that's in the middle of some javascript code). I guess there's something borken in bookservice in general at this point...:-(
| SyntaxError using gdata-python-client to access Google Book Search Data API | >>> import gdata.books.service
>>> service = gdata.books.service.BookService()
>>> results = service.search_by_keyword(isbn='0434003484')
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
results = service.search_by_keyword(isbn='0434003484')
... snip ...
File "C:\Python26\lib\site-packages\atom\__init__.py", line 127, in CreateClassFromXMLString
tree = ElementTree.fromstring(xml_string)
File "<string>", line 85, in XML
SyntaxError: syntax error: line 1, column 0
This is a minimal example -- in particular, the book service unit tests included in the package also fail with the exact same error. I've looked at the wiki and open issue tickets on Google Code to no avail (and this seems to me more apt to be a silly error on my end rather than a problem with the library). I'm not sure how to interpret the error message. If it matters, I'm using python 2.6.5 and the latest version of gdata, namely 2.0.10.
| [
"I found I needed to disable SSL in the gdata client for it to work:\n...\ngd_client.ProgrammaticLogin()\ngd_client.ssl = False\n...\n\n",
"sje397's answer is the correct one; in your example above, if you do:\nservice.ssl = False\n\nbefore running the search_by_keyword method, the result is properly returned. If you don't set SSL to be false, then because the client hasn't properly authenticated, the request is redirected to the main Google homepage (hence what Alex Martelli was seeing errors in was the HTML you get when you go to http://www.google.com ... definitely not well-formed XML).\n",
"Hacking around a bit to see the xml string, I notice it has a lowercase <!doctype html> at the start (should be uppercase DOCTYPE) which of course is making the XML parse fail -- definitely a bug in the book service which needs to be reported. As a temporary workaround you could hack the atom/__init__.xml to change line 127 to...:\ntree = ElementTree.fromstring(xml_string.replace('doctype','DOCTYPE'))\n\nbut while that gets past this bug in the XML it reveals another at column 496 (I think that's in the middle of some javascript code). I guess there's something borken in bookservice in general at this point...:-(\n"
] | [
3,
2,
1
] | [] | [] | [
"elementtree",
"gdata",
"gdata_python_client",
"google_books",
"python"
] | stackoverflow_0002925985_elementtree_gdata_gdata_python_client_google_books_python.txt |
Q:
How to take advantage of subprocess within Django? - Django
I'm currently using os.popen() but have been recommended to use subprocess.popen() instead.
Any ideas on how I can integrate this?
It would be cool and fun to have a Python shell accessible on a Django app. But I reckon that it might be a bit complex to implement.
I guess I would have to retrieve the subprocess, as a new request comes in.
Any ideas?
A:
Try:
http://www.datamech.com/devan/trypython/trypythonx.py
and then ask him for the source. That's the route I'd go and then just restrict access to the page within Django's auth system.
| How to take advantage of subprocess within Django? - Django | I'm currently using os.popen() but have been recommended to use subprocess.popen() instead.
Any ideas on how I can integrate this?
It would be cool and fun to have a Python shell accessible on a Django app. But I reckon that it might be a bit complex to implement.
I guess I would have to retrieve the subprocess, as a new request comes in.
Any ideas?
| [
"Try:\nhttp://www.datamech.com/devan/trypython/trypythonx.py\nand then ask him for the source. That's the route I'd go and then just restrict access to the page within Django's auth system.\n"
] | [
1
] | [] | [] | [
"command_line",
"django",
"popen",
"python"
] | stackoverflow_0003036878_command_line_django_popen_python.txt |
Q:
Django colon syntax in template tags: only in newer versions?
I just deployed an application to a new server, and although I'm using virtualenv, I had to install a new environment on the production server, which has a different architecture.
Anyway, I received no TemplateSytaxErrors in development, but on the production server, I get:
Exception Type: TemplateSyntaxError
Exception Value: Caught SyntaxError while rendering: invalid syntax (views.py, line 25)
The offending line is:
{% url admin:password_change as password_change_url %}
Upon removing that line, the TemplateSyntaxError hops to the next line that has a colon in it (and lets other template tags work fine).
So my question is this: is there some discrepancy in versions of Python/Django that would allow or disallow the namespacing syntax?
The template tags are in django-grappelli (http://code.google.com/p/django-grappelli/), so I'd rather not go through their code and rewrite all the template tags.
Development server:
32-bit Debian
Python 2.5.5
Django 1.2.1
Production server:
64-bit CentOS
Python 2.4.3
Django 1.2.1
Any ideas?
A:
On closer inspection, I realized this wasn't the offending line, even though it was highlighted in the traceback:
{% url admin:password_change as password_change_url %}
The line was actually in my views.py, where I used the ternary operator ("this" if condition else "that"). Little did I know, this syntax is only supported in Python 2.5 and up.
Problem solved.
| Django colon syntax in template tags: only in newer versions? | I just deployed an application to a new server, and although I'm using virtualenv, I had to install a new environment on the production server, which has a different architecture.
Anyway, I received no TemplateSytaxErrors in development, but on the production server, I get:
Exception Type: TemplateSyntaxError
Exception Value: Caught SyntaxError while rendering: invalid syntax (views.py, line 25)
The offending line is:
{% url admin:password_change as password_change_url %}
Upon removing that line, the TemplateSyntaxError hops to the next line that has a colon in it (and lets other template tags work fine).
So my question is this: is there some discrepancy in versions of Python/Django that would allow or disallow the namespacing syntax?
The template tags are in django-grappelli (http://code.google.com/p/django-grappelli/), so I'd rather not go through their code and rewrite all the template tags.
Development server:
32-bit Debian
Python 2.5.5
Django 1.2.1
Production server:
64-bit CentOS
Python 2.4.3
Django 1.2.1
Any ideas?
| [
"On closer inspection, I realized this wasn't the offending line, even though it was highlighted in the traceback:\n{% url admin:password_change as password_change_url %}\n\nThe line was actually in my views.py, where I used the ternary operator (\"this\" if condition else \"that\"). Little did I know, this syntax is only supported in Python 2.5 and up.\nProblem solved.\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003040356_django_python.txt |
Q:
Gstreamer of python's gst.LinkError problem
I am wiring a gstreamer application with Python. And I get a LinkError with following code:
import pygst
pygst.require('0.10')
import gst
import pygtk
pygtk.require('2.0')
import gtk
# this is very important, without this, callbacks from gstreamer thread
# will messed our program up
gtk.gdk.threads_init()
def main():
pipeline = gst.Pipeline('pipleline')
filesrc = gst.element_factory_make("filesrc", "filesrc")
filesrc.set_property('location', 'C:/a.mp3')
decode = gst.element_factory_make("decodebin", "decode")
convert = gst.element_factory_make('audioconvert', 'convert')
sink = gst.element_factory_make("autoaudiosink", "sink")
pipeline.add(filesrc, decode, convert, sink)
gst.element_link_many(filesrc, decode, convert, sink)
pipeline.set_state(gst.STATE_PLAYING)
gtk.main()
main()
And the error:
ImportError: could not import gio
Traceback (most recent call last):
File "H:\workspace\ggg\src\test2.py", line 37, in <module>
main()
File "H:\workspace\ggg\src\test2.py", line 31, in main
gst.element_link_many(filesrc, decode, convert, sink)
gst.LinkError: failed to link decode with convert
It is very strange, with same pipeline, but built with parse_launch, it works. Here is the code:
import pygst
pygst.require('0.10')
import gst
import pygtk
pygtk.require('2.0')
import gtk
# this is very important, without this, callbacks from gstreamer thread
# will messed our program up
gtk.gdk.threads_init()
def main():
player = gst.parse_launch('filesrc location=C:/a.mp3 ! decodebin ! audioconvert ! autoaudiosink')
player.set_state(gst.STATE_PLAYING)
gtk.main()
main()
Here comes the question, why the manual one failed, but the parsed one success? What's wrong with that? How can I fix it?
Thanks.
A:
your problem is here:
gst.element_link_many(filesrc, decode, convert, sink)
the reason is that not all elements have simple, static inputs and outputs. at this point in your program, your decodebin does not have any source pads (that is: no outputs).
a pad is like a nipple - it's an input / output to an element. pads can appear, disappear or just sit there. there are three classes of pads: static pads (the easiest and what you would expect), request pads (that appear only when you ask for them) and sometimes pads (that appear only when the element wants to make them appear). the outputs of decodebin are sometimes pads.
if you inspect the output of gst-inspect decodebin, you can see this for yourself:
Pad Templates:
SINK template: 'sink'
Availability: Always
Capabilities:
ANY
SRC template: 'src%d'
Availability: Sometimes
Capabilities:
ANY
at line 26 of your program, you can't link decode to anything, because it doesn't have any source pads to link with. source pads on a decodebin appear only as the input stream is decoded: this doesn't happen instantaneously. any number of source pads may appear (e.g one for an audio stream, two for a video stream with audio, none for an un-decodable stream).
you need to wait until the pads are created, and then link them. decodebin emits a signal, "new-decoded-pad" to tell you when this happens (this is also documented in gst-inspect decodebin). you must connect a callback function to this signal, and link your decode and audioconvert in the callback. here is your corrected code:
#!/usr/bin/python
import pygst
pygst.require('0.10')
import gst
import pygtk
pygtk.require('2.0')
import gtk
# this is very important, without this, callbacks from gstreamer thread
# will messed our program up
gtk.gdk.threads_init()
def on_new_decoded_pad(dbin, pad, islast):
decode = pad.get_parent()
pipeline = decode.get_parent()
convert = pipeline.get_by_name('convert')
decode.link(convert)
pipeline.set_state(gst.STATE_PLAYING)
print "linked!"
def main():
pipeline = gst.Pipeline('pipleline')
filesrc = gst.element_factory_make("filesrc", "filesrc")
filesrc.set_property('location', 'C:/a.mp3')
decode = gst.element_factory_make("decodebin", "decode")
convert = gst.element_factory_make('audioconvert', 'convert')
sink = gst.element_factory_make("autoaudiosink", "sink")
pipeline.add(filesrc, decode, convert, sink)
gst.element_link_many(filesrc, decode)
gst.element_link_many(convert, sink)
decode.connect("new-decoded-pad", on_new_decoded_pad)
pipeline.set_state(gst.STATE_PAUSED)
gtk.main()
main()
gst.parse_launch works because it takes care of all these niggly details for you. there is also the high level element playbin which automatically creates and links a decodebin internally.
| Gstreamer of python's gst.LinkError problem | I am wiring a gstreamer application with Python. And I get a LinkError with following code:
import pygst
pygst.require('0.10')
import gst
import pygtk
pygtk.require('2.0')
import gtk
# this is very important, without this, callbacks from gstreamer thread
# will messed our program up
gtk.gdk.threads_init()
def main():
pipeline = gst.Pipeline('pipleline')
filesrc = gst.element_factory_make("filesrc", "filesrc")
filesrc.set_property('location', 'C:/a.mp3')
decode = gst.element_factory_make("decodebin", "decode")
convert = gst.element_factory_make('audioconvert', 'convert')
sink = gst.element_factory_make("autoaudiosink", "sink")
pipeline.add(filesrc, decode, convert, sink)
gst.element_link_many(filesrc, decode, convert, sink)
pipeline.set_state(gst.STATE_PLAYING)
gtk.main()
main()
And the error:
ImportError: could not import gio
Traceback (most recent call last):
File "H:\workspace\ggg\src\test2.py", line 37, in <module>
main()
File "H:\workspace\ggg\src\test2.py", line 31, in main
gst.element_link_many(filesrc, decode, convert, sink)
gst.LinkError: failed to link decode with convert
It is very strange, with same pipeline, but built with parse_launch, it works. Here is the code:
import pygst
pygst.require('0.10')
import gst
import pygtk
pygtk.require('2.0')
import gtk
# this is very important, without this, callbacks from gstreamer thread
# will messed our program up
gtk.gdk.threads_init()
def main():
player = gst.parse_launch('filesrc location=C:/a.mp3 ! decodebin ! audioconvert ! autoaudiosink')
player.set_state(gst.STATE_PLAYING)
gtk.main()
main()
Here comes the question, why the manual one failed, but the parsed one success? What's wrong with that? How can I fix it?
Thanks.
| [
"your problem is here:\ngst.element_link_many(filesrc, decode, convert, sink)\n\nthe reason is that not all elements have simple, static inputs and outputs. at this point in your program, your decodebin does not have any source pads (that is: no outputs).\na pad is like a nipple - it's an input / output to an element. pads can appear, disappear or just sit there. there are three classes of pads: static pads (the easiest and what you would expect), request pads (that appear only when you ask for them) and sometimes pads (that appear only when the element wants to make them appear). the outputs of decodebin are sometimes pads.\nif you inspect the output of gst-inspect decodebin, you can see this for yourself:\nPad Templates:\n SINK template: 'sink'\n Availability: Always\n Capabilities:\n ANY\n\n SRC template: 'src%d'\n Availability: Sometimes\n Capabilities:\n ANY\n\nat line 26 of your program, you can't link decode to anything, because it doesn't have any source pads to link with. source pads on a decodebin appear only as the input stream is decoded: this doesn't happen instantaneously. any number of source pads may appear (e.g one for an audio stream, two for a video stream with audio, none for an un-decodable stream). \nyou need to wait until the pads are created, and then link them. decodebin emits a signal, \"new-decoded-pad\" to tell you when this happens (this is also documented in gst-inspect decodebin). you must connect a callback function to this signal, and link your decode and audioconvert in the callback. here is your corrected code:\n#!/usr/bin/python\n\nimport pygst\npygst.require('0.10')\nimport gst\n\nimport pygtk\npygtk.require('2.0')\nimport gtk\n\n# this is very important, without this, callbacks from gstreamer thread\n# will messed our program up\ngtk.gdk.threads_init()\n\ndef on_new_decoded_pad(dbin, pad, islast):\n decode = pad.get_parent()\n pipeline = decode.get_parent()\n convert = pipeline.get_by_name('convert')\n decode.link(convert)\n pipeline.set_state(gst.STATE_PLAYING)\n print \"linked!\"\n\ndef main():\n pipeline = gst.Pipeline('pipleline')\n\n filesrc = gst.element_factory_make(\"filesrc\", \"filesrc\")\n filesrc.set_property('location', 'C:/a.mp3')\n\n decode = gst.element_factory_make(\"decodebin\", \"decode\")\n\n convert = gst.element_factory_make('audioconvert', 'convert')\n\n sink = gst.element_factory_make(\"autoaudiosink\", \"sink\")\n\n pipeline.add(filesrc, decode, convert, sink)\n gst.element_link_many(filesrc, decode)\n gst.element_link_many(convert, sink)\n\n decode.connect(\"new-decoded-pad\", on_new_decoded_pad)\n\n pipeline.set_state(gst.STATE_PAUSED)\n\n gtk.main()\n\nmain()\n\ngst.parse_launch works because it takes care of all these niggly details for you. there is also the high level element playbin which automatically creates and links a decodebin internally.\n"
] | [
20
] | [] | [] | [
"gstreamer",
"python"
] | stackoverflow_0002993777_gstreamer_python.txt |
Q:
finding elements in python association lists efficiently
I have a set of lists that look like this:
conditions = [
["condition1", ["sample1", "sample2", "sample3"]],
["condition2", ["sample4", "sample5", "sample6"],
...]
how can I do the following things efficiently and elegantly in Python?
Find all the elements in a certain condition?
e.g. get all the samples in condition2. Right now I can do:
for cond in conditions:
cond_name, samples = cond
if cond_name == requested_cond:
return samples
but that's clunky.
Find the ordered union of a list of conditions? E.g. ordered_union(["condition1", "condition2"], conditions) should return:
["sample1", "sample2", "sample3", "sample4", "sample5", "sample6"]
How can I do this efficiently in Python? There are probably clever one liners?
A:
This looks more like a job for a dict:
conditions = {
"condition1": ["sample1", "sample2", "sample3"],
"condition2": ["sample4", "sample5", "sample6"],
...}
You could then get the "ordered union" using
>>> conditions["condition1"]+conditions["condition2"]
['sample1', 'sample2', 'sample3', 'sample4', 'sample5', 'sample6']
In Python 3.1 or 2.7, you can preserve the order using an OrderedDict instead:
from collections import OrderedDict
conditions = OrderedDict([
["condition1", ["sample1", "sample2", "sample3"]],
["condition2", ["sample4", "sample5", "sample6"]]
])
You could then get the "ordered union", also for OrderedDicts of arbitrary size:
>>> import itertools
>>> [item for item in itertools.chain(*conditions.values())]
['sample1', 'sample2', 'sample3', 'sample4', 'sample5', 'sample6']
A:
Ah well, if you're forced to keep that clunky data structure, you can't expect much. The one-liner equivalent of your first solution is going to be something like:
def samplesof(requested_cond, conditions):
return next(s for c, s in conditions if c==requested_cond)
and for the second one, if you insist on one-liners, it's going to be something like:
def ordered_union(the_conds, conditions):
return [s for c in the_conds for s in samplesof(c, conditions)]
There are faster ways to solve the second problem, but they're all multi-line, e.g.:
aux_set = set(the_conds)
samples_by_cond = dict((c, s) for c, s in conditions if c in aux_set)
return [s for c in the_conds for s in samples_by_cond[c]]
Note that the key to the reason this latter approach is faster is that it uses the right data structures (a set and a dict) -- unfortunately it has to build them itself, because the incoming conditions nested list is really the wrong data structure.
Couldn't you encapsulate conditions as a member variable of a class that builds the crucial (right, fast) auxiliary data structures just once? E.g.:
class Sensible(object):
def __init__(self, conditions):
self.seq = []
self.dic = {}
for c, s in conditions:
self.seq.append(c)
self.dic[c] = s
def samplesof(self, requested_condition):
return self.dic[requested_condition]
def ordered_union(self, the_conds):
return [s for c in the_conds for s in self.dic[c]]
Now that is fast and elegant!
I'm assuming that you need self.seq (the sequence of conditions) for something else (it's certainly not needed for the two operations you mention!), and that there are no repetitions in that sequence and in the samples (whatever your actual specs are they won't be hard to accomodate, but blindly trying to guess them when you mention nothing about them would be very hard and pointless;-).
A:
You need to use a dict (dictionary) instead of a list. Also, you can keep the samples in a set if you want efficient set-based operations.
conditions = { "condition1" : set(["sample1", "sample2", "sample3"]),
"condition2" : set(["sample4", "sample5", "sample6"]) }
print conditions["condition2"]
# set(['sample5', 'sample4', 'sample6'])
union = conditions["condition1"].union(conditions["condition2"])
print sorted(union)
# ['sample1', 'sample2', 'sample3', 'sample4', 'sample5', 'sample6']
A:
On the 1st question:
>>> dict(conditions)['condition1']
['sample1', 'sample2', 'sample3']
On #2 (it's not quite clear what you mean by 'ordered union' so i am making assumption 'ordered lists concatenated in order'):
>>> tmpdict = dict(conditions)
>>> sum( map(tmpdict.get, ["condition1", "condition2"]), [] )
['sample1', 'sample2', 'sample3', 'sample4', 'sample5', 'sample6']
ps. example depreciated to address A.M.'s rightful criticism - that due to implementation issues sum() exhibits quadratic behavior with increase of list size. Instead I suggest the code below:
>>> import operator
>>> tmpdict = dict(conditions)
>>> reduce(operator.iadd, map(tmpdict.get, ["condition1", "condition2"]), [] )
['sample1', 'sample2', 'sample3', 'sample4', 'sample5', 'sample6']
| finding elements in python association lists efficiently | I have a set of lists that look like this:
conditions = [
["condition1", ["sample1", "sample2", "sample3"]],
["condition2", ["sample4", "sample5", "sample6"],
...]
how can I do the following things efficiently and elegantly in Python?
Find all the elements in a certain condition?
e.g. get all the samples in condition2. Right now I can do:
for cond in conditions:
cond_name, samples = cond
if cond_name == requested_cond:
return samples
but that's clunky.
Find the ordered union of a list of conditions? E.g. ordered_union(["condition1", "condition2"], conditions) should return:
["sample1", "sample2", "sample3", "sample4", "sample5", "sample6"]
How can I do this efficiently in Python? There are probably clever one liners?
| [
"This looks more like a job for a dict:\nconditions = {\n\"condition1\": [\"sample1\", \"sample2\", \"sample3\"],\n\"condition2\": [\"sample4\", \"sample5\", \"sample6\"],\n...}\n\nYou could then get the \"ordered union\" using\n>>> conditions[\"condition1\"]+conditions[\"condition2\"]\n['sample1', 'sample2', 'sample3', 'sample4', 'sample5', 'sample6']\n\nIn Python 3.1 or 2.7, you can preserve the order using an OrderedDict instead:\nfrom collections import OrderedDict\nconditions = OrderedDict([\n[\"condition1\", [\"sample1\", \"sample2\", \"sample3\"]],\n[\"condition2\", [\"sample4\", \"sample5\", \"sample6\"]]\n])\n\nYou could then get the \"ordered union\", also for OrderedDicts of arbitrary size:\n>>> import itertools\n>>> [item for item in itertools.chain(*conditions.values())]\n['sample1', 'sample2', 'sample3', 'sample4', 'sample5', 'sample6']\n\n",
"Ah well, if you're forced to keep that clunky data structure, you can't expect much. The one-liner equivalent of your first solution is going to be something like:\ndef samplesof(requested_cond, conditions):\n return next(s for c, s in conditions if c==requested_cond)\n\nand for the second one, if you insist on one-liners, it's going to be something like:\ndef ordered_union(the_conds, conditions):\n return [s for c in the_conds for s in samplesof(c, conditions)]\n\nThere are faster ways to solve the second problem, but they're all multi-line, e.g.:\naux_set = set(the_conds)\nsamples_by_cond = dict((c, s) for c, s in conditions if c in aux_set)\nreturn [s for c in the_conds for s in samples_by_cond[c]]\n\nNote that the key to the reason this latter approach is faster is that it uses the right data structures (a set and a dict) -- unfortunately it has to build them itself, because the incoming conditions nested list is really the wrong data structure.\nCouldn't you encapsulate conditions as a member variable of a class that builds the crucial (right, fast) auxiliary data structures just once? E.g.:\nclass Sensible(object):\n def __init__(self, conditions):\n self.seq = []\n self.dic = {}\n for c, s in conditions:\n self.seq.append(c)\n self.dic[c] = s\n def samplesof(self, requested_condition):\n return self.dic[requested_condition]\n def ordered_union(self, the_conds):\n return [s for c in the_conds for s in self.dic[c]]\n\nNow that is fast and elegant!\nI'm assuming that you need self.seq (the sequence of conditions) for something else (it's certainly not needed for the two operations you mention!), and that there are no repetitions in that sequence and in the samples (whatever your actual specs are they won't be hard to accomodate, but blindly trying to guess them when you mention nothing about them would be very hard and pointless;-).\n",
"You need to use a dict (dictionary) instead of a list. Also, you can keep the samples in a set if you want efficient set-based operations. \nconditions = { \"condition1\" : set([\"sample1\", \"sample2\", \"sample3\"]),\n \"condition2\" : set([\"sample4\", \"sample5\", \"sample6\"]) }\n\nprint conditions[\"condition2\"]\n# set(['sample5', 'sample4', 'sample6'])\nunion = conditions[\"condition1\"].union(conditions[\"condition2\"])\nprint sorted(union)\n# ['sample1', 'sample2', 'sample3', 'sample4', 'sample5', 'sample6']\n\n",
"On the 1st question:\n>>> dict(conditions)['condition1']\n['sample1', 'sample2', 'sample3']\n\nOn #2 (it's not quite clear what you mean by 'ordered union' so i am making assumption 'ordered lists concatenated in order'):\n\n>>> tmpdict = dict(conditions)\n>>> sum( map(tmpdict.get, [\"condition1\", \"condition2\"]), [] )\n['sample1', 'sample2', 'sample3', 'sample4', 'sample5', 'sample6']\n\n\nps. example depreciated to address A.M.'s rightful criticism - that due to implementation issues sum() exhibits quadratic behavior with increase of list size. Instead I suggest the code below:\n>>> import operator\n>>> tmpdict = dict(conditions)\n>>> reduce(operator.iadd, map(tmpdict.get, [\"condition1\", \"condition2\"]), [] )\n['sample1', 'sample2', 'sample3', 'sample4', 'sample5', 'sample6']\n\n"
] | [
6,
5,
2,
2
] | [] | [] | [
"list",
"list_comprehension",
"python"
] | stackoverflow_0003040335_list_list_comprehension_python.txt |
Q:
How can I receive percent encoded slashes with Django on App Engine?
I'm using Django with Google's App Engine.
I want to send information to the server with percent encoded slashes. A request like http:/localhost/turtle/waxy%2Fsmooth that would match against a URL like r'^/turtle/(?P<type>([A-Za-z]|%2F)+)$'. The request gets to the server intact, but sometime before it is compared against the regex the %2F is converted into a forward slash.
What can I do to stop the %2Fs from being converted into forward slashes? Thanks!
A:
os.environ['PATH_INFO'] is decoded, so you lose that information. Probably os.environ['REQUEST_URI'] is available, and if it is available it is not decoded. Django only reads PATH_INFO. You could probably do something like:
request_uri = environ['REQUEST_URI']
request_uri = re.sub(r'%2f', '****', request_uri, re.I)
environ['PATH_INFO'] = urllib.unquote(request_uri)
Then all cases of %2f are replaced with **** (or whatever you want to use).
| How can I receive percent encoded slashes with Django on App Engine? | I'm using Django with Google's App Engine.
I want to send information to the server with percent encoded slashes. A request like http:/localhost/turtle/waxy%2Fsmooth that would match against a URL like r'^/turtle/(?P<type>([A-Za-z]|%2F)+)$'. The request gets to the server intact, but sometime before it is compared against the regex the %2F is converted into a forward slash.
What can I do to stop the %2Fs from being converted into forward slashes? Thanks!
| [
"os.environ['PATH_INFO'] is decoded, so you lose that information. Probably os.environ['REQUEST_URI'] is available, and if it is available it is not decoded. Django only reads PATH_INFO. You could probably do something like:\nrequest_uri = environ['REQUEST_URI']\nrequest_uri = re.sub(r'%2f', '****', request_uri, re.I)\nenviron['PATH_INFO'] = urllib.unquote(request_uri)\n\nThen all cases of %2f are replaced with **** (or whatever you want to use).\n"
] | [
4
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0003040659_django_google_app_engine_python.txt |
Q:
FileIO out of order when using subprocesses in Python
I am trying to generate a log file with information in order. This is what I have:
class ExecThread(threading.Thread):
def __init__(self, command):
self.command = command
self._lock = threading.Lock()
threading.Thread.__init__ ( self )
def run ( self ):
self._lock.acquire()
sys.stdout.write(''.join(["Executing: ",self.command,'\n']))
log_file.write(''.join([self.command,'\n']))
os.system(self.command)
self._lock.release()
for ive in locate('*.ive', root_dir):
command = "osgconv"
command = ''.join([command,' ',"-O OutputTextureFiles",' ', infile,' ', outfile,' ',"2>&1"])
conv_osg_thread = ExecThread(command)
conv_osg_thread.start()
conv_osg_thread.join()
The command I am executing has this redirection at the end: "2>&1"
When I run this I get the output of the subprocess before the message "Executing blah", which is listed first! I thought the lock() would fix it, but no.
Please help, I would really appreciate if someone could point out my error.
A:
I/O is buffered by default. Try sys.stdout.flush() after sys.stdout.write().
| FileIO out of order when using subprocesses in Python | I am trying to generate a log file with information in order. This is what I have:
class ExecThread(threading.Thread):
def __init__(self, command):
self.command = command
self._lock = threading.Lock()
threading.Thread.__init__ ( self )
def run ( self ):
self._lock.acquire()
sys.stdout.write(''.join(["Executing: ",self.command,'\n']))
log_file.write(''.join([self.command,'\n']))
os.system(self.command)
self._lock.release()
for ive in locate('*.ive', root_dir):
command = "osgconv"
command = ''.join([command,' ',"-O OutputTextureFiles",' ', infile,' ', outfile,' ',"2>&1"])
conv_osg_thread = ExecThread(command)
conv_osg_thread.start()
conv_osg_thread.join()
The command I am executing has this redirection at the end: "2>&1"
When I run this I get the output of the subprocess before the message "Executing blah", which is listed first! I thought the lock() would fix it, but no.
Please help, I would really appreciate if someone could point out my error.
| [
"I/O is buffered by default. Try sys.stdout.flush() after sys.stdout.write().\n"
] | [
0
] | [] | [] | [
"multithreading",
"python",
"redirect"
] | stackoverflow_0003041686_multithreading_python_redirect.txt |
Q:
Django/jQuery - read file and pass to browser as file download prompt
I've previously asked a question regarding passing files to the browser so a user receives a download prompt. However these files were really just strings creatd at the end of a function and it was simple to pass them to an iframe's src attribute for the desired effect.
Now I have a more ambitious requirement, I need to pass pre existing files of any format to the browser. I have attempted this using the following code:
def return_file(request):
try:
bob=open(urllib.unquote(request.POST["file"]),"rb")
response=HttpResponse(content=bob,mimetype="application/x-unknown")
response["Content-Disposition"] = "attachment; filename=nothing.xls"
return HttpResponse(response)
except:
return HttpResponse(sys.exc_info())
With my original setup the following jQuery was sufficient to give the desired download prompt:
jQuery('#download').attr("src","/return_file/");
However this won't work anymore as I need to pass POST values to the function. my attempt to rectify that is below, but instead of a download prompt I get the file displayed as text.
jQuery.get("/return_file/",{"file":"c:/filename.xls"},function(data)
{
jQuery(thisButton).children("iframe").attr("src",data);
});
Any ideas as to where I'm going wrong?
Thanks!
EDIT:
I've now changed everything so that passing the filename using POST returns an id number retrieved from the database which when appended to the URL causes the file to be returned. Thus /return_file/1/ returns a file with id 1.
jQuery('#download').attr("src","http://localhost/return_file/1/");
where "download" is the id of an iframe.
There must be a better way of dealing with file downloads. Does anyone have ideas for a better method?
A:
Why not just use bob.read() the same way you previously used a differently-constructed string? Seems simplest!
| Django/jQuery - read file and pass to browser as file download prompt | I've previously asked a question regarding passing files to the browser so a user receives a download prompt. However these files were really just strings creatd at the end of a function and it was simple to pass them to an iframe's src attribute for the desired effect.
Now I have a more ambitious requirement, I need to pass pre existing files of any format to the browser. I have attempted this using the following code:
def return_file(request):
try:
bob=open(urllib.unquote(request.POST["file"]),"rb")
response=HttpResponse(content=bob,mimetype="application/x-unknown")
response["Content-Disposition"] = "attachment; filename=nothing.xls"
return HttpResponse(response)
except:
return HttpResponse(sys.exc_info())
With my original setup the following jQuery was sufficient to give the desired download prompt:
jQuery('#download').attr("src","/return_file/");
However this won't work anymore as I need to pass POST values to the function. my attempt to rectify that is below, but instead of a download prompt I get the file displayed as text.
jQuery.get("/return_file/",{"file":"c:/filename.xls"},function(data)
{
jQuery(thisButton).children("iframe").attr("src",data);
});
Any ideas as to where I'm going wrong?
Thanks!
EDIT:
I've now changed everything so that passing the filename using POST returns an id number retrieved from the database which when appended to the URL causes the file to be returned. Thus /return_file/1/ returns a file with id 1.
jQuery('#download').attr("src","http://localhost/return_file/1/");
where "download" is the id of an iframe.
There must be a better way of dealing with file downloads. Does anyone have ideas for a better method?
| [
"Why not just use bob.read() the same way you previously used a differently-constructed string? Seems simplest!\n"
] | [
2
] | [] | [] | [
"django",
"html",
"jquery",
"python"
] | stackoverflow_0003041603_django_html_jquery_python.txt |
Q:
"Passing Go" in a (python) date range
Updated to remove extraneous text and ambiguity.
The Rules:
An employee accrues 8 hours of Paid Time Off on the day after each quarter. Quarters, specifically being:
Jan 1 - Mar 31
Apr 1 - Jun 30
Jul 1 - Sep 30
Oct 1 - Dec 31
The Problem
Using python, I need to define the guts of the following function:
def acrued_hours_between(start_date, end_date):
# stuff
return integer
I'm currently using Python, and wondering what the correct approach to something like this would be.
I'm assuming that using DateTime objects, and possibly the dateutil module, would help here, but my brain isn't wrapping around this problem for some reason.
Update
I imagine the calculation being somewhat simple, as the problem is:
"How many hours of Paid Time Off are accrued from start_date to end_date?" given the above "rules".
A:
The OP's edit mentions the real underlying problem is:
"How many hours of Paid Time Off are
accrued from X-date to Y-date?"
I agree, and I'd compute that in the most direct and straightforward way, e.g.:
import datetime
import itertools
accrual_months_days = (1,1), (4,1), (7,1), (10,1)
def accruals(begin_date, end_date, hours_per=8):
"""Vacation accrued between begin_date and end_date included."""
cur_year = begin_date.year - 1
result = 0
for m, d in itertools.cycle(accrual_months_days):
if m == 1: cur_year += 1
d = datetime.date(cur_year, m, d)
if d < begin_date: continue
if d > end_date: return result
result += hours_per
if __name__ == '__main__': # examples
print accruals(datetime.date(2010, 1, 12), datetime.date(2010, 9, 20))
print accruals(datetime.date(2010, 4, 20), datetime.date(2012, 12, 21))
print accruals(datetime.date(2010, 12, 21), datetime.date(2012, 4, 20))
A direct formula would of course be faster, but could be tricky to do it without bugs -- if nothing else, this "correct by inspection" example can serve to calibrate the faster one automatically, by checking that they agree over a large sample of date pairs (be sure to include in the latter all corner cases such as first and last days of quarters of course).
A:
I would sort all the events for a particular employee in time order and simulate the events in that order checking that the available days of paid time off never falls below zero. A paid time off request is an event with a value -(number of hours). Jan 1st has an event with value +8 hours.
Every time a modification is made to the data, run the simulation again from the start.
The advantage of this method is that it will detect situations in which a new event is valid at that time but causes the number of free days to drop such that a later event which previously was valid now becomes invalid.
This could be optimized by storing intermediate results in a cache but since you will likely only have a few hundred events per employee this optimization probably won't be necessary.
A:
This can be done with plain old integer math:
from datetime import date
def hours_accrued(start, end):
'''hours_accrued(date, date) -> int
Answers the question "How many hours of Paid Time Off
are accrued from X-date to Y-date?"
>>> hours_accrued(date(2010, 4, 20), date(2012, 12, 21))
80
>>> hours_accrued(date(2010, 12, 21), date(2012, 4, 20))
48
'''
return ( 4*(end.year - start.year)
+ ((end.month-1)/3 - (start.month-1)/3) ) * 8
A:
I would count all free days before the date in question, then subtract the number of used days before then in order to come to a value for the maximum number of allowable days.
A:
Set up a tuple for each date range (we'll call them quarters). In the tuple store the quarter (as a cardinal index, or as a begin date), the maximum accrued hours for a quarter, and the number of used hours in a quarter. You'll want to have a set of tuples that are sorted for this to work, so a plain list probably isn't your best option. A dictionary might be a better way to approach this, with the quarter as the key and the max/used entries returned in the tuple, as it can be "sorted".
(Note: I looked at the original explanation and rewrote my answer)
Get a copy of the set of all quarters for a given employee, sorted by the quarter's date. Iterate over each quarter summing the difference between the maximum per-quarter allotment of vacation time and the time "spent" on that quarter until you reach the quarter that the request date falls into. This gives accumulated time.
If accumulated time plus the time alloted for the requested quarter is not as much as the requested hours, fail immediately and reject the request. Otherwise, continue iterating up to the quarter of your quest.
If there is sufficient accumulated time, continue iterating over the copied set, computing the new available times on a per-quarter basis, starting with the left-over time from your initial calculation.
If any quarter has a computed time falling below zero, fail immediately and reject the request. Otherwise, continue until you run out of quarters.
If all quarters are computed, update the original set of data with the copy and grant the request.
| "Passing Go" in a (python) date range | Updated to remove extraneous text and ambiguity.
The Rules:
An employee accrues 8 hours of Paid Time Off on the day after each quarter. Quarters, specifically being:
Jan 1 - Mar 31
Apr 1 - Jun 30
Jul 1 - Sep 30
Oct 1 - Dec 31
The Problem
Using python, I need to define the guts of the following function:
def acrued_hours_between(start_date, end_date):
# stuff
return integer
I'm currently using Python, and wondering what the correct approach to something like this would be.
I'm assuming that using DateTime objects, and possibly the dateutil module, would help here, but my brain isn't wrapping around this problem for some reason.
Update
I imagine the calculation being somewhat simple, as the problem is:
"How many hours of Paid Time Off are accrued from start_date to end_date?" given the above "rules".
| [
"The OP's edit mentions the real underlying problem is:\n\n\"How many hours of Paid Time Off are\n accrued from X-date to Y-date?\"\n\nI agree, and I'd compute that in the most direct and straightforward way, e.g.:\nimport datetime\nimport itertools\n\naccrual_months_days = (1,1), (4,1), (7,1), (10,1)\n\ndef accruals(begin_date, end_date, hours_per=8):\n \"\"\"Vacation accrued between begin_date and end_date included.\"\"\"\n cur_year = begin_date.year - 1\n result = 0\n for m, d in itertools.cycle(accrual_months_days):\n if m == 1: cur_year += 1\n d = datetime.date(cur_year, m, d)\n if d < begin_date: continue\n if d > end_date: return result\n result += hours_per\n\nif __name__ == '__main__': # examples\n print accruals(datetime.date(2010, 1, 12), datetime.date(2010, 9, 20))\n print accruals(datetime.date(2010, 4, 20), datetime.date(2012, 12, 21))\n print accruals(datetime.date(2010, 12, 21), datetime.date(2012, 4, 20))\n\nA direct formula would of course be faster, but could be tricky to do it without bugs -- if nothing else, this \"correct by inspection\" example can serve to calibrate the faster one automatically, by checking that they agree over a large sample of date pairs (be sure to include in the latter all corner cases such as first and last days of quarters of course).\n",
"I would sort all the events for a particular employee in time order and simulate the events in that order checking that the available days of paid time off never falls below zero. A paid time off request is an event with a value -(number of hours). Jan 1st has an event with value +8 hours.\nEvery time a modification is made to the data, run the simulation again from the start.\nThe advantage of this method is that it will detect situations in which a new event is valid at that time but causes the number of free days to drop such that a later event which previously was valid now becomes invalid.\nThis could be optimized by storing intermediate results in a cache but since you will likely only have a few hundred events per employee this optimization probably won't be necessary.\n",
"This can be done with plain old integer math:\nfrom datetime import date\n\ndef hours_accrued(start, end):\n '''hours_accrued(date, date) -> int\n\n Answers the question \"How many hours of Paid Time Off\n are accrued from X-date to Y-date?\"\n\n >>> hours_accrued(date(2010, 4, 20), date(2012, 12, 21))\n 80\n >>> hours_accrued(date(2010, 12, 21), date(2012, 4, 20))\n 48\n '''\n return ( 4*(end.year - start.year)\n + ((end.month-1)/3 - (start.month-1)/3) ) * 8\n\n",
"I would count all free days before the date in question, then subtract the number of used days before then in order to come to a value for the maximum number of allowable days.\n",
"Set up a tuple for each date range (we'll call them quarters). In the tuple store the quarter (as a cardinal index, or as a begin date), the maximum accrued hours for a quarter, and the number of used hours in a quarter. You'll want to have a set of tuples that are sorted for this to work, so a plain list probably isn't your best option. A dictionary might be a better way to approach this, with the quarter as the key and the max/used entries returned in the tuple, as it can be \"sorted\".\n(Note: I looked at the original explanation and rewrote my answer)\nGet a copy of the set of all quarters for a given employee, sorted by the quarter's date. Iterate over each quarter summing the difference between the maximum per-quarter allotment of vacation time and the time \"spent\" on that quarter until you reach the quarter that the request date falls into. This gives accumulated time.\nIf accumulated time plus the time alloted for the requested quarter is not as much as the requested hours, fail immediately and reject the request. Otherwise, continue iterating up to the quarter of your quest.\nIf there is sufficient accumulated time, continue iterating over the copied set, computing the new available times on a per-quarter basis, starting with the left-over time from your initial calculation.\nIf any quarter has a computed time falling below zero, fail immediately and reject the request. Otherwise, continue until you run out of quarters.\nIf all quarters are computed, update the original set of data with the copy and grant the request.\n"
] | [
5,
1,
1,
0,
0
] | [] | [] | [
"calendar",
"date",
"datetime",
"python",
"python_dateutil"
] | stackoverflow_0003041167_calendar_date_datetime_python_python_dateutil.txt |
Q:
Best practice- How to team-split a django project while still allowing code reusal
I know this sounds kind of vague, but please let me explain-
I'm starting work on a brand new project, it will have two main components: "ACME PRODUCT" (think Gmail, Meebo, etc), and "THE SITE" (help, information, marketing stuff, promotional landing pages, etc lots of marketing-induced cruft).
So basically the url /acme/* will load stuff in the uber cool ajaxy application, and every other URI will load stuff in the other site.
Problem: "THE SITE" component is out of my hands, and will be handled by a consultants team that will work closely with marketing, And I and my team will work solely on the ACME PRODUCT.
Question: How to set up the django project in such a way that we can have:
Seperate releases. (They can push new marketing pages and functionality without having to worry about the state of our code. Maybe even separate Subversion "projects")
Minimize impact (on our product) of whatever flying-unicorns-hocus-pocus the other team codes into the site.
Still allow some code reusal.
My main concern is that the ACME product needs to be rock solid, and therefore needs to be somewhat isolated of whatever mistakes/code bloopers the consultants make in their marketing side of the site.
How have you handled this? Any ideas?
Thanks!
A:
Django's componentization of apps means that you can have independent teams working on the various apps, with template tags and filters (and of course, normal Python functions) used for cross-app coupling.
A:
I doubt the amount of code reuse you can get between the two projects, given your organizational situation, is worth the headaches, organizational risks, and delay risks that it would entail -- after all your team can never rely on the other, since
the ACME product needs to be rock
solid, and therefore needs to be
somewhat isolated of whatever
mistakes/code bloopers the consultants
make in their marketing side of the
site.
This being the case, I would, at most, have the ACME team sometimes release a few little underlying libraries for the other team's use... but even that is fraught, unless used with wildly severe constraints, since one of the bloopers the consultants may make is to code with dependencies on the library's implementation, so ACME basically cannot keep maintaining the library after releasing it for the consultants' use (ACME might think that keeping APIs constraints would be fine, but they can't deal with the other team's reuse-bloopers).
Although one would need to know many specific details, it doesn't appear that the deep underlying commonality between the two teams' projects, at application layer, is all that much anyway (third party stable open-source projects providing common application-independent functionality can of course be used by either or both teams), so the costs of encouraging reuse would not correspond to commensurate returns anyway, from what we can judge looking from "out here".
| Best practice- How to team-split a django project while still allowing code reusal | I know this sounds kind of vague, but please let me explain-
I'm starting work on a brand new project, it will have two main components: "ACME PRODUCT" (think Gmail, Meebo, etc), and "THE SITE" (help, information, marketing stuff, promotional landing pages, etc lots of marketing-induced cruft).
So basically the url /acme/* will load stuff in the uber cool ajaxy application, and every other URI will load stuff in the other site.
Problem: "THE SITE" component is out of my hands, and will be handled by a consultants team that will work closely with marketing, And I and my team will work solely on the ACME PRODUCT.
Question: How to set up the django project in such a way that we can have:
Seperate releases. (They can push new marketing pages and functionality without having to worry about the state of our code. Maybe even separate Subversion "projects")
Minimize impact (on our product) of whatever flying-unicorns-hocus-pocus the other team codes into the site.
Still allow some code reusal.
My main concern is that the ACME product needs to be rock solid, and therefore needs to be somewhat isolated of whatever mistakes/code bloopers the consultants make in their marketing side of the site.
How have you handled this? Any ideas?
Thanks!
| [
"Django's componentization of apps means that you can have independent teams working on the various apps, with template tags and filters (and of course, normal Python functions) used for cross-app coupling.\n",
"I doubt the amount of code reuse you can get between the two projects, given your organizational situation, is worth the headaches, organizational risks, and delay risks that it would entail -- after all your team can never rely on the other, since\n\nthe ACME product needs to be rock\n solid, and therefore needs to be\n somewhat isolated of whatever\n mistakes/code bloopers the consultants\n make in their marketing side of the\n site.\n\nThis being the case, I would, at most, have the ACME team sometimes release a few little underlying libraries for the other team's use... but even that is fraught, unless used with wildly severe constraints, since one of the bloopers the consultants may make is to code with dependencies on the library's implementation, so ACME basically cannot keep maintaining the library after releasing it for the consultants' use (ACME might think that keeping APIs constraints would be fine, but they can't deal with the other team's reuse-bloopers).\nAlthough one would need to know many specific details, it doesn't appear that the deep underlying commonality between the two teams' projects, at application layer, is all that much anyway (third party stable open-source projects providing common application-independent functionality can of course be used by either or both teams), so the costs of encouraging reuse would not correspond to commensurate returns anyway, from what we can judge looking from \"out here\".\n"
] | [
3,
2
] | [] | [] | [
"deployment",
"django",
"python"
] | stackoverflow_0003041077_deployment_django_python.txt |
Q:
Does OOP make sense for small scripts?
I mostly write small scripts in python, about 50 - 250 lines of code. I usually don't use any objects, just straightforward procedural programming.
I know OOP basics and I have used object in other programming languages before, but for small scripts I don't see how objects would improve them. But maybe that is just my limited experience with OOP.
Am I missing something by not trying harder to use objects, or does OOP just not make a lot of sense for small scripts?
A:
I use whatever paradigm best suits the issue at hand -- be it procedural, OOP, functional, ... program size is not a criterion, though (by a little margin) a larger program may be more likely to take advantage of OOP's strengths -- multiple instances of a class, subclassing and overriding, special method overloads, OOP design patterns, etc. Any of these opportunities can perfectly well occur in a small script, there's just a somewhat higher probability that it will occur in a larger one.
In addition, I detest the global statement, so if the natural procedural approach would require it, I will almost invariably switch to OOP instead -- even if the only advantage is the ability to use a qualified name instead of the barename which would require global.
There's definitely no need to "try harder" in general -- just ask yourself "is there an opportunity here to use (a) multiple instances (etc etc)" and it will soon become second nature, i.e., you'll spot the opportunities without needing to consciously remind yourself every time to look for them, and your programming will improve as a result.
A:
Object-Oriented Programming, while useful for representing systems as real-world objects (and hopefully making large software system easier to understand) is not the silver bullet to every solution (despite what some people teach).
If your system does not benefit from what OOP provides (things such as data abstraction, encapsulation, modularity, polymorphism, and inheritance), then it would not make sense to incur all the overhead of doing OOP. However, if you find that as your system grows these things become a bigger concern to you, then you may want to consider moving to an OOP solution.
Edit: As an update, you may want to head over to Wikipedia to read the articles on various criticisms of OOP. Remember that OOP is a tool, and just like you wouldn't use a hammer for everything, OOP should not be used for everything. Consider the best tool for the job.
A:
One of the unfortunate habits developed with oop is Objectophrenia - the delusion of seeing objects in every piece of code we write.
The reason why that happens is due our delusion of believing in the existence of a unified objects theorem.
Every piece of code you write, you begin to see it as a template for objects and how they fit into our personal scheme of things. Even though it might be a small task at hand, we get tempted by the question - is this something I could place into my class repository which I could also use for the future? Do I see a pattern here with code I have previously written and with code which my object clairvoyance tells me that I will one day write? Can I structure my present task into one of these patterns.
It is an annoying habit. Frequently, it is better not to have it. But when you find that every bit of code you write somehow falls into patterns and you refactor/realign those patterns until it covers most of your needs, you tend to get a feeling of satisfaction and accomplishment.
Problems begins to appear when a programmer gets delusional (compulsive obsessive object oriented disorder) and does not realise that there are exceptions to patterns and trying to over-manipulate patterns to cover more cases is wrong. It's like my childhood obsession with trying to cover a piece of bread completely with butter or jam spread every morning I had breakfast. That sometimes, it is just better to leave the object oriented perception behind and just perform the task at hand quick and dirty.
The accepted industrial adage of 80-20 might be a good measure. Using this adage in a different manner than it is normally perceived, we could say 80% of the time have an object oriented perception. 20% of the time - code it quick and dirty.
Be immersed by objects but eventually you have to resist its consuming you.
You probably have not done enough programming yet because if you have, you would see all the patterns that you had done and you will also begin to believe in patterns that you have yet to apply. When you begin to see such objectophrenia visions, it's time to be careful not to be consumed by them.
A:
If you plan to use the script independently, then no. However if you plan to import it and reuse some of it, then yes. In the second case, it's best to write some classes providing the functionality that's required and then have a conditional run (if __name__=='__main__':) with code to execute the "script" version of the script.
A:
My experience is that any purely procedural script longer than a few dozen lines becomes difficult to maintain. For one thing, if I'm setting or modifying a variable in one place and using it in another place, and those two places can't fit on a single screen, trouble will follow.
The answer, of course, is to tighten the scope and make the different parts of your application more encapsulated. OOP is one way to do that, and can be a useful way to model your environment. I like OOP, as I find I can mentally jump from thinking about how the inside of a particular object will work, to thinking about how the objects will work together, and I stay saner.
However, OOP is certainly not the only way to make your code better encapsulated; another approach would be a set of small, well-named functions with carefully defined inputs and outputs, and a master script that calls those functions as appropriate.
A:
OOP is a tool to manage complexity in code, 50-250 lines of code are rarely complicated. Most scripts I have written are primarily procedural. So yes, for small scripts just go with procedural programming.
Note that for significantly complicated scripts OOP may be more relevant, but there is still not hard and fast rule that says use OOP for them. It is a matter of personal preference then.
A:
Use the right tool for the right job. For small scripts that don't require complex data structures and algorithms, there is likely no use for object oriented concepts.
A:
Am I missing something by not trying harder to use objects, or does OOP just not make a lot of sense for small scripts?
Objects buy you encapsulation and reuse (through inheritance). Neither is likely to be terribly useful when writing small scripts. When you have written a collection of similar scripts or you find yourself repeatedly changing your scripts, then maybe you should consider where objects might help.
A:
In your case I'd say that OOP would be helpful only if it makes the scripts more readable and understandable. If not, you probably don't need to bother.
A:
OOP is just another paradigm. A lot of problems can be solved using both procedural or OOP.
I use OOP when I see clear need of inheritance in the code i am writing, its easier to manage common behaviour and common attributes.
It sometimes makes it easy to understand, and manage. Even if the code is small.
A:
Another benefit of OOP is to communicate intent (whether to other developers, managers, or yourself some point in the future). If the script is small enough where it can be fully communicated in a couple of sentences then OOP is probably not necessary, in my opinion.
A:
Using OOP for few hundred lines of code rarely makes sense. But if your script is useful, it will probably grow rather quickly because new features will be added. If this is the case, it is better to start coding OOP way it will pay in the long run.
A:
First of all - what do you mean by objects? In Python functions are objects and you're most likely using them. :)
If by objects you mean classes and instances thereof, then I would say something obvious: no, there is no reason to saying that using them is making your code better by itself. In small scripts there is not going to be any leverage coming from sophisticated OO design.
A:
OOP is about what you get if you add polymorphism on top of modular programming.
The latter of both promotes low coupling, encapsulation, separation of responsibility and some other concepts, that usually produce code, that is short, expressive, maintainable, flexible, extensible, reusable and robust.
This is not so much a question about size, but about length of the software's life cycle. If you write any code, as short as it may be, as long as it is complex enough that you don't want to rewrite it, when your requirements change, it is important that it meets the aforementioned criteria.
OOP makes modular programming easier in that it has established solutions for implementing the concepts promoted by modular programming, and that polymorphism allows really low coupling through dependency injection.
I personally find it simpler to use OOP to achieve modularity (and reusability in particular), but I guess, that is a matter of habit.
To put it in one sentence. OOP will not help you in solving a given problem better, than procedural programming, but instead yields a solution, that is easier to apply to other problems.
A:
It really depends on what the script is an what it's doing and how you think about the world.
Personally after a script has made it past 20-30 lines of code I can usually find a way that OOP makes more sense to me (especially in Python).
For instance, say I'm writing a script that parses a log file. Well, conceptually I can imagine this "log parser" machine... I can throw all these sheets of paper into it and it will sort them, chop parts out of some pages and paste them onto another and eventually hand me a nice report.
So then I start thinking, well, what does this parser do? Well, first off he's (yes, the parser is a he. I don't know how many of my programs are women, but this one is definitely a guy) going to read the pages, so I'll need a method called page reader. Then he's going to find all of the data referring to the new Frobnitz process we're using. Then he's going to move all the references about the Frobnitz process to appear next to the Easter Bunny graph. Ooh, so now I need a findeasterbunny method. After he's done that, then he's going to take the rest of the logs, remove every 3rd word, and reverse the order of the text. So I'll need a thirdwordremover and a textreversal method, too. So an empty shell class would look like so:
class LogParser(Object):
def __init__(self):
#do self stuff here
def pageReader(self):
#do the reading stuff here, probably call some of the other functions
def findFrobnitz(self):
pass
def findEasterBunny(self):
pass
def thirdWordRemover(self):
pass
def textReversal(self):
pass
That's a really contrived example, and honestly probably not a situation I'd use OOP for... but it really just depends on what's easiest for me to comprehend at that particular moment in time.
A:
"Script" means "sequential" and "procedural". It's a definition.
All of the objects your script deals with are -- well -- objects. All programming involves objects. The objects already exist in the context in which you're writing your script.
Some languages allow you to clearly identify the objects. Some languages don't clearly identify the objects. The objects are always there. It's a question of whether the language makes it clear or obscure.
Since the objects are always there, I find it helps to use a language that allows clear identification of the objects, their attributes, methods and relationships. Even for short "scripts", I find that explicit objects and an OO language helps.
The point is this.
There's no useful distinction between "procedural", "script" and "OO".
It's merely a shift in emphasis. The objects are always there. The world is inherently object-oriented. The real question is "Do you use a language that makes the objects explicit?"
A:
as someone who does a lot of scripts, if you get the idea that your code may at some point go beyond 250 line start to go oop. I use a lot of vba and vbscript and I would agree that anything under 100 lines is usually pretty straightforward and taking the time to plan a good oop design is just a waste.
That being said I have one script that came to about 500 line + and looking back on it, because i didn't do it oop it quickly turned into an unholy mess of spaghetti. so now anything over 200 lines I make sure i have a good oop plan ahead of time
| Does OOP make sense for small scripts? | I mostly write small scripts in python, about 50 - 250 lines of code. I usually don't use any objects, just straightforward procedural programming.
I know OOP basics and I have used object in other programming languages before, but for small scripts I don't see how objects would improve them. But maybe that is just my limited experience with OOP.
Am I missing something by not trying harder to use objects, or does OOP just not make a lot of sense for small scripts?
| [
"I use whatever paradigm best suits the issue at hand -- be it procedural, OOP, functional, ... program size is not a criterion, though (by a little margin) a larger program may be more likely to take advantage of OOP's strengths -- multiple instances of a class, subclassing and overriding, special method overloads, OOP design patterns, etc. Any of these opportunities can perfectly well occur in a small script, there's just a somewhat higher probability that it will occur in a larger one.\nIn addition, I detest the global statement, so if the natural procedural approach would require it, I will almost invariably switch to OOP instead -- even if the only advantage is the ability to use a qualified name instead of the barename which would require global.\nThere's definitely no need to \"try harder\" in general -- just ask yourself \"is there an opportunity here to use (a) multiple instances (etc etc)\" and it will soon become second nature, i.e., you'll spot the opportunities without needing to consciously remind yourself every time to look for them, and your programming will improve as a result.\n",
"Object-Oriented Programming, while useful for representing systems as real-world objects (and hopefully making large software system easier to understand) is not the silver bullet to every solution (despite what some people teach).\nIf your system does not benefit from what OOP provides (things such as data abstraction, encapsulation, modularity, polymorphism, and inheritance), then it would not make sense to incur all the overhead of doing OOP. However, if you find that as your system grows these things become a bigger concern to you, then you may want to consider moving to an OOP solution.\nEdit: As an update, you may want to head over to Wikipedia to read the articles on various criticisms of OOP. Remember that OOP is a tool, and just like you wouldn't use a hammer for everything, OOP should not be used for everything. Consider the best tool for the job.\n",
"One of the unfortunate habits developed with oop is Objectophrenia - the delusion of seeing objects in every piece of code we write.\nThe reason why that happens is due our delusion of believing in the existence of a unified objects theorem.\nEvery piece of code you write, you begin to see it as a template for objects and how they fit into our personal scheme of things. Even though it might be a small task at hand, we get tempted by the question - is this something I could place into my class repository which I could also use for the future? Do I see a pattern here with code I have previously written and with code which my object clairvoyance tells me that I will one day write? Can I structure my present task into one of these patterns.\nIt is an annoying habit. Frequently, it is better not to have it. But when you find that every bit of code you write somehow falls into patterns and you refactor/realign those patterns until it covers most of your needs, you tend to get a feeling of satisfaction and accomplishment.\nProblems begins to appear when a programmer gets delusional (compulsive obsessive object oriented disorder) and does not realise that there are exceptions to patterns and trying to over-manipulate patterns to cover more cases is wrong. It's like my childhood obsession with trying to cover a piece of bread completely with butter or jam spread every morning I had breakfast. That sometimes, it is just better to leave the object oriented perception behind and just perform the task at hand quick and dirty.\nThe accepted industrial adage of 80-20 might be a good measure. Using this adage in a different manner than it is normally perceived, we could say 80% of the time have an object oriented perception. 20% of the time - code it quick and dirty.\nBe immersed by objects but eventually you have to resist its consuming you.\nYou probably have not done enough programming yet because if you have, you would see all the patterns that you had done and you will also begin to believe in patterns that you have yet to apply. When you begin to see such objectophrenia visions, it's time to be careful not to be consumed by them.\n",
"If you plan to use the script independently, then no. However if you plan to import it and reuse some of it, then yes. In the second case, it's best to write some classes providing the functionality that's required and then have a conditional run (if __name__=='__main__':) with code to execute the \"script\" version of the script.\n",
"My experience is that any purely procedural script longer than a few dozen lines becomes difficult to maintain. For one thing, if I'm setting or modifying a variable in one place and using it in another place, and those two places can't fit on a single screen, trouble will follow.\nThe answer, of course, is to tighten the scope and make the different parts of your application more encapsulated. OOP is one way to do that, and can be a useful way to model your environment. I like OOP, as I find I can mentally jump from thinking about how the inside of a particular object will work, to thinking about how the objects will work together, and I stay saner.\nHowever, OOP is certainly not the only way to make your code better encapsulated; another approach would be a set of small, well-named functions with carefully defined inputs and outputs, and a master script that calls those functions as appropriate.\n",
"OOP is a tool to manage complexity in code, 50-250 lines of code are rarely complicated. Most scripts I have written are primarily procedural. So yes, for small scripts just go with procedural programming.\nNote that for significantly complicated scripts OOP may be more relevant, but there is still not hard and fast rule that says use OOP for them. It is a matter of personal preference then.\n",
"Use the right tool for the right job. For small scripts that don't require complex data structures and algorithms, there is likely no use for object oriented concepts.\n",
"\nAm I missing something by not trying harder to use objects, or does OOP just not make a lot of sense for small scripts?\n\nObjects buy you encapsulation and reuse (through inheritance). Neither is likely to be terribly useful when writing small scripts. When you have written a collection of similar scripts or you find yourself repeatedly changing your scripts, then maybe you should consider where objects might help.\n",
"In your case I'd say that OOP would be helpful only if it makes the scripts more readable and understandable. If not, you probably don't need to bother.\n",
"OOP is just another paradigm. A lot of problems can be solved using both procedural or OOP. \nI use OOP when I see clear need of inheritance in the code i am writing, its easier to manage common behaviour and common attributes. \nIt sometimes makes it easy to understand, and manage. Even if the code is small. \n",
"Another benefit of OOP is to communicate intent (whether to other developers, managers, or yourself some point in the future). If the script is small enough where it can be fully communicated in a couple of sentences then OOP is probably not necessary, in my opinion.\n",
"Using OOP for few hundred lines of code rarely makes sense. But if your script is useful, it will probably grow rather quickly because new features will be added. If this is the case, it is better to start coding OOP way it will pay in the long run.\n",
"First of all - what do you mean by objects? In Python functions are objects and you're most likely using them. :)\nIf by objects you mean classes and instances thereof, then I would say something obvious: no, there is no reason to saying that using them is making your code better by itself. In small scripts there is not going to be any leverage coming from sophisticated OO design.\n",
"OOP is about what you get if you add polymorphism on top of modular programming.\nThe latter of both promotes low coupling, encapsulation, separation of responsibility and some other concepts, that usually produce code, that is short, expressive, maintainable, flexible, extensible, reusable and robust.\nThis is not so much a question about size, but about length of the software's life cycle. If you write any code, as short as it may be, as long as it is complex enough that you don't want to rewrite it, when your requirements change, it is important that it meets the aforementioned criteria.\nOOP makes modular programming easier in that it has established solutions for implementing the concepts promoted by modular programming, and that polymorphism allows really low coupling through dependency injection.\nI personally find it simpler to use OOP to achieve modularity (and reusability in particular), but I guess, that is a matter of habit.\nTo put it in one sentence. OOP will not help you in solving a given problem better, than procedural programming, but instead yields a solution, that is easier to apply to other problems.\n",
"It really depends on what the script is an what it's doing and how you think about the world.\nPersonally after a script has made it past 20-30 lines of code I can usually find a way that OOP makes more sense to me (especially in Python).\nFor instance, say I'm writing a script that parses a log file. Well, conceptually I can imagine this \"log parser\" machine... I can throw all these sheets of paper into it and it will sort them, chop parts out of some pages and paste them onto another and eventually hand me a nice report.\nSo then I start thinking, well, what does this parser do? Well, first off he's (yes, the parser is a he. I don't know how many of my programs are women, but this one is definitely a guy) going to read the pages, so I'll need a method called page reader. Then he's going to find all of the data referring to the new Frobnitz process we're using. Then he's going to move all the references about the Frobnitz process to appear next to the Easter Bunny graph. Ooh, so now I need a findeasterbunny method. After he's done that, then he's going to take the rest of the logs, remove every 3rd word, and reverse the order of the text. So I'll need a thirdwordremover and a textreversal method, too. So an empty shell class would look like so:\nclass LogParser(Object):\n def __init__(self):\n #do self stuff here\n def pageReader(self):\n #do the reading stuff here, probably call some of the other functions\n def findFrobnitz(self):\n pass\n def findEasterBunny(self):\n pass\n def thirdWordRemover(self):\n pass\n def textReversal(self):\n pass\n\nThat's a really contrived example, and honestly probably not a situation I'd use OOP for... but it really just depends on what's easiest for me to comprehend at that particular moment in time.\n",
"\"Script\" means \"sequential\" and \"procedural\". It's a definition. \nAll of the objects your script deals with are -- well -- objects. All programming involves objects. The objects already exist in the context in which you're writing your script.\nSome languages allow you to clearly identify the objects. Some languages don't clearly identify the objects. The objects are always there. It's a question of whether the language makes it clear or obscure.\nSince the objects are always there, I find it helps to use a language that allows clear identification of the objects, their attributes, methods and relationships. Even for short \"scripts\", I find that explicit objects and an OO language helps.\nThe point is this.\nThere's no useful distinction between \"procedural\", \"script\" and \"OO\". \nIt's merely a shift in emphasis. The objects are always there. The world is inherently object-oriented. The real question is \"Do you use a language that makes the objects explicit?\"\n",
"as someone who does a lot of scripts, if you get the idea that your code may at some point go beyond 250 line start to go oop. I use a lot of vba and vbscript and I would agree that anything under 100 lines is usually pretty straightforward and taking the time to plan a good oop design is just a waste.\n\nThat being said I have one script that came to about 500 line + and looking back on it, because i didn't do it oop it quickly turned into an unholy mess of spaghetti. so now anything over 200 lines I make sure i have a good oop plan ahead of time\n"
] | [
33,
27,
9,
8,
6,
4,
4,
4,
2,
2,
2,
2,
1,
1,
1,
0,
0
] | [] | [] | [
"oop",
"python",
"scripting"
] | stackoverflow_0003039889_oop_python_scripting.txt |
Q:
In python, is there a simple way to connect to a mysql database that doesn't require root access?
I'm writing a script to parse some text files, and insert the data that they contain into a mysql database. I don't have root access on the server that this script will run on. I've been looking at mysql-python, but it requires a bunch of dependencies that I don't have available. Is there a simpler way to do this?
A:
I would recommend the MySQL Python Connector, a MySQL DB-API adapter that does not use the C client library but rather reimplements the MySQL protocol completely in pure Python (compatible with Python 2.5 to 2.7, as well a 3.1).
To install C-coded extensions to Python you generally need root access (though the server you're using might have arranged things differently, that's not all that likely). But with a pure Python solution you can simply upload the modules in question (e.g. those from the Connector I recommend) just as you're uploading those you write yourself, which (if you of course do have a valid userid and password for that MySQL database!-) might solve it for you.
| In python, is there a simple way to connect to a mysql database that doesn't require root access? | I'm writing a script to parse some text files, and insert the data that they contain into a mysql database. I don't have root access on the server that this script will run on. I've been looking at mysql-python, but it requires a bunch of dependencies that I don't have available. Is there a simpler way to do this?
| [
"I would recommend the MySQL Python Connector, a MySQL DB-API adapter that does not use the C client library but rather reimplements the MySQL protocol completely in pure Python (compatible with Python 2.5 to 2.7, as well a 3.1).\nTo install C-coded extensions to Python you generally need root access (though the server you're using might have arranged things differently, that's not all that likely). But with a pure Python solution you can simply upload the modules in question (e.g. those from the Connector I recommend) just as you're uploading those you write yourself, which (if you of course do have a valid userid and password for that MySQL database!-) might solve it for you.\n"
] | [
3
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003042051_mysql_python.txt |
Q:
I keep Getting KeyError: 'tried' Whenever I Tried to Run Django Dev Server from Remote Machine
I am running django 1.1.1 on python2.6.1, and did start the django web server like this
manage.py runserver 192.0.0.1:8000
then tried to connect to the django dev web server on http://192.0.0.1:8000/
keep getting this message on the remote computer
Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\django\core\servers\basehttp.py", line 279, in run
self.result = application(self.environ, self.start_response)
File "C:\Python26\Lib\site-packages\django\core\servers\basehttp.py", line 651, in __call__
return self.application(environ, start_response)
File "C:\Python26\lib\site-packages\django\core\handlers\wsgi.py", line 241, in __call__
response = self.get_response(request)
File "C:\Python26\lib\site-packages\django\core\handlers\base.py", line 115, in get_response
return debug.technical_404_response(request, e)
File "C:\Python26\Lib\site-packages\django\views\debug.py", line 247, in technical_404_response
tried = exception.args[0]['tried']
KeyError: 'tried'
what i am doing wrong ?
it seen to work ok if i run http://192.0.0.1:8000/ on the computer that runs the Django web server and have that ip 192.0.0.1:8000
A:
If you look at the revision logs of that file you'll see that django has recently started catching the KeyError that is raised in that try block.
The log message reads "Ensured generating debug 404 page won't raise a key error. Thanks pigletto."
See the ticket http://code.djangoproject.com/ticket/12083 and the changeset http://code.djangoproject.com/changeset/12679
So, I would check if you're raising a debug 404 page, or if any of the other comments in the ticket jump out of you.
Hope that helps!
Update: After looking at the code a little bit closer, I'd take a good look at your urls.py file for any mistakes in the url resolving regex. Are you doing url('') instead of ('^$') for the root/homepage?
| I keep Getting KeyError: 'tried' Whenever I Tried to Run Django Dev Server from Remote Machine | I am running django 1.1.1 on python2.6.1, and did start the django web server like this
manage.py runserver 192.0.0.1:8000
then tried to connect to the django dev web server on http://192.0.0.1:8000/
keep getting this message on the remote computer
Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\django\core\servers\basehttp.py", line 279, in run
self.result = application(self.environ, self.start_response)
File "C:\Python26\Lib\site-packages\django\core\servers\basehttp.py", line 651, in __call__
return self.application(environ, start_response)
File "C:\Python26\lib\site-packages\django\core\handlers\wsgi.py", line 241, in __call__
response = self.get_response(request)
File "C:\Python26\lib\site-packages\django\core\handlers\base.py", line 115, in get_response
return debug.technical_404_response(request, e)
File "C:\Python26\Lib\site-packages\django\views\debug.py", line 247, in technical_404_response
tried = exception.args[0]['tried']
KeyError: 'tried'
what i am doing wrong ?
it seen to work ok if i run http://192.0.0.1:8000/ on the computer that runs the Django web server and have that ip 192.0.0.1:8000
| [
"If you look at the revision logs of that file you'll see that django has recently started catching the KeyError that is raised in that try block. \nThe log message reads \"Ensured generating debug 404 page won't raise a key error. Thanks pigletto.\"\nSee the ticket http://code.djangoproject.com/ticket/12083 and the changeset http://code.djangoproject.com/changeset/12679\nSo, I would check if you're raising a debug 404 page, or if any of the other comments in the ticket jump out of you.\nHope that helps!\nUpdate: After looking at the code a little bit closer, I'd take a good look at your urls.py file for any mistakes in the url resolving regex. Are you doing url('') instead of ('^$') for the root/homepage?\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003041973_django_python.txt |
Q:
converting hexadecimal , octal numbers into decimal form using python script
There are many inbulit functions like int(octal) which can be used to convert octal numbers into decimal numbers on command line but these doesn't work out in script .
int(0671) returns 0671 in script, where as it represent decimal form of octal number on python command line.
Help???
Thank You
A:
There's some confusion here -- pedantically (and with computers it's always best to be pedantic;-), there are no "octal numbers", there are strings which are octal representations of numbers (and other strings, more commonly encountered, which are their decimal representations, hexadecimal representations). The underlying numbers (integers) are a totally distinct type from any of the representations (by default their decimal representation is shown) -- e.g.:
>>> 2 + 2
4
>>> '2' + '2'
'22'
the quotes indicate strings (i.e., representations) -- and note that, per se, they have nothing to do with the numbers they may be representing.
So, one way to interpret your question is that you want to convert an octal representation into a decimal one (etc) -- that would be:
>>> str(int('0671', 8))
'441'
note the quoted (indicating strings, i.e., representations). int(s, 8) converts the string s into an integer as an octal representation (or raises an exception if the conversion can't work). str(n) produces the string form of number n (which, as I mentioned, is by default a decimal representation).
A:
First, the int() is useless. You can just type 0671.
Then, the number is stored in binary on the computer itself, you are only converting its string representation. The number itself doesn't change. Therefore, both of these will resolve to True, for example, which might've been the source of confusion:
0671 == 0671
0671 == 441
To ensure you will get the program to output the number in the base you want, the simplest way is to use string formatting, like so (if you want it to be in base 10):
print "%d" % 0671 # will output the number in base 10
| converting hexadecimal , octal numbers into decimal form using python script | There are many inbulit functions like int(octal) which can be used to convert octal numbers into decimal numbers on command line but these doesn't work out in script .
int(0671) returns 0671 in script, where as it represent decimal form of octal number on python command line.
Help???
Thank You
| [
"There's some confusion here -- pedantically (and with computers it's always best to be pedantic;-), there are no \"octal numbers\", there are strings which are octal representations of numbers (and other strings, more commonly encountered, which are their decimal representations, hexadecimal representations). The underlying numbers (integers) are a totally distinct type from any of the representations (by default their decimal representation is shown) -- e.g.:\n>>> 2 + 2\n4\n>>> '2' + '2'\n'22'\n\nthe quotes indicate strings (i.e., representations) -- and note that, per se, they have nothing to do with the numbers they may be representing.\nSo, one way to interpret your question is that you want to convert an octal representation into a decimal one (etc) -- that would be:\n>>> str(int('0671', 8))\n'441'\n\nnote the quoted (indicating strings, i.e., representations). int(s, 8) converts the string s into an integer as an octal representation (or raises an exception if the conversion can't work). str(n) produces the string form of number n (which, as I mentioned, is by default a decimal representation).\n",
"First, the int() is useless. You can just type 0671.\nThen, the number is stored in binary on the computer itself, you are only converting its string representation. The number itself doesn't change. Therefore, both of these will resolve to True, for example, which might've been the source of confusion:\n0671 == 0671\n0671 == 441\n\nTo ensure you will get the program to output the number in the base you want, the simplest way is to use string formatting, like so (if you want it to be in base 10):\nprint \"%d\" % 0671 # will output the number in base 10\n\n"
] | [
12,
2
] | [] | [] | [
"hex",
"octal",
"python"
] | stackoverflow_0003042135_hex_octal_python.txt |
Q:
Easy_install of wxpython has "setup script" error
I have an install of python 2.5 that fink placed in /sw/bin/. I use the easy install command
sudo /sw/bin/easy_install wxPython
to try to install wxpython and I get an error while trying to process wxPython-src-2.8.9.1.tab.bz2 that there is not setup script. Easy-install has worked for several other installations until this one. Any help on why it's busting now?
EDIT: The error occurs before dumping back to shell prompt.
Reading http://wxPython.org/download.php
Best match: wxPython src-2.8.9.1
Downloading http://downloads.sourceforge.net/wxpython/wxPython-src-2.8.9.1.tar.bz2
Processing wxPython-src-2.8.9.1.tar.bz2
error: Couldn't find a setup script in /tmp/easy_install-tNg6FG/wxPython-src-2.8.9.1.tar.bz2
A:
There is a simple reason why it's busting: there just is no setup.py in wxPython; wxPython does not use distutils for installation.
Instead, read the file README.1st.txt in source distribution for instruction on how to install wxPython.
A:
wxPython 2.8.9.1 does use distutils
Under 'wxPython-src-2.8.9.1/wxPython/' run:
sudo python setup.py install
To install wxPython. At least that's what the INSTALL.txt says for that specific version.
| Easy_install of wxpython has "setup script" error | I have an install of python 2.5 that fink placed in /sw/bin/. I use the easy install command
sudo /sw/bin/easy_install wxPython
to try to install wxpython and I get an error while trying to process wxPython-src-2.8.9.1.tab.bz2 that there is not setup script. Easy-install has worked for several other installations until this one. Any help on why it's busting now?
EDIT: The error occurs before dumping back to shell prompt.
Reading http://wxPython.org/download.php
Best match: wxPython src-2.8.9.1
Downloading http://downloads.sourceforge.net/wxpython/wxPython-src-2.8.9.1.tar.bz2
Processing wxPython-src-2.8.9.1.tar.bz2
error: Couldn't find a setup script in /tmp/easy_install-tNg6FG/wxPython-src-2.8.9.1.tar.bz2
| [
"There is a simple reason why it's busting: there just is no setup.py in wxPython; wxPython does not use distutils for installation.\nInstead, read the file README.1st.txt in source distribution for instruction on how to install wxPython.\n",
"wxPython 2.8.9.1 does use distutils\nUnder 'wxPython-src-2.8.9.1/wxPython/' run:\nsudo python setup.py install\n\nTo install wxPython. At least that's what the INSTALL.txt says for that specific version.\n"
] | [
9,
3
] | [] | [] | [
"easy_install",
"python",
"wxpython"
] | stackoverflow_0000477573_easy_install_python_wxpython.txt |
Q:
Is this __import__ functionality correct?
I have a package named jiva_tasks, which I'm trying to import via celery (using the CELERY_IMPORTS attribute of celeryconfig. The import statement that celery is using is this:
__import__(module, [], [], [''])
Oddly enough, when this syntax is used, the module gets imported twice, once as jiva_tasks and another time as jiva_tasks. (with a period at the end). Now, chances are good that celery should be passing in globals rather than an empty list, but this seems broken to me. It seems odd that even if given the wrong arguments, __import__ would import something that isn't a valid python module name.
I know that the way to fix this is to pass in globals, but I want to understand why I'm getting this result. Is this a bug, or is there something I don't understand about how __import__ is working?
Update: It also seems to be working fine if I use importlib.
Update 2: Here's the sys.meta_path and sys.import_path right before the __import__ line gets executed:
>>> sys.meta_path
[]
>>> sys.path_hooks
[<type 'zipimport.zipimporter'>]
It doesn't appear to me that there's anything out of the ordinary. However, I just now realized that the package I'm importing is installed using setuptools' develop command. Does that make a difference?
A:
Creating an empty file "foo.py" and then creating a "bar.py" that says:
__import__('foo', [], [], [''])
import sys
print sorted(sys.modules)
prints out a list that only includes foo once, and not foo. or anything else with a trailing dot — so it's not simply the fact that celery is using __import__ that is causing the problem here. Can you figure out what additional step celery is taking that adds the second module? (Or does a print sorted(sys.modules) right before and after the __import__() call suggest that both modules appear at that moment — in which case we need to look at what import hooks are defined at the moment of the import?)
| Is this __import__ functionality correct? | I have a package named jiva_tasks, which I'm trying to import via celery (using the CELERY_IMPORTS attribute of celeryconfig. The import statement that celery is using is this:
__import__(module, [], [], [''])
Oddly enough, when this syntax is used, the module gets imported twice, once as jiva_tasks and another time as jiva_tasks. (with a period at the end). Now, chances are good that celery should be passing in globals rather than an empty list, but this seems broken to me. It seems odd that even if given the wrong arguments, __import__ would import something that isn't a valid python module name.
I know that the way to fix this is to pass in globals, but I want to understand why I'm getting this result. Is this a bug, or is there something I don't understand about how __import__ is working?
Update: It also seems to be working fine if I use importlib.
Update 2: Here's the sys.meta_path and sys.import_path right before the __import__ line gets executed:
>>> sys.meta_path
[]
>>> sys.path_hooks
[<type 'zipimport.zipimporter'>]
It doesn't appear to me that there's anything out of the ordinary. However, I just now realized that the package I'm importing is installed using setuptools' develop command. Does that make a difference?
| [
"Creating an empty file \"foo.py\" and then creating a \"bar.py\" that says:\n__import__('foo', [], [], [''])\nimport sys\nprint sorted(sys.modules)\n\nprints out a list that only includes foo once, and not foo. or anything else with a trailing dot — so it's not simply the fact that celery is using __import__ that is causing the problem here. Can you figure out what additional step celery is taking that adds the second module? (Or does a print sorted(sys.modules) right before and after the __import__() call suggest that both modules appear at that moment — in which case we need to look at what import hooks are defined at the moment of the import?)\n"
] | [
1
] | [] | [] | [
"celery",
"global",
"import",
"python"
] | stackoverflow_0003017219_celery_global_import_python.txt |
Q:
"IronPython + .NET" vs "Python + PyQt". Which one is better for Windows App development?
I'm new in using Python. I would like to develop Windows GUI Application using Python. After some research, I found that I have 2 options:-
IronPython + .NET Framework
Python + PyQt
May I know which one is better for Windows Application development? Which option has more features (e.g. database support, etc)?
Other than the .NET support, is there any big difference between IronPython and Python? Which one is a better choice for me?
Thank you.
Patrick.L
A:
I faced the same issue and have, with misgivings, decided to go with IronPython/C#/.Net. I liked Qt but got cold feet when it was sold to Nokia because I just wasn't sure Nokia's goals in owning Qt were consistent with my needs for a windows UI. That said, Nokia has made some positive moves by combining separate platform licenses into a single license and dropping GPL licensing in favor or LGPL.
Technically, Qt is well designed but relies heavily on hard to debug C# macros. I'm not sure why. The best thing about Qt is that it is open source. If you need to, you can fix it. I don't have direct experience with PyQt but it has been around for quite a while.
.Net is .Net and as usual with Microsoft, a moving target. You will sacrifice speed for ease of coding. The IronPython group seems good but I'm not sure if Microsoft's commitment is there. Visual Studio support isn't there yet although the plans sound good. After all, MS only really cares if they own everything, which is not the case for Python. What I really expect is MS will create a dynamic version of C#, interpreter and all, and tell all the Python programmers that it is better and supported and well integrated with .Net. They will then through their considerable weight behind crushing Python like they've done to Java.
Good luck. It's a big decision.
A:
Per my play with both PyQt (as interface to Qt) and IronPython (as an interface to WinForms) the bag is mixed.
Both are basically "bindings" for underlying platforms. PyQt is practically "autogenerated" from Qt's API and slightly more "mature" as a wrapper because of significant use on Linux.
IronPython goes a little deeper and seems to "rebox" system objects with small unfilled gaps between cPython and .Net libs (gzip, zip, subprocess etc).
In both cases, you need to look through Python into the toolkit and say to yourself if you like the toolkit. All python is doing is repackaging the toolkit's API to the objects. Again, forget about Python aspect. Look at the underlying toolkit API and think to yourself if you can live with that.
I personally find the C++ nature of Qt's API too un-pythonic to be happy with it. C# and Python are so alike that if you remove curlies and type declaration from C# you would not know if it's C# or Python. As a result, for a Python programmer, C#-based .Net API, code and examples as provided in MSDN and elsewhere are instantly applicable with very minor tweaks.
In the end, a more correct comparison would be between PyQt (Qt bindings for cPython) and Win32py (Windows ABI bindings for cPython). IronPython is almost a reinvention of same language on a different platform, with all the problems (lacking functionality) that comes with that.
A:
First, there are lots more than 2 options (python has more GUI libraries than you can shake a stick at), but let's go on your premise for a minute. "Better" being subjective begs the question: "what do you want to learn?"
If the goal is Windows GUI Applications development, than I'd go with .Net. .Net is well respected, there is lots of work for .Net programmers, and it's windows centric nature (yeah I know there's Mono but still) means you aren't trying to think about details of three+ sets of user expectations.
If the goal is to learn widely used Python libraries and techniques, I'd go with PyQt (and recently did). It's cross-platform, well respected, and has a large community. But you lose the chance to learn the .Net platform as part of this project.
I don't think you can loose either way if your goal is to learn. If your goal is to get something done, think about the long-term plans for the project and where its going over the long run. Do you want something that's well integrated into the Windows user-interface, and uses standard widgets? Do you want something that can easily be adapted to other platforms in the future?
A:
PyQt is a great library, but .NET is the best way to go for Windows. That is because you can use any GUI controls that C# would be able to use in Python. Furthermore, in addition to WinForms, IronPython can be used to create WPF applications, which look good.
The main difference is the features, and PyQt has more cross-platform features, and .NET definitely has the edge in Windows.
A:
I haven't used IronPython with .NET, but I have written a lot of PyQt code. From my experience, PyQt is a great library. It is a very well executed bindings to Qt, which is a very well known and widely used library.
Since it's standard Python you're writing, you can enjoy all the Python standard library which gives you a ton of capabilities, in addition to several useful Qt modules imported with PyQt. Writing PyQt code is productive, and the GUIs come out pretty and responsive. And you can't ignore the portability benefit: with just the tiniest modifications, if any, you can just run these programs on Linux and they will just work.
| "IronPython + .NET" vs "Python + PyQt". Which one is better for Windows App development? | I'm new in using Python. I would like to develop Windows GUI Application using Python. After some research, I found that I have 2 options:-
IronPython + .NET Framework
Python + PyQt
May I know which one is better for Windows Application development? Which option has more features (e.g. database support, etc)?
Other than the .NET support, is there any big difference between IronPython and Python? Which one is a better choice for me?
Thank you.
Patrick.L
| [
"I faced the same issue and have, with misgivings, decided to go with IronPython/C#/.Net. I liked Qt but got cold feet when it was sold to Nokia because I just wasn't sure Nokia's goals in owning Qt were consistent with my needs for a windows UI. That said, Nokia has made some positive moves by combining separate platform licenses into a single license and dropping GPL licensing in favor or LGPL. \nTechnically, Qt is well designed but relies heavily on hard to debug C# macros. I'm not sure why. The best thing about Qt is that it is open source. If you need to, you can fix it. I don't have direct experience with PyQt but it has been around for quite a while. \n.Net is .Net and as usual with Microsoft, a moving target. You will sacrifice speed for ease of coding. The IronPython group seems good but I'm not sure if Microsoft's commitment is there. Visual Studio support isn't there yet although the plans sound good. After all, MS only really cares if they own everything, which is not the case for Python. What I really expect is MS will create a dynamic version of C#, interpreter and all, and tell all the Python programmers that it is better and supported and well integrated with .Net. They will then through their considerable weight behind crushing Python like they've done to Java. \nGood luck. It's a big decision.\n",
"Per my play with both PyQt (as interface to Qt) and IronPython (as an interface to WinForms) the bag is mixed.\nBoth are basically \"bindings\" for underlying platforms. PyQt is practically \"autogenerated\" from Qt's API and slightly more \"mature\" as a wrapper because of significant use on Linux. \nIronPython goes a little deeper and seems to \"rebox\" system objects with small unfilled gaps between cPython and .Net libs (gzip, zip, subprocess etc).\nIn both cases, you need to look through Python into the toolkit and say to yourself if you like the toolkit. All python is doing is repackaging the toolkit's API to the objects. Again, forget about Python aspect. Look at the underlying toolkit API and think to yourself if you can live with that.\nI personally find the C++ nature of Qt's API too un-pythonic to be happy with it. C# and Python are so alike that if you remove curlies and type declaration from C# you would not know if it's C# or Python. As a result, for a Python programmer, C#-based .Net API, code and examples as provided in MSDN and elsewhere are instantly applicable with very minor tweaks.\nIn the end, a more correct comparison would be between PyQt (Qt bindings for cPython) and Win32py (Windows ABI bindings for cPython). IronPython is almost a reinvention of same language on a different platform, with all the problems (lacking functionality) that comes with that.\n",
"First, there are lots more than 2 options (python has more GUI libraries than you can shake a stick at), but let's go on your premise for a minute. \"Better\" being subjective begs the question: \"what do you want to learn?\"\nIf the goal is Windows GUI Applications development, than I'd go with .Net. .Net is well respected, there is lots of work for .Net programmers, and it's windows centric nature (yeah I know there's Mono but still) means you aren't trying to think about details of three+ sets of user expectations.\nIf the goal is to learn widely used Python libraries and techniques, I'd go with PyQt (and recently did). It's cross-platform, well respected, and has a large community. But you lose the chance to learn the .Net platform as part of this project.\nI don't think you can loose either way if your goal is to learn. If your goal is to get something done, think about the long-term plans for the project and where its going over the long run. Do you want something that's well integrated into the Windows user-interface, and uses standard widgets? Do you want something that can easily be adapted to other platforms in the future?\n",
"PyQt is a great library, but .NET is the best way to go for Windows. That is because you can use any GUI controls that C# would be able to use in Python. Furthermore, in addition to WinForms, IronPython can be used to create WPF applications, which look good.\nThe main difference is the features, and PyQt has more cross-platform features, and .NET definitely has the edge in Windows.\n",
"I haven't used IronPython with .NET, but I have written a lot of PyQt code. From my experience, PyQt is a great library. It is a very well executed bindings to Qt, which is a very well known and widely used library.\nSince it's standard Python you're writing, you can enjoy all the Python standard library which gives you a ton of capabilities, in addition to several useful Qt modules imported with PyQt. Writing PyQt code is productive, and the GUIs come out pretty and responsive. And you can't ignore the portability benefit: with just the tiniest modifications, if any, you can just run these programs on Linux and they will just work.\n"
] | [
5,
4,
3,
3,
1
] | [] | [] | [
".net",
"ironpython",
"pyqt",
"python",
"user_interface"
] | stackoverflow_0002657036_.net_ironpython_pyqt_python_user_interface.txt |
Q:
Easy ways to investigate unknown Python APIs
When studying a snippet of unknown Python code, I occasionally bump into the
varName.methodName()
pattern.
To figure out what's this, I shall study the code more, find where varName was instantiated, find its type. So if varName proves to be an instance of ClassName class, I would knew that methodName() is a method of ClassName.
Sometimes varName == self and methodName() is a method of this class, or a method inherited from some other class, if the current class is subclassing some other classes.
Are there quick ways / tools that could take 'methodName' as input, scan over all installed Python modules and show which classes have methodName()?
The closest thing related to this I know of is ipython. If I type a class name, then dot ('.') then TAB, it can show the class members. Instead of a class I could use a name of an object (which is an instance of a certain class) and it would work too. As soon as I choose a method name from the provided options, I can type '?' or '??' and get some help if there's a docstring.
I wonder if ipython can do some intelligent scanning based only on 'methodName' string.
If you know alternatives to ipython that could possibly help with this, please do suggest them.
Edit: as requested, I'm explicitly adding that I would like a way to find methods by method names not only in Python source code files. Some Python packages (notably PyQt) contain a lot of .so files, and ipython is able to do completions by presumably importing them first. So a plain text search like grep (or even ctags) won't do the trick here.
A:
I sometimes inserted help(varName) into my code, so that when that particular function is run, the help file will show up instead. For example, if I have this code:
def foo(bar):
bar.baz()
and I want to figure out what class bar is and what .baz does, I just insert this
def foo(bar):
help(bar)
help(bar.baz)
bar.baz()
then run the script. Another way which is less invasive is to use print type(bar).
A:
You want Exuberant ctags (old ctags doesn't generate tags for Python).
Once you've installed (the way to do that depends on your platform), run it on your files:
$ /usr/local/bin/ctags *py
(you can run it multiple times to append tags to an existing tag file, have it recurse into subdirectories, etc, all with command-line options) and it makes a tags file like the following (for brevity I'm using a single Python file with one class defining a single method):
$ cat tags
!_TAG_FILE_FORMAT 2 /extended format; --format=1 will not append ;" to lines/
!_TAG_FILE_SORTED 1 /0=unsorted, 1=sorted, 2=foldcase/
!_TAG_PROGRAM_AUTHOR Darren Hiebert /dhiebert@users.sourceforge.net/
!_TAG_PROGRAM_NAME Exuberant Ctags //
!_TAG_PROGRAM_URL http://ctags.sourceforge.net /official site/
!_TAG_PROGRAM_VERSION 5.7 //
Foo a.py /^class Foo(object):$/;" c
amethod a.py /^ def amethod(self): pass$/;" m class:Foo
Now, quoting this article:
Let say when you discover a function
call which you wanna see the
definition, simply point the cursor to
that function and press ctrl ] and it
will bring you there. If you want to
go back to where you came from, simply
press ctrl t. Instead of ctrl t, I
like to use ctrl i and ctrl o to
travel to forward and backward of the
check points.
Also, control-P does (some attempt at) code completion for identifiers found in tags.
(:help tags in vim will give you more details).
A:
I'd take an interactive approach similar to Lie Ryan's: run the script in debug mode, set a break at the line of interest, and interactively query the variable in question.
This is a more robust approach than your requested "scan the source code looking for matching methodnames" because it's guaranteed to get you the variable you're actually wondering about, rather than returning a set of possibles.
A:
You could use the pydoc utility that comes with most versions of Python. On windows this is usually C:\PythonXX\Tools\Scripts\pydocgui.pyw (where XX is the Python version).
Running this will launch a small Tkinter window with a search box. You can search the auto-generated docs for all installed python modules, or open a browser on the top level documentation.
A:
If you use Eclipse with PyDev for your IDE, you can use the PyDev Globals Browser. You can search for modules, classes, methods and functions. Clicking on a result will open the source file and move the cursor to the line where the object is defined.
alt text http://www.michaelfogleman.com/static/images/pydev_browser.png
You can also hit F3 to jump to the definition of a variable that your cursor is on. For example if your cursor is on a line like import util, hitting F3 will open util.py.
A:
Given that your editor is vim, may I suggest ropevim. It uses rope, a Python refactoring library. Two of ropevim's features are "find occurrences" and "goto definition". Both of these will help you navigate your source tree.
| Easy ways to investigate unknown Python APIs | When studying a snippet of unknown Python code, I occasionally bump into the
varName.methodName()
pattern.
To figure out what's this, I shall study the code more, find where varName was instantiated, find its type. So if varName proves to be an instance of ClassName class, I would knew that methodName() is a method of ClassName.
Sometimes varName == self and methodName() is a method of this class, or a method inherited from some other class, if the current class is subclassing some other classes.
Are there quick ways / tools that could take 'methodName' as input, scan over all installed Python modules and show which classes have methodName()?
The closest thing related to this I know of is ipython. If I type a class name, then dot ('.') then TAB, it can show the class members. Instead of a class I could use a name of an object (which is an instance of a certain class) and it would work too. As soon as I choose a method name from the provided options, I can type '?' or '??' and get some help if there's a docstring.
I wonder if ipython can do some intelligent scanning based only on 'methodName' string.
If you know alternatives to ipython that could possibly help with this, please do suggest them.
Edit: as requested, I'm explicitly adding that I would like a way to find methods by method names not only in Python source code files. Some Python packages (notably PyQt) contain a lot of .so files, and ipython is able to do completions by presumably importing them first. So a plain text search like grep (or even ctags) won't do the trick here.
| [
"I sometimes inserted help(varName) into my code, so that when that particular function is run, the help file will show up instead. For example, if I have this code:\ndef foo(bar):\n bar.baz()\n\nand I want to figure out what class bar is and what .baz does, I just insert this\ndef foo(bar):\n help(bar)\n help(bar.baz)\n bar.baz()\n\nthen run the script. Another way which is less invasive is to use print type(bar).\n",
"You want Exuberant ctags (old ctags doesn't generate tags for Python).\nOnce you've installed (the way to do that depends on your platform), run it on your files:\n$ /usr/local/bin/ctags *py\n\n(you can run it multiple times to append tags to an existing tag file, have it recurse into subdirectories, etc, all with command-line options) and it makes a tags file like the following (for brevity I'm using a single Python file with one class defining a single method):\n$ cat tags\n!_TAG_FILE_FORMAT 2 /extended format; --format=1 will not append ;\" to lines/\n!_TAG_FILE_SORTED 1 /0=unsorted, 1=sorted, 2=foldcase/\n!_TAG_PROGRAM_AUTHOR Darren Hiebert /dhiebert@users.sourceforge.net/\n!_TAG_PROGRAM_NAME Exuberant Ctags //\n!_TAG_PROGRAM_URL http://ctags.sourceforge.net /official site/\n!_TAG_PROGRAM_VERSION 5.7 //\nFoo a.py /^class Foo(object):$/;\" c\namethod a.py /^ def amethod(self): pass$/;\" m class:Foo\n\nNow, quoting this article:\n\nLet say when you discover a function\n call which you wanna see the\n definition, simply point the cursor to\n that function and press ctrl ] and it\n will bring you there. If you want to\n go back to where you came from, simply\n press ctrl t. Instead of ctrl t, I\n like to use ctrl i and ctrl o to\n travel to forward and backward of the\n check points.\n\nAlso, control-P does (some attempt at) code completion for identifiers found in tags.\n(:help tags in vim will give you more details).\n",
"I'd take an interactive approach similar to Lie Ryan's: run the script in debug mode, set a break at the line of interest, and interactively query the variable in question.\nThis is a more robust approach than your requested \"scan the source code looking for matching methodnames\" because it's guaranteed to get you the variable you're actually wondering about, rather than returning a set of possibles.\n",
"You could use the pydoc utility that comes with most versions of Python. On windows this is usually C:\\PythonXX\\Tools\\Scripts\\pydocgui.pyw (where XX is the Python version).\nRunning this will launch a small Tkinter window with a search box. You can search the auto-generated docs for all installed python modules, or open a browser on the top level documentation.\n",
"If you use Eclipse with PyDev for your IDE, you can use the PyDev Globals Browser. You can search for modules, classes, methods and functions. Clicking on a result will open the source file and move the cursor to the line where the object is defined.\nalt text http://www.michaelfogleman.com/static/images/pydev_browser.png\nYou can also hit F3 to jump to the definition of a variable that your cursor is on. For example if your cursor is on a line like import util, hitting F3 will open util.py.\n",
"Given that your editor is vim, may I suggest ropevim. It uses rope, a Python refactoring library. Two of ropevim's features are \"find occurrences\" and \"goto definition\". Both of these will help you navigate your source tree.\n"
] | [
3,
3,
1,
0,
0,
0
] | [] | [] | [
"api",
"python"
] | stackoverflow_0003038606_api_python.txt |
Q:
Can I treat IronPython as a Pythonic replacement to C#?
I do understand that this topic has been covered in some way at StackOverflow but I'm still not able to figure out the exact answer: can I treat IronPython as a Pythonic replacement to C#?
I use CPython every day, I love the Zen :) but my current task is a Windows-only application with a complex GUI and some other features which I would like to implement using .NET.
A:
IronPython is NOT equivalent to "other languages that run on .NET", as the language has support for substantially fewer CLR runtime features.
IronPython classes are not "real" .NET classes, and DLR APIs need to be used when calling IronPython code from traditional CLR-based languages; this means that if you want genuinely easy interoperability, you're stuck writing glue to "hide" the DLR.
Boo is a much more complete Pythonically-inspired language targeting the CLR. Its (dynamically inferrable) static typing (which can be replaced with duck typing on a variable-by-variable basis) also allows libraries written in Boo to be natively used from C# and other CLR-based languages, without needing to make any allowances for the language in use.
A:
That depends on what it is about C# that you need, and which needs replacing.
If the reason you use C# is that you need a reasonably high performance statically typed language then no, IronPython is likely not going to be a replacement.
If the reason you use it is simply "I need something that runs on .NET and can access .NET libraries", then yes, any language that runs on .NET can be used to replace it.
If you use C# because you're working with a team of programmers who only know C-like languages, C# might also be difficult to replace with IronPython.
It depends on what characteristics about C# it is that you care about, and need to find replacements for.
A:
One thing to consider - and I have no idea how IronPython behaves in that respect - is Common Language Subsystem (CLS) compliance for assemblies. CLS compliance guarantees that any .Net language can access a compiled DLL of your code. That means e.g. in C# you cannot have any public or protected method or parameter that is a unsigned integer. I have no idea how easy it is to achieve CLS compliant code in IronPython, an interesting blog entry that I found dates from 2008.
A:
The question "Can I treat IronPython as a Pythonic replacement for C#?" has been answered pretty well by jalf. If the question were "Is IronPython a Pythonic .NET Language?" though, then the answer would absolutely be yes. The principles of Zen - esp. least surprise - absolutely apply to IronPython's integration with the CLR as well.
A:
I think if you were to do that,
it would be easier in .NET 4.0.
I think you can use the newly released IronPython 2.6.1 for .NET 4.0,
It is already easy to use C# in IronPython.
As you can see here, you can easily do it the other way around (using IronPython from C#) with .NET 4.0.
I think its possible, but I agree Boo is a safer way to go.
A:
"Complex" UI usually entails not "writing" it but building it within Visual Studio with point and click. All the callbacks and eventing code is inserted by itself. There is almost nothing like that on python side. I'd say go for C# straight out.
There is one nagging thing though. If you are true Pythonista, the static typing will get to you very very quickly and you will want to start throwing heavy objects at random people.
If that point comes think about building out the UI with C# and embedding IronPython as a scripting engine for implementing your business logic. That could be a tolerable middle ground.
| Can I treat IronPython as a Pythonic replacement to C#? | I do understand that this topic has been covered in some way at StackOverflow but I'm still not able to figure out the exact answer: can I treat IronPython as a Pythonic replacement to C#?
I use CPython every day, I love the Zen :) but my current task is a Windows-only application with a complex GUI and some other features which I would like to implement using .NET.
| [
"IronPython is NOT equivalent to \"other languages that run on .NET\", as the language has support for substantially fewer CLR runtime features.\nIronPython classes are not \"real\" .NET classes, and DLR APIs need to be used when calling IronPython code from traditional CLR-based languages; this means that if you want genuinely easy interoperability, you're stuck writing glue to \"hide\" the DLR.\nBoo is a much more complete Pythonically-inspired language targeting the CLR. Its (dynamically inferrable) static typing (which can be replaced with duck typing on a variable-by-variable basis) also allows libraries written in Boo to be natively used from C# and other CLR-based languages, without needing to make any allowances for the language in use.\n",
"That depends on what it is about C# that you need, and which needs replacing.\nIf the reason you use C# is that you need a reasonably high performance statically typed language then no, IronPython is likely not going to be a replacement.\nIf the reason you use it is simply \"I need something that runs on .NET and can access .NET libraries\", then yes, any language that runs on .NET can be used to replace it.\nIf you use C# because you're working with a team of programmers who only know C-like languages, C# might also be difficult to replace with IronPython.\nIt depends on what characteristics about C# it is that you care about, and need to find replacements for.\n",
"One thing to consider - and I have no idea how IronPython behaves in that respect - is Common Language Subsystem (CLS) compliance for assemblies. CLS compliance guarantees that any .Net language can access a compiled DLL of your code. That means e.g. in C# you cannot have any public or protected method or parameter that is a unsigned integer. I have no idea how easy it is to achieve CLS compliant code in IronPython, an interesting blog entry that I found dates from 2008.\n",
"The question \"Can I treat IronPython as a Pythonic replacement for C#?\" has been answered pretty well by jalf. If the question were \"Is IronPython a Pythonic .NET Language?\" though, then the answer would absolutely be yes. The principles of Zen - esp. least surprise - absolutely apply to IronPython's integration with the CLR as well.\n",
"I think if you were to do that,\nit would be easier in .NET 4.0.\nI think you can use the newly released IronPython 2.6.1 for .NET 4.0,\nIt is already easy to use C# in IronPython.\nAs you can see here, you can easily do it the other way around (using IronPython from C#) with .NET 4.0.\nI think its possible, but I agree Boo is a safer way to go.\n",
"\"Complex\" UI usually entails not \"writing\" it but building it within Visual Studio with point and click. All the callbacks and eventing code is inserted by itself. There is almost nothing like that on python side. I'd say go for C# straight out.\nThere is one nagging thing though. If you are true Pythonista, the static typing will get to you very very quickly and you will want to start throwing heavy objects at random people.\nIf that point comes think about building out the UI with C# and embedding IronPython as a scripting engine for implementing your business logic. That could be a tolerable middle ground.\n"
] | [
13,
10,
2,
1,
0,
0
] | [] | [] | [
".net",
"cpython",
"ironpython",
"python",
"python.net"
] | stackoverflow_0002617007_.net_cpython_ironpython_python_python.net.txt |
Q:
Which style of return is "better" for a method that might return None?
I have a method that will either return an object or None if the lookup fails. Which style of the following is better?
def get_foo(needle):
haystack = object_dict()
if needle not in haystack: return None
return haystack[needle]
or,
def get_foo(needle):
haystack = object_dict()
try:
return haystack[needle]
except KeyError:
# Needle not found
return None
I'm undecided as to which is more more desirable myself. Another choice would be return haystack[needle] if needle in haystack else None, but I'm not sure that's any better.
A:
For this particular example, it looks like the dict method get is the most concise:
def get_foo(needle):
haystack = object_dict()
return haystack.get(needle)
In general, in Python, people tend to prefer try/except than checking something first - see the EAFP entry in the glossary. Note that many "test for membership" functions use exceptions behind the scenes.
I won't start a flamewar on the relative merits of multiple returns or the alternatives :)
A:
if both do exactly the same, choose that one that you like the most and thats more readable - i like the second one, but both are good.
(maybe one if this is faster than the other one - so if preformance is realy important, test it and choose the faster one)
| Which style of return is "better" for a method that might return None? | I have a method that will either return an object or None if the lookup fails. Which style of the following is better?
def get_foo(needle):
haystack = object_dict()
if needle not in haystack: return None
return haystack[needle]
or,
def get_foo(needle):
haystack = object_dict()
try:
return haystack[needle]
except KeyError:
# Needle not found
return None
I'm undecided as to which is more more desirable myself. Another choice would be return haystack[needle] if needle in haystack else None, but I'm not sure that's any better.
| [
"For this particular example, it looks like the dict method get is the most concise:\ndef get_foo(needle):\n haystack = object_dict()\n return haystack.get(needle)\n\nIn general, in Python, people tend to prefer try/except than checking something first - see the EAFP entry in the glossary. Note that many \"test for membership\" functions use exceptions behind the scenes.\nI won't start a flamewar on the relative merits of multiple returns or the alternatives :)\n",
"if both do exactly the same, choose that one that you like the most and thats more readable - i like the second one, but both are good.\n(maybe one if this is faster than the other one - so if preformance is realy important, test it and choose the faster one)\n"
] | [
10,
2
] | [
"In every language I've used the first version is perferable. Exceptions are basically goto's in disguise with many of the same problems, so I don't use them if I can avoid it.\nThere is also a possible performance cost. I don't know about Python, but in many other languages there is a heavy cost for creating the exception that you are going to throw away on the next line.\n"
] | [
-2
] | [
"coding_style",
"python"
] | stackoverflow_0003042627_coding_style_python.txt |
Q:
Model inheritance and RSS Feed framework
I'm using model inheritance to manage a multiple models queryset:
from django.db import models
from django.contrib.sites.models import Site
from django.contrib.auth.models import User
from imagekit.models import ImageModel
import datetime
class Entry(models.Model):
date_pub = models.DateTimeField(default=datetime.datetime.now)
author = models.ForeignKey(User)
via = models.URLField(blank=True)
comments_allowed = models.BooleanField(default=True)
class IKOptions:
spec_module = 'journal.icon_specs'
cache_dir = 'icon/resized'
image_field = 'icon'
class Post(Entry):
title = models.CharField(max_length=200)
description = models.TextField()
slug = models.SlugField(unique=True)
def __unicode__(self):
return self.title
class Photo(Entry):
alt = models.CharField(max_length=200)
description = models.TextField(blank=True)
original = models.ImageField(upload_to='photo/')
def __unicode__(self):
return self.alt
class Quote(Entry):
blockquote = models.TextField()
cite = models.TextField(blank=True)
def __unicode__(self):
return self.blockquote
A conditional template is enough to render the right snippets of html with a view based on Entry.objects.all():
{% extends "base.html" %}
{% block main %}
<hr>
{% for entry in entries %}
{% if entry.post %}
[...do something with entry.post]
{% endif %}
{% if entry.photo %}
[...do something with entry.photo]
{% endif %}
[...and so on]
Now I'm trying to generate a RSS feed using the new Feed Framework featured in Django 1.2 but without any luck... The over-simplified settings of the framework don't let me specify conditional item_title and item_description based on the child objects of Entry:
from django.contrib.syndication.views import Feed
from totanus.journal.models import Entry, Photo, Post, Quote
class LatestEntriesFeed(Feed):
title = "RSS Feed"
link = "/journal/"
description = "Journal RSS"
def items(self):
return Entry.objects.order_by('-date_pub')[:10]
def item_title(self, item):
# if child is Post
return item.post.title # this isn't working, of course...
Should I create a custom view-template set to manage the RSS creation and syndication or is there a way to use the Feed framework with this subclassed model?
A:
You have two options:
use the title_template and description_template attributes on the Feed class to point to templates that can handle a very generic input variable.
Recreate your template logic in the feed class' methods so that your template variable gets a normalized piece of data.
Either one will get you to the same end point.
| Model inheritance and RSS Feed framework | I'm using model inheritance to manage a multiple models queryset:
from django.db import models
from django.contrib.sites.models import Site
from django.contrib.auth.models import User
from imagekit.models import ImageModel
import datetime
class Entry(models.Model):
date_pub = models.DateTimeField(default=datetime.datetime.now)
author = models.ForeignKey(User)
via = models.URLField(blank=True)
comments_allowed = models.BooleanField(default=True)
class IKOptions:
spec_module = 'journal.icon_specs'
cache_dir = 'icon/resized'
image_field = 'icon'
class Post(Entry):
title = models.CharField(max_length=200)
description = models.TextField()
slug = models.SlugField(unique=True)
def __unicode__(self):
return self.title
class Photo(Entry):
alt = models.CharField(max_length=200)
description = models.TextField(blank=True)
original = models.ImageField(upload_to='photo/')
def __unicode__(self):
return self.alt
class Quote(Entry):
blockquote = models.TextField()
cite = models.TextField(blank=True)
def __unicode__(self):
return self.blockquote
A conditional template is enough to render the right snippets of html with a view based on Entry.objects.all():
{% extends "base.html" %}
{% block main %}
<hr>
{% for entry in entries %}
{% if entry.post %}
[...do something with entry.post]
{% endif %}
{% if entry.photo %}
[...do something with entry.photo]
{% endif %}
[...and so on]
Now I'm trying to generate a RSS feed using the new Feed Framework featured in Django 1.2 but without any luck... The over-simplified settings of the framework don't let me specify conditional item_title and item_description based on the child objects of Entry:
from django.contrib.syndication.views import Feed
from totanus.journal.models import Entry, Photo, Post, Quote
class LatestEntriesFeed(Feed):
title = "RSS Feed"
link = "/journal/"
description = "Journal RSS"
def items(self):
return Entry.objects.order_by('-date_pub')[:10]
def item_title(self, item):
# if child is Post
return item.post.title # this isn't working, of course...
Should I create a custom view-template set to manage the RSS creation and syndication or is there a way to use the Feed framework with this subclassed model?
| [
"You have two options:\n\nuse the title_template and description_template attributes on the Feed class to point to templates that can handle a very generic input variable.\nRecreate your template logic in the feed class' methods so that your template variable gets a normalized piece of data.\n\nEither one will get you to the same end point.\n"
] | [
2
] | [] | [] | [
"django",
"feed",
"inheritance",
"python",
"rss"
] | stackoverflow_0003040818_django_feed_inheritance_python_rss.txt |
Q:
Python script to remove lines from file containing words in array
I have the following script which identifies lines in a file which I want to remove, based on an array but does not remove them.
What should I change?
sourcefile = "C:\\Python25\\PC_New.txt"
filename2 = "C:\\Python25\\PC_reduced.txt"
offending = ["Exception","Integer","RuntimeException"]
def fixup( filename ):
print "fixup ", filename
fin = open( filename )
fout = open( filename2 , "w")
for line in fin.readlines():
for item in offending:
print "got one",line
line = line.replace( item, "MUST DELETE" )
line=line.strip()
fout.write(line)
fin.close()
fout.close()
fixup(sourcefile)
A:
sourcefile = "C:\\Python25\\PC_New.txt"
filename2 = "C:\\Python25\\PC_reduced.txt"
offending = ["Exception","Integer","RuntimeException"]
def fixup( filename ):
fin = open( filename )
fout = open( filename2 , "w")
for line in fin:
if True in [item in line for item in offending]:
continue
fout.write(line)
fin.close()
fout.close()
fixup(sourcefile)
EDIT: Or even better:
for line in fin:
if not True in [item in line for item in offending]:
fout.write(line)
A:
The basic strategy is to write a copy of the input file to the output file, but with changes. In your case, the changes are very simple: you just omit the lines you don't want.
Once you have your copy safely written, you can delete the original file and use 'os.rename()' to rename your temp file to the original file name. I like to write the temp file in the same directory as the original file, to make sure I have permission to write in that directory and because I don't know if os.rename() can move a file from one volume to another.
You don't need to say for line in fin.readlines(); it is enough to say for line in fin. When you use .readlines() you are telling Python to read every line of the input file, all at once, into memory; when you just use fin by itself you read one line at a time.
Here is your code, modified to do these changes.
sourcefile = "C:\\Python25\\PC_New.txt"
filename2 = "C:\\Python25\\PC_reduced.txt"
offending = ["Exception","Integer","RuntimeException"]
def line_offends(line, offending):
for word in line.split():
if word in offending:
return True
return False
def fixup( filename ):
print "fixup ", filename
fin = open( filename )
fout = open( filename2 , "w")
for line in fin:
if line_offends(line, offending):
continue
fout.write(line)
fin.close()
fout.close()
#os.rename() left as an exercise for the student
fixup(sourcefile)
If line_offends() returns True, we execute continue and the loop continues without executing the next part. That means the line never gets written. For this simple example, it would really be just as good to do it this way:
for line in fin:
if not line_offends(line, offending):
fout.write(line)
I wrote it with the continue because often there is non-trivial work being done in the main loop, and you want to avoid all of it if the test is true. IMHO it is nicer to have a simple "if this line is unwanted, continue" rather than indenting a whole bunch of stuff inside an if for a condition that might be very rare.
A:
You're not writing it to the output file. Also, I would use "in" to check for the string existing in the line. See the modified script below (not tested):
sourcefile = "C:\\Python25\\PC_New.txt"
filename2 = "C:\\Python25\\PC_reduced.txt"
offending = ["Exception","Integer","RuntimeException"]
def fixup( filename ):
print "fixup ", filename
fin = open( filename )
fout = open( filename2 , "w")
for line in fin.readlines():
if not offending in line:
# There are no offending words in this line
# write it to the output file
fout.write(line)
fin.close()
fout.close()
fixup(sourcefile)
A:
'''This is a rather simple implementation but should do what you are searching for'''
sourcefile = "C:\\Python25\\PC_New.txt"
filename2 = "C:\\Python25\\PC_reduced.txt"
offending = ["Exception","Integer","RuntimeException"]
def fixup( filename ):
print "fixup ", filename
fin = open( filename )
fout = open( filename2 , "w")
for line in fin.readlines():
for item in offending:
print "got one",line
line = line.replace( item, "MUST DELETE" )
line=line.strip()
fout.write(line)
fin.close()
fout.close()
fixup(sourcefile)
| Python script to remove lines from file containing words in array | I have the following script which identifies lines in a file which I want to remove, based on an array but does not remove them.
What should I change?
sourcefile = "C:\\Python25\\PC_New.txt"
filename2 = "C:\\Python25\\PC_reduced.txt"
offending = ["Exception","Integer","RuntimeException"]
def fixup( filename ):
print "fixup ", filename
fin = open( filename )
fout = open( filename2 , "w")
for line in fin.readlines():
for item in offending:
print "got one",line
line = line.replace( item, "MUST DELETE" )
line=line.strip()
fout.write(line)
fin.close()
fout.close()
fixup(sourcefile)
| [
"sourcefile = \"C:\\\\Python25\\\\PC_New.txt\" \nfilename2 = \"C:\\\\Python25\\\\PC_reduced.txt\"\n\noffending = [\"Exception\",\"Integer\",\"RuntimeException\"]\n\ndef fixup( filename ): \n fin = open( filename ) \n fout = open( filename2 , \"w\") \n for line in fin: \n if True in [item in line for item in offending]:\n continue\n fout.write(line)\n fin.close() \n fout.close() \n\nfixup(sourcefile)\n\nEDIT: Or even better:\nfor line in fin: \n if not True in [item in line for item in offending]:\n fout.write(line)\n\n",
"The basic strategy is to write a copy of the input file to the output file, but with changes. In your case, the changes are very simple: you just omit the lines you don't want.\nOnce you have your copy safely written, you can delete the original file and use 'os.rename()' to rename your temp file to the original file name. I like to write the temp file in the same directory as the original file, to make sure I have permission to write in that directory and because I don't know if os.rename() can move a file from one volume to another.\nYou don't need to say for line in fin.readlines(); it is enough to say for line in fin. When you use .readlines() you are telling Python to read every line of the input file, all at once, into memory; when you just use fin by itself you read one line at a time.\nHere is your code, modified to do these changes.\nsourcefile = \"C:\\\\Python25\\\\PC_New.txt\" \nfilename2 = \"C:\\\\Python25\\\\PC_reduced.txt\"\n\noffending = [\"Exception\",\"Integer\",\"RuntimeException\"]\n\ndef line_offends(line, offending):\n for word in line.split():\n if word in offending:\n return True\n return False\n\ndef fixup( filename ): \n print \"fixup \", filename \n fin = open( filename ) \n fout = open( filename2 , \"w\") \n for line in fin:\n if line_offends(line, offending):\n continue\n fout.write(line)\n fin.close()\n fout.close()\n #os.rename() left as an exercise for the student\n\nfixup(sourcefile)\n\nIf line_offends() returns True, we execute continue and the loop continues without executing the next part. That means the line never gets written. For this simple example, it would really be just as good to do it this way:\n for line in fin:\n if not line_offends(line, offending):\n fout.write(line)\n\nI wrote it with the continue because often there is non-trivial work being done in the main loop, and you want to avoid all of it if the test is true. IMHO it is nicer to have a simple \"if this line is unwanted, continue\" rather than indenting a whole bunch of stuff inside an if for a condition that might be very rare.\n",
"You're not writing it to the output file. Also, I would use \"in\" to check for the string existing in the line. See the modified script below (not tested):\nsourcefile = \"C:\\\\Python25\\\\PC_New.txt\" \nfilename2 = \"C:\\\\Python25\\\\PC_reduced.txt\"\n\noffending = [\"Exception\",\"Integer\",\"RuntimeException\"]\n\ndef fixup( filename ): \n print \"fixup \", filename \n fin = open( filename ) \n fout = open( filename2 , \"w\") \n\n for line in fin.readlines(): \n if not offending in line:\n # There are no offending words in this line\n # write it to the output file\n fout.write(line)\n\n fin.close() \n fout.close() \n\nfixup(sourcefile)\n\n",
"'''This is a rather simple implementation but should do what you are searching for'''\nsourcefile = \"C:\\\\Python25\\\\PC_New.txt\"\n\nfilename2 = \"C:\\\\Python25\\\\PC_reduced.txt\"\n\noffending = [\"Exception\",\"Integer\",\"RuntimeException\"]\n\ndef fixup( filename ): \n\n print \"fixup \", filename \n fin = open( filename ) \n fout = open( filename2 , \"w\") \n for line in fin.readlines(): \n for item in offending: \n print \"got one\",line \n line = line.replace( item, \"MUST DELETE\" ) \n line=line.strip()\n fout.write(line) \n fin.close() \n fout.close() \n\nfixup(sourcefile)\n\n"
] | [
5,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003042856_python.txt |
Q:
Use Regular expression with fileinput
I am trying to replace a variable stored in another file using regular expression. The code I have tried is:
r = re.compile(r"self\.uid\s*=\s*('\w{12})'")
for line in fileinput.input(['file.py'], inplace=True):
print line.replace(r.match(line), sys.argv[1]),
The format of the variable in the file is:
self.uid = '027FC8EBC2D1'
I am trying to pass in a parameter in this format and use regular expression to verify that the sys.argv[1] is correct format and to find the variable stored in this file and replace it with the new variable.
Can anyone help. Thanks for the help.
A:
You can use re.sub which will match the regular expression and do the substitution in one go:
r = re.compile(r"(self\.uid\s*=\s*)'\w{12}'")
for line in fileinput.input(['file.py'], inplace=True):
print r.sub(r"\1'%s'" %sys.argv[1],line),
A:
You need to use re.sub(), not str.replace():
re.sub(pattern, repl, string[, count])
Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. ... Backreferences, such as \6, are replaced with the substring matched by group 6 in the pattern.
...
In addition to character escapes and backreferences as described above, \g<name> will use the substring matched by the group named name, as defined by the (?P<name>...) syntax. \g<number> uses the corresponding group number;
Quick test, using \g<number> for backreference:
>>> r = re.compile(r"(self\.uid\s*=\s*)'\w{12}'")
>>> line = "self.uid = '027FC8EBC2D1'"
>>> newv = "AAAABBBBCCCC"
>>> r.sub(r"\g<1>'%s'" % newv, line)
"self.uid = 'AAAABBBBCCCC'"
>>>
A:
str.replace(old, new[, count])(old, new[, count]):
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
re.match returns either MatchObject or (most likely in your case) None, neither is a string required by str.replace.
| Use Regular expression with fileinput | I am trying to replace a variable stored in another file using regular expression. The code I have tried is:
r = re.compile(r"self\.uid\s*=\s*('\w{12})'")
for line in fileinput.input(['file.py'], inplace=True):
print line.replace(r.match(line), sys.argv[1]),
The format of the variable in the file is:
self.uid = '027FC8EBC2D1'
I am trying to pass in a parameter in this format and use regular expression to verify that the sys.argv[1] is correct format and to find the variable stored in this file and replace it with the new variable.
Can anyone help. Thanks for the help.
| [
"You can use re.sub which will match the regular expression and do the substitution in one go:\nr = re.compile(r\"(self\\.uid\\s*=\\s*)'\\w{12}'\")\nfor line in fileinput.input(['file.py'], inplace=True):\n print r.sub(r\"\\1'%s'\" %sys.argv[1],line),\n\n",
"You need to use re.sub(), not str.replace():\n\nre.sub(pattern, repl, string[, count])\nReturn the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. ... Backreferences, such as \\6, are replaced with the substring matched by group 6 in the pattern.\n...\nIn addition to character escapes and backreferences as described above, \\g<name> will use the substring matched by the group named name, as defined by the (?P<name>...) syntax. \\g<number> uses the corresponding group number;\n\nQuick test, using \\g<number> for backreference:\n>>> r = re.compile(r\"(self\\.uid\\s*=\\s*)'\\w{12}'\")\n>>> line = \"self.uid = '027FC8EBC2D1'\"\n>>> newv = \"AAAABBBBCCCC\"\n>>> r.sub(r\"\\g<1>'%s'\" % newv, line)\n\"self.uid = 'AAAABBBBCCCC'\"\n>>> \n\n",
"str.replace(old, new[, count])(old, new[, count]):\n\nReturn a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.\n\nre.match returns either MatchObject or (most likely in your case) None, neither is a string required by str.replace.\n"
] | [
6,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003043849_python_regex.txt |
Q:
Problem with Django styling
Hi new to django but I'm having issues with the stylesheets (CSS) of pages.
my settings.py contains
MEDIA_ROOT = ''
MEDIA_URL = ''
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), 'templates'),
)
please can someone help me shed some light on what I need to do to get the CSS styles working in my templates
Thanks
A:
The templates setting is just for aiding when you're selecting a template file for rendering in your view handler.
If you want to serve files, such as CSS, see how to serve static files with Django, which is the easiest way. The best way, however, is to configure your server to, for the CSS (and other static files) requests, serve the files himself instead of handing the request to the Django handler.
| Problem with Django styling | Hi new to django but I'm having issues with the stylesheets (CSS) of pages.
my settings.py contains
MEDIA_ROOT = ''
MEDIA_URL = ''
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), 'templates'),
)
please can someone help me shed some light on what I need to do to get the CSS styles working in my templates
Thanks
| [
"The templates setting is just for aiding when you're selecting a template file for rendering in your view handler.\nIf you want to serve files, such as CSS, see how to serve static files with Django, which is the easiest way. The best way, however, is to configure your server to, for the CSS (and other static files) requests, serve the files himself instead of handing the request to the Django handler.\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003043868_django_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.