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 |
|---|---|---|---|---|---|---|---|---|---|
Recurrence sequence in Java / Python / Mathematica | 1,540,519 | <p><strong>How can you write the following statement in the given languages?</strong></p>
<pre><code>a(0) = 1
a_(n+1) = 1 - 1 / ( a_n + 3)
</code></pre>
<p>I need to find the smallest value of <code>n</code> when <code>a_n -> 0.732050...</code>.</p>
<p><strong>My attempt in Mathematica</strong></p>
<pre><code>a[(x+1)_] = 1 - 1/(a[x_] + 3)
</code></pre>
<p>The problem is apparently in this <code>a[(x+1)_]</code>.
However, I do not know how to do it iteratively in Mathematica.</p>
| 3 | 2009-10-08T21:12:03Z | 1,540,642 | <h3>Mathematica</h3>
<pre><code>a[0] = 1;
a[n_] := a[n] = 1 - 1/(a[n-1] + 3)
</code></pre>
<p>(Note the <a href="http://stackoverflow.com/questions/129877/how-do-i-write-a-generic-memoize-function/173038#173038">memoization trick</a>.)</p>
<p>Also, a[n] converges (very quickly) to sqrt(3)-1:</p>
<pre><code>Solve[x == 1 - 1/(x+3), x]
</code></pre>
| 8 | 2009-10-08T21:36:39Z | [
"java",
"python",
"wolfram-mathematica",
"sequence"
] |
Recurrence sequence in Java / Python / Mathematica | 1,540,519 | <p><strong>How can you write the following statement in the given languages?</strong></p>
<pre><code>a(0) = 1
a_(n+1) = 1 - 1 / ( a_n + 3)
</code></pre>
<p>I need to find the smallest value of <code>n</code> when <code>a_n -> 0.732050...</code>.</p>
<p><strong>My attempt in Mathematica</strong></p>
<pre><code>a[(x+1)_] = 1 - 1/(a[x_] + 3)
</code></pre>
<p>The problem is apparently in this <code>a[(x+1)_]</code>.
However, I do not know how to do it iteratively in Mathematica.</p>
| 3 | 2009-10-08T21:12:03Z | 1,540,722 | <p><strong>Python</strong></p>
<pre><code>next = lambda x: 1.0 - (1.0 / (float(x) + 3.0))
last, z, count = -1, 0.0, 0
while last != z:
print count, z
last, z, count = z, next(z), count+1
</code></pre>
<p>I try to avoid writing "while True" or such if I can avoid it. Almost certainly no code that I write will loop <em>forever</em>. In this case, it ran sixteen times for me. Sixteen is a lot less than âµ-null.</p>
| 2 | 2009-10-08T21:55:18Z | [
"java",
"python",
"wolfram-mathematica",
"sequence"
] |
Recurrence sequence in Java / Python / Mathematica | 1,540,519 | <p><strong>How can you write the following statement in the given languages?</strong></p>
<pre><code>a(0) = 1
a_(n+1) = 1 - 1 / ( a_n + 3)
</code></pre>
<p>I need to find the smallest value of <code>n</code> when <code>a_n -> 0.732050...</code>.</p>
<p><strong>My attempt in Mathematica</strong></p>
<pre><code>a[(x+1)_] = 1 - 1/(a[x_] + 3)
</code></pre>
<p>The problem is apparently in this <code>a[(x+1)_]</code>.
However, I do not know how to do it iteratively in Mathematica.</p>
| 3 | 2009-10-08T21:12:03Z | 1,541,755 | <p>Python, simplest:</p>
<pre><code>def a(n):
if n == 0: return 1
return 1 - 1 / float(a(n-1) + 3)
# limit is sqrt(3) - 1
limit = 3.0 ** 0.5 - 1.0
# get 9 digits' precision
i = 0
while abs(a(i) - limit) > 1.0e-9:
i += 1
print i
</code></pre>
<p>This emits <code>8</code>, suggesting that optimizations such as recursion elimination or memoizing are likely not warranted.</p>
<p>Of course normally we'd want to get the limit numerically rather than analytically, so the normal way to loop would be rather different -- and best encapsulated in a higher-order function...:</p>
<pre><code># get a function's limit numerically
def limit(f, eps=1.0e-11):
previous_value = f(0)
next_value = f(1)
i = 2
while abs(next_value - previous_value) > eps:
previous_value = next_value
next_value = f(i)
i += 1
return next_value
</code></pre>
<p>Nontrivial looping logic is usually best encapsulated in a generator:</p>
<pre><code>def next_prev(f):
previous_value = f(0)
i = 1
while True:
next_value = f(i)
yield next_value, previous_value
i += 1
previous_value = next_value
</code></pre>
<p>with the help of this generator, the <code>limit</code> HOF becomes much simpler:</p>
<pre><code>def limit(f, eps=1.0e-11):
for next_value, previous_value in next_prev(f):
if abs(next_value - previous_value) < eps:
return next_value
</code></pre>
<p>Note how useful the separation is: <code>next_prev</code> embodies the concept of "get the next and previous value of the function", <code>limit</code> just deals with "when should the loop terminate".</p>
<p>Last but not least, <a href="http://docs.python.org/library/itertools.html" rel="nofollow">itertools</a> often offers a good alternative to generators, letting you encapsulate finicky iteration logic in speedy ways (though it does take some getting used to...;-):</p>
<pre><code>import itertools
def next_prev(f):
values = itertools.imap(f, itertools.count())
prv, nxt = itertools.tee(values)
nxt.next()
return itertools.izip(prv, nxt)
</code></pre>
| 4 | 2009-10-09T04:13:07Z | [
"java",
"python",
"wolfram-mathematica",
"sequence"
] |
Recurrence sequence in Java / Python / Mathematica | 1,540,519 | <p><strong>How can you write the following statement in the given languages?</strong></p>
<pre><code>a(0) = 1
a_(n+1) = 1 - 1 / ( a_n + 3)
</code></pre>
<p>I need to find the smallest value of <code>n</code> when <code>a_n -> 0.732050...</code>.</p>
<p><strong>My attempt in Mathematica</strong></p>
<pre><code>a[(x+1)_] = 1 - 1/(a[x_] + 3)
</code></pre>
<p>The problem is apparently in this <code>a[(x+1)_]</code>.
However, I do not know how to do it iteratively in Mathematica.</p>
| 3 | 2009-10-08T21:12:03Z | 5,708,211 | <p>A one-liner in Mathematica which gives a list of exact elements of your sequence:</p>
<pre><code>In[66]:= NestWhileList[1 - 1/(#1 + 3) &, 1,
RealExponent[Subtract[##]] > -8 &, 2]
Out[66]= {1, 3/4, 11/15, 41/56, 153/209, 571/780, 2131/2911, \
7953/10864, 29681/40545}
</code></pre>
<p>The difference between the last two elements is less than 10^-8. It thus have taken 8 iterations:</p>
<pre><code>In[67]:= Length[%]
Out[67]= 9
</code></pre>
| 1 | 2011-04-18T20:01:44Z | [
"java",
"python",
"wolfram-mathematica",
"sequence"
] |
Java Equivalent to Python Dictionaries | 1,540,673 | <p>I am a long time user of Python and really like the way that the dictionaries are used. They are very intuitive and easy to use. Is there a good Java equivalent to python's dictionaries? I have heard of people using hashmaps and hashtables. Could someone explain the similarities and differences of using hashtables and hashmaps versus python's dictionaries?</p>
| 59 | 2009-10-08T21:44:34Z | 1,540,683 | <p>As far as I'm aware (I don't actually use java) dictionaries are just another name for a hashmap/hashtable.</p>
<p>Grabbing code from <a href="http://www.fluffycat.com/Java/HashMaps/" rel="nofollow">http://www.fluffycat.com/Java/HashMaps/</a> it seems they are used in a very similar manner, with a bit of extra java boiler-plate.</p>
| 3 | 2009-10-08T21:46:16Z | [
"java",
"python",
"hash",
"dictionary"
] |
Java Equivalent to Python Dictionaries | 1,540,673 | <p>I am a long time user of Python and really like the way that the dictionaries are used. They are very intuitive and easy to use. Is there a good Java equivalent to python's dictionaries? I have heard of people using hashmaps and hashtables. Could someone explain the similarities and differences of using hashtables and hashmaps versus python's dictionaries?</p>
| 59 | 2009-10-08T21:44:34Z | 1,540,699 | <p>Python's <code>dict</code> class is an implementation of what the Python documentation informally calls "<a href="http://docs.python.org/library/stdtypes.html#mapping-types-dict">mapping types</a>". Internally, <code>dict</code> is implemented using a hashtable.</p>
<p>Java's <a href="http://java.sun.com/javase/6/docs/api/java/util/HashMap.html"><code>HashMap</code></a> class is an implementation of the <a href="http://java.sun.com/javase/6/docs/api/java/util/Map.html"><code>Map</code></a> interface. Internally, <code>HashMap</code> is implemented using a hashtable.</p>
<p>There are a few minor differences in syntax, and I believe the implementations are tuned slightly differently, but overall they are completely interchangeable.</p>
| 59 | 2009-10-08T21:49:58Z | [
"java",
"python",
"hash",
"dictionary"
] |
Java Equivalent to Python Dictionaries | 1,540,673 | <p>I am a long time user of Python and really like the way that the dictionaries are used. They are very intuitive and easy to use. Is there a good Java equivalent to python's dictionaries? I have heard of people using hashmaps and hashtables. Could someone explain the similarities and differences of using hashtables and hashmaps versus python's dictionaries?</p>
| 59 | 2009-10-08T21:44:34Z | 1,540,813 | <p>One difference between the two is that <code>dict</code> has stricter requirements as to what data types can act as a key. Java will allow any object to work as a key -- although you should take care to ensure that the object's <code>hashCode()</code> method returns a unique value that reflects its internal state. Python requires keys to fit its definition of <a href="http://docs.python.org/3.1/glossary.html#term-hashable" rel="nofollow">hashable</a>, which specifies that the object's hash code should never change over its lifetime.</p>
| 3 | 2009-10-08T22:16:35Z | [
"java",
"python",
"hash",
"dictionary"
] |
Java Equivalent to Python Dictionaries | 1,540,673 | <p>I am a long time user of Python and really like the way that the dictionaries are used. They are very intuitive and easy to use. Is there a good Java equivalent to python's dictionaries? I have heard of people using hashmaps and hashtables. Could someone explain the similarities and differences of using hashtables and hashmaps versus python's dictionaries?</p>
| 59 | 2009-10-08T21:44:34Z | 39,432,556 | <p>The idea of dictionary and Map is similar. Both contain elements like</p>
<pre><code>key1:value1, key2:value2 ... and so on
</code></pre>
<p>In Java, <code>Map</code> is implemented different ways like <code>HashMap</code>, or <code>TreeMap</code> etc. <code>put(), get()</code> operations are similar</p>
<pre><code>Map map = new HashMap();
// Put elements to the map
map.put("Ram", new Double(3434.34));
map.put("Krishna", new Double(123.22));
map.put("Hary", new Double(1378.00));
//to get elements
map.get("Krishna"); # =123.22
map.get("Hary"); # = 1378.00
</code></pre>
<p>See documentation of HashMap in java8 <a href="https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html" rel="nofollow">https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html</a></p>
| 1 | 2016-09-11T03:26:10Z | [
"java",
"python",
"hash",
"dictionary"
] |
how to force python httplib library to use only A requests | 1,540,749 | <p>The problem is that urllib using httplib is querying fro AAAA records what i would like to avoid. Is there a nice way to do that?</p>
<pre><code>>>> import socket
>>> socket.gethostbyname('www.python.org')
'82.94.164.162'
21:52:37.302028 IP 192.168.0.9.44992 > 192.168.0.1.53: 27463+ A? www.python.org. (32)
21:52:37.312031 IP 192.168.0.1.53 > 192.168.0.9.44992: 27463 1/0/0 A 82.94.164.162 (48)
python /usr/lib/python2.6/urllib.py -t http://www.python.org >/dev/null 2>&1
21:53:44.118314 IP 192.168.0.9.40669 > 192.168.0.1.53: 32354+ A? www.python.org. (32)
21:53:44.118647 IP 192.168.0.9.40669 > 192.168.0.1.53: 50414+ AAAA? www.python.org. (32)
21:53:44.122547 IP 192.168.0.1.53 > 192.168.0.9.40669: 32354 1/0/0 A 82.94.164.162 (48)
21:53:44.135215 IP 192.168.0.1.53 > 192.168.0.9.40669: 50414 1/0/0 AAAA[|domain]
</code></pre>
| 2 | 2009-10-08T22:01:50Z | 1,540,776 | <p>Look here: <a href="http://stackoverflow.com/questions/1189253/how-do-i-resolve-an-srv-record-in-python">how-do-i-resolve-an-srv-record-in-python</a></p>
<p>Once you resolved the correct A ip, use it in your request, instead of the dns.</p>
| 1 | 2009-10-08T22:07:10Z | [
"python",
"dns",
"ipv6",
"ipv4"
] |
how to force python httplib library to use only A requests | 1,540,749 | <p>The problem is that urllib using httplib is querying fro AAAA records what i would like to avoid. Is there a nice way to do that?</p>
<pre><code>>>> import socket
>>> socket.gethostbyname('www.python.org')
'82.94.164.162'
21:52:37.302028 IP 192.168.0.9.44992 > 192.168.0.1.53: 27463+ A? www.python.org. (32)
21:52:37.312031 IP 192.168.0.1.53 > 192.168.0.9.44992: 27463 1/0/0 A 82.94.164.162 (48)
python /usr/lib/python2.6/urllib.py -t http://www.python.org >/dev/null 2>&1
21:53:44.118314 IP 192.168.0.9.40669 > 192.168.0.1.53: 32354+ A? www.python.org. (32)
21:53:44.118647 IP 192.168.0.9.40669 > 192.168.0.1.53: 50414+ AAAA? www.python.org. (32)
21:53:44.122547 IP 192.168.0.1.53 > 192.168.0.9.40669: 32354 1/0/0 A 82.94.164.162 (48)
21:53:44.135215 IP 192.168.0.1.53 > 192.168.0.9.40669: 50414 1/0/0 AAAA[|domain]
</code></pre>
| 2 | 2009-10-08T22:01:50Z | 1,546,412 | <p>The correct answer is:</p>
<p><a href="http://docs.python.org/library/socket.html">http://docs.python.org/library/socket.html</a></p>
<p>The Python socket library is using the following:</p>
<p>socket.socket([family[, type[, proto]]])
Create a new socket using the given address family, socket type and protocol number. The address family should be AF_INET (the default), AF_INET6 or AF_UNIX. The socket type should be SOCK_STREAM (the default), SOCK_DGRAM or perhaps one of the other SOCK_ constants. The protocol number is usually zero and may be omitted in that case.</p>
<pre><code>/* Supported address families. */
#define AF_UNSPEC 0
#define AF_INET 2 /* Internet IP Protocol */
#define AF_INET6 10 /* IP version 6 */
</code></pre>
<p>By default it is using 0 and if you call it with 2 it will query only for A records.</p>
<p>Remember caching the resolv results in your app IS A REALLY BAD IDEA. Never do it!</p>
| 6 | 2009-10-09T22:43:12Z | [
"python",
"dns",
"ipv6",
"ipv4"
] |
Dumping a multiprocessing.Queue into a list | 1,540,822 | <p>I wish to dump a <code>multiprocessing.Queue</code> into a list. For that task I've written the following function:</p>
<pre><code>import Queue
def dump_queue(queue):
"""
Empties all pending items in a queue and returns them in a list.
"""
result = []
# START DEBUG CODE
initial_size = queue.qsize()
print("Queue has %s items initially." % initial_size)
# END DEBUG CODE
while True:
try:
thing = queue.get(block=False)
result.append(thing)
except Queue.Empty:
# START DEBUG CODE
current_size = queue.qsize()
total_size = current_size + len(result)
print("Dumping complete:")
if current_size == initial_size:
print("No items were added to the queue.")
else:
print("%s items were added to the queue." % \
(total_size - initial_size))
print("Extracted %s items from the queue, queue has %s items \
left" % (len(result), current_size))
# END DEBUG CODE
return result
</code></pre>
<p>But for some reason it doesn't work.</p>
<p>Observe the following shell session:</p>
<pre><code>>>> import multiprocessing
>>> q = multiprocessing.Queue()
>>> for i in range(100):
... q.put([range(200) for j in range(100)])
...
>>> q.qsize()
100
>>> l=dump_queue(q)
Queue has 100 items initially.
Dumping complete:
0 items were added to the queue.
Extracted 1 items from the queue, queue has 99 items left
>>> l=dump_queue(q)
Queue has 99 items initially.
Dumping complete:
0 items were added to the queue.
Extracted 3 items from the queue, queue has 96 items left
>>> l=dump_queue(q)
Queue has 96 items initially.
Dumping complete:
0 items were added to the queue.
Extracted 1 items from the queue, queue has 95 items left
>>>
</code></pre>
<p>What's happening here? Why aren't all the items being dumped?</p>
| 14 | 2009-10-08T22:17:37Z | 1,541,117 | <p>Try this:</p>
<pre><code>import Queue
import time
def dump_queue(queue):
"""
Empties all pending items in a queue and returns them in a list.
"""
result = []
for i in iter(queue.get, 'STOP'):
result.append(i)
time.sleep(.1)
return result
import multiprocessing
q = multiprocessing.Queue()
for i in range(100):
q.put([range(200) for j in range(100)])
q.put('STOP')
l=dump_queue(q)
print len(l)
</code></pre>
<p>Multiprocessing queues have an internal buffer which has a feeder thread which pulls work off a buffer and flushes it to the pipe. If not all of the objects have been flushed, I could see a case where Empty is raised prematurely. Using a sentinel to indicate the end of the queue is safe (and reliable). Also, using the iter(get, sentinel) idiom is just better than relying on Empty.</p>
<p>I don't like that it could raise empty due to flushing timing (I added the time.sleep(.1) to allow a context switch to the feeder thread, you may not need it, it works without it - it's a habit to release the GIL).</p>
| 18 | 2009-10-08T23:36:18Z | [
"python",
"queue",
"multiprocessing"
] |
Dumping a multiprocessing.Queue into a list | 1,540,822 | <p>I wish to dump a <code>multiprocessing.Queue</code> into a list. For that task I've written the following function:</p>
<pre><code>import Queue
def dump_queue(queue):
"""
Empties all pending items in a queue and returns them in a list.
"""
result = []
# START DEBUG CODE
initial_size = queue.qsize()
print("Queue has %s items initially." % initial_size)
# END DEBUG CODE
while True:
try:
thing = queue.get(block=False)
result.append(thing)
except Queue.Empty:
# START DEBUG CODE
current_size = queue.qsize()
total_size = current_size + len(result)
print("Dumping complete:")
if current_size == initial_size:
print("No items were added to the queue.")
else:
print("%s items were added to the queue." % \
(total_size - initial_size))
print("Extracted %s items from the queue, queue has %s items \
left" % (len(result), current_size))
# END DEBUG CODE
return result
</code></pre>
<p>But for some reason it doesn't work.</p>
<p>Observe the following shell session:</p>
<pre><code>>>> import multiprocessing
>>> q = multiprocessing.Queue()
>>> for i in range(100):
... q.put([range(200) for j in range(100)])
...
>>> q.qsize()
100
>>> l=dump_queue(q)
Queue has 100 items initially.
Dumping complete:
0 items were added to the queue.
Extracted 1 items from the queue, queue has 99 items left
>>> l=dump_queue(q)
Queue has 99 items initially.
Dumping complete:
0 items were added to the queue.
Extracted 3 items from the queue, queue has 96 items left
>>> l=dump_queue(q)
Queue has 96 items initially.
Dumping complete:
0 items were added to the queue.
Extracted 1 items from the queue, queue has 95 items left
>>>
</code></pre>
<p>What's happening here? Why aren't all the items being dumped?</p>
| 14 | 2009-10-08T22:17:37Z | 39,765,300 | <p>In some situations we already computed everything and we want just to convert the Queue.</p>
<pre><code>shared_queue = Queue()
shared_queue_list = []
...
join() #All process are joined
while shared_queue.qsize() != 0:
shared_queue_list.append(shared_queue.get())
</code></pre>
<p>Now shared_queue_list has the results converted to a list.</p>
| 2 | 2016-09-29T08:33:54Z | [
"python",
"queue",
"multiprocessing"
] |
How make a better markdown for developer blog | 1,540,834 | <p>I'm rebuilding my blog at <a href="http://www.elmalabarista.com/blog/" rel="nofollow">http://www.elmalabarista.com/blog/</a>. I have use in my previous version markdown and now I remember why I have almost zero code samples. Doing code samples in markdown is very fragile.</p>
<p>I try to put some python there I can't make markdown mark it as code!. The main culprit? The syntax is markdown for code is out spaces. Despite the fact I use wmd as the editor (how that work here in SO is a mistery for me), it never be able to move rigth the text so never get as code. this is the problem:</p>
<p>I put something simple:</p>
<pre><code>:::python
def hello():
pass
</code></pre>
<p>But the problem is that something I have:</p>
<p>:::python
def hello():
pass</p>
<p>or</p>
<p>:::python
def hello():
pass</p>
<p>(yes bot was formatted but you see? not work). Any mistake -using tabs, too much, too litle spaces) is punished heavily. And if the code is long, the chance of a problem increase too.</p>
<p>So, exist any way to simply do:</p>
<p>### My article</p>
<ol>
<li>My list entry one</li>
<li>My list entry two</li>
</ol>
<p>:::python
def x (a, b):
return a * b</p>
<p>and get converted rigth and never bother about this small thing again???</p>
<p>By the way, I'm using pygments & python markdown.</p>
| 1 | 2009-10-08T22:21:13Z | 1,540,849 | <p>Consider using <a href="http://docutils.sourceforge.net/rst.html" rel="nofollow">reStructuredText</a> -- it's the standard lightweight markup for Python, and is often used for docstrings and embedded documentation. It's quite easy, but also powerful -- if I remember correctly, the core Python libraries and Django both use it.</p>
| 3 | 2009-10-08T22:26:00Z | [
"python",
"markdown",
"code-formatting"
] |
How make a better markdown for developer blog | 1,540,834 | <p>I'm rebuilding my blog at <a href="http://www.elmalabarista.com/blog/" rel="nofollow">http://www.elmalabarista.com/blog/</a>. I have use in my previous version markdown and now I remember why I have almost zero code samples. Doing code samples in markdown is very fragile.</p>
<p>I try to put some python there I can't make markdown mark it as code!. The main culprit? The syntax is markdown for code is out spaces. Despite the fact I use wmd as the editor (how that work here in SO is a mistery for me), it never be able to move rigth the text so never get as code. this is the problem:</p>
<p>I put something simple:</p>
<pre><code>:::python
def hello():
pass
</code></pre>
<p>But the problem is that something I have:</p>
<p>:::python
def hello():
pass</p>
<p>or</p>
<p>:::python
def hello():
pass</p>
<p>(yes bot was formatted but you see? not work). Any mistake -using tabs, too much, too litle spaces) is punished heavily. And if the code is long, the chance of a problem increase too.</p>
<p>So, exist any way to simply do:</p>
<p>### My article</p>
<ol>
<li>My list entry one</li>
<li>My list entry two</li>
</ol>
<p>:::python
def x (a, b):
return a * b</p>
<p>and get converted rigth and never bother about this small thing again???</p>
<p>By the way, I'm using pygments & python markdown.</p>
| 1 | 2009-10-08T22:21:13Z | 1,540,958 | <p>I've been using <a href="http://code.google.com/p/google-code-prettify/" rel="nofollow">google-code-prettify</a>, which works pretty well.</p>
<p><strong><a href="http://google-code-prettify.googlecode.com/svn/trunk/README.html" rel="nofollow">Usage</a></strong>:</p>
<p>Put code snippets in <pre class="prettyprint">...</pre> or <code class="prettyprint">...</code> and it will automatically be pretty printed.</p>
| 1 | 2009-10-08T22:52:05Z | [
"python",
"markdown",
"code-formatting"
] |
How make a better markdown for developer blog | 1,540,834 | <p>I'm rebuilding my blog at <a href="http://www.elmalabarista.com/blog/" rel="nofollow">http://www.elmalabarista.com/blog/</a>. I have use in my previous version markdown and now I remember why I have almost zero code samples. Doing code samples in markdown is very fragile.</p>
<p>I try to put some python there I can't make markdown mark it as code!. The main culprit? The syntax is markdown for code is out spaces. Despite the fact I use wmd as the editor (how that work here in SO is a mistery for me), it never be able to move rigth the text so never get as code. this is the problem:</p>
<p>I put something simple:</p>
<pre><code>:::python
def hello():
pass
</code></pre>
<p>But the problem is that something I have:</p>
<p>:::python
def hello():
pass</p>
<p>or</p>
<p>:::python
def hello():
pass</p>
<p>(yes bot was formatted but you see? not work). Any mistake -using tabs, too much, too litle spaces) is punished heavily. And if the code is long, the chance of a problem increase too.</p>
<p>So, exist any way to simply do:</p>
<p>### My article</p>
<ol>
<li>My list entry one</li>
<li>My list entry two</li>
</ol>
<p>:::python
def x (a, b):
return a * b</p>
<p>and get converted rigth and never bother about this small thing again???</p>
<p>By the way, I'm using pygments & python markdown.</p>
| 1 | 2009-10-08T22:21:13Z | 2,082,939 | <p>You need to indent code more than 4 spaces (btw have you noticed on SO if you add 4 spaces it gets recognized as code), this is 4 space indented:</p>
<pre><code>:::python
def hello():
pass
</code></pre>
| 1 | 2010-01-17T22:37:34Z | [
"python",
"markdown",
"code-formatting"
] |
Trace/BPT trap with Python threading module | 1,540,835 | <p>The following code dies with <code>Trace/BPT trap</code>:</p>
<pre><code>from tvdb_api import Tvdb
from threading import Thread
class GrabStuff(Thread):
def run(self):
t = Tvdb()
def main():
threads = [GrabStuff() for x in range(1)]
[x.start() for x in threads]
[x.join() for x in threads]
if __name__ == '__main__':
main()
</code></pre>
<p>The error occurs due to the <code>Tvdb()</code>, but I have no idea why.</p>
<p>I ran the code with <code>python -m pdb thescript.py</code> and stepped through the code, and it dies at after the following lines:</p>
<pre><code>> .../threading.py(468)start()
-> _active_limbo_lock.acquire()
(Pdb)
> .../threading.py(469)start()
-> _limbo[self] = self
(Pdb)
> .../threading.py(470)start()
-> _active_limbo_lock.release()
(Pdb)
> .../threading.py(471)start()
-> _start_new_thread(self.__bootstrap, ())
(Pdb)
> .../threading.py(472)start()
-> self.__started.wait()
(Pdb) Trace/BPT trap
</code></pre>
<p>(I replaced the full path to threading.py with <code>...</code>)</p>
<p>The same problem occurs with <code>2.6.1</code> and <code>2.5.4</code>. The machine is running on OS X 10.6.1 Snow Leopard. The <code>tvdb_api</code> code can be found on <a href="http://github.com/dbr/tvdb%5Fapi" rel="nofollow">github.com/dbr/tvdb_api</a></p>
| 1 | 2009-10-08T22:21:16Z | 1,547,316 | <p>Bad things can happen when importing modules for the first time in a thread on OS X 10.6. See, for instance, <a href="http://bugs.python.org/issue7085" rel="nofollow">this issue</a>. As a workaround, try looking through Tvdb and add its complete chain of imports to the main module.</p>
| 3 | 2009-10-10T07:41:55Z | [
"python",
"multithreading"
] |
Python 'object' type and inheritance | 1,540,975 | <p>In Python I can define a class 'foo' in the following ways:</p>
<pre><code>class foo:
pass
</code></pre>
<p>or</p>
<pre><code>class foo(object):
pass
</code></pre>
<p>What is the difference? I have tried to use the function issubclass(foo, object) to see if it returns True for both class definitions. It does not.</p>
<pre>
IDLE 2.6.3
>>> class foo:
pass
>>> issubclass(foo, object)
False
>>> class foo(object):
pass
>>> issubclass(foo, object)
True
</pre>
<p>Thanks.</p>
| 4 | 2009-10-08T22:56:28Z | 1,540,998 | <p>Inheriting from <code>object</code> makes a class a "new-style class". There is a discussion of old-style vs. new-style here: <a href="http://stackoverflow.com/questions/54867/old-style-and-new-style-classes-in-python">Old style and new style classes in Python</a></p>
<p>As @CrazyJugglerDrummer commented below, in Python 3 all classes are "new-style" classes. In Python 3, the following two declarations are exactly equivalent:</p>
<pre><code>class A(object):
pass
class A:
pass
</code></pre>
| 9 | 2009-10-08T23:04:13Z | [
"python",
"inheritance",
"object"
] |
Python 'object' type and inheritance | 1,540,975 | <p>In Python I can define a class 'foo' in the following ways:</p>
<pre><code>class foo:
pass
</code></pre>
<p>or</p>
<pre><code>class foo(object):
pass
</code></pre>
<p>What is the difference? I have tried to use the function issubclass(foo, object) to see if it returns True for both class definitions. It does not.</p>
<pre>
IDLE 2.6.3
>>> class foo:
pass
>>> issubclass(foo, object)
False
>>> class foo(object):
pass
>>> issubclass(foo, object)
True
</pre>
<p>Thanks.</p>
| 4 | 2009-10-08T22:56:28Z | 1,541,003 | <p>The first creates an "old-style" class, which are deprecated and have been removed in Python 3. You should not use it in Python 2.x. See the documentation for the <a href="http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes" rel="nofollow">Python data model</a>.</p>
| 2 | 2009-10-08T23:04:59Z | [
"python",
"inheritance",
"object"
] |
Python 'object' type and inheritance | 1,540,975 | <p>In Python I can define a class 'foo' in the following ways:</p>
<pre><code>class foo:
pass
</code></pre>
<p>or</p>
<pre><code>class foo(object):
pass
</code></pre>
<p>What is the difference? I have tried to use the function issubclass(foo, object) to see if it returns True for both class definitions. It does not.</p>
<pre>
IDLE 2.6.3
>>> class foo:
pass
>>> issubclass(foo, object)
False
>>> class foo(object):
pass
>>> issubclass(foo, object)
True
</pre>
<p>Thanks.</p>
| 4 | 2009-10-08T22:56:28Z | 1,541,004 | <p><em>Old style</em> and <em>new style</em> objects... they have sightly different behaviours, for example in the constructors, or in the method resolution order in multiple inheritance.</p>
| 2 | 2009-10-08T23:05:12Z | [
"python",
"inheritance",
"object"
] |
Bubble Breaker Game Solver better than greedy? | 1,541,101 | <p>For a mental exercise I decided to try and solve the bubble breaker game found on many cell phones as well as an example here:<a href="http://www.kongregate.com/games/Sevas/bubble-breaker-game" rel="nofollow">Bubble Break Game</a></p>
<ul>
<li>The random (N,M,C) board consists N rows x M columns with C colors</li>
<li>The goal is to get the highest score by picking the sequence of bubble groups that ultimately leads to the highest score </li>
<li>A bubble group is 2 or more bubbles of the same color that are adjacent to each other in either x or y direction. Diagonals do not count </li>
<li>When a group is picked, the bubbles disappear, any holes are filled with bubbles from above first, ie shift down, then any holes are filled by shifting right</li>
<li>A bubble group score = n * (n - 1) where n is the number of bubbles in the bubble group</li>
</ul>
<p>The first algorithm is a simple exhaustive recursive algorithm which explores going through the board row by row and column by column picking bubble groups. Once the bubble group is picked, we create a new board and try to solve that board, recursively descending down</p>
<p>Some of the ideas I am using include normalized memoization. Once a board is solved we store the board and the best score in a memoization table. </p>
<p>I create a <a href="http://pastebin.com/f4ca00800" rel="nofollow">prototype in python</a> which shows a (2,15,5) board takes 8859 boards to solve in about 3 seconds. A (3,15,5) board takes 12,384,726 boards in 50 minutes on a server. The solver rate is ~3k-4k boards/sec and gradually decreases as the memoization search takes longer. Memoization table grows to 5,692,482 boards, and hits 6,713,566 times.</p>
<p>What other approaches could yield high scores besides the exhaustive search?</p>
<p>I don't seen any obvious way to divide and conquer. But trending towards larger and larger bubbles groups seems to be one approach</p>
<p>Thanks to David Locke for posting the paper link which talks above a window solver which uses a constant-depth lookahead heuristic. </p>
| 4 | 2009-10-08T23:29:18Z | 1,541,124 | <p>This isn't my area of expertise, but I would like to recommend a book to you. Get a copy of <a href="http://www.algorist.com/" rel="nofollow">The Algorithm Design Manual</a> by Steven Skiena. This has a whole list of different algorithms, and once you read through it you can use it as a reference. If nothing else it will help you consider your options.</p>
| 0 | 2009-10-08T23:37:57Z | [
"python",
"algorithm",
"language-agnostic"
] |
Bubble Breaker Game Solver better than greedy? | 1,541,101 | <p>For a mental exercise I decided to try and solve the bubble breaker game found on many cell phones as well as an example here:<a href="http://www.kongregate.com/games/Sevas/bubble-breaker-game" rel="nofollow">Bubble Break Game</a></p>
<ul>
<li>The random (N,M,C) board consists N rows x M columns with C colors</li>
<li>The goal is to get the highest score by picking the sequence of bubble groups that ultimately leads to the highest score </li>
<li>A bubble group is 2 or more bubbles of the same color that are adjacent to each other in either x or y direction. Diagonals do not count </li>
<li>When a group is picked, the bubbles disappear, any holes are filled with bubbles from above first, ie shift down, then any holes are filled by shifting right</li>
<li>A bubble group score = n * (n - 1) where n is the number of bubbles in the bubble group</li>
</ul>
<p>The first algorithm is a simple exhaustive recursive algorithm which explores going through the board row by row and column by column picking bubble groups. Once the bubble group is picked, we create a new board and try to solve that board, recursively descending down</p>
<p>Some of the ideas I am using include normalized memoization. Once a board is solved we store the board and the best score in a memoization table. </p>
<p>I create a <a href="http://pastebin.com/f4ca00800" rel="nofollow">prototype in python</a> which shows a (2,15,5) board takes 8859 boards to solve in about 3 seconds. A (3,15,5) board takes 12,384,726 boards in 50 minutes on a server. The solver rate is ~3k-4k boards/sec and gradually decreases as the memoization search takes longer. Memoization table grows to 5,692,482 boards, and hits 6,713,566 times.</p>
<p>What other approaches could yield high scores besides the exhaustive search?</p>
<p>I don't seen any obvious way to divide and conquer. But trending towards larger and larger bubbles groups seems to be one approach</p>
<p>Thanks to David Locke for posting the paper link which talks above a window solver which uses a constant-depth lookahead heuristic. </p>
| 4 | 2009-10-08T23:29:18Z | 1,541,206 | <p>According to <a href="http://erikdemaine.org/clickomania/">this paper</a>, determining if you can empty the board (which is related to the problem you want to solve) is NP-Complete. That doesn't mean that you won't be able to find a good algorithm, it just means that you likely won't find an efficient one.</p>
| 7 | 2009-10-09T00:01:34Z | [
"python",
"algorithm",
"language-agnostic"
] |
Bubble Breaker Game Solver better than greedy? | 1,541,101 | <p>For a mental exercise I decided to try and solve the bubble breaker game found on many cell phones as well as an example here:<a href="http://www.kongregate.com/games/Sevas/bubble-breaker-game" rel="nofollow">Bubble Break Game</a></p>
<ul>
<li>The random (N,M,C) board consists N rows x M columns with C colors</li>
<li>The goal is to get the highest score by picking the sequence of bubble groups that ultimately leads to the highest score </li>
<li>A bubble group is 2 or more bubbles of the same color that are adjacent to each other in either x or y direction. Diagonals do not count </li>
<li>When a group is picked, the bubbles disappear, any holes are filled with bubbles from above first, ie shift down, then any holes are filled by shifting right</li>
<li>A bubble group score = n * (n - 1) where n is the number of bubbles in the bubble group</li>
</ul>
<p>The first algorithm is a simple exhaustive recursive algorithm which explores going through the board row by row and column by column picking bubble groups. Once the bubble group is picked, we create a new board and try to solve that board, recursively descending down</p>
<p>Some of the ideas I am using include normalized memoization. Once a board is solved we store the board and the best score in a memoization table. </p>
<p>I create a <a href="http://pastebin.com/f4ca00800" rel="nofollow">prototype in python</a> which shows a (2,15,5) board takes 8859 boards to solve in about 3 seconds. A (3,15,5) board takes 12,384,726 boards in 50 minutes on a server. The solver rate is ~3k-4k boards/sec and gradually decreases as the memoization search takes longer. Memoization table grows to 5,692,482 boards, and hits 6,713,566 times.</p>
<p>What other approaches could yield high scores besides the exhaustive search?</p>
<p>I don't seen any obvious way to divide and conquer. But trending towards larger and larger bubbles groups seems to be one approach</p>
<p>Thanks to David Locke for posting the paper link which talks above a window solver which uses a constant-depth lookahead heuristic. </p>
| 4 | 2009-10-08T23:29:18Z | 1,541,209 | <p>I'm thinking you could try a branch and bound search with the following idea:</p>
<ol>
<li><p>Given a state of the game S, you branch on S by breaking it up in m sets Si where each Si is the state after taking a legal move of all m legal moves given the state S</p></li>
<li><p>You need two functions U(S) and L(S) that compute a lower and upper bound respectively of a given state S. </p>
<p>For the U(S) function I'm thinking calculate the score that you would get if you were able to freely shuffle K bubbles in the board (each move) and arrange the blocks in such a way that would result in the highest score, where K is a value you choose yourself. When your calculating U(S) for a given S it should go quicker if you choose higher K (the conditions are relaxed) so choosing the value of K will be a trade of for quickness of finding U(S) and quality (how tight an upper bound U(S) is.)</p>
<p>For the L(S) function calculate the score that you would get if you simply randomly kept click until you got to a state that could not be solved any further. You can do this several times taking the highest lower bound that you get.</p></li>
</ol>
<p>Once you have these two functions you can apply standard Bound and Branch search. Note that the speed of your search is going to greatly depend on how tight your Upper Bound is and how tight your Lower Bound is.</p>
| 1 | 2009-10-09T00:02:44Z | [
"python",
"algorithm",
"language-agnostic"
] |
Bubble Breaker Game Solver better than greedy? | 1,541,101 | <p>For a mental exercise I decided to try and solve the bubble breaker game found on many cell phones as well as an example here:<a href="http://www.kongregate.com/games/Sevas/bubble-breaker-game" rel="nofollow">Bubble Break Game</a></p>
<ul>
<li>The random (N,M,C) board consists N rows x M columns with C colors</li>
<li>The goal is to get the highest score by picking the sequence of bubble groups that ultimately leads to the highest score </li>
<li>A bubble group is 2 or more bubbles of the same color that are adjacent to each other in either x or y direction. Diagonals do not count </li>
<li>When a group is picked, the bubbles disappear, any holes are filled with bubbles from above first, ie shift down, then any holes are filled by shifting right</li>
<li>A bubble group score = n * (n - 1) where n is the number of bubbles in the bubble group</li>
</ul>
<p>The first algorithm is a simple exhaustive recursive algorithm which explores going through the board row by row and column by column picking bubble groups. Once the bubble group is picked, we create a new board and try to solve that board, recursively descending down</p>
<p>Some of the ideas I am using include normalized memoization. Once a board is solved we store the board and the best score in a memoization table. </p>
<p>I create a <a href="http://pastebin.com/f4ca00800" rel="nofollow">prototype in python</a> which shows a (2,15,5) board takes 8859 boards to solve in about 3 seconds. A (3,15,5) board takes 12,384,726 boards in 50 minutes on a server. The solver rate is ~3k-4k boards/sec and gradually decreases as the memoization search takes longer. Memoization table grows to 5,692,482 boards, and hits 6,713,566 times.</p>
<p>What other approaches could yield high scores besides the exhaustive search?</p>
<p>I don't seen any obvious way to divide and conquer. But trending towards larger and larger bubbles groups seems to be one approach</p>
<p>Thanks to David Locke for posting the paper link which talks above a window solver which uses a constant-depth lookahead heuristic. </p>
| 4 | 2009-10-08T23:29:18Z | 1,541,230 | <p>To get a faster solution than exhaustive search, I think what you want is probably dynamic programming. In dynamic programming, you find some sort of "step" that takes you possibly closer to your solution, and keep track of the results of each step in a big matrix. Then, once you have filled in the matrix, you can find the best result, and then work backward to get a path through the matrix that leads to the best result. The matrix is effectively a form of memoization.</p>
<p>Dynamic programming is discussed in <a href="http://www.algorist.com/" rel="nofollow">The Algorithm Design Manual</a> but there is also plenty of discussion of it on the web. Here's a good intro: <a href="http://20bits.com/articles/introduction-to-dynamic-programming/" rel="nofollow">http://20bits.com/articles/introduction-to-dynamic-programming/</a></p>
<p>I'm not sure exactly what the "step" is for this problem. Perhaps you could make a scoring metric for a board that simply sums the points for each of the bubble groups, and then record this score as you try popping balloons? Good steps would tend to cause bubble groups to coalesce, improving the score, and bad steps would break up bubble groups, making the score worse.</p>
| 1 | 2009-10-09T00:10:10Z | [
"python",
"algorithm",
"language-agnostic"
] |
Bubble Breaker Game Solver better than greedy? | 1,541,101 | <p>For a mental exercise I decided to try and solve the bubble breaker game found on many cell phones as well as an example here:<a href="http://www.kongregate.com/games/Sevas/bubble-breaker-game" rel="nofollow">Bubble Break Game</a></p>
<ul>
<li>The random (N,M,C) board consists N rows x M columns with C colors</li>
<li>The goal is to get the highest score by picking the sequence of bubble groups that ultimately leads to the highest score </li>
<li>A bubble group is 2 or more bubbles of the same color that are adjacent to each other in either x or y direction. Diagonals do not count </li>
<li>When a group is picked, the bubbles disappear, any holes are filled with bubbles from above first, ie shift down, then any holes are filled by shifting right</li>
<li>A bubble group score = n * (n - 1) where n is the number of bubbles in the bubble group</li>
</ul>
<p>The first algorithm is a simple exhaustive recursive algorithm which explores going through the board row by row and column by column picking bubble groups. Once the bubble group is picked, we create a new board and try to solve that board, recursively descending down</p>
<p>Some of the ideas I am using include normalized memoization. Once a board is solved we store the board and the best score in a memoization table. </p>
<p>I create a <a href="http://pastebin.com/f4ca00800" rel="nofollow">prototype in python</a> which shows a (2,15,5) board takes 8859 boards to solve in about 3 seconds. A (3,15,5) board takes 12,384,726 boards in 50 minutes on a server. The solver rate is ~3k-4k boards/sec and gradually decreases as the memoization search takes longer. Memoization table grows to 5,692,482 boards, and hits 6,713,566 times.</p>
<p>What other approaches could yield high scores besides the exhaustive search?</p>
<p>I don't seen any obvious way to divide and conquer. But trending towards larger and larger bubbles groups seems to be one approach</p>
<p>Thanks to David Locke for posting the paper link which talks above a window solver which uses a constant-depth lookahead heuristic. </p>
| 4 | 2009-10-08T23:29:18Z | 1,542,050 | <p>You can translate this problem into problem of searching shortest path on graph. <a href="http://en.wikipedia.org/wiki/Shortest%5Fpath%5Fproblem" rel="nofollow">http://en.wikipedia.org/wiki/Shortest%5Fpath%5Fproblem</a></p>
<p>I would try whit A* and heuristics would include number of islands.</p>
| 1 | 2009-10-09T06:09:15Z | [
"python",
"algorithm",
"language-agnostic"
] |
Bubble Breaker Game Solver better than greedy? | 1,541,101 | <p>For a mental exercise I decided to try and solve the bubble breaker game found on many cell phones as well as an example here:<a href="http://www.kongregate.com/games/Sevas/bubble-breaker-game" rel="nofollow">Bubble Break Game</a></p>
<ul>
<li>The random (N,M,C) board consists N rows x M columns with C colors</li>
<li>The goal is to get the highest score by picking the sequence of bubble groups that ultimately leads to the highest score </li>
<li>A bubble group is 2 or more bubbles of the same color that are adjacent to each other in either x or y direction. Diagonals do not count </li>
<li>When a group is picked, the bubbles disappear, any holes are filled with bubbles from above first, ie shift down, then any holes are filled by shifting right</li>
<li>A bubble group score = n * (n - 1) where n is the number of bubbles in the bubble group</li>
</ul>
<p>The first algorithm is a simple exhaustive recursive algorithm which explores going through the board row by row and column by column picking bubble groups. Once the bubble group is picked, we create a new board and try to solve that board, recursively descending down</p>
<p>Some of the ideas I am using include normalized memoization. Once a board is solved we store the board and the best score in a memoization table. </p>
<p>I create a <a href="http://pastebin.com/f4ca00800" rel="nofollow">prototype in python</a> which shows a (2,15,5) board takes 8859 boards to solve in about 3 seconds. A (3,15,5) board takes 12,384,726 boards in 50 minutes on a server. The solver rate is ~3k-4k boards/sec and gradually decreases as the memoization search takes longer. Memoization table grows to 5,692,482 boards, and hits 6,713,566 times.</p>
<p>What other approaches could yield high scores besides the exhaustive search?</p>
<p>I don't seen any obvious way to divide and conquer. But trending towards larger and larger bubbles groups seems to be one approach</p>
<p>Thanks to David Locke for posting the paper link which talks above a window solver which uses a constant-depth lookahead heuristic. </p>
| 4 | 2009-10-08T23:29:18Z | 1,542,558 | <p>In my chess program I use some ideas which could probably adapted to this problem.</p>
<ul>
<li><p>Move Ordering. First find all
possible moves, store them in a list,
and sort them according to some
heuristic. The "better" ones first,
the "bad" ones last. For example,
this could be a function of the size
of the group (prefer medium sized
groups), or the number of adjacent
colors, groups, etc.</p></li>
<li><p>Iterative Deepening. Instead of
running a pure depth-first search,
cut of the search after a certain
deep and use some heuristic to assess
the result. Now research the tree
with "better" moves first.</p></li>
<li><p>Pruning. Don't search moves which
seems "obviously" bad, according to
some, again, heuristic. This involves
the risk that you won't find the
optimal solution anymore, but
depending on your heuristics you will
very likely find it much earlier.</p></li>
<li><p>Hash Tables. No need to store every
board you come accross, just remember
a certain number and overwrite older
ones.</p></li>
</ul>
| 1 | 2009-10-09T08:27:33Z | [
"python",
"algorithm",
"language-agnostic"
] |
Bubble Breaker Game Solver better than greedy? | 1,541,101 | <p>For a mental exercise I decided to try and solve the bubble breaker game found on many cell phones as well as an example here:<a href="http://www.kongregate.com/games/Sevas/bubble-breaker-game" rel="nofollow">Bubble Break Game</a></p>
<ul>
<li>The random (N,M,C) board consists N rows x M columns with C colors</li>
<li>The goal is to get the highest score by picking the sequence of bubble groups that ultimately leads to the highest score </li>
<li>A bubble group is 2 or more bubbles of the same color that are adjacent to each other in either x or y direction. Diagonals do not count </li>
<li>When a group is picked, the bubbles disappear, any holes are filled with bubbles from above first, ie shift down, then any holes are filled by shifting right</li>
<li>A bubble group score = n * (n - 1) where n is the number of bubbles in the bubble group</li>
</ul>
<p>The first algorithm is a simple exhaustive recursive algorithm which explores going through the board row by row and column by column picking bubble groups. Once the bubble group is picked, we create a new board and try to solve that board, recursively descending down</p>
<p>Some of the ideas I am using include normalized memoization. Once a board is solved we store the board and the best score in a memoization table. </p>
<p>I create a <a href="http://pastebin.com/f4ca00800" rel="nofollow">prototype in python</a> which shows a (2,15,5) board takes 8859 boards to solve in about 3 seconds. A (3,15,5) board takes 12,384,726 boards in 50 minutes on a server. The solver rate is ~3k-4k boards/sec and gradually decreases as the memoization search takes longer. Memoization table grows to 5,692,482 boards, and hits 6,713,566 times.</p>
<p>What other approaches could yield high scores besides the exhaustive search?</p>
<p>I don't seen any obvious way to divide and conquer. But trending towards larger and larger bubbles groups seems to be one approach</p>
<p>Thanks to David Locke for posting the paper link which talks above a window solver which uses a constant-depth lookahead heuristic. </p>
| 4 | 2009-10-08T23:29:18Z | 3,044,739 | <p>I'm almost finished writing my version of the "solver" in Java. It does both exhaustive search, which takes fricking ages for larger board sizes, and a directed search based on a "pool" of possible paths, which is pruned after every generation, and a fitness function used to prune the pool. I'm just trying to tune the fitness function now...</p>
<p>Update - this is now available at <a href="http://bubblesolver.sourceforge.net/" rel="nofollow">http://bubblesolver.sourceforge.net/</a></p>
| 1 | 2010-06-15T11:38:38Z | [
"python",
"algorithm",
"language-agnostic"
] |
Difference between GET and FILTER in Django model layer | 1,541,249 | <p>What is the difference, please explain them in laymen's terms with examples. Thanks!</p>
| 18 | 2009-10-09T00:21:12Z | 1,541,322 | <p>I don't know if you really need an example, it's quite easy:</p>
<ul>
<li>if you know it's one object that matches your query, use get. It will fail if it's more than one.</li>
<li>otherwise use filter, which gives you a list of objects.</li>
</ul>
<p>To be more precise:</p>
<ul>
<li><code>MyTable.objects.get(id=x).whatever</code> gives you the <code>whatever</code> property of your object</li>
<li><code>MyTable.objects.filter(somecolumn=x)</code> is not only usable as a list, but you can also query it again, something like <code>MyTable.objects.filter(somecolumn=x).order_by('date')</code>. </li>
<li>The reason is that it's not actually a list, but a query object. You can iterate through it like through a list: <code>for obj in MyTable.objects.filter(somecolumn=x)</code></li>
</ul>
| 32 | 2009-10-09T00:50:56Z | [
"python",
"django"
] |
Why is subprocess.Popen not waiting until the child process terminates? | 1,541,273 | <p>I'm having a problem with Python's subprocess.Popen method. </p>
<p>Here's a test script which demonstrates the problem. It's being run on a Linux box.</p>
<pre><code>#!/usr/bin/env python
import subprocess
import time
def run(cmd):
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
return p
### START MAIN
# copy some rows from a source table to a destination table
# note that the destination table is empty when this script is run
cmd = 'mysql -u ve --skip-column-names --batch --execute="insert into destination (select * from source limit 100000)" test'
run(cmd)
# check to see how many rows exist in the destination table
cmd = 'mysql -u ve --skip-column-names --batch --execute="select count(*) from destination" test'
process = run(cmd)
count = (int(process.communicate()[0][:-1]))
# if subprocess.Popen() waited for the child to terminate than count should be
# greater than 0
if count > 0:
print "success: " + str(count)
else:
print "failure: " + str(count)
time.sleep(5)
# find out how many rows exists in the destination table after sleeping
process = run(cmd)
count = (int(process.communicate()[0][:-1]))
print "after sleeping the count is " + str(count)
</code></pre>
<p>Usually the output from this script is:</p>
<pre><code>success: 100000
</code></pre>
<p>but sometimes it's</p>
<pre><code>failure: 0
after sleeping the count is 100000
</code></pre>
<p>Note that in the failure case, the select immediately after the insert shows 0 rows but after sleeping for 5 seconds a second select correctly shows a row count of 100000. My conclusion is that one of the following is true:</p>
<ol>
<li>subprocess.Popen is not waiting for the child thread to terminate - This seems to contradict the documentation</li>
<li>the mysql insert is not atomic - my understanding of mysql seems to indicate insert is atomic</li>
<li>the select is not seeing the correct row count right away - according to a friend who knows mysql better than I do this should not happen either</li>
</ol>
<p>What am I missing?</p>
<p>FYI, I'm aware that this is a hacky way of interacting with mysql from Python and MySQLdb would likely not have this problem but I'm curious as to why this method does not work.</p>
| 5 | 2009-10-09T00:30:31Z | 1,541,355 | <p><code>subprocess.Popen</code>, when instantiated, runs the program. It does not, however, wait for it -- it fires it off in the background as if you'd typed <code>cmd &</code> in a shell. So, in the code above, you've essentially defined a race condition -- if the inserts can finish in time, it will appear normal, but if not you get the unexpected output. You are not waiting for your first <code>run()</code>'d PID to finish, you are simply returning its <code>Popen</code> instance and continuing.</p>
<p>I'm not sure how this behavior contradicts the documentation, because there's some very clear methods on Popen that seem to indicate it is not waited for, like:</p>
<pre><code>Popen.wait()
Wait for child process to terminate. Set and return returncode attribute.
</code></pre>
<p>I do agree, however, that the documentation for this module could be improved.</p>
<p>To wait for the program to finish, I'd recommend using <code>subprocess</code>'s convenience method, <code>subprocess.call</code>, or using <code>communicate</code> on a <code>Popen</code> object (for the case when you need stdout). You are already doing this for your second call.</p>
<pre><code>### START MAIN
# copy some rows from a source table to a destination table
# note that the destination table is empty when this script is run
cmd = 'mysql -u ve --skip-column-names --batch --execute="insert into destination (select * from source limit 100000)" test'
subprocess.call(cmd)
# check to see how many rows exist in the destination table
cmd = 'mysql -u ve --skip-column-names --batch --execute="select count(*) from destination" test'
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
try: count = (int(process.communicate()[0][:-1]))
except: count = 0
</code></pre>
<p>Additionally, in most cases, you do not need to run the command in a shell. This is one of those cases, but you'll have to rewrite your command like a sequence. Doing it that way also allows you to avoid traditional shell injection and worry less about quoting, like so:</p>
<pre><code>prog = ["mysql", "-u", "ve", "--execute", 'insert into foo values ("snargle", 2)']
subprocess.call(prog)
</code></pre>
<p>This will even work, and will not inject as you'd expect:</p>
<pre><code>prog = ["printf", "%s", "<", "/etc/passwd"]
subprocess.call(prog)
</code></pre>
<p>Try it interactively. You avoid the possibilities of shell injection, particularly if you're accepting user input. I suspect you're using the less-awesome string method of communicating with subprocess because you ran into trouble getting the sequences to work :^)</p>
| 19 | 2009-10-09T01:05:31Z | [
"python",
"mysql"
] |
Why is subprocess.Popen not waiting until the child process terminates? | 1,541,273 | <p>I'm having a problem with Python's subprocess.Popen method. </p>
<p>Here's a test script which demonstrates the problem. It's being run on a Linux box.</p>
<pre><code>#!/usr/bin/env python
import subprocess
import time
def run(cmd):
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
return p
### START MAIN
# copy some rows from a source table to a destination table
# note that the destination table is empty when this script is run
cmd = 'mysql -u ve --skip-column-names --batch --execute="insert into destination (select * from source limit 100000)" test'
run(cmd)
# check to see how many rows exist in the destination table
cmd = 'mysql -u ve --skip-column-names --batch --execute="select count(*) from destination" test'
process = run(cmd)
count = (int(process.communicate()[0][:-1]))
# if subprocess.Popen() waited for the child to terminate than count should be
# greater than 0
if count > 0:
print "success: " + str(count)
else:
print "failure: " + str(count)
time.sleep(5)
# find out how many rows exists in the destination table after sleeping
process = run(cmd)
count = (int(process.communicate()[0][:-1]))
print "after sleeping the count is " + str(count)
</code></pre>
<p>Usually the output from this script is:</p>
<pre><code>success: 100000
</code></pre>
<p>but sometimes it's</p>
<pre><code>failure: 0
after sleeping the count is 100000
</code></pre>
<p>Note that in the failure case, the select immediately after the insert shows 0 rows but after sleeping for 5 seconds a second select correctly shows a row count of 100000. My conclusion is that one of the following is true:</p>
<ol>
<li>subprocess.Popen is not waiting for the child thread to terminate - This seems to contradict the documentation</li>
<li>the mysql insert is not atomic - my understanding of mysql seems to indicate insert is atomic</li>
<li>the select is not seeing the correct row count right away - according to a friend who knows mysql better than I do this should not happen either</li>
</ol>
<p>What am I missing?</p>
<p>FYI, I'm aware that this is a hacky way of interacting with mysql from Python and MySQLdb would likely not have this problem but I'm curious as to why this method does not work.</p>
| 5 | 2009-10-09T00:30:31Z | 1,541,701 | <p>Dude, why did you think <code>subprocess.Popen</code> returned an object with a <a href="http://docs.python.org/library/subprocess.html?highlight=subprocess.popen#subprocess.Popen.wait"><code>wait</code></a> method, unless it was because the waiting was <strong>NOT</strong> implicit, intrinsic, immediate, and inevitable, as you appear to surmise...?! The most common reason to spawn a subprocess is NOT to immediately wait for it to finish, but rather to let it proceed (e.g. on another core, or at worst by time-slicing -- that's the operating system's -- and hardware's -- lookout) at the same time as the parent process continues; when the parent process needs to wait for the subprocess to be finished, it will obviously call <code>wait</code> on the object returned by the original <code>subprocess.Process</code> call.</p>
| 6 | 2009-10-09T03:51:15Z | [
"python",
"mysql"
] |
Why is subprocess.Popen not waiting until the child process terminates? | 1,541,273 | <p>I'm having a problem with Python's subprocess.Popen method. </p>
<p>Here's a test script which demonstrates the problem. It's being run on a Linux box.</p>
<pre><code>#!/usr/bin/env python
import subprocess
import time
def run(cmd):
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
return p
### START MAIN
# copy some rows from a source table to a destination table
# note that the destination table is empty when this script is run
cmd = 'mysql -u ve --skip-column-names --batch --execute="insert into destination (select * from source limit 100000)" test'
run(cmd)
# check to see how many rows exist in the destination table
cmd = 'mysql -u ve --skip-column-names --batch --execute="select count(*) from destination" test'
process = run(cmd)
count = (int(process.communicate()[0][:-1]))
# if subprocess.Popen() waited for the child to terminate than count should be
# greater than 0
if count > 0:
print "success: " + str(count)
else:
print "failure: " + str(count)
time.sleep(5)
# find out how many rows exists in the destination table after sleeping
process = run(cmd)
count = (int(process.communicate()[0][:-1]))
print "after sleeping the count is " + str(count)
</code></pre>
<p>Usually the output from this script is:</p>
<pre><code>success: 100000
</code></pre>
<p>but sometimes it's</p>
<pre><code>failure: 0
after sleeping the count is 100000
</code></pre>
<p>Note that in the failure case, the select immediately after the insert shows 0 rows but after sleeping for 5 seconds a second select correctly shows a row count of 100000. My conclusion is that one of the following is true:</p>
<ol>
<li>subprocess.Popen is not waiting for the child thread to terminate - This seems to contradict the documentation</li>
<li>the mysql insert is not atomic - my understanding of mysql seems to indicate insert is atomic</li>
<li>the select is not seeing the correct row count right away - according to a friend who knows mysql better than I do this should not happen either</li>
</ol>
<p>What am I missing?</p>
<p>FYI, I'm aware that this is a hacky way of interacting with mysql from Python and MySQLdb would likely not have this problem but I'm curious as to why this method does not work.</p>
| 5 | 2009-10-09T00:30:31Z | 1,541,709 | <p>If you don't absolutely need to use subprocess and popen, it's usually simpler to use <code>os.system</code>. For example, for quick scripts I often do something like this:</p>
<pre><code>import os
run = os.system #convenience alias
result = run('mysql -u ve --execute="select * from wherever" test')
</code></pre>
<p>Unlike popen, <code>os.system</code> DOES wait for your process to return before moving on to the next stage of your script.</p>
<p>More info on it in the docs: <a href="http://docs.python.org/library/os.html#os.system">http://docs.python.org/library/os.html#os.system</a></p>
| 7 | 2009-10-09T03:54:09Z | [
"python",
"mysql"
] |
python regular expression to parse div tags | 1,541,281 | <p>a question about python regular expression.</p>
<p>I would like to match a div block like </p>
<pre><code><div class="leftTail"><ul class="hotnews">any news stuff</ul></div>
</code></pre>
<p>I was thinking a pattern like</p>
<pre><code>p = re.compile(r'<div\s+class=\"leftTail\">[^(div)]+</div>')
</code></pre>
<p>but it seems not working properly</p>
<p>another pattern</p>
<pre><code>p = re.compile(r'<div\s+class=\"leftTail\">[\W|\w]+</div>')
</code></pre>
<p>i got much more than i think, it gets all the stuff until the last tag in the file.</p>
<p>Thanks for any help</p>
| 1 | 2009-10-09T00:32:25Z | 1,541,283 | <p>Don't use regular expressions to parse XML or HTML. You'll never be able to get it to work correctly for nested divs.</p>
| 4 | 2009-10-09T00:35:04Z | [
"python",
"regex"
] |
python regular expression to parse div tags | 1,541,281 | <p>a question about python regular expression.</p>
<p>I would like to match a div block like </p>
<pre><code><div class="leftTail"><ul class="hotnews">any news stuff</ul></div>
</code></pre>
<p>I was thinking a pattern like</p>
<pre><code>p = re.compile(r'<div\s+class=\"leftTail\">[^(div)]+</div>')
</code></pre>
<p>but it seems not working properly</p>
<p>another pattern</p>
<pre><code>p = re.compile(r'<div\s+class=\"leftTail\">[\W|\w]+</div>')
</code></pre>
<p>i got much more than i think, it gets all the stuff until the last tag in the file.</p>
<p>Thanks for any help</p>
| 1 | 2009-10-09T00:32:25Z | 1,541,288 | <p>You might want to consider graduating to an actual HTML parser. I suggest you give <a href="http://www.crummy.com/software/BeautifulSoup/">Beautiful Soup</a> a try. There are many crazy ways for HTML to be formatted, and the regular expressions may not work correctly all the time, even if you write them correctly.</p>
| 12 | 2009-10-09T00:36:04Z | [
"python",
"regex"
] |
python regular expression to parse div tags | 1,541,281 | <p>a question about python regular expression.</p>
<p>I would like to match a div block like </p>
<pre><code><div class="leftTail"><ul class="hotnews">any news stuff</ul></div>
</code></pre>
<p>I was thinking a pattern like</p>
<pre><code>p = re.compile(r'<div\s+class=\"leftTail\">[^(div)]+</div>')
</code></pre>
<p>but it seems not working properly</p>
<p>another pattern</p>
<pre><code>p = re.compile(r'<div\s+class=\"leftTail\">[\W|\w]+</div>')
</code></pre>
<p>i got much more than i think, it gets all the stuff until the last tag in the file.</p>
<p>Thanks for any help</p>
| 1 | 2009-10-09T00:32:25Z | 1,541,302 | <p>try this:</p>
<pre><code>p = re.compile(r'<div\s+class=\"leftTail\">.*?</div>')
</code></pre>
| 4 | 2009-10-09T00:41:39Z | [
"python",
"regex"
] |
Django SELECT statement, Order by | 1,541,376 | <p>Suppose I have 2 models. </p>
<p>The 2nd model has a one-to-one relationship with the first model. </p>
<p>I'd like to select information from the first model, but ORDER BY the 2nd model. How can I do that?</p>
<pre><code>class Content(models.Model):
link = models.TextField(blank=True)
title = models.TextField(blank=True)
is_channel = models.BooleanField(default=0, db_index=True)
class Score(models.Model):
content = models.OneToOneField(Content, primary_key=True)
counter = models.IntegerField(default=0)
</code></pre>
| 4 | 2009-10-09T01:15:36Z | 1,541,390 | <p>I think you can do:</p>
<pre><code>Content.objects.filter(...).order_by('score__counter')
</code></pre>
<p>More generally, when models have a relationship, you can select, order, and filter by fields on the "other" model using the <code>relationshipName__fieldName</code> pseudo attribute of the model which you are selecting on.</p>
| 7 | 2009-10-09T01:23:17Z | [
"python",
"django"
] |
Why Does List Argument in Python Behave Like ByRef? | 1,541,620 | <p>This may be for most languages in general, but I'm not sure. I'm a beginner at Python and have always worked on copies of lists in C# and VB. But in Python whenever I pass a list as an argument and enumerate through using a "for i in range," and then change the value of the list argument, the input values actually changes the original list. I thought Python was supposed to pass arguments by value by default so that once the function is finished I still have the original values from before I called the function. What am I missing? Thanks!</p>
| 1 | 2009-10-09T03:14:43Z | 1,541,625 | <p>Python does pass arguments by value but the value you are receiving is a copy of the reference (incidentally this is the exact same way that C#, VB.NET, and Java behave as well).</p>
<p>This is the important thing to remember:</p>
<blockquote>
<p><em>Objects are not passed by reference - object references are passed by value</em>.</p>
</blockquote>
<p>Since you have a copy of the reference, any operation on what that reference points to will be just as if you were holding the original reference itself.</p>
| 8 | 2009-10-09T03:17:09Z | [
"python",
"reference",
"argument-passing",
"object-reference"
] |
Why Does List Argument in Python Behave Like ByRef? | 1,541,620 | <p>This may be for most languages in general, but I'm not sure. I'm a beginner at Python and have always worked on copies of lists in C# and VB. But in Python whenever I pass a list as an argument and enumerate through using a "for i in range," and then change the value of the list argument, the input values actually changes the original list. I thought Python was supposed to pass arguments by value by default so that once the function is finished I still have the original values from before I called the function. What am I missing? Thanks!</p>
| 1 | 2009-10-09T03:14:43Z | 1,541,645 | <p>To add to Andrew's answer, you need to explicitly make a copy of a list if you want to retain the original. You can do this using the <code>copy</code> module, or just do something like </p>
<pre><code>a = [1,2]
b = list(a)
</code></pre>
<p>Since copying objects usually implies a performance hit, I find it helpful to explicitly use the copy module in my larger projects. That way, I can easily find all the places where I'm going to use a bunch more memory.</p>
| 0 | 2009-10-09T03:26:44Z | [
"python",
"reference",
"argument-passing",
"object-reference"
] |
Why Does List Argument in Python Behave Like ByRef? | 1,541,620 | <p>This may be for most languages in general, but I'm not sure. I'm a beginner at Python and have always worked on copies of lists in C# and VB. But in Python whenever I pass a list as an argument and enumerate through using a "for i in range," and then change the value of the list argument, the input values actually changes the original list. I thought Python was supposed to pass arguments by value by default so that once the function is finished I still have the original values from before I called the function. What am I missing? Thanks!</p>
| 1 | 2009-10-09T03:14:43Z | 1,541,681 | <p>Python -- just like Java does for anything but primitive scalars, and like C# and VB.NET do for the default kind parameters as opposed to boxed types and out / ref parms -- passes "by object reference" (search for that phrase <a href="http://en.wikipedia.org/wiki/Python%5Fsyntax%5Fand%5Fsemantics" rel="nofollow">here</a> -- it's how Guido, Python's architect and creator, uses to explain this argument-passing concept).</p>
<p>Every name is a reference to some object; passing a name (or any other expression) as an argument is just creating yet another reference to the same object (which the function body can access through the parameter's name). ((There's no such thing as "a reference to a name": there are <em>names</em>, which are one kind of reference to objects, and object -- period)).</p>
<p>When you're passing a mutable object, i.e. one which has mutating methods (like for example a list), the called function can mutate the object by calling, directly or indirectly, its mutating methods. ((By "indirectly", I mean "through operators" -- for example:</p>
<pre><code>somelist[len(somelist):] = [whatever]
</code></pre>
<p>is exactly identical to <code>somelist.append(whatever)</code>.))</p>
<p>When you want to pass a list into a function, but do <strong>not</strong> want the function to be able to mutate that list in any way, you must pass a <em>copy</em> of the list instead of the original -- just like in Java, C#, VB.NET.</p>
<p>Be <em>very</em> clear about the distinction between <strong>rebinding a name</strong> and <strong>mutating an object</strong>. Rebinding the name ("barename", that is -- qualified-names are different;-) <strong>only</strong> affects that <strong>name</strong> -- <strong>NOT</strong> any object whatsoever. For example:</p>
<pre><code>def f1(alist):
alist = [23]
def f2(alist):
alist[:] = [23]
</code></pre>
<p>Can you spot the difference between these two functions? One is rebinding the <strong>barename</strong> <code>alist</code> -- without any effect whatsoever on anything. The other is mutating (altering, changing, ...) the list object it received as its argument -- by setting its content to be a one-item list with an int as its sole item. <strong>Completely, utterly</strong> different things!!!</p>
| 4 | 2009-10-09T03:44:07Z | [
"python",
"reference",
"argument-passing",
"object-reference"
] |
A .net wrapper for Google App Engine? | 1,541,722 | <p>Does anyone know of a .net wrapper around either python or java Google App Engine services?</p>
<p>Any help appreciated // :)</p>
| 3 | 2009-10-09T03:59:11Z | 1,541,765 | <p>I don't believe this is even <em>conceivable</em> (if I understand what you're asking about): App Engine will run code on a Python virtual machine or a Java one, never on a .NET one, so where would this "wrapper" <em>run</em>? If your need is for .NET "in the cloud", consider <a href="http://www.microsoft.com/azure/default.mspx" rel="nofollow">Azure</a> (you could run .NET on Amazon Web Services, I guess, given AWS's flexibility -- but if you're married to MS's platform anyway, why not use <em>their</em> cloud...?).</p>
| 3 | 2009-10-09T04:16:41Z | [
"java",
".net",
"python",
"web-services",
"google-app-engine"
] |
A .net wrapper for Google App Engine? | 1,541,722 | <p>Does anyone know of a .net wrapper around either python or java Google App Engine services?</p>
<p>Any help appreciated // :)</p>
| 3 | 2009-10-09T03:59:11Z | 1,542,102 | <p>I don't think it's impossible to run .net on GAE. At least, it's not impossible to run something that was generated from .net sources or interprets them at runtime. Just think about Ruby or Python, both work on the JVM (using JRuby and Jython). You'll probably have to look for something similar or try to cross-compile you .net code to Java class files.</p>
<p>Here is a related question: <a href="http://stackoverflow.com/questions/494389/why-doesnt-sun-do-a-c-to-java-byte-code-compiler">Why doesnât Sun do a C# to Java byte code compiler?</a>. Some people suggest using <a href="http://sourceforge.net/projects/jacil/" rel="nofollow">JaCIL</a> or <a href="http://jsc.sourceforge.net/" rel="nofollow">jsc</a>. I didn't try those myself, but I'd bet you'll have to get your hands dirty to get something to work.</p>
| 2 | 2009-10-09T06:26:20Z | [
"java",
".net",
"python",
"web-services",
"google-app-engine"
] |
A .net wrapper for Google App Engine? | 1,541,722 | <p>Does anyone know of a .net wrapper around either python or java Google App Engine services?</p>
<p>Any help appreciated // :)</p>
| 3 | 2009-10-09T03:59:11Z | 17,356,271 | <p>Python has a .NET alternative called IronPython. But I don't think it will work in GAE as it supports only pure python. I am also facing a similar problem trying to port a source written in C#.net into GAE compatible code. I'm going to work around it by re-inventing the spokes of the wheel (not the wheel itself) by re-doing the UI using SVG or some other method. Have you considered that? </p>
| 0 | 2013-06-28T02:24:35Z | [
"java",
".net",
"python",
"web-services",
"google-app-engine"
] |
Upgrade Python to 2.6 on Mac | 1,541,776 | <p>I'd like to upgrade the default python installation (2.5.1) supplied with OS X Leopard to the latest version. Please let me know how I can achieve this.</p>
<p>Thanks</p>
| 14 | 2009-10-09T04:24:03Z | 1,541,785 | <p>May I suggest you leave the "Default" be, and install Python in /usr/local/bin.</p>
<ol>
<li>Download python</li>
<li>Unzip it</li>
<li>./configure</li>
<li>make</li>
<li>sudo make install</li>
</ol>
<p>done.</p>
<p>Since /usr/local/bin comes before /usr/bin in the $PATH, you will invoke 2.6 when you type python, but the OS will remain stable...</p>
| 6 | 2009-10-09T04:28:09Z | [
"python",
"osx",
"installation",
"upgrade"
] |
Upgrade Python to 2.6 on Mac | 1,541,776 | <p>I'd like to upgrade the default python installation (2.5.1) supplied with OS X Leopard to the latest version. Please let me know how I can achieve this.</p>
<p>Thanks</p>
| 14 | 2009-10-09T04:24:03Z | 1,541,795 | <p>I believe there are a few options. The one I like is to install alternative UNIX software on my Macs using MacPorts, <a href="http://www.macports.org/" rel="nofollow">http://www.macports.org/</a> -- this way the new software is installed in a different directory and won't mess up anything depending on the apple-installed version, and macports also has a nice way of keeping their installed software up to date. I believe MacPorts helps take care of dependencies as well. </p>
| 0 | 2009-10-09T04:30:00Z | [
"python",
"osx",
"installation",
"upgrade"
] |
Upgrade Python to 2.6 on Mac | 1,541,776 | <p>I'd like to upgrade the default python installation (2.5.1) supplied with OS X Leopard to the latest version. Please let me know how I can achieve this.</p>
<p>Thanks</p>
| 14 | 2009-10-09T04:24:03Z | 1,541,806 | <p>You have a number of options</p>
<ul>
<li><p>Install with <a href="http://www.macports.org/">MacPorts</a> or <a href="http://www.finkproject.org/">Fink</a>, e.g.:</p>
<pre><code>sudo port install python2.6
</code></pre></li>
<li>Install from the disc image from <a href="http://python.org/ftp/python/2.6.3/python-2.6.3-macosx.dmg">python.org</a></li>
<li><p>Install from <a href="http://python.org/ftp/python/2.6.3/Python-2.6.3.tgz">source</a>:</p>
<pre><code>tar xzvf Python-2.6.3.tgz
cd Python-2.6.3
./configure && make && sudo make install
</code></pre></li>
</ul>
| 5 | 2009-10-09T04:32:15Z | [
"python",
"osx",
"installation",
"upgrade"
] |
Upgrade Python to 2.6 on Mac | 1,541,776 | <p>I'd like to upgrade the default python installation (2.5.1) supplied with OS X Leopard to the latest version. Please let me know how I can achieve this.</p>
<p>Thanks</p>
| 14 | 2009-10-09T04:24:03Z | 1,541,850 | <p>When an OS is distributed with some specific Python release and uses it for some OS functionality (as is the case with Mac OS X, as well as many Linux distros &c), you should <strong>not</strong> tamper in any way with the system-supplied Python (as in, "upgrading" it and the like): while Python strives for backwards compatibility within any major release (such as <code>2.*</code> or <code>3.*</code>, this can never be 100% guaranted; your OS supplied tested all functionality thoroughly with the specific Python version they distribute; if you manage to alter that version, "on your head be it" -- neither your OS supplier nor the PSF accepts any responsibility for whatever damage that might perhaps do to your system.</p>
<p>Rather, as other answers already suggested, install any other release you wish "besides" the system one -- why tamper with that crucial one, and risk breaking things, when installing others is so easy anyway?! On typical Mac OS X 10.5 machines (haven't upgraded any of my several macs to 10.6 yet), I have the Apple-supplied 2.5, a 2.4 on the side to support some old projects not worth the bother to upgrate, the latest 2.6 for new stuff, 3.1 as well to get the very newest -- they all live together in peace and quiet, I just type the release number explicitly, i.e. using <code>python2.6</code> at the prompt, when I want a specific release. What release gets used when at the shell prompt you just say <code>python</code> is up to you (I personally prefer that to mean "the system-supplied Python", but it's a matter of taste: by setting paths, or shell aliases, &c, you can make it mean whatever you wish).</p>
| 20 | 2009-10-09T04:48:25Z | [
"python",
"osx",
"installation",
"upgrade"
] |
Upgrade Python to 2.6 on Mac | 1,541,776 | <p>I'd like to upgrade the default python installation (2.5.1) supplied with OS X Leopard to the latest version. Please let me know how I can achieve this.</p>
<p>Thanks</p>
| 14 | 2009-10-09T04:24:03Z | 1,542,144 | <p>Don't upgrade.</p>
<ol>
<li>Install <a href="http://www.activestate.com/activepython/downloads" rel="nofollow">ActivePython</a> (which <a href="http://docs.activestate.com/activepython/2.6/faq.html#does-activepython-collide-with-other-python-distributions-on-mac-os-x" rel="nofollow">co-exists</a> with others). </li>
<li>Open Terminal</li>
<li>Type <code>python2.6</code></li>
</ol>
| 8 | 2009-10-09T06:35:57Z | [
"python",
"osx",
"installation",
"upgrade"
] |
Upgrade Python to 2.6 on Mac | 1,541,776 | <p>I'd like to upgrade the default python installation (2.5.1) supplied with OS X Leopard to the latest version. Please let me know how I can achieve this.</p>
<p>Thanks</p>
| 14 | 2009-10-09T04:24:03Z | 1,701,884 | <p>The best is to use <a href="http://www.macports.org/" rel="nofollow">macports</a> (just like Adam Rosenfield stated on this thread).</p>
<p>You can easily switch between Python versions using macports select mechanism:</p>
<p><code>$ sudo port select --set python pythonXY</code></p>
<p>To view the list of available Python versions you can use above and/or confirm which one you're using:</p>
<p><code>$ sudo port select --list python</code></p>
<p>To install a new Python version:</p>
<p><code>$ sudo port install pythonXY</code></p>
| 4 | 2009-11-09T15:47:00Z | [
"python",
"osx",
"installation",
"upgrade"
] |
Upgrade Python to 2.6 on Mac | 1,541,776 | <p>I'd like to upgrade the default python installation (2.5.1) supplied with OS X Leopard to the latest version. Please let me know how I can achieve this.</p>
<p>Thanks</p>
| 14 | 2009-10-09T04:24:03Z | 1,996,525 | <p>The standard <a href="http://python.org" rel="nofollow">http://python.org</a> install for Mac OSX will happily <em>coexist</em> with the "system python". If you let the installer change your paths, when you run python from a prompt in terminal, it will find the version at </p>
<pre><code> /Library/Frameworks/Python.framework/Versions/2.6/bin/python
</code></pre>
<p>However, this won't interfere with anything that OSX itself does with python, which correctly hardwires the path to the version that it installs.</p>
| 1 | 2010-01-03T22:09:58Z | [
"python",
"osx",
"installation",
"upgrade"
] |
Get window title with python? | 1,541,784 | <p>I'm trying to write a python program that checks every X seconds if the 'window title' for 'last.fm' (<a href="http://www.last.fm/download" rel="nofollow">http://www.last.fm/download</a>) changed, if it did (or it's the first time I run the program) it should use use the string captured from the window title to search for the song's lyrics and display them to the user. </p>
<p>I'm currently using KDE4 as my desktop environment and I just need to be 'pointed in the right direction' on how I can capture the string that belongs to the window title for last.fm client. </p>
<p>Thanks! </p>
| 4 | 2009-10-09T04:27:56Z | 1,542,447 | <p>I think by using a automation framework you may be able to achieve this as a subset.
e.g. try dogtail(<a href="https://fedorahosted.org/dogtail/" rel="nofollow">https://fedorahosted.org/dogtail/</a>), it can focus on windows by name, click on buttons by name, so in the src code you may be able to see how to get title.</p>
| 1 | 2009-10-09T07:58:25Z | [
"python",
"kde"
] |
Get window title with python? | 1,541,784 | <p>I'm trying to write a python program that checks every X seconds if the 'window title' for 'last.fm' (<a href="http://www.last.fm/download" rel="nofollow">http://www.last.fm/download</a>) changed, if it did (or it's the first time I run the program) it should use use the string captured from the window title to search for the song's lyrics and display them to the user. </p>
<p>I'm currently using KDE4 as my desktop environment and I just need to be 'pointed in the right direction' on how I can capture the string that belongs to the window title for last.fm client. </p>
<p>Thanks! </p>
| 4 | 2009-10-09T04:27:56Z | 1,543,090 | <p>Try using dcop and piloting kwin. You can probably list all the window titles.</p>
<p>See the following for an example on how to use dcop:
<a href="http://docs.kde.org/stable/en/kdegraphics/ksnapshot/dcop.html" rel="nofollow">http://docs.kde.org/stable/en/kdegraphics/ksnapshot/dcop.html</a></p>
| 0 | 2009-10-09T10:48:30Z | [
"python",
"kde"
] |
Get window title with python? | 1,541,784 | <p>I'm trying to write a python program that checks every X seconds if the 'window title' for 'last.fm' (<a href="http://www.last.fm/download" rel="nofollow">http://www.last.fm/download</a>) changed, if it did (or it's the first time I run the program) it should use use the string captured from the window title to search for the song's lyrics and display them to the user. </p>
<p>I'm currently using KDE4 as my desktop environment and I just need to be 'pointed in the right direction' on how I can capture the string that belongs to the window title for last.fm client. </p>
<p>Thanks! </p>
| 4 | 2009-10-09T04:27:56Z | 1,543,307 | <p>Have a look at X11 utilities, specifically <code>xlsclients</code> and <code>xprop</code>.</p>
<p>As an example, this is the shell commands I used to get info about my firefox
window:</p>
<pre><code>id_=$(xlsclients -al|grep "Command: firefox-bin" -A1 -B4|head -n1|cut -d ' ' -f 2|tr -d ':')
xprop -id "$_id"
</code></pre>
<p>Output:</p>
<pre><code>SM_CLIENT_ID(STRING) = "1181f048b9000125508490000000037360008"
WM_CLASS(STRING) = "firefox-bin", "Firefox-bin"
WM_COMMAND(STRING) = { "firefox-bin" }
WM_CLIENT_LEADER(WINDOW): window id # 0x0
_NET_WM_PID(CARDINAL) = 4265
WM_LOCALE_NAME(STRING) = "no_NO"
WM_CLIENT_MACHINE(STRING) = "gnom.ifi.uio.no"
WM_NORMAL_HINTS(WM_SIZE_HINTS):
program specified size: 10 by 10
WM_PROTOCOLS(ATOM): protocols WM_DELETE_WINDOW, WM_TAKE_FOCUS, _NET_WM_PING
WM_ICON_NAME(STRING) = "firefox-bin"
_NET_WM_ICON_NAME(UTF8_STRING) = 0x66, 0x69, 0x72, 0x65, 0x66, 0x6f, 0x78, 0x2d, 0x62, 0x69, 0x6e
WM_NAME(STRING) = "Firefox"
_NET_WM_NAME(UTF8_STRING) = 0x46, 0x69, 0x72, 0x65, 0x66, 0x6f, 0x78
</code></pre>
| 0 | 2009-10-09T11:46:30Z | [
"python",
"kde"
] |
Get window title with python? | 1,541,784 | <p>I'm trying to write a python program that checks every X seconds if the 'window title' for 'last.fm' (<a href="http://www.last.fm/download" rel="nofollow">http://www.last.fm/download</a>) changed, if it did (or it's the first time I run the program) it should use use the string captured from the window title to search for the song's lyrics and display them to the user. </p>
<p>I'm currently using KDE4 as my desktop environment and I just need to be 'pointed in the right direction' on how I can capture the string that belongs to the window title for last.fm client. </p>
<p>Thanks! </p>
| 4 | 2009-10-09T04:27:56Z | 1,543,979 | <p>You can use the <code>wmctrl</code> utility through the <code>subprocess</code> module. You can type <code>wmctrl -l</code> into a terminal and see the output you can get from it.</p>
| 3 | 2009-10-09T14:03:13Z | [
"python",
"kde"
] |
Get window title with python? | 1,541,784 | <p>I'm trying to write a python program that checks every X seconds if the 'window title' for 'last.fm' (<a href="http://www.last.fm/download" rel="nofollow">http://www.last.fm/download</a>) changed, if it did (or it's the first time I run the program) it should use use the string captured from the window title to search for the song's lyrics and display them to the user. </p>
<p>I'm currently using KDE4 as my desktop environment and I just need to be 'pointed in the right direction' on how I can capture the string that belongs to the window title for last.fm client. </p>
<p>Thanks! </p>
| 4 | 2009-10-09T04:27:56Z | 1,893,129 | <p>another answer maybe to check if the application publishes the song change to DBus. if it does then you can just listen for the event and act on that. </p>
| 0 | 2009-12-12T11:31:51Z | [
"python",
"kde"
] |
Check for duplicates in a flat list | 1,541,797 | <p>example 1:</p>
<p><code>['one', 'two', 'one']</code> should return True.</p>
<p>example 2:</p>
<p><code>['one', 'two', 'three']</code> should return False.</p>
| 67 | 2009-10-09T04:30:32Z | 1,541,820 | <p>Recommended for <em>short</em> lists only:</p>
<pre><code>any(thelist.count(x) > 1 for x in thelist)
</code></pre>
<p>Do <strong>not</strong> use on a long list -- it can take time proportional to the <strong>square</strong> of the number of items in the list!</p>
<p>For longer lists with hashable items (strings, numbers, &c):</p>
<pre><code>def anydup(thelist):
seen = set()
for x in thelist:
if x in seen: return True
seen.add(x)
return False
</code></pre>
<p>If your items are not hashable (sublists, dicts, etc) it gets hairier, though it may still be possible to get O(N logN) if they're at least comparable. But you need to know or test the characteristics of the items (hashable or not, comparable or not) to get the best performance you can -- O(N) for hashables, O(N log N) for non-hashable comparables, otherwise it's down to O(N squared) and there's nothing one can do about it:-(.</p>
| 30 | 2009-10-09T04:36:37Z | [
"python",
"string",
"list",
"duplicates"
] |
Check for duplicates in a flat list | 1,541,797 | <p>example 1:</p>
<p><code>['one', 'two', 'one']</code> should return True.</p>
<p>example 2:</p>
<p><code>['one', 'two', 'three']</code> should return False.</p>
| 67 | 2009-10-09T04:30:32Z | 1,541,827 | <p>Use <code>set()</code> to remove duplicates if all values are <em>hashable</em>:</p>
<pre><code>>>> your_list = ['one', 'two', 'one']
>>> len(your_list) != len(set(your_list))
True
</code></pre>
| 157 | 2009-10-09T04:38:45Z | [
"python",
"string",
"list",
"duplicates"
] |
Check for duplicates in a flat list | 1,541,797 | <p>example 1:</p>
<p><code>['one', 'two', 'one']</code> should return True.</p>
<p>example 2:</p>
<p><code>['one', 'two', 'three']</code> should return False.</p>
| 67 | 2009-10-09T04:30:32Z | 6,250,875 | <p>If you are fond of functional programming style, here is a useful function, self-documented and tested code using <a href="http://docs.python.org/library/doctest.html" rel="nofollow">doctest</a>.</p>
<pre><code>def decompose(a_list):
"""Turns a list into a set of all elements and a set of duplicated elements.
Returns a pair of sets. The first one contains elements
that are found at least once in the list. The second one
contains elements that appear more than once.
>>> decompose([1,2,3,5,3,2,6])
(set([1, 2, 3, 5, 6]), set([2, 3]))
"""
return reduce(
lambda (u, d), o : (u.union([o]), d.union(u.intersection([o]))),
a_list,
(set(), set()))
if __name__ == "__main__":
import doctest
doctest.testmod()
</code></pre>
<p>From there you can test unicity by checking whether the second element of the returned pair is empty:</p>
<pre><code>def is_set(l):
"""Test if there is no duplicate element in l.
>>> is_set([1,2,3])
True
>>> is_set([1,2,1])
False
>>> is_set([])
True
"""
return not decompose(l)[1]
</code></pre>
<p>Note that this is not efficient since you are explicitly constructing the decomposition. But along the line of using reduce, you can come up to something equivalent (but slightly less efficient) to answer 5:</p>
<pre><code>def is_set(l):
try:
def func(s, o):
if o in s:
raise Exception
return s.union([o])
reduce(func, l, set())
return True
except:
return False
</code></pre>
| 5 | 2011-06-06T10:44:28Z | [
"python",
"string",
"list",
"duplicates"
] |
Check for duplicates in a flat list | 1,541,797 | <p>example 1:</p>
<p><code>['one', 'two', 'one']</code> should return True.</p>
<p>example 2:</p>
<p><code>['one', 'two', 'three']</code> should return False.</p>
| 67 | 2009-10-09T04:30:32Z | 18,515,820 | <p>This is old, but the answers here led me to a slightly different solution. If you are up for abusing comprehensions, you can get short-circuiting this way.</p>
<pre><code>xs = [1, 2, 1]
s = set()
any(x in s or s.add(x) for x in xs)
# You can use a similar approach to actually retrieve the duplicates.
s = set()
duplicates = set(x for x in xs if x in s or s.add(x))
</code></pre>
| 3 | 2013-08-29T16:03:06Z | [
"python",
"string",
"list",
"duplicates"
] |
Check for duplicates in a flat list | 1,541,797 | <p>example 1:</p>
<p><code>['one', 'two', 'one']</code> should return True.</p>
<p>example 2:</p>
<p><code>['one', 'two', 'three']</code> should return False.</p>
| 67 | 2009-10-09T04:30:32Z | 31,569,431 | <p>I recently answered a related question to <a href="http://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-python-list/31439372#31439372">establish all the duplicates</a> in a list, using a generator. It has the advantage that if used just to establish 'if there is a duplicate' then you just need to get the first item and the rest can be ignored, which is the ultimate shortcut.</p>
<p>This is an interesting set based approach I adapted straight from <a href="http://stackoverflow.com/users/1025391/moooeeeep">moooeeeep</a>:</p>
<pre><code>def getDupes(l):
seen = set()
seen_add = seen.add
for x in l:
if x in seen or seen_add(x):
yield x
</code></pre>
<p>Accordingly, a full list of dupes would be <code>list(getDupes(etc))</code>. To simply test "if" there is a dupe, it should be wrapped as follows:</p>
<pre><code>def hasDupes(l):
try:
if getDupes(c).next(): return True # Found a dupe
except StopIteration:
pass
return False
</code></pre>
<p>This scales well and provides consistent operating times wherever the dupe is in the list -- I tested with lists of up to 1m entries. If you know something about the data, specifically, that dupes are likely to show up in the first half, or other things that let you skew your requirements, like needing to get the actual dupes, then there are a couple of really alternative dupe locators that might outperform. The two I recommend are...</p>
<p>Simple dict based approach, very readable:</p>
<pre><code>def getDupes(c):
d = {}
for i in c:
if i in d:
if d[i]:
yield i
d[i] = False
else:
d[i] = True
</code></pre>
<p>Leverage itertools (essentially an ifilter/izip/tee) on the sorted list, very efficient if you are getting all the dupes though not as quick to get just the first:</p>
<pre><code>def getDupes(c):
a, b = itertools.tee(sorted(c))
next(b, None)
r = None
for k, g in itertools.ifilter(lambda x: x[0]==x[1], itertools.izip(a, b)):
if k != r:
yield k
r = k
</code></pre>
<p>These were the top performers from the approaches I tried for the <a href="http://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-python-list/31439372#31439372">full dupe list</a>, with the first dupe occurring anywhere in a 1m element list from the start to the middle. It was surprising how little overhead the sort step added. Your mileage may vary, but here are my specific timed results:</p>
<pre><code>Finding FIRST duplicate, single dupe places "n" elements in to 1m element array
Test set len change : 50 - . . . . . -- 0.002
Test in dict : 50 - . . . . . -- 0.002
Test in set : 50 - . . . . . -- 0.002
Test sort/adjacent : 50 - . . . . . -- 0.023
Test sort/groupby : 50 - . . . . . -- 0.026
Test sort/zip : 50 - . . . . . -- 1.102
Test sort/izip : 50 - . . . . . -- 0.035
Test sort/tee/izip : 50 - . . . . . -- 0.024
Test moooeeeep : 50 - . . . . . -- 0.001 *
Test iter*/sorted : 50 - . . . . . -- 0.027
Test set len change : 5000 - . . . . . -- 0.017
Test in dict : 5000 - . . . . . -- 0.003 *
Test in set : 5000 - . . . . . -- 0.004
Test sort/adjacent : 5000 - . . . . . -- 0.031
Test sort/groupby : 5000 - . . . . . -- 0.035
Test sort/zip : 5000 - . . . . . -- 1.080
Test sort/izip : 5000 - . . . . . -- 0.043
Test sort/tee/izip : 5000 - . . . . . -- 0.031
Test moooeeeep : 5000 - . . . . . -- 0.003 *
Test iter*/sorted : 5000 - . . . . . -- 0.031
Test set len change : 50000 - . . . . . -- 0.035
Test in dict : 50000 - . . . . . -- 0.023
Test in set : 50000 - . . . . . -- 0.023
Test sort/adjacent : 50000 - . . . . . -- 0.036
Test sort/groupby : 50000 - . . . . . -- 0.134
Test sort/zip : 50000 - . . . . . -- 1.121
Test sort/izip : 50000 - . . . . . -- 0.054
Test sort/tee/izip : 50000 - . . . . . -- 0.045
Test moooeeeep : 50000 - . . . . . -- 0.019 *
Test iter*/sorted : 50000 - . . . . . -- 0.055
Test set len change : 500000 - . . . . . -- 0.249
Test in dict : 500000 - . . . . . -- 0.145
Test in set : 500000 - . . . . . -- 0.165
Test sort/adjacent : 500000 - . . . . . -- 0.139
Test sort/groupby : 500000 - . . . . . -- 1.138
Test sort/zip : 500000 - . . . . . -- 1.159
Test sort/izip : 500000 - . . . . . -- 0.126
Test sort/tee/izip : 500000 - . . . . . -- 0.120 *
Test moooeeeep : 500000 - . . . . . -- 0.131
Test iter*/sorted : 500000 - . . . . . -- 0.157
</code></pre>
| 1 | 2015-07-22T16:54:59Z | [
"python",
"string",
"list",
"duplicates"
] |
python/django for loop creating database populated with 0000-9999 | 1,541,891 | <p>Basically, i've created a view to populate my database with Serial models from 0000 to 9999. below is the code i'm using for the view.</p>
<pre><code>def insert_serials(request):
for i in range(0,10000):
serial = Serial(i,False)
serial.save()
else:
print 'The for loop is over'
</code></pre>
<p>what is the right way to do this, and i'm getting an IntegrityError, duplicate keys, my model defination is below:</p>
<pre><code>class Serial(models.Model):
serial = models.CharField(max_length=4)
closed = models.BooleanField()
def __unicode__(self):
return "%s" %(self.serial)
def get_absolute_url(self):
return "/draw/serial/%s/" % (self.serial)
</code></pre>
| 0 | 2009-10-09T05:03:47Z | 1,541,911 | <p>Try adding <code>unique=False</code> in the <code>closed</code> field declaration.</p>
<p>Also, you're trying to put integers into a string field. You should do it like <code>Serial('%04d' % i, False)</code> to put values from <code>'0000'</code> to <code>'9999'</code>.</p>
| 0 | 2009-10-09T05:11:49Z | [
"python",
"django"
] |
python/django for loop creating database populated with 0000-9999 | 1,541,891 | <p>Basically, i've created a view to populate my database with Serial models from 0000 to 9999. below is the code i'm using for the view.</p>
<pre><code>def insert_serials(request):
for i in range(0,10000):
serial = Serial(i,False)
serial.save()
else:
print 'The for loop is over'
</code></pre>
<p>what is the right way to do this, and i'm getting an IntegrityError, duplicate keys, my model defination is below:</p>
<pre><code>class Serial(models.Model):
serial = models.CharField(max_length=4)
closed = models.BooleanField()
def __unicode__(self):
return "%s" %(self.serial)
def get_absolute_url(self):
return "/draw/serial/%s/" % (self.serial)
</code></pre>
| 0 | 2009-10-09T05:03:47Z | 1,541,936 | <p>There may be positional default arguments, try using keywords:</p>
<pre><code>from django.db import transaction
@transaction.commit_manually
def insert_serials(request):
for i in range(0,10000):
serial = Serial(serial=str(i),closed=False)
serial.save()
transaction.commit()
print 'The for loop is over'
</code></pre>
<p>It's wrapped in a transaction should speed it up a bit.
See <a href="http://docs.djangoproject.com/en/dev/topics/db/transactions/#django-db-transaction-commit-manually" rel="nofollow">transaction.commit_manually</a> for details</p>
| 1 | 2009-10-09T05:19:12Z | [
"python",
"django"
] |
python/django for loop creating database populated with 0000-9999 | 1,541,891 | <p>Basically, i've created a view to populate my database with Serial models from 0000 to 9999. below is the code i'm using for the view.</p>
<pre><code>def insert_serials(request):
for i in range(0,10000):
serial = Serial(i,False)
serial.save()
else:
print 'The for loop is over'
</code></pre>
<p>what is the right way to do this, and i'm getting an IntegrityError, duplicate keys, my model defination is below:</p>
<pre><code>class Serial(models.Model):
serial = models.CharField(max_length=4)
closed = models.BooleanField()
def __unicode__(self):
return "%s" %(self.serial)
def get_absolute_url(self):
return "/draw/serial/%s/" % (self.serial)
</code></pre>
| 0 | 2009-10-09T05:03:47Z | 1,542,225 | <p>Your code is working on my site - Mac OS X, Python 2.6.3, django from trunk, sqlite3</p>
<p>I changed your view function code a bit, though - </p>
<pre><code>from django.http import HttpResponse
from models import Serial
def insert_serials(request):
for i in range(0,10000):
serial = Serial(i,False)
serial.save()
return HttpResponse("Serials are inserted")
</code></pre>
| 1 | 2009-10-09T07:02:46Z | [
"python",
"django"
] |
python/django for loop creating database populated with 0000-9999 | 1,541,891 | <p>Basically, i've created a view to populate my database with Serial models from 0000 to 9999. below is the code i'm using for the view.</p>
<pre><code>def insert_serials(request):
for i in range(0,10000):
serial = Serial(i,False)
serial.save()
else:
print 'The for loop is over'
</code></pre>
<p>what is the right way to do this, and i'm getting an IntegrityError, duplicate keys, my model defination is below:</p>
<pre><code>class Serial(models.Model):
serial = models.CharField(max_length=4)
closed = models.BooleanField()
def __unicode__(self):
return "%s" %(self.serial)
def get_absolute_url(self):
return "/draw/serial/%s/" % (self.serial)
</code></pre>
| 0 | 2009-10-09T05:03:47Z | 1,557,851 | <p>Your id field (implied by the absence of a PK definition in your model) is not being autonumbered correctly and therefore every INSERT after the first is failing with a duplicate id value. What's your database? Did you have Django create the table, or did you do it yourself?</p>
| 0 | 2009-10-13T01:43:44Z | [
"python",
"django"
] |
binding local variables in python | 1,542,551 | <p>I wonder if there is a good way to bind local variables in python. Most of my work involves cobbling together short data or text processing scripts with a series of expressions (when python permits), so defining object classes (to use as namespaces) and instantiating them seems a bit much. </p>
<p>So what I had in mind was something like in (common) lisp, where you could do something like</p>
<pre><code>(setq data '(1 2 3))
(setq output
(let ( (x (nth 2 data)) )
x + x))
</code></pre>
<p>In python, the best I could come up with is </p>
<pre><code>data = [1,2,3]
output = ((lambda x: x + x)
(data[2]))
</code></pre>
<p>These are, of course, very simple examples but might there be something that is as scalable as let or let* in lisp? Are defining classes the best way to go to create a local namespace?...(but feels a little less interactive that way)</p>
<p><strong>Edit:</strong> So to further explain the intention (my apologies for vagueness), I want to reduce the use of global variables. So in the case above, I meant to use the extraction operator as a general case of any type of operation that might not want to be repeated. For instance, one might write either</p>
<pre><code>output = data[2] + data[2]
</code></pre>
<p>or </p>
<pre><code>x = data[2]
output = x + x
del x
</code></pre>
<p>to accomplish the same result. In essence, if the desired operation on 'data' is more complicated then getting the second item, I wouldn't want to type it out multiple times, or let the computer compute the value of the same expression more times than necessary. So in most cases one would assign the result of the operation, in this case, data[2], or operator.itemgetter(2)(data), to some variable in the global space, but I have an aversion to leaving variables around in the global space if they were only necessary to store intermediate values in a computation... hence the use of the 'del' command immediately afterwards. Defining a local environment or namespace and binding intermediate results to local variables would be an ideal alternative.</p>
| 4 | 2009-10-09T08:26:23Z | 1,542,570 | <p>Not really knowing Lisp, I can't see what you're trying to do here. But I would say that in general you should not try to write Python as if it were Lisp, or indeed any language as if it were any other language. I've been programming in Python for five years and I've never seen a need to do what you're trying above.</p>
<p>Can you give an example of a use case for the above - what are you actually trying to do, in terms of the end result? Maybe then we can advise you on the best way to do it in Python, rather than Lisp.</p>
| 1 | 2009-10-09T08:30:48Z | [
"python",
"lisp"
] |
binding local variables in python | 1,542,551 | <p>I wonder if there is a good way to bind local variables in python. Most of my work involves cobbling together short data or text processing scripts with a series of expressions (when python permits), so defining object classes (to use as namespaces) and instantiating them seems a bit much. </p>
<p>So what I had in mind was something like in (common) lisp, where you could do something like</p>
<pre><code>(setq data '(1 2 3))
(setq output
(let ( (x (nth 2 data)) )
x + x))
</code></pre>
<p>In python, the best I could come up with is </p>
<pre><code>data = [1,2,3]
output = ((lambda x: x + x)
(data[2]))
</code></pre>
<p>These are, of course, very simple examples but might there be something that is as scalable as let or let* in lisp? Are defining classes the best way to go to create a local namespace?...(but feels a little less interactive that way)</p>
<p><strong>Edit:</strong> So to further explain the intention (my apologies for vagueness), I want to reduce the use of global variables. So in the case above, I meant to use the extraction operator as a general case of any type of operation that might not want to be repeated. For instance, one might write either</p>
<pre><code>output = data[2] + data[2]
</code></pre>
<p>or </p>
<pre><code>x = data[2]
output = x + x
del x
</code></pre>
<p>to accomplish the same result. In essence, if the desired operation on 'data' is more complicated then getting the second item, I wouldn't want to type it out multiple times, or let the computer compute the value of the same expression more times than necessary. So in most cases one would assign the result of the operation, in this case, data[2], or operator.itemgetter(2)(data), to some variable in the global space, but I have an aversion to leaving variables around in the global space if they were only necessary to store intermediate values in a computation... hence the use of the 'del' command immediately afterwards. Defining a local environment or namespace and binding intermediate results to local variables would be an ideal alternative.</p>
| 4 | 2009-10-09T08:26:23Z | 1,542,574 | <p>It's a bit unclear what you are asking, bit I'll try to answer anyway:</p>
<p>You bind variables to names with = in Python. So your <code>data = [1,2,3]</code> binds the list <code>[1,2,3]</code> to the name <code>data</code>.</p>
<p>You can create local namespaces with classes and functions/methods.</p>
<p>The closest you get so something as powerful as <code>let</code> is probably <code>def</code> and <code>lambda</code>. Python is (despite where some people try to tell you) not Lisp, and not particularly functional, so you will have to adapt your mindset a bit.</p>
<p>Update: Ah, I see what you mean now.</p>
<p><em>All</em> variables are pretty much local in Python. The nearest you get to global variables are variables defined in module space, because you can access them with <code>from <module> import <variable></code>. You also can access them from wherever in the module, but not modify them (unless you say that you want to modify them with the <code>global</code> keyword. Anything you define in a function/method or class definition, will only be accessible from that namespace.</p>
<p>So in short: you don't have to worry about the things you worry about now. Python takes care of it for you. :)</p>
| 2 | 2009-10-09T08:33:08Z | [
"python",
"lisp"
] |
binding local variables in python | 1,542,551 | <p>I wonder if there is a good way to bind local variables in python. Most of my work involves cobbling together short data or text processing scripts with a series of expressions (when python permits), so defining object classes (to use as namespaces) and instantiating them seems a bit much. </p>
<p>So what I had in mind was something like in (common) lisp, where you could do something like</p>
<pre><code>(setq data '(1 2 3))
(setq output
(let ( (x (nth 2 data)) )
x + x))
</code></pre>
<p>In python, the best I could come up with is </p>
<pre><code>data = [1,2,3]
output = ((lambda x: x + x)
(data[2]))
</code></pre>
<p>These are, of course, very simple examples but might there be something that is as scalable as let or let* in lisp? Are defining classes the best way to go to create a local namespace?...(but feels a little less interactive that way)</p>
<p><strong>Edit:</strong> So to further explain the intention (my apologies for vagueness), I want to reduce the use of global variables. So in the case above, I meant to use the extraction operator as a general case of any type of operation that might not want to be repeated. For instance, one might write either</p>
<pre><code>output = data[2] + data[2]
</code></pre>
<p>or </p>
<pre><code>x = data[2]
output = x + x
del x
</code></pre>
<p>to accomplish the same result. In essence, if the desired operation on 'data' is more complicated then getting the second item, I wouldn't want to type it out multiple times, or let the computer compute the value of the same expression more times than necessary. So in most cases one would assign the result of the operation, in this case, data[2], or operator.itemgetter(2)(data), to some variable in the global space, but I have an aversion to leaving variables around in the global space if they were only necessary to store intermediate values in a computation... hence the use of the 'del' command immediately afterwards. Defining a local environment or namespace and binding intermediate results to local variables would be an ideal alternative.</p>
| 4 | 2009-10-09T08:26:23Z | 1,542,769 | <p>I can only second Lennart and Daniel - Python is not Lisp, and trying to write language X into language Y is usually inefficient and frustrating at best.</p>
<p>First point: your example code</p>
<pre><code>data = [1,2,3]
output = ((lambda x: x + x)
(data[2]))
</code></pre>
<p>would be much more readable as:</p>
<pre><code>data = [1, 2, 3]
output = (lambda x=data[2] : x +x)()
</code></pre>
<p>but anyway, in this concrete case, using a lambda is total overkill, overcomplexificated, and mostly inefficient. A braindead</p>
<pre><code>output = data[2] + data[2]
</code></pre>
<p>would JustWork(tm) !-)</p>
<p>Now wrt/ to local bindings / namespaces, the usual solution is to use... functions - eventually nested. While 100% object (as in "everything is an object"), Python is not pure object, and plain functions are just fine. FWIW, even for "scripts", you should put your logic in a function then call it - function's local namespace access is faster than "global" (really: module level) namespace access. The canonical pattern is</p>
<pre><code>import whatever
def some_func(args):
code_here
def some_other_func(args)
code_here
def main(args):
parse_args
some_func(something)
some_other_func(something_else)
return some_exit_code
if __name__ == '__main__'
import sys
sys.exit(main(sys.argv))
</code></pre>
<p>Note also that nested functions can also access the enclosing namespace, ie</p>
<pre><code>def main():
data = [1, 2, 3]
def foo():
x = data[2]
return x + x
print foo()
data = [4, 5, 6]
print foo()
# if you want the nested function to close over its arguments:
def bar(data=data):
x = data[2]
return x + x
print bar()
data = [7, 8, 9]
print bar()
</code></pre>
<p>HTH</p>
| 3 | 2009-10-09T09:22:50Z | [
"python",
"lisp"
] |
binding local variables in python | 1,542,551 | <p>I wonder if there is a good way to bind local variables in python. Most of my work involves cobbling together short data or text processing scripts with a series of expressions (when python permits), so defining object classes (to use as namespaces) and instantiating them seems a bit much. </p>
<p>So what I had in mind was something like in (common) lisp, where you could do something like</p>
<pre><code>(setq data '(1 2 3))
(setq output
(let ( (x (nth 2 data)) )
x + x))
</code></pre>
<p>In python, the best I could come up with is </p>
<pre><code>data = [1,2,3]
output = ((lambda x: x + x)
(data[2]))
</code></pre>
<p>These are, of course, very simple examples but might there be something that is as scalable as let or let* in lisp? Are defining classes the best way to go to create a local namespace?...(but feels a little less interactive that way)</p>
<p><strong>Edit:</strong> So to further explain the intention (my apologies for vagueness), I want to reduce the use of global variables. So in the case above, I meant to use the extraction operator as a general case of any type of operation that might not want to be repeated. For instance, one might write either</p>
<pre><code>output = data[2] + data[2]
</code></pre>
<p>or </p>
<pre><code>x = data[2]
output = x + x
del x
</code></pre>
<p>to accomplish the same result. In essence, if the desired operation on 'data' is more complicated then getting the second item, I wouldn't want to type it out multiple times, or let the computer compute the value of the same expression more times than necessary. So in most cases one would assign the result of the operation, in this case, data[2], or operator.itemgetter(2)(data), to some variable in the global space, but I have an aversion to leaving variables around in the global space if they were only necessary to store intermediate values in a computation... hence the use of the 'del' command immediately afterwards. Defining a local environment or namespace and binding intermediate results to local variables would be an ideal alternative.</p>
| 4 | 2009-10-09T08:26:23Z | 1,543,348 | <p>You could combine a function decorator and default parameters to get something like let and block scoped variables:</p>
<pre><code>def let(func):
return func()
data = [1,2,3]
@let
def output(x=data[2]):
return x + x
print(output) # 6
# or if a single expression is enough:
output = let(lambda x=data[2]: x+x)
</code></pre>
<p>But this isn't a popular idiom in Python so I advise you avoid it to make your code easier to understand for others. Just use regular local variables:</p>
<pre><code>data = [1,2,3]
x = data[2]
output = x + x
</code></pre>
<p>If this becomes a real problem it's a good sign you are trying to do too much in a single function.</p>
| 2 | 2009-10-09T11:54:30Z | [
"python",
"lisp"
] |
How to write this "model" in Django? | 1,542,659 | <p>I am currently using Django Users model.
Very simple. However, I'd like to add one feature: Adding friends!</p>
<p>I would like to create 2 columns in my table:</p>
<p>UID (the ID of the User)
friend_id (the ID of his friend! ...of course, this ID is also in Django's User model.
The UID-friend_id combination must be unique! For example, if my ID is 84, I cannot have two rows the same, because I can only subscribe to the same friend once.</p>
<p>Can anyone tell me if this is the right way to do it? Should I do some KEY relationship for the "friend_id", or should I leave it like this, as "IntegerField"?</p>
<pre><code>class Friend(models.Model):
uid = models.ForeignKey(User)
friend_id = models.IntegerField(default=0)
</code></pre>
<p>Thank you</p>
| 2 | 2009-10-09T08:54:04Z | 1,542,697 | <p>You should create a model that defines the relationship between two users, and then define two foreign-key fields, each one to a User. You can then add a unique constraint to make sure you don't have duplicates.</p>
<p>There is a article here explaining exactly how to do this: <a href="http://www.packtpub.com/article/building-friend-networks-with-django-1.0" rel="nofollow">http://www.packtpub.com/article/building-friend-networks-with-django-1.0</a></p>
<p>The example model from that page:</p>
<pre><code>class Friendship(models.Model):
from_friend = models.ForeignKey(
User, related_name='friend_set'
)
to_friend = models.ForeignKey(
User, related_name='to_friend_set'
)
def __unicode__(self):
return u'%s, %s' % (
self.from_friend.username,
self.to_friend.username
)
class Meta:
unique_together = (('to_friend', 'from_friend'), )
</code></pre>
| 11 | 2009-10-09T09:04:01Z | [
"python",
"django"
] |
Accuracy of stat mtime in Windows | 1,542,711 | <p>Have an example piece of (Python) code to check if a directory has changed:</p>
<pre><code>import os
def watch(path, fdict):
"""Checks a directory and children for changes"""
changed = []
for root, dirs, files in os.walk(path):
for f in files:
abspath = os.path.abspath(os.path.join(root, f))
new_mtime = os.stat(abspath).st_mtime
if not fdict.has_key(abspath) or new_mtime > fdict[abspath]:
changed.append(abspath)
fdict[abspath] = new_mtime
return fdict, changed
</code></pre>
<p>But the accompanying unittest randomly fails unless I add at least a 2 second sleep:</p>
<pre><code>import unittest
import project_creator
import os
import time
class tests(unittest.TestCase):
def setUp(self):
os.makedirs('autotest')
f = open(os.path.join('autotest', 'new_file.txt'), 'w')
f.write('New file')
def tearDown(self):
os.unlink(os.path.join('autotest', 'new_file.txt'))
os.rmdir('autotest')
def test_amend_file(self):
changed = project_creator.watch('autotest', {})
time.sleep(2)
f = open(os.path.join('autotest', 'new_file.txt'), 'a')
f.write('\nA change!')
f.close()
changed = project_creator.watch('autotest', changed[0])
self.assertEqual(changed[1], [os.path.abspath(os.path.join('autotest', 'new_file.txt'))])
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>Is stat really limited to worse than 1 second accuracy? (Edit: apparently so, with FAT)
Is there any (cross platform) way of detecting more rapid changes?</p>
| 0 | 2009-10-09T09:09:46Z | 1,542,849 | <p>The <em>proper</em> way is to watch a directory instead of polling for changes. </p>
<p>Check out <a href="http://msdn.microsoft.com/en-us/library/aa364417%28VS.85%29.aspx" rel="nofollow">FindFirstChangeNotification Function</a>.<br />
<a href="http://timgolden.me.uk/python/win32%5Fhow%5Fdo%5Fi/watch%5Fdirectory%5Ffor%5Fchanges.html" rel="nofollow">Watch a Directory for Changes</a> is a Python implementation.</p>
<p>If directory watching isn't accurate enough then probably the only alternative is to intercept file systems calls.</p>
| 1 | 2009-10-09T09:42:33Z | [
"python",
"windows",
"filemtime"
] |
Accuracy of stat mtime in Windows | 1,542,711 | <p>Have an example piece of (Python) code to check if a directory has changed:</p>
<pre><code>import os
def watch(path, fdict):
"""Checks a directory and children for changes"""
changed = []
for root, dirs, files in os.walk(path):
for f in files:
abspath = os.path.abspath(os.path.join(root, f))
new_mtime = os.stat(abspath).st_mtime
if not fdict.has_key(abspath) or new_mtime > fdict[abspath]:
changed.append(abspath)
fdict[abspath] = new_mtime
return fdict, changed
</code></pre>
<p>But the accompanying unittest randomly fails unless I add at least a 2 second sleep:</p>
<pre><code>import unittest
import project_creator
import os
import time
class tests(unittest.TestCase):
def setUp(self):
os.makedirs('autotest')
f = open(os.path.join('autotest', 'new_file.txt'), 'w')
f.write('New file')
def tearDown(self):
os.unlink(os.path.join('autotest', 'new_file.txt'))
os.rmdir('autotest')
def test_amend_file(self):
changed = project_creator.watch('autotest', {})
time.sleep(2)
f = open(os.path.join('autotest', 'new_file.txt'), 'a')
f.write('\nA change!')
f.close()
changed = project_creator.watch('autotest', changed[0])
self.assertEqual(changed[1], [os.path.abspath(os.path.join('autotest', 'new_file.txt'))])
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>Is stat really limited to worse than 1 second accuracy? (Edit: apparently so, with FAT)
Is there any (cross platform) way of detecting more rapid changes?</p>
| 0 | 2009-10-09T09:09:46Z | 1,542,856 | <p>if this were linux, i'd use inotify. there's apparently a windows inotify equivalent - the java <a href="http://jnotify.sourceforge.net/" rel="nofollow">jnotify library</a> has implemented it - but i don't know if there's a python implementation</p>
| 0 | 2009-10-09T09:44:45Z | [
"python",
"windows",
"filemtime"
] |
Accuracy of stat mtime in Windows | 1,542,711 | <p>Have an example piece of (Python) code to check if a directory has changed:</p>
<pre><code>import os
def watch(path, fdict):
"""Checks a directory and children for changes"""
changed = []
for root, dirs, files in os.walk(path):
for f in files:
abspath = os.path.abspath(os.path.join(root, f))
new_mtime = os.stat(abspath).st_mtime
if not fdict.has_key(abspath) or new_mtime > fdict[abspath]:
changed.append(abspath)
fdict[abspath] = new_mtime
return fdict, changed
</code></pre>
<p>But the accompanying unittest randomly fails unless I add at least a 2 second sleep:</p>
<pre><code>import unittest
import project_creator
import os
import time
class tests(unittest.TestCase):
def setUp(self):
os.makedirs('autotest')
f = open(os.path.join('autotest', 'new_file.txt'), 'w')
f.write('New file')
def tearDown(self):
os.unlink(os.path.join('autotest', 'new_file.txt'))
os.rmdir('autotest')
def test_amend_file(self):
changed = project_creator.watch('autotest', {})
time.sleep(2)
f = open(os.path.join('autotest', 'new_file.txt'), 'a')
f.write('\nA change!')
f.close()
changed = project_creator.watch('autotest', changed[0])
self.assertEqual(changed[1], [os.path.abspath(os.path.join('autotest', 'new_file.txt'))])
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>Is stat really limited to worse than 1 second accuracy? (Edit: apparently so, with FAT)
Is there any (cross platform) way of detecting more rapid changes?</p>
| 0 | 2009-10-09T09:09:46Z | 8,386,780 | <p>Watchdog:
<a href="http://packages.python.org/watchdog/quickstart.html" rel="nofollow">http://packages.python.org/watchdog/quickstart.html</a></p>
<p>Is a good project to have some multi-platform changes notification.</p>
| 1 | 2011-12-05T14:27:37Z | [
"python",
"windows",
"filemtime"
] |
Does python's print function handle unicode differently now than when Dive Into Python was written? | 1,542,785 | <p>I'm trying to work my way through some frustrating encoding issues by going back to basics. In Dive Into Python example 9.14 (<a href="http://diveintopython.net/xml_processing/unicode.html" rel="nofollow">here</a>) we have this:</p>
<pre><code>>>> s = u'La Pe\xf1a'
>>> print s
Traceback (innermost last): File "<interactive input>", line 1, in ?
UnicodeError: ASCII encoding error: ordinal not in range(128)
>>> print s.encode('latin-1')
La Peña
</code></pre>
<p>But on my machine, this happens:</p>
<pre><code>>>> sys.getdefaultencoding()
'ascii'
>>> s = u'La Pe\xf1a'
>>> print s
La Peña
</code></pre>
<p>I don't understand why these are different. Anybody?</p>
| 4 | 2009-10-09T09:28:47Z | 1,542,823 | <p>The default encoding for <code>print</code> doesn't depend on <code>sys.getdefaultencoding()</code>, but on <code>sys.stdout.encoding</code>. If you launch python with e.g. <code>LANG=C</code> or redirect a python script to a file, the encoding for stdout will be <code>ANSI_X3.4-1968</code>. On the other hand, if <code>sys.stdout</code> is a terminal, it will use the terminal's encoding.</p>
<p>To explain what <code>sys.getdefaultencoding()</code> does -- it's used when implicitly converting strings from/to unicode. In this example, <code>str(u'La Pe\xf1a')</code> with the default ASCII encoding would fail, but with modified default encoding it would encode the string to Latin-1. However setting the default encoding is a horrible idea, you should always use explicit encoding when you want to go from <code>unicode</code> to <code>str</code>.</p>
| 6 | 2009-10-09T09:36:11Z | [
"python",
"unicode",
"character-encoding"
] |
What to do when Django query returns none? It gives me error | 1,542,878 | <pre><code>to_friend = User.objects.filter(username=friend_q)[0:1]
</code></pre>
<p>If 'friend_q' is NOT inside the User.username...it will give error.
What is the recommended tactic?</p>
<p>Thank you</p>
| 4 | 2009-10-09T09:50:41Z | 1,542,897 | <p>The reason you're getting an error is because you're trying to evaluate the Query object when there's nothing in it. The [0:1] at the end is attempting to take the first item out of an empty list. If you split up the expression a little like below, you can check for an empty list before taking an element out of it.</p>
<pre><code>to_friends = User.objects.filter(username=friend_q)
if to_friends:
to_friend = to_friends[0]
</code></pre>
| 0 | 2009-10-09T09:55:42Z | [
"python",
"django"
] |
What to do when Django query returns none? It gives me error | 1,542,878 | <pre><code>to_friend = User.objects.filter(username=friend_q)[0:1]
</code></pre>
<p>If 'friend_q' is NOT inside the User.username...it will give error.
What is the recommended tactic?</p>
<p>Thank you</p>
| 4 | 2009-10-09T09:50:41Z | 1,542,919 | <ol>
<li><p>FWIW, Username is unique. So U can use </p>
<pre><code>to_friend = User.objects.get(username=friend_q)
</code></pre></li>
<li><p>If you want to raise a 404 when the user doesn't exist, you may as well,</p>
<pre><code>from django.shortcuts import get_object_or_404
to_friend = get_object_or_404(User,username=friend_q)
</code></pre></li>
<li><p>To prevent error, you may simply put it in the try except block, very pythonic.</p>
<pre><code>try:
to_friend = User.objects.get(username=friend_q)
except User.DoesNotExist:
to_friend = None
</code></pre></li>
<li><p>Since this is a common requirement, you should consider defining <code>get_user_or_none</code> on the UserManager, and other managers that would require <code>None</code> return, similar to get_object_or_404. This was in consideration for django core, but was not included, for what ever the reason. Still, is a handy, 4 line function, for models that need <code>None</code> back.</p></li>
</ol>
| 5 | 2009-10-09T10:01:41Z | [
"python",
"django"
] |
What to do when Django query returns none? It gives me error | 1,542,878 | <pre><code>to_friend = User.objects.filter(username=friend_q)[0:1]
</code></pre>
<p>If 'friend_q' is NOT inside the User.username...it will give error.
What is the recommended tactic?</p>
<p>Thank you</p>
| 4 | 2009-10-09T09:50:41Z | 1,542,934 | <p>If friend_q is not a user present in the database, to_friend will be equal to an empty list.</p>
<pre><code>>>> from django.contrib.auth.models import User
>>> User.objects.filter(username='does-not-exist')
[]
</code></pre>
<p>However, it's better to use the get() method to lookup a specific entry:</p>
<pre><code>>>> User.objects.get(username='does-exist')
<User: does-exist>
>>> User.objects.get(username='does-not-exist')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python2.5/django/db/models/manager.py", line 120, in get
File "/usr/lib/python2.5/django/db/models/query.py", line 305, in get
DoesNotExist: User matching query does not exist.
</code></pre>
<p>You can now catch the DoesNotExist exception and take appropriate actions.</p>
<pre><code>try:
to_friend = User.objects.get(username=friend_q)
except User.DoesNotExist:
# do something, raise error, ...
</code></pre>
| 8 | 2009-10-09T10:06:39Z | [
"python",
"django"
] |
Help in the following code | 1,542,991 | <pre><code>def startConnection(self):
from ftplib import FTP
self.ftp = FTP(self.loginServer)
print 'Loging In'
print self.ftp.login(self.username, self.password)
data = []
self.ftp.dir(data.append)
for line in data:
try:
self.date_str = ' '.join(line.split()[5:8])
newDate = time.strptime(self.date_str,'%b %d %H:%M')
print newDate
col_list = line.split()
name = col_list[0]
tempDir = {}
if name.startswith('d'):
tempDir['directory'] = newDate
else:
tempDir['file']=newDate
self.dirInfo[col_list[8]] = tempDir
except:
print "**********Exception for line **********\n" + line + "\n**********Exception End**********"
</code></pre>
<p>This function is working fine,
newDate value is Aug 20 11:12, but year is missing,
so Bydefault year value it is taking 1900, which is not correct.
To debug it, i logged in ftp server and did dir / ls in both the cases it is showing timestamp like 'Aug 20 11:12'. But if i do ls -lTr, in that case it is showing year,</p>
<p>what i want is some how i can pass above command to ftp and get the result.
Is there any python ftplib module's function that can do this.</p>
| 0 | 2009-10-09T10:23:52Z | 1,543,006 | <p>Try</p>
<pre><code>self.ftp.dir('-lTr', data.append)
</code></pre>
| 1 | 2009-10-09T10:28:54Z | [
"python",
"ftplib"
] |
Help in the following code | 1,542,991 | <pre><code>def startConnection(self):
from ftplib import FTP
self.ftp = FTP(self.loginServer)
print 'Loging In'
print self.ftp.login(self.username, self.password)
data = []
self.ftp.dir(data.append)
for line in data:
try:
self.date_str = ' '.join(line.split()[5:8])
newDate = time.strptime(self.date_str,'%b %d %H:%M')
print newDate
col_list = line.split()
name = col_list[0]
tempDir = {}
if name.startswith('d'):
tempDir['directory'] = newDate
else:
tempDir['file']=newDate
self.dirInfo[col_list[8]] = tempDir
except:
print "**********Exception for line **********\n" + line + "\n**********Exception End**********"
</code></pre>
<p>This function is working fine,
newDate value is Aug 20 11:12, but year is missing,
so Bydefault year value it is taking 1900, which is not correct.
To debug it, i logged in ftp server and did dir / ls in both the cases it is showing timestamp like 'Aug 20 11:12'. But if i do ls -lTr, in that case it is showing year,</p>
<p>what i want is some how i can pass above command to ftp and get the result.
Is there any python ftplib module's function that can do this.</p>
| 0 | 2009-10-09T10:23:52Z | 1,543,026 | <p>If you are using a command that gives a short-form date, or want to cope with different arguments being handed to <code>ls</code> you'll have to make multiple attempts to parse the date with different format strings, until you don't get a <code>ValueError</code>, post-processing the successful parse according to which format it has matched -- files more than a year old will often report a date format including a year but no time of day (here you could probably stick with a default 00:00:00 time); recent files reported in a format without a year can have the current year defaulted in; formats that contain a year would be left unchanged.</p>
| 0 | 2009-10-09T10:33:59Z | [
"python",
"ftplib"
] |
Pure Python persistent key and value based container (a hash like interface) with large file system support? | 1,543,087 | <p>I am looking for a (possibly) pure Python library for persistent hash table (btree or b+tree which would provide following features</p>
<ol>
<li>Large file support (possibly in terabytes)</li>
<li>Fast enough and low memory footprint (looking for a descent balance between speed and memory)</li>
<li>Low cost of management</li>
<li>Reliability i.e. doesn't corrupt file once the content is written through the file system</li>
<li>Lastly a pure Python implementation. I am OK if it has C library but I am looking for a cross platform solution</li>
</ol>
<p>I have looked into solutions like redis, shelve, tokyo cabinet. Tokyo cabinet is impressive and has a Python binding in the making at <a href="http://code.google.com/p/python-tokyocabinet/" rel="nofollow">http://code.google.com/p/python-tokyocabinet/</a>, but its Windows port is a work in progress.</p>
<p>Thanks for some good suggestions. I am currently exploring SQLite3 with Python. I got suggestions to use database engine but am more inclined towards a lean and mean persistent b+tree implementations</p>
| 3 | 2009-10-09T10:47:56Z | 1,543,184 | <p>ZODB<br />
<a href="http://pypi.python.org/pypi/ZODB3" rel="nofollow">http://pypi.python.org/pypi/ZODB3</a></p>
<p>Like Lennart says, use the latest version of course</p>
| 2 | 2009-10-09T11:13:37Z | [
"python",
"hash",
"persistence"
] |
Pure Python persistent key and value based container (a hash like interface) with large file system support? | 1,543,087 | <p>I am looking for a (possibly) pure Python library for persistent hash table (btree or b+tree which would provide following features</p>
<ol>
<li>Large file support (possibly in terabytes)</li>
<li>Fast enough and low memory footprint (looking for a descent balance between speed and memory)</li>
<li>Low cost of management</li>
<li>Reliability i.e. doesn't corrupt file once the content is written through the file system</li>
<li>Lastly a pure Python implementation. I am OK if it has C library but I am looking for a cross platform solution</li>
</ol>
<p>I have looked into solutions like redis, shelve, tokyo cabinet. Tokyo cabinet is impressive and has a Python binding in the making at <a href="http://code.google.com/p/python-tokyocabinet/" rel="nofollow">http://code.google.com/p/python-tokyocabinet/</a>, but its Windows port is a work in progress.</p>
<p>Thanks for some good suggestions. I am currently exploring SQLite3 with Python. I got suggestions to use database engine but am more inclined towards a lean and mean persistent b+tree implementations</p>
| 3 | 2009-10-09T10:47:56Z | 1,543,245 | <p>ZODB is indeed a powerful tool, but maybe it's overkill.</p>
<p>You can hack your own solution in few Python lines : simply code a dictionary like object as a data base adapter. Try using <a href="http://sebsauvage.net/python/snyppets/index.html#dbdict" rel="nofollow">this snippets</a>, replacing the SQLite call to MySql and you should be done.</p>
| 1 | 2009-10-09T11:27:21Z | [
"python",
"hash",
"persistence"
] |
Pure Python persistent key and value based container (a hash like interface) with large file system support? | 1,543,087 | <p>I am looking for a (possibly) pure Python library for persistent hash table (btree or b+tree which would provide following features</p>
<ol>
<li>Large file support (possibly in terabytes)</li>
<li>Fast enough and low memory footprint (looking for a descent balance between speed and memory)</li>
<li>Low cost of management</li>
<li>Reliability i.e. doesn't corrupt file once the content is written through the file system</li>
<li>Lastly a pure Python implementation. I am OK if it has C library but I am looking for a cross platform solution</li>
</ol>
<p>I have looked into solutions like redis, shelve, tokyo cabinet. Tokyo cabinet is impressive and has a Python binding in the making at <a href="http://code.google.com/p/python-tokyocabinet/" rel="nofollow">http://code.google.com/p/python-tokyocabinet/</a>, but its Windows port is a work in progress.</p>
<p>Thanks for some good suggestions. I am currently exploring SQLite3 with Python. I got suggestions to use database engine but am more inclined towards a lean and mean persistent b+tree implementations</p>
| 3 | 2009-10-09T10:47:56Z | 1,543,403 | <p>Use a relational database. </p>
<ul>
<li>Really fast when retrieving data based on a key, if you put an index in the key. </li>
<li>Good scaling</li>
<li>Don't get easily corrupted</li>
<li>Tools already available for:
<ul>
<li>Backups</li>
<li>Replication</li>
<li>Clustering</li>
</ul></li>
<li>Cross-platform</li>
<li>Works over the network</li>
<li>Allow really fast <code>JOIN</code>s, grouping, agreggation, and other complex queries, in case you need them</li>
</ul>
<p>You can easily create a class that works like a <code>dict</code> or hash table, but uses the database as storage. You can make it cache as much as you want on memory.</p>
| 2 | 2009-10-09T12:09:47Z | [
"python",
"hash",
"persistence"
] |
Google Federated Login (OpenID+Oauth) for Hosted Apps - changing end points? | 1,543,123 | <p>I'm trying to integrate the Google Federated Login with a premier apps account, but I'm having some problems.</p>
<p>When I send the request to: <code>https://www.google.com/accounts/o8/ud</code> with all the parameters (see below), I get back both a <code>request_token</code> and list of attributes asked for by <code>Attribute Exchange</code>. This is perfect, as we need the email via attribute exhange (AX) to store the user in our application database, and we need the request token for future <code>API requests to scopes</code> (ie: calendar, contacts, etc).</p>
<p>However, using that URL (herein referred to as the <code>endpoint</code>) doesn't keep the user signed in to their hosted apps (gmail, calendar, <em>et al</em>), which is a problem.</p>
<p>Changing the endpoint to <code>https://www.google.com/a/thedomain.com/o8/ud?be=o8</code> changes everything. I am automagically signed in to other google apps (gmail etc). However, using that endpoint, I only get the request token <strong><em>or</em></strong> the attributes via AX. Obviously thats not particularly Hybrid. Its very much one or the other.</p>
<p>Example request to the endpoint <code>https://www.google.com/accounts/o8/ud</code></p>
<pre><code>parameters = {
'openid.ns': 'http://specs.openid.net/auth/2.0',
'openid.claimed_id': 'http://specs.openid.net/auth/2.0/identifier_select',
'openid.identity': 'http://specs.openid.net/auth/2.0/identifier_select',
'openid.return_to':'http://our.domain.com/accounts/callback/',
'openid.realm': 'http://our.domain.com/',
'openid.assoc_handle': assoc_handle,
'openid.mode': 'checkid_setup',
'openid.ns.ext2': 'http://specs.openid.net/extensions/oauth/1.0',
'openid.ext2.consumer': 'our.domain.com',
'openid.ext2.scope': 'https://mail.google.com/mail/feed/atom',
'openid.ns.ax':'http://openid.net/srv/ax/1.0',
'openid.ax.mode':'fetch_request',
'openid.ax.required':'firstname,lastname,email',
'openid.ax.type.firstname':'http://axschema.org/namePerson/first',
'openid.ax.type.lastname':'http://axschema.org/namePerson/last',
'openid.ax.type.email':'http://axschema.org/contact/email',
}
return HttpResponseRedirect(end_point + '?' + urllib.urlencode(parameters))
</code></pre>
<p>(assoc_handle is previously set successfully by the openid initial request)</p>
<p>I've been struggling for days trying to get this Hybird approach working, fighting the most opaque error messages (<code>This page is invalid</code> ... thanks Google) and lack of consistent documentation. I've trawled every code sample I can to get to this point. Any help would be appreciated ...</p>
| 8 | 2009-10-09T10:58:14Z | 1,650,977 | <p>For the record, posterity, and anyone else who might come asunder of this, I'll document the (ridiculous) answer.</p>
<p>Ultimately, the problem was calling:</p>
<pre><code>return HttpResponseRedirect(
'https://www.google.com/a/thedomain.com/o8/ud?be=o8'
+ '?'
+ urllib.urlencode(parameters)
)
</code></pre>
<p>Can you spot it? Yeah, it was the explicit inclusion of the question mark that caused the problem. Two query strings never exist at once. </p>
| 7 | 2009-10-30T16:44:30Z | [
"python",
"openid",
"oauth",
"hybridauthprovider"
] |
simple dropping elements from the list in python | 1,543,456 | <p>I'd like to achieve following effect</p>
<pre><code>a=[11, -1, -1, -1]
msg=['one','two','tree','four']
msg[where a<0]
['two','tree','four']
</code></pre>
<p>In similar simple fashion (without nasty loops).</p>
<p>PS. For curious people this if statement is working natively in one of functional languages. </p>
<p>//EDIT</p>
<p>I know that below text is different that the requirements above, but I've found what I wonted to acheave.
I don't want to spam another answer in my own thread, so I've also find some nice solution,
and I want to present it to you.</p>
<pre><code>filter(lambda x: not x.endswith('one'),msg)
</code></pre>
| 1 | 2009-10-09T12:21:07Z | 1,543,463 | <p>You can use <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehensions</a> for this. You need to match the items from the two lists, for which the <a href="http://docs.python.org/3.1/library/functions.html#zip" rel="nofollow"><code>zip</code></a> function is used. This will generate a list of tuples, where each tuple contains one item from each of the original lists (i.e., <code>[(11, 'one'), ...]</code>). Once you have this, you can iterate over the result, check if the first element is below 0 and return the second element. See the linked Python docs for more details about the syntax.</p>
<pre><code>[y for (x, y) in zip(a, msg) if x < 0]
</code></pre>
<p>The actual problem seems to be about finding items in the <code>msg</code> list that don't contain the string <code>"one"</code>. This can be done directly:</p>
<pre><code>[m for m in msg if "one" not in m]
</code></pre>
| 10 | 2009-10-09T12:23:29Z | [
"python",
"filter"
] |
simple dropping elements from the list in python | 1,543,456 | <p>I'd like to achieve following effect</p>
<pre><code>a=[11, -1, -1, -1]
msg=['one','two','tree','four']
msg[where a<0]
['two','tree','four']
</code></pre>
<p>In similar simple fashion (without nasty loops).</p>
<p>PS. For curious people this if statement is working natively in one of functional languages. </p>
<p>//EDIT</p>
<p>I know that below text is different that the requirements above, but I've found what I wonted to acheave.
I don't want to spam another answer in my own thread, so I've also find some nice solution,
and I want to present it to you.</p>
<pre><code>filter(lambda x: not x.endswith('one'),msg)
</code></pre>
| 1 | 2009-10-09T12:21:07Z | 1,543,464 | <pre><code>[m for m, i in zip(msg, a) if i < 0]
</code></pre>
| 2 | 2009-10-09T12:23:57Z | [
"python",
"filter"
] |
simple dropping elements from the list in python | 1,543,456 | <p>I'd like to achieve following effect</p>
<pre><code>a=[11, -1, -1, -1]
msg=['one','two','tree','four']
msg[where a<0]
['two','tree','four']
</code></pre>
<p>In similar simple fashion (without nasty loops).</p>
<p>PS. For curious people this if statement is working natively in one of functional languages. </p>
<p>//EDIT</p>
<p>I know that below text is different that the requirements above, but I've found what I wonted to acheave.
I don't want to spam another answer in my own thread, so I've also find some nice solution,
and I want to present it to you.</p>
<pre><code>filter(lambda x: not x.endswith('one'),msg)
</code></pre>
| 1 | 2009-10-09T12:21:07Z | 1,543,792 | <p>The answers already posted are good, but if you want an alternative you can look at numpy and at its arrays.</p>
<pre><code>>>> import numpy as np
>>> a = np.array([11, -1, -1, -1])
>>> msg = np.array(['one','two','tree','four'])
>>> a < 0
array([False, True, True, True], dtype=bool)
>>> msg[a < 0]
array(['two', 'tree', 'four'], dtype='|S4')
</code></pre>
<p>I don't know how array indexing is implemented in numpy, but it is usually fast and problably rewritten in C. Compared to the other solutions, this should be more readable, but it requires numpy.</p>
| 1 | 2009-10-09T13:35:58Z | [
"python",
"filter"
] |
simple dropping elements from the list in python | 1,543,456 | <p>I'd like to achieve following effect</p>
<pre><code>a=[11, -1, -1, -1]
msg=['one','two','tree','four']
msg[where a<0]
['two','tree','four']
</code></pre>
<p>In similar simple fashion (without nasty loops).</p>
<p>PS. For curious people this if statement is working natively in one of functional languages. </p>
<p>//EDIT</p>
<p>I know that below text is different that the requirements above, but I've found what I wonted to acheave.
I don't want to spam another answer in my own thread, so I've also find some nice solution,
and I want to present it to you.</p>
<pre><code>filter(lambda x: not x.endswith('one'),msg)
</code></pre>
| 1 | 2009-10-09T12:21:07Z | 1,543,987 | <p>I think <strong>[msg[i] for i in range(len(a)) if a[i]<0]</strong> will work for you.</p>
| 0 | 2009-10-09T14:05:10Z | [
"python",
"filter"
] |
Can't get django-registration to work (on Windows) | 1,543,601 | <p>Trying to add <a href="http://bitbucket.org/ubernostrum/django-registration/wiki/Home" rel="nofollow">django-registration</a> to my app. I have installed <a href="http://pypi.python.org/pypi/setuptools" rel="nofollow">setup tools</a> to use <a href="http://peak.telecommunity.com/DevCenter/EasyInstall#using-easy-install" rel="nofollow">easy_install</a>. I think that works..</p>
<p>I run easy_install django-registation and a cmd prompt window flashes up, does something and closes. I don't think it's an error. But when I look in my app folder, theres nothing relation to django-registration.</p>
<p>Anyone know what is wrong? And where should the django-registration files appear?</p>
<p>(Also tried it with django-profiles and it was exactly the same)</p>
| 0 | 2009-10-09T12:59:30Z | 1,543,639 | <p>Django-registration will be installed on your python path, not in the project itself. You can see if it installed correctly by entering your python prompt and running:</p>
<pre><code>>>>import registration
</code></pre>
<p>If you don't get an error it is working and installed. Just add 'registration' to your INSTALLED_APPS. </p>
| 4 | 2009-10-09T13:07:46Z | [
"python",
"django",
"registration",
"setuptools",
"easy-install"
] |
Python gzip: is there a way to decompress from a string? | 1,543,652 | <p>I've read this <a href="http://stackoverflow.com/questions/1313845/if-i-have-the-contents-of-a-zipfile-in-a-python-string-can-i-decompress-it-witho">SO post</a> around the problem to no avail.</p>
<p>I am trying to decompress a .gz file coming from an URL.</p>
<pre><code>url_file_handle=StringIO( gz_data )
gzip_file_handle=gzip.open(url_file_handle,"r")
decompressed_data = gzip_file_handle.read()
gzip_file_handle.close()
</code></pre>
<p>... but I get <em>TypeError: coercing to Unicode: need string or buffer, cStringIO.StringI found</em></p>
<p>What's going on?</p>
<pre><code>Traceback (most recent call last):
File "/opt/google/google_appengine-1.2.5/google/appengine/tools/dev_appserver.py", line 2974, in _HandleRequest
base_env_dict=env_dict)
File "/opt/google/google_appengine-1.2.5/google/appengine/tools/dev_appserver.py", line 411, in Dispatch
base_env_dict=base_env_dict)
File "/opt/google/google_appengine-1.2.5/google/appengine/tools/dev_appserver.py", line 2243, in Dispatch
self._module_dict)
File "/opt/google/google_appengine-1.2.5/google/appengine/tools/dev_appserver.py", line 2161, in ExecuteCGI
reset_modules = exec_script(handler_path, cgi_path, hook)
File "/opt/google/google_appengine-1.2.5/google/appengine/tools/dev_appserver.py", line 2057, in ExecuteOrImportScript
exec module_code in script_module.__dict__
File "/home/jldupont/workspace/jldupont/trunk/site/app/server/tasks/debian/repo_fetcher.py", line 36, in <module>
main()
File "/home/jldupont/workspace/jldupont/trunk/site/app/server/tasks/debian/repo_fetcher.py", line 30, in main
gziph=gzip.open(fh,'r')
File "/usr/lib/python2.5/gzip.py", line 49, in open
return GzipFile(filename, mode, compresslevel)
File "/usr/lib/python2.5/gzip.py", line 95, in __init__
fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb')
TypeError: coercing to Unicode: need string or buffer, cStringIO.StringI found
</code></pre>
| 20 | 2009-10-09T13:09:12Z | 1,543,665 | <p><code>gzip.open</code> is a shorthand for opening a file, what you want is <code>gzip.GzipFile</code> which you can pass a fileobj</p>
<pre><code>open(filename, mode='rb', compresslevel=9)
#Shorthand for GzipFile(filename, mode, compresslevel).
</code></pre>
<p>vs</p>
<pre><code>class GzipFile
__init__(self, filename=None, mode=None, compresslevel=9, fileobj=None)
# At least one of fileobj and filename must be given a non-trivial value.
</code></pre>
<p>so this should work for you</p>
<pre><code>gzip_file_handle = gzip.GzipFile(fileobj=url_file_handle)
</code></pre>
| 27 | 2009-10-09T13:13:46Z | [
"python",
"gzip"
] |
Python gzip: is there a way to decompress from a string? | 1,543,652 | <p>I've read this <a href="http://stackoverflow.com/questions/1313845/if-i-have-the-contents-of-a-zipfile-in-a-python-string-can-i-decompress-it-witho">SO post</a> around the problem to no avail.</p>
<p>I am trying to decompress a .gz file coming from an URL.</p>
<pre><code>url_file_handle=StringIO( gz_data )
gzip_file_handle=gzip.open(url_file_handle,"r")
decompressed_data = gzip_file_handle.read()
gzip_file_handle.close()
</code></pre>
<p>... but I get <em>TypeError: coercing to Unicode: need string or buffer, cStringIO.StringI found</em></p>
<p>What's going on?</p>
<pre><code>Traceback (most recent call last):
File "/opt/google/google_appengine-1.2.5/google/appengine/tools/dev_appserver.py", line 2974, in _HandleRequest
base_env_dict=env_dict)
File "/opt/google/google_appengine-1.2.5/google/appengine/tools/dev_appserver.py", line 411, in Dispatch
base_env_dict=base_env_dict)
File "/opt/google/google_appengine-1.2.5/google/appengine/tools/dev_appserver.py", line 2243, in Dispatch
self._module_dict)
File "/opt/google/google_appengine-1.2.5/google/appengine/tools/dev_appserver.py", line 2161, in ExecuteCGI
reset_modules = exec_script(handler_path, cgi_path, hook)
File "/opt/google/google_appengine-1.2.5/google/appengine/tools/dev_appserver.py", line 2057, in ExecuteOrImportScript
exec module_code in script_module.__dict__
File "/home/jldupont/workspace/jldupont/trunk/site/app/server/tasks/debian/repo_fetcher.py", line 36, in <module>
main()
File "/home/jldupont/workspace/jldupont/trunk/site/app/server/tasks/debian/repo_fetcher.py", line 30, in main
gziph=gzip.open(fh,'r')
File "/usr/lib/python2.5/gzip.py", line 49, in open
return GzipFile(filename, mode, compresslevel)
File "/usr/lib/python2.5/gzip.py", line 95, in __init__
fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb')
TypeError: coercing to Unicode: need string or buffer, cStringIO.StringI found
</code></pre>
| 20 | 2009-10-09T13:09:12Z | 18,319,515 | <p>If your data is already in a string, try zlib, which claims to be fully gzip compatible:</p>
<pre><code>import zlib
decompressed_data = zlib.decompress(gz_data, 16+zlib.MAX_WBITS)
</code></pre>
<p>Read more: <a href="http://docs.python.org/library/zlib.html">http://docs.python.org/library/zlib.html</a>â</p>
| 17 | 2013-08-19T17:21:45Z | [
"python",
"gzip"
] |
Comprehensions in Python and Javascript are only very basic? | 1,543,820 | <p>Looking at comprehensions in Python and Javascript, so far I can't see some of the main features that I consider most powerful in comprehensions in languages like Haskell. </p>
<p>Do they allow things like multiple generators? Or are they just a basic map-filter form?</p>
<p>If they don't allow multiple generators, I find them quite disappointing - why have such things been left out?</p>
| 6 | 2009-10-09T13:39:13Z | 1,543,844 | <p>Yes, you can have multiple iterables in a <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow">Python list comprehension</a>:</p>
<pre><code>>>> [(x,y) for x in range(2) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
</code></pre>
| 3 | 2009-10-09T13:42:04Z | [
"javascript",
"python",
"haskell",
"list-comprehension"
] |
Comprehensions in Python and Javascript are only very basic? | 1,543,820 | <p>Looking at comprehensions in Python and Javascript, so far I can't see some of the main features that I consider most powerful in comprehensions in languages like Haskell. </p>
<p>Do they allow things like multiple generators? Or are they just a basic map-filter form?</p>
<p>If they don't allow multiple generators, I find them quite disappointing - why have such things been left out?</p>
| 6 | 2009-10-09T13:39:13Z | 1,543,870 | <p>Python allows multiple generators:</p>
<pre><code>>>> [(x,y,x*y) for x in range(1,5) for y in range(1,5)]
[(1, 1, 1), (1, 2, 2), (1, 3, 3), (1, 4, 4),
(2, 1, 2), (2, 2, 4), (2, 3, 6), (2, 4, 8),
(3, 1, 3), (3, 2, 6), (3, 3, 9), (3, 4, 12),
(4, 1, 4), (4, 2, 8), (4, 3, 12), (4, 4, 16)]
</code></pre>
<p>And also restrictions:</p>
<pre><code>>>> [(x,y,x*y) for x in range(1,5) for y in range(1,5) if x*y > 8]
[(3, 3, 9), (3, 4, 12), (4, 3, 12), (4, 4, 16)]
</code></pre>
<p><b>Update</b>: Javascript's syntax is similar (results from using the <a href="http://squarefree.com/shell/" rel="nofollow">javascript shell</a> on firefox):</p>
<pre><code>var nums = [1, 2, 3, 21, 22, 30];
var s = eval('[[i,j] for each (i in nums) for each (j in [3,4]) if (i%2 == 0)]');
s.toSource();
[[2, 3], [2, 4], [22, 3], [22, 4], [30, 3], [30, 4]]
</code></pre>
<p>(For some reason, something about the context stuff is evaluated in in the javascript shell requires the eval indirection to have list comprehensions work. Javascript inside a <code><script></code> tag doesn't require that, of course)</p>
| 12 | 2009-10-09T13:44:43Z | [
"javascript",
"python",
"haskell",
"list-comprehension"
] |
Comprehensions in Python and Javascript are only very basic? | 1,543,820 | <p>Looking at comprehensions in Python and Javascript, so far I can't see some of the main features that I consider most powerful in comprehensions in languages like Haskell. </p>
<p>Do they allow things like multiple generators? Or are they just a basic map-filter form?</p>
<p>If they don't allow multiple generators, I find them quite disappointing - why have such things been left out?</p>
| 6 | 2009-10-09T13:39:13Z | 1,543,956 | <p>Add an if statement as well...</p>
<pre><code>>>> [(x,y) for x in range(5) for y in range(6) if x % 3 == 0 and y % 2 == 0]
[(0, 0), (0, 2), (0, 4), (3, 0), (3, 2), (3, 4)]
</code></pre>
| 1 | 2009-10-09T13:58:33Z | [
"javascript",
"python",
"haskell",
"list-comprehension"
] |
Comprehensions in Python and Javascript are only very basic? | 1,543,820 | <p>Looking at comprehensions in Python and Javascript, so far I can't see some of the main features that I consider most powerful in comprehensions in languages like Haskell. </p>
<p>Do they allow things like multiple generators? Or are they just a basic map-filter form?</p>
<p>If they don't allow multiple generators, I find them quite disappointing - why have such things been left out?</p>
| 6 | 2009-10-09T13:39:13Z | 1,543,985 | <p>Comprehensions is very powerful in Haskell to a large extent because Haskell is functional, so it makes extremely much sense for them to be. Python is not functional so it makes less sense.</p>
<p>You can make a lot of complex things with comprehensions in Python but it quickly becomes hard to read, thereby defeating the whole purpose (meaning you should do it some other way).</p>
<p>However, as pointed out here, python does allow multiple generators in comprehensions.</p>
| 1 | 2009-10-09T14:04:48Z | [
"javascript",
"python",
"haskell",
"list-comprehension"
] |
How to insert repeated message in google protocol buffer _pb2.py file | 1,543,904 | <p>How to insert repeated message in google protocol buffer _pb2.py file</p>
| 0 | 2009-10-09T13:49:15Z | 1,770,798 | <p>make changes to your .proto file. Look at the example : <a href="http://code.google.com/apis/protocolbuffers/docs/pythontutorial.html" rel="nofollow">http://code.google.com/apis/protocolbuffers/docs/pythontutorial.html</a></p>
| 0 | 2009-11-20T14:31:18Z | [
"python",
"buffer",
"protocols"
] |
Force another program's standard output to be unbuffered using Python | 1,544,050 | <p>A python script is controlling an external application on Linux, passing in input via a pipe to the external applications stdin, and reading output via a pipe from the external applications stdout. </p>
<p>The problem is that writes to pipes are buffered by block, and not by line, and therefore delays occur before the controlling script receives data output by, for example, printf in the external application.</p>
<p>The external application cannot be altered to add explicit fflush(0) calls.</p>
<p>How can the <a href="http://python.org/doc/2.3.5/lib/module-pty.html" rel="nofollow">pty</a> module of the python standard library be used with the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> module to achieve this?</p>
| 11 | 2009-10-09T14:15:36Z | 1,544,155 | <p>Try running the Python interpreter with the -u argument:</p>
<pre><code>python -u myscript.py
</code></pre>
<p>This forces Python to use unbuffered stdin/stdout which may help you.</p>
| -1 | 2009-10-09T14:33:28Z | [
"python",
"linux",
"pipe",
"stdout"
] |
Force another program's standard output to be unbuffered using Python | 1,544,050 | <p>A python script is controlling an external application on Linux, passing in input via a pipe to the external applications stdin, and reading output via a pipe from the external applications stdout. </p>
<p>The problem is that writes to pipes are buffered by block, and not by line, and therefore delays occur before the controlling script receives data output by, for example, printf in the external application.</p>
<p>The external application cannot be altered to add explicit fflush(0) calls.</p>
<p>How can the <a href="http://python.org/doc/2.3.5/lib/module-pty.html" rel="nofollow">pty</a> module of the python standard library be used with the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> module to achieve this?</p>
| 11 | 2009-10-09T14:15:36Z | 1,544,178 | <p>I don't think it's possible. If the source application doesn't flush its outgoing buffer, the data will not reach outside that process until the buffer overflows and a flush is forced.</p>
<p>Notice how a well-established command such as <a href="http://linux.about.com/library/cmd/blcmdl1%5Ffile.htm" rel="nofollow">file</a> has an option (-n) that causes it to flush its output explicitly. This is required when using file in the mode where it reads input file names from a pipe, and prints the detected type. Since in this mode, the file program doesn't quit when done, the output would otherwise not appear.</p>
<p>Consider this at a lower level: the output buffering simply means that doing <code>write()</code> on a buffered stream copies the data into an in-memory buffer, until the buffer fills up or (typically) until a linefeed is found. Then, the part of the buffer up to the overflow or linefeed is written <code>write()</code>n to the underlying system-level file descriptor (which could be a file, a pipe, a socket, ...).</p>
<p>I don't understand how you're going to convince that program to flush its buffer, from the outside.</p>
| 3 | 2009-10-09T14:36:23Z | [
"python",
"linux",
"pipe",
"stdout"
] |
Force another program's standard output to be unbuffered using Python | 1,544,050 | <p>A python script is controlling an external application on Linux, passing in input via a pipe to the external applications stdin, and reading output via a pipe from the external applications stdout. </p>
<p>The problem is that writes to pipes are buffered by block, and not by line, and therefore delays occur before the controlling script receives data output by, for example, printf in the external application.</p>
<p>The external application cannot be altered to add explicit fflush(0) calls.</p>
<p>How can the <a href="http://python.org/doc/2.3.5/lib/module-pty.html" rel="nofollow">pty</a> module of the python standard library be used with the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> module to achieve this?</p>
| 11 | 2009-10-09T14:15:36Z | 1,544,661 | <p>Doing this is possible, but the only solution I can think of is fairly convoluted, non-portable, and probably fraught with problematic details. You can use LD_PRELOAD to cause the external application to load a dynamic library which contains a constructor that invokes setvbuf to unbuffer stdout. You will probably also want to wrap setvbuf in the library to prevent the application from explicitly buffering its own stdout. And you'll want to wrap fwrite and printf so that they flush on each call. Writing the .so to be preloaded will take you outside of python. </p>
| 5 | 2009-10-09T15:58:32Z | [
"python",
"linux",
"pipe",
"stdout"
] |
Force another program's standard output to be unbuffered using Python | 1,544,050 | <p>A python script is controlling an external application on Linux, passing in input via a pipe to the external applications stdin, and reading output via a pipe from the external applications stdout. </p>
<p>The problem is that writes to pipes are buffered by block, and not by line, and therefore delays occur before the controlling script receives data output by, for example, printf in the external application.</p>
<p>The external application cannot be altered to add explicit fflush(0) calls.</p>
<p>How can the <a href="http://python.org/doc/2.3.5/lib/module-pty.html" rel="nofollow">pty</a> module of the python standard library be used with the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> module to achieve this?</p>
| 11 | 2009-10-09T14:15:36Z | 1,544,690 | <p>Its worth noting that some programs only buffer their output when they think it's not going to a "real user" (ie, a tty). When they detect that their output is being read by another program, they buffer.</p>
<p>The emulation of a tty is one of the things that <a href="http://expect.nist.gov/" rel="nofollow">Expect</a> does in automating other processes.</p>
<p>There is a <a href="http://sourceforge.net/projects/pexpect/" rel="nofollow">pure Python implementation of Expect</a>, but I don't know how well it handles tty emulation.</p>
| 2 | 2009-10-09T16:02:16Z | [
"python",
"linux",
"pipe",
"stdout"
] |
Force another program's standard output to be unbuffered using Python | 1,544,050 | <p>A python script is controlling an external application on Linux, passing in input via a pipe to the external applications stdin, and reading output via a pipe from the external applications stdout. </p>
<p>The problem is that writes to pipes are buffered by block, and not by line, and therefore delays occur before the controlling script receives data output by, for example, printf in the external application.</p>
<p>The external application cannot be altered to add explicit fflush(0) calls.</p>
<p>How can the <a href="http://python.org/doc/2.3.5/lib/module-pty.html" rel="nofollow">pty</a> module of the python standard library be used with the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> module to achieve this?</p>
| 11 | 2009-10-09T14:15:36Z | 1,547,764 | <p>You can use PTYs to solve this by:</p>
<ul>
<li>Creating a pty master/slave pair;</li>
<li>Connecting the child process's stdin, stdout and stderr to the pty slave device;</li>
<li>Reading from and writing to the pty master in the parent.</li>
</ul>
| 5 | 2009-10-10T11:56:37Z | [
"python",
"linux",
"pipe",
"stdout"
] |
Force another program's standard output to be unbuffered using Python | 1,544,050 | <p>A python script is controlling an external application on Linux, passing in input via a pipe to the external applications stdin, and reading output via a pipe from the external applications stdout. </p>
<p>The problem is that writes to pipes are buffered by block, and not by line, and therefore delays occur before the controlling script receives data output by, for example, printf in the external application.</p>
<p>The external application cannot be altered to add explicit fflush(0) calls.</p>
<p>How can the <a href="http://python.org/doc/2.3.5/lib/module-pty.html" rel="nofollow">pty</a> module of the python standard library be used with the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> module to achieve this?</p>
| 11 | 2009-10-09T14:15:36Z | 6,270,326 | <p>The answer to this question might help:</p>
<p><a href="http://stackoverflow.com/questions/5411780/python-run-a-daemon-sub-process-read-stdout">Python Run a daemon sub-process & read stdout</a></p>
<p>Seems to be addressing the same issue.</p>
| 2 | 2011-06-07T19:07:53Z | [
"python",
"linux",
"pipe",
"stdout"
] |
Force another program's standard output to be unbuffered using Python | 1,544,050 | <p>A python script is controlling an external application on Linux, passing in input via a pipe to the external applications stdin, and reading output via a pipe from the external applications stdout. </p>
<p>The problem is that writes to pipes are buffered by block, and not by line, and therefore delays occur before the controlling script receives data output by, for example, printf in the external application.</p>
<p>The external application cannot be altered to add explicit fflush(0) calls.</p>
<p>How can the <a href="http://python.org/doc/2.3.5/lib/module-pty.html" rel="nofollow">pty</a> module of the python standard library be used with the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> module to achieve this?</p>
| 11 | 2009-10-09T14:15:36Z | 9,477,623 | <p>This question is a bit old, but I think your problem could now be solved by using subprocess to call <a href="http://www.pixelbeat.org/programming/stdio_buffering/stdbuf-man.html" rel="nofollow">stdbuf</a> with the command you want to exec.</p>
| 1 | 2012-02-28T06:50:45Z | [
"python",
"linux",
"pipe",
"stdout"
] |
Non-intrusively unlock file on Windows | 1,544,275 | <p>Is there a way to unlock a file on Windows with a Python script? The file is exclusively locked by another process. I need a solution without killing or interupting the locking process.</p>
<p>I already had a look at <a href="http://code.activestate.com/recipes/65203/" rel="nofollow">portalocker</a>, a portable locking implementation. But this needs a file handle to unlock, which I can not get, as the file is already locked by the locking process.</p>
<p>If there is no way, could someone lead me to the Windows API doc which describes the problem further?</p>
| 1 | 2009-10-09T14:48:24Z | 1,544,308 | <p><a href="http://technet.microsoft.com/en-us/magazine/2009.04.windowsconfidential.aspx">Bad idea</a></p>
| 9 | 2009-10-09T14:52:22Z | [
"python",
"windows",
"file",
"winapi",
"locking"
] |
Non-intrusively unlock file on Windows | 1,544,275 | <p>Is there a way to unlock a file on Windows with a Python script? The file is exclusively locked by another process. I need a solution without killing or interupting the locking process.</p>
<p>I already had a look at <a href="http://code.activestate.com/recipes/65203/" rel="nofollow">portalocker</a>, a portable locking implementation. But this needs a file handle to unlock, which I can not get, as the file is already locked by the locking process.</p>
<p>If there is no way, could someone lead me to the Windows API doc which describes the problem further?</p>
| 1 | 2009-10-09T14:48:24Z | 1,544,319 | <p>Anything you do will affect the other process if that process thinks it has a lock on the file then breaking the lock means that the program has unexpected brhaviour and could brek or corrupt things.</p>
<p>Thus only do this if you know exactly what will happen.</p>
<p>The api used by the other program probably uses <a href="http://msdn.microsoft.com/en-us/library/aa365203%28VS.85%29.aspx" rel="nofollow">msdn LockFile</a></p>
| 0 | 2009-10-09T14:55:16Z | [
"python",
"windows",
"file",
"winapi",
"locking"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.