title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Clojure prime numbers lazy sequence | 1,590,716 | <p>What is the Clojure equivalent (for the exact algorithm) of the following Python code?</p>
<pre><code>from itertools import count
from math import sqrt
def prime_gen():
primes = []
for n in count(2):
if all(n%p for p in primes if p <= sqrt(n)):
primes.append(n)
yield n
</code></pre>
| 7 | 2009-10-19T19:46:12Z | 1,591,051 | <p>This is as Pythonish as I can make it:</p>
<pre><code>(def prime-gen
(let [primes (atom [])]
(for [n (iterate inc 2)
:when (not-any? #(zero? (rem n %))
(filter #(<= % (Math/sqrt n))
@primes))]
(do (swap! primes conj n)
n))))
(take 10 prime-gen) ; => (2 3 5 7 11 13 17 19 23 29)
</code></pre>
<p>Clojure doesn't consider the integer 0 to be boolean false. It took me a few minutes to figure out that your Python code was taking advantage of this.</p>
<p><a href="http://stackoverflow.com/questions/960980/fast-prime-number-generation-in-clojure">Here</a> are some other prime number algorithms in Clojure. There's also a prime number implementation in <code>clojure.contrib.lazy-seqs</code>.</p>
| 10 | 2009-10-19T20:46:22Z | [
"python",
"clojure"
] |
Clojure prime numbers lazy sequence | 1,590,716 | <p>What is the Clojure equivalent (for the exact algorithm) of the following Python code?</p>
<pre><code>from itertools import count
from math import sqrt
def prime_gen():
primes = []
for n in count(2):
if all(n%p for p in primes if p <= sqrt(n)):
primes.append(n)
yield n
</code></pre>
| 7 | 2009-10-19T19:46:12Z | 37,084,208 | <p>This version is much faster than @Brian Carper's</p>
<pre><code>(def prime-gen
(let [primes (atom [2N])]
(iterate
#(let [ps @primes]
(loop [n (inc %)]
(if (loop [i 0]
(let [p (nth ps i)]
(cond
(< n (* p p)) true
(zero? (mod n p)) false
:else (recur (inc i)))))
(do (swap! primes conj n) n)
(recur (inc n)))))
(first @primes))))
</code></pre>
| 0 | 2016-05-07T03:31:31Z | [
"python",
"clojure"
] |
appengine, urlfetch, and the content-length header | 1,590,844 | <p>I have a Google Appengine app requesting pages from another server using urllib2 POSTs. I recently enabled gzip compression on the other server running Apache2, and the Appengine page requests started failing on key-error, indicating 'content-length' is not in the headers.</p>
<p>I am not explicitly declaring gzip as an accepted encoding in my requests from Appengine, but it is possible Appengine is adding that header. Googling has not turned up any clear indication that Appengine's urlfetch implicitly adds a header to accept gzip encoding. </p>
<p>Apache2, if I recall correctly, omits content-length headers when the response is compressed, but that should not affect non-compressed responses from the same server. </p>
<p>Does anybody have any insight as to what is happening, why the content-length header is being omitted?</p>
| 4 | 2009-10-19T20:14:20Z | 1,613,636 | <p>According to this thread:
<a href="http://groups.google.com/group/google-appengine-java/browse%5Fthread/thread/5c5f2a7e2d2beadc?pli=1" rel="nofollow">http://groups.google.com/group/google-appengine-java/browse%5Fthread/thread/5c5f2a7e2d2beadc?pli=1</a>)
on an Appengine Java newsgroup, Google does generally set the 'Accept-Encoding: gzip' header on urlfetch requests, and then decompresses (ungzips) the input before handing the data to the script.</p>
<p>So apparently, Appengine adds an accept-encoding: gzip header implicitly on the requests way out to the internet, and decompresses the response, but does not insert a content-length into the headers for the decompressed data size. So if the outside server will provide gzipped responses, the net result to the Appengine script (after all the pre- and post- processing behavior by Appengine described above) is the loss of the content-length header.</p>
| 2 | 2009-10-23T13:57:08Z | [
"python",
"google-app-engine",
"post",
"apache2"
] |
Preserving whitespace with Pygments | 1,591,024 | <p>I'm currently writing an application that uses Pygments to perform syntax highlighting. The problem I'm having is any code I process with Pygments has the leading and trailing whitespace in the file removed, and a single line break added to the end. Is there a way to make Pygments preserve the whitespace?</p>
| 0 | 2009-10-19T20:41:36Z | 1,591,083 | <p>I think you want to make your own lexer, e.g.</p>
<pre><code>lexer = lexers.get_lexer_by_name("python", stripnl=False)
</code></pre>
<p>and explicitly pass it to <code>pygment.highlight</code>. See the lexers' reference <a href="http://pygments.org/docs/lexers/" rel="nofollow">here</a>.</p>
| 1 | 2009-10-19T20:50:51Z | [
"python"
] |
Combinations with replacements | 1,591,087 | <p>I know how to generate combinations of a set and that's a builtin in Python (what I use), anyway. But how to generate combinations with replacements?</p>
<p>Suppose I have a set with, say, two identical elements - for example, <strong>AABCDE</strong>.</p>
<p>Combinations of 3 items could be:</p>
<pre><code>"AAB"
"ABC"
"CDE"
</code></pre>
<p>However, the program would count <strong>ABC</strong> twice - once when using the first A, and the second one using the second A.</p>
<p>What is a good way to generate such combinations without duplicates?</p>
<p>Thanks.</p>
| 0 | 2009-10-19T20:51:12Z | 1,591,100 | <p>convert it to <code>set</code>, that's the easiest way to get rid of duplicates.</p>
| 2 | 2009-10-19T20:54:24Z | [
"python",
"combinations"
] |
Combinations with replacements | 1,591,087 | <p>I know how to generate combinations of a set and that's a builtin in Python (what I use), anyway. But how to generate combinations with replacements?</p>
<p>Suppose I have a set with, say, two identical elements - for example, <strong>AABCDE</strong>.</p>
<p>Combinations of 3 items could be:</p>
<pre><code>"AAB"
"ABC"
"CDE"
</code></pre>
<p>However, the program would count <strong>ABC</strong> twice - once when using the first A, and the second one using the second A.</p>
<p>What is a good way to generate such combinations without duplicates?</p>
<p>Thanks.</p>
| 0 | 2009-10-19T20:51:12Z | 1,591,147 | <pre><code>>>> import itertools
>>> ["".join(x) for x in (itertools.combinations(set("AABCDE"),3))]
['ACB', 'ACE', 'ACD', 'ABE', 'ABD', 'AED', 'CBE', 'CBD', 'CED', 'BED']
>>>
</code></pre>
<p>From your other comments, I think I misunderstood what you are asking.</p>
<pre><code>>>> import itertools
>>> set("".join(x) for x in (itertools.combinations("AABCDE",3)))
set(['AAE', 'AAD', 'ABC', 'ABD', 'ABE', 'AAC', 'AAB', 'BCD', 'BCE', 'ACD', 'CDE', 'ACE', 'ADE', 'BDE'])
</code></pre>
| 2 | 2009-10-19T21:03:29Z | [
"python",
"combinations"
] |
Combinations with replacements | 1,591,087 | <p>I know how to generate combinations of a set and that's a builtin in Python (what I use), anyway. But how to generate combinations with replacements?</p>
<p>Suppose I have a set with, say, two identical elements - for example, <strong>AABCDE</strong>.</p>
<p>Combinations of 3 items could be:</p>
<pre><code>"AAB"
"ABC"
"CDE"
</code></pre>
<p>However, the program would count <strong>ABC</strong> twice - once when using the first A, and the second one using the second A.</p>
<p>What is a good way to generate such combinations without duplicates?</p>
<p>Thanks.</p>
| 0 | 2009-10-19T20:51:12Z | 30,520,169 | <pre><code>def stepper_w_w(l,stop):#stepper_with_while
"""l is a list of any size usually you would input [1,1,1,1...],
stop is the highest number you want to stop at so if you put in stop=5
the sequence would stop at [5,5,5,5...]
This stepper shows the first number that equals the last.
This generates combinations with replacement. """
numb1=1
while numb1<stop:
#print(numb1)
l[0]=numb1
NeL=0
while l[len(l)-1]<=numb1:
if l[NeL]==l[len(l)-1]:
l[NeL]+=1
l[(NeL+1):]=[1]*((len(l))-(NeL+1))
print(l)
"""iter_2s=NeL+1
while iter_2s<=(len(l)-1): #this is different from above
l[iter_2s]=2
iter_2s+=1
print(l)"""
NeL=-1
NeL+=1
numb1+=1
</code></pre>
| 0 | 2015-05-29T02:31:17Z | [
"python",
"combinations"
] |
Python: How can I know which exceptions might be thrown from a method call | 1,591,319 | <p>Is there a way knowing (at coding time) which exceptions to expect when executing python code?
I end up catching the base Exception class 90% of the time since I don't know which exception type might be thrown(and don't tell me to read the documentation. many times an exception can be propagated from the deep. and many times the documentation is not updated or correct). Is there some kind of tool to check this ? (like by reading the python code and libs)?</p>
| 45 | 2009-10-19T21:43:36Z | 1,591,337 | <p>You should only catch exceptions that you will handle.</p>
<p>Catching all exceptions by their concrete types is nonsense. You should catch specific exceptions you <em>can</em> and <em>will</em> handle. For other exceptions, you may write a generic catch that catches "base Exception", logs it (use <code>str()</code> function) and terminates your program (or does something else that's appropriate in a crashy situation).</p>
<p>If you really gonna handle <em>all</em> exceptions and are sure none of them are fatal (for example, if you're running the code in some kind of a sandboxed environment), then your approach of catching generic BaseException fits your aims.</p>
<p>You might be also interested in <a href="http://docs.python.org/library/exceptions.html#exceptions.BaseException">language exception reference</a>, not a reference for the library you're using.</p>
<p>If the library reference is really poor and it doesn't re-throw its own exceptions when catching system ones, <strong>the only useful approach is to run tests</strong> (maybe add it to test suite, because if something is undocumented, it may change!). Delete a file crucial for your code and check what exception is being thrown. Supply too much data and check what error it yields.</p>
<p>You will have to run tests anyway, since, even <strong>if the method of getting the exceptions by source code existed, it wouldn't give you any idea how you should handle any of those</strong>. Maybe you should be showing error message "File needful.txt is not found!" when you catch <code>IndexError</code>? Only test can tell.</p>
| 23 | 2009-10-19T21:51:39Z | [
"python",
"exception"
] |
Python: How can I know which exceptions might be thrown from a method call | 1,591,319 | <p>Is there a way knowing (at coding time) which exceptions to expect when executing python code?
I end up catching the base Exception class 90% of the time since I don't know which exception type might be thrown(and don't tell me to read the documentation. many times an exception can be propagated from the deep. and many times the documentation is not updated or correct). Is there some kind of tool to check this ? (like by reading the python code and libs)?</p>
| 45 | 2009-10-19T21:43:36Z | 1,591,363 | <p>normally, you'd need to catch exception only around a few lines of code. You wouldn't want to put your whole <code>main</code> function into the <code>try except</code> clause. for every few line you always should now (or be able easily to check) what kind of exception might be raised.</p>
<p>docs have an exhaustive <a href="http://docs.python.org/3.1/library/exceptions.html" rel="nofollow">list of built-in exceptions</a>. don't try to except those exception that you're not expecting, they might be handled/expected in the calling code.</p>
<p><strong>edit</strong>: what might be thrown depends on obviously on what you're doing! accessing random element of a sequence: <code>IndexError</code>, random element of a dict: <code>KeyError</code>, etc.</p>
<p>Just try to run those few lines in IDLE and cause an exception. But unittest would be a better solution, naturally.</p>
| 1 | 2009-10-19T21:56:17Z | [
"python",
"exception"
] |
Python: How can I know which exceptions might be thrown from a method call | 1,591,319 | <p>Is there a way knowing (at coding time) which exceptions to expect when executing python code?
I end up catching the base Exception class 90% of the time since I don't know which exception type might be thrown(and don't tell me to read the documentation. many times an exception can be propagated from the deep. and many times the documentation is not updated or correct). Is there some kind of tool to check this ? (like by reading the python code and libs)?</p>
| 45 | 2009-10-19T21:43:36Z | 1,591,368 | <p>The correct tool to solve this problem is unittests. If you are having exceptions raised by real code that the unittests do not raise, then you need more unittests.</p>
<p>Consider this</p>
<pre><code>def f(duck):
try:
duck.quack()
except ??? could be anything
</code></pre>
<p>duck can be any object</p>
<p>Obviously you can have an <code>AttributeError</code> if duck has no quack, a <code>TypeError</code> if duck has a quack but it is not callable. You have no idea what <code>duck.quack()</code> might raise though, maybe even a <code>DuckError</code> or something</p>
<p>Now supposing you have code like this</p>
<pre><code>arr[i] = get_something_from_database()
</code></pre>
<p>If it raises an <code>IndexError</code> you don't know whether it has come from arr[i] or from deep inside the database function. usually it doesn't matter so much where the exception occurred, rather that something went wrong and what you wanted to happen didn't happen.</p>
<p>A handy technique is to catch and maybe reraise the exception like this</p>
<pre><code>except Exception as e
#inspect e, decide what to do
raise
</code></pre>
| 8 | 2009-10-19T21:56:46Z | [
"python",
"exception"
] |
Python: How can I know which exceptions might be thrown from a method call | 1,591,319 | <p>Is there a way knowing (at coding time) which exceptions to expect when executing python code?
I end up catching the base Exception class 90% of the time since I don't know which exception type might be thrown(and don't tell me to read the documentation. many times an exception can be propagated from the deep. and many times the documentation is not updated or correct). Is there some kind of tool to check this ? (like by reading the python code and libs)?</p>
| 45 | 2009-10-19T21:43:36Z | 1,591,432 | <p>I guess a solution could be only imprecise because of lack of static typing rules.</p>
<p>I'm not aware of some tool that checks exceptions, but you could come up with your own tool matching your needs (a good chance to play a little with static analysis).</p>
<p>As a first attempt, you could write a function that builds an AST, finds all <code>Raise</code> nodes, and then tries to figure out common patterns of raising exceptions (e. g. calling a constructor directly)</p>
<p>Let <code>x</code> be the following program:</p>
<pre><code>x = '''\
if f(x):
raise IOError(errno.ENOENT, 'not found')
else:
e = g(x)
raise e
'''
</code></pre>
<p>Build the AST using the <code>compiler</code> package:</p>
<pre><code>tree = compiler.parse(x)
</code></pre>
<p>Then define a <code>Raise</code> visitor class:</p>
<pre><code>class RaiseVisitor(object):
def __init__(self):
self.nodes = []
def visitRaise(self, n):
self.nodes.append(n)
</code></pre>
<p>And walk the AST collecting <code>Raise</code> nodes:</p>
<pre><code>v = RaiseVisitor()
compiler.walk(tree, v)
>>> print v.nodes
[
Raise(
CallFunc(
Name('IOError'),
[Getattr(Name('errno'), 'ENOENT'), Const('not found')],
None, None),
None, None),
Raise(Name('e'), None, None),
]
</code></pre>
<p>You may continue by resolving symbols using compiler symbol tables, analyzing data dependencies, etc. Or you may just deduce, that <code>CallFunc(Name('IOError'), ...)</code> "should definitely mean raising <code>IOError</code>", which is quite OK for quick practical results :)</p>
| 14 | 2009-10-19T22:15:17Z | [
"python",
"exception"
] |
Python: How can I know which exceptions might be thrown from a method call | 1,591,319 | <p>Is there a way knowing (at coding time) which exceptions to expect when executing python code?
I end up catching the base Exception class 90% of the time since I don't know which exception type might be thrown(and don't tell me to read the documentation. many times an exception can be propagated from the deep. and many times the documentation is not updated or correct). Is there some kind of tool to check this ? (like by reading the python code and libs)?</p>
| 45 | 2009-10-19T21:43:36Z | 1,591,860 | <p>I ran into this when using socket, I wanted to find out all the error conditions I would run in to (so rather than trying to create errors and figure out what socket does I just wanted a concise list). Ultimately I ended up grep'ing "/usr/lib64/python2.4/test/test_socket.py" for "raise":</p>
<pre><code>$ grep raise test_socket.py
Any exceptions raised by the clients during their tests
raise TypeError, "test_func must be a callable function"
raise NotImplementedError, "clientSetUp must be implemented."
def raise_error(*args, **kwargs):
raise socket.error
def raise_herror(*args, **kwargs):
raise socket.herror
def raise_gaierror(*args, **kwargs):
raise socket.gaierror
self.failUnlessRaises(socket.error, raise_error,
self.failUnlessRaises(socket.error, raise_herror,
self.failUnlessRaises(socket.error, raise_gaierror,
raise socket.error
# Check that setting it to an invalid value raises ValueError
# Check that setting it to an invalid type raises TypeError
def raise_timeout(*args, **kwargs):
self.failUnlessRaises(socket.timeout, raise_timeout,
def raise_timeout(*args, **kwargs):
self.failUnlessRaises(socket.timeout, raise_timeout,
</code></pre>
<p>Which is a pretty concise list of errors. Now of course this only works on a case by case basis and depends on the tests being accurate (which they usually are). Otherwise you need to pretty much catch all exceptions, log them and dissect them and figure out how to handle them (which with unit testing wouldn't be to difficult).</p>
| 3 | 2009-10-20T00:26:38Z | [
"python",
"exception"
] |
Python: How can I know which exceptions might be thrown from a method call | 1,591,319 | <p>Is there a way knowing (at coding time) which exceptions to expect when executing python code?
I end up catching the base Exception class 90% of the time since I don't know which exception type might be thrown(and don't tell me to read the documentation. many times an exception can be propagated from the deep. and many times the documentation is not updated or correct). Is there some kind of tool to check this ? (like by reading the python code and libs)?</p>
| 45 | 2009-10-19T21:43:36Z | 1,891,657 | <p>Noone explained so far, why you can't have a full, 100% correct list of exceptions, so I thought it's worth commenting on. One of the reasons is a first-class function. Let's say that you have a function like this:</p>
<pre><code>def apl(f,arg):
return f(arg)
</code></pre>
<p>Now <code>apl</code> can raise any exception that <code>f</code> raises. While there are not many functions like that in the core library, anything that uses list comprehension with custom filters, map, reduce, etc. are affected.</p>
<p>The documentation and the source analysers are the only "serious" sources of information here. Just keep in mind what they cannot do.</p>
| 2 | 2009-12-12T00:02:31Z | [
"python",
"exception"
] |
Python: How can I know which exceptions might be thrown from a method call | 1,591,319 | <p>Is there a way knowing (at coding time) which exceptions to expect when executing python code?
I end up catching the base Exception class 90% of the time since I don't know which exception type might be thrown(and don't tell me to read the documentation. many times an exception can be propagated from the deep. and many times the documentation is not updated or correct). Is there some kind of tool to check this ? (like by reading the python code and libs)?</p>
| 45 | 2009-10-19T21:43:36Z | 22,664,826 | <p>There are two ways that I found informative. The first one, run the instructions in iPython, which will display the exception type.</p>
<pre><code>n = 2
str = 'me '
str + 2
TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code></pre>
<p>In the second way we settle for catching too much and improving on it. Include a try expression in your code and catch <strong>except Exception as err</strong>. Print sufficient data to know what exception was thrown. As exceptions are thrown improve your code by adding a more precise except clause. When you feel that you have cached all relevant exceptions remove the all inclusive one. A good thing to do anyway because it swallows programming errors.</p>
<pre><code>try:
so something
except Exception as err:
print "Some message"
print err.__class__
print err
exit(1)
</code></pre>
| 0 | 2014-03-26T14:56:09Z | [
"python",
"exception"
] |
Cron job to connect to sql server and run a sproc using python | 1,591,477 | <p>I want to learn python, and my task is the run a sql server 2008 stored procedure via a cron job.</p>
<p>Can someone step through a script for me in python?</p>
| 0 | 2009-10-19T22:25:44Z | 1,591,533 | <p>I am assuming you mean <strong>Microsoft's</strong> SQL server...</p>
<pre><code>#! /usr/bin/python
import pymssql
con = pymssql.connect (host='xxxxx',user='xxxx',
password='xxxxx',database='xxxxx')
cur = con.cursor()
query = "DECLARE @id INT; EXECUTE sp_GetUserID; SELECT @id;"
cur.execute(query)
outputparameter = cur.fetchall()
con.commit()
con.close()
</code></pre>
<p>Taken from <a href="http://coding.derkeiler.com/Archive/Python/comp.lang.python/2008-10/msg02620.html" rel="nofollow">http://coding.derkeiler.com/Archive/Python/comp.lang.python/2008-10/msg02620.html</a> (copyright retained)</p>
<p>Put that in a script and run it from cron...</p>
<p><a href="http://stackoverflow.com/questions/191644/how-do-you-get-output-parameters-from-a-stored-procedure-in-python">Check this question too.</a></p>
| 1 | 2009-10-19T22:39:19Z | [
"python"
] |
From PHP workers to Python threads | 1,591,555 | <p>Right now I'm running 50 PHP (in CLI mode) individual workers (processes) per machine that are waiting to receive their workload (job). For example, the job of resizing an image. In workload they receive the image (binary data) and the desired size. The worker does it's work and returns the resized image back. Then it waits for more jobs (it loops in a smart way). I'm presuming that I have the same executable, libraries and classes loaded and instantiated 50 times. Am I correct? Because this does not sound very effective.</p>
<p>What I'd like to have now is one process that handles all this work and being able to use all available CPU cores while having everything loaded only once (to be more efficient). I presume a new thread would be started for each job and after it finishes, the thread would stop. More jobs would be accepted if there are less than 50 threads doing the work. If all 50 threads are busy, no additional jobs are accepted.</p>
<p>I am using a lot of libraries (for Memcached, Redis, MogileFS, ...) to have access to all the various components that the system uses and Python is pretty much the only language apart from PHP that has support for all of them.</p>
<p>Can Python do what I want and will it be faster and more efficient that the current PHP solution?</p>
| 3 | 2009-10-19T22:47:00Z | 1,591,593 | <p>If you are on a sane operating system then shared libraries should only be loaded once and shared among all processes using them. Memory for data structures and connection handles will obviously be duplicated, but the overhead of stopping and starting the systems may be greater than keeping things up while idle. If you are using something like gearman it might make sense to let several workers stay up even if idle and then have a persistent monitoring process that will start new workers if all the current workers are busy up until a threshold such as the number of available CPUs. That process could then kill workers in a LIFO manner after they have been idle for some period of time.</p>
| 1 | 2009-10-19T22:56:37Z | [
"php",
"python",
"multithreading"
] |
From PHP workers to Python threads | 1,591,555 | <p>Right now I'm running 50 PHP (in CLI mode) individual workers (processes) per machine that are waiting to receive their workload (job). For example, the job of resizing an image. In workload they receive the image (binary data) and the desired size. The worker does it's work and returns the resized image back. Then it waits for more jobs (it loops in a smart way). I'm presuming that I have the same executable, libraries and classes loaded and instantiated 50 times. Am I correct? Because this does not sound very effective.</p>
<p>What I'd like to have now is one process that handles all this work and being able to use all available CPU cores while having everything loaded only once (to be more efficient). I presume a new thread would be started for each job and after it finishes, the thread would stop. More jobs would be accepted if there are less than 50 threads doing the work. If all 50 threads are busy, no additional jobs are accepted.</p>
<p>I am using a lot of libraries (for Memcached, Redis, MogileFS, ...) to have access to all the various components that the system uses and Python is pretty much the only language apart from PHP that has support for all of them.</p>
<p>Can Python do what I want and will it be faster and more efficient that the current PHP solution?</p>
| 3 | 2009-10-19T22:47:00Z | 1,591,603 | <p>Linux has shared libraries, so those 50 php processes use mostly the same libraries.
You don't sound like you even have a problem at all.</p>
<p><em>"this does not sound very effective."</em> is not a problem description, if anything those words are a problem on their own. Writing code needs a <em>real reason</em>, else you're just wasting time and/or money.</p>
<p>Python is a fine language and won't perform worse than php. Python's <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">multiprocessing</a> module will probably help a lot too. But there isn't much to gain if the php implementation is not completly insane. So why even bother spending time on it when everything works? That is usually the goal, not a reason to rewrite ...</p>
| 4 | 2009-10-19T22:59:44Z | [
"php",
"python",
"multithreading"
] |
From PHP workers to Python threads | 1,591,555 | <p>Right now I'm running 50 PHP (in CLI mode) individual workers (processes) per machine that are waiting to receive their workload (job). For example, the job of resizing an image. In workload they receive the image (binary data) and the desired size. The worker does it's work and returns the resized image back. Then it waits for more jobs (it loops in a smart way). I'm presuming that I have the same executable, libraries and classes loaded and instantiated 50 times. Am I correct? Because this does not sound very effective.</p>
<p>What I'd like to have now is one process that handles all this work and being able to use all available CPU cores while having everything loaded only once (to be more efficient). I presume a new thread would be started for each job and after it finishes, the thread would stop. More jobs would be accepted if there are less than 50 threads doing the work. If all 50 threads are busy, no additional jobs are accepted.</p>
<p>I am using a lot of libraries (for Memcached, Redis, MogileFS, ...) to have access to all the various components that the system uses and Python is pretty much the only language apart from PHP that has support for all of them.</p>
<p>Can Python do what I want and will it be faster and more efficient that the current PHP solution?</p>
| 3 | 2009-10-19T22:47:00Z | 1,591,616 | <p>Most probably - yes. But don't assume you have to do multithreading. Have a look at the multiprocessing module. It already has an implementation of a Pool included, which is what you could use. And it basically solves the GIL problem (multithreading can run only 1 "standard python code" at any time - that's a very simplified explanation).</p>
<p>It will still fork a process per job, but in a different way than starting it all over again. All the initialisations done- and libraries loaded before entering the worker process will be inherited in a copy-on-write way. You won't do more initialisations than necessary and you will not waste memory for the same libarary/class if you didn't actually make it different from the pre-pool state.</p>
<p>So yes - looking only at this part, python will be wasting less resources and will use a "nicer" worker-pool model. Whether it will really be faster / less CPU-abusing, is hard to tell without testing, or at least looking at the code. Try it yourself.</p>
<p>Added: If you're worried about memory usage, python may also help you a bit, since it has a "proper" garbage collector, while in php GC is a not a priority and not that good (and for a good reason too).</p>
| 4 | 2009-10-19T23:04:14Z | [
"php",
"python",
"multithreading"
] |
How to update/modify a XML file in python? | 1,591,579 | <p>I have a xml file that I would like to update after it has already data.</p>
<p>I thought about open the xml file in "a" (append) mode. The problem is that the new data will start to be dumped after the "root" tag has been closed.</p>
<p>What I wanted someone to be kind enough to tell me is how can I delete the last line of a file, and then start dumping data from that point on and then close the "root" tag.</p>
<p>Of course I could read the whole file and do some string manipulations, but I don't think this is the best idea..</p>
<p>Thanks for your time.</p>
| 8 | 2009-10-19T22:52:30Z | 1,591,600 | <p>What you really want to do is use an XML parser and append the new elements with the API provided.</p>
<p>Then simply overwrite the file.</p>
<p>The easiest to use would probably be a DOM parser like the one below:</p>
<p><a href="http://docs.python.org/library/xml.dom.minidom.html" rel="nofollow">http://docs.python.org/library/xml.dom.minidom.html</a></p>
| 1 | 2009-10-19T22:58:47Z | [
"python",
"xml",
"io"
] |
How to update/modify a XML file in python? | 1,591,579 | <p>I have a xml file that I would like to update after it has already data.</p>
<p>I thought about open the xml file in "a" (append) mode. The problem is that the new data will start to be dumped after the "root" tag has been closed.</p>
<p>What I wanted someone to be kind enough to tell me is how can I delete the last line of a file, and then start dumping data from that point on and then close the "root" tag.</p>
<p>Of course I could read the whole file and do some string manipulations, but I don't think this is the best idea..</p>
<p>Thanks for your time.</p>
| 8 | 2009-10-19T22:52:30Z | 1,591,604 | <p>You should read the XML file using specific XML modules. That way you can edit the XML document in memory and rewrite your changed XML document into the file.</p>
<p>Here is a quick start: <a href="http://docs.python.org/library/xml.dom.minidom.html" rel="nofollow">http://docs.python.org/library/xml.dom.minidom.html</a></p>
<p>There are a lot of other XML utilities, which one is best depends on the nature of your XML file and in which way you want to edit it.</p>
| 0 | 2009-10-19T23:00:33Z | [
"python",
"xml",
"io"
] |
How to update/modify a XML file in python? | 1,591,579 | <p>I have a xml file that I would like to update after it has already data.</p>
<p>I thought about open the xml file in "a" (append) mode. The problem is that the new data will start to be dumped after the "root" tag has been closed.</p>
<p>What I wanted someone to be kind enough to tell me is how can I delete the last line of a file, and then start dumping data from that point on and then close the "root" tag.</p>
<p>Of course I could read the whole file and do some string manipulations, but I don't think this is the best idea..</p>
<p>Thanks for your time.</p>
| 8 | 2009-10-19T22:52:30Z | 1,591,617 | <p>While I agree with Tim and Oben Sonne that you should use an XML library, there are ways to still manipulate it as a simple string object. </p>
<p>I likely would not try to use a single file pointer for what you are describing, and instead read the file into memory, edit it, then write it out.:</p>
<pre><code>inFile = open('file.xml', 'r')
data = inFile.readlines()
inFile.close()
# some manipulation on `data`
outFile = open('file.xml', 'w')
outFile.writelines(data)
outFile.close()
</code></pre>
| 3 | 2009-10-19T23:04:14Z | [
"python",
"xml",
"io"
] |
How to update/modify a XML file in python? | 1,591,579 | <p>I have a xml file that I would like to update after it has already data.</p>
<p>I thought about open the xml file in "a" (append) mode. The problem is that the new data will start to be dumped after the "root" tag has been closed.</p>
<p>What I wanted someone to be kind enough to tell me is how can I delete the last line of a file, and then start dumping data from that point on and then close the "root" tag.</p>
<p>Of course I could read the whole file and do some string manipulations, but I don't think this is the best idea..</p>
<p>Thanks for your time.</p>
| 8 | 2009-10-19T22:52:30Z | 1,591,629 | <p>The quick and easy way, which you definitely <strong>should not do</strong> (see below), is to read the whole file into a list of strings using readlines(). I write this in case the quick and easy solution is what you're looking for.</p>
<p>Just open the file using open(), then call the readlines() method. What you'll get is a list of all the strings in the file. Now, you can easily add strings before the last element (just add to the list one element before the last). Finally, you can write these back to the file using writelines().</p>
<p>An example might help:</p>
<pre><code>my_file = open(filename, "r")
lines_of_file = my_file.readlines()
lines_of_file.insert(-1, "This line is added one before the last line")
my_file.writelines(lines_of_file)
</code></pre>
<p>The reason you shouldn't be doing this is because, unless you are doing something very quick n' dirty, you should be using an XML parses. This is a library that allows you to work with XML intelligently, using concepts like DOM, trees, and nodes. This is not only the proper way to work with XML, it is also the standard way, making your code both more portable, and easier for other programmers to understand. </p>
<p>Tim's answer mentioned checking out <a href="http://docs.python.org/library/xml.dom.minidom.html" rel="nofollow">http://docs.python.org/library/xml.dom.minidom.html</a> for this purpose, which I think would be a great idea.</p>
| 2 | 2009-10-19T23:06:21Z | [
"python",
"xml",
"io"
] |
How to update/modify a XML file in python? | 1,591,579 | <p>I have a xml file that I would like to update after it has already data.</p>
<p>I thought about open the xml file in "a" (append) mode. The problem is that the new data will start to be dumped after the "root" tag has been closed.</p>
<p>What I wanted someone to be kind enough to tell me is how can I delete the last line of a file, and then start dumping data from that point on and then close the "root" tag.</p>
<p>Of course I could read the whole file and do some string manipulations, but I don't think this is the best idea..</p>
<p>Thanks for your time.</p>
| 8 | 2009-10-19T22:52:30Z | 1,591,655 | <p>Useful Python XML parsers:</p>
<ol>
<li><a href="http://docs.python.org/library/xml.dom.minidom.html" rel="nofollow">Minidom</a> - functional but limited</li>
<li><a href="http://effbot.org/zone/element-index.htm" rel="nofollow">ElementTree</a> - decent performance, more functionality</li>
<li><a href="http://lxml.de/" rel="nofollow">lxml</a> - high-performance <em>in most cases</em>, high functionality including real xpath support</li>
</ol>
<p>Any of those is better than trying to update the XML file as strings of text.</p>
<p>What that means to you:</p>
<p>Open your file with an XML parser of your choice, find the node you're interested in, replace the value, serialize the file back out.</p>
| 12 | 2009-10-19T23:12:10Z | [
"python",
"xml",
"io"
] |
How to update/modify a XML file in python? | 1,591,579 | <p>I have a xml file that I would like to update after it has already data.</p>
<p>I thought about open the xml file in "a" (append) mode. The problem is that the new data will start to be dumped after the "root" tag has been closed.</p>
<p>What I wanted someone to be kind enough to tell me is how can I delete the last line of a file, and then start dumping data from that point on and then close the "root" tag.</p>
<p>Of course I could read the whole file and do some string manipulations, but I don't think this is the best idea..</p>
<p>Thanks for your time.</p>
| 8 | 2009-10-19T22:52:30Z | 1,591,732 | <p>To make this process more robust, you could consider using the SAX parser (that way you don't have to hold the whole file in memory), read & write till the end of tree and then start appending.</p>
| 1 | 2009-10-19T23:38:53Z | [
"python",
"xml",
"io"
] |
How to update/modify a XML file in python? | 1,591,579 | <p>I have a xml file that I would like to update after it has already data.</p>
<p>I thought about open the xml file in "a" (append) mode. The problem is that the new data will start to be dumped after the "root" tag has been closed.</p>
<p>What I wanted someone to be kind enough to tell me is how can I delete the last line of a file, and then start dumping data from that point on and then close the "root" tag.</p>
<p>Of course I could read the whole file and do some string manipulations, but I don't think this is the best idea..</p>
<p>Thanks for your time.</p>
| 8 | 2009-10-19T22:52:30Z | 27,934,162 | <p>Using <code>ElementTree</code>:</p>
<pre><code>import xml.etree.ElementTree
# Open original file
et = xml.etree.ElementTree.parse('file.xml')
# Append new tag: <a x='1' y='abc'>body text</a>
new_tag = xml.etree.ElementTree.SubElement(et.getroot(), 'a')
new_tag.text = 'body text'
new_tag.attrib['x'] = '1' # must be str; cannot be an int
new_tag.attrib['y'] = 'abc'
# Write back to file
#et.write('file.xml')
et.write('file_new.xml')
</code></pre>
<p>note: output written to <code>file_new.xml</code> for you to experiment, writing back to <code>file.xml</code> will replace the old content.</p>
<p>IMPORTANT: the ElementTree library stores attributes in a dict, as such, the order in which these attributes are listed in the xml text will NOT be preserved. Instead, they will be output in alphabetical order.
(also, comments are removed. I'm finding this rather annoying)</p>
<p>ie: the xml input text <code><b y='xxx' x='2'>some body</b></code> will be output as <code><b x='2' y='xxx'>some body</b></code>(after alphabetising the order parameters are defined)</p>
<p>This means when committing the original, and changed files to a revision control system (such as SVN, CSV, ClearCase, etc), a diff between the 2 files may not look pretty.</p>
| 16 | 2015-01-14T00:52:58Z | [
"python",
"xml",
"io"
] |
How to make all combinations of the elements in an array? | 1,591,762 | <p>I have a list. It contains x lists, each with y elements.
I want to pair each element with all the other elements, just once, (a,b = b,a)</p>
<p>EDIT: this has been criticized as being too vague.So I'll describe the history.
My function produces random equations and using genetic techniques, mutates and crossbreeds them, selecting for fitness.
After a number of iterations, it returns a list of 12 objects, sorted by fitness of their 'equation' attribute.
Using the 'parallel python' module to run this function 8 times, a list containing 8 lists of 12 objects (each with an equation attribute) each is returned.
Now, within each list, the 12 objects have already been cross-bread with each other.
I want to cross-breed each object in a list with all the other objects in all the other lists, but not with the objects within it's own list with which it has already been cross-bread. (whew!)</p>
| 2 | 2009-10-19T23:51:01Z | 1,591,774 | <p><code>itertools.product</code> is your friend.</p>
<p>about removing the duplicates, try with a set of sets.</p>
<p>Now it's a little bit clearer what you want:</p>
<pre><code>import itertools
def recombinate(families):
"families is the list of 8 elements, each one with 12 individuals"
for fi, fj in itertools.combinations(families, 2):
for pair in itertools.product(fi, fj):
yield pair
</code></pre>
<p>basically, take all the 2-combinations of families (of those produced in parallel) and for each pair of families, yield all the pairs of elements.</p>
| 7 | 2009-10-19T23:56:35Z | [
"python"
] |
How to make all combinations of the elements in an array? | 1,591,762 | <p>I have a list. It contains x lists, each with y elements.
I want to pair each element with all the other elements, just once, (a,b = b,a)</p>
<p>EDIT: this has been criticized as being too vague.So I'll describe the history.
My function produces random equations and using genetic techniques, mutates and crossbreeds them, selecting for fitness.
After a number of iterations, it returns a list of 12 objects, sorted by fitness of their 'equation' attribute.
Using the 'parallel python' module to run this function 8 times, a list containing 8 lists of 12 objects (each with an equation attribute) each is returned.
Now, within each list, the 12 objects have already been cross-bread with each other.
I want to cross-breed each object in a list with all the other objects in all the other lists, but not with the objects within it's own list with which it has already been cross-bread. (whew!)</p>
| 2 | 2009-10-19T23:51:01Z | 1,591,802 | <p>First of all, please don't refer to this as an "array". You are using a list of lists. In Python, an array is a different type of data structure, provided by the array module. </p>
<p>Also, your application sounds suspiciously like a matrix. If you are really doing matrix manipulations, you should investigate the Numpy package.</p>
<p>At first glance your problem sounded like something that the zip() function would solve or itertools.izip(). You should definitely read through the docs for the itertools module because it has various list manipulations and they will run faster than anything you could write yourself in Python.</p>
| 0 | 2009-10-20T00:10:18Z | [
"python"
] |
How to make all combinations of the elements in an array? | 1,591,762 | <p>I have a list. It contains x lists, each with y elements.
I want to pair each element with all the other elements, just once, (a,b = b,a)</p>
<p>EDIT: this has been criticized as being too vague.So I'll describe the history.
My function produces random equations and using genetic techniques, mutates and crossbreeds them, selecting for fitness.
After a number of iterations, it returns a list of 12 objects, sorted by fitness of their 'equation' attribute.
Using the 'parallel python' module to run this function 8 times, a list containing 8 lists of 12 objects (each with an equation attribute) each is returned.
Now, within each list, the 12 objects have already been cross-bread with each other.
I want to cross-breed each object in a list with all the other objects in all the other lists, but not with the objects within it's own list with which it has already been cross-bread. (whew!)</p>
| 2 | 2009-10-19T23:51:01Z | 1,592,512 | <p>You haven't made it completely clear what you need. It sounds like itertools should have what you need. Perhaps what you wish is an itertools.combinations of the itertools.product of the lists in your big list. </p>
<p>@fortran: you can't have a set of sets. You can have a set of frozensets, but depending on what it really means to have duplicates here, that might not be what is needed.</p>
| 1 | 2009-10-20T04:48:39Z | [
"python"
] |
Twisted: tcp server with push producer example? | 1,591,787 | <p>I want to put together simple TCP server using Python and Twisted.</p>
<p>The server starts up and waits for connection - I already have client - non-python application. Once connection is made server starts sending data at some interval (e.g. 1 sec).</p>
<p>The server reads data from a static file (a record at a time), I should be able to figure out this part.</p>
<p>I assume that I would use push producer to start pushing data once client is connected.</p>
<p>I have simple tcp server with factory in twisted and I can react to connectionMade/dataReceived and so on but I can't figure <strong>out how to plug in the push producer</strong>.</p>
<p><strong>Anyone knows any examples showing push producer with tcp server in twisted?</strong></p>
| 6 | 2009-10-20T00:05:26Z | 1,592,434 | <p>What about something simplistic like:</p>
<pre><code>thedata = '''
Questa mattina
mi son svegliato
o bella ciao, bella ciao,
bella ciao, ciao, ciao
questa mattina
mi son svegliato
ho trovato l'invasor!
'''.splitlines(True)
class Push(protocol.Protocol):
"""This is just about the simplest possible protocol"""
def connectionMade(self):
for line in thedata:
if not line or line.isspace():
continue
self.transport.write(line)
time.sleep(1.0)
self.transport.loseConnection()
</code></pre>
<p>This has hard-coded data, but you say that reading it from a file instead is not your problem. If you can tell us what's wrong with this overly simplistic "push server", maybe we can offer better help!-)</p>
| 1 | 2009-10-20T04:26:40Z | [
"python",
"twisted",
"tcpserver"
] |
Twisted: tcp server with push producer example? | 1,591,787 | <p>I want to put together simple TCP server using Python and Twisted.</p>
<p>The server starts up and waits for connection - I already have client - non-python application. Once connection is made server starts sending data at some interval (e.g. 1 sec).</p>
<p>The server reads data from a static file (a record at a time), I should be able to figure out this part.</p>
<p>I assume that I would use push producer to start pushing data once client is connected.</p>
<p>I have simple tcp server with factory in twisted and I can react to connectionMade/dataReceived and so on but I can't figure <strong>out how to plug in the push producer</strong>.</p>
<p><strong>Anyone knows any examples showing push producer with tcp server in twisted?</strong></p>
| 6 | 2009-10-20T00:05:26Z | 3,088,794 | <p><a href="http://twistedmatrix.com/pipermail/twisted-python/2009-December/021183.html" rel="nofollow">Here</a> is a complete example of a push producer. It's been added to the twisted svn as an example.</p>
| 4 | 2010-06-21T21:57:50Z | [
"python",
"twisted",
"tcpserver"
] |
os.popen subprocess conversion | 1,591,798 | <p>This snippet gets me the dotted quad of my BSD network interface.
I would like to figure out how to use the subprocess module instead.</p>
<pre><code>ifcfg_lines = os.popen("/sbin/ifconfig fxp0").readlines()
x = string.split(ifcfg_lines[3])[1]
</code></pre>
<p>Seems as if I can't use subprocess in exactly the same way.
I don't think I want shell=True or PIPE.
What should I do to make the output indexable?</p>
<p>Thanks.</p>
| 0 | 2009-10-20T00:08:30Z | 1,591,805 | <p>Why not use something like:</p>
<pre><code>import socket
ipadr = socket.gethostbyname(socket.gethostname())
</code></pre>
<p>as in <a href="http://stackoverflow.com/questions/166506/finding-local-ip-addresses-in-python">Finding Local IP Addresses in Python</a> and remove the subprocess dependency? There are also some other suggestions in that question.</p>
<p>I also found a post on the <a href="http://alastairs-place.net/netifaces/" rel="nofollow">netifaces</a> package that does aims to do this with better cross-platform support.</p>
| 0 | 2009-10-20T00:12:04Z | [
"python",
"string",
"indexing",
"subprocess"
] |
os.popen subprocess conversion | 1,591,798 | <p>This snippet gets me the dotted quad of my BSD network interface.
I would like to figure out how to use the subprocess module instead.</p>
<pre><code>ifcfg_lines = os.popen("/sbin/ifconfig fxp0").readlines()
x = string.split(ifcfg_lines[3])[1]
</code></pre>
<p>Seems as if I can't use subprocess in exactly the same way.
I don't think I want shell=True or PIPE.
What should I do to make the output indexable?</p>
<p>Thanks.</p>
| 0 | 2009-10-20T00:08:30Z | 1,591,815 | <pre><code>from subprocess import Popen, PIPE
ifcfg_lines = Popen("/sbin/ifconfig fxp0",shell=True,stdout=PIPE).stdout.readlines()
x = string.split(ifcfg_lines[3])[1]
</code></pre>
<p>For a little more elegance, hide the details:</p>
<pre><code>def getBSDIP():
from subprocess import Popen, PIPE
import string
CURRENT = Popen("/sbin/ifconfig fxp0", shell=True,stdout=PIPE).stdout.readlines()
return(string.split(CURRENT[3])[1])
</code></pre>
<p>If you are going to use subprocess to do this then elegance is a bit limited because you are essentially doing something like screenscraping, except here you are scriptscraping. If you want a truly general solution, use the socket library, i.e. let Python handle the portability.</p>
<p>Often, when you look at a bit of code and you wish that there was a better cleaner way to do it, this means that you need to question your assumptions, and change the algorithm or architecture of the solution.</p>
| 1 | 2009-10-20T00:14:42Z | [
"python",
"string",
"indexing",
"subprocess"
] |
Existence of a table generation framework for experiments | 1,591,864 | <p>I am running experiments on computer programs with a number of variables whose effect I am measuring. For each run, I record the time, the precision and the recall. </p>
<p>Are there any frameworks that exist that can help me with <strong>running tests and generating tables?</strong> I am currently using the Python CSV library to generate basic tables. However, things get complicated depending on how many variables you want to change, since the table format may have to be different.</p>
<p>For an illustration of various formats see <a href="http://spreadsheets.google.com/pub?key=trRdDhrzIc0xH-CRuP0Ml6g&output=html" rel="nofollow">http://spreadsheets.google.com/pub?key=trRdDhrzIc0xH-CRuP0Ml6g&output=html</a>. There are probably more formats that I am not aware of.</p>
<ul>
<li>I would prefer it to be written in Python, but frameworks in other languages (esp. Java/C++ as I know them) would be acceptable</li>
<li>This bounty is <strong>only</strong> for listing an existing framework(s) - no rolling your own!</li>
<li>Also, I need the answer within <strong>6 days</strong>, so the bounty will be awarded to the best answer Sunday night Australian time.</li>
<li>I've actually (finally) written my own framework, but I need to compare it against others.</li>
<li>Bounties are still valid for community wiki questions</li>
<li>This question is not about generating test data. It simply has to call the test function with appropriate arguments.</li>
<li>I am not just looking for a general tool like Matlab/Excel unless you can demonstrate that it has the functionality or provide the name of a plugin with suitable requirements.</li>
</ul>
| 0 | 2009-10-20T00:27:39Z | 1,592,273 | <p>I could be misunderstanding, but you appear to be concerned about the presentation and seem to want to get beyond a 2d table with just one axis per variable. As you point out, things get difficult with more variables. A spreadsheet is inherently 2d and the best you'll get with graphing is 3d. I'd bet you have more variables than that.</p>
<p>My suggestion is organizing your data as columns of variables & results. List one experiment per row. That is sure simple for python.csv to deal with.</p>
<p>Slice/sort/manipulate the info with the "Data->Auto Filter" in Excel or Open Office to see which variables are significant. Graph in simple line graphs to see the relations you may miss. Then, after you have your relations figured out you might find that a 2d table is good way to present the data. Maybe you can take the next step with numpy or matplotlib.</p>
<p>Hope this helps.</p>
| 4 | 2009-10-20T03:19:07Z | [
"java",
"c++",
"python",
"research"
] |
Existence of a table generation framework for experiments | 1,591,864 | <p>I am running experiments on computer programs with a number of variables whose effect I am measuring. For each run, I record the time, the precision and the recall. </p>
<p>Are there any frameworks that exist that can help me with <strong>running tests and generating tables?</strong> I am currently using the Python CSV library to generate basic tables. However, things get complicated depending on how many variables you want to change, since the table format may have to be different.</p>
<p>For an illustration of various formats see <a href="http://spreadsheets.google.com/pub?key=trRdDhrzIc0xH-CRuP0Ml6g&output=html" rel="nofollow">http://spreadsheets.google.com/pub?key=trRdDhrzIc0xH-CRuP0Ml6g&output=html</a>. There are probably more formats that I am not aware of.</p>
<ul>
<li>I would prefer it to be written in Python, but frameworks in other languages (esp. Java/C++ as I know them) would be acceptable</li>
<li>This bounty is <strong>only</strong> for listing an existing framework(s) - no rolling your own!</li>
<li>Also, I need the answer within <strong>6 days</strong>, so the bounty will be awarded to the best answer Sunday night Australian time.</li>
<li>I've actually (finally) written my own framework, but I need to compare it against others.</li>
<li>Bounties are still valid for community wiki questions</li>
<li>This question is not about generating test data. It simply has to call the test function with appropriate arguments.</li>
<li>I am not just looking for a general tool like Matlab/Excel unless you can demonstrate that it has the functionality or provide the name of a plugin with suitable requirements.</li>
</ul>
| 0 | 2009-10-20T00:27:39Z | 1,593,240 | <p>A good framework to automate testing is nose: <a href="http://somethingaboutorange.com/mrl/projects/nose/0.11.1/" rel="nofollow">http://somethingaboutorange.com/mrl/projects/nose/0.11.1/</a></p>
<p>It recognizes any function with the word 'tests_' in its name as a function. </p>
| -1 | 2009-10-20T08:45:00Z | [
"java",
"c++",
"python",
"research"
] |
Existence of a table generation framework for experiments | 1,591,864 | <p>I am running experiments on computer programs with a number of variables whose effect I am measuring. For each run, I record the time, the precision and the recall. </p>
<p>Are there any frameworks that exist that can help me with <strong>running tests and generating tables?</strong> I am currently using the Python CSV library to generate basic tables. However, things get complicated depending on how many variables you want to change, since the table format may have to be different.</p>
<p>For an illustration of various formats see <a href="http://spreadsheets.google.com/pub?key=trRdDhrzIc0xH-CRuP0Ml6g&output=html" rel="nofollow">http://spreadsheets.google.com/pub?key=trRdDhrzIc0xH-CRuP0Ml6g&output=html</a>. There are probably more formats that I am not aware of.</p>
<ul>
<li>I would prefer it to be written in Python, but frameworks in other languages (esp. Java/C++ as I know them) would be acceptable</li>
<li>This bounty is <strong>only</strong> for listing an existing framework(s) - no rolling your own!</li>
<li>Also, I need the answer within <strong>6 days</strong>, so the bounty will be awarded to the best answer Sunday night Australian time.</li>
<li>I've actually (finally) written my own framework, but I need to compare it against others.</li>
<li>Bounties are still valid for community wiki questions</li>
<li>This question is not about generating test data. It simply has to call the test function with appropriate arguments.</li>
<li>I am not just looking for a general tool like Matlab/Excel unless you can demonstrate that it has the functionality or provide the name of a plugin with suitable requirements.</li>
</ul>
| 0 | 2009-10-20T00:27:39Z | 1,629,112 | <p>If the number of variables or the number of possible values for each variable is even moderately large, the set of tests can quickly become unwieldy. In that case you probably want to consider reasonable coverage with a subset of the values. An example tool for generating a candidate set of tests is <a href="http://www.satisfice.com/tools.shtml" rel="nofollow">Allpairs</a> (perl, so you should be able to adapt it to your own needs if necessary). Not sure if this is the sort of "framework" you are looking for or not. See also <a href="http://code.google.com/p/csvtest/wiki/FAQ" rel="nofollow">csvtest</a>.</p>
<p>... I'll repeat here my comment that you should use one column per variable, one row per test (numbers pulled out of thin air below)</p>
<pre><code>a b c time precision recall
1 1 0 2 0.5 0.7
1 2 0 3 ...etc.
</code></pre>
<p>Not only is this simpler to inspect, but you can perform analysis on it (including the cross-sections in your example spreadsheet) in a fairly straightforward manner as well. Think of it as a single database table.</p>
| 2 | 2009-10-27T06:56:56Z | [
"java",
"c++",
"python",
"research"
] |
Existence of a table generation framework for experiments | 1,591,864 | <p>I am running experiments on computer programs with a number of variables whose effect I am measuring. For each run, I record the time, the precision and the recall. </p>
<p>Are there any frameworks that exist that can help me with <strong>running tests and generating tables?</strong> I am currently using the Python CSV library to generate basic tables. However, things get complicated depending on how many variables you want to change, since the table format may have to be different.</p>
<p>For an illustration of various formats see <a href="http://spreadsheets.google.com/pub?key=trRdDhrzIc0xH-CRuP0Ml6g&output=html" rel="nofollow">http://spreadsheets.google.com/pub?key=trRdDhrzIc0xH-CRuP0Ml6g&output=html</a>. There are probably more formats that I am not aware of.</p>
<ul>
<li>I would prefer it to be written in Python, but frameworks in other languages (esp. Java/C++ as I know them) would be acceptable</li>
<li>This bounty is <strong>only</strong> for listing an existing framework(s) - no rolling your own!</li>
<li>Also, I need the answer within <strong>6 days</strong>, so the bounty will be awarded to the best answer Sunday night Australian time.</li>
<li>I've actually (finally) written my own framework, but I need to compare it against others.</li>
<li>Bounties are still valid for community wiki questions</li>
<li>This question is not about generating test data. It simply has to call the test function with appropriate arguments.</li>
<li>I am not just looking for a general tool like Matlab/Excel unless you can demonstrate that it has the functionality or provide the name of a plugin with suitable requirements.</li>
</ul>
| 0 | 2009-10-20T00:27:39Z | 1,636,568 | <p>I think <a href="http://www.pytables.org/moin" rel="nofollow">PyTables</a> will do what you are looking for, and more. It lets you make HDF5 tables/files. Guessing from <a href="http://www.pytables.org/docs/manual/ch03.html#id323222" rel="nofollow">the examples in the documentation</a>, it was originally built for recording results from experiments. </p>
<p>It also allows you to <a href="http://www.pytables.org/docs/manual/ch03.html#id327136" rel="nofollow">nest columns</a>, which if I understand your google docs example correctly, will allow you keep all of your results in one table as you vary a, b <em>and</em> c.</p>
<p><strong>Edit:</strong>
You can define tables with dictionaries instead of classes. <a href="http://www.pytables.org/docs/manual/ch03.html#secondExample" rel="nofollow">Example</a>. <a href="http://www.pytables.org/docs/manual/ch04.html#createTableDescr" rel="nofollow">Documentation</a>. This will allow you to create a table with an appropriate number of columns based on values of 'a'. </p>
<p>Basically your definition of columns will look something like this:</p>
<pre><code>table_def = {'a1': Int32Col(pos=0), 'a2': Int32Col(pos=1), etc.}
</code></pre>
<p>Then, you'll add new records for each value of 'b'.</p>
| 1 | 2009-10-28T11:04:46Z | [
"java",
"c++",
"python",
"research"
] |
Existence of a table generation framework for experiments | 1,591,864 | <p>I am running experiments on computer programs with a number of variables whose effect I am measuring. For each run, I record the time, the precision and the recall. </p>
<p>Are there any frameworks that exist that can help me with <strong>running tests and generating tables?</strong> I am currently using the Python CSV library to generate basic tables. However, things get complicated depending on how many variables you want to change, since the table format may have to be different.</p>
<p>For an illustration of various formats see <a href="http://spreadsheets.google.com/pub?key=trRdDhrzIc0xH-CRuP0Ml6g&output=html" rel="nofollow">http://spreadsheets.google.com/pub?key=trRdDhrzIc0xH-CRuP0Ml6g&output=html</a>. There are probably more formats that I am not aware of.</p>
<ul>
<li>I would prefer it to be written in Python, but frameworks in other languages (esp. Java/C++ as I know them) would be acceptable</li>
<li>This bounty is <strong>only</strong> for listing an existing framework(s) - no rolling your own!</li>
<li>Also, I need the answer within <strong>6 days</strong>, so the bounty will be awarded to the best answer Sunday night Australian time.</li>
<li>I've actually (finally) written my own framework, but I need to compare it against others.</li>
<li>Bounties are still valid for community wiki questions</li>
<li>This question is not about generating test data. It simply has to call the test function with appropriate arguments.</li>
<li>I am not just looking for a general tool like Matlab/Excel unless you can demonstrate that it has the functionality or provide the name of a plugin with suitable requirements.</li>
</ul>
| 0 | 2009-10-20T00:27:39Z | 1,637,746 | <p>If you are only concerned with display, you could write an Excel file with <a href="http://pypi.python.org/pypi/xlwt" rel="nofollow">xlwt</a>. (<a href="http://panela.blog-city.com/pyexcelerator%5Fxlwt%5Fcheatsheet%5Fcreate%5Fnative%5Fexcel%5Ffrom%5Fpu.htm" rel="nofollow">cheatsheet</a>).</p>
<p>It can write xls files directly, without using Excel. </p>
<p>You can merge row label cells to group the results for each experiment. Or, just write one row per experiment, with each variable having its own column (as others have suggested) and use either a pivot table or sumproduct to shape the data into the desired format. </p>
| 1 | 2009-10-28T14:47:30Z | [
"java",
"c++",
"python",
"research"
] |
Existence of a table generation framework for experiments | 1,591,864 | <p>I am running experiments on computer programs with a number of variables whose effect I am measuring. For each run, I record the time, the precision and the recall. </p>
<p>Are there any frameworks that exist that can help me with <strong>running tests and generating tables?</strong> I am currently using the Python CSV library to generate basic tables. However, things get complicated depending on how many variables you want to change, since the table format may have to be different.</p>
<p>For an illustration of various formats see <a href="http://spreadsheets.google.com/pub?key=trRdDhrzIc0xH-CRuP0Ml6g&output=html" rel="nofollow">http://spreadsheets.google.com/pub?key=trRdDhrzIc0xH-CRuP0Ml6g&output=html</a>. There are probably more formats that I am not aware of.</p>
<ul>
<li>I would prefer it to be written in Python, but frameworks in other languages (esp. Java/C++ as I know them) would be acceptable</li>
<li>This bounty is <strong>only</strong> for listing an existing framework(s) - no rolling your own!</li>
<li>Also, I need the answer within <strong>6 days</strong>, so the bounty will be awarded to the best answer Sunday night Australian time.</li>
<li>I've actually (finally) written my own framework, but I need to compare it against others.</li>
<li>Bounties are still valid for community wiki questions</li>
<li>This question is not about generating test data. It simply has to call the test function with appropriate arguments.</li>
<li>I am not just looking for a general tool like Matlab/Excel unless you can demonstrate that it has the functionality or provide the name of a plugin with suitable requirements.</li>
</ul>
| 0 | 2009-10-20T00:27:39Z | 1,652,191 | <p>I believe Matlab to be perfect for generating and manipulating such tables. It treats the universe as vectors and matrices, and it's very high-level.<br />
Downsides:<br />
It's very expensive<br />
If you plan to automate the running of tests, integrating Matlab to what your test programs are running at might be hard.</p>
| 1 | 2009-10-30T20:40:49Z | [
"java",
"c++",
"python",
"research"
] |
Existence of a table generation framework for experiments | 1,591,864 | <p>I am running experiments on computer programs with a number of variables whose effect I am measuring. For each run, I record the time, the precision and the recall. </p>
<p>Are there any frameworks that exist that can help me with <strong>running tests and generating tables?</strong> I am currently using the Python CSV library to generate basic tables. However, things get complicated depending on how many variables you want to change, since the table format may have to be different.</p>
<p>For an illustration of various formats see <a href="http://spreadsheets.google.com/pub?key=trRdDhrzIc0xH-CRuP0Ml6g&output=html" rel="nofollow">http://spreadsheets.google.com/pub?key=trRdDhrzIc0xH-CRuP0Ml6g&output=html</a>. There are probably more formats that I am not aware of.</p>
<ul>
<li>I would prefer it to be written in Python, but frameworks in other languages (esp. Java/C++ as I know them) would be acceptable</li>
<li>This bounty is <strong>only</strong> for listing an existing framework(s) - no rolling your own!</li>
<li>Also, I need the answer within <strong>6 days</strong>, so the bounty will be awarded to the best answer Sunday night Australian time.</li>
<li>I've actually (finally) written my own framework, but I need to compare it against others.</li>
<li>Bounties are still valid for community wiki questions</li>
<li>This question is not about generating test data. It simply has to call the test function with appropriate arguments.</li>
<li>I am not just looking for a general tool like Matlab/Excel unless you can demonstrate that it has the functionality or provide the name of a plugin with suitable requirements.</li>
</ul>
| 0 | 2009-10-20T00:27:39Z | 1,653,264 | <p>I'm a little confused about exactly what you want to generate. Are you trying to just format tables, or actually generate the combinations of the values? In that case you'll want to look at design-of-experiment or test matrix generation tools like:</p>
<ul>
<li><a href="http://sourceforge.net/apps/trac/allpairs/" rel="nofollow">All Pairs (Python)</a></li>
<li><a href="http://people.sc.fsu.edu/~burkardt/m%5Fsrc/test%5Fmatrix/test%5Fmatrix.html" rel="nofollow">Test Matrix (Matlab)</a></li>
<li><a href="http://www.maths.manchester.ac.uk/~higham/mctoolbox/" rel="nofollow">Matrix Computation Toolbox (Matlab)</a></li>
<li>or the <a href="http://math.nist.gov/MatrixMarket/" rel="nofollow">Matrix Market at math.nist.gov</a></li>
</ul>
| 1 | 2009-10-31T03:02:49Z | [
"java",
"c++",
"python",
"research"
] |
Existence of a table generation framework for experiments | 1,591,864 | <p>I am running experiments on computer programs with a number of variables whose effect I am measuring. For each run, I record the time, the precision and the recall. </p>
<p>Are there any frameworks that exist that can help me with <strong>running tests and generating tables?</strong> I am currently using the Python CSV library to generate basic tables. However, things get complicated depending on how many variables you want to change, since the table format may have to be different.</p>
<p>For an illustration of various formats see <a href="http://spreadsheets.google.com/pub?key=trRdDhrzIc0xH-CRuP0Ml6g&output=html" rel="nofollow">http://spreadsheets.google.com/pub?key=trRdDhrzIc0xH-CRuP0Ml6g&output=html</a>. There are probably more formats that I am not aware of.</p>
<ul>
<li>I would prefer it to be written in Python, but frameworks in other languages (esp. Java/C++ as I know them) would be acceptable</li>
<li>This bounty is <strong>only</strong> for listing an existing framework(s) - no rolling your own!</li>
<li>Also, I need the answer within <strong>6 days</strong>, so the bounty will be awarded to the best answer Sunday night Australian time.</li>
<li>I've actually (finally) written my own framework, but I need to compare it against others.</li>
<li>Bounties are still valid for community wiki questions</li>
<li>This question is not about generating test data. It simply has to call the test function with appropriate arguments.</li>
<li>I am not just looking for a general tool like Matlab/Excel unless you can demonstrate that it has the functionality or provide the name of a plugin with suitable requirements.</li>
</ul>
| 0 | 2009-10-20T00:27:39Z | 1,654,603 | <p>Some things that I suggest that you look at are <a href="http://pyepl.sourceforge.net/" rel="nofollow">PyEPL</a>, the Python Experiment-Programming Library geared for psychology experiments, and this paper on <a href="http://gael-varoquaux.info/computers/agile%5Fcomputer%5Fcontrol%5Fof%5Fan%5Fexperiment.pdf" rel="nofollow">Agile Control of a Complex Experiment</a> which covers the authors experience in using Python for experiment control.</p>
<p>For internal manipulation of tables, you should be using NumPy and if you need to store them, then PyTables HDF5 format is widely used in science.</p>
<p><a href="http://www.cs.sandia.gov/DAKOTA/software.html" rel="nofollow">DAKOTA</a>(Design Analysis Kit for Optimization and Terascale Applications) may be what you are looking for. Not Python, but <a href="http://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/20080047741%5F2008047287.pdf" rel="nofollow">ROSE</a>(Repetitive Object-Oriented Simulation Environment) is also something to look at. Both of these incorporate Design of Experiments.</p>
| 1 | 2009-10-31T14:49:11Z | [
"java",
"c++",
"python",
"research"
] |
How do I go about setting up a TDD development process with Google App Engine? | 1,591,875 | <p>I'm primarily a Ruby guy, but lately I've been working on a lot of Python stuff, in particular, App Engine code. In Ruby, I'd use automated continuous integration (<a href="http://www.zenspider.com/ZSS/Products/ZenTest/">autotest</a>), code coverage tools (<a href="http://github.com/relevance/rcov">rcov</a>), static analysis (<a href="http://github.com/kevinrutherford/reek">reek</a>), and mutation testing (<a href="http://seattlerb.rubyforge.org/heckle/">heckle</a>) in my development process, but I'm not sure how best to set up a similar development process for an App Engine environment. I'd also be interested in analogs to <a href="http://rspec.info/">RSpec</a> and <a href="http://cukes.info/">Cucumber</a> for Python that could work in App Engine.</p>
| 15 | 2009-10-20T00:31:05Z | 1,592,003 | <p>You won't always find one to one equivalents of Ruby testing tools in Python, but there are some great testing tools in Python. Some of the tools that I've found useful include:</p>
<ul>
<li><a href="http://docs.python.org/library/unittest.html">unittest</a> - the xUnit tool included in the Python standard library. It includes all the basics for unit testing. </li>
<li><a href="http://docs.python.org/library/doctest.html">doctest</a> - an awesome part of the standard library, it allows you to write tests in the docstrings of functions, classes, modules, methods. It is great at conveying intended API usage. <a href="http://blog.ianbicking.org/behavior-driven-programming.html">Ian Bicking</a> suggests using doctest for Behavior Driven Development. Doctest fits very well into the <a href="http://sphinx.pocoo.org/">Sphinx</a> documentation system (you can make sure all the examples in your documentation pass every time you build the docs).</li>
<li><a href="http://somethingaboutorange.com/mrl/projects/nose/">nose</a> and <a href="http://codespeak.net/py/dist/test/">py.test</a> are seen as the next-gen versions of unittest. They can run all existing unittest cases, but allow for easier, non-class based unit tests. py.test also allows for distributed execution.</li>
<li><a href="http://www.voidspace.org.uk/python/mock.html">mock</a> is a nice library for mocking behavior.</li>
<li><a href="http://github.com/brunobord/tdaemon">tdaemon</a> watches a directory for updates to your code and will re-execute your test suite. (my <a href="http://github.com/johnpaulett/tdaemon">personal branch</a> contains a few unmerged improvements).</li>
<li><a href="http://buildbot.net/">Buildbot</a>, <a href="http://bitten.edgewall.org/">Bitten</a>, and even <a href="http://hudson-ci.org/">Hudson</a> all work well as full-fledged continuous integration servers for Python code. </li>
<li><a href="http://nedbatchelder.com/code/coverage/">coverage.py</a> computes the code coverage of your code.</li>
<li><a href="http://www.logilab.org/857">pylint</a> will provide a lint-like analysis of your code, making sure it follows common coding conventions and does not have any common bugs. There is also a "lighter" analysis tool, <a href="http://divmod.org/trac/wiki/DivmodPyflakes">PyFlakes</a>.</li>
<li>There are a number of HTTP / Browser testing tools that work well in Python, including <a href="http://twill.idyll.org/python-api.html">Twill</a>, <a href="http://seleniumhq.org/">Selenium</a>, and <a href="http://www.getwindmill.com/">Windmill</a>.</li>
</ul>
<p>If you are using Django on App Engine, it includes <a href="http://docs.djangoproject.com/en/dev/topics/testing/">several extensions</a> to unittest that allow you simulate an HTTP client and database persistence.</p>
<p>There are a ton of other tools that I have not used (such as <a href="http://www.codeplex.com/pyspec/">PySpec</a> and <a href="http://pypi.python.org/pypi/Behaviour">Behaviour</a>) that could also be helpful. I haven't seen any mutation testing tool in Python, but I bet there is one out there (I would love to learn what it is).</p>
<p>Happy testing!</p>
| 26 | 2009-10-20T01:25:29Z | [
"python",
"unit-testing",
"google-app-engine",
"tdd"
] |
How do I go about setting up a TDD development process with Google App Engine? | 1,591,875 | <p>I'm primarily a Ruby guy, but lately I've been working on a lot of Python stuff, in particular, App Engine code. In Ruby, I'd use automated continuous integration (<a href="http://www.zenspider.com/ZSS/Products/ZenTest/">autotest</a>), code coverage tools (<a href="http://github.com/relevance/rcov">rcov</a>), static analysis (<a href="http://github.com/kevinrutherford/reek">reek</a>), and mutation testing (<a href="http://seattlerb.rubyforge.org/heckle/">heckle</a>) in my development process, but I'm not sure how best to set up a similar development process for an App Engine environment. I'd also be interested in analogs to <a href="http://rspec.info/">RSpec</a> and <a href="http://cukes.info/">Cucumber</a> for Python that could work in App Engine.</p>
| 15 | 2009-10-20T00:31:05Z | 1,592,011 | <p>Haven't used App Engine, but my feeling for the most popular python testing tools is</p>
<ul>
<li><a href="http://docs.python.org/library/development.html" rel="nofollow">unittest/doctest</a> are the testing packages from the Python standard
library. unittest is the xUnit for python.</li>
<li><a href="http://somethingaboutorange.com/mrl/projects/nose/" rel="nofollow">nose</a> is a test runner/finder. It has many options, including
<code>--with-coverage</code>, which uses <a href="http://www.nedbatchelder.com/code/modules/coverage.html" rel="nofollow">coverage</a> to give you code coverage
reports.</li>
<li><a href="http://www.nedbatchelder.com/code/modules/coverage.html" rel="nofollow">pylint</a> is the most featureful lint-checker for python. Useful beyond
a syntax checker since it advises on unused variables/functions, when
methods should be functions, and more.</li>
<li><a href="http://jester.sourceforge.net/" rel="nofollow">pester</a> (mutation testing)</li>
<li><a href="http://buildbot.sourceforge.net/" rel="nofollow">buildbot</a> (continuous integration)</li>
</ul>
<p>You'll probably want to reference this (not quite complete) list of <a href="http://www.pycheesecake.org/wiki/PythonTestingToolsTaxonomy" rel="nofollow">Python
Testing Tools</a>.</p>
<p>For BDD, the field was thin last time I checked. Many of the true BDD tools
were not usable with nose and/or too limiting in the syntax they required.
You might have some luck with <a href="http://darcs.idyll.org/~t/projects/pinocchio/doc/#spec-generate-test-description-from-test-class-method-names" rel="nofollow">spec</a>, which is a BDD-like nose plugin.
Just found <a href="http://www.pyccuracy.org/" rel="nofollow">pyccuracy</a>, which looks a lot like cucumber, but I haven't
tried it.</p>
<p>For what its worth, I now just use <code>nosetests -v</code> (the nose runner with
--verbose), which will use the first line of the docstring in the test runner
output. That is, given a test like:</p>
<pre><code>class TestFoo(unittest.TestCase):
def testAnyNameHere(self):
""" Foo should be bar"""
foo = "bar"
self.assertEqual(foo, 'bar')
</code></pre>
<p>nosetests will give:</p>
<pre><code>$ nosetests -v
Foo should be bar... ok
-----------------------------
Ran 1 tests in 0.002s
OK
</code></pre>
| 3 | 2009-10-20T01:27:56Z | [
"python",
"unit-testing",
"google-app-engine",
"tdd"
] |
How do I go about setting up a TDD development process with Google App Engine? | 1,591,875 | <p>I'm primarily a Ruby guy, but lately I've been working on a lot of Python stuff, in particular, App Engine code. In Ruby, I'd use automated continuous integration (<a href="http://www.zenspider.com/ZSS/Products/ZenTest/">autotest</a>), code coverage tools (<a href="http://github.com/relevance/rcov">rcov</a>), static analysis (<a href="http://github.com/kevinrutherford/reek">reek</a>), and mutation testing (<a href="http://seattlerb.rubyforge.org/heckle/">heckle</a>) in my development process, but I'm not sure how best to set up a similar development process for an App Engine environment. I'd also be interested in analogs to <a href="http://rspec.info/">RSpec</a> and <a href="http://cukes.info/">Cucumber</a> for Python that could work in App Engine.</p>
| 15 | 2009-10-20T00:31:05Z | 1,592,108 | <p>On my GAE project, I use:</p>
<ul>
<li><a href="http://code.google.com/p/nose-gae/">NoseGAE</a>—This is the critical piece that ties all the rest together</li>
<li>Mock, as in John's excellent answer. I use this largely for AWS and other web services</li>
<li>Fixtures (the package, not the idea)</li>
</ul>
<p>I also prefer many of Rails's idioms. I broke my tests into unit, and functional using Python packages. You can run a subset of tests using <code>--tests=unit</code> or <code>--tests=functional</code>. It is all a bit more manual than Rails but at least I can unit test the hard stuff and make sure I never have regressions.</p>
<p>I also made a simple <code>FunctionalTest</code> class to do much of the very common actions in Rails, such as <code>assert_response</code> and <code>assert_xpath</code> (similar to assert_select).</p>
<pre><code>class FunctionalTest(Test):
def get(self, *args, **kw):
self.response = app.get(*args, **kw)
def post(self, *args, **kw):
self.response = app.post(*args, **kw)
def assert_response(self, expected):
pattern = str(expected) if re.search(r'^\d+$', expected) \
else (r'^\d+ %s' % expected)
assert re.search(pattern, self.response.status, re.IGNORECASE), \
'Response status was not "%s": %s' % (expected, self.response.status)
def assert_xpath(self, path, expected):
element = ElementTree.fromstring(self.response.body)
found_nodes = element.findall('.' + path)
if type(expected) is int:
assert_equal(expected, len(found_nodes))
elif type(expected) is str or type(expected) is unicode:
assert (True in [(node.text == expected) for node in found_nodes])
else:
raise Exception, "Unknown expected value: %r" % type(expected)
</code></pre>
<p>If you are doing lots of ListElement equality searches, definitely learn the <code>--tests=foo</code> syntax because testing for matching elements within a list is very slow.</p>
<p>Sometimes I like to load the Rails console against my fixture data to see what's going on in the test environment (i.e. <code>script/console test</code>). To do something similar with GAE, run dev_appserver.py with the parameter <code>--datastore_path="$TMPDIR/nosegae.datastore"</code> (or possibly substitute <code>/tmp</code> for <code>$TMPDIR</code>.</p>
| 15 | 2009-10-20T02:07:44Z | [
"python",
"unit-testing",
"google-app-engine",
"tdd"
] |
How do I go about setting up a TDD development process with Google App Engine? | 1,591,875 | <p>I'm primarily a Ruby guy, but lately I've been working on a lot of Python stuff, in particular, App Engine code. In Ruby, I'd use automated continuous integration (<a href="http://www.zenspider.com/ZSS/Products/ZenTest/">autotest</a>), code coverage tools (<a href="http://github.com/relevance/rcov">rcov</a>), static analysis (<a href="http://github.com/kevinrutherford/reek">reek</a>), and mutation testing (<a href="http://seattlerb.rubyforge.org/heckle/">heckle</a>) in my development process, but I'm not sure how best to set up a similar development process for an App Engine environment. I'd also be interested in analogs to <a href="http://rspec.info/">RSpec</a> and <a href="http://cukes.info/">Cucumber</a> for Python that could work in App Engine.</p>
| 15 | 2009-10-20T00:31:05Z | 8,238,153 | <p>It looks like another new option is <a href="http://pypi.python.org/pypi/agar" rel="nofollow">Agar</a>, which is based on <a href="http://code.google.com/appengine/docs/python/tools/localunittesting.html" rel="nofollow">google.appengine.ext.testbed</a>, part of the App Engine SDK. See <a href="http://www.recursion.org/2011/11/22/local-unit-testing-gae-with-agar" rel="nofollow">this blog post</a> for details.</p>
| 0 | 2011-11-23T06:32:54Z | [
"python",
"unit-testing",
"google-app-engine",
"tdd"
] |
Python binary data reading | 1,591,920 | <p>A urllib2 request receives binary response as below:</p>
<pre><code>00 00 00 01 00 04 41 4D 54 44 00 00 00 00 02 41
97 33 33 41 99 5C 29 41 90 3D 71 41 91 D7 0A 47
0F C6 14 00 00 01 16 6A E0 68 80 41 93 B4 05 41
97 1E B8 41 90 7A E1 41 96 8F 57 46 E6 2E 80 00
00 01 16 7A 53 7C 80 FF FF
</code></pre>
<p>Its structure is:</p>
<pre><code>DATA, TYPE, DESCRIPTION
00 00 00 01, 4 bytes, Symbol Count =1
00 04, 2 bytes, Symbol Length = 4
41 4D 54 44, 6 bytes, Symbol = AMTD
00, 1 byte, Error code = 0 (OK)
00 00 00 02, 4 bytes, Bar Count = 2
FIRST BAR
41 97 33 33, 4 bytes, Close = 18.90
41 99 5C 29, 4 bytes, High = 19.17
41 90 3D 71, 4 bytes, Low = 18.03
41 91 D7 0A, 4 bytes, Open = 18.23
47 0F C6 14, 4 bytes, Volume = 3,680,608
00 00 01 16 6A E0 68 80, 8 bytes, Timestamp = November 23,2007
SECOND BAR
41 93 B4 05, 4 bytes, Close = 18.4629
41 97 1E B8, 4 bytes, High = 18.89
41 90 7A E1, 4 bytes, Low = 18.06
41 96 8F 57, 4 bytes, Open = 18.82
46 E6 2E 80, 4 bytes, Volume = 2,946,325
00 00 01 16 7A 53 7C 80, 8 bytes, Timestamp = November 26,2007
TERMINATOR
FF FF, 2 bytes,
</code></pre>
<p>How to read binary data like this?</p>
<p>Thanks in advance.</p>
<h3>Update:</h3>
<p>I tried struct module on first 6 bytes with following code:</p>
<pre><code>struct.unpack('ih', response.read(6))
</code></pre>
<p>(16777216, 1024)</p>
<p>But it should output (1, 4). I take a look at the manual but have no clue what was wrong.</p>
| 3 | 2009-10-20T00:51:46Z | 1,591,926 | <p>Take a look at the <a href="http://docs.python.org/library/struct.html?#struct.unpack" rel="nofollow">struct.unpack</a> in the struct module.</p>
| 2 | 2009-10-20T00:54:39Z | [
"python",
"binary-data"
] |
Python binary data reading | 1,591,920 | <p>A urllib2 request receives binary response as below:</p>
<pre><code>00 00 00 01 00 04 41 4D 54 44 00 00 00 00 02 41
97 33 33 41 99 5C 29 41 90 3D 71 41 91 D7 0A 47
0F C6 14 00 00 01 16 6A E0 68 80 41 93 B4 05 41
97 1E B8 41 90 7A E1 41 96 8F 57 46 E6 2E 80 00
00 01 16 7A 53 7C 80 FF FF
</code></pre>
<p>Its structure is:</p>
<pre><code>DATA, TYPE, DESCRIPTION
00 00 00 01, 4 bytes, Symbol Count =1
00 04, 2 bytes, Symbol Length = 4
41 4D 54 44, 6 bytes, Symbol = AMTD
00, 1 byte, Error code = 0 (OK)
00 00 00 02, 4 bytes, Bar Count = 2
FIRST BAR
41 97 33 33, 4 bytes, Close = 18.90
41 99 5C 29, 4 bytes, High = 19.17
41 90 3D 71, 4 bytes, Low = 18.03
41 91 D7 0A, 4 bytes, Open = 18.23
47 0F C6 14, 4 bytes, Volume = 3,680,608
00 00 01 16 6A E0 68 80, 8 bytes, Timestamp = November 23,2007
SECOND BAR
41 93 B4 05, 4 bytes, Close = 18.4629
41 97 1E B8, 4 bytes, High = 18.89
41 90 7A E1, 4 bytes, Low = 18.06
41 96 8F 57, 4 bytes, Open = 18.82
46 E6 2E 80, 4 bytes, Volume = 2,946,325
00 00 01 16 7A 53 7C 80, 8 bytes, Timestamp = November 26,2007
TERMINATOR
FF FF, 2 bytes,
</code></pre>
<p>How to read binary data like this?</p>
<p>Thanks in advance.</p>
<h3>Update:</h3>
<p>I tried struct module on first 6 bytes with following code:</p>
<pre><code>struct.unpack('ih', response.read(6))
</code></pre>
<p>(16777216, 1024)</p>
<p>But it should output (1, 4). I take a look at the manual but have no clue what was wrong.</p>
| 3 | 2009-10-20T00:51:46Z | 1,591,935 | <p>Use pack/unpack functions from "struct" package. More info here <a href="http://docs.python.org/library/struct.html" rel="nofollow">http://docs.python.org/library/struct.html</a></p>
<p>Bye!</p>
| 1 | 2009-10-20T00:57:16Z | [
"python",
"binary-data"
] |
Python binary data reading | 1,591,920 | <p>A urllib2 request receives binary response as below:</p>
<pre><code>00 00 00 01 00 04 41 4D 54 44 00 00 00 00 02 41
97 33 33 41 99 5C 29 41 90 3D 71 41 91 D7 0A 47
0F C6 14 00 00 01 16 6A E0 68 80 41 93 B4 05 41
97 1E B8 41 90 7A E1 41 96 8F 57 46 E6 2E 80 00
00 01 16 7A 53 7C 80 FF FF
</code></pre>
<p>Its structure is:</p>
<pre><code>DATA, TYPE, DESCRIPTION
00 00 00 01, 4 bytes, Symbol Count =1
00 04, 2 bytes, Symbol Length = 4
41 4D 54 44, 6 bytes, Symbol = AMTD
00, 1 byte, Error code = 0 (OK)
00 00 00 02, 4 bytes, Bar Count = 2
FIRST BAR
41 97 33 33, 4 bytes, Close = 18.90
41 99 5C 29, 4 bytes, High = 19.17
41 90 3D 71, 4 bytes, Low = 18.03
41 91 D7 0A, 4 bytes, Open = 18.23
47 0F C6 14, 4 bytes, Volume = 3,680,608
00 00 01 16 6A E0 68 80, 8 bytes, Timestamp = November 23,2007
SECOND BAR
41 93 B4 05, 4 bytes, Close = 18.4629
41 97 1E B8, 4 bytes, High = 18.89
41 90 7A E1, 4 bytes, Low = 18.06
41 96 8F 57, 4 bytes, Open = 18.82
46 E6 2E 80, 4 bytes, Volume = 2,946,325
00 00 01 16 7A 53 7C 80, 8 bytes, Timestamp = November 26,2007
TERMINATOR
FF FF, 2 bytes,
</code></pre>
<p>How to read binary data like this?</p>
<p>Thanks in advance.</p>
<h3>Update:</h3>
<p>I tried struct module on first 6 bytes with following code:</p>
<pre><code>struct.unpack('ih', response.read(6))
</code></pre>
<p>(16777216, 1024)</p>
<p>But it should output (1, 4). I take a look at the manual but have no clue what was wrong.</p>
| 3 | 2009-10-20T00:51:46Z | 1,592,172 | <blockquote>
<pre><code>>>> struct.unpack('ih', response.read(6))
(16777216, 1024)
</code></pre>
</blockquote>
<p>You are unpacking big-endian data on a little-endian machine. Try this instead:</p>
<pre><code>>>> struct.unpack('!IH', response.read(6))
(1L, 4)
</code></pre>
<p>This tells unpack to consider the data in network-order (big-endian). Also, the values of counts and lengths can not be negative, so you should should use the unsigned variants in your format string.</p>
| 5 | 2009-10-20T02:34:44Z | [
"python",
"binary-data"
] |
Python binary data reading | 1,591,920 | <p>A urllib2 request receives binary response as below:</p>
<pre><code>00 00 00 01 00 04 41 4D 54 44 00 00 00 00 02 41
97 33 33 41 99 5C 29 41 90 3D 71 41 91 D7 0A 47
0F C6 14 00 00 01 16 6A E0 68 80 41 93 B4 05 41
97 1E B8 41 90 7A E1 41 96 8F 57 46 E6 2E 80 00
00 01 16 7A 53 7C 80 FF FF
</code></pre>
<p>Its structure is:</p>
<pre><code>DATA, TYPE, DESCRIPTION
00 00 00 01, 4 bytes, Symbol Count =1
00 04, 2 bytes, Symbol Length = 4
41 4D 54 44, 6 bytes, Symbol = AMTD
00, 1 byte, Error code = 0 (OK)
00 00 00 02, 4 bytes, Bar Count = 2
FIRST BAR
41 97 33 33, 4 bytes, Close = 18.90
41 99 5C 29, 4 bytes, High = 19.17
41 90 3D 71, 4 bytes, Low = 18.03
41 91 D7 0A, 4 bytes, Open = 18.23
47 0F C6 14, 4 bytes, Volume = 3,680,608
00 00 01 16 6A E0 68 80, 8 bytes, Timestamp = November 23,2007
SECOND BAR
41 93 B4 05, 4 bytes, Close = 18.4629
41 97 1E B8, 4 bytes, High = 18.89
41 90 7A E1, 4 bytes, Low = 18.06
41 96 8F 57, 4 bytes, Open = 18.82
46 E6 2E 80, 4 bytes, Volume = 2,946,325
00 00 01 16 7A 53 7C 80, 8 bytes, Timestamp = November 26,2007
TERMINATOR
FF FF, 2 bytes,
</code></pre>
<p>How to read binary data like this?</p>
<p>Thanks in advance.</p>
<h3>Update:</h3>
<p>I tried struct module on first 6 bytes with following code:</p>
<pre><code>struct.unpack('ih', response.read(6))
</code></pre>
<p>(16777216, 1024)</p>
<p>But it should output (1, 4). I take a look at the manual but have no clue what was wrong.</p>
| 3 | 2009-10-20T00:51:46Z | 1,592,173 | <p>As it was already mentioned, <code>struct</code> is the module you need to use.</p>
<p>Please read its documentation to learn about byte ordering, etc.</p>
<p>In your example you need to do the following (as your data is big-endian and unsigned):</p>
<pre><code>>>> import struct
>>> x = '\x00\x00\x00\x01\x00\x04'
>>> struct.unpack('>IH', x)
(1, 4)
</code></pre>
| 0 | 2009-10-20T02:34:52Z | [
"python",
"binary-data"
] |
Python binary data reading | 1,591,920 | <p>A urllib2 request receives binary response as below:</p>
<pre><code>00 00 00 01 00 04 41 4D 54 44 00 00 00 00 02 41
97 33 33 41 99 5C 29 41 90 3D 71 41 91 D7 0A 47
0F C6 14 00 00 01 16 6A E0 68 80 41 93 B4 05 41
97 1E B8 41 90 7A E1 41 96 8F 57 46 E6 2E 80 00
00 01 16 7A 53 7C 80 FF FF
</code></pre>
<p>Its structure is:</p>
<pre><code>DATA, TYPE, DESCRIPTION
00 00 00 01, 4 bytes, Symbol Count =1
00 04, 2 bytes, Symbol Length = 4
41 4D 54 44, 6 bytes, Symbol = AMTD
00, 1 byte, Error code = 0 (OK)
00 00 00 02, 4 bytes, Bar Count = 2
FIRST BAR
41 97 33 33, 4 bytes, Close = 18.90
41 99 5C 29, 4 bytes, High = 19.17
41 90 3D 71, 4 bytes, Low = 18.03
41 91 D7 0A, 4 bytes, Open = 18.23
47 0F C6 14, 4 bytes, Volume = 3,680,608
00 00 01 16 6A E0 68 80, 8 bytes, Timestamp = November 23,2007
SECOND BAR
41 93 B4 05, 4 bytes, Close = 18.4629
41 97 1E B8, 4 bytes, High = 18.89
41 90 7A E1, 4 bytes, Low = 18.06
41 96 8F 57, 4 bytes, Open = 18.82
46 E6 2E 80, 4 bytes, Volume = 2,946,325
00 00 01 16 7A 53 7C 80, 8 bytes, Timestamp = November 26,2007
TERMINATOR
FF FF, 2 bytes,
</code></pre>
<p>How to read binary data like this?</p>
<p>Thanks in advance.</p>
<h3>Update:</h3>
<p>I tried struct module on first 6 bytes with following code:</p>
<pre><code>struct.unpack('ih', response.read(6))
</code></pre>
<p>(16777216, 1024)</p>
<p>But it should output (1, 4). I take a look at the manual but have no clue what was wrong.</p>
| 3 | 2009-10-20T00:51:46Z | 1,592,340 | <pre><code>>>> data
'\x00\x00\x00\x01\x00\x04AMTD\x00\x00\x00\x00\x02A\x9733A\x99\\)A\x90=qA\x91\xd7\nG\x0f\xc6\x14\x00\x00\x01\x16j\xe0h\x80A\x93\xb4\x05A\x97\x1e\xb8A\x90z\xe1A\x96\x8fWF\xe6.\x80\x00\x00\x01\x16zS|\x80\xff\xff'
>>> from struct import unpack, calcsize
>>> scount, slength = unpack("!IH", data[:6])
>>> assert scount == 1
>>> symbol, error_code = unpack("!%dsb" % slength, data[6:6+slength+1])
>>> assert error_code == 0
>>> symbol
'AMTD'
>>> bar_count = unpack("!I", data[6+slength+1:6+slength+1+4])
>>> bar_count
(2,)
>>> bar_format = "!5fQ"
>>> from collections import namedtuple
>>> Bar = namedtuple("Bar", "Close High Low Open Volume Timestamp")
>>> b = Bar(*unpack(bar_format, data[6+slength+1+4:6+slength+1+4+calcsize(bar_format)]))
>>> b
Bar(Close=18.899999618530273, High=19.170000076293945, Low=18.030000686645508, Open=18.229999542236328, Volume=36806.078125, Timestamp=1195794000000L)
>>> import time
>>> time.ctime(b.Timestamp//1000)
'Fri Nov 23 08:00:00 2007'
>>> int(b.Volume*100 + 0.5)
3680608
</code></pre>
| 6 | 2009-10-20T03:51:26Z | [
"python",
"binary-data"
] |
Python binary data reading | 1,591,920 | <p>A urllib2 request receives binary response as below:</p>
<pre><code>00 00 00 01 00 04 41 4D 54 44 00 00 00 00 02 41
97 33 33 41 99 5C 29 41 90 3D 71 41 91 D7 0A 47
0F C6 14 00 00 01 16 6A E0 68 80 41 93 B4 05 41
97 1E B8 41 90 7A E1 41 96 8F 57 46 E6 2E 80 00
00 01 16 7A 53 7C 80 FF FF
</code></pre>
<p>Its structure is:</p>
<pre><code>DATA, TYPE, DESCRIPTION
00 00 00 01, 4 bytes, Symbol Count =1
00 04, 2 bytes, Symbol Length = 4
41 4D 54 44, 6 bytes, Symbol = AMTD
00, 1 byte, Error code = 0 (OK)
00 00 00 02, 4 bytes, Bar Count = 2
FIRST BAR
41 97 33 33, 4 bytes, Close = 18.90
41 99 5C 29, 4 bytes, High = 19.17
41 90 3D 71, 4 bytes, Low = 18.03
41 91 D7 0A, 4 bytes, Open = 18.23
47 0F C6 14, 4 bytes, Volume = 3,680,608
00 00 01 16 6A E0 68 80, 8 bytes, Timestamp = November 23,2007
SECOND BAR
41 93 B4 05, 4 bytes, Close = 18.4629
41 97 1E B8, 4 bytes, High = 18.89
41 90 7A E1, 4 bytes, Low = 18.06
41 96 8F 57, 4 bytes, Open = 18.82
46 E6 2E 80, 4 bytes, Volume = 2,946,325
00 00 01 16 7A 53 7C 80, 8 bytes, Timestamp = November 26,2007
TERMINATOR
FF FF, 2 bytes,
</code></pre>
<p>How to read binary data like this?</p>
<p>Thanks in advance.</p>
<h3>Update:</h3>
<p>I tried struct module on first 6 bytes with following code:</p>
<pre><code>struct.unpack('ih', response.read(6))
</code></pre>
<p>(16777216, 1024)</p>
<p>But it should output (1, 4). I take a look at the manual but have no clue what was wrong.</p>
| 3 | 2009-10-20T00:51:46Z | 1,592,361 | <p>So here's my best shot at interpreting the data you're giving...:</p>
<pre><code>import datetime
import struct
class Printable(object):
specials = ()
def __str__(self):
resultlines = []
for pair in self.__dict__.items():
if pair[0] in self.specials: continue
resultlines.append('%10s %s' % pair)
return '\n'.join(resultlines)
head_fmt = '>IH6sBH'
head_struct = struct.Struct(head_fmt)
class Header(Printable):
specials = ('bars',)
def __init__(self, symbol_count, symbol_length,
symbol, error_code, bar_count):
self.__dict__.update(locals())
self.bars = []
del self.self
bar_fmt = '>5fQ'
bar_struct = struct.Struct(bar_fmt)
class Bar(Printable):
specials = ('header',)
def __init__(self, header, close, high, low,
open, volume, timestamp):
self.__dict__.update(locals())
self.header.bars.append(self)
del self.self
self.timestamp /= 1000.0
self.timestamp = datetime.date.fromtimestamp(self.timestamp)
def showdata(data):
terminator = '\xff' * 2
assert data[-2:] == terminator
head_data = head_struct.unpack(data[:head_struct.size])
try:
assert head_data[4] * bar_struct.size + head_struct.size == \
len(data) - len(terminator)
except AssertionError:
print 'data length is %d' % len(data)
print 'head struct size is %d' % head_struct.size
print 'bar struct size is %d' % bar_struct.size
print 'number of bars is %d' % head_data[4]
print 'head data:', head_data
print 'terminator:', terminator
print 'so, something is wrong, since',
print head_data[4] * bar_struct.size + head_struct.size, '!=',
print len(data) - len(terminator)
raise
head = Header(*head_data)
for i in range(head.bar_count):
bar_substr = data[head_struct.size + i * bar_struct.size:
head_struct.size + (i+1) * bar_struct.size]
bar_data = bar_struct.unpack(bar_substr)
Bar(head, *bar_data)
assert len(head.bars) == head.bar_count
print head
for i, x in enumerate(head.bars):
print 'Bar #%s' % i
print x
datas = '''
00 00 00 01 00 04 41 4D 54 44 00 00 00 00 02 41
97 33 33 41 99 5C 29 41 90 3D 71 41 91 D7 0A 47
0F C6 14 00 00 01 16 6A E0 68 80 41 93 B4 05 41
97 1E B8 41 90 7A E1 41 96 8F 57 46 E6 2E 80 00
00 01 16 7A 53 7C 80 FF FF
'''
data = ''.join(chr(int(x, 16)) for x in datas.split())
showdata(data)
</code></pre>
<p>this emits:</p>
<pre><code>symbol_count 1
bar_count 2
symbol AMTD
error_code 0
symbol_length 4
Bar #0
volume 36806.078125
timestamp 2007-11-22
high 19.1700000763
low 18.0300006866
close 18.8999996185
open 18.2299995422
Bar #1
volume 29463.25
timestamp 2007-11-25
high 18.8899993896
low 18.0599994659
close 18.4629001617
open 18.8199901581
</code></pre>
<p>...which seems to be pretty close to what you want, net of some output formatting details. Hope this helps!-)</p>
| 10 | 2009-10-20T04:00:48Z | [
"python",
"binary-data"
] |
A simple framework for Google App Engine (like Sinatra)? | 1,592,088 | <p>Is there a simple 'wrapper' framework for appengine? Something like <a href="http://www.sinatrarb.com/" rel="nofollow">Sinatra</a> or <a href="http://github.com/breily/juno" rel="nofollow">Juno</a>? So that one can write code like the following:</p>
<pre><code>from juno import *
@route('/')
def index(web):
return 'Juno says hi'
run()
</code></pre>
<p><strong>UPDATE</strong>: I want to use the Python API (not Java) in GAE.</p>
| 5 | 2009-10-20T01:59:57Z | 1,592,189 | <p>You should check out <a href="http://gaelyk.appspot.com/" rel="nofollow">gaelyk</a>. It's a lightweight framework on top of appengine that uses groovy.</p>
| 0 | 2009-10-20T02:43:41Z | [
"python",
"google-app-engine",
"web-frameworks"
] |
A simple framework for Google App Engine (like Sinatra)? | 1,592,088 | <p>Is there a simple 'wrapper' framework for appengine? Something like <a href="http://www.sinatrarb.com/" rel="nofollow">Sinatra</a> or <a href="http://github.com/breily/juno" rel="nofollow">Juno</a>? So that one can write code like the following:</p>
<pre><code>from juno import *
@route('/')
def index(web):
return 'Juno says hi'
run()
</code></pre>
<p><strong>UPDATE</strong>: I want to use the Python API (not Java) in GAE.</p>
| 5 | 2009-10-20T01:59:57Z | 1,592,249 | <p>No such framework has been released at this time, to the best of my knowledge (most people appear to be quite happy with Django I guess;-). You could try using Juno with <a href="http://gist.github.com/140565" rel="nofollow">this patch</a> -- it doesn't seem to be quite ready for prime time, but then again, it IS a pretty tiny patch, maybe little more is needed to allow Juno to work entirely on GAE!</p>
| 2 | 2009-10-20T03:08:36Z | [
"python",
"google-app-engine",
"web-frameworks"
] |
A simple framework for Google App Engine (like Sinatra)? | 1,592,088 | <p>Is there a simple 'wrapper' framework for appengine? Something like <a href="http://www.sinatrarb.com/" rel="nofollow">Sinatra</a> or <a href="http://github.com/breily/juno" rel="nofollow">Juno</a>? So that one can write code like the following:</p>
<pre><code>from juno import *
@route('/')
def index(web):
return 'Juno says hi'
run()
</code></pre>
<p><strong>UPDATE</strong>: I want to use the Python API (not Java) in GAE.</p>
| 5 | 2009-10-20T01:59:57Z | 1,592,866 | <p>Another framework that I've been meaning to try out is <a href="http://bloog.billkatz.com/" rel="nofollow">Bloog</a>. It is actually a blog engine for GAE but also provides a framework for developing other GAE apps.</p>
| 1 | 2009-10-20T06:50:36Z | [
"python",
"google-app-engine",
"web-frameworks"
] |
A simple framework for Google App Engine (like Sinatra)? | 1,592,088 | <p>Is there a simple 'wrapper' framework for appengine? Something like <a href="http://www.sinatrarb.com/" rel="nofollow">Sinatra</a> or <a href="http://github.com/breily/juno" rel="nofollow">Juno</a>? So that one can write code like the following:</p>
<pre><code>from juno import *
@route('/')
def index(web):
return 'Juno says hi'
run()
</code></pre>
<p><strong>UPDATE</strong>: I want to use the Python API (not Java) in GAE.</p>
| 5 | 2009-10-20T01:59:57Z | 1,593,340 | <p>I use <a href="http://webpy.org/" rel="nofollow">web.py</a>. It's really simple and doesn't get in your way.</p>
<p>This is how it looks:</p>
<pre><code>import web
urls = (
'/(.*)', 'hello'
)
app = web.application(urls, globals())
class hello:
def GET(self, name):
if not name:
name = 'world'
return 'Hello, ' + name + '!'
if __name__ == "__main__":
app.run()
</code></pre>
| 2 | 2009-10-20T09:04:04Z | [
"python",
"google-app-engine",
"web-frameworks"
] |
A simple framework for Google App Engine (like Sinatra)? | 1,592,088 | <p>Is there a simple 'wrapper' framework for appengine? Something like <a href="http://www.sinatrarb.com/" rel="nofollow">Sinatra</a> or <a href="http://github.com/breily/juno" rel="nofollow">Juno</a>? So that one can write code like the following:</p>
<pre><code>from juno import *
@route('/')
def index(web):
return 'Juno says hi'
run()
</code></pre>
<p><strong>UPDATE</strong>: I want to use the Python API (not Java) in GAE.</p>
| 5 | 2009-10-20T01:59:57Z | 1,593,411 | <p>There are several frameworks either specifically for App Engine, or well suited to it:</p>
<ul>
<li><a href="http://webpy.org/">web.py</a> - Not specifically for App Engine, but well suited.</li>
<li><a href="http://code.google.com/p/google-app-engine-oil/">Google App Engine Oil</a></li>
<li><a href="http://code.google.com/p/web2py/">web2py</a> - Also not specifically for App Engine</li>
<li><a href="http://code.google.com/p/pyxer/">pyxer</a></li>
<li><a href="http://code.google.com/p/kay-framework/">kay</a></li>
<li><a href="http://code.google.com/p/tipfy/">tipfy</a></li>
</ul>
| 7 | 2009-10-20T09:21:32Z | [
"python",
"google-app-engine",
"web-frameworks"
] |
A simple framework for Google App Engine (like Sinatra)? | 1,592,088 | <p>Is there a simple 'wrapper' framework for appengine? Something like <a href="http://www.sinatrarb.com/" rel="nofollow">Sinatra</a> or <a href="http://github.com/breily/juno" rel="nofollow">Juno</a>? So that one can write code like the following:</p>
<pre><code>from juno import *
@route('/')
def index(web):
return 'Juno says hi'
run()
</code></pre>
<p><strong>UPDATE</strong>: I want to use the Python API (not Java) in GAE.</p>
| 5 | 2009-10-20T01:59:57Z | 4,366,792 | <p><a href="http://bottle.paws.de/docs/dev/index.html" rel="nofollow">Bottle</a> is one-single-file framework, so it's very easy to deploy it on GAE.</p>
<p>Bottle is similar with Sinatra, see the "hello world" example below:</p>
<p>Sinatra:</p>
<pre><code>require 'sinatra'
get '/hi' do
"Hello World!"
end
</code></pre>
<p>Bottle:</p>
<pre><code>from bottle import *
@get('/hi')
def hi():
return "Hello World!"
</code></pre>
<p>Though I have to admit that Ruby is better for DSL.</p>
| 1 | 2010-12-06T13:22:40Z | [
"python",
"google-app-engine",
"web-frameworks"
] |
Subclass lookup | 1,592,089 | <p>(I'm developing in Python 3.1, so if there's some shiny new 3.x feature I should know about for this, please let me know!)</p>
<p>I've got a class (we'll just call it "Packet") that serves as the parent for a bunch of child classes representing each of a few dozen packet types in a legacy client-server protocol over which I have no control. (The packets often have wildly differing behavior, so I just gave them each their own class to make my life easier.)</p>
<p>When receiving a packet, I'll have a simple "dispatch" function that checks the packet header to determine the type, then hands it off to the class that knows how to deal with it.</p>
<p>I do <em>not</em> want to maintain the lookup table by hand -- it's inelegant and just asking for trouble. Instead, I'd like the table built at runtime by examining all of the subclasses of Packet, which will have class variables specifying what packet type they correspond to, e.g.:</p>
<pre><code>class Login(Packet):
type_id = 0x01
</code></pre>
<p>I thought, of course, about iterating through <code>object.__subclasses__()</code>, but I've found slightly varying viewpoints on the safety and propriety of using it for things like this, including implications that it is implementation-specific and may not work in places other than CPython, and that it may disappear from CPython in the future. Am I being too paranoid? Is __subclassess__ considered a "real" part of the language now?</p>
<p>If not, what's a good "pythonic" way to approach this?</p>
| 0 | 2009-10-20T02:00:03Z | 1,592,110 | <p>"I'd like the table built at runtime by examining all of the subclasses of Packet," </p>
<p>This is guaranteed to cause endless problems. This kind of thing puts a strange constraint on your subclasses. You can't use any abstract superclasses to simplify things.</p>
<p>Here's a specific example of what won't work if you "automatically" discover the subclasses.</p>
<pre><code>class MessagePacket( object ):
"""superclass. Ignore me, I'm abstract."""
class Type_01( MessagePacket ):
type_id = 0x01
class Type_023( MessagePacket ):
"""superclass with common features for type 2 and 3. Ignore me, I'm abstract."""
class Type_02( Type_023 ):
type_id = 0x02
class Type_03( Type_023 ):
type_id = 0x03
class Type_04( MessagePacket ):
"""superclass for subtypes of 4. Ignore me, I'm abstract."""
type_id = 0x04
class Type_04A( Type_04 ):
discriminator = lambda x: x[23] == 'a' or x[35] == 42
class Type_04B( Type_04 ):
discriminator = lambda x: True
</code></pre>
<p>That should be enough to show that "automatic discovery" is doomed from the outset.</p>
<p>The correct solution is to have a <strong>Factory</strong> class which embodies the correct subclass hierarchy, exploiting all features based on -- well -- manual design.</p>
<pre><code>class Factory( object ):
def __init__( self, *subclass_list ):
self.subclass = dict( (s.type_id,s) for s in subclass_list )
def parse( self, packet ):
if packet.type_id == 04:
# special subclass logic
return self.subclass[packet.type_id]( packet )
</code></pre>
<p>It doesn't seem too onerous a burden to include the following:</p>
<pre><code>factory= Factory( Subclass1, Subclass2, ... SubclassN )
</code></pre>
<p>And when you add subclasses, add to the list of subclasses that are <em>actually</em> being used.</p>
| 3 | 2009-10-20T02:08:05Z | [
"python",
"python-3.x"
] |
Subclass lookup | 1,592,089 | <p>(I'm developing in Python 3.1, so if there's some shiny new 3.x feature I should know about for this, please let me know!)</p>
<p>I've got a class (we'll just call it "Packet") that serves as the parent for a bunch of child classes representing each of a few dozen packet types in a legacy client-server protocol over which I have no control. (The packets often have wildly differing behavior, so I just gave them each their own class to make my life easier.)</p>
<p>When receiving a packet, I'll have a simple "dispatch" function that checks the packet header to determine the type, then hands it off to the class that knows how to deal with it.</p>
<p>I do <em>not</em> want to maintain the lookup table by hand -- it's inelegant and just asking for trouble. Instead, I'd like the table built at runtime by examining all of the subclasses of Packet, which will have class variables specifying what packet type they correspond to, e.g.:</p>
<pre><code>class Login(Packet):
type_id = 0x01
</code></pre>
<p>I thought, of course, about iterating through <code>object.__subclasses__()</code>, but I've found slightly varying viewpoints on the safety and propriety of using it for things like this, including implications that it is implementation-specific and may not work in places other than CPython, and that it may disappear from CPython in the future. Am I being too paranoid? Is __subclassess__ considered a "real" part of the language now?</p>
<p>If not, what's a good "pythonic" way to approach this?</p>
| 0 | 2009-10-20T02:00:03Z | 1,592,119 | <p>I guess you can use Python metaclasses (Python ⥠2.2) to share such an information between classes, that would be quite pythonic. Take a look at the implementation of the Google's <a href="http://code.google.com/p/protobuf/" rel="nofollow">Protocol Buffers</a>. Here is <a href="http://code.google.com/apis/protocolbuffers/docs/pythontutorial.html" rel="nofollow">the tutorial</a> showing metaclasses at work. By the way, the domain of Protocol Buffers is similar to yours.</p>
| 1 | 2009-10-20T02:11:51Z | [
"python",
"python-3.x"
] |
Subclass lookup | 1,592,089 | <p>(I'm developing in Python 3.1, so if there's some shiny new 3.x feature I should know about for this, please let me know!)</p>
<p>I've got a class (we'll just call it "Packet") that serves as the parent for a bunch of child classes representing each of a few dozen packet types in a legacy client-server protocol over which I have no control. (The packets often have wildly differing behavior, so I just gave them each their own class to make my life easier.)</p>
<p>When receiving a packet, I'll have a simple "dispatch" function that checks the packet header to determine the type, then hands it off to the class that knows how to deal with it.</p>
<p>I do <em>not</em> want to maintain the lookup table by hand -- it's inelegant and just asking for trouble. Instead, I'd like the table built at runtime by examining all of the subclasses of Packet, which will have class variables specifying what packet type they correspond to, e.g.:</p>
<pre><code>class Login(Packet):
type_id = 0x01
</code></pre>
<p>I thought, of course, about iterating through <code>object.__subclasses__()</code>, but I've found slightly varying viewpoints on the safety and propriety of using it for things like this, including implications that it is implementation-specific and may not work in places other than CPython, and that it may disappear from CPython in the future. Am I being too paranoid? Is __subclassess__ considered a "real" part of the language now?</p>
<p>If not, what's a good "pythonic" way to approach this?</p>
| 0 | 2009-10-20T02:00:03Z | 1,592,235 | <pre><code>
>>> class PacketMeta(type):
... def __init__(self,*args,**kw):
... if self.type_id is not None:
... self.subclasses[self.type_id]=self
... return type.__init__(self,*args,**kw)
...
>>> class Packet(object):
... __metaclass__=PacketMeta
... subclasses={}
... type_id = None
...
>>> class Login(Packet):
... type_id = 0x01
...
>>> class Logout(Packet):
... type_id = 0x02
...
>>>
>>> Packet.subclasses
{1: <class '__main__.Login'>, 2: <class '__main__.Logout'>}
>>>
</code></pre>
<p>If you prefer to use the <code>__subclasses__()</code> you can do something like this</p>
<pre><code>>>> class Packet(object):
... pass
...
>>> class Login(Packet):
... type_id = 0x01
...
>>> class Logout(Packet):
... type_id = 0x02
...
def packetfactory(packet_id):
for x in Packet.__subclasses__():
if x.type_id==packet_id:
return x
...
>>> packetfactory(0x01)
<class '__main__.Login'>
>>> packetfactory(0x02)
<class '__main__.Logout'>
</code></pre>
| 2 | 2009-10-20T03:01:33Z | [
"python",
"python-3.x"
] |
Subclass lookup | 1,592,089 | <p>(I'm developing in Python 3.1, so if there's some shiny new 3.x feature I should know about for this, please let me know!)</p>
<p>I've got a class (we'll just call it "Packet") that serves as the parent for a bunch of child classes representing each of a few dozen packet types in a legacy client-server protocol over which I have no control. (The packets often have wildly differing behavior, so I just gave them each their own class to make my life easier.)</p>
<p>When receiving a packet, I'll have a simple "dispatch" function that checks the packet header to determine the type, then hands it off to the class that knows how to deal with it.</p>
<p>I do <em>not</em> want to maintain the lookup table by hand -- it's inelegant and just asking for trouble. Instead, I'd like the table built at runtime by examining all of the subclasses of Packet, which will have class variables specifying what packet type they correspond to, e.g.:</p>
<pre><code>class Login(Packet):
type_id = 0x01
</code></pre>
<p>I thought, of course, about iterating through <code>object.__subclasses__()</code>, but I've found slightly varying viewpoints on the safety and propriety of using it for things like this, including implications that it is implementation-specific and may not work in places other than CPython, and that it may disappear from CPython in the future. Am I being too paranoid? Is __subclassess__ considered a "real" part of the language now?</p>
<p>If not, what's a good "pythonic" way to approach this?</p>
| 0 | 2009-10-20T02:00:03Z | 1,592,240 | <p><code>__subclasses__</code> IS part of the Python language, and implemented by IronPython and Jython as well as CPython (no pypy at hand to test, right now, but I'd be astonished if they have broken that!-). Whatever gave you the impression that <code>__subclasses__</code> was at all problematic?! I see a comment by @gnibbler in the same vein and I'd like to challenge that: can you post URLs about <code>__subclasses__</code> not being a crucial part of the Python language?!</p>
| 3 | 2009-10-20T03:02:46Z | [
"python",
"python-3.x"
] |
Convert hex to float | 1,592,158 | <p>How to convert the following hex string to float (single precision 32-bit) in Python?</p>
<pre><code>"41973333" -> 1.88999996185302734375E1
"41995C29" -> 1.91700000762939453125E1
"470FC614" -> 3.6806078125E4
</code></pre>
| 20 | 2009-10-20T02:32:02Z | 1,592,179 | <p>I'm guessing this question relates to <a href="http://stackoverflow.com/questions/1591920/python-binary-data-reading">this one</a> and you are working with 4 bytes rather than 8 hex digits.</p>
<p><code>"\x41\x91\x33\x33"</code> is a 4 byte string even though it looks like 16</p>
<pre><code>>>> len("\x41\x91\x33\x33")
4
>>> import struct
>>> struct.unpack(">fff","\x41\x97\x33\x33\x41\x99\x5C\x29\x47\x0F\xC6\x14")
(18.899999618530273, 19.170000076293945, 36806.078125)
</code></pre>
<p>If you do need to deal with the string of hexdigits rather than the actual bytes, you can use <code>struct.pack</code> to convert it, like this</p>
<pre><code>>>> for hx in ["41973333","41995C29","470FC614"]:
... print(struct.unpack(">f",struct.pack(">i",int(hx,16)))[0])
...
18.8999996185
19.1700000763
36806.078125
</code></pre>
| 5 | 2009-10-20T02:37:28Z | [
"python",
"binary",
"floating-point",
"hex",
"decimal"
] |
Convert hex to float | 1,592,158 | <p>How to convert the following hex string to float (single precision 32-bit) in Python?</p>
<pre><code>"41973333" -> 1.88999996185302734375E1
"41995C29" -> 1.91700000762939453125E1
"470FC614" -> 3.6806078125E4
</code></pre>
| 20 | 2009-10-20T02:32:02Z | 1,592,200 | <p>I recommend using <a href="http://docs.python.org/library/ctypes.html">the ctypes module</a> which basically lets you work with low level data types. In your case you could say</p>
<pre><code>from ctypes import *
def convert(s):
i = int(s, 16) # convert from hex to a Python int
cp = pointer(c_int(i)) # make this into a c integer
fp = cast(cp, POINTER(c_float)) # cast the int pointer to a float pointer
return fp.contents.value # dereference the pointer, get the float
print convert("41973333") # returns 1.88999996185302734375E1
print convert("41995C29") # returns 1.91700000762939453125E1
print convert("470FC614") # returns 3.6806078125E4
</code></pre>
<p>I believe that the <code>ctypes</code> module makes sense here, because you're essentially asking how to perform low-level bit casting. Your question is basically, how do I tell Python to take some data and interpret that data as if those exact same bits were a different data type?</p>
<p>In C if you had an int and wanted to interpret its bits as a float, you'd do roughly the same thing, taking a pointer and then casting and dereferencing it:</p>
<pre><code>int i = 0x41973333;
float f = *((float*)&i);
</code></pre>
<p>and that's exactly what the Python code using the <code>ctypes</code> library is doing in my example.</p>
| 10 | 2009-10-20T02:49:58Z | [
"python",
"binary",
"floating-point",
"hex",
"decimal"
] |
Convert hex to float | 1,592,158 | <p>How to convert the following hex string to float (single precision 32-bit) in Python?</p>
<pre><code>"41973333" -> 1.88999996185302734375E1
"41995C29" -> 1.91700000762939453125E1
"470FC614" -> 3.6806078125E4
</code></pre>
| 20 | 2009-10-20T02:32:02Z | 1,592,226 | <p>Slice up the hex strings into 2-character chunks (bytes), make each chunk into the right byte with int formatting, struct.unpack when done. I.e.:</p>
<pre><code>import struct
testcases = {
"41973333": 1.88999996185302734375E1,
"41995C29": 1.91700000762939453125E1,
"470FC614": 3.6806078125E4,
}
def hex2float(s):
bins = ''.join(chr(int(s[x:x+2], 16)) for x in range(0, len(s), 2))
return struct.unpack('>f', bins)[0]
for s in testcases:
print hex2float(s), testcases[s]
</code></pre>
<p>emitting, as desired:</p>
<pre><code>18.8999996185 18.8999996185
19.1700000763 19.1700000763
36806.078125 36806.078125
</code></pre>
| 4 | 2009-10-20T02:58:23Z | [
"python",
"binary",
"floating-point",
"hex",
"decimal"
] |
Convert hex to float | 1,592,158 | <p>How to convert the following hex string to float (single precision 32-bit) in Python?</p>
<pre><code>"41973333" -> 1.88999996185302734375E1
"41995C29" -> 1.91700000762939453125E1
"470FC614" -> 3.6806078125E4
</code></pre>
| 20 | 2009-10-20T02:32:02Z | 1,592,362 | <pre><code>>>> import struct
>>> struct.unpack('!f', '41973333'.decode('hex'))[0]
18.899999618530273
>>> struct.unpack('!f', '41995C29'.decode('hex'))[0]
19.170000076293945
>>> struct.unpack('!f', '470FC614'.decode('hex'))[0]
36806.078125
</code></pre>
<p>Update: see comment on how to do this in Python 3.</p>
| 36 | 2009-10-20T04:00:51Z | [
"python",
"binary",
"floating-point",
"hex",
"decimal"
] |
Convert hex to float | 1,592,158 | <p>How to convert the following hex string to float (single precision 32-bit) in Python?</p>
<pre><code>"41973333" -> 1.88999996185302734375E1
"41995C29" -> 1.91700000762939453125E1
"470FC614" -> 3.6806078125E4
</code></pre>
| 20 | 2009-10-20T02:32:02Z | 21,617,990 | <p>Gentelmen... Behold:</p>
<pre><code> class fl:
def __init__(this, value=0, byte_size=4):
this.value = value
if this.value: # speedy check (before performing any calculations)
Fe=((byte_size*8)-1)//(byte_size+1)+(byte_size>2)*byte_size//2+(byte_size==3)
Fm,Fb,Fie=(((byte_size*8)-(1+Fe)), ~(~0<<Fe-1), (1<<Fe)-1)
FS,FE,FM=((this.value>>((byte_size*8)-1))&1,(this.value>>Fm)&Fie,this.value&~(~0 << Fm))
if FE == Fie: this.value=(float('NaN') if FM!=0 else (float('+inf') if FS else float('-inf')))
else: this.value=((pow(-1,FS)*(2**(FE-Fb-Fm)*((1<<Fm)+FM))) if FE else pow(-1,FS)*(2**(1-Fb-Fm)*FM))
del Fe; del Fm; del Fb; del Fie; del FS; del FE; del FM
else: this.value = 0.0
print fl( 0x41973333 ).value # >>> 18.899999618530273
print fl( 0x41995C29 ).value # >>> 19.170000076293945
print fl( 0x470FC614 ).value # >>> 36806.078125
print fl( 0x00800000 ).value # >>> 1.1754943508222875e-38 (minimum float value)
print fl( 0x7F7FFFFF ).value # >>> 340282346638528859811704183484516925440L (maximum float value)
# looks like I've found a small bug o.o
# the code still works though (the numbers are properly formatted)
# the result SHOULD be: 3.4028234663852886e+38 (rounded)
print fl( 0x3f80000000, 5 ).value # >>> 1.0
</code></pre>
<p>sorry for the little ".value" at the end...<br>
this code has been used as a class in my program for nearly 2 years now.<br>
(with a little editing, you can easily make it into a function)</p>
<p>credit to PyTony over at DaniWeb for the code.</p>
<p>unlike non-dynamic computing,<br>
the code is not hard-wired to a fixed float size,<br>
and works with any byte-size.<br></p>
<p>though I guess we still have a few bugs to work out. XDD<br>
(I'll edit this code later (if I can) with the update)</p>
<p>all is good though for now though...<br>
I havn't had a problem converting 3D game models with it. :)</p>
| 0 | 2014-02-07T02:10:26Z | [
"python",
"binary",
"floating-point",
"hex",
"decimal"
] |
Convert hex to float | 1,592,158 | <p>How to convert the following hex string to float (single precision 32-bit) in Python?</p>
<pre><code>"41973333" -> 1.88999996185302734375E1
"41995C29" -> 1.91700000762939453125E1
"470FC614" -> 3.6806078125E4
</code></pre>
| 20 | 2009-10-20T02:32:02Z | 32,684,085 | <p>The ctypes approach does not work when the hex string contains leading zeroes. Don't use it.</p>
| -1 | 2015-09-20T20:39:55Z | [
"python",
"binary",
"floating-point",
"hex",
"decimal"
] |
Rendering different part of templates according to the request values in Django | 1,592,331 | <p>In my view to render my template I receive different parameters through my request.</p>
<p>According to these parameters I need to render different "part" in my templates.</p>
<p>For example let say that if I receive in my request</p>
<pre><code>to_render = ["table", "bar_chart"]
</code></pre>
<p>I want to render a partial template for table and an other for bar_chart</p>
<pre><code>to_render = ["bar_chart", "line_chart"]
</code></pre>
<p>Then I will want to render a partial template for the bar_chart and an other for line_chart</p>
<p>Can I define this in my view?</p>
<p>Or do I have to manage this in my template?</p>
<p>Thank you!</p>
| 0 | 2009-10-20T03:48:34Z | 1,592,367 | <p>just manage it in your template</p>
| 2 | 2009-10-20T04:02:40Z | [
"python",
"django",
"django-templates",
"django-views"
] |
Rendering different part of templates according to the request values in Django | 1,592,331 | <p>In my view to render my template I receive different parameters through my request.</p>
<p>According to these parameters I need to render different "part" in my templates.</p>
<p>For example let say that if I receive in my request</p>
<pre><code>to_render = ["table", "bar_chart"]
</code></pre>
<p>I want to render a partial template for table and an other for bar_chart</p>
<pre><code>to_render = ["bar_chart", "line_chart"]
</code></pre>
<p>Then I will want to render a partial template for the bar_chart and an other for line_chart</p>
<p>Can I define this in my view?</p>
<p>Or do I have to manage this in my template?</p>
<p>Thank you!</p>
| 0 | 2009-10-20T03:48:34Z | 1,592,454 | <p>Sure, you can manage this in your view. The <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#ref-templates-api" rel="nofollow">template API</a> shows clearly how to use the templating system in Python.</p>
| 1 | 2009-10-20T04:32:02Z | [
"python",
"django",
"django-templates",
"django-views"
] |
Compilers targeting .pyc files? | 1,592,347 | <p>Out of curiosity, are there many compilers out there which target <code>.pyc</code> files?</p>
<p>After a bit of Googling, the only two I can find are:</p>
<ul>
<li><a href="http://github.com/whymirror/unholy" rel="nofollow">unholy</a>: why_'s Ruby-to-pyc compiler</li>
<li><a href="http://python.org/" rel="nofollow">Python</a>: The PSF's Python to pyc compiler</li>
</ul>
<p>So⦠Are there any more?</p>
<p>(as a side note, I got thinking about this because I want to write a Scheme-to-pyc compiler)</p>
<p>(as a second side note, I'm not under any illusion that a Scheme-to-pyc compiler would be <em>useful</em>, but it would give me an incredible excuse to learn some internals of both Scheme and Python)</p>
| 4 | 2009-10-20T03:53:17Z | 1,592,404 | <p>"I want to write a Scheme-to-pyc compiler".</p>
<p>My brain hurts! Why would you want to do that? Python byte code is an intermediate language specifically designed to meet the needs of the Python language and designed to run on Python virtual machines that, again, have been tailored to the needs of Python. Some of the most important areas of Python development these days are moving Python to other "virtual machines", such as <a href="http://www.jython.org/" rel="nofollow">Jython</a> (JVM), <a href="http://www.codeplex.com/IronPython" rel="nofollow">IronPython</a> (.NET), <a href="http://codespeak.net/pypy/" rel="nofollow">PyPy</a> and the <a href="http://code.google.com/p/unladen-swallow/" rel="nofollow">Unladen Swallow</a> project (moving CPython to an <a href="http://llvm.org/" rel="nofollow">LLVM</a>-based representation). Trying to squeeze the syntax and semantics of another, very different language (Scheme) into the intermediate representation of another high-level language seems to be attacking the problem (whatever the problem is) at the wrong level. So, in general, it doesn't seem like there would be many .pyc compilers out there and there's a good reason for that.</p>
| 4 | 2009-10-20T04:18:00Z | [
"python",
"compiler-construction",
"pyc"
] |
Compilers targeting .pyc files? | 1,592,347 | <p>Out of curiosity, are there many compilers out there which target <code>.pyc</code> files?</p>
<p>After a bit of Googling, the only two I can find are:</p>
<ul>
<li><a href="http://github.com/whymirror/unholy" rel="nofollow">unholy</a>: why_'s Ruby-to-pyc compiler</li>
<li><a href="http://python.org/" rel="nofollow">Python</a>: The PSF's Python to pyc compiler</li>
</ul>
<p>So⦠Are there any more?</p>
<p>(as a side note, I got thinking about this because I want to write a Scheme-to-pyc compiler)</p>
<p>(as a second side note, I'm not under any illusion that a Scheme-to-pyc compiler would be <em>useful</em>, but it would give me an incredible excuse to learn some internals of both Scheme and Python)</p>
| 4 | 2009-10-20T03:53:17Z | 1,592,531 | <p>I suggest you focus on CPython.</p>
<p><a href="http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html" rel="nofollow">http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html</a></p>
<p>Rather than a Scheme to .pyc translator, I suggest you write a Scheme to Python translator, and then let CPython handle the conversion to .pyc. (There is precedent for doing it this way; the first C++ compiler was <a href="http://en.wikipedia.org/wiki/Cfront" rel="nofollow">Cfront</a> which translated C++ into C, and then let the system C compiler do the rest.)</p>
<p>From what I know of Scheme, it wouldn't be that difficult to translate Scheme to Python.</p>
<p>One warning: the Python virtual machine is probably not as fast for Scheme as Scheme itself. For example, Python doesn't automatically turn tail recursion into iteration; and Python has a relatively shallow stack, so you would actually need to turn tail recursion to iteration for your translator.</p>
<p>As a bonus, once Unladen Swallow speeds up Python, your Scheme-to-Python translator would benefit, and at that point might even become practical!</p>
<p>If this seems like a fun project to you, I say go for it. Not every project has to be immediately practical.</p>
<p>P.S. If you want a project that is somewhat more practical, you might want to write an AWK to Python translator. That way, people with legacy AWK scripts could easily make the leap forward to Python!</p>
| 2 | 2009-10-20T04:55:19Z | [
"python",
"compiler-construction",
"pyc"
] |
Compilers targeting .pyc files? | 1,592,347 | <p>Out of curiosity, are there many compilers out there which target <code>.pyc</code> files?</p>
<p>After a bit of Googling, the only two I can find are:</p>
<ul>
<li><a href="http://github.com/whymirror/unholy" rel="nofollow">unholy</a>: why_'s Ruby-to-pyc compiler</li>
<li><a href="http://python.org/" rel="nofollow">Python</a>: The PSF's Python to pyc compiler</li>
</ul>
<p>So⦠Are there any more?</p>
<p>(as a side note, I got thinking about this because I want to write a Scheme-to-pyc compiler)</p>
<p>(as a second side note, I'm not under any illusion that a Scheme-to-pyc compiler would be <em>useful</em>, but it would give me an incredible excuse to learn some internals of both Scheme and Python)</p>
| 4 | 2009-10-20T03:53:17Z | 1,598,066 | <p>I wrote a compiler several years ago which accepted a lisp-like language called "Noodle" and produced Python bytecode. While it never became particularly useful, it was a tremendously good learning experience both for understanding Common Lisp better (I copied several of its features) and for understanding Python better.</p>
<p>I can think of two particular cases when it might be useful to target Python bytecode directly, instead of producing Python and passing it on to a Python compiler:</p>
<ol>
<li>Full closures: in Python before 3.0 (before the <code>nonlocal</code> keyword), you can't modify the value of a closed-over variable without resorting to bytecode hackery. You can mutate values instead, so it's common practice to have a closure referencing a list, for example, and changing the first element in it from the inner scope. That can get real annoying. The restriction is part of the syntax, though, not the Python VM. My language had explicit variable declaration, so it successfully provided "normal" closures with modifiable closed-over values.</li>
<li>Getting at a traceback object without referencing any builtins. Real niche case, for sure, but I used it to break an early version of the "safelite" jail. See <a href="http://thepaulprog.blogspot.com/2009/02/safelite-exploit.html" rel="nofollow">my posting</a> about it.</li>
</ol>
<p>So yeah, it's probably way more work than it's worth, but I enjoyed it, and you might too.</p>
| 3 | 2009-10-21T00:17:26Z | [
"python",
"compiler-construction",
"pyc"
] |
Compilers targeting .pyc files? | 1,592,347 | <p>Out of curiosity, are there many compilers out there which target <code>.pyc</code> files?</p>
<p>After a bit of Googling, the only two I can find are:</p>
<ul>
<li><a href="http://github.com/whymirror/unholy" rel="nofollow">unholy</a>: why_'s Ruby-to-pyc compiler</li>
<li><a href="http://python.org/" rel="nofollow">Python</a>: The PSF's Python to pyc compiler</li>
</ul>
<p>So⦠Are there any more?</p>
<p>(as a side note, I got thinking about this because I want to write a Scheme-to-pyc compiler)</p>
<p>(as a second side note, I'm not under any illusion that a Scheme-to-pyc compiler would be <em>useful</em>, but it would give me an incredible excuse to learn some internals of both Scheme and Python)</p>
| 4 | 2009-10-20T03:53:17Z | 1,814,044 | <p>Just for your interest, I have written a toy compiler from a simple LISP to Python. Practically, this is a LISP to pyc compiler.</p>
<p>Have a look: <a href="http://bernhardkausler.wordpress.com/2009/11/28/sinc-%E2%80%94-the-tiniest-lisp-compiler-to-python/" rel="nofollow">sinC - The tiniest LISP compiler</a></p>
| 2 | 2009-11-28T22:56:37Z | [
"python",
"compiler-construction",
"pyc"
] |
Compilers targeting .pyc files? | 1,592,347 | <p>Out of curiosity, are there many compilers out there which target <code>.pyc</code> files?</p>
<p>After a bit of Googling, the only two I can find are:</p>
<ul>
<li><a href="http://github.com/whymirror/unholy" rel="nofollow">unholy</a>: why_'s Ruby-to-pyc compiler</li>
<li><a href="http://python.org/" rel="nofollow">Python</a>: The PSF's Python to pyc compiler</li>
</ul>
<p>So⦠Are there any more?</p>
<p>(as a side note, I got thinking about this because I want to write a Scheme-to-pyc compiler)</p>
<p>(as a second side note, I'm not under any illusion that a Scheme-to-pyc compiler would be <em>useful</em>, but it would give me an incredible excuse to learn some internals of both Scheme and Python)</p>
| 4 | 2009-10-20T03:53:17Z | 13,425,716 | <p>Probably a bit late at the party but if you're still interested the clojure-py project (https://github.com/halgari/clojure-py) is now able to compile a significant subset of clojure to python bytecode -- but some help is always welcome.</p>
<p>Targeting bytecode is not that hard in itself, except for one thing: it is not stable across platforms (e.g. MAKE_FUNCTION pops 2 elements from the stack in Python 3 but only 1 in Python 2), and these differences are not clearly documented in a single spot (afaict) -- so you probably have some abstraction layer needed.</p>
| 1 | 2012-11-16T23:01:59Z | [
"python",
"compiler-construction",
"pyc"
] |
Decoding Mac OS text in Python | 1,592,925 | <p>I'm writing some code to parse RTF documents, and need to handle the various codepages they can use. Python comes with decoders for all the necessary Windows codepages, but I'm not sure how to handle the Mac ones:</p>
<pre><code># 77: "10000", # Mac Roman
# 78: "10001", # Mac Shift Jis
# 79: "10003", # Mac Hangul
# 80: "10008", # Mac GB2312
# 81: "10002", # Mac Big5
# 83: "10005", # Mac Hebrew
# 84: "10004", # Mac Arabic
# 85: "10006", # Mac Greek
# 86: "10081", # Mac Turkish
# 87: "10021", # Mac Thai
# 88: "10029", # Mac East Europe
# 89: "10007", # Mac Russian
</code></pre>
<p>Does Python have any built-in support for these? If not, is there a cross-platform pure-Python library that will handle them?</p>
| 6 | 2009-10-20T07:05:44Z | 1,592,936 | <p>You can use the python codecs for these that are known by their names 'mac-roman', 'mac-turkish', etc.</p>
<pre><code>>>> 'foo'.decode('mac-turkish')
u'foo'
</code></pre>
<p>You'll have to refer to them by their names, these numbers you've got in your question don't appear in the source files. For more information look at <code>$pylib/encodings/mac_*.py</code>.</p>
| 8 | 2009-10-20T07:09:54Z | [
"python",
"osx"
] |
Decoding Mac OS text in Python | 1,592,925 | <p>I'm writing some code to parse RTF documents, and need to handle the various codepages they can use. Python comes with decoders for all the necessary Windows codepages, but I'm not sure how to handle the Mac ones:</p>
<pre><code># 77: "10000", # Mac Roman
# 78: "10001", # Mac Shift Jis
# 79: "10003", # Mac Hangul
# 80: "10008", # Mac GB2312
# 81: "10002", # Mac Big5
# 83: "10005", # Mac Hebrew
# 84: "10004", # Mac Arabic
# 85: "10006", # Mac Greek
# 86: "10081", # Mac Turkish
# 87: "10021", # Mac Thai
# 88: "10029", # Mac East Europe
# 89: "10007", # Mac Russian
</code></pre>
<p>Does Python have any built-in support for these? If not, is there a cross-platform pure-Python library that will handle them?</p>
| 6 | 2009-10-20T07:05:44Z | 1,592,937 | <p>It seems that at least Mac Roman and Mac Turkish encodings exist in Python stdlib, under names macroman and macturkish. See <a href="http://svn.python.org/projects/python/trunk/Lib/encodings/aliases.py" rel="nofollow">http://svn.python.org/projects/python/trunk/Lib/encodings/aliases.py</a> for a complete list of encoding aliases in the most up-to-date Python.</p>
| 3 | 2009-10-20T07:10:02Z | [
"python",
"osx"
] |
Decoding Mac OS text in Python | 1,592,925 | <p>I'm writing some code to parse RTF documents, and need to handle the various codepages they can use. Python comes with decoders for all the necessary Windows codepages, but I'm not sure how to handle the Mac ones:</p>
<pre><code># 77: "10000", # Mac Roman
# 78: "10001", # Mac Shift Jis
# 79: "10003", # Mac Hangul
# 80: "10008", # Mac GB2312
# 81: "10002", # Mac Big5
# 83: "10005", # Mac Hebrew
# 84: "10004", # Mac Arabic
# 85: "10006", # Mac Greek
# 86: "10081", # Mac Turkish
# 87: "10021", # Mac Thai
# 88: "10029", # Mac East Europe
# 89: "10007", # Mac Russian
</code></pre>
<p>Does Python have any built-in support for these? If not, is there a cross-platform pure-Python library that will handle them?</p>
| 6 | 2009-10-20T07:05:44Z | 1,592,941 | <p>No.</p>
<p>However, <a href="http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/" rel="nofollow">unicode.org</a> provides codec description files that you can use to generate modules that will parse those codecs. Included with python source distributions is a script that will convert these files: <code>Python-x.x/Tools/unicode/gencodec.py</code>.</p>
| 1 | 2009-10-20T07:10:50Z | [
"python",
"osx"
] |
Is there any simple way to benchmark python script? | 1,593,019 | <p>Usually I use shell command <code>time</code>. My purpose is to test if data is small, medium, large or very large set, how much time and memory usage will be.</p>
<p>Any tools for linux or just python to do this?</p>
| 39 | 2009-10-20T07:40:54Z | 1,593,034 | <p>Have a look at <a href="http://docs.python.org/library/timeit.html">timeit</a>, <a href="http://docs.python.org/library/profile.html">the python profiler</a> and <a href="https://pycallgraph.readthedocs.org/en/master/">pycallgraph</a>.</p>
<h2>timeit</h2>
<pre><code>def test():
"""Stupid test function"""
lst = []
for i in range(100):
lst.append(i)
if __name__ == '__main__':
import timeit
print(timeit.timeit("test()", setup="from __main__ import test"))
</code></pre>
<p>Essentially, you can pass it python code as a string parameter, and it will run in the specified amount of times and prints the execution time. The important bits from the docs:</p>
<blockquote>
<p><strong><code>timeit.timeit(stmt='pass', setup='pass', timer=<default timer>,
number=1000000)</code></strong> </p>
<blockquote>
<p>Create a <code>Timer</code> instance with the given statement, <em>setup</em>
code and <em>timer</em> function and run its <code>timeit</code> method with
<em>number</em> executions.</p>
</blockquote>
</blockquote>
<p>... and:</p>
<blockquote>
<p><strong><code>Timer.timeit(number=1000000)</code></strong></p>
<blockquote>
<p>Time <em>number</em> executions of the main statement. This executes the setup
statement once, and then returns the time it takes to execute the main
statement a number of times, measured in seconds as a float.
The argument is the number of times through the loop, defaulting to one
million. The main statement, the setup statement and the timer function
to be used are passed to the constructor.</p>
<p><strong>Note</strong></p>
<blockquote>
<p>By default, <code>timeit</code> temporarily turns off <code>garbage
collection</code> during the timing. The advantage of this approach is that
it makes independent timings more comparable. This disadvantage is
that GC may be an important component of the performance of the
function being measured. If so, GC can be re-enabled as the first
statement in the <em>setup</em> string. For example:</p>
<blockquote>
<p><code>timeit.Timer('for i in xrange(10): oct(i)', 'gc.enable()').timeit()</code></p>
</blockquote>
</blockquote>
</blockquote>
</blockquote>
<h2>Profiling</h2>
<p>Profiling will give you a <em>much</em> more detailed idea about what's going on. Here's the "instant example" from <a href="http://docs.python.org/library/profile.html">the official docs</a>:</p>
<pre><code>import cProfile
import re
cProfile.run('re.compile("foo|bar")')
</code></pre>
<p>Which will give you:</p>
<pre><code> 197 function calls (192 primitive calls) in 0.002 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.001 0.001 <string>:1(<module>)
1 0.000 0.000 0.001 0.001 re.py:212(compile)
1 0.000 0.000 0.001 0.001 re.py:268(_compile)
1 0.000 0.000 0.000 0.000 sre_compile.py:172(_compile_charset)
1 0.000 0.000 0.000 0.000 sre_compile.py:201(_optimize_charset)
4 0.000 0.000 0.000 0.000 sre_compile.py:25(_identityfunction)
3/1 0.000 0.000 0.000 0.000 sre_compile.py:33(_compile)
</code></pre>
<p>Both of these modules should give you an idea about where to look for bottlenecks.</p>
<p>Also, to get to grips with the output of <code>profile</code>, have a look at <a href="http://stackoverflow.com/questions/1469679/understanding-python-profile-output">this post</a></p>
<h2>pycallgraph</h2>
<p><a href="http://docs.python.org/library/profile.html">This module</a> uses graphviz to create callgraphs like the following:</p>
<p><img src="http://i.stack.imgur.com/605RV.png" alt="callgraph example"></p>
<p>You can easily see which paths used up the most time by colour. You can either create them using the pycallgraph API, or using a packaged script:</p>
<pre><code>pycallgraph graphviz -- ./mypythonscript.py
</code></pre>
<p>The overhead is quite considerable though. So for already long-running processes, creating the graph can take some time.</p>
| 60 | 2009-10-20T07:45:04Z | [
"python",
"unix",
"shell",
"benchmarking"
] |
Is there any simple way to benchmark python script? | 1,593,019 | <p>Usually I use shell command <code>time</code>. My purpose is to test if data is small, medium, large or very large set, how much time and memory usage will be.</p>
<p>Any tools for linux or just python to do this?</p>
| 39 | 2009-10-20T07:40:54Z | 1,593,210 | <p>Have a look at <a href="https://pypi.python.org/pypi/nose/" rel="nofollow">nose</a> and at one of its plugins, <a href="http://somethingaboutorange.com/mrl/projects/nose/0.11.1/plugins/prof.html" rel="nofollow">this one</a> in particular.</p>
<p>Once installed, nose is a script in your path, and that you can call in a directory which contains some python scripts:</p>
<pre><code>$: nosetests
</code></pre>
<p>This will look in all the python files in the current directory and will execute any function that it recognizes as a test: for example, it recognizes any function with the word test_ in its name as a test.</p>
<p>So you can just create a python script called test_yourfunction.py and write something like this in it:</p>
<pre><code>$: cat > test_yourfunction.py
def test_smallinput():
yourfunction(smallinput)
def test_mediuminput():
yourfunction(mediuminput)
def test_largeinput():
yourfunction(largeinput)
</code></pre>
<p>Then you have to run </p>
<pre><code>$: nosetest --with-profile --profile-stats-file yourstatsprofile.prof testyourfunction.py
</code></pre>
<p>and to read the profile file, use this python line:</p>
<pre><code>python -c "import hotshot.stats ; stats = hotshot.stats.load('yourstatsprofile.prof') ; stats.sort_stats('time', 'calls') ; stats.print_stats(200)"
</code></pre>
| 2 | 2009-10-20T08:38:42Z | [
"python",
"unix",
"shell",
"benchmarking"
] |
Is there any simple way to benchmark python script? | 1,593,019 | <p>Usually I use shell command <code>time</code>. My purpose is to test if data is small, medium, large or very large set, how much time and memory usage will be.</p>
<p>Any tools for linux or just python to do this?</p>
| 39 | 2009-10-20T07:40:54Z | 5,544,739 | <p>I usually do a quick <code>time ./script.py</code> to see how long it takes. That does not show you the memory though, at least not as a default. You can use <code>/usr/bin/time -v ./script.py</code> to get a lot of information, including memory usage.</p>
| 6 | 2011-04-04T21:47:21Z | [
"python",
"unix",
"shell",
"benchmarking"
] |
Is there any simple way to benchmark python script? | 1,593,019 | <p>Usually I use shell command <code>time</code>. My purpose is to test if data is small, medium, large or very large set, how much time and memory usage will be.</p>
<p>Any tools for linux or just python to do this?</p>
| 39 | 2009-10-20T07:40:54Z | 11,151,365 | <p>I use a simple decorator to time the func</p>
<pre><code>def st_time(func):
"""
st decorator to calculate the total time of a func
"""
def st_func(*args, **keyArgs):
t1 = time.time()
r = func(*args, **keyArgs)
t2 = time.time()
print "Function=%s, Time=%s" % (func.__name__, t2 - t1)
return r
return st_func
</code></pre>
| 14 | 2012-06-22T06:46:52Z | [
"python",
"unix",
"shell",
"benchmarking"
] |
Is there any simple way to benchmark python script? | 1,593,019 | <p>Usually I use shell command <code>time</code>. My purpose is to test if data is small, medium, large or very large set, how much time and memory usage will be.</p>
<p>Any tools for linux or just python to do this?</p>
| 39 | 2009-10-20T07:40:54Z | 11,857,869 | <p>The <code>timeit</code> module was slow and weird, so I wrote this:</p>
<pre><code>def timereps(reps, func):
from time import time
start = time()
for i in range(0, reps):
func()
end = time()
return (end - start) / reps
</code></pre>
<p>Example:</p>
<pre><code>import os
listdir_time = timereps(10000, lambda: os.listdir('/'))
print "python can do %d os.listdir('/') per second" % (1 / listdir_time)
</code></pre>
<p>For me, it says:</p>
<pre><code>python can do 40925 os.listdir('/') per second
</code></pre>
<p>This is a primitive sort of benchmarking, but it's good enough.</p>
| 4 | 2012-08-08T04:55:00Z | [
"python",
"unix",
"shell",
"benchmarking"
] |
How do I check if the python debug option is set from within a script | 1,593,274 | <p>If I'm in debug mode, I want to do other stuff than when I'm not.</p>
<pre><code>if DEBUG:
STORED_DATA_FILE = os.path.join(TEMP_DIR, 'store.dat')
LOG_LEVEL = logging.DEBUG
print "debug mode"
else:
STORED_DATA_FILE = os.path.join(SCRIPT_PATH, 'store.dat')
LOG_LEVEL = logging.INFO
print "not debug mode"
</code></pre>
<p>then:</p>
<pre><code>python script.py
not debug mode
python -d script.py
debug mode
</code></pre>
<p>How can I detect that? It certainly isn't using the <code>__debug__</code> variable.</p>
| 7 | 2009-10-20T08:50:46Z | 1,593,355 | <p>you can use <code>python -O</code> with the <code>__debug__</code> variable</p>
<p>where <code>-O</code> means optimise. so <code>__debug__</code> is false</p>
<p><code>-d</code> turns on debugging for the parser, which is not what you want</p>
| 9 | 2009-10-20T09:08:05Z | [
"python",
"script-debugging"
] |
How do I check if the python debug option is set from within a script | 1,593,274 | <p>If I'm in debug mode, I want to do other stuff than when I'm not.</p>
<pre><code>if DEBUG:
STORED_DATA_FILE = os.path.join(TEMP_DIR, 'store.dat')
LOG_LEVEL = logging.DEBUG
print "debug mode"
else:
STORED_DATA_FILE = os.path.join(SCRIPT_PATH, 'store.dat')
LOG_LEVEL = logging.INFO
print "not debug mode"
</code></pre>
<p>then:</p>
<pre><code>python script.py
not debug mode
python -d script.py
debug mode
</code></pre>
<p>How can I detect that? It certainly isn't using the <code>__debug__</code> variable.</p>
| 7 | 2009-10-20T08:50:46Z | 1,593,401 | <p>Parser debug mode is enabled with <code>-d</code> commandline option or PYTHONDEBUG environment variable and starting from python 2.6 is reflected in <code>sys.flags.debug</code>. But are you sure this is what you are looking for?</p>
| 5 | 2009-10-20T09:19:37Z | [
"python",
"script-debugging"
] |
python queue get(),task_done() question | 1,593,299 | <p>my consumer side of the queue:</p>
<pre><code>m = queue.get()
queue.task_done()
<rest of the program>
</code></pre>
<p>questions:</p>
<ol>
<li><p>does task_done() effectively pop m off the queue and release whatever locks the consumer has on the queue?</p></li>
<li><p>i need to use m during the rest of the program. is it safe, or do i need to copy it before i call task_done()? or, is m usable after task_done()?</p></li>
</ol>
<p>be happy</p>
| 18 | 2009-10-20T08:54:43Z | 1,593,330 | <p>No, <code>queue.get()</code> pops the item off the queue. After you do that, you can do whatever you want with it, as long as the producer works like it should and doesn't touch it anymore. <code>queue.task_done()</code> is called only to notify the queue that you are done with something (it doesn't even know about the specific item, it just counts unfinished items in the queue), so that <code>queue.join()</code> knows the work is finished.</p>
| 34 | 2009-10-20T09:00:46Z | [
"python",
"queue"
] |
How to get all related/parent instances from set of child instances without looping through latter set | 1,593,306 | <p>Please regard the following Django models:</p>
<pre><code>
ParentModel(models.Model):
...
ChildModel(models.Model):
parent = models.ForeignKey(ParentModel, related_name='children')
</code></pre>
<p>Let's assume there is certain subset of all children in the database available as a queryset (call it the 1st set).<br />
Now, I'd like to gain access to the subset of all parents (call it the 2nd set) that said children from the 1st set relate to.</p>
<p>How do you do that without looping through the 1st set at the python level (and potentially cause a linear number of DB hits), i.e., with only one or two DB hits?</p>
<p>Thank you!</p>
| 1 | 2009-10-20T08:56:08Z | 1,593,392 | <p>Assuming you have a queryset called <code>children</code>:</p>
<pre><code>ParentModel.objects.filter(children__in=children)
</code></pre>
| 4 | 2009-10-20T09:17:49Z | [
"python",
"django",
"django-views",
"foreign-key-relationship"
] |
How to read a csv file with python | 1,593,318 | <p>I'm trying to read a csv file but it doesn't work.
I can read my csv file but when I see what I read, there where white space between values.</p>
<p>Here is my code </p>
<pre><code># -*- coding: iso-8859-1 -*-
import sql_db, tmpl_macros, os
import security, form, common
import csv
class windows_dialect(csv.Dialect):
"""Describe the usual properties of unix-generated CSV files."""
delimiter = ','
quotechar = '"'
doublequote = 1
skipinitialspace = 0
lineterminator = 'n'
quoting = csv.QUOTE_MINIMAL
def reco(d):
cars = {210:'"', 211:'"', 213:"'", 136:'à ', 143:'è', 142:'é'}
for c in cars:
d = d.replace(chr(c),cars[c])
return d
def page_process(ctx):
if ctx.req_equals('catalog_send'):
if 'catalog_file' in ctx.locals.__dict__:
contenu = ctx.locals.catalog_file[0].file.read()
#contenu.encode('')
p = csv.reader(contenu, delimiter=',')
inserted = 0
modified = 0
(cr,db) = sql_db.cursor_get()
for line in p:
if line:
logfile = open('/tmp/test.log', 'a')
logfile.write(line[0])
logfile.write('\n')
logfile.write('-----------------------------\n')
logfile.close()
</code></pre>
| 3 | 2009-10-20T08:58:39Z | 1,593,351 | <p>I prefer to use numpy's genfromtxt rather than the standard csv library, because it generates numpy's recarray, which are clean data structures to store data in a table-like object.</p>
<pre><code>>>> from numpy import genfromtxt
>>> data = genfromtxt(csvfile, delimiter=',', dtype=None)
# data is a table-like structure (a numpy recarray) in which you can access columns and rows easily
>>> data['firstcolumn']
<content of the first column>
</code></pre>
| 6 | 2009-10-20T09:07:08Z | [
"python",
"csv"
] |
How to read a csv file with python | 1,593,318 | <p>I'm trying to read a csv file but it doesn't work.
I can read my csv file but when I see what I read, there where white space between values.</p>
<p>Here is my code </p>
<pre><code># -*- coding: iso-8859-1 -*-
import sql_db, tmpl_macros, os
import security, form, common
import csv
class windows_dialect(csv.Dialect):
"""Describe the usual properties of unix-generated CSV files."""
delimiter = ','
quotechar = '"'
doublequote = 1
skipinitialspace = 0
lineterminator = 'n'
quoting = csv.QUOTE_MINIMAL
def reco(d):
cars = {210:'"', 211:'"', 213:"'", 136:'à ', 143:'è', 142:'é'}
for c in cars:
d = d.replace(chr(c),cars[c])
return d
def page_process(ctx):
if ctx.req_equals('catalog_send'):
if 'catalog_file' in ctx.locals.__dict__:
contenu = ctx.locals.catalog_file[0].file.read()
#contenu.encode('')
p = csv.reader(contenu, delimiter=',')
inserted = 0
modified = 0
(cr,db) = sql_db.cursor_get()
for line in p:
if line:
logfile = open('/tmp/test.log', 'a')
logfile.write(line[0])
logfile.write('\n')
logfile.write('-----------------------------\n')
logfile.close()
</code></pre>
| 3 | 2009-10-20T08:58:39Z | 1,593,488 | <p>You don't do anything with the dialect you've defined. Did you mean to do this:</p>
<pre><code>csv.register_dialect('windows_dialect', windows_dialect)
p = csv.reader(contenu, dialect='windows_dialect')
</code></pre>
<p>Also not sure what the <code>reco</code> function is for.</p>
| 0 | 2009-10-20T09:35:02Z | [
"python",
"csv"
] |
How to read a csv file with python | 1,593,318 | <p>I'm trying to read a csv file but it doesn't work.
I can read my csv file but when I see what I read, there where white space between values.</p>
<p>Here is my code </p>
<pre><code># -*- coding: iso-8859-1 -*-
import sql_db, tmpl_macros, os
import security, form, common
import csv
class windows_dialect(csv.Dialect):
"""Describe the usual properties of unix-generated CSV files."""
delimiter = ','
quotechar = '"'
doublequote = 1
skipinitialspace = 0
lineterminator = 'n'
quoting = csv.QUOTE_MINIMAL
def reco(d):
cars = {210:'"', 211:'"', 213:"'", 136:'à ', 143:'è', 142:'é'}
for c in cars:
d = d.replace(chr(c),cars[c])
return d
def page_process(ctx):
if ctx.req_equals('catalog_send'):
if 'catalog_file' in ctx.locals.__dict__:
contenu = ctx.locals.catalog_file[0].file.read()
#contenu.encode('')
p = csv.reader(contenu, delimiter=',')
inserted = 0
modified = 0
(cr,db) = sql_db.cursor_get()
for line in p:
if line:
logfile = open('/tmp/test.log', 'a')
logfile.write(line[0])
logfile.write('\n')
logfile.write('-----------------------------\n')
logfile.close()
</code></pre>
| 3 | 2009-10-20T08:58:39Z | 1,600,227 | <p>If you have control over the data, use tab-delimited instead::</p>
<pre><code>import csv
import string
writer = open('junk.txt', 'wb')
for x in range(10):
writer.write('\t'.join(string.letters[:5]))
writer.write('\r\n')
writer.close()
reader = csv.reader(open('junk.txt', 'r'), dialect='excel-tab')
for line in reader:
print line
</code></pre>
<p>This produces expected results.</p>
<p>A tip for getting more useful feedback: Demonstrate your problem through self-contained and complete example code that doesn't contain extraneous and unimportant artifacts.</p>
| 2 | 2009-10-21T11:25:35Z | [
"python",
"csv"
] |
Permissions for a site only | 1,593,423 | <p>I have a multilingual Django project. Every language is a different subdomain.
So we've decided to use the "sites" application and to create one different site for every language.</p>
<p>On that project, I also have a "pages" application, which is quite similar to a CMS. The user can create pages with content and they'll be displayed in the appropriate language site.</p>
<p>Now I'm looking to be able to manage advanced permissions. What I need to do is to allow, in the admin application a user only to create and update pages for one (or many) specific language/site.</p>
<p>What'd be the cleaner way to do something like that ?</p>
<p><strong>Edit : Here is the solution I've adapted, given by Chris</strong></p>
<p>I create a decorator that's checking if the user is appropriately in the group that has access to the lang.
See Chris' accepted answer for an example of this.</p>
<p>In a "normal" view, I do the following :</p>
<pre><code>def view(self):
# Whatever you wanna do
return render_to_response('page.html', {}, RequestContext(request))
view = group_required(view)
</code></pre>
<p>If the user is in the group, it'll return the method. Otherwise, it'll return an "Access Denied" error.</p>
<p>And in my admin, I do the following :</p>
<pre><code>class PageAdmin(admin.ModelAdmin):
list_display = ('title', 'published')
fieldsets = [
(None, {'fields': ['title', 'slug', 'whatever_field_you_have']}),
]
def has_add_permission(self, request):
return in_group_required(request)
admin.site.register(Page, PageAdmin)
</code></pre>
<p>Where the in_group_required is a similar method to group_required mentionned above. But will return only true or false depending of if we have access or not.</p>
<p>And because we use them quite much in the previous examples, you'll find above here what I have in my in_group and group_required methods.</p>
<pre><code>def group_required(func):
def _decorator(request, *args, **kwargs):
if not in_group(request):
return HttpResponse("Access denied")
return func(*args, **kwargs)
return _decorator
def in_group(request):
language = Language.objects.get(site__domain__exact=request.get_host())
for group in language.group.all():
if request.user in group.user_set.all():
return True
return False
</code></pre>
| 3 | 2009-10-20T09:24:27Z | 1,593,883 | <p>You could create a Group (<a href="http://docs.djangoproject.com/en/dev/topics/auth/" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/auth/</a>)
per site / language and add the users to the groups accordingly.</p>
<p>Then, you can check if the request.user.groups belongs to the group.
(You can do this with a decorator:</p>
<pre><code>def group_required(func):
def _decorator(request, *args, **kwargs):
hostname = request.META.get('HTTP_HOST')
lang = hostname.split(".")[0]
if not lang in request.user.groups:
return HttpResponse("Access denied")
return func(*args, **kwargs)
return _decorator
</code></pre>
<p>(Correct / modify the code to match your requirements...)</p>
| 3 | 2009-10-20T11:14:23Z | [
"python",
"django",
"permissions"
] |
Permissions for a site only | 1,593,423 | <p>I have a multilingual Django project. Every language is a different subdomain.
So we've decided to use the "sites" application and to create one different site for every language.</p>
<p>On that project, I also have a "pages" application, which is quite similar to a CMS. The user can create pages with content and they'll be displayed in the appropriate language site.</p>
<p>Now I'm looking to be able to manage advanced permissions. What I need to do is to allow, in the admin application a user only to create and update pages for one (or many) specific language/site.</p>
<p>What'd be the cleaner way to do something like that ?</p>
<p><strong>Edit : Here is the solution I've adapted, given by Chris</strong></p>
<p>I create a decorator that's checking if the user is appropriately in the group that has access to the lang.
See Chris' accepted answer for an example of this.</p>
<p>In a "normal" view, I do the following :</p>
<pre><code>def view(self):
# Whatever you wanna do
return render_to_response('page.html', {}, RequestContext(request))
view = group_required(view)
</code></pre>
<p>If the user is in the group, it'll return the method. Otherwise, it'll return an "Access Denied" error.</p>
<p>And in my admin, I do the following :</p>
<pre><code>class PageAdmin(admin.ModelAdmin):
list_display = ('title', 'published')
fieldsets = [
(None, {'fields': ['title', 'slug', 'whatever_field_you_have']}),
]
def has_add_permission(self, request):
return in_group_required(request)
admin.site.register(Page, PageAdmin)
</code></pre>
<p>Where the in_group_required is a similar method to group_required mentionned above. But will return only true or false depending of if we have access or not.</p>
<p>And because we use them quite much in the previous examples, you'll find above here what I have in my in_group and group_required methods.</p>
<pre><code>def group_required(func):
def _decorator(request, *args, **kwargs):
if not in_group(request):
return HttpResponse("Access denied")
return func(*args, **kwargs)
return _decorator
def in_group(request):
language = Language.objects.get(site__domain__exact=request.get_host())
for group in language.group.all():
if request.user in group.user_set.all():
return True
return False
</code></pre>
| 3 | 2009-10-20T09:24:27Z | 1,593,943 | <p>You can override has_add_permission (and related methods) in your ModelAdmin class.
(With similar code like shown above)</p>
| 1 | 2009-10-20T11:28:10Z | [
"python",
"django",
"permissions"
] |
Permissions for a site only | 1,593,423 | <p>I have a multilingual Django project. Every language is a different subdomain.
So we've decided to use the "sites" application and to create one different site for every language.</p>
<p>On that project, I also have a "pages" application, which is quite similar to a CMS. The user can create pages with content and they'll be displayed in the appropriate language site.</p>
<p>Now I'm looking to be able to manage advanced permissions. What I need to do is to allow, in the admin application a user only to create and update pages for one (or many) specific language/site.</p>
<p>What'd be the cleaner way to do something like that ?</p>
<p><strong>Edit : Here is the solution I've adapted, given by Chris</strong></p>
<p>I create a decorator that's checking if the user is appropriately in the group that has access to the lang.
See Chris' accepted answer for an example of this.</p>
<p>In a "normal" view, I do the following :</p>
<pre><code>def view(self):
# Whatever you wanna do
return render_to_response('page.html', {}, RequestContext(request))
view = group_required(view)
</code></pre>
<p>If the user is in the group, it'll return the method. Otherwise, it'll return an "Access Denied" error.</p>
<p>And in my admin, I do the following :</p>
<pre><code>class PageAdmin(admin.ModelAdmin):
list_display = ('title', 'published')
fieldsets = [
(None, {'fields': ['title', 'slug', 'whatever_field_you_have']}),
]
def has_add_permission(self, request):
return in_group_required(request)
admin.site.register(Page, PageAdmin)
</code></pre>
<p>Where the in_group_required is a similar method to group_required mentionned above. But will return only true or false depending of if we have access or not.</p>
<p>And because we use them quite much in the previous examples, you'll find above here what I have in my in_group and group_required methods.</p>
<pre><code>def group_required(func):
def _decorator(request, *args, **kwargs):
if not in_group(request):
return HttpResponse("Access denied")
return func(*args, **kwargs)
return _decorator
def in_group(request):
language = Language.objects.get(site__domain__exact=request.get_host())
for group in language.group.all():
if request.user in group.user_set.all():
return True
return False
</code></pre>
| 3 | 2009-10-20T09:24:27Z | 1,594,188 | <p>If you want to filter the Page objects on the admin index of your page-application,
you can override the method queryset() in ModelAdmin.
This QuerySet returns only those Page objects, that belong to a Site (and therefore Group)
of which the request.user is a member.</p>
<pre><code>Pages.objects.filter(site__name__in=request.user.groups)
</code></pre>
| 0 | 2009-10-20T12:15:06Z | [
"python",
"django",
"permissions"
] |
Get the request uri outside of a RequestHandler in Google App Engine (Python) | 1,593,483 | <p>So, within a webapp.RequestHandler subclass I would use <code>self.request.uri</code> to get the request URI. But, I can't access this outside of a RequestHandler and so no go. Any ideas?</p>
<p>I'm running Python and I'm new at it as well as GAE.</p>
| 1 | 2009-10-20T09:33:50Z | 1,593,985 | <p>You should generally be doing everything within some sort of RequestHandler or the equivalent in your non-WebApp framework. However, if you really <strong>insist</strong> on being stuck in the early 1990s and writing plain CGI scripts, the environment variables SERVER_NAME and PATH_INFO may be what you want; see a CGI reference for more info.</p>
| 2 | 2009-10-20T11:34:22Z | [
"python",
"google-app-engine"
] |
Get the request uri outside of a RequestHandler in Google App Engine (Python) | 1,593,483 | <p>So, within a webapp.RequestHandler subclass I would use <code>self.request.uri</code> to get the request URI. But, I can't access this outside of a RequestHandler and so no go. Any ideas?</p>
<p>I'm running Python and I'm new at it as well as GAE.</p>
| 1 | 2009-10-20T09:33:50Z | 1,594,029 | <p>Since using request outside code handling it is meaningless I assume you'd like to access it from some method called by handler without passing request to it. Your choices are:</p>
<ol>
<li>Refactor code so that request is passed to it.</li>
<li>When the former is not possible use a hack by defining a global <a href="http://docs.python.org/library/threading.html#threading.local" rel="nofollow"><code>threading.local()</code></a>, storing request somewhere in request handler and access it in your method.</li>
</ol>
| 0 | 2009-10-20T11:43:35Z | [
"python",
"google-app-engine"
] |
Python: How to check if a nested list is essentially empty? | 1,593,564 | <p>Is there a Pythonic way to <strong>check</strong> if a <em>list</em> (a <em>nested</em> list with elements & lists) is essentially <strong>empty</strong>? What I mean by empty here is that the list might have elements, but those are also empty lists.</p>
<p>The Pythonic way to check an empty list works only on a flat list:</p>
<pre><code>alist = []
if not alist:
print("Empty list!")
</code></pre>
<p>For example, all the following lists should be positive for emptiness:</p>
<pre><code>alist = []
blist = [alist] # [[]]
clist = [alist, alist, alist] # [[], [], []]
dlist = [blist] # [[[]]]
</code></pre>
| 6 | 2009-10-20T09:57:24Z | 1,593,589 | <p>I don't think there is an obvious way to do it in Python. My best guess would be to use a recursive function like this one :</p>
<pre><code>def empty(li):
if li == []:
return True
else:
return all((isinstance(sli, list) and empty(sli)) for sli in li)
</code></pre>
<p>Note that <code>all</code> only comes with Python >= 2.5, and that it will not handle infinitely recursive lists (for example, <code>a = []; a.append(a)</code>).</p>
| 4 | 2009-10-20T10:03:33Z | [
"python",
"list"
] |
Python: How to check if a nested list is essentially empty? | 1,593,564 | <p>Is there a Pythonic way to <strong>check</strong> if a <em>list</em> (a <em>nested</em> list with elements & lists) is essentially <strong>empty</strong>? What I mean by empty here is that the list might have elements, but those are also empty lists.</p>
<p>The Pythonic way to check an empty list works only on a flat list:</p>
<pre><code>alist = []
if not alist:
print("Empty list!")
</code></pre>
<p>For example, all the following lists should be positive for emptiness:</p>
<pre><code>alist = []
blist = [alist] # [[]]
clist = [alist, alist, alist] # [[], [], []]
dlist = [blist] # [[[]]]
</code></pre>
| 6 | 2009-10-20T09:57:24Z | 1,593,612 | <p>A simple recursive check would be enough, and return as early as possible, we assume it input is not a list or contains non-lists it is not empty</p>
<pre><code>def isEmpty(alist):
try:
for a in alist:
if not isEmpty(a):
return False
except:
# we will reach here if alist is not a iterator/list
return False
return True
alist = []
blist = [alist] # [[]]
clist = [alist, alist, alist] # [[], [], []]
dlist = [blist] # [[[]]]
elist = [1, isEmpty, dlist]
if isEmpty(alist):
print "alist is empty"
if isEmpty(dlist):
print "dlist is empty"
if not isEmpty(elist):
print "elist is not empty"
</code></pre>
<p>You can further improve it to check for recursive list or no list objects, or may be empty dicts etc.</p>
| 1 | 2009-10-20T10:09:26Z | [
"python",
"list"
] |
Python: How to check if a nested list is essentially empty? | 1,593,564 | <p>Is there a Pythonic way to <strong>check</strong> if a <em>list</em> (a <em>nested</em> list with elements & lists) is essentially <strong>empty</strong>? What I mean by empty here is that the list might have elements, but those are also empty lists.</p>
<p>The Pythonic way to check an empty list works only on a flat list:</p>
<pre><code>alist = []
if not alist:
print("Empty list!")
</code></pre>
<p>For example, all the following lists should be positive for emptiness:</p>
<pre><code>alist = []
blist = [alist] # [[]]
clist = [alist, alist, alist] # [[], [], []]
dlist = [blist] # [[[]]]
</code></pre>
| 6 | 2009-10-20T09:57:24Z | 1,593,759 | <p>Simple code, works for any iterable object, not just lists:</p>
<pre><code>>>> def empty(seq):
... try:
... return all(map(empty, seq))
... except TypeError:
... return False
...
>>> empty([])
True
>>> empty([4])
False
>>> empty([[]])
True
>>> empty([[], []])
True
>>> empty([[], [8]])
False
>>> empty([[], (False for _ in range(0))])
True
>>> empty([[], (False for _ in range(1))])
False
>>> empty([[], (True for _ in range(1))])
False
</code></pre>
<p>This code makes the assumption that anything that can be iterated over will contain other elements, and should not be considered a leaf in the "tree". If an attempt to iterate over an object fails, then it is not a sequence, and hence certainly not an empty sequence (thus <code>False</code> is returned). Finally, this code makes use of the fact that <a href="http://docs.python.org/3.1/library/functions.html#all"><code>all</code></a> returns <code>True</code> if its argument is an empty sequence.</p>
| 7 | 2009-10-20T10:38:54Z | [
"python",
"list"
] |
Python: How to check if a nested list is essentially empty? | 1,593,564 | <p>Is there a Pythonic way to <strong>check</strong> if a <em>list</em> (a <em>nested</em> list with elements & lists) is essentially <strong>empty</strong>? What I mean by empty here is that the list might have elements, but those are also empty lists.</p>
<p>The Pythonic way to check an empty list works only on a flat list:</p>
<pre><code>alist = []
if not alist:
print("Empty list!")
</code></pre>
<p>For example, all the following lists should be positive for emptiness:</p>
<pre><code>alist = []
blist = [alist] # [[]]
clist = [alist, alist, alist] # [[], [], []]
dlist = [blist] # [[[]]]
</code></pre>
| 6 | 2009-10-20T09:57:24Z | 1,593,797 | <p>If you do not need to iterate through the lists, simpler is better, so something like this will work:</p>
<pre><code>def empty_tree(input_list):
"""Recursively iterate through values in nested lists."""
for item in input_list:
if not isinstance(item, list) or not empty_tree(item):
return False
return True
</code></pre>
<p>However, it would be good to separate the recursive iteration that you will most probably reuse elsewhere and checking that it returns no elements. This way if the mechanism of iteration changes you need to implement the change in one place. For instance when you need to support arbitrary nested iterables, or nested dicts.</p>
<pre><code>def flatten(input_list):
"""Recursively iterate through values in nested lists."""
for item in input_list:
if isinstance(item, list): # Use what ever nesting condition you need here
for child_item in flatten(item):
yield child_item
else:
yield item
def has_items(seq):
"""Checks if an iterator has any items."""
return any(1 for _ in seq)
if not has_items(flatten(my_list)):
pass
</code></pre>
| 9 | 2009-10-20T10:51:43Z | [
"python",
"list"
] |
Python: How to check if a nested list is essentially empty? | 1,593,564 | <p>Is there a Pythonic way to <strong>check</strong> if a <em>list</em> (a <em>nested</em> list with elements & lists) is essentially <strong>empty</strong>? What I mean by empty here is that the list might have elements, but those are also empty lists.</p>
<p>The Pythonic way to check an empty list works only on a flat list:</p>
<pre><code>alist = []
if not alist:
print("Empty list!")
</code></pre>
<p>For example, all the following lists should be positive for emptiness:</p>
<pre><code>alist = []
blist = [alist] # [[]]
clist = [alist, alist, alist] # [[], [], []]
dlist = [blist] # [[[]]]
</code></pre>
| 6 | 2009-10-20T09:57:24Z | 1,605,679 | <p>I have combined the use of <code>isinstance()</code> by <strong>Ants Aasma</strong> and <code>all(map())</code> by <strong>Stephan202</strong>, to form the following solution. <code>all([])</code> returns <code>True</code> and the function relies on this behaviour. I think it has the best of both and is better since it does not rely on the <code>TypeError</code> exception.</p>
<pre><code>def isListEmpty(inList):
if isinstance(inList, list): # Is a list
return all( map(isListEmpty, inList) )
return False # Not a list
</code></pre>
| 7 | 2009-10-22T08:11:16Z | [
"python",
"list"
] |
python constructing functions on the fly | 1,593,572 | <p>I have several little functions <code>f1</code>, <code>f2</code>, <code>f3</code> and a function <code>f</code>.</p>
<p>I want <code>f</code> to be a "container" to <code>f1</code>, <code>f2</code>, <code>f3</code>: to do the some of operations <code>f1</code>, <code>f2</code>, <code>f3</code>, depending on the program configuration (for example <code>f1</code> and <code>f2</code> or <code>f1</code> and <code>f3</code> or all the three) and nothing more.</p>
<p>I see two simple solutions: first to add some <code>if</code>'s in the function <code>f</code>:</p>
<pre><code>if configuration_f1_f2:
f1()
f2()
</code></pre>
<p>second, I can add a list of operations in <code>f</code>:</p>
<pre><code>for op in operations:
op()
</code></pre>
<p>and add <code>f1</code>, <code>f2</code>, <code>f3</code> in <code>operations</code> or remove them, depending on configuration.</p>
<p>But can I somehow construct dynamically code of 'f' adding to it calls of <code>f1</code>, <code>f2</code> and <code>f3</code> exact what I need without any <code>if</code>'s or <code>list</code>'s or <code>for</code>'s? I mean something like on the fly code manipulation. So if my configuration is "<code>f1</code> and <code>f3</code>", I set code of <code>f</code> so that it is </p>
<pre><code>f1()
f3()
</code></pre>
<p>and when my configuration changes to "<code>f2</code> and <code>f3</code>" I modify code of <code>f</code> to </p>
<pre><code>f2()
f3()
</code></pre>
<p>Can I manipulate the code of the function that way?</p>
| 5 | 2009-10-20T09:59:00Z | 1,593,586 | <p>Create dictionary</p>
<pre><code>fun_dict = {'f1': f1, 'f2': f2}
</code></pre>
<p>then parse your config and run function from dict:</p>
<pre><code>fun_dict[parsed_name]()
</code></pre>
| 1 | 2009-10-20T10:03:15Z | [
"python"
] |
python constructing functions on the fly | 1,593,572 | <p>I have several little functions <code>f1</code>, <code>f2</code>, <code>f3</code> and a function <code>f</code>.</p>
<p>I want <code>f</code> to be a "container" to <code>f1</code>, <code>f2</code>, <code>f3</code>: to do the some of operations <code>f1</code>, <code>f2</code>, <code>f3</code>, depending on the program configuration (for example <code>f1</code> and <code>f2</code> or <code>f1</code> and <code>f3</code> or all the three) and nothing more.</p>
<p>I see two simple solutions: first to add some <code>if</code>'s in the function <code>f</code>:</p>
<pre><code>if configuration_f1_f2:
f1()
f2()
</code></pre>
<p>second, I can add a list of operations in <code>f</code>:</p>
<pre><code>for op in operations:
op()
</code></pre>
<p>and add <code>f1</code>, <code>f2</code>, <code>f3</code> in <code>operations</code> or remove them, depending on configuration.</p>
<p>But can I somehow construct dynamically code of 'f' adding to it calls of <code>f1</code>, <code>f2</code> and <code>f3</code> exact what I need without any <code>if</code>'s or <code>list</code>'s or <code>for</code>'s? I mean something like on the fly code manipulation. So if my configuration is "<code>f1</code> and <code>f3</code>", I set code of <code>f</code> so that it is </p>
<pre><code>f1()
f3()
</code></pre>
<p>and when my configuration changes to "<code>f2</code> and <code>f3</code>" I modify code of <code>f</code> to </p>
<pre><code>f2()
f3()
</code></pre>
<p>Can I manipulate the code of the function that way?</p>
| 5 | 2009-10-20T09:59:00Z | 1,593,596 | <p>If <code>f1</code>, <code>f2</code> etc. are functions with side effects, than you should use an explicit <code>for</code> loop (no fancy <code>map</code> solution). Perhaps you want something like this?</p>
<pre><code>configurations = {
'config_1': (f1, f2, f3),
'config_2': (f1, f2),
}
def f(config='config_1'):
for op in configurations[config]:
op()
</code></pre>
<p>If <code>f1</code>, <code>f2</code> etc. receive arguments, then perhaps this is a more suitable definition of <code>f</code>:</p>
<pre><code>def f(config, *args, **kwargs):
for op in configurations[config]:
op(*args, **kwargs)
</code></pre>
| 3 | 2009-10-20T10:05:18Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.