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 |
|---|---|---|---|---|---|---|---|---|---|
How to get the signed integer value of a long in python? | 1,375,897 | <p>If lv stores a long value, and the machine is 32 bits, the following code: </p>
<pre><code>iv = int(lv & 0xffffffff)
</code></pre>
<p>results an iv of type long, instead of the machine's int. </p>
<p>How can I get the (signed) int value in this case?</p>
| 12 | 2009-09-03T20:54:38Z | 37,095,855 | <p>Essentially, the problem is to sign extend from 32 bits to... an infinite number of bits, because Python has arbitrarily large integers. Normally, sign extension is done automatically by CPU instructions when casting, so it's interesting that this is harder in Python than it would be in, say, C.</p>
<p>By playing around, I found something similar to BreizhGatch's function, but that doesn't require a conditional statement. <code>n & 0x80000000</code> extracts the 32-bit sign bit; then, the <code>-</code> keeps the same 32-bit representation but sign-extends it; finally, the extended sign bits are set on <code>n</code>.</p>
<pre><code>def toSigned32(n):
n = n & 0xffffffff
return n | (-(n & 0x80000000))
</code></pre>
<p><a href="https://graphics.stanford.edu/~seander/bithacks.html#VariableSignExtend" rel="nofollow">Bit Twiddling Hacks</a> suggests another solution that perhaps works more generally. <code>n ^ 0x80000000</code> flips the 32-bit sign bit; then <code>- 0x80000000</code> will sign-extend the opposite bit. Another way to think about it is that initially, negative numbers are above positive numbers (separated by <code>0x80000000</code>); the <code>^</code> swaps their positions; then the <code>-</code> shifts negative numbers to below 0.</p>
<pre><code>def toSigned32(n):
n = n & 0xffffffff
return (n ^ 0x80000000) - 0x80000000
</code></pre>
| 0 | 2016-05-08T03:17:02Z | [
"python",
"unsigned",
"signed"
] |
How to get the signed integer value of a long in python? | 1,375,897 | <p>If lv stores a long value, and the machine is 32 bits, the following code: </p>
<pre><code>iv = int(lv & 0xffffffff)
</code></pre>
<p>results an iv of type long, instead of the machine's int. </p>
<p>How can I get the (signed) int value in this case?</p>
| 12 | 2009-09-03T20:54:38Z | 38,064,259 | <p>A quick and dirty solution (x is never greater than 32-bit in my case). </p>
<pre><code>if x > 0x7fffffff:
x = x - 4294967296
</code></pre>
| 1 | 2016-06-27T22:34:28Z | [
"python",
"unsigned",
"signed"
] |
In python, how does one test if a string-like object is mutable? | 1,375,936 | <p>I have a function that takes a string-like argument.</p>
<p>I want to decide if I can safely store the argument and be sure that it won't change. So I'd like to test if it's mutable, e.g the result of a <code>buffer()</code> built from an <code>array.array()</code>, or not.</p>
<p>Currently I use:</p>
<pre><code>type(s) == str
</code></pre>
<p>Is there a better way to do it?</p>
<p>(copying the argument is too costly, that's why I want to avoid it)</p>
| 5 | 2009-09-03T21:02:40Z | 1,375,970 | <p>Just use <a href="http://en.wikipedia.org/wiki/Duck%5Ftyping" rel="nofollow">duck typing</a> -- remember, it's "Easier to Ask for Forgiveness Than Permission". Try to mutate the string-like object, and be prepared to catch an exception if you can't.</p>
| 3 | 2009-09-03T21:07:59Z | [
"python"
] |
In python, how does one test if a string-like object is mutable? | 1,375,936 | <p>I have a function that takes a string-like argument.</p>
<p>I want to decide if I can safely store the argument and be sure that it won't change. So I'd like to test if it's mutable, e.g the result of a <code>buffer()</code> built from an <code>array.array()</code>, or not.</p>
<p>Currently I use:</p>
<pre><code>type(s) == str
</code></pre>
<p>Is there a better way to do it?</p>
<p>(copying the argument is too costly, that's why I want to avoid it)</p>
| 5 | 2009-09-03T21:02:40Z | 1,376,014 | <p>It would be better to use</p>
<pre><code>isinstance(s, basestring)
</code></pre>
<p>It works for Unicode strings too.</p>
| 5 | 2009-09-03T21:16:51Z | [
"python"
] |
In python, how does one test if a string-like object is mutable? | 1,375,936 | <p>I have a function that takes a string-like argument.</p>
<p>I want to decide if I can safely store the argument and be sure that it won't change. So I'd like to test if it's mutable, e.g the result of a <code>buffer()</code> built from an <code>array.array()</code>, or not.</p>
<p>Currently I use:</p>
<pre><code>type(s) == str
</code></pre>
<p>Is there a better way to do it?</p>
<p>(copying the argument is too costly, that's why I want to avoid it)</p>
| 5 | 2009-09-03T21:02:40Z | 1,376,060 | <p>I'd just convert it to an immutable string:</p>
<pre><code>>>> s1 = "possibly mutable"
>>>
>>> s2 = str(s1)
>>> s1 is s2
True
</code></pre>
<p>In case <code>s1</code> is immutable the same object is given back, resulting in no memory overhead. If it's mutable a copy is being made.</p>
| 3 | 2009-09-03T21:25:29Z | [
"python"
] |
In python, how does one test if a string-like object is mutable? | 1,375,936 | <p>I have a function that takes a string-like argument.</p>
<p>I want to decide if I can safely store the argument and be sure that it won't change. So I'd like to test if it's mutable, e.g the result of a <code>buffer()</code> built from an <code>array.array()</code>, or not.</p>
<p>Currently I use:</p>
<pre><code>type(s) == str
</code></pre>
<p>Is there a better way to do it?</p>
<p>(copying the argument is too costly, that's why I want to avoid it)</p>
| 5 | 2009-09-03T21:02:40Z | 1,376,326 | <p>If it's just a <em>heuristic</em> for your caching, just use whatever works. isinstance(x, str), for example, almost exactly like now. (Given you want to decide whether to cache or not; a False-bearing test just means a cache miss, you don't do anything wrong.)</p>
<p><hr /></p>
<p>(Remark: It turns out that buffer objects are hashable, even though their string representation may change under your feet; The hash discussion below is interesting, but is not the <em>pure</em> solution it was intended to be.)</p>
<p>However, well implemented classes should have instances being hashable if they are immutable and not if they are mutable. A general test would be to hash your object and test for success.</p>
<pre><code>>>> hash({})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: dict objects are unhashable
</code></pre>
<p>This will give false positives I'm sure, but mutable objects being hashable is strictly an interface break; <strong>I would</strong> expect python library types to obey this interface, a test of a small sample gives correct answers:</p>
<pre><code>hashabe: str (Immutable), buffer (Warning, immutable slice of (possibly) mutable object!)
unhashable: list, array.array
</code></pre>
| 4 | 2009-09-03T22:35:21Z | [
"python"
] |
Python subprocess with heredocs | 1,376,016 | <p>I was playing around with Python's subprocess module, trying a few examples but I can't seem to get heredoc statements to work.</p>
<p>Here is the trivial example I was playing with:</p>
<pre><code>import subprocess
a = "A String of Text"
p = subprocess.Popen(["cat", "<<DATA\n" + a + "\nDATA"])
</code></pre>
<p>I get the following error when I run the code above:</p>
<pre><code>cat: <<DATA\nA String of Text\nDATA: No such file or directory
</code></pre>
<p>Am I doing it wrong? Is this even possible? If so how would I go about doing it?</p>
<p><hr /></p>
<p>Update</p>
<p>Just wanted to say that this should never be performed in a real python program because there are better ways of doing this.</p>
| 2 | 2009-09-03T21:17:29Z | 1,376,090 | <p>The shell "heredoc" support is a shell feature. <code>subprocess.Popen</code> does not run your command through the shell by default, so this syntax certainly won't work.</p>
<p>However, since you're using pipes anyway, there isn't any need to use the heredoc support of the shell. Just write your string <code>a</code> to the stdin pipe of the process you just started. This is exactly what the shell would do with the heredoc anyway.</p>
<p>You can do this with <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.communicate" rel="nofollow"><code>Popen.communicate()</code></a>:</p>
<pre><code>p.communicate(a)
</code></pre>
<p>The return value of the <code>communicate()</code> function contains the output of the process (in two streams, see the docs).</p>
| 4 | 2009-09-03T21:33:35Z | [
"python",
"subprocess",
"heredoc"
] |
Python subprocess with heredocs | 1,376,016 | <p>I was playing around with Python's subprocess module, trying a few examples but I can't seem to get heredoc statements to work.</p>
<p>Here is the trivial example I was playing with:</p>
<pre><code>import subprocess
a = "A String of Text"
p = subprocess.Popen(["cat", "<<DATA\n" + a + "\nDATA"])
</code></pre>
<p>I get the following error when I run the code above:</p>
<pre><code>cat: <<DATA\nA String of Text\nDATA: No such file or directory
</code></pre>
<p>Am I doing it wrong? Is this even possible? If so how would I go about doing it?</p>
<p><hr /></p>
<p>Update</p>
<p>Just wanted to say that this should never be performed in a real python program because there are better ways of doing this.</p>
| 2 | 2009-09-03T21:17:29Z | 1,376,105 | <p>You're passing shell syntax as an arguments to <code>cat</code> program. You can try to do it like that:</p>
<pre><code>p = subprocess.Popen(["sh", "-c", "cat <<DATA\n" + a + "\nDATA"])
</code></pre>
<p>But the concept itself is wrong. You should use Python features instead of calling shell scripts inside your python scripts.</p>
<p>And in this particular case you should that shell's heredoc syntax interpolates variables, so you'll need to escape all the text inside <code>a</code> and make sure there's no <code>DATA</code> line in it.</p>
| 2 | 2009-09-03T21:37:49Z | [
"python",
"subprocess",
"heredoc"
] |
Python subprocess with heredocs | 1,376,016 | <p>I was playing around with Python's subprocess module, trying a few examples but I can't seem to get heredoc statements to work.</p>
<p>Here is the trivial example I was playing with:</p>
<pre><code>import subprocess
a = "A String of Text"
p = subprocess.Popen(["cat", "<<DATA\n" + a + "\nDATA"])
</code></pre>
<p>I get the following error when I run the code above:</p>
<pre><code>cat: <<DATA\nA String of Text\nDATA: No such file or directory
</code></pre>
<p>Am I doing it wrong? Is this even possible? If so how would I go about doing it?</p>
<p><hr /></p>
<p>Update</p>
<p>Just wanted to say that this should never be performed in a real python program because there are better ways of doing this.</p>
| 2 | 2009-09-03T21:17:29Z | 1,376,180 | <p>As others have pointed out, you need to run it in a shell. Popen makes this easy with a shell=True argument. I get the following output:</p>
<pre><code>>>> import subprocess
>>> a = "A String of Text"
>>> p = subprocess.Popen("cat <<DATA\n" + a + "\nDATA", shell=True)
>>> A String of Text
>>> p.wait()
0
</code></pre>
| 3 | 2009-09-03T21:58:11Z | [
"python",
"subprocess",
"heredoc"
] |
Locking PC in Python on Ubuntu | 1,376,232 | <p>i'm doing application that locks the PC using pyGtk, but i have a problem, when i click on the ok button the function of the button should get the time from the textbox, hide the window then sleep for a while, and at last lock the pc using a bash command. but it just don't hide.</p>
<p>and here is the <a href="http://dl.getdropbox.com/u/616034/ParentalControl.py" rel="nofollow">complete program</a></p>
| 2 | 2009-09-03T22:08:49Z | 1,379,694 | <p>Provided you are using Gnome on Ubuntu </p>
<pre><code>import os
os.system('gnome-screensaver-command â-lock')
</code></pre>
| 3 | 2009-09-04T14:41:06Z | [
"python",
"pygtk"
] |
Locking PC in Python on Ubuntu | 1,376,232 | <p>i'm doing application that locks the PC using pyGtk, but i have a problem, when i click on the ok button the function of the button should get the time from the textbox, hide the window then sleep for a while, and at last lock the pc using a bash command. but it just don't hide.</p>
<p>and here is the <a href="http://dl.getdropbox.com/u/616034/ParentalControl.py" rel="nofollow">complete program</a></p>
| 2 | 2009-09-03T22:08:49Z | 1,384,252 | <p>Is there any reason for the main class to be a thread? I would make it just a normal class, which would be a lot easier to debug. The reason its not working is that all gtk related stuff must happen in the gtk thread, so do all widget method calls like this: <code>gobject.idle_add(widget.method_name)</code>. So to hide the password window: <code>gobject.idle_add(self.pwdWindow.hide)</code></p>
<p>You'll have to <code>import gobject</code> first of course (You might need to install it first).</p>
<p><strong>EDIT:</strong> I don't think that that was your problem, either way I edited your program a lot, here is the modified <a href="http://dl.getdropbox.com/u/961121/ParentalControl.py.tar.gz" rel="nofollow">code</a>.</p>
| 1 | 2009-09-05T20:59:12Z | [
"python",
"pygtk"
] |
Web/Screen Scraping with Google App Engine - Code works in python interpreter but not GAE | 1,376,377 | <p>I want to do some web scraping with GAE. (Infinite Campus Student Information Portal, fyi). This service requires you to login to get in the website.
I had some code that worked using mechanize in normal python. When I learned that I couldn't use mechanize in Google App Engine I ended up using urllib2 + ClientForm. I couldn't get it to login to the server, so after a few hours of fiddling with cookie handling I ran the exact same code in a normal python interpreter, and it worked. I found the log file and saw a ton of messages about stripping out the 'host' header in my request... I found the source file on Google Code and the host header was in an 'untrusted' list and removed from all requests by user code.</p>
<p>Apparently GAE strips out the host header, which is required by I.C. to determine which school system to log you in, which is why it appeared like I couldn't login. </p>
<p>How would I get around this problem? I can't specify anything else in my fake form submission to the target site. Why would this be a "security hole" in the first place?</p>
| 3 | 2009-09-03T22:52:46Z | 1,376,630 | <p>App Engine does not <em>strip out</em> the Host header: it forces it to be an accurate value based on the URI you are requesting. Assuming that URI's absolute, the server isn't even allowed to consider the Host header anyway, per <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.2" rel="nofollow">RFC2616</a>:</p>
<blockquote>
<ol>
<li>If Request-URI is an absoluteURI, the host is part of the Request-URI.
Any Host header field value in the
request MUST be ignored.</li>
</ol>
</blockquote>
<p>...so I suspect you're misdiagnosing the cause of your problem. Try directing the request to a "dummy" server that you control (e.g. another very simple app engine app of yours) so you can look at all the headers and body of the request as it comes from your GAE app, vs, how it comes from your "normal python interpreter". What do you observe this way?</p>
| 2 | 2009-09-04T00:14:50Z | [
"python",
"google-app-engine",
"screen-scraping"
] |
How to make a repeating generator in Python | 1,376,438 | <p>How do you make a repeating generator, like xrange, in Python? For instance, if I do:</p>
<pre><code>>>> m = xrange(5)
>>> print list(m)
>>> print list(m)
</code></pre>
<p>I get the same result both times â the numbers 0..4. However, if I try the same with yield:</p>
<pre><code>>>> def myxrange(n):
... i = 0
... while i < n:
... yield i
... i += 1
>>> m = myxrange(5)
>>> print list(m)
>>> print list(m)
</code></pre>
<p>The second time I try to iterate over m, I get nothing back â an empty list.</p>
<p>Is there a simple way to create a repeating generator like xrange with yield, or generator comprehensions? I found <a href="http://bugs.python.org/msg89898" rel="nofollow">a workaround on a Python tracker issue</a>, which uses a decorator to transform a generator into an iterator. This restarts every time you start using it, even if you didn't use all the values last time through, just like xrange. I also came up with my own decorator, based on the same idea, which actually returns a generator, but one which can restart after throwing a StopIteration exception:</p>
<pre><code>@decorator.decorator
def eternal(genfunc, *args, **kwargs):
class _iterable:
iter = None
def __iter__(self): return self
def next(self, *nargs, **nkwargs):
self.iter = self.iter or genfunc(*args, **kwargs):
try:
return self.iter.next(*nargs, **nkwargs)
except StopIteration:
self.iter = None
raise
return _iterable()
</code></pre>
<p>Is there a better way to solve the problem, using only yield and/or generator comprehensions? Or something built into Python? So I don't need to roll my own classes and decorators?</p>
<h1>Update</h1>
<p>The <a href="http://stackoverflow.com/questions/1376438/how-to-make-a-repeating-generator-in-python#comment1221812_1376531">comment by u0b34a0f6ae</a> nailed the source of my misunderstanding:</p>
<blockquote>
<p>xrange(5) does not return an iterator, it creates an xrange object. xrange objects can be iterated, just like dictionaries, more than once.</p>
</blockquote>
<p>My "eternal" function was barking up the wrong tree entirely, by acting like an iterator/generator (<code>__iter__</code> returns self) rather than like a collection/xrange (<code>__iter__</code> returns a new iterator).</p>
| 12 | 2009-09-03T23:12:33Z | 1,376,497 | <p>I think the answer to that is "No". I'm possibly wrong. It may be that with some of the funky new things you can do with generators in 2.6 involving arguments and exception handling that would allow something like what you want. But those features are mostly intended for implementing semi-continuations.</p>
<p>Why do you want to not have your own classes or decorators? And why did you want to create a decorator that returned a generator instead of a class instance?</p>
| 0 | 2009-09-03T23:29:13Z | [
"python"
] |
How to make a repeating generator in Python | 1,376,438 | <p>How do you make a repeating generator, like xrange, in Python? For instance, if I do:</p>
<pre><code>>>> m = xrange(5)
>>> print list(m)
>>> print list(m)
</code></pre>
<p>I get the same result both times â the numbers 0..4. However, if I try the same with yield:</p>
<pre><code>>>> def myxrange(n):
... i = 0
... while i < n:
... yield i
... i += 1
>>> m = myxrange(5)
>>> print list(m)
>>> print list(m)
</code></pre>
<p>The second time I try to iterate over m, I get nothing back â an empty list.</p>
<p>Is there a simple way to create a repeating generator like xrange with yield, or generator comprehensions? I found <a href="http://bugs.python.org/msg89898" rel="nofollow">a workaround on a Python tracker issue</a>, which uses a decorator to transform a generator into an iterator. This restarts every time you start using it, even if you didn't use all the values last time through, just like xrange. I also came up with my own decorator, based on the same idea, which actually returns a generator, but one which can restart after throwing a StopIteration exception:</p>
<pre><code>@decorator.decorator
def eternal(genfunc, *args, **kwargs):
class _iterable:
iter = None
def __iter__(self): return self
def next(self, *nargs, **nkwargs):
self.iter = self.iter or genfunc(*args, **kwargs):
try:
return self.iter.next(*nargs, **nkwargs)
except StopIteration:
self.iter = None
raise
return _iterable()
</code></pre>
<p>Is there a better way to solve the problem, using only yield and/or generator comprehensions? Or something built into Python? So I don't need to roll my own classes and decorators?</p>
<h1>Update</h1>
<p>The <a href="http://stackoverflow.com/questions/1376438/how-to-make-a-repeating-generator-in-python#comment1221812_1376531">comment by u0b34a0f6ae</a> nailed the source of my misunderstanding:</p>
<blockquote>
<p>xrange(5) does not return an iterator, it creates an xrange object. xrange objects can be iterated, just like dictionaries, more than once.</p>
</blockquote>
<p>My "eternal" function was barking up the wrong tree entirely, by acting like an iterator/generator (<code>__iter__</code> returns self) rather than like a collection/xrange (<code>__iter__</code> returns a new iterator).</p>
| 12 | 2009-09-03T23:12:33Z | 1,376,531 | <p>Not directly. Part of the flexibility that allows generators to be used for implementing co-routines, resource management, etc, is that they are always one-shot. Once run, a generator cannot be re-run. You would have to create a new generator object.</p>
<p>However, you can create your own class which overrides <code>__iter__()</code>. It will act like a reusable generator:</p>
<pre><code>def multigen(gen_func):
class _multigen(object):
def __init__(self, *args, **kwargs):
self.__args = args
self.__kwargs = kwargs
def __iter__(self):
return gen_func(*self.__args, **self.__kwargs)
return _multigen
@multigen
def myxrange(n):
i = 0
while i < n:
yield i
i += 1
m = myxrange(5)
print list(m)
print list(m)
</code></pre>
| 14 | 2009-09-03T23:40:37Z | [
"python"
] |
How to make a repeating generator in Python | 1,376,438 | <p>How do you make a repeating generator, like xrange, in Python? For instance, if I do:</p>
<pre><code>>>> m = xrange(5)
>>> print list(m)
>>> print list(m)
</code></pre>
<p>I get the same result both times â the numbers 0..4. However, if I try the same with yield:</p>
<pre><code>>>> def myxrange(n):
... i = 0
... while i < n:
... yield i
... i += 1
>>> m = myxrange(5)
>>> print list(m)
>>> print list(m)
</code></pre>
<p>The second time I try to iterate over m, I get nothing back â an empty list.</p>
<p>Is there a simple way to create a repeating generator like xrange with yield, or generator comprehensions? I found <a href="http://bugs.python.org/msg89898" rel="nofollow">a workaround on a Python tracker issue</a>, which uses a decorator to transform a generator into an iterator. This restarts every time you start using it, even if you didn't use all the values last time through, just like xrange. I also came up with my own decorator, based on the same idea, which actually returns a generator, but one which can restart after throwing a StopIteration exception:</p>
<pre><code>@decorator.decorator
def eternal(genfunc, *args, **kwargs):
class _iterable:
iter = None
def __iter__(self): return self
def next(self, *nargs, **nkwargs):
self.iter = self.iter or genfunc(*args, **kwargs):
try:
return self.iter.next(*nargs, **nkwargs)
except StopIteration:
self.iter = None
raise
return _iterable()
</code></pre>
<p>Is there a better way to solve the problem, using only yield and/or generator comprehensions? Or something built into Python? So I don't need to roll my own classes and decorators?</p>
<h1>Update</h1>
<p>The <a href="http://stackoverflow.com/questions/1376438/how-to-make-a-repeating-generator-in-python#comment1221812_1376531">comment by u0b34a0f6ae</a> nailed the source of my misunderstanding:</p>
<blockquote>
<p>xrange(5) does not return an iterator, it creates an xrange object. xrange objects can be iterated, just like dictionaries, more than once.</p>
</blockquote>
<p>My "eternal" function was barking up the wrong tree entirely, by acting like an iterator/generator (<code>__iter__</code> returns self) rather than like a collection/xrange (<code>__iter__</code> returns a new iterator).</p>
| 12 | 2009-09-03T23:12:33Z | 1,985,733 | <p>If you write a lot of these, John Millikin's answer is the cleanest it gets.</p>
<p>But if you don't mind adding 3 lines and some indentation, you can do it without a custom decorator. This composes 2 tricks:</p>
<ol>
<li><p>[Generally useful:] You can easily make a class iterable without implementing
<code>.next()</code> - just use a generator for <code>__iter__(self)</code>!</p></li>
<li><p>Instead of bothering with a constructor, you can define a one-off class inside a function. </p></li>
</ol>
<p>=></p>
<pre><code>def myxrange(n):
class Iterable(object):
def __iter__(self):
i = 0
while i < n:
yield i
i += 1
return Iterable()
</code></pre>
<p>Small print: I didn't test performance, spawning classes like this might be wasteful. But awesome ;-)</p>
| 1 | 2009-12-31T14:59:47Z | [
"python"
] |
How to make a repeating generator in Python | 1,376,438 | <p>How do you make a repeating generator, like xrange, in Python? For instance, if I do:</p>
<pre><code>>>> m = xrange(5)
>>> print list(m)
>>> print list(m)
</code></pre>
<p>I get the same result both times â the numbers 0..4. However, if I try the same with yield:</p>
<pre><code>>>> def myxrange(n):
... i = 0
... while i < n:
... yield i
... i += 1
>>> m = myxrange(5)
>>> print list(m)
>>> print list(m)
</code></pre>
<p>The second time I try to iterate over m, I get nothing back â an empty list.</p>
<p>Is there a simple way to create a repeating generator like xrange with yield, or generator comprehensions? I found <a href="http://bugs.python.org/msg89898" rel="nofollow">a workaround on a Python tracker issue</a>, which uses a decorator to transform a generator into an iterator. This restarts every time you start using it, even if you didn't use all the values last time through, just like xrange. I also came up with my own decorator, based on the same idea, which actually returns a generator, but one which can restart after throwing a StopIteration exception:</p>
<pre><code>@decorator.decorator
def eternal(genfunc, *args, **kwargs):
class _iterable:
iter = None
def __iter__(self): return self
def next(self, *nargs, **nkwargs):
self.iter = self.iter or genfunc(*args, **kwargs):
try:
return self.iter.next(*nargs, **nkwargs)
except StopIteration:
self.iter = None
raise
return _iterable()
</code></pre>
<p>Is there a better way to solve the problem, using only yield and/or generator comprehensions? Or something built into Python? So I don't need to roll my own classes and decorators?</p>
<h1>Update</h1>
<p>The <a href="http://stackoverflow.com/questions/1376438/how-to-make-a-repeating-generator-in-python#comment1221812_1376531">comment by u0b34a0f6ae</a> nailed the source of my misunderstanding:</p>
<blockquote>
<p>xrange(5) does not return an iterator, it creates an xrange object. xrange objects can be iterated, just like dictionaries, more than once.</p>
</blockquote>
<p>My "eternal" function was barking up the wrong tree entirely, by acting like an iterator/generator (<code>__iter__</code> returns self) rather than like a collection/xrange (<code>__iter__</code> returns a new iterator).</p>
| 12 | 2009-09-03T23:12:33Z | 19,875,981 | <p>use this solution:</p>
<pre><code>>>> myxrange_ = lambda x: myxrange(x)
>>> print list(myxrange_(5))
... [0, 1, 2, 3, 4]
>>> print list(myxrange_(5))
... [0, 1, 2, 3, 4]
>>> for number in myxrange_(5):
... print number
...
0
1
2
3
4
>>>
</code></pre>
<p>and with a decorator:</p>
<pre><code>>>> def decorator(generator):
... return lambda x: generator(x)
...
>>> @decorator
>>> def myxrange(n):
... i = 0
... while i < n:
... yield i
... i += 1
...
>>> print list(myxrange(5))
... [0, 1, 2, 3, 4]
>>> print list(myxrange(5))
... [0, 1, 2, 3, 4]
>>>
</code></pre>
<p>Simple.</p>
| -1 | 2013-11-09T12:32:45Z | [
"python"
] |
Python : email sending failing on SSL read | 1,376,450 | <p>I keep getting this intermittent error when trying to send through 'smtp.gmail.com'. </p>
<pre><code>Traceback (most recent call last):
File "/var/home/ptarjan/django/mysite/django/core/handlers/base.py", line 92, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/var/home/ptarjan/django/mysite/registration/views.py", line 137, in register
new_user = form.save()
File "/var/home/ptarjan/django/mysite/registration/forms.py", line 79, in save
email=self.cleaned_data['email'])
File "/var/home/ptarjan/django/mysite/django/db/transaction.py", line 240, in _commit_on_success
res = func(*args, **kw)
File "/var/home/ptarjan/django/mysite/registration/models.py", line 120, in create_inactive_user
registration_profile.send_registration_mail()
File "/var/home/ptarjan/django/mysite/registration/models.py", line 259, in send_registration_mail
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [self.user.email])
File "/var/home/ptarjan/django/mysite/django/core/mail.py", line 390, in send_mail
connection=connection).send()
File "/var/home/ptarjan/django/mysite/django/core/mail.py", line 266, in send
return self.get_connection(fail_silently).send_messages([self])
File "/var/home/ptarjan/django/mysite/django/core/mail.py", line 172, in send_messages
sent = self._send(message)
File "/var/home/ptarjan/django/mysite/django/core/mail.py", line 186, in _send
email_message.message().as_string())
File "/usr/lib/python2.5/smtplib.py", line 704, in sendmail
(code,resp) = self.data(msg)
File "/usr/lib/python2.5/smtplib.py", line 484, in data
(code,repl)=self.getreply()
File "/usr/lib/python2.5/smtplib.py", line 352, in getreply
line = self.file.readline()
File "/usr/lib/python2.5/smtplib.py", line 160, in readline
chr = self.sslobj.read(1)
sslerror: The read operation timed out
</code></pre>
<p>I'm running Django 1.1 with the django-registarion app. With these in my settings.py</p>
<pre><code>EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = "**SECRET**"
EMAIL_HOST_PASSWORD = "**SECRET**"
EMAIL_PORT = 587
EMAIL_USE_TLS = True
</code></pre>
| 1 | 2009-09-03T23:15:54Z | 1,376,862 | <p>Looks like gmail may simply be occasionally slow to respond, so your operation times out. Perhaps you can use a try/except to catch such issues and retry a few times (maybe waiting a while between attempts). BTW, this task seems well suited to a dedicated or pooled thread which encapsulates the whole "send mail with retries" operation.</p>
| 0 | 2009-09-04T01:53:26Z | [
"python",
"django",
"email",
"smtp",
"ssl"
] |
Python : email sending failing on SSL read | 1,376,450 | <p>I keep getting this intermittent error when trying to send through 'smtp.gmail.com'. </p>
<pre><code>Traceback (most recent call last):
File "/var/home/ptarjan/django/mysite/django/core/handlers/base.py", line 92, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/var/home/ptarjan/django/mysite/registration/views.py", line 137, in register
new_user = form.save()
File "/var/home/ptarjan/django/mysite/registration/forms.py", line 79, in save
email=self.cleaned_data['email'])
File "/var/home/ptarjan/django/mysite/django/db/transaction.py", line 240, in _commit_on_success
res = func(*args, **kw)
File "/var/home/ptarjan/django/mysite/registration/models.py", line 120, in create_inactive_user
registration_profile.send_registration_mail()
File "/var/home/ptarjan/django/mysite/registration/models.py", line 259, in send_registration_mail
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [self.user.email])
File "/var/home/ptarjan/django/mysite/django/core/mail.py", line 390, in send_mail
connection=connection).send()
File "/var/home/ptarjan/django/mysite/django/core/mail.py", line 266, in send
return self.get_connection(fail_silently).send_messages([self])
File "/var/home/ptarjan/django/mysite/django/core/mail.py", line 172, in send_messages
sent = self._send(message)
File "/var/home/ptarjan/django/mysite/django/core/mail.py", line 186, in _send
email_message.message().as_string())
File "/usr/lib/python2.5/smtplib.py", line 704, in sendmail
(code,resp) = self.data(msg)
File "/usr/lib/python2.5/smtplib.py", line 484, in data
(code,repl)=self.getreply()
File "/usr/lib/python2.5/smtplib.py", line 352, in getreply
line = self.file.readline()
File "/usr/lib/python2.5/smtplib.py", line 160, in readline
chr = self.sslobj.read(1)
sslerror: The read operation timed out
</code></pre>
<p>I'm running Django 1.1 with the django-registarion app. With these in my settings.py</p>
<pre><code>EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = "**SECRET**"
EMAIL_HOST_PASSWORD = "**SECRET**"
EMAIL_PORT = 587
EMAIL_USE_TLS = True
</code></pre>
| 1 | 2009-09-03T23:15:54Z | 1,378,565 | <p>Altho' I don't know why, I <strong>have been thro' this</strong>, and it works when you have settings variables ordered in a particular order:</p>
<ul>
<li>EMAIL_HOST</li>
<li>EMAIL_PORT</li>
<li>EMAIL_HOST_USER</li>
<li>EMAIL_HOST_PASSWORD</li>
<li>EMAIL_USE_TLS</li>
</ul>
| 3 | 2009-09-04T11:03:10Z | [
"python",
"django",
"email",
"smtp",
"ssl"
] |
pyobjc indexed accessor method with range | 1,376,463 | <p>I'm trying to implement an indexed accessor method for my model class in Python, as per <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/KeyValueCoding/Concepts/AccessorConventions.html" rel="nofollow">the KVC guide</a>. I want to use the optional ranged method, to load multiple objects at once for performance reasons. The method takes a pointer to a C-array buffer which my method needs to copy the objects into. I've tried something like the following, which doesn't work. How do I accomplish this?</p>
<pre><code>@objc.accessor # i've also tried @objc.signature('v@:o^@')
def getFoos_range_(self, range):
return self._some_array[range.location:range.location + range.length]
</code></pre>
<p><strong>Edit</strong>: I finally found the <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html" rel="nofollow">type encodings reference</a> after Apple moved all the docs. After reading that, I tried this:</p>
<pre><code>@objc.signature('v@:N^@@')
def getFoos_range_(self, buf, range):
</code></pre>
<p>but this didn't appear to work either. The first argument is supposed to be a pointer to a C-array, but the length is unknown until runtime, so I didn't know exactly how to construct the correct type encoding. I tried <code>'v@:N^[1000@]@'</code> just to see, and that didn't work either.</p>
<p>My model object is bound to the contentArray of an NSArrayController driving a table view. It doesn't appear to be calling this method at all, perhaps because it expects a different signature than the one the bridge is providing. Any suggestions?</p>
| 3 | 2009-09-03T23:19:51Z | 5,336,824 | <p>You were close. The correct decorator for this method is:</p>
<pre><code>@objc.signature('v@:o^@{_NSRange=QQ}')
</code></pre>
<p><code>NSRange</code> is not an object, but a struct, and can't be specified simply as <code>@</code>; you need to include the members<sup>1</sup>.</p>
<p>Unfortunately, this is not the end of it. After a whole lot of experimentation and poring over the PyObjC source, I finally figured out that in order to get this method to work, you <em>also</em> need to specify metadata for the method that is redundant to this signature. (However, I still haven't puzzled out why.) </p>
<p>This is done using the function <code>objc.registerMetaDataForSelector</code>:</p>
<pre><code>objc.registerMetaDataForSelector(b"SUPERCLASSNAME",
b"getKey:range:",
dict(retval=dict(type=objc._C_VOID),
arguments={
2+0: dict(type_modifier=objc._C_OUT,
c_array_length_in_arg=2+1),
2+1: dict(type=b'{_NSRange=II}',
type64=b'{_NSRange=QQ}')
}
)
)
</code></pre>
<p>Examples and some details of the use of this function can be found in the file <a href="http://svn.red-bean.com/pyobjc/trunk/pyobjc/pyobjc-core/PyObjCTest/test_metadata_py.py" rel="nofollow"><code>test_metadata_py.py</code></a> (and nearby <code>test_metadata*.py</code> files) in the PyObjC source. </p>
<p><strong>N.B.</strong> that the metadata has to be specified on the <em>superclass</em> of whatever class you are interested in implementing <code>get<Key>:range:</code> for, and also that this function needs to be called sometime before the end of your class definition (but either before or inside the <code>class</code> statement itself both seem to work). I haven't yet puzzled these bits out either.</p>
<p>I based this metadata on the metadata for <code>NSArray getObjects:range:</code> in the Foundation PyObjC.bridgesupport file<sup>2</sup>, and was aided by referring to Apple's <a href="http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man5/BridgeSupport.5.html" rel="nofollow">BridgeSupport manpage</a>.</p>
<p>With this worked out, it's also worth noting that the easiest way to define the method is (at least, IMO):</p>
<pre><code>@objc.signature('v@:o^@{_NSRange=QQ}')
def get<#Key#>_range_(self, buf, inRange):
#NSLog(u"get<#Key#>")
return self.<#Key#>.getObjects_range_(buf, inRange)
</code></pre>
<p>I.e., using your array's built-in <code>getObjects:range:</code>.</p>
<hr>
<p>1: On 32-bit Python, the <code>QQ</code>, meaning two <code>unsigned long long</code>s, should become <code>II</code>, meaning two <code>unsigned int</code>s<br>
2: Located (on Snow Leopard) at: /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/PyObjC/Foundation/PyObjC.bridgesupport</p>
| 2 | 2011-03-17T08:54:04Z | [
"python",
"cocoa",
"pyobjc",
"key-value-coding"
] |
How to extract a string between 2 other strings in python? | 1,376,640 | <p>Like if I have a string like <code>str1 = "IWantToMasterPython"</code></p>
<p>If I want to extract <code>"Py"</code> from the above string. I write:</p>
<pre><code>extractedString = foo("Master","thon")
</code></pre>
<p>I want to do all this because i am trying to extract lyrics from an html page. The lyrics are written like <code><div class = "lyricbox"> ....lyrics goes here....</div></code>.</p>
<p>Any suggestions on how can I implement.</p>
| 16 | 2009-09-04T00:17:29Z | 1,376,658 | <p>The solution is to use a regexp:</p>
<pre><code>import re
r = re.compile('Master(.*?)thon')
m = r.search(str1)
if m:
lyrics = m.group(1)
</code></pre>
| 27 | 2009-09-04T00:23:53Z | [
"python",
"string"
] |
How to extract a string between 2 other strings in python? | 1,376,640 | <p>Like if I have a string like <code>str1 = "IWantToMasterPython"</code></p>
<p>If I want to extract <code>"Py"</code> from the above string. I write:</p>
<pre><code>extractedString = foo("Master","thon")
</code></pre>
<p>I want to do all this because i am trying to extract lyrics from an html page. The lyrics are written like <code><div class = "lyricbox"> ....lyrics goes here....</div></code>.</p>
<p>Any suggestions on how can I implement.</p>
| 16 | 2009-09-04T00:17:29Z | 1,376,661 | <pre><code>def foo(s, leader, trailer):
end_of_leader = s.index(leader) + len(leader)
start_of_trailer = s.index(trailer, end_of_leader)
return s[end_of_leader:start_of_trailer]
</code></pre>
<p>this raises ValueError if the leader is not present in string s, or the trailer is not present after that (you have not specified what behavior you want in such anomalous conditions; raising an exception is a pretty natural and Pythonic thing to do, letting the caller handle that with a try/except if it know what to do in such cases).</p>
<p>A RE-based approach is also possible, but I think this pure-string approach is simpler.</p>
| 8 | 2009-09-04T00:24:59Z | [
"python",
"string"
] |
How to extract a string between 2 other strings in python? | 1,376,640 | <p>Like if I have a string like <code>str1 = "IWantToMasterPython"</code></p>
<p>If I want to extract <code>"Py"</code> from the above string. I write:</p>
<pre><code>extractedString = foo("Master","thon")
</code></pre>
<p>I want to do all this because i am trying to extract lyrics from an html page. The lyrics are written like <code><div class = "lyricbox"> ....lyrics goes here....</div></code>.</p>
<p>Any suggestions on how can I implement.</p>
| 16 | 2009-09-04T00:17:29Z | 1,378,517 | <p>If you're extracting any data from a html page, I'd strongly suggest using <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> library. I used it also for extracting data from html and it works great.</p>
| 2 | 2009-09-04T10:51:25Z | [
"python",
"string"
] |
How to extract a string between 2 other strings in python? | 1,376,640 | <p>Like if I have a string like <code>str1 = "IWantToMasterPython"</code></p>
<p>If I want to extract <code>"Py"</code> from the above string. I write:</p>
<pre><code>extractedString = foo("Master","thon")
</code></pre>
<p>I want to do all this because i am trying to extract lyrics from an html page. The lyrics are written like <code><div class = "lyricbox"> ....lyrics goes here....</div></code>.</p>
<p>Any suggestions on how can I implement.</p>
| 16 | 2009-09-04T00:17:29Z | 1,380,182 | <p>BeautifulSoup is the easiest way to do what you want. It can be installed like:</p>
<pre><code>sudo easy_install beautifulsoup
</code></pre>
<p>The sample code to do what you want is:</p>
<pre><code>from BeautifulSoup import BeautifulSoup
doc = ['<div class="lyricbox">Hey You</div>']
soup = BeautifulSoup(''.join(doc))
print soup.find('div', {'class': 'lyricbox'}).string
</code></pre>
<p>You can use Python's <a href="http://docs.python.org/library/urllib.html">urllib</a> to grab content from the url directly. The <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Quick%20Start">Beautiful Soup doc</a> is helpful too if you want to do some more parsing.</p>
| 10 | 2009-09-04T16:09:02Z | [
"python",
"string"
] |
How to extract a string between 2 other strings in python? | 1,376,640 | <p>Like if I have a string like <code>str1 = "IWantToMasterPython"</code></p>
<p>If I want to extract <code>"Py"</code> from the above string. I write:</p>
<pre><code>extractedString = foo("Master","thon")
</code></pre>
<p>I want to do all this because i am trying to extract lyrics from an html page. The lyrics are written like <code><div class = "lyricbox"> ....lyrics goes here....</div></code>.</p>
<p>Any suggestions on how can I implement.</p>
| 16 | 2009-09-04T00:17:29Z | 14,728,237 | <p>You can also try this if your would like all the occurrences output in a list :</p>
<pre><code>import re
str1 = "IWantToMasterPython"
out = re.compile('Master(.*?)thon', re.DOTALL | re.IGNORECASE).findall(str1)
if out :
print out
</code></pre>
| 0 | 2013-02-06T11:43:55Z | [
"python",
"string"
] |
PyParsing simple language expressions | 1,376,716 | <p>I'm trying to write something that will parse some code. I'm able to successfully parse <code>foo(spam)</code> and <code>spam+eggs</code>, but <code>foo(spam+eggs)</code> (recursive descent? my terminology from compilers is a bit rusty) fails.</p>
<p>I have the following code:</p>
<pre><code>from pyparsing_py3 import *
myVal = Word(alphas+nums+'_')
myFunction = myVal + '(' + delimitedList( myVal ) + ')'
myExpr = Forward()
mySubExpr = ( \
myVal \
| (Suppress('(') + Group(myExpr) + Suppress(')')) \
| myFunction \
)
myExpr << Group( mySubExpr + ZeroOrMore( oneOf('+ - / * =') + mySubExpr ) )
# SHOULD return: [blah, [foo, +, bar]]
# but actually returns: [blah]
print(myExpr.parseString('blah(foo+bar)'))
</code></pre>
| 2 | 2009-09-04T00:46:21Z | 1,376,851 | <p>Several issues: delimitedList is looking for a comma-delimited list of myVal, i.e. identifiers, as the only acceptable form of argument list, so of course it can't match 'foo+bar' (not a comma-delimited list of myVal!); fixing that reveals another -- myVal and myFunction start the same way so their order in mySubExpr matters; fixing that reveals yet another -- TWO levels of nesting instead of one. This versions seems ok...:</p>
<pre><code>myVal = Word(alphas+nums+'_')
myExpr = Forward()
mySubExpr = (
(Suppress('(') + Group(myExpr) + Suppress(')'))
| myVal + Suppress('(') + Group(delimitedList(myExpr)) + Suppress(')')
| myVal
)
myExpr << mySubExpr + ZeroOrMore( oneOf('+ - / * =') + mySubExpr )
print(myExpr.parseString('blah(foo+bar)'))
</code></pre>
<p>emits <code>['blah', ['foo', '+', 'bar']]</code> as desired. I also removed the redundant backslashes, since logical line continuation occurs anyway within parentheses; they were innocuous but did hamper readability.</p>
| 4 | 2009-09-04T01:47:33Z | [
"python",
"parsing",
"pyparsing"
] |
PyParsing simple language expressions | 1,376,716 | <p>I'm trying to write something that will parse some code. I'm able to successfully parse <code>foo(spam)</code> and <code>spam+eggs</code>, but <code>foo(spam+eggs)</code> (recursive descent? my terminology from compilers is a bit rusty) fails.</p>
<p>I have the following code:</p>
<pre><code>from pyparsing_py3 import *
myVal = Word(alphas+nums+'_')
myFunction = myVal + '(' + delimitedList( myVal ) + ')'
myExpr = Forward()
mySubExpr = ( \
myVal \
| (Suppress('(') + Group(myExpr) + Suppress(')')) \
| myFunction \
)
myExpr << Group( mySubExpr + ZeroOrMore( oneOf('+ - / * =') + mySubExpr ) )
# SHOULD return: [blah, [foo, +, bar]]
# but actually returns: [blah]
print(myExpr.parseString('blah(foo+bar)'))
</code></pre>
| 2 | 2009-09-04T00:46:21Z | 1,377,708 | <p>I've found that a good habit to get into when using the '<<' operator with Forwards is to always enclose the RHS in parentheses. That is:</p>
<pre><code>myExpr << mySubExpr + ZeroOrMore( oneOf('+ - / * =') + mySubExpr )
</code></pre>
<p>is better as:</p>
<pre><code>myExpr << ( mySubExpr + ZeroOrMore( oneOf('+ - / * =') + mySubExpr ) )
</code></pre>
<p>This is a result of my unfortunate choice of '<<' as the "insertion" operator for inserting the expression into a Forward. The parentheses are unnecessary in this particular case, but in this one:</p>
<pre><code>integer = Word(nums)
myExpr << mySubExpr + ZeroOrMore( oneOf('+ - / * =') + mySubExpr ) | integer
</code></pre>
<p>we see why I say "unfortunate". If I simplify this to "A << B | C", we easily see that the precedence of operations causes evaluation to be performed as "(A << B) | C", since '<<' has higher precedence than '|'. The result is that the Forward A only gets the expression B inserted in it. The "| C" part does get executed, but what happens is that you get "A | C" which creates a MatchFirst object, which is then immediately discarded since it is not assigned to any variable name. The solution would be to group the statement within parentheses as "A << (B | C)". In expressions composed only using '+' operations, there is no actual need for the parentheses, since '+' has a higher precedence than '<<'. But this is just lucky coding, and causes problem when someone later adds an alternative expression using '|' and doesn't realize the precedence implications. So I suggest just adopting the style "A << (expression)" to help avoid this confusion.</p>
<p>(Someday I will write pyparsing 2.0 - which will allow me to break compatibilty with existing code - and change this to use the '<<=' operator, which fixes all of these precedence issues, since '<<=' has lower precedence than any of the other operators used by pyparsing.)</p>
| 4 | 2009-09-04T07:29:36Z | [
"python",
"parsing",
"pyparsing"
] |
calculate user inputed time with Python | 1,376,835 | <p>I need to calculate (using python) how much time a user has inputed, whether they input something like 3:30 or 3.5. I'm not really sure what the best way to go about this is and I thought I'd ask for advice from the experts. </p>
<p>=== Edit ==================</p>
<p>To specify more clearly, I want the user to input hours and minutes or just minutes. I want them to be able to input the time in two formats, either in hh:mm (3:30 or 03:30) or as a float (3.5) hours. </p>
<p>The overall goal is to keep track of the time they have worked. So, I will be adding the time they enter up to get a total.</p>
| 0 | 2009-09-04T01:40:30Z | 1,376,843 | <p>There are a few possible solutions, but at some point you're gonna run into ambiguous cases that will result in arbitrary conversions.</p>
<p>Overall I'd suggest taking any input and parsing the separators (whether : or . or something else) and then converting to seconds based on some schema of units you've defined.</p>
<p>Alternatively you could do a series of try/except statements to test it against different time formatting schemes to see if it matches.</p>
<p>I'm not sure what will be best in your case...</p>
| 0 | 2009-09-04T01:45:07Z | [
"python",
"regex"
] |
calculate user inputed time with Python | 1,376,835 | <p>I need to calculate (using python) how much time a user has inputed, whether they input something like 3:30 or 3.5. I'm not really sure what the best way to go about this is and I thought I'd ask for advice from the experts. </p>
<p>=== Edit ==================</p>
<p>To specify more clearly, I want the user to input hours and minutes or just minutes. I want them to be able to input the time in two formats, either in hh:mm (3:30 or 03:30) or as a float (3.5) hours. </p>
<p>The overall goal is to keep track of the time they have worked. So, I will be adding the time they enter up to get a total.</p>
| 0 | 2009-09-04T01:40:30Z | 1,376,855 | <p>Can you precisely define the syntax of the strings that the user is allowed to input? Once you do that, if it's simple enough it can be matched by simple Python string expressions, else you may be better off with pyparsing or the like. Also, a precise syntax will make it easier to identify any ambiguities so you can either change the rules (so that no input string is ever ambiguous) or at least decide precisely how to interpret them (AND document the fact for the user's benefit!-).</p>
<p><strong>edit</strong>: given the OP's clarification (hh:mm or just minutes as a float) it seems simple:</p>
<pre><code> while True:
s = raw_input('Please enter amount of time (hh:mm or just minutes):')
try:
if ':' in s:
h, m = s.split(':')
else:
h = ''
m = s
t = int(h)*3600 + float(m)* 60
except ValueError, e:
print "Problems with your input (%r): %s" % (s, e)
print "please try again!"
else:
break
</code></pre>
<p>You may want to get finer-grained in diagnosing exactly what problem the user input may have (when you accept and parse user input, 99% of the effort goes into identifying incredibly [[expletive deleted]] mistakes: it's VERY hard to make your code foolproof, because fools are do deucedly INGENUOUS!-), but this should help you get started.</p>
| 1 | 2009-09-04T01:50:28Z | [
"python",
"regex"
] |
calculate user inputed time with Python | 1,376,835 | <p>I need to calculate (using python) how much time a user has inputed, whether they input something like 3:30 or 3.5. I'm not really sure what the best way to go about this is and I thought I'd ask for advice from the experts. </p>
<p>=== Edit ==================</p>
<p>To specify more clearly, I want the user to input hours and minutes or just minutes. I want them to be able to input the time in two formats, either in hh:mm (3:30 or 03:30) or as a float (3.5) hours. </p>
<p>The overall goal is to keep track of the time they have worked. So, I will be adding the time they enter up to get a total.</p>
| 0 | 2009-09-04T01:40:30Z | 1,376,880 | <p>First of all, you'll need some conventions. Is 3.55 five minutes to four hours, five milliseconds to four seconds, or 3 and 55/100 of a minute/hour/second? The same applies to 3:55. At least have a distinction between dot and colon, specifying that a dot means a fraction and a colon, a separator of hour/minute/second.</p>
<p>Although you haven't specified what "time" is (since or o'clock?), you'll need that too.</p>
<p>Then, it's simple a matter of having a final representation of a time that you want to work with, and keep converting the input until your final representation is achieved. Let's say you decide that ultimately time should be represented as MM:SS (two digits for minutes, a colon, two digits for seconds), you'll need to search the string for allowed occurrences of characters, and act accordingly. For example, having a colon and a dot at the same time is not allowed. If there's a single colon, you have a fraction, therefore you'll treat the second part as a fraction of 60.</p>
<p>Keep doing this until you have your final representation, and then just do what you gotta do with said "time".</p>
<p>I don't know on what constraints you're working with, but the problem could be narrowed if instead of a single "time" input, you had two: The first, where people type the hours, and the second, where they type the minutes. Of course, that would only work if you can divide the input...</p>
| 0 | 2009-09-04T02:00:46Z | [
"python",
"regex"
] |
calculate user inputed time with Python | 1,376,835 | <p>I need to calculate (using python) how much time a user has inputed, whether they input something like 3:30 or 3.5. I'm not really sure what the best way to go about this is and I thought I'd ask for advice from the experts. </p>
<p>=== Edit ==================</p>
<p>To specify more clearly, I want the user to input hours and minutes or just minutes. I want them to be able to input the time in two formats, either in hh:mm (3:30 or 03:30) or as a float (3.5) hours. </p>
<p>The overall goal is to keep track of the time they have worked. So, I will be adding the time they enter up to get a total.</p>
| 0 | 2009-09-04T01:40:30Z | 1,377,010 | <p>This is the code that we have in one of our internal web applications that we use for <strong>time-tracking</strong> purposes. When the user enters a time, the string value is passed through this function, which returns a structure of time data. </p>
<p>It's written in javascript, and the code could be directly ported to python.</p>
<p>I hope it helps a bit.</p>
<pre><code>var ParseTime_NOW_MATCH = /^ *= *$/
var ParseTime_PLUS_MATCH = /^ *\+ *([0-9]{0,2}(\.[0-9]{0,3})?) *$/
var ParseTime_12_MATCH = /^ *([0-9]{1,2}):?([0-9]{2}) *([aApP])[mM]? *$/
var ParseTime_24_MATCH = /^ *([0-9]{1,2}):?([0-9]{2}) *$/
// ########################################################################################
// Returns either:
// {
// Error: false,
// HourDecimal: NN.NN,
// HourInt: NN,
// MinuteInt: NN,
// Format12: "SS:SS SS",
// Format24: "SS:SS"
// }
// or
// {
// Error: true,
// Message: "Error Message"
// }
function ParseTime(sTime)
{
var match;
var HH12;
var HH24;
var MM60;
var AMPM;
///////////////////////////////////////////////////////////////////////////////////////
if((match = ParseTime_NOW_MATCH.exec(sTime)) != null)
{
// console.log(match);
return {Error: true, Message: "Unsupported format"};
}
///////////////////////////////////////////////////////////////////////////////////////
else if((match = ParseTime_PLUS_MATCH.exec(sTime)) != null)
{
// console.log(match);
return {Error: true, Message: "Unsupported format"};
}
///////////////////////////////////////////////////////////////////////////////////////
else if((match = ParseTime_24_MATCH.exec(sTime)) != null)
{
// console.log("24");
// console.log(match);
HH24 = parseInt(match[1], 10);
MM60 = parseInt(match[2], 10);
if(HH24 > 23 || MM60 > 59)
{
return {Error: true, Message: "Invalid Hour or Minute (24)."};
}
else if(HH24 == 0)
{
HH12 = 12;
AMPM = 'AM';
}
else if(HH24 <= 11)
{
HH12 = HH24;
AMPM = 'AM';
}
else if(HH24 == 12)
{
HH12 = HH24;
AMPM = 'PM';
}
else
{
HH12 = HH24 - 12;
AMPM = 'PM';
}
}
///////////////////////////////////////////////////////////////////////////////////////
else if((match = ParseTime_12_MATCH.exec(sTime)) != null)
{
// console.log(match);
AMPM = ((match[3] == 'A' || match[3] == 'a') ? 'AM' : 'PM');
HH12 = parseInt(match[1], 10);
MM60 = parseInt(match[2], 10);
if(HH12 > 12 || HH12 < 1 || MM60 > 59)
{
return {Error: true, Message: "Invalid Hour or Minute (12)."};
}
else if(HH12 == 12 && AMPM == 'AM')
{
HH24 = 0;
}
else if(AMPM == 'AM')
{
HH24 = HH12;
}
else if(AMPM == 'PM')
{
HH24 = HH12 + 12;
}
}
///////////////////////////////////////////////////////////////////////////////////////
else
{
return {Error: true, Message: "Invalid Time Format."};
}
return {
Error : false,
HourDecimal : HH24 + (MM60 / 60),
HourInt : HH24,
MinuteInt : MM60,
Format12 : HH12 + ':' + (MM60 < 10 ? "0"+MM60 : MM60) + ' ' + AMPM,
Format24 : (HH24 < 10 ? "0"+HH24 : HH24) + ':' + (MM60 < 10 ? "0"+MM60 : MM60)
}
}
</code></pre>
| 0 | 2009-09-04T03:01:20Z | [
"python",
"regex"
] |
calculate user inputed time with Python | 1,376,835 | <p>I need to calculate (using python) how much time a user has inputed, whether they input something like 3:30 or 3.5. I'm not really sure what the best way to go about this is and I thought I'd ask for advice from the experts. </p>
<p>=== Edit ==================</p>
<p>To specify more clearly, I want the user to input hours and minutes or just minutes. I want them to be able to input the time in two formats, either in hh:mm (3:30 or 03:30) or as a float (3.5) hours. </p>
<p>The overall goal is to keep track of the time they have worked. So, I will be adding the time they enter up to get a total.</p>
| 0 | 2009-09-04T01:40:30Z | 1,377,036 | <p>Can you do this with a <strong>GUI and restrict the user input</strong>? Processing the text seems super error prone otherwise (on the part of the user, not to mention the programmer), and for hours worked... you sort-of want to get that right.</p>
| 0 | 2009-09-04T03:15:22Z | [
"python",
"regex"
] |
Porting from Python to C# | 1,376,976 | <p>I´m trying to learn C#, coming from a Python/PHP background, and I´m trying to port a script from Python to getting started.</p>
<p>The script reads a text file line by line (about 150K lines), apply a list of regex until one is matched, get the named groups results and add the values as properties of a class.</p>
<p>Here´s how the data looks like (each line starting by 'No.' is the beginning of a new record):</p>
<pre>
No.813177294 09/01/1987 150
Tit.INCAL INDÃSTRIA DE CALÃADOS LTDA (BR/PE)
*PARÃGRAFO ÃNICO DO ART. 162 DA LPI.
Procurador: ROBERTO C. FREIRE
No.901699870 02/06/2009 LD6
*Exigência Formal não respondida, Pedido de Registro de Marca considerado inexistente, de acordo com o Art. 157 da LPI
No.830009817 12/12/2008 003
Tit.BIOLAB SANUS FARMACÃUTICA LTDA. (BR/SP)
C.N.P.J./C.I.C./NºINPI : 49475833000106
Apres.: Nominativa ; Nat.: De Produto
Marca: ENXUG
NCL(9) 05 medicamentos para uso humano; preparações farmacêuticas; diuréticos, analgésicos;
anestésicos; anti-helmÃnticos; antibióticos; hormônios para uso medicinal.
Procurador: CRUZEIRO/NEWMARC PATENTES E MARCAS LTDA
</pre>
<p>And how the regex looks like:</p>
<pre><code>regexp = {
# No.123456789 13/12/2008 560
# No.123456789 13/12/2008 560
# No.123456789 13/12/2008 560
# No.123456789 560
'number': re.compile(r'No.(?P<Number>[\d]{9}) +((?P<Date>[\d]{2}/[\d]{2}/[\d]{4}) +)?(?P<Code>.*)'),
# NCL(7) 25 no no no no no ; no no no no no no; *nonono no non o nono
# NCL(9) 25 no no no no no ; no no no no no no; *nonono no non o nono
'ncl': re.compile(r'NCL\([\d]{1}\) (?P<Ncl>[\d]{2})( (?P<Especification>.*))?'),
'doc': re.compile(r'C.N.P.J./C.I.C./NºINPI : (?P<Document>.*)'),
'description': re.compile(r'\*(?P<Description>.*)'),
...
}
</code></pre>
<h2>Now my questions:</h2>
<p>1) Can I use the same concept, applying each of a <code>Dictionary<string, Regex></code> in each line until one is matched?</p>
<p>2) If I do, there´s a way to get a <code>Dictionary<string, string></code> of the named groups results? (At this stage I can treat everything as a string).</p>
<p>3) If supposed I have a class like this...</p>
<pre><code>class Record
{
public string Number { get; set; }
public string Date { get; set; }
public string Code { get; set; }
public string Ncl { get; set; }
public string Especification { get; set; }
public string Document { get; set; }
public string Description { get; set; }
}
</code></pre>
<p>...there is a way to set the properties with the values of the named groups?</p>
<p>4) I´m totally missing the point here, trying to code in a static typed language still thinking in a dynamically typed one? If this is the case, what can I do?</p>
<p>Sorry for this somewhat lengthy question. I really tried to resume to make this shorter :-)</p>
<p>Thanks in advance.</p>
| 1 | 2009-09-04T02:41:26Z | 1,376,987 | <p>Sorry this is not a specific answer, but could you use IronPython to convert your scripts to run under the CLR and then step to C#?</p>
| 1 | 2009-09-04T02:47:43Z | [
"c#",
"python"
] |
Porting from Python to C# | 1,376,976 | <p>I´m trying to learn C#, coming from a Python/PHP background, and I´m trying to port a script from Python to getting started.</p>
<p>The script reads a text file line by line (about 150K lines), apply a list of regex until one is matched, get the named groups results and add the values as properties of a class.</p>
<p>Here´s how the data looks like (each line starting by 'No.' is the beginning of a new record):</p>
<pre>
No.813177294 09/01/1987 150
Tit.INCAL INDÃSTRIA DE CALÃADOS LTDA (BR/PE)
*PARÃGRAFO ÃNICO DO ART. 162 DA LPI.
Procurador: ROBERTO C. FREIRE
No.901699870 02/06/2009 LD6
*Exigência Formal não respondida, Pedido de Registro de Marca considerado inexistente, de acordo com o Art. 157 da LPI
No.830009817 12/12/2008 003
Tit.BIOLAB SANUS FARMACÃUTICA LTDA. (BR/SP)
C.N.P.J./C.I.C./NºINPI : 49475833000106
Apres.: Nominativa ; Nat.: De Produto
Marca: ENXUG
NCL(9) 05 medicamentos para uso humano; preparações farmacêuticas; diuréticos, analgésicos;
anestésicos; anti-helmÃnticos; antibióticos; hormônios para uso medicinal.
Procurador: CRUZEIRO/NEWMARC PATENTES E MARCAS LTDA
</pre>
<p>And how the regex looks like:</p>
<pre><code>regexp = {
# No.123456789 13/12/2008 560
# No.123456789 13/12/2008 560
# No.123456789 13/12/2008 560
# No.123456789 560
'number': re.compile(r'No.(?P<Number>[\d]{9}) +((?P<Date>[\d]{2}/[\d]{2}/[\d]{4}) +)?(?P<Code>.*)'),
# NCL(7) 25 no no no no no ; no no no no no no; *nonono no non o nono
# NCL(9) 25 no no no no no ; no no no no no no; *nonono no non o nono
'ncl': re.compile(r'NCL\([\d]{1}\) (?P<Ncl>[\d]{2})( (?P<Especification>.*))?'),
'doc': re.compile(r'C.N.P.J./C.I.C./NºINPI : (?P<Document>.*)'),
'description': re.compile(r'\*(?P<Description>.*)'),
...
}
</code></pre>
<h2>Now my questions:</h2>
<p>1) Can I use the same concept, applying each of a <code>Dictionary<string, Regex></code> in each line until one is matched?</p>
<p>2) If I do, there´s a way to get a <code>Dictionary<string, string></code> of the named groups results? (At this stage I can treat everything as a string).</p>
<p>3) If supposed I have a class like this...</p>
<pre><code>class Record
{
public string Number { get; set; }
public string Date { get; set; }
public string Code { get; set; }
public string Ncl { get; set; }
public string Especification { get; set; }
public string Document { get; set; }
public string Description { get; set; }
}
</code></pre>
<p>...there is a way to set the properties with the values of the named groups?</p>
<p>4) I´m totally missing the point here, trying to code in a static typed language still thinking in a dynamically typed one? If this is the case, what can I do?</p>
<p>Sorry for this somewhat lengthy question. I really tried to resume to make this shorter :-)</p>
<p>Thanks in advance.</p>
| 1 | 2009-09-04T02:41:26Z | 1,376,994 | <p>1., sure</p>
<p>2., see e.g. here</p>
<p>3., yep, same basic concept as 2</p>
<p>4., nah, C# is flexible enough to allow you to port your architecture over</p>
<p>Also consider studying <a href="http://www.manning.com/foord/" rel="nofollow">this book</a> as the best intro to .NET for Python programmers AND vice versa (I'm biased, having been a tech editor and being a friend of the author, but I think this is objectively defensible;-).</p>
| 3 | 2009-09-04T02:52:14Z | [
"c#",
"python"
] |
Porting from Python to C# | 1,376,976 | <p>I´m trying to learn C#, coming from a Python/PHP background, and I´m trying to port a script from Python to getting started.</p>
<p>The script reads a text file line by line (about 150K lines), apply a list of regex until one is matched, get the named groups results and add the values as properties of a class.</p>
<p>Here´s how the data looks like (each line starting by 'No.' is the beginning of a new record):</p>
<pre>
No.813177294 09/01/1987 150
Tit.INCAL INDÃSTRIA DE CALÃADOS LTDA (BR/PE)
*PARÃGRAFO ÃNICO DO ART. 162 DA LPI.
Procurador: ROBERTO C. FREIRE
No.901699870 02/06/2009 LD6
*Exigência Formal não respondida, Pedido de Registro de Marca considerado inexistente, de acordo com o Art. 157 da LPI
No.830009817 12/12/2008 003
Tit.BIOLAB SANUS FARMACÃUTICA LTDA. (BR/SP)
C.N.P.J./C.I.C./NºINPI : 49475833000106
Apres.: Nominativa ; Nat.: De Produto
Marca: ENXUG
NCL(9) 05 medicamentos para uso humano; preparações farmacêuticas; diuréticos, analgésicos;
anestésicos; anti-helmÃnticos; antibióticos; hormônios para uso medicinal.
Procurador: CRUZEIRO/NEWMARC PATENTES E MARCAS LTDA
</pre>
<p>And how the regex looks like:</p>
<pre><code>regexp = {
# No.123456789 13/12/2008 560
# No.123456789 13/12/2008 560
# No.123456789 13/12/2008 560
# No.123456789 560
'number': re.compile(r'No.(?P<Number>[\d]{9}) +((?P<Date>[\d]{2}/[\d]{2}/[\d]{4}) +)?(?P<Code>.*)'),
# NCL(7) 25 no no no no no ; no no no no no no; *nonono no non o nono
# NCL(9) 25 no no no no no ; no no no no no no; *nonono no non o nono
'ncl': re.compile(r'NCL\([\d]{1}\) (?P<Ncl>[\d]{2})( (?P<Especification>.*))?'),
'doc': re.compile(r'C.N.P.J./C.I.C./NºINPI : (?P<Document>.*)'),
'description': re.compile(r'\*(?P<Description>.*)'),
...
}
</code></pre>
<h2>Now my questions:</h2>
<p>1) Can I use the same concept, applying each of a <code>Dictionary<string, Regex></code> in each line until one is matched?</p>
<p>2) If I do, there´s a way to get a <code>Dictionary<string, string></code> of the named groups results? (At this stage I can treat everything as a string).</p>
<p>3) If supposed I have a class like this...</p>
<pre><code>class Record
{
public string Number { get; set; }
public string Date { get; set; }
public string Code { get; set; }
public string Ncl { get; set; }
public string Especification { get; set; }
public string Document { get; set; }
public string Description { get; set; }
}
</code></pre>
<p>...there is a way to set the properties with the values of the named groups?</p>
<p>4) I´m totally missing the point here, trying to code in a static typed language still thinking in a dynamically typed one? If this is the case, what can I do?</p>
<p>Sorry for this somewhat lengthy question. I really tried to resume to make this shorter :-)</p>
<p>Thanks in advance.</p>
| 1 | 2009-09-04T02:41:26Z | 1,376,995 | <ol>
<li>Yes you can. </li>
<li>.Net has support for named groups. So for <code>(?<first>group)(?'second'group)</code>, the returned Match object will support named retrieval like this. You can build youself a dictionary from this object or directly pass the Match object<br />
<code>var match = Regex.Match("subject", "regex");<br />
var matchedText = match.Groups("first")</code><br />
See <a href="http://www.regular-expressions.info/named.html" rel="nofollow">Named Groups in .Net</a> and <a href="http://www.regular-expressions.info/dotnet.html" rel="nofollow">Regex support in .Net</a></li>
<li>I think writing a <code>Record Record.Parse(namedValueCollection)</code> would be a way to do it</li>
<li>You write code... You learn. I find the reverse direction a bit disorienting.. Moving from dynamic to static should be relatively easier... just that you might have to write relatively more code for some routine tasks like iteration or map or select etc.</li>
</ol>
| 2 | 2009-09-04T02:53:04Z | [
"c#",
"python"
] |
Porting from Python to C# | 1,376,976 | <p>I´m trying to learn C#, coming from a Python/PHP background, and I´m trying to port a script from Python to getting started.</p>
<p>The script reads a text file line by line (about 150K lines), apply a list of regex until one is matched, get the named groups results and add the values as properties of a class.</p>
<p>Here´s how the data looks like (each line starting by 'No.' is the beginning of a new record):</p>
<pre>
No.813177294 09/01/1987 150
Tit.INCAL INDÃSTRIA DE CALÃADOS LTDA (BR/PE)
*PARÃGRAFO ÃNICO DO ART. 162 DA LPI.
Procurador: ROBERTO C. FREIRE
No.901699870 02/06/2009 LD6
*Exigência Formal não respondida, Pedido de Registro de Marca considerado inexistente, de acordo com o Art. 157 da LPI
No.830009817 12/12/2008 003
Tit.BIOLAB SANUS FARMACÃUTICA LTDA. (BR/SP)
C.N.P.J./C.I.C./NºINPI : 49475833000106
Apres.: Nominativa ; Nat.: De Produto
Marca: ENXUG
NCL(9) 05 medicamentos para uso humano; preparações farmacêuticas; diuréticos, analgésicos;
anestésicos; anti-helmÃnticos; antibióticos; hormônios para uso medicinal.
Procurador: CRUZEIRO/NEWMARC PATENTES E MARCAS LTDA
</pre>
<p>And how the regex looks like:</p>
<pre><code>regexp = {
# No.123456789 13/12/2008 560
# No.123456789 13/12/2008 560
# No.123456789 13/12/2008 560
# No.123456789 560
'number': re.compile(r'No.(?P<Number>[\d]{9}) +((?P<Date>[\d]{2}/[\d]{2}/[\d]{4}) +)?(?P<Code>.*)'),
# NCL(7) 25 no no no no no ; no no no no no no; *nonono no non o nono
# NCL(9) 25 no no no no no ; no no no no no no; *nonono no non o nono
'ncl': re.compile(r'NCL\([\d]{1}\) (?P<Ncl>[\d]{2})( (?P<Especification>.*))?'),
'doc': re.compile(r'C.N.P.J./C.I.C./NºINPI : (?P<Document>.*)'),
'description': re.compile(r'\*(?P<Description>.*)'),
...
}
</code></pre>
<h2>Now my questions:</h2>
<p>1) Can I use the same concept, applying each of a <code>Dictionary<string, Regex></code> in each line until one is matched?</p>
<p>2) If I do, there´s a way to get a <code>Dictionary<string, string></code> of the named groups results? (At this stage I can treat everything as a string).</p>
<p>3) If supposed I have a class like this...</p>
<pre><code>class Record
{
public string Number { get; set; }
public string Date { get; set; }
public string Code { get; set; }
public string Ncl { get; set; }
public string Especification { get; set; }
public string Document { get; set; }
public string Description { get; set; }
}
</code></pre>
<p>...there is a way to set the properties with the values of the named groups?</p>
<p>4) I´m totally missing the point here, trying to code in a static typed language still thinking in a dynamically typed one? If this is the case, what can I do?</p>
<p>Sorry for this somewhat lengthy question. I really tried to resume to make this shorter :-)</p>
<p>Thanks in advance.</p>
| 1 | 2009-09-04T02:41:26Z | 1,376,998 | <p>If you really want to learn C#, you should demand only references and not full answers, like <a href="http://msdn.microsoft.com/en-us/library/30wbz966%28VS.71%29.aspx" rel="nofollow">this one (RegEx class)</a>, but I'm sure you can find much more information with a quick Google search too.</p>
| 1 | 2009-09-04T02:54:09Z | [
"c#",
"python"
] |
Porting from Python to C# | 1,376,976 | <p>I´m trying to learn C#, coming from a Python/PHP background, and I´m trying to port a script from Python to getting started.</p>
<p>The script reads a text file line by line (about 150K lines), apply a list of regex until one is matched, get the named groups results and add the values as properties of a class.</p>
<p>Here´s how the data looks like (each line starting by 'No.' is the beginning of a new record):</p>
<pre>
No.813177294 09/01/1987 150
Tit.INCAL INDÃSTRIA DE CALÃADOS LTDA (BR/PE)
*PARÃGRAFO ÃNICO DO ART. 162 DA LPI.
Procurador: ROBERTO C. FREIRE
No.901699870 02/06/2009 LD6
*Exigência Formal não respondida, Pedido de Registro de Marca considerado inexistente, de acordo com o Art. 157 da LPI
No.830009817 12/12/2008 003
Tit.BIOLAB SANUS FARMACÃUTICA LTDA. (BR/SP)
C.N.P.J./C.I.C./NºINPI : 49475833000106
Apres.: Nominativa ; Nat.: De Produto
Marca: ENXUG
NCL(9) 05 medicamentos para uso humano; preparações farmacêuticas; diuréticos, analgésicos;
anestésicos; anti-helmÃnticos; antibióticos; hormônios para uso medicinal.
Procurador: CRUZEIRO/NEWMARC PATENTES E MARCAS LTDA
</pre>
<p>And how the regex looks like:</p>
<pre><code>regexp = {
# No.123456789 13/12/2008 560
# No.123456789 13/12/2008 560
# No.123456789 13/12/2008 560
# No.123456789 560
'number': re.compile(r'No.(?P<Number>[\d]{9}) +((?P<Date>[\d]{2}/[\d]{2}/[\d]{4}) +)?(?P<Code>.*)'),
# NCL(7) 25 no no no no no ; no no no no no no; *nonono no non o nono
# NCL(9) 25 no no no no no ; no no no no no no; *nonono no non o nono
'ncl': re.compile(r'NCL\([\d]{1}\) (?P<Ncl>[\d]{2})( (?P<Especification>.*))?'),
'doc': re.compile(r'C.N.P.J./C.I.C./NºINPI : (?P<Document>.*)'),
'description': re.compile(r'\*(?P<Description>.*)'),
...
}
</code></pre>
<h2>Now my questions:</h2>
<p>1) Can I use the same concept, applying each of a <code>Dictionary<string, Regex></code> in each line until one is matched?</p>
<p>2) If I do, there´s a way to get a <code>Dictionary<string, string></code> of the named groups results? (At this stage I can treat everything as a string).</p>
<p>3) If supposed I have a class like this...</p>
<pre><code>class Record
{
public string Number { get; set; }
public string Date { get; set; }
public string Code { get; set; }
public string Ncl { get; set; }
public string Especification { get; set; }
public string Document { get; set; }
public string Description { get; set; }
}
</code></pre>
<p>...there is a way to set the properties with the values of the named groups?</p>
<p>4) I´m totally missing the point here, trying to code in a static typed language still thinking in a dynamically typed one? If this is the case, what can I do?</p>
<p>Sorry for this somewhat lengthy question. I really tried to resume to make this shorter :-)</p>
<p>Thanks in advance.</p>
| 1 | 2009-09-04T02:41:26Z | 1,377,059 | <p>What you're looking for sounds do-able. Of course you'll want to look at <code>System.Text.RegularExpressions</code>, specifically the <code>Regex</code> type there. </p>
<p>Additionally, I'm really fond of the iterator pattern for reading lines from a file:</p>
<pre><code>public static IEnumerable<string> ReadLines(string path)
{
using(var sr = new StreamReader(path))
{
string line;
while ( (line = sr.ReadLine()) != null)
{
yield return line;
}
}
}
</code></pre>
<p>You start with that base code (which you can re-use almost everywhere) and call it in this method:</p>
<pre><code>public static IEnumerable<Record> ReadRecords(string path)
{
IEnumerable<Regex> expresssions = new List<Regex>
{
new Regex( @"No.(?P<Number>[\d]{9}) +((?P<Date>[\d]{2}/[\d]{2}/[\d]{4}) +)?(?P<Code>.*)" ),
new Regex( @"NCL\([\d]{1}\) (?P<Ncl>[\d]{2})( (?P<Especification>"),
new Regex( @"C.N.P.J./C.I.C./NºINPI : (?P<Document>.*)")
};
foreach ( MatchCollection matches
in ReadLines(path)
.Select(s => expressions.First(e => e.IsMatch(s)).Matches(s)))
.Where(m => m.Count > 0)
)
{
yield return Record.FromExpressionMatches(matches);
}
}
</code></pre>
<p>Finish it up by adding a static factory method to your Record class that accepts a MatchCollection parameter. The one thing it looks like you're missing here is that you expect to hit each of the expressions once before completing a single record. That will work a little differently. But hopefully this gives you enough to get you really going.</p>
| 1 | 2009-09-04T03:23:04Z | [
"c#",
"python"
] |
Porting from Python to C# | 1,376,976 | <p>I´m trying to learn C#, coming from a Python/PHP background, and I´m trying to port a script from Python to getting started.</p>
<p>The script reads a text file line by line (about 150K lines), apply a list of regex until one is matched, get the named groups results and add the values as properties of a class.</p>
<p>Here´s how the data looks like (each line starting by 'No.' is the beginning of a new record):</p>
<pre>
No.813177294 09/01/1987 150
Tit.INCAL INDÃSTRIA DE CALÃADOS LTDA (BR/PE)
*PARÃGRAFO ÃNICO DO ART. 162 DA LPI.
Procurador: ROBERTO C. FREIRE
No.901699870 02/06/2009 LD6
*Exigência Formal não respondida, Pedido de Registro de Marca considerado inexistente, de acordo com o Art. 157 da LPI
No.830009817 12/12/2008 003
Tit.BIOLAB SANUS FARMACÃUTICA LTDA. (BR/SP)
C.N.P.J./C.I.C./NºINPI : 49475833000106
Apres.: Nominativa ; Nat.: De Produto
Marca: ENXUG
NCL(9) 05 medicamentos para uso humano; preparações farmacêuticas; diuréticos, analgésicos;
anestésicos; anti-helmÃnticos; antibióticos; hormônios para uso medicinal.
Procurador: CRUZEIRO/NEWMARC PATENTES E MARCAS LTDA
</pre>
<p>And how the regex looks like:</p>
<pre><code>regexp = {
# No.123456789 13/12/2008 560
# No.123456789 13/12/2008 560
# No.123456789 13/12/2008 560
# No.123456789 560
'number': re.compile(r'No.(?P<Number>[\d]{9}) +((?P<Date>[\d]{2}/[\d]{2}/[\d]{4}) +)?(?P<Code>.*)'),
# NCL(7) 25 no no no no no ; no no no no no no; *nonono no non o nono
# NCL(9) 25 no no no no no ; no no no no no no; *nonono no non o nono
'ncl': re.compile(r'NCL\([\d]{1}\) (?P<Ncl>[\d]{2})( (?P<Especification>.*))?'),
'doc': re.compile(r'C.N.P.J./C.I.C./NºINPI : (?P<Document>.*)'),
'description': re.compile(r'\*(?P<Description>.*)'),
...
}
</code></pre>
<h2>Now my questions:</h2>
<p>1) Can I use the same concept, applying each of a <code>Dictionary<string, Regex></code> in each line until one is matched?</p>
<p>2) If I do, there´s a way to get a <code>Dictionary<string, string></code> of the named groups results? (At this stage I can treat everything as a string).</p>
<p>3) If supposed I have a class like this...</p>
<pre><code>class Record
{
public string Number { get; set; }
public string Date { get; set; }
public string Code { get; set; }
public string Ncl { get; set; }
public string Especification { get; set; }
public string Document { get; set; }
public string Description { get; set; }
}
</code></pre>
<p>...there is a way to set the properties with the values of the named groups?</p>
<p>4) I´m totally missing the point here, trying to code in a static typed language still thinking in a dynamically typed one? If this is the case, what can I do?</p>
<p>Sorry for this somewhat lengthy question. I really tried to resume to make this shorter :-)</p>
<p>Thanks in advance.</p>
| 1 | 2009-09-04T02:41:26Z | 1,377,253 | <pre><code>dictionary<string,string> dic_test = new dictionary<string,string>();
dic_test.add(key,value);
</code></pre>
| 0 | 2009-09-04T04:40:36Z | [
"c#",
"python"
] |
How do you deal with missing data using numpy/scipy? | 1,377,130 | <p>One of the things I deal with most in data cleaning is missing values. R deals with this well using its "NA" missing data label. In python, it appears that I'll have to deal with masked arrays which seem to be a major pain to set up and don't seem to be well documented. Any suggestions on making this process easier in Python? This is becoming a deal-breaker in moving into Python for data analysis. Thanks</p>
<p><strong>Update</strong> It's obviously been a while since I've looked at the methods in the numpy.ma module. It appears that at least the basic analysis functions are available for masked arrays, and the examples provided helped me understand how to create masked arrays (thanks to the authors). I would like to see if some of the newer statistical methods in Python (being developed in this year's GSoC) incorporates this aspect, and at least does the complete case analysis.</p>
| 9 | 2009-09-04T03:44:57Z | 1,380,476 | <p>I also question the problem with masked arrays. Here are a couple of examples:</p>
<pre><code>import numpy as np
data = np.ma.masked_array(np.arange(10))
data[5] = np.ma.masked # Mask a specific value
data[data>6] = np.ma.masked # Mask any value greater than 6
# Same thing done at initialization time
init_data = np.arange(10)
data = np.ma.masked_array(init_data, mask=(init_data > 6))
</code></pre>
| 1 | 2009-09-04T17:08:30Z | [
"python",
"numpy",
"data-analysis"
] |
How do you deal with missing data using numpy/scipy? | 1,377,130 | <p>One of the things I deal with most in data cleaning is missing values. R deals with this well using its "NA" missing data label. In python, it appears that I'll have to deal with masked arrays which seem to be a major pain to set up and don't seem to be well documented. Any suggestions on making this process easier in Python? This is becoming a deal-breaker in moving into Python for data analysis. Thanks</p>
<p><strong>Update</strong> It's obviously been a while since I've looked at the methods in the numpy.ma module. It appears that at least the basic analysis functions are available for masked arrays, and the examples provided helped me understand how to create masked arrays (thanks to the authors). I would like to see if some of the newer statistical methods in Python (being developed in this year's GSoC) incorporates this aspect, and at least does the complete case analysis.</p>
| 9 | 2009-09-04T03:44:57Z | 1,380,530 | <p>Masked arrays are the anwswer, as DpplerShift describes. For quick and dirty use, you can use fancy indexing with boolean arrays:</p>
<pre><code>>>> import numpy as np
>>> data = np.arange(10)
>>> valid_idx = data % 2 == 0 #pretend that even elements are missing
>>> # Get non-missing data
>>> data[valid_idx]
array([0, 2, 4, 6, 8])
</code></pre>
<p>You can now use valid_idx as a quick mask on other data as well</p>
<pre><code>>>> comparison = np.arange(10) + 10
>>> comparison[valid_idx]
array([10, 12, 14, 16, 18])
</code></pre>
| 1 | 2009-09-04T17:22:16Z | [
"python",
"numpy",
"data-analysis"
] |
How do you deal with missing data using numpy/scipy? | 1,377,130 | <p>One of the things I deal with most in data cleaning is missing values. R deals with this well using its "NA" missing data label. In python, it appears that I'll have to deal with masked arrays which seem to be a major pain to set up and don't seem to be well documented. Any suggestions on making this process easier in Python? This is becoming a deal-breaker in moving into Python for data analysis. Thanks</p>
<p><strong>Update</strong> It's obviously been a while since I've looked at the methods in the numpy.ma module. It appears that at least the basic analysis functions are available for masked arrays, and the examples provided helped me understand how to create masked arrays (thanks to the authors). I would like to see if some of the newer statistical methods in Python (being developed in this year's GSoC) incorporates this aspect, and at least does the complete case analysis.</p>
| 9 | 2009-09-04T03:44:57Z | 11,086,822 | <p>If you are willing to consider a library, pandas (http://pandas.pydata.org/) is a library built on top of numpy which amongst many other things provides:</p>
<blockquote>
<p>Intelligent data alignment and integrated handling of missing data: gain automatic label-based alignment in computations and easily manipulate messy data into an orderly form</p>
</blockquote>
<p>I've been using it for almost one year in the financial industry where missing and badly aligned data is the norm and it really made my life easier.</p>
| 4 | 2012-06-18T16:12:12Z | [
"python",
"numpy",
"data-analysis"
] |
How to make this code handle big inputs more efficiently? | 1,377,335 | <p>Hey. I know this is not a 'refactor my code' site but I made this little piece of code which works perfectly fine with moderately sized input but it's problematic with string of size, say, over 2000.</p>
<p>What it does - it takes a string of numbers as a parameter, and it returns the number of ways it can be interpreted as a string of letters, where each letter in the English alphabet is assigned a numeric value according to its lexical position: A -> 1, B-> 2, Z-> 26 etc.</p>
<p>Since some letters are represented as two numbers the suffix tree is not unique so there can be multiple interpretations. For example '111' could be both 'AAA', 'KA' and 'AK'.</p>
<p>This is my code. It's fairly readable and straightforward but it's problematic because:</p>
<ol>
<li>It has to copy part of the string every time to call it as argument to the recursive part.</li>
<li>It has to store huge strings in the cache so it's very expensive, memory-wise.</li>
<li>... it's recursive.</li>
</ol>
<p>Help much appreciated :)</p>
<pre><code>cache = dict()
def alpha_code(numbers):
"""
Returns the number of ways a string of numbers
can be interpreted as an alphabetic sequence.
"""
global cache
if numbers in cache: return cache[numbers]
## check the basic cases
if numbers.startswith('0'): return 0
if len(numbers) <= 1: return 1
## dynamic programming part
## obviously we can treat the first (non-zero)
## digit as a single letter and continue -
## '342...' -> C + '42...'
total = alpha_code(numbers[1:])
## the first two digits make for a legal letter
## iff this condition holds
## '2511...' -> Y + '11...'
## '3711...' -> illegal
if numbers[:2] <= '26':
total += alpha_code(numbers[2:])
cache[numbers] = total
return total
</code></pre>
| 1 | 2009-09-04T05:11:36Z | 1,377,387 | <p>Try using a dynamic programming approach instead:</p>
<ol>
<li>Create an array (call it 'P') with 1 element per character in the string.</li>
<li>Initialize P[0] = 1 (unless the first character is 0, in which case just return 0 for the result).</li>
<li>Initialize P[1] = 2 if the first two characters can be interpreted as a letter as can the current; otherwise 1 if the current character is non-zero, otherwise return 0 for the result).</li>
<li><p>Fill in the rest of the array from left to right, via the following rule (pseudocode):</p>
<p>P[x] =
(<strong>if</strong> current character is '0' <strong>then</strong> 0, <strong>else</strong> P[x-1])
+
(<strong>if</strong> previous character + current character can be interpreted as a letter
<strong>then</strong> P[x-2] <strong>else</strong> 0)</p></li>
</ol>
<p>(Note that if P[x] is ever 0 you should return zero, since that means there were two 0's in a row which your rules don't seem to allow.)</p>
<p>The first portion of the sum is to deal with the case where the current character is interpreted as a letter; the second part of the sum is to deal with the case where the 2 most recent characters are interpreted as a letter.</p>
<p>Essentially, P[x] will be equal to the number of ways that the entirety of the string <em>from the start up to position x</em> can be interpreted as letters. Since you can determine this from looking at previous results, you only need to loop through the contents of the string once - an O(N) time instead of a O(2<sup>N</sup>) which is a huge improvement. Your final result is simply P[len(input)-1] since "everything from the start up to the end" is the same as just "the entire string".</p>
<p>Example run for your very basic input case of '111':</p>
<ul>
<li>P[0] = 1 (Since 1 is non-zero)</li>
<li>P[1] = 2 (Since 11 is a valid letter, and 1 is also a valid letter)</li>
<li>P[2] = 3 (Since the most recent two characters together are a valid letter, and the current character is nonzero, so P[0]+P[1] = 1+2 = 3)</li>
</ul>
<p>Since P[2] is our last result, and it's 3, our answer is 3.</p>
<p>If the string were '1111' instead, we'd continue another step:</p>
<ul>
<li>P[3] = 5 (Since the most recent two characters are a valid letter, and current character is non-zero, so P[1]+P[2] = 2+3 = 5)</li>
</ul>
<p>The answer is indeed 5 - valid interpretations being AAAA, KK, AKA, AAK, KAA. Notice how those 5 potential answers are built up from the potential interpretations of '11' and '111':</p>
<p>'11': AA or K
'111': AAA or KA or AK</p>
<p>'111'+A: AAA+A or KA+A or AK+A
'11'+K: AA+K or K+K</p>
| 3 | 2009-09-04T05:34:12Z | [
"python",
"recursion"
] |
How to make this code handle big inputs more efficiently? | 1,377,335 | <p>Hey. I know this is not a 'refactor my code' site but I made this little piece of code which works perfectly fine with moderately sized input but it's problematic with string of size, say, over 2000.</p>
<p>What it does - it takes a string of numbers as a parameter, and it returns the number of ways it can be interpreted as a string of letters, where each letter in the English alphabet is assigned a numeric value according to its lexical position: A -> 1, B-> 2, Z-> 26 etc.</p>
<p>Since some letters are represented as two numbers the suffix tree is not unique so there can be multiple interpretations. For example '111' could be both 'AAA', 'KA' and 'AK'.</p>
<p>This is my code. It's fairly readable and straightforward but it's problematic because:</p>
<ol>
<li>It has to copy part of the string every time to call it as argument to the recursive part.</li>
<li>It has to store huge strings in the cache so it's very expensive, memory-wise.</li>
<li>... it's recursive.</li>
</ol>
<p>Help much appreciated :)</p>
<pre><code>cache = dict()
def alpha_code(numbers):
"""
Returns the number of ways a string of numbers
can be interpreted as an alphabetic sequence.
"""
global cache
if numbers in cache: return cache[numbers]
## check the basic cases
if numbers.startswith('0'): return 0
if len(numbers) <= 1: return 1
## dynamic programming part
## obviously we can treat the first (non-zero)
## digit as a single letter and continue -
## '342...' -> C + '42...'
total = alpha_code(numbers[1:])
## the first two digits make for a legal letter
## iff this condition holds
## '2511...' -> Y + '11...'
## '3711...' -> illegal
if numbers[:2] <= '26':
total += alpha_code(numbers[2:])
cache[numbers] = total
return total
</code></pre>
| 1 | 2009-09-04T05:11:36Z | 1,377,391 | <p>A non-recursive algorithm can be written but I don't think it will be faster. I'm no python expert so I'll just give you an algorithm:</p>
<pre><code>Convert the array on numbers to an array of letters using just A thru I and leaving the zeros in place.
Create two nested loops where you search and replace all the known pairs that represent larger letters. (AA -> K)
</code></pre>
<p>The nice thing about this algorithm is you can optimize the search/replace by first searching for and indexing all the As and Bs in the array.</p>
<p>Since you are using Python, regardless of what you do, you should convert the string into a list of numbers. The numbers 0-9 are static objects in Python so that means they are free to allocate. You could also create reusable character objects of A thru Z. The other benefit of a list is the replace operation to remove two elements and insert a single element is problem much faster than copying the string over and over.</p>
| 0 | 2009-09-04T05:35:33Z | [
"python",
"recursion"
] |
How to make this code handle big inputs more efficiently? | 1,377,335 | <p>Hey. I know this is not a 'refactor my code' site but I made this little piece of code which works perfectly fine with moderately sized input but it's problematic with string of size, say, over 2000.</p>
<p>What it does - it takes a string of numbers as a parameter, and it returns the number of ways it can be interpreted as a string of letters, where each letter in the English alphabet is assigned a numeric value according to its lexical position: A -> 1, B-> 2, Z-> 26 etc.</p>
<p>Since some letters are represented as two numbers the suffix tree is not unique so there can be multiple interpretations. For example '111' could be both 'AAA', 'KA' and 'AK'.</p>
<p>This is my code. It's fairly readable and straightforward but it's problematic because:</p>
<ol>
<li>It has to copy part of the string every time to call it as argument to the recursive part.</li>
<li>It has to store huge strings in the cache so it's very expensive, memory-wise.</li>
<li>... it's recursive.</li>
</ol>
<p>Help much appreciated :)</p>
<pre><code>cache = dict()
def alpha_code(numbers):
"""
Returns the number of ways a string of numbers
can be interpreted as an alphabetic sequence.
"""
global cache
if numbers in cache: return cache[numbers]
## check the basic cases
if numbers.startswith('0'): return 0
if len(numbers) <= 1: return 1
## dynamic programming part
## obviously we can treat the first (non-zero)
## digit as a single letter and continue -
## '342...' -> C + '42...'
total = alpha_code(numbers[1:])
## the first two digits make for a legal letter
## iff this condition holds
## '2511...' -> Y + '11...'
## '3711...' -> illegal
if numbers[:2] <= '26':
total += alpha_code(numbers[2:])
cache[numbers] = total
return total
</code></pre>
| 1 | 2009-09-04T05:11:36Z | 1,377,425 | <p>Recursion elimination is always a fun task. Here, I'd focus on ensuring the cache is correctly populated, then just use it, as follows...:</p>
<pre><code>import collections
def alpha_code(numbers):
# populate cache with all needed pieces
cache = dict()
pending_work = collections.deque([numbers])
while pending_work:
work = pending_work.popleft()
# if cache[work] is known or easy, just go for it
if work in cache:
continue
if work[:1] == '0':
cache[work] = 0
continue
elif len(work) <= 1:
cache[work] = 1
continue
# are there missing pieces? If so queue up the pieces
# on the left (shorter first), the current work piece
# on the right, and keep churning
n1 = work[1:]
t1 = cache.get(n1)
if t1 is None:
pending_work.appendleft(n1)
if work[:2] <= '26':
n2 = work[2:]
t2 = cache.get(n2)
if t2 is None:
pending_work.appendleft(n2)
else:
t2 = 0
if t1 is None or t2 is None:
pending_work.append(work)
continue
# we have all pieces needed to add this one
total = t1 + t2
cache[work] = total
# cache fully populated, so we know the answer
return cache[numbers]
</code></pre>
| 1 | 2009-09-04T05:46:29Z | [
"python",
"recursion"
] |
How to make this code handle big inputs more efficiently? | 1,377,335 | <p>Hey. I know this is not a 'refactor my code' site but I made this little piece of code which works perfectly fine with moderately sized input but it's problematic with string of size, say, over 2000.</p>
<p>What it does - it takes a string of numbers as a parameter, and it returns the number of ways it can be interpreted as a string of letters, where each letter in the English alphabet is assigned a numeric value according to its lexical position: A -> 1, B-> 2, Z-> 26 etc.</p>
<p>Since some letters are represented as two numbers the suffix tree is not unique so there can be multiple interpretations. For example '111' could be both 'AAA', 'KA' and 'AK'.</p>
<p>This is my code. It's fairly readable and straightforward but it's problematic because:</p>
<ol>
<li>It has to copy part of the string every time to call it as argument to the recursive part.</li>
<li>It has to store huge strings in the cache so it's very expensive, memory-wise.</li>
<li>... it's recursive.</li>
</ol>
<p>Help much appreciated :)</p>
<pre><code>cache = dict()
def alpha_code(numbers):
"""
Returns the number of ways a string of numbers
can be interpreted as an alphabetic sequence.
"""
global cache
if numbers in cache: return cache[numbers]
## check the basic cases
if numbers.startswith('0'): return 0
if len(numbers) <= 1: return 1
## dynamic programming part
## obviously we can treat the first (non-zero)
## digit as a single letter and continue -
## '342...' -> C + '42...'
total = alpha_code(numbers[1:])
## the first two digits make for a legal letter
## iff this condition holds
## '2511...' -> Y + '11...'
## '3711...' -> illegal
if numbers[:2] <= '26':
total += alpha_code(numbers[2:])
cache[numbers] = total
return total
</code></pre>
| 1 | 2009-09-04T05:11:36Z | 1,378,705 | <p>You can largely reduce the memory footprint by not copying the string, and passing instead the original string and the index of the first character to study:</p>
<pre><code>def alpha_code(numbers, start_from = 0)
....
</code></pre>
<p>You would then call recursively as:</p>
<pre><code>alpha_code(numbers, start_from + 1) # or start_from + 2, etc.
</code></pre>
<p>This way, your preserve the simplicity of a recursive algorithm and you save a lot of memory.</p>
| 0 | 2009-09-04T11:32:27Z | [
"python",
"recursion"
] |
What is faster in Python, "while" or "for xrange" | 1,377,429 | <p>We can do numeric iteration like:</p>
<pre><code>for i in xrange(10):
print i,
</code></pre>
<p>and in C-style:</p>
<pre><code>i = 0
while i < 10:
print i,
i = i + 1
</code></pre>
<p>Yes, I know, the first one is less error-prone, more pythonic but is it fast enough as C-style version?</p>
<p>PS. I'm from C++ planet and pretty new on Python one.</p>
| 4 | 2009-09-04T05:48:23Z | 1,377,454 | <p>Who cares? Seriously. If you want to know, use timeit package (you can invoke it from command line with -m).</p>
<p>But it doesn't matter at all, because the difference is negligible. And in general, Python is not a language that you choose if you want speed.</p>
| 13 | 2009-09-04T05:57:32Z | [
"python",
"micro-optimization"
] |
What is faster in Python, "while" or "for xrange" | 1,377,429 | <p>We can do numeric iteration like:</p>
<pre><code>for i in xrange(10):
print i,
</code></pre>
<p>and in C-style:</p>
<pre><code>i = 0
while i < 10:
print i,
i = i + 1
</code></pre>
<p>Yes, I know, the first one is less error-prone, more pythonic but is it fast enough as C-style version?</p>
<p>PS. I'm from C++ planet and pretty new on Python one.</p>
| 4 | 2009-09-04T05:48:23Z | 1,377,933 | <p>They are <strong>both</strong> to avoid :-)</p>
<p>Generally speaking, each time I see an iteration over numbers, I see some non-pythonic code, that could be expressed in a better way using iterations over lists or generators.<br />
Actually, I've said "pythonic", but it is all about <strong>readability</strong>. Using idiomatic code will increase readability, and ultimately also performance, because the compiler will better know how to optimize it.</p>
| 2 | 2009-09-04T08:22:59Z | [
"python",
"micro-optimization"
] |
What is faster in Python, "while" or "for xrange" | 1,377,429 | <p>We can do numeric iteration like:</p>
<pre><code>for i in xrange(10):
print i,
</code></pre>
<p>and in C-style:</p>
<pre><code>i = 0
while i < 10:
print i,
i = i + 1
</code></pre>
<p>Yes, I know, the first one is less error-prone, more pythonic but is it fast enough as C-style version?</p>
<p>PS. I'm from C++ planet and pretty new on Python one.</p>
| 4 | 2009-09-04T05:48:23Z | 1,378,157 | <p>I am sure the <code>while</code> version is slower. Python will have to lookup the add operation for the integer object on each turn of the loop etc, it is not pure C just because it looks like it!</p>
<p>And if you want a pythonic version of exactly the above, use:</p>
<pre><code>print " ".join(str(i) for i in xrange(10))
</code></pre>
<p><hr /></p>
<p>Edit: My timings look like this. This is just a silly running loop without printing, just to show you what writing out "i += 1" etc costs in Python.</p>
<pre><code>$ python -mtimeit "i=0" "while i < 1000: i+=1"
1000 loops, best of 3: 303 usec per loop
$ python -mtimeit "for i in xrange(1000): pass"
10000 loops, best of 3: 120 usec per loop
</code></pre>
| 13 | 2009-09-04T09:26:46Z | [
"python",
"micro-optimization"
] |
What is faster in Python, "while" or "for xrange" | 1,377,429 | <p>We can do numeric iteration like:</p>
<pre><code>for i in xrange(10):
print i,
</code></pre>
<p>and in C-style:</p>
<pre><code>i = 0
while i < 10:
print i,
i = i + 1
</code></pre>
<p>Yes, I know, the first one is less error-prone, more pythonic but is it fast enough as C-style version?</p>
<p>PS. I'm from C++ planet and pretty new on Python one.</p>
| 4 | 2009-09-04T05:48:23Z | 1,378,502 | <p>The first one.</p>
<p>You mean, faster to develop, right?</p>
<p>PS: It doesn't matter, machines these days are so fast that it is meaningless to ponder on micro optimizations, prior to identifying the bottlenecks using a thorough profiler.</p>
| 4 | 2009-09-04T10:48:59Z | [
"python",
"micro-optimization"
] |
What is faster in Python, "while" or "for xrange" | 1,377,429 | <p>We can do numeric iteration like:</p>
<pre><code>for i in xrange(10):
print i,
</code></pre>
<p>and in C-style:</p>
<pre><code>i = 0
while i < 10:
print i,
i = i + 1
</code></pre>
<p>Yes, I know, the first one is less error-prone, more pythonic but is it fast enough as C-style version?</p>
<p>PS. I'm from C++ planet and pretty new on Python one.</p>
| 4 | 2009-09-04T05:48:23Z | 1,378,942 | <p>Well, if you are after efficiency in numerical code, you ought to use <a href="http://numpy.scipy.org" rel="nofollow" title="numpy">numpy</a> and <a href="http://www.scipy.org" rel="nofollow" title="scipy">scipy</a>. Your integration can be quickly written as <code>numpy.sum( numpy.arange( 10 ) )</code></p>
| 0 | 2009-09-04T12:31:53Z | [
"python",
"micro-optimization"
] |
What is faster in Python, "while" or "for xrange" | 1,377,429 | <p>We can do numeric iteration like:</p>
<pre><code>for i in xrange(10):
print i,
</code></pre>
<p>and in C-style:</p>
<pre><code>i = 0
while i < 10:
print i,
i = i + 1
</code></pre>
<p>Yes, I know, the first one is less error-prone, more pythonic but is it fast enough as C-style version?</p>
<p>PS. I'm from C++ planet and pretty new on Python one.</p>
| 4 | 2009-09-04T05:48:23Z | 1,380,023 | <p>If your program is too slow, try using <a href="http://psyco.sourceforge.net/" rel="nofollow">psyco</a>.</p>
<p>Don't worry about the kind of micro-optimisation in your question. Write your program to be maintainable (which includes following standard Python style so other programmers can read it easier).</p>
| 0 | 2009-09-04T15:42:02Z | [
"python",
"micro-optimization"
] |
What is faster in Python, "while" or "for xrange" | 1,377,429 | <p>We can do numeric iteration like:</p>
<pre><code>for i in xrange(10):
print i,
</code></pre>
<p>and in C-style:</p>
<pre><code>i = 0
while i < 10:
print i,
i = i + 1
</code></pre>
<p>Yes, I know, the first one is less error-prone, more pythonic but is it fast enough as C-style version?</p>
<p>PS. I'm from C++ planet and pretty new on Python one.</p>
| 4 | 2009-09-04T05:48:23Z | 1,380,037 | <p>In Python, the shorter and clearer version is always better. If I am not mistaken the range and xrange functions are not native, if you try xrange(sys.maxint+1) you will get an overflow error.</p>
<p>Besides, what the hell could this be useful for? If you are just printing 10 numbers, then surely readability counts a thousand times more - and I don't think you're going to print over a million numbers...</p>
| -1 | 2009-09-04T15:45:16Z | [
"python",
"micro-optimization"
] |
Render HTML to PDF in Django site | 1,377,446 | <p>For my django powered site, I am looking for an easy solution to convert dynamic html pages to pdf.</p>
<p>Pages include HTML and charts from Google visualization API (which is javascript based, yet including those graphs is a must).</p>
| 85 | 2009-09-04T05:54:35Z | 1,377,470 | <p>Try the <a href="http://torisugari.googlepages.com/commandlineprint2" rel="nofollow">command line print</a> firefox extension.</p>
| 2 | 2009-09-04T06:02:11Z | [
"python",
"html",
"django",
"pdf",
"pdf-generation"
] |
Render HTML to PDF in Django site | 1,377,446 | <p>For my django powered site, I am looking for an easy solution to convert dynamic html pages to pdf.</p>
<p>Pages include HTML and charts from Google visualization API (which is javascript based, yet including those graphs is a must).</p>
| 85 | 2009-09-04T05:54:35Z | 1,377,652 | <p>Try the solution from <a href="http://www.reportlab.org/">Reportlab</a>.</p>
<p>Download it and install it as usual with python setup.py install</p>
<p>You will also need to install the following modules: xhtml2pdf, html5lib, pypdf with easy_install.</p>
<p>Here is an usage example:</p>
<p><strong>First define this function:</strong></p>
<pre><code>import cStringIO as StringIO
from xhtml2pdf import pisa
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
from cgi import escape
def render_to_pdf(template_src, context_dict):
template = get_template(template_src)
context = Context(context_dict)
html = template.render(context)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))
</code></pre>
<p><strong>Then you can use it like this:</strong></p>
<pre><code>def myview(request):
#Retrieve data or whatever you need
return render_to_pdf(
'mytemplate.html',
{
'pagesize':'A4',
'mylist': results,
}
)
</code></pre>
<p><strong>The template:</strong></p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>My Title</title>
<style type="text/css">
@page {
size: {{ pagesize }};
margin: 1cm;
@frame footer {
-pdf-frame-content: footerContent;
bottom: 0cm;
margin-left: 9cm;
margin-right: 9cm;
height: 1cm;
}
}
</style>
</head>
<body>
<div>
{% for item in mylist %}
RENDER MY CONTENT
{% endfor %}
</div>
<div id="footerContent">
{%block page_foot%}
Page <pdf:pagenumber>
{%endblock%}
</div>
</body>
</html>
</code></pre>
<p>Hope it helps.</p>
| 174 | 2009-09-04T07:12:50Z | [
"python",
"html",
"django",
"pdf",
"pdf-generation"
] |
Render HTML to PDF in Django site | 1,377,446 | <p>For my django powered site, I am looking for an easy solution to convert dynamic html pages to pdf.</p>
<p>Pages include HTML and charts from Google visualization API (which is javascript based, yet including those graphs is a must).</p>
| 85 | 2009-09-04T05:54:35Z | 6,353,136 | <p>See cool package <a href="https://github.com/NetAngels/django-webodt">https://github.com/NetAngels/django-webodt</a> </p>
| 5 | 2011-06-15T04:48:13Z | [
"python",
"html",
"django",
"pdf",
"pdf-generation"
] |
Render HTML to PDF in Django site | 1,377,446 | <p>For my django powered site, I am looking for an easy solution to convert dynamic html pages to pdf.</p>
<p>Pages include HTML and charts from Google visualization API (which is javascript based, yet including those graphs is a must).</p>
| 85 | 2009-09-04T05:54:35Z | 13,961,258 | <p>I just whipped this up for CBV. Not used in production but generates a PDF for me. Probably needs work for the error reporting side of things but does the trick so far.</p>
<pre><code>import StringIO
from cgi import escape
from xhtml2pdf import pisa
from django.http import HttpResponse
from django.template.response import TemplateResponse
from django.views.generic import TemplateView
class PDFTemplateResponse(TemplateResponse):
def generate_pdf(self, retval):
html = self.content
result = StringIO.StringIO()
rendering = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
if rendering.err:
return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))
else:
self.content = result.getvalue()
def __init__(self, *args, **kwargs):
super(PDFTemplateResponse, self).__init__(*args, mimetype='application/pdf', **kwargs)
self.add_post_render_callback(self.generate_pdf)
class PDFTemplateView(TemplateView):
response_class = PDFTemplateResponse
</code></pre>
<p>Used like:</p>
<pre><code>class MyPdfView(PDFTemplateView):
template_name = 'things/pdf.html'
</code></pre>
| 9 | 2012-12-19T21:11:38Z | [
"python",
"html",
"django",
"pdf",
"pdf-generation"
] |
Render HTML to PDF in Django site | 1,377,446 | <p>For my django powered site, I am looking for an easy solution to convert dynamic html pages to pdf.</p>
<p>Pages include HTML and charts from Google visualization API (which is javascript based, yet including those graphs is a must).</p>
| 85 | 2009-09-04T05:54:35Z | 16,890,568 | <p>i found this app <a href="https://github.com/directeur/django-pdf" rel="nofollow">https://github.com/directeur/django-pdf</a> . Just have to add "?format=pdf" in url to get the pdf.But css is not working in this too.</p>
| 1 | 2013-06-03T05:37:23Z | [
"python",
"html",
"django",
"pdf",
"pdf-generation"
] |
Render HTML to PDF in Django site | 1,377,446 | <p>For my django powered site, I am looking for an easy solution to convert dynamic html pages to pdf.</p>
<p>Pages include HTML and charts from Google visualization API (which is javascript based, yet including those graphs is a must).</p>
| 85 | 2009-09-04T05:54:35Z | 18,990,121 | <p>You can use iReport editor to define the layout, and publish the report in jasper reports server. After publish you can invoke the rest api to get the results.</p>
<p>Here is the test of the functionality:</p>
<pre><code>from django.test import TestCase
from x_reports_jasper.models import JasperServerClient
"""
to try integraction with jasper server through rest
"""
class TestJasperServerClient(TestCase):
# define required objects for tests
def setUp(self):
# load the connection to remote server
try:
self.j_url = "http://127.0.0.1:8080/jasperserver"
self.j_user = "jasperadmin"
self.j_pass = "jasperadmin"
self.client = JasperServerClient.create_client(self.j_url,self.j_user,self.j_pass)
except Exception, e:
# if errors could not execute test given prerrequisites
raise
# test exception when server data is invalid
def test_login_to_invalid_address_should_raise(self):
self.assertRaises(Exception,JasperServerClient.create_client, "http://127.0.0.1:9090/jasperserver",self.j_user,self.j_pass)
# test execute existent report in server
def test_get_report(self):
r_resource_path = "/reports/<PathToPublishedReport>"
r_format = "pdf"
r_params = {'PARAM_TO_REPORT':"1",}
#resource_meta = client.load_resource_metadata( rep_resource_path )
[uuid,out_mime,out_data] = self.client.generate_report(r_resource_path,r_format,r_params)
self.assertIsNotNone(uuid)
</code></pre>
<p>And here is an example of the invocation implementation:</p>
<pre><code>from django.db import models
import requests
import sys
from xml.etree import ElementTree
import logging
# module logger definition
logger = logging.getLogger(__name__)
# Create your models here.
class JasperServerClient(models.Manager):
def __handle_exception(self, exception_root, exception_id, exec_info ):
type, value, traceback = exec_info
raise JasperServerClientError(exception_root, exception_id), None, traceback
# 01: REPORT-METADATA
# get resource description to generate the report
def __handle_report_metadata(self, rep_resourcepath):
l_path_base_resource = "/rest/resource"
l_path = self.j_url + l_path_base_resource
logger.info( "metadata (begin) [path=%s%s]" %( l_path ,rep_resourcepath) )
resource_response = None
try:
resource_response = requests.get( "%s%s" %( l_path ,rep_resourcepath) , cookies = self.login_response.cookies)
except Exception, e:
self.__handle_exception(e, "REPORT_METADATA:CALL_ERROR", sys.exc_info())
resource_response_dom = None
try:
# parse to dom and set parameters
logger.debug( " - response [data=%s]" %( resource_response.text) )
resource_response_dom = ElementTree.fromstring(resource_response.text)
datum = ""
for node in resource_response_dom.getiterator():
datum = "%s<br />%s - %s" % (datum, node.tag, node.text)
logger.debug( " - response [xml=%s]" %( datum ) )
#
self.resource_response_payload= resource_response.text
logger.info( "metadata (end) ")
except Exception, e:
logger.error( "metadata (error) [%s]" % (e))
self.__handle_exception(e, "REPORT_METADATA:PARSE_ERROR", sys.exc_info())
# 02: REPORT-PARAMS
def __add_report_params(self, metadata_text, params ):
if(type(params) != dict):
raise TypeError("Invalid parameters to report")
else:
logger.info( "add-params (begin) []" )
#copy parameters
l_params = {}
for k,v in params.items():
l_params[k]=v
# get the payload metadata
metadata_dom = ElementTree.fromstring(metadata_text)
# add attributes to payload metadata
root = metadata_dom #('report'):
for k,v in l_params.items():
param_dom_element = ElementTree.Element('parameter')
param_dom_element.attrib["name"] = k
param_dom_element.text = v
root.append(param_dom_element)
#
metadata_modified_text =ElementTree.tostring(metadata_dom, encoding='utf8', method='xml')
logger.info( "add-params (end) [payload-xml=%s]" %( metadata_modified_text ) )
return metadata_modified_text
# 03: REPORT-REQUEST-CALL
# call to generate the report
def __handle_report_request(self, rep_resourcepath, rep_format, rep_params):
# add parameters
self.resource_response_payload = self.__add_report_params(self.resource_response_payload,rep_params)
# send report request
l_path_base_genreport = "/rest/report"
l_path = self.j_url + l_path_base_genreport
logger.info( "report-request (begin) [path=%s%s]" %( l_path ,rep_resourcepath) )
genreport_response = None
try:
genreport_response = requests.put( "%s%s?RUN_OUTPUT_FORMAT=%s" %(l_path,rep_resourcepath,rep_format),data=self.resource_response_payload, cookies = self.login_response.cookies )
logger.info( " - send-operation-result [value=%s]" %( genreport_response.text) )
except Exception,e:
self.__handle_exception(e, "REPORT_REQUEST:CALL_ERROR", sys.exc_info())
# parse the uuid of the requested report
genreport_response_dom = None
try:
genreport_response_dom = ElementTree.fromstring(genreport_response.text)
for node in genreport_response_dom.findall("uuid"):
datum = "%s" % (node.text)
genreport_uuid = datum
for node in genreport_response_dom.findall("file/[@type]"):
datum = "%s" % (node.text)
genreport_mime = datum
logger.info( "report-request (end) [uuid=%s,mime=%s]" %( genreport_uuid, genreport_mime) )
return [genreport_uuid,genreport_mime]
except Exception,e:
self.__handle_exception(e, "REPORT_REQUEST:PARSE_ERROR", sys.exc_info())
# 04: REPORT-RETRIEVE RESULTS
def __handle_report_reply(self, genreport_uuid ):
l_path_base_getresult = "/rest/report"
l_path = self.j_url + l_path_base_getresult
logger.info( "report-reply (begin) [uuid=%s,path=%s]" %( genreport_uuid,l_path) )
getresult_response = requests.get( "%s%s/%s?file=report" %(self.j_url,l_path_base_getresult,genreport_uuid),data=self.resource_response_payload, cookies = self.login_response.cookies )
l_result_header_mime =getresult_response.headers['Content-Type']
logger.info( "report-reply (end) [uuid=%s,mime=%s]" %( genreport_uuid, l_result_header_mime) )
return [l_result_header_mime, getresult_response.content]
# public methods ---------------------------------------
# tries the authentication with jasperserver throug rest
def login(self, j_url, j_user,j_pass):
self.j_url= j_url
l_path_base_auth = "/rest/login"
l_path = self.j_url + l_path_base_auth
logger.info( "login (begin) [path=%s]" %( l_path) )
try:
self.login_response = requests.post(l_path , params = {
'j_username':j_user,
'j_password':j_pass
})
if( requests.codes.ok != self.login_response.status_code ):
self.login_response.raise_for_status()
logger.info( "login (end)" )
return True
# see http://blog.ianbicking.org/2007/09/12/re-raising-exceptions/
except Exception, e:
logger.error("login (error) [e=%s]" % e )
self.__handle_exception(e, "LOGIN:CALL_ERROR",sys.exc_info())
#raise
def generate_report(self, rep_resourcepath,rep_format,rep_params):
self.__handle_report_metadata(rep_resourcepath)
[uuid,mime] = self.__handle_report_request(rep_resourcepath, rep_format,rep_params)
# TODO: how to handle async?
[out_mime,out_data] = self.__handle_report_reply(uuid)
return [uuid,out_mime,out_data]
@staticmethod
def create_client(j_url, j_user, j_pass):
client = JasperServerClient()
login_res = client.login( j_url, j_user, j_pass )
return client
class JasperServerClientError(Exception):
def __init__(self,exception_root,reason_id,reason_message=None):
super(JasperServerClientError, self).__init__(str(reason_message))
self.code = reason_id
self.description = str(exception_root) + " " + str(reason_message)
def __str__(self):
return self.code + " " + self.description
</code></pre>
| 1 | 2013-09-24T19:15:27Z | [
"python",
"html",
"django",
"pdf",
"pdf-generation"
] |
Render HTML to PDF in Django site | 1,377,446 | <p>For my django powered site, I am looking for an easy solution to convert dynamic html pages to pdf.</p>
<p>Pages include HTML and charts from Google visualization API (which is javascript based, yet including those graphs is a must).</p>
| 85 | 2009-09-04T05:54:35Z | 25,800,473 | <p><a href="https://github.com/nigma/django-easy-pdf">https://github.com/nigma/django-easy-pdf</a></p>
<p>Template:</p>
<pre><code>{% extends "easy_pdf/base.html" %}
{% block content %}
<div id="content">
<h1>Hi there!</h1>
</div>
{% endblock %}
</code></pre>
<p>View:</p>
<pre><code>from easy_pdf.views import PDFTemplateView
class HelloPDFView(PDFTemplateView):
template_name = "hello.html"
</code></pre>
| 6 | 2014-09-12T03:55:10Z | [
"python",
"html",
"django",
"pdf",
"pdf-generation"
] |
Render HTML to PDF in Django site | 1,377,446 | <p>For my django powered site, I am looking for an easy solution to convert dynamic html pages to pdf.</p>
<p>Pages include HTML and charts from Google visualization API (which is javascript based, yet including those graphs is a must).</p>
| 85 | 2009-09-04T05:54:35Z | 27,419,707 | <p>Try <a href="http://wkhtmltopdf.org/" rel="nofollow">wkhtmltopdf</a> with either one of the following wrappers</p>
<p><a href="https://github.com/incuna/django-wkhtmltopdf" rel="nofollow">django-wkhtmltopdf</a> or <a href="https://github.com/JazzCore/python-pdfkit/" rel="nofollow">python-pdfkit</a> </p>
<p>This worked great for me,supports javascript and css or anything for that matter which a webkit browser supports.</p>
<p>For more detailed tutorial please see this <a href="https://codehustle.wordpress.com/2016/07/16/html-to-pdf-in-django-using-wkhtmltopdf/" rel="nofollow">blog post</a> </p>
| 8 | 2014-12-11T09:45:27Z | [
"python",
"html",
"django",
"pdf",
"pdf-generation"
] |
Render HTML to PDF in Django site | 1,377,446 | <p>For my django powered site, I am looking for an easy solution to convert dynamic html pages to pdf.</p>
<p>Pages include HTML and charts from Google visualization API (which is javascript based, yet including those graphs is a must).</p>
| 85 | 2009-09-04T05:54:35Z | 29,440,704 | <p>After trying to get this to work for too many hours, I finally found this:
<a href="https://github.com/vierno/django-xhtml2pdf" rel="nofollow">https://github.com/vierno/django-xhtml2pdf</a></p>
<p>It's a fork of <a href="https://github.com/chrisglass/django-xhtml2pdf" rel="nofollow">https://github.com/chrisglass/django-xhtml2pdf</a> that provides a mixin for a generic class-based view. I used it like this:</p>
<pre><code> # views.py
from django_xhtml2pdf.views import PdfMixin
class GroupPDFGenerate(PdfMixin, DetailView):
model = PeerGroupSignIn
template_name = 'groups/pdf.html'
# templates/groups/pdf.html
<html>
<style>
@page { your xhtml2pdf pisa PDF parameters }
</style>
</head>
<body>
<div id="header_content"> (this is defined in the style section)
<h1>{{ peergroupsignin.this_group_title }}</h1>
...
</code></pre>
<p>Use the model name you defined in your view in all lowercase when populating the template fields. Because its a GCBV, you can just call it as '.as_view' in your urls.py:</p>
<pre><code> # urls.py (using url namespaces defined in the main urls.py file)
url(
regex=r"^(?P<pk>\d+)/generate_pdf/$",
view=views.GroupPDFGenerate.as_view(),
name="generate_pdf",
),
</code></pre>
| 2 | 2015-04-03T22:48:41Z | [
"python",
"html",
"django",
"pdf",
"pdf-generation"
] |
Python multiprocessing with twisted's reactor | 1,377,494 | <p>Dear everyone
I am working on a xmlrpc server which has to perform certain tasks cyclically. I am using twisted as the core of the xmlrpc service but I am running into a little problem:</p>
<pre><code>class cemeteryRPC(xmlrpc.XMLRPC):
def __init__(self, dic):
xmlrpc.XMLRPC.__init__(self)
def xmlrpc_foo(self):
return 1
def cycle(self):
print "Hello"
time.sleep(3)
class cemeteryM( base ):
def __init__(self, dic): # dic is for cemetery
multiprocessing.Process.__init__(self)
self.cemRPC = cemeteryRPC()
def run(self):
# Start reactor on a second process
reactor.listenTCP( c.PORT_XMLRPC, server.Site( self.cemRPC ) )
p = multiprocessing.Process( target=reactor.run )
p.start()
while not self.exit.is_set():
self.cemRPC.cycle()
#p.join()
if __name__ == "__main__":
import errno
test = cemeteryM()
test.start()
# trying new method
notintr = False
while not notintr:
try:
test.join()
notintr = True
except OSError, ose:
if ose.errno != errno.EINTR:
raise ose
except KeyboardInterrupt:
notintr = True
</code></pre>
<p>How should i go about joining these two process so that their respective joins doesn't block?</p>
<p>(I am pretty confused by "join". Why would it block and I have googled but can't find much helpful explanation to the usage of join. Can someone explain this to me?) </p>
<p>Regards</p>
| 4 | 2009-09-04T06:08:57Z | 1,378,840 | <p>Do you really need to run Twisted in a separate process? That looks pretty unusual to me.</p>
<p>Try to think of Twisted's Reactor as your main loop - and hang everything you need off that - rather than trying to run Twisted as a background task.</p>
<p>The more normal way of performing this sort of operation would be to use Twisted's .callLater or to add a LoopingCall object to the Reactor.</p>
<p>e.g.</p>
<pre><code>from twisted.web import xmlrpc, server
from twisted.internet import task
from twisted.internet import reactor
class Example(xmlrpc.XMLRPC):
def xmlrpc_add(self, a, b):
return a + b
def timer_event(self):
print "one second"
r = Example()
m = task.LoopingCall(r.timer_event)
m.start(1.0)
reactor.listenTCP(7080, server.Site(r))
reactor.run()
</code></pre>
| 11 | 2009-09-04T12:06:34Z | [
"python",
"twisted",
"multiprocessing"
] |
Python multiprocessing with twisted's reactor | 1,377,494 | <p>Dear everyone
I am working on a xmlrpc server which has to perform certain tasks cyclically. I am using twisted as the core of the xmlrpc service but I am running into a little problem:</p>
<pre><code>class cemeteryRPC(xmlrpc.XMLRPC):
def __init__(self, dic):
xmlrpc.XMLRPC.__init__(self)
def xmlrpc_foo(self):
return 1
def cycle(self):
print "Hello"
time.sleep(3)
class cemeteryM( base ):
def __init__(self, dic): # dic is for cemetery
multiprocessing.Process.__init__(self)
self.cemRPC = cemeteryRPC()
def run(self):
# Start reactor on a second process
reactor.listenTCP( c.PORT_XMLRPC, server.Site( self.cemRPC ) )
p = multiprocessing.Process( target=reactor.run )
p.start()
while not self.exit.is_set():
self.cemRPC.cycle()
#p.join()
if __name__ == "__main__":
import errno
test = cemeteryM()
test.start()
# trying new method
notintr = False
while not notintr:
try:
test.join()
notintr = True
except OSError, ose:
if ose.errno != errno.EINTR:
raise ose
except KeyboardInterrupt:
notintr = True
</code></pre>
<p>How should i go about joining these two process so that their respective joins doesn't block?</p>
<p>(I am pretty confused by "join". Why would it block and I have googled but can't find much helpful explanation to the usage of join. Can someone explain this to me?) </p>
<p>Regards</p>
| 4 | 2009-09-04T06:08:57Z | 1,379,268 | <p>Hey asdvawev - .join() in multiprocessing works just like .join() in threading - it's a blocking call the main thread runs to wait for the worker to shut down. If the worker never shuts down, then .join() will never return. For example:</p>
<pre><code>class myproc(Process):
def run(self):
while True:
time.sleep(1)
</code></pre>
<p>Calling run on this means that join() will never, ever return. Typically to prevent this I'll use an Event() object passed into the child process to allow me to signal the child when to exit:</p>
<pre><code>class myproc(Process):
def __init__(self, event):
self.event = event
Process.__init__(self)
def run(self):
while not self.event.is_set():
time.sleep(1)
</code></pre>
<p>Alternatively, if your work is encapsulated in a queue - you can simply have the child process work off of the queue until it encounters a sentinel (typically a None entry in the queue) and then shut down.</p>
<p>Both of these suggestions means that prior to calling .join() you can send set the event, or insert the sentinel and when join() is called, the process will finish it's current task and then exit properly.</p>
| 3 | 2009-09-04T13:29:24Z | [
"python",
"twisted",
"multiprocessing"
] |
What kind of setup (IDE et al) do I need to run IronPython unit tests of C#.NET developed assemblies? | 1,377,548 | <p>I'm attempting to learn IronPython, to broaden my .NET horizons. I want to be able to use Python to write the unit-tests for my next personal project. So being able to access C#.NET assemblies from my Python code is necessary. I also wanted an IDE with auto-complete and smart indenting. PyScripter seemed like a good option, but can I run IronPython from it, and can I link to .NET assemblies from it? </p>
<p><strong>What kind of setup (IDE et al) do I need to run IronPython unit tests of C#.NET developed assemblies?</strong></p>
| 0 | 2009-09-04T06:28:40Z | 1,377,575 | <p>See Michael Foord's website <a href="http://www.voidspace.org.uk/python/weblog/arch%5FWebsite.shtml" rel="nofollow">for IDE</a> and <a href="http://www.voidspace.org.uk/python/weblog/arch%5Fd7%5F2009%5F06%5F13.shtml" rel="nofollow">unittest</a> also discover. And many IronPython articles and the book IronPython in Action
and his tweets save you having to hunt for IronPython references </p>
| 1 | 2009-09-04T06:36:16Z | [
".net",
"python",
"ironpython"
] |
What kind of setup (IDE et al) do I need to run IronPython unit tests of C#.NET developed assemblies? | 1,377,548 | <p>I'm attempting to learn IronPython, to broaden my .NET horizons. I want to be able to use Python to write the unit-tests for my next personal project. So being able to access C#.NET assemblies from my Python code is necessary. I also wanted an IDE with auto-complete and smart indenting. PyScripter seemed like a good option, but can I run IronPython from it, and can I link to .NET assemblies from it? </p>
<p><strong>What kind of setup (IDE et al) do I need to run IronPython unit tests of C#.NET developed assemblies?</strong></p>
| 0 | 2009-09-04T06:28:40Z | 1,377,595 | <p>Here's a good link to an article about different IDE's and how they work with IronPython:
<a href="http://www.voidspace.org.uk/ironpython/tools-and-ides.shtml" rel="nofollow">http://www.voidspace.org.uk/ironpython/tools-and-ides.shtml</a></p>
| 2 | 2009-09-04T06:47:30Z | [
".net",
"python",
"ironpython"
] |
What kind of setup (IDE et al) do I need to run IronPython unit tests of C#.NET developed assemblies? | 1,377,548 | <p>I'm attempting to learn IronPython, to broaden my .NET horizons. I want to be able to use Python to write the unit-tests for my next personal project. So being able to access C#.NET assemblies from my Python code is necessary. I also wanted an IDE with auto-complete and smart indenting. PyScripter seemed like a good option, but can I run IronPython from it, and can I link to .NET assemblies from it? </p>
<p><strong>What kind of setup (IDE et al) do I need to run IronPython unit tests of C#.NET developed assemblies?</strong></p>
| 0 | 2009-09-04T06:28:40Z | 1,378,519 | <p>FWIW, Frood himself uses Wing IDE.</p>
<p>But, if its on Windows, why not VS?</p>
| 0 | 2009-09-04T10:51:57Z | [
".net",
"python",
"ironpython"
] |
What kind of setup (IDE et al) do I need to run IronPython unit tests of C#.NET developed assemblies? | 1,377,548 | <p>I'm attempting to learn IronPython, to broaden my .NET horizons. I want to be able to use Python to write the unit-tests for my next personal project. So being able to access C#.NET assemblies from my Python code is necessary. I also wanted an IDE with auto-complete and smart indenting. PyScripter seemed like a good option, but can I run IronPython from it, and can I link to .NET assemblies from it? </p>
<p><strong>What kind of setup (IDE et al) do I need to run IronPython unit tests of C#.NET developed assemblies?</strong></p>
| 0 | 2009-09-04T06:28:40Z | 1,383,258 | <p>You can also consider using Eclipse with PyDev which has support for IronPython</p>
| 0 | 2009-09-05T12:47:32Z | [
".net",
"python",
"ironpython"
] |
What kind of setup (IDE et al) do I need to run IronPython unit tests of C#.NET developed assemblies? | 1,377,548 | <p>I'm attempting to learn IronPython, to broaden my .NET horizons. I want to be able to use Python to write the unit-tests for my next personal project. So being able to access C#.NET assemblies from my Python code is necessary. I also wanted an IDE with auto-complete and smart indenting. PyScripter seemed like a good option, but can I run IronPython from it, and can I link to .NET assemblies from it? </p>
<p><strong>What kind of setup (IDE et al) do I need to run IronPython unit tests of C#.NET developed assemblies?</strong></p>
| 0 | 2009-09-04T06:28:40Z | 1,389,592 | <p>You can use Visual Studio. I use IronPython Studio integrated with VS2008. But I feel that it has very poor intellisense for Python.</p>
| 0 | 2009-09-07T14:07:28Z | [
".net",
"python",
"ironpython"
] |
Python dictionary to store socket objects | 1,378,079 | <p>Can we store socket objects in a Python dictionary.
I want to create a socket, store socket object, do some stuff and then read from the socket(search from dictionary to get socketobject).</p>
| 3 | 2009-09-04T09:02:32Z | 1,378,084 | <p>Yes:</p>
<pre><code>>>> import socket
>>> s = socket.socket()
>>> d = {"key" : s}
>>> d
{'key': <socket._socketobject object at 0x00CEB5A8>}
</code></pre>
| 10 | 2009-09-04T09:05:41Z | [
"python"
] |
Python dicts in sqlalchemy | 1,378,325 | <p>I would like to load/save a dict to/from my sqlite DB, but am having some problems figuring out a simple way to do it. I don't really need to be able to filter, etc., based on the contents so a simple conversion to/from string is fine.</p>
<p>The next-best thing would be foreign keys. Please don't post links to huge examples, my head would explode if I ever set eyes on any those.</p>
| 15 | 2009-09-04T10:03:36Z | 1,378,366 | <p>If you need to map a 1-N <strong>relation</strong> and map it as <code>dict</code> rather then <code>list</code>, then read <a href="http://www.sqlalchemy.org/docs/05/mappers.html#dictionary-based-collections" rel="nofollow">Dictionary Based Collections</a></p>
<p>But if you mean a <strong>field</strong>, then what you can do it to have a DB field of type string, which is mapped to your Python object. But on the same python object you provide a property which will be kind-of proxy for this mapped string field of type dict().
Code example (not tested):</p>
<pre><code>class MyObject(object):
# fields (mapped automatically by sqlalchemy using mapper(...)
MyFieldAsString = None
def _get_MyFieldAsDict(self):
if self.MyFieldAsString:
return eval(self.MyFieldAsString)
else:
return {} # be careful with None and empty dict
def _set_MyFieldAsDict(self, value):
if value:
self.MyFieldAsString = str(value)
else:
self.MyFieldAsString = None
MyFieldAsDict = property(_get_MyFieldAsDict, _set_MyFieldAsDict)
</code></pre>
| 2 | 2009-09-04T10:12:58Z | [
"python",
"sql",
"sqlite",
"sqlalchemy"
] |
Python dicts in sqlalchemy | 1,378,325 | <p>I would like to load/save a dict to/from my sqlite DB, but am having some problems figuring out a simple way to do it. I don't really need to be able to filter, etc., based on the contents so a simple conversion to/from string is fine.</p>
<p>The next-best thing would be foreign keys. Please don't post links to huge examples, my head would explode if I ever set eyes on any those.</p>
| 15 | 2009-09-04T10:03:36Z | 1,378,818 | <p>The SQLAlchemy <a href="http://docs.sqlalchemy.org/en/latest/core/type_basics.html#sqlalchemy.types.PickleType">PickleType</a> is meant exactly for this.</p>
<pre><code>class SomeEntity(Base):
__tablename__ = 'some_entity'
id = Column(Integer, primary_key=True)
attributes = Column(PickleType)
# Just set the attribute to save it
s = SomeEntity(attributes={'baked': 'beans', 'spam': 'ham'})
session.add(s)
session.commit()
# If mutable=True on PickleType (the default) SQLAlchemy automatically
# notices modifications.
s.attributes['parrot'] = 'dead'
session.commit()
</code></pre>
<p>You can change the serialization mechanism by changing out the pickler with something else that has <code>dumps()</code> and <code>loads()</code> methods. The underlying storage mechanism by subclassing PickleType and overriding the impl attritbute:</p>
<pre><code>class TextPickleType(PickleType):
impl = Text
import json
class SomeOtherEntity(Base):
__tablename__ = 'some_other_entity'
id = Column(Integer, primary_key=True)
attributes = Column(TextPickleType(pickler=json))
</code></pre>
| 42 | 2009-09-04T12:00:09Z | [
"python",
"sql",
"sqlite",
"sqlalchemy"
] |
How to get/set data of(into) visual components (of winodws programs) programmatically? | 1,378,803 | <p>Let me clarify the question a bit. I am talking about windows GUI programs. Say a program-window has a dialog box (or a confirm button) asking user input. How can I provide input to that program using my program (written in say C#, Java or Python). Or say, a program window is showing some image in one of its panels. How can I grab that from other(my) program. It is a kind of impersonating (or inter-win-program messaging?). Someone told me it can be done using spy++. But how? Can you explain? What code to write? What to do with spy++? Provide an example please. If this question is a dupe provide me links. Thanks.</p>
| 0 | 2009-09-04T11:56:42Z | 1,378,847 | <p>To programmatically generate key presses, see <a href="http://stackoverflow.com/questions/136734/key-presses-in-python">http://stackoverflow.com/questions/136734/key-presses-in-python</a>, and search for "generate", "key", "emulate", "fake".</p>
<p>To programmatically capture the screen, see <a href="http://stackoverflow.com/questions/1163761/c-capture-screenshot-of-active-window">http://stackoverflow.com/questions/1163761/c-capture-screenshot-of-active-window</a>, and search for terms like "capture", "window", "screen".</p>
| 1 | 2009-09-04T12:09:23Z | [
"c#",
"java",
"python",
"windows",
"impersonation"
] |
How to get/set data of(into) visual components (of winodws programs) programmatically? | 1,378,803 | <p>Let me clarify the question a bit. I am talking about windows GUI programs. Say a program-window has a dialog box (or a confirm button) asking user input. How can I provide input to that program using my program (written in say C#, Java or Python). Or say, a program window is showing some image in one of its panels. How can I grab that from other(my) program. It is a kind of impersonating (or inter-win-program messaging?). Someone told me it can be done using spy++. But how? Can you explain? What code to write? What to do with spy++? Provide an example please. If this question is a dupe provide me links. Thanks.</p>
| 0 | 2009-09-04T11:56:42Z | 1,378,864 | <p>spy++ is listening for all win32 messages. It is very useful for debugging an application but I don't think that it is a good idea to use it as an inter-process communication mechanism.</p>
<p>You can use win32 apis to send input to your program. As an example, You can modify the content of an edit text by using the <a href="http://msdn.microsoft.com/en-us/library/ms633546%28VS.85%29.aspx" rel="nofollow">SetWindowText</a> function. </p>
<p>You need to get the handle of the window. You can use the FindWindow and the GetDlgItem to get it.</p>
<p>It will work for c++ and python thanks to <a href="http://python.net/crew/mhammond/win32/Downloads.html" rel="nofollow">win32 python extension</a>. I don't know if there it is possible to use win32 api from java.</p>
| 2 | 2009-09-04T12:13:03Z | [
"c#",
"java",
"python",
"windows",
"impersonation"
] |
How to get/set data of(into) visual components (of winodws programs) programmatically? | 1,378,803 | <p>Let me clarify the question a bit. I am talking about windows GUI programs. Say a program-window has a dialog box (or a confirm button) asking user input. How can I provide input to that program using my program (written in say C#, Java or Python). Or say, a program window is showing some image in one of its panels. How can I grab that from other(my) program. It is a kind of impersonating (or inter-win-program messaging?). Someone told me it can be done using spy++. But how? Can you explain? What code to write? What to do with spy++? Provide an example please. If this question is a dupe provide me links. Thanks.</p>
| 0 | 2009-09-04T11:56:42Z | 1,378,949 | <p>If you want to write win32 code to do it, start here:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms632589%28VS.85%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms632589(VS.85).aspx</a></p>
<p>If you just want to hook the gui as easily as possible, investigate:</p>
<p><a href="http://www.winbatch.com/" rel="nofollow">http://www.winbatch.com/</a></p>
<p><a href="http://www.autoitscript.com/" rel="nofollow">http://www.autoitscript.com/</a></p>
<p><a href="http://www.autohotkey.com/" rel="nofollow">http://www.autohotkey.com/</a></p>
| 1 | 2009-09-04T12:33:02Z | [
"c#",
"java",
"python",
"windows",
"impersonation"
] |
Python: how to format traceback objects | 1,378,889 | <p>I have a traceback object that I want to show in the nice format I get when calling <code>traceback.format_exc()</code>.</p>
<p>Is there a builtin function for this? Or a few lines of code?</p>
| 15 | 2009-09-04T12:19:51Z | 1,378,909 | <p>format_exc is really just</p>
<pre><code> etype, value, tb = sys.exc_info()
return ''.join(format_exception(etype, value, tb, limit))
</code></pre>
<p>So if you have the exception type, value, and traceback ready, it should be easy. If you have just the exception, notice that <code>format_exception</code> is essentially.</p>
<pre><code> list = ['Traceback (most recent call last):\n']
list = list + format_tb(tb, limit)
</code></pre>
<p>where limit defaults to None.</p>
| 19 | 2009-09-04T12:24:44Z | [
"python",
"object",
"format",
"traceback"
] |
Python: how to format traceback objects | 1,378,889 | <p>I have a traceback object that I want to show in the nice format I get when calling <code>traceback.format_exc()</code>.</p>
<p>Is there a builtin function for this? Or a few lines of code?</p>
| 15 | 2009-09-04T12:19:51Z | 1,378,910 | <p>Have you tried <a href="http://docs.python.org/library/traceback.html#traceback.print%5Ftb">traceback.print_tb</a> or <a href="http://docs.python.org/library/traceback.html#traceback.format%5Ftb">traceback.format_tb</a>?</p>
| 7 | 2009-09-04T12:25:01Z | [
"python",
"object",
"format",
"traceback"
] |
Python: how to format traceback objects | 1,378,889 | <p>I have a traceback object that I want to show in the nice format I get when calling <code>traceback.format_exc()</code>.</p>
<p>Is there a builtin function for this? Or a few lines of code?</p>
| 15 | 2009-09-04T12:19:51Z | 1,378,913 | <p><code>traceback</code> docs give <a href="http://docs.python.org/library/traceback.html#traceback-examples" rel="nofollow">few examples</a> and <a href="http://docs.python.org/library/traceback.html" rel="nofollow">whole set of functions</a> for formatting traceback objects.</p>
| 2 | 2009-09-04T12:25:50Z | [
"python",
"object",
"format",
"traceback"
] |
list of methods for python shell? | 1,378,926 | <p>You'd have already found out by my usage of terminology that I'm a python n00b.</p>
<p>straight forward question:</p>
<p>How can i see a list of methods for a particular object in an interactive python shell like i can in ruby (you can do that in ruby irb with a '.methods' after the object)?</p>
| 6 | 2009-09-04T12:29:08Z | 1,378,929 | <p><code>dir( object )</code></p>
<p>will give you the list.</p>
<p>for instance:</p>
<pre><code>a = 2
dir( a )
</code></pre>
<p>will list off all the methods you can call for an integer.</p>
| 7 | 2009-09-04T12:29:57Z | [
"python",
"shell",
"interactive"
] |
list of methods for python shell? | 1,378,926 | <p>You'd have already found out by my usage of terminology that I'm a python n00b.</p>
<p>straight forward question:</p>
<p>How can i see a list of methods for a particular object in an interactive python shell like i can in ruby (you can do that in ruby irb with a '.methods' after the object)?</p>
| 6 | 2009-09-04T12:29:08Z | 1,378,933 | <p>Do this:</p>
<pre><code>dir(obj)
</code></pre>
| 1 | 2009-09-04T12:30:22Z | [
"python",
"shell",
"interactive"
] |
list of methods for python shell? | 1,378,926 | <p>You'd have already found out by my usage of terminology that I'm a python n00b.</p>
<p>straight forward question:</p>
<p>How can i see a list of methods for a particular object in an interactive python shell like i can in ruby (you can do that in ruby irb with a '.methods' after the object)?</p>
| 6 | 2009-09-04T12:29:08Z | 1,378,935 | <pre><code>>>> help(my_object)
</code></pre>
| 5 | 2009-09-04T12:30:51Z | [
"python",
"shell",
"interactive"
] |
list of methods for python shell? | 1,378,926 | <p>You'd have already found out by my usage of terminology that I'm a python n00b.</p>
<p>straight forward question:</p>
<p>How can i see a list of methods for a particular object in an interactive python shell like i can in ruby (you can do that in ruby irb with a '.methods' after the object)?</p>
| 6 | 2009-09-04T12:29:08Z | 1,378,971 | <p>Others have mentioned <a href="http://docs.python.org/3.1/library/functions.html#dir" rel="nofollow"><code>dir</code></a>. Let me make an remark of caution: Python objects may have a <a href="http://docs.python.org/3.1/reference/datamodel.html?highlight=%5F%5Fgetattr%5F%5F#object.%5F%5Fgetattr%5F%5F" rel="nofollow"><code>__getattr__</code></a> method defined which is called when one attempts to call an undefined method on said object. Obviously <code>dir</code> does not list all those (infinitely many) method names. Some libraries make explicit use of this feature, e.g. <a href="http://www.dabeaz.com/ply/" rel="nofollow">PLY</a> (Python Lex-Yacc).</p>
<p>Example:</p>
<pre><code>>>> class Test:
... def __getattr__(self, name):
... return 'foo <%s>' % name
...
>>> t = Test()
>>> t.bar
'foo <bar>'
>>> 'bar' in dir(t)
False
</code></pre>
| 2 | 2009-09-04T12:37:55Z | [
"python",
"shell",
"interactive"
] |
list of methods for python shell? | 1,378,926 | <p>You'd have already found out by my usage of terminology that I'm a python n00b.</p>
<p>straight forward question:</p>
<p>How can i see a list of methods for a particular object in an interactive python shell like i can in ruby (you can do that in ruby irb with a '.methods' after the object)?</p>
| 6 | 2009-09-04T12:29:08Z | 1,379,011 | <p>If you want only methods, then</p>
<pre><code>def methods(obj):
return [attr for attr in dir(obj) if callable(getattr(obj, attr))]
</code></pre>
<p>But do try out IPython, it has tab completion for object attributes, so typing <code>obj.<tab></code> shows you a list of available attributes on that object.</p>
| 0 | 2009-09-04T12:44:40Z | [
"python",
"shell",
"interactive"
] |
list of methods for python shell? | 1,378,926 | <p>You'd have already found out by my usage of terminology that I'm a python n00b.</p>
<p>straight forward question:</p>
<p>How can i see a list of methods for a particular object in an interactive python shell like i can in ruby (you can do that in ruby irb with a '.methods' after the object)?</p>
| 6 | 2009-09-04T12:29:08Z | 1,379,242 | <p>For an enhanced version of <code>dir()</code> check out <code>see()</code>!</p>
<pre><code>>>> test = [1,2,3]
>>> see(test)
[] in + += * *= < <= == != > >= hash()
help() iter() len() repr() reversed() str() .append()
.count() .extend() .index() .insert() .pop() .remove()
.reverse() .sort()
</code></pre>
<p>You can get it here:</p>
<ul>
<li><a href="http://pypi.python.org/pypi/see/0.5.4" rel="nofollow">http://pypi.python.org/pypi/see/0.5.4</a> (packaged version)</li>
<li><a href="http://inky.github.com/see/" rel="nofollow">http://inky.github.com/see/</a> (home page)</li>
<li><a href="http://github.com/inky/see/tree/master" rel="nofollow">http://github.com/inky/see/tree/master</a> (source)</li>
</ul>
| 3 | 2009-09-04T13:25:31Z | [
"python",
"shell",
"interactive"
] |
list of methods for python shell? | 1,378,926 | <p>You'd have already found out by my usage of terminology that I'm a python n00b.</p>
<p>straight forward question:</p>
<p>How can i see a list of methods for a particular object in an interactive python shell like i can in ruby (you can do that in ruby irb with a '.methods' after the object)?</p>
| 6 | 2009-09-04T12:29:08Z | 1,379,470 | <p>Python supports tab completion as well. I prefer my python prompt clean (so no thanks to IPython), but with tab completion.</p>
<p>Setup in .bashrc or similar:</p>
<pre><code>PYTHONSTARTUP=$HOME/.pythonrc
</code></pre>
<p>Put this in .pythonrc:</p>
<pre><code>try:
import readline
except ImportError:
print ("Module readline not available.")
else:
print ("Enabling tab completion")
import rlcompleter
readline.parse_and_bind("tab: complete")
</code></pre>
<p>It will print "Enabling tab completion" each time the python prompt starts up, because it's better to be explicit. This won't interfere with execution of python scripts and programs.</p>
<p><hr /></p>
<p>Example:</p>
<pre><code>>>> lst = []
>>> lst.
lst.__add__( lst.__iadd__( lst.__setattr__(
lst.__class__( lst.__imul__( lst.__setitem__(
lst.__contains__( lst.__init__( lst.__setslice__(
lst.__delattr__( lst.__iter__( lst.__sizeof__(
lst.__delitem__( lst.__le__( lst.__str__(
lst.__delslice__( lst.__len__( lst.__subclasshook__(
lst.__doc__ lst.__lt__( lst.append(
lst.__eq__( lst.__mul__( lst.count(
lst.__format__( lst.__ne__( lst.extend(
lst.__ge__( lst.__new__( lst.index(
lst.__getattribute__( lst.__reduce__( lst.insert(
lst.__getitem__( lst.__reduce_ex__( lst.pop(
lst.__getslice__( lst.__repr__( lst.remove(
lst.__gt__( lst.__reversed__( lst.reverse(
lst.__hash__ lst.__rmul__( lst.sort(
</code></pre>
| 4 | 2009-09-04T14:01:30Z | [
"python",
"shell",
"interactive"
] |
list of methods for python shell? | 1,378,926 | <p>You'd have already found out by my usage of terminology that I'm a python n00b.</p>
<p>straight forward question:</p>
<p>How can i see a list of methods for a particular object in an interactive python shell like i can in ruby (you can do that in ruby irb with a '.methods' after the object)?</p>
| 6 | 2009-09-04T12:29:08Z | 1,379,700 | <p>Existing answers do a good job of showing you how to get the ATTRIBUTES of an object, but do not precisely answer the question you posed -- how to get the METHODS of an object. Python objects have a unified namespace (differently from Ruby, where methods and attributes use different namespaces). Consider for example:</p>
<pre><code>>>> class X(object):
... @classmethod
... def clame(cls): pass
... @staticmethod
... def stame(): pass
... def meth(self): pass
... def __init__(self):
... self.lam = lambda: None
... self.val = 23
...
>>> x = X()
>>> dir(x)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
'__getattribute__', '__hash__', '__init__', '__module__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', '__weakref__',
'clame', 'lam', 'meth', 'stame', 'val']
</code></pre>
<p>((output split for readability)).</p>
<p>As you see, this is giving you the names of all attributes -- including plenty of special methods that are just inherited from <code>object</code>, special data attributes such as <code>__class__</code>, <code>__dict__</code> and <code>__doc__</code>, per-instance data attributes (<code>val</code>), per-instance executable attributes (<code>lam</code>), as well as actual methods.</p>
<p>If and when you need to be more selective, try:</p>
<pre><code>>>> import inspect
>>> [n for n, v in inspect.getmembers(x, inspect.ismethod)]
['__init__', 'clame', 'meth']
</code></pre>
<p>Standard library module <code>inspect</code> is the best way to do introspection in Python: it builds on top of the built-in introspection hooks (such as <code>dir</code> and more advanced ones) to offer you useful, rich, and simple introspection services. Here, for example, you see that only instance and class methods specifically designed by this class are shown -- not static methods, not instance attributes whether callable or not, not special methods inherited from <code>object</code>. If your selectivity needs are slightly different, it's easy to build your own tweaked version of <code>ismethod</code> and pass it as the second argument of <code>getmembers</code>, to tailor the results to your precise, exact needs.</p>
| 14 | 2009-09-04T14:42:50Z | [
"python",
"shell",
"interactive"
] |
list of methods for python shell? | 1,378,926 | <p>You'd have already found out by my usage of terminology that I'm a python n00b.</p>
<p>straight forward question:</p>
<p>How can i see a list of methods for a particular object in an interactive python shell like i can in ruby (you can do that in ruby irb with a '.methods' after the object)?</p>
| 6 | 2009-09-04T12:29:08Z | 22,969,378 | <p>Its simple do this for any object you have created</p>
<pre><code>dir(object)
</code></pre>
<p>it will return a list of all the attributes of the object.</p>
| 1 | 2014-04-09T17:09:05Z | [
"python",
"shell",
"interactive"
] |
is there a way to start/stop linux processes with python? | 1,378,974 | <p>I want to be able to start a process and then be able to kill it afterwards</p>
| 6 | 2009-09-04T12:38:06Z | 1,378,989 | <p>Have a look at the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow"><code>subprocess</code></a> module.
You can also use low-level primitives like <code>fork()</code> via the <code>os</code> module.</p>
| 7 | 2009-09-04T12:40:44Z | [
"python",
"linux"
] |
is there a way to start/stop linux processes with python? | 1,378,974 | <p>I want to be able to start a process and then be able to kill it afterwards</p>
| 6 | 2009-09-04T12:38:06Z | 1,378,994 | <p><a href="http://docs.python.org/library/os.html#process-management" rel="nofollow">http://docs.python.org/library/os.html#process-management</a></p>
| 3 | 2009-09-04T12:42:17Z | [
"python",
"linux"
] |
is there a way to start/stop linux processes with python? | 1,378,974 | <p>I want to be able to start a process and then be able to kill it afterwards</p>
| 6 | 2009-09-04T12:38:06Z | 1,379,135 | <p>A simple function that uses subprocess module:</p>
<pre><code>def CMD(cmd) :
p = subprocess.Popen(cmd, shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=False)
return (p.stdin, p.stdout, p.stderr)
</code></pre>
| 3 | 2009-09-04T13:07:31Z | [
"python",
"linux"
] |
is there a way to start/stop linux processes with python? | 1,378,974 | <p>I want to be able to start a process and then be able to kill it afterwards</p>
| 6 | 2009-09-04T12:38:06Z | 1,380,308 | <p>see docs for primitive fork() and modules <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a>, <a href="http://docs.python.org/library/multiprocessing.html#module-multiprocessing.managers" rel="nofollow">multiprocessing</a>, <a href="http://docs.python.org/library/threading.html?highlight=threading#module-threading" rel="nofollow">multithreading</a> </p>
| 0 | 2009-09-04T16:33:13Z | [
"python",
"linux"
] |
is there a way to start/stop linux processes with python? | 1,378,974 | <p>I want to be able to start a process and then be able to kill it afterwards</p>
| 6 | 2009-09-04T12:38:06Z | 1,380,817 | <p>If you need to interact with the sub process at all, I recommend the pexpect module (<a href="http://pypi.python.org/pypi/pexpect/2.4" rel="nofollow">link text</a>). You can send input to the process, receive (or "expect") output in return, and you can close the process (with force=True to send SIGKILL).</p>
| 0 | 2009-09-04T18:25:40Z | [
"python",
"linux"
] |
is there a way to start/stop linux processes with python? | 1,378,974 | <p>I want to be able to start a process and then be able to kill it afterwards</p>
| 6 | 2009-09-04T12:38:06Z | 1,385,959 | <p>Here's a little python script that starts a process, checks if it is running, waits a while, kills it, waits for it to terminate, then checks again. It uses the 'kill' command. Version 2.6 of python subprocess has a kill function. This was written on 2.5.</p>
<pre><code>import subprocess
import time
proc = subprocess.Popen(["sleep", "60"], shell=False)
print 'poll =', proc.poll(), '("None" means process not terminated yet)'
time.sleep(3)
subprocess.call(["kill", "-9", "%d" % proc.pid])
proc.wait()
print 'poll =', proc.poll()
</code></pre>
<p>The timed output shows that it was terminated after about 3 seconds, and not 60 as the call to sleep suggests.</p>
<pre><code>$ time python prockill.py
poll = None ("None" means process not terminated yet)
poll = -9
real 0m3.082s
user 0m0.055s
sys 0m0.029s
</code></pre>
| 12 | 2009-09-06T15:43:41Z | [
"python",
"linux"
] |
Are there any cpython libraries that work with jsr168 and/or jsr286? | 1,379,607 | <p>On a Java portal you can have portlets that include data provided by other applications. We want to replace our existing Java portal with a Django application, which means duplicating the Java portal's ability to display portlets. The two Sun specifications in question that we want to duplicate are JSR168 and JSR286.</p>
<p>I need a cPython solution. Not Jython or Java. Nothing against those tools, we just don't use them. For the record, the Jython based <a href="http://code.google.com/p/portletpy/" rel="nofollow">Portletpy</a> does the opposite of what we are aiming to do.</p>
<p>Also, I suspect this question has been caused by a misunderstanding on our part of how the JSR168/JSR286 specification works. I <strong><em>think</em></strong> that JSR168/JSR286 is an arcane protocol for communicating some sort of content between separate applications, but in the Java world that tends to be done by other methods such as SOAP. Instead, the issue might be that these protocols are simply definitions of how to display content objects in views. If all we have to do is handle SOAP calls and display data, then this whole question is moot.</p>
<p>Simple architecture image below of what we <strong><em>think</em></strong> we want to do:</p>
<p><img src="http://farm3.static.flickr.com/2424/3887309111%5Fe846ac9819.jpg" alt="alt text" /></p>
| 3 | 2009-09-04T14:27:28Z | 1,382,879 | <p>I'm not sure you can do this. From JSR 168:</p>
<p><img src="http://imgur.com/8rxJQ.png" alt="JSR 168 Request/response Handling" /></p>
<p>If I understand correctly, you want the Django application to take the place of the existing "Java Portal/Portlet Container" in the diagram. Unfortunately, the interface between the portlet container and the individual portlets is using in-memory API calls, not as a Web service. There's no easy URL-like interface where you can call into the Java piece to get a chunk of HTML which you then incorporate into a Django-served page.</p>
<p>JSR 286 is an update and while it refines the mechanisms for communicating between portlets, as well as serving resources from portlets, it doesn't really change the above model radically.</p>
<p>I'm not saying it couldn't be done - just that there's no easy, standard way to do it.</p>
| 3 | 2009-09-05T09:36:07Z | [
"python",
"django",
"jsr168",
"jsr286"
] |
Are there any cpython libraries that work with jsr168 and/or jsr286? | 1,379,607 | <p>On a Java portal you can have portlets that include data provided by other applications. We want to replace our existing Java portal with a Django application, which means duplicating the Java portal's ability to display portlets. The two Sun specifications in question that we want to duplicate are JSR168 and JSR286.</p>
<p>I need a cPython solution. Not Jython or Java. Nothing against those tools, we just don't use them. For the record, the Jython based <a href="http://code.google.com/p/portletpy/" rel="nofollow">Portletpy</a> does the opposite of what we are aiming to do.</p>
<p>Also, I suspect this question has been caused by a misunderstanding on our part of how the JSR168/JSR286 specification works. I <strong><em>think</em></strong> that JSR168/JSR286 is an arcane protocol for communicating some sort of content between separate applications, but in the Java world that tends to be done by other methods such as SOAP. Instead, the issue might be that these protocols are simply definitions of how to display content objects in views. If all we have to do is handle SOAP calls and display data, then this whole question is moot.</p>
<p>Simple architecture image below of what we <strong><em>think</em></strong> we want to do:</p>
<p><img src="http://farm3.static.flickr.com/2424/3887309111%5Fe846ac9819.jpg" alt="alt text" /></p>
| 3 | 2009-09-04T14:27:28Z | 5,405,069 | <p>One way to get around this could be using a WSRP (Web Services for Remote Portlets, see Wikipedia) producer, that converts a JSR 168/286 into web services and consume them from django. But it seems that WSRP has not been very popular and I couldn't find any Python platform implementations (although partial works could exist). Beside this, I'm also interested in this topic.</p>
| 0 | 2011-03-23T12:13:58Z | [
"python",
"django",
"jsr168",
"jsr286"
] |
pytz localize vs datetime replace | 1,379,740 | <p>I'm having some weird issues with pytz's .localize() function. Sometimes it wouldn't make adjustments to the localized datetime:</p>
<p>.localize behaviour:</p>
<pre><code>>>> tz
<DstTzInfo 'Africa/Abidjan' LMT-1 day, 23:44:00 STD>
>>> d
datetime.datetime(2009, 9, 2, 14, 45, 42, 91421)
>>> tz.localize(d)
datetime.datetime(2009, 9, 2, 14, 45, 42, 91421,
tzinfo=<DstTzInfo 'Africa/Abidjan' GMT0:00:00 STD>)
>>> tz.normalize(tz.localize(d))
datetime.datetime(2009, 9, 2, 14, 45, 42, 91421,
tzinfo=<DstTzInfo 'Africa/Abidjan' GMT0:00:00 STD>)
</code></pre>
<p>As you can see, time has not been changed as a result of localize/normalize operations.
However, if .replace is used:</p>
<pre><code>>>> d.replace(tzinfo=tz)
datetime.datetime(2009, 9, 2, 14, 45, 42, 91421,
tzinfo=<DstTzInfo 'Africa/Abidjan' LMT-1 day, 23:44:00 STD>)
>>> tz.normalize(d.replace(tzinfo=tz))
datetime.datetime(2009, 9, 2, 15, 1, 42, 91421,
tzinfo=<DstTzInfo 'Africa/Abidjan' GMT0:00:00 STD>)
</code></pre>
<p>Which seems to make adjustments into datetime. </p>
<p>Question is - which is correct and why other's wrong?</p>
<p>Thanks!</p>
| 25 | 2009-09-04T14:50:11Z | 1,379,874 | <p><code>localize</code> just assumes that the naive datetime you pass it is "right" (except for not knowing about the timezone!) and so just sets the timezone, no other adjustments.</p>
<p>You can (and it's advisable...) internally work in UTC (rather than with naive datetimes) and use <code>replace</code> when you need to perform I/O of datetimes in a localized way (<code>normalize</code> will handle DST and the like).</p>
| 19 | 2009-09-04T15:12:52Z | [
"python",
"datetime",
"timezone",
"utc",
"pytz"
] |
pytz localize vs datetime replace | 1,379,740 | <p>I'm having some weird issues with pytz's .localize() function. Sometimes it wouldn't make adjustments to the localized datetime:</p>
<p>.localize behaviour:</p>
<pre><code>>>> tz
<DstTzInfo 'Africa/Abidjan' LMT-1 day, 23:44:00 STD>
>>> d
datetime.datetime(2009, 9, 2, 14, 45, 42, 91421)
>>> tz.localize(d)
datetime.datetime(2009, 9, 2, 14, 45, 42, 91421,
tzinfo=<DstTzInfo 'Africa/Abidjan' GMT0:00:00 STD>)
>>> tz.normalize(tz.localize(d))
datetime.datetime(2009, 9, 2, 14, 45, 42, 91421,
tzinfo=<DstTzInfo 'Africa/Abidjan' GMT0:00:00 STD>)
</code></pre>
<p>As you can see, time has not been changed as a result of localize/normalize operations.
However, if .replace is used:</p>
<pre><code>>>> d.replace(tzinfo=tz)
datetime.datetime(2009, 9, 2, 14, 45, 42, 91421,
tzinfo=<DstTzInfo 'Africa/Abidjan' LMT-1 day, 23:44:00 STD>)
>>> tz.normalize(d.replace(tzinfo=tz))
datetime.datetime(2009, 9, 2, 15, 1, 42, 91421,
tzinfo=<DstTzInfo 'Africa/Abidjan' GMT0:00:00 STD>)
</code></pre>
<p>Which seems to make adjustments into datetime. </p>
<p>Question is - which is correct and why other's wrong?</p>
<p>Thanks!</p>
| 25 | 2009-09-04T14:50:11Z | 1,592,837 | <p>This DstTzInfo class is used for timezones where the offset from UTC changes at certain points in time. For example (as you are probably aware), many locations transition to "daylight savings time" at the beginning of Summer, and then back to "standard time" at the end of Summer. Each DstTzInfo instance only represents one of these timezones, but the "localize" and "normalize" methods help you get the right instance.</p>
<p>For Abidjan, there has only ever been one transition (according to pytz), and that was in 1912:</p>
<pre><code>>>> tz = pytz.timezone('Africa/Abidjan')
>>> tz._utc_transition_times
[datetime.datetime(1, 1, 1, 0, 0), datetime.datetime(1912, 1, 1, 0, 16, 8)]
</code></pre>
<p>The tz object we get out of pytz represents the pre-1912 timezone:</p>
<pre><code>>>> tz
<DstTzInfo 'Africa/Abidjan' LMT-1 day, 23:44:00 STD>
</code></pre>
<p>Now looking up at your two examples, see that when you call tz.localize(d) you do <em>NOT</em> get this pre-1912 timezone added to your naive datetime object. It assumes that the datetime object you give it represents local time <em>in the correct timezone for that local time</em>, which is the post-1912 timezone.</p>
<p>However in your second example using d.replace(tzinfo=tz), it takes your datetime object to represent the time in the pre-1912 timezone. This is probably not what you meant. Then when you call dt.normalize it converts this to the timezone that is correct for that datetime value, ie the post-1912 timezone.</p>
| 4 | 2009-10-20T06:40:10Z | [
"python",
"datetime",
"timezone",
"utc",
"pytz"
] |
pytz localize vs datetime replace | 1,379,740 | <p>I'm having some weird issues with pytz's .localize() function. Sometimes it wouldn't make adjustments to the localized datetime:</p>
<p>.localize behaviour:</p>
<pre><code>>>> tz
<DstTzInfo 'Africa/Abidjan' LMT-1 day, 23:44:00 STD>
>>> d
datetime.datetime(2009, 9, 2, 14, 45, 42, 91421)
>>> tz.localize(d)
datetime.datetime(2009, 9, 2, 14, 45, 42, 91421,
tzinfo=<DstTzInfo 'Africa/Abidjan' GMT0:00:00 STD>)
>>> tz.normalize(tz.localize(d))
datetime.datetime(2009, 9, 2, 14, 45, 42, 91421,
tzinfo=<DstTzInfo 'Africa/Abidjan' GMT0:00:00 STD>)
</code></pre>
<p>As you can see, time has not been changed as a result of localize/normalize operations.
However, if .replace is used:</p>
<pre><code>>>> d.replace(tzinfo=tz)
datetime.datetime(2009, 9, 2, 14, 45, 42, 91421,
tzinfo=<DstTzInfo 'Africa/Abidjan' LMT-1 day, 23:44:00 STD>)
>>> tz.normalize(d.replace(tzinfo=tz))
datetime.datetime(2009, 9, 2, 15, 1, 42, 91421,
tzinfo=<DstTzInfo 'Africa/Abidjan' GMT0:00:00 STD>)
</code></pre>
<p>Which seems to make adjustments into datetime. </p>
<p>Question is - which is correct and why other's wrong?</p>
<p>Thanks!</p>
| 25 | 2009-09-04T14:50:11Z | 4,693,938 | <p>I realize I'm a little late on this...
but here is what I found to work well.
Work in UTC as Alex stated: </p>
<pre><code>tz = pytz.timezone('Africa/Abidjan')
now = datetime.datetime.utcnow()
</code></pre>
<p>Then to localize:</p>
<pre><code>tzoffset = tz.utcoffset(now)
mynow = now+tzoffset
</code></pre>
<p>And this method does handle DST perfectly</p>
| 5 | 2011-01-14T17:23:16Z | [
"python",
"datetime",
"timezone",
"utc",
"pytz"
] |
Django and weird legacy database tables | 1,379,905 | <p>I'm trying to integrate a legacy database in Django.</p>
<p>I'm running into problems with some weird tables that result from horribly bad database design, but I'm not free to change it.</p>
<p>The problem is that there are tables that dont have a primarykey ID, but a product ID and, here comes the problem, a lot of them are multiple in case of a certain column needs to have multiple values, for example </p>
<pre><code>ID | ... | namestring
2 | ... | name1
2 | ... | name2
</code></pre>
<p>Is there a possibility to circumvent the usual primarykey behavior and write a function that returns an object for such an ID with multiple rows ? The column namestring could become a list then.</p>
<p>There is no manual editing required, as this is exported data from another system, I just have to access it..</p>
<p>Thanks for any hints !</p>
| 0 | 2009-09-04T15:18:32Z | 1,380,703 | <p>Django's ORM will have trouble working with this table unless you add a unique primary key column.</p>
<p>If you do add a primary key, then it would be trivial to write a method to query for a given product ID and return a list of the values corresponding to that product ID. Something like:</p>
<pre><code>def names_for(product_id):
return [row.namestring for row in ProductName.objects.filter(product_id=product_id)]
</code></pre>
<p>This function could also be a custom manager method, or a method on your Product model, or whatever makes most sense to you.</p>
<p><strong>EDIT</strong>: Assuming you have a Product model that the product_id in this table refers to, and the only use you'll have for this table is to look up these names for a given product, your other option is to leave this table out of the ORM altogether, and just write a method on Product that <a href="http://docs.djangoproject.com/en/dev/topics/db/sql/" rel="nofollow">uses raw SQL and cursor.execute</a> to fetch the names for that product. This is nice and clean and doesn't require adding a unique PK to the table. The main thing you lose is the ability to administer this table via Django modelforms or the admin.</p>
| 2 | 2009-09-04T18:00:32Z | [
"python",
"database",
"django",
"table",
"legacy"
] |
Splitting up a list into parts of balanced lengths | 1,380,162 | <p>I need an algorithm which given a list <code>L</code> and a number <code>N</code>, returns a list of <code>N</code> smaller lists where the sublists are "balanced". Examples:</p>
<pre><code>algo(range(1, 8), 3) -> [[1,2,3], [4,5], [6,7]]
algo(range(1, 6), 4) -> [[1,2], [3], [4], [5]]
algo(range(1, 12), 5) -> [[1,2,3], [4,5], [6,7], [8,9], [10, 11]]
</code></pre>
<p>As you can see, the algorithm should "prefer" the first list in the output.</p>
<p>I've been trying for hours, but I can't figure out a nice and terse algorithm for it. This will be implemented in Python, by the way, but it's really the algorithm that I'm after here. This is <em>not</em> homework, this is for a website which will display contents in a list in three columns (Django).</p>
<p><hr /></p>
<p>I got the best answer from #python on freenode and it is as follows:</p>
<pre><code>def split_up(l, n):
q, r = divmod(len(l), n)
def division_point(i):
return i * q + min(i, r)
return [l[division_point(i):division_point(i+1)] for i in range(n)]
</code></pre>
<p>Don't ask me why it works though. :) I'll give the correct answer to the one with most votes though.</p>
| 6 | 2009-09-04T16:04:41Z | 1,380,225 | <p>If I understand your problem... you would only have to add one item for each list under mod(n), where you have algo (range(a,b), n)</p>
<p>So you should:</p>
<ol>
<li>Have b-a > n</li>
<li>Calculate b-a = n*x + y (I dont really know if the operator % exists on python, so you should get y)</li>
<li>The first y lists will have (b-a/n + 1) elements and the other lists will have (b-a/n)</li>
</ol>
| 0 | 2009-09-04T16:16:46Z | [
"python",
"algorithm"
] |
Splitting up a list into parts of balanced lengths | 1,380,162 | <p>I need an algorithm which given a list <code>L</code> and a number <code>N</code>, returns a list of <code>N</code> smaller lists where the sublists are "balanced". Examples:</p>
<pre><code>algo(range(1, 8), 3) -> [[1,2,3], [4,5], [6,7]]
algo(range(1, 6), 4) -> [[1,2], [3], [4], [5]]
algo(range(1, 12), 5) -> [[1,2,3], [4,5], [6,7], [8,9], [10, 11]]
</code></pre>
<p>As you can see, the algorithm should "prefer" the first list in the output.</p>
<p>I've been trying for hours, but I can't figure out a nice and terse algorithm for it. This will be implemented in Python, by the way, but it's really the algorithm that I'm after here. This is <em>not</em> homework, this is for a website which will display contents in a list in three columns (Django).</p>
<p><hr /></p>
<p>I got the best answer from #python on freenode and it is as follows:</p>
<pre><code>def split_up(l, n):
q, r = divmod(len(l), n)
def division_point(i):
return i * q + min(i, r)
return [l[division_point(i):division_point(i+1)] for i in range(n)]
</code></pre>
<p>Don't ask me why it works though. :) I'll give the correct answer to the one with most votes though.</p>
| 6 | 2009-09-04T16:04:41Z | 1,380,256 | <p>This is the code I came up with, without the sorting. Just slap on a lst.sort() if the input is not sorted.</p>
<p>I think this came out nicely, using iterators and using islice to cut off the next piece.</p>
<pre><code>import itertools
def partlst(lst, n):
"""Partition @lst in @n balanced parts, in given order"""
parts, rest = divmod(len(lst), n)
lstiter = iter(lst)
for j in xrange(n):
plen = len(lst)/n + (1 if rest > 0 else 0)
rest -= 1
yield list(itertools.islice(lstiter, plen))
parts = list(partlst(range(1, 15), 5))
print len(parts)
print parts
</code></pre>
| 4 | 2009-09-04T16:21:49Z | [
"python",
"algorithm"
] |
Splitting up a list into parts of balanced lengths | 1,380,162 | <p>I need an algorithm which given a list <code>L</code> and a number <code>N</code>, returns a list of <code>N</code> smaller lists where the sublists are "balanced". Examples:</p>
<pre><code>algo(range(1, 8), 3) -> [[1,2,3], [4,5], [6,7]]
algo(range(1, 6), 4) -> [[1,2], [3], [4], [5]]
algo(range(1, 12), 5) -> [[1,2,3], [4,5], [6,7], [8,9], [10, 11]]
</code></pre>
<p>As you can see, the algorithm should "prefer" the first list in the output.</p>
<p>I've been trying for hours, but I can't figure out a nice and terse algorithm for it. This will be implemented in Python, by the way, but it's really the algorithm that I'm after here. This is <em>not</em> homework, this is for a website which will display contents in a list in three columns (Django).</p>
<p><hr /></p>
<p>I got the best answer from #python on freenode and it is as follows:</p>
<pre><code>def split_up(l, n):
q, r = divmod(len(l), n)
def division_point(i):
return i * q + min(i, r)
return [l[division_point(i):division_point(i+1)] for i in range(n)]
</code></pre>
<p>Don't ask me why it works though. :) I'll give the correct answer to the one with most votes though.</p>
| 6 | 2009-09-04T16:04:41Z | 1,380,306 | <p>Assuming you want output to contain lists of equal length when possible, otherwise give preference to lists in the beginning. Difference between lengths of sub-lists no more than one.</p>
<pre><code>>>> l = [0, 1, 2, 3, 4, 5, 6]
>>> def algo(li, n):
a, b = divmod(len(li), n)
c = [a + 1] * b + [a] * (n-b)
s = 0
for i, j in enumerate(c):
c[i] = li[s:s+j]
s += j
return c
>>> algo(l, 3)
[[0, 1, 2], [3, 4], [5, 6]]
>>> algo(l, 4)
[[0, 1], [2, 3], [4, 5], [6]]
</code></pre>
| 1 | 2009-09-04T16:33:02Z | [
"python",
"algorithm"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.