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 |
|---|---|---|---|---|---|---|---|---|---|
Python .sort() not working as expected | 1,513,727 | <p>Tackling a few puzzle problems on a quiet Saturday night (wooohoo... not) and am struggling with sort(). The results aren't quite what I expect. The program iterates through every combination from 100 - 999 and checks if the product is a palindome. If it is, append to the list. I need the list sorted :D Here's my program:</p>
<pre><code>list = [] #list of numbers
for x in xrange(100,1000): #loops for first value of combination
for y in xrange(x,1000): #and 2nd value
mult = x*y
reversed = str(mult)[::-1] #reverses the number
if (reversed == str(mult)):
list.append(reversed)
list.sort()
print list[:10]
</code></pre>
<p>which nets:</p>
<pre><code>['101101', '10201', '102201', '102201', '105501', '105501', '106601', '108801',
'108801', '110011']
</code></pre>
<p>Clearly index 0 is larger then 1. Any idea what's going on? I have a feeling it's got something to do with trailing/leading zeroes, but I had a quick look and I can't see the problem.</p>
<p>Bonus points if you know where the puzzle comes from :P</p>
| 3 | 2009-10-03T13:22:03Z | 1,513,745 | <p>Your list contains strings so it is sorting them alphabetically - try converting the list to integers and then do the sort.</p>
| 2 | 2009-10-03T13:28:08Z | [
"python",
"list",
"sorting"
] |
Python .sort() not working as expected | 1,513,727 | <p>Tackling a few puzzle problems on a quiet Saturday night (wooohoo... not) and am struggling with sort(). The results aren't quite what I expect. The program iterates through every combination from 100 - 999 and checks if the product is a palindome. If it is, append to the list. I need the list sorted :D Here's my program:</p>
<pre><code>list = [] #list of numbers
for x in xrange(100,1000): #loops for first value of combination
for y in xrange(x,1000): #and 2nd value
mult = x*y
reversed = str(mult)[::-1] #reverses the number
if (reversed == str(mult)):
list.append(reversed)
list.sort()
print list[:10]
</code></pre>
<p>which nets:</p>
<pre><code>['101101', '10201', '102201', '102201', '105501', '105501', '106601', '108801',
'108801', '110011']
</code></pre>
<p>Clearly index 0 is larger then 1. Any idea what's going on? I have a feeling it's got something to do with trailing/leading zeroes, but I had a quick look and I can't see the problem.</p>
<p>Bonus points if you know where the puzzle comes from :P</p>
| 3 | 2009-10-03T13:22:03Z | 1,513,749 | <p>The comparator operator is treating your input as strings instead of integers. In string comparsion 2 as the 3rd letter is lexically greater than 1.
<code>
reversed = str(mult)[::-1]
</code></p>
| 0 | 2009-10-03T13:28:52Z | [
"python",
"list",
"sorting"
] |
Python .sort() not working as expected | 1,513,727 | <p>Tackling a few puzzle problems on a quiet Saturday night (wooohoo... not) and am struggling with sort(). The results aren't quite what I expect. The program iterates through every combination from 100 - 999 and checks if the product is a palindome. If it is, append to the list. I need the list sorted :D Here's my program:</p>
<pre><code>list = [] #list of numbers
for x in xrange(100,1000): #loops for first value of combination
for y in xrange(x,1000): #and 2nd value
mult = x*y
reversed = str(mult)[::-1] #reverses the number
if (reversed == str(mult)):
list.append(reversed)
list.sort()
print list[:10]
</code></pre>
<p>which nets:</p>
<pre><code>['101101', '10201', '102201', '102201', '105501', '105501', '106601', '108801',
'108801', '110011']
</code></pre>
<p>Clearly index 0 is larger then 1. Any idea what's going on? I have a feeling it's got something to do with trailing/leading zeroes, but I had a quick look and I can't see the problem.</p>
<p>Bonus points if you know where the puzzle comes from :P</p>
| 3 | 2009-10-03T13:22:03Z | 1,513,790 | <p>Sort is doing its job. If you intended to store integers in the list, take Lukáš advice. You can also tell sort how to sort, for example by making ints:</p>
<pre><code>list.sort(key=int)
</code></pre>
<p>the key parameter takes a function that calculates an item to take the list object's place in all comparisons. An integer will compare numerically as you expect.</p>
<p>(By the way, <code>list</code> is a really bad variable name, as you override the builtin list() type!)</p>
| 8 | 2009-10-03T13:45:35Z | [
"python",
"list",
"sorting"
] |
Python .sort() not working as expected | 1,513,727 | <p>Tackling a few puzzle problems on a quiet Saturday night (wooohoo... not) and am struggling with sort(). The results aren't quite what I expect. The program iterates through every combination from 100 - 999 and checks if the product is a palindome. If it is, append to the list. I need the list sorted :D Here's my program:</p>
<pre><code>list = [] #list of numbers
for x in xrange(100,1000): #loops for first value of combination
for y in xrange(x,1000): #and 2nd value
mult = x*y
reversed = str(mult)[::-1] #reverses the number
if (reversed == str(mult)):
list.append(reversed)
list.sort()
print list[:10]
</code></pre>
<p>which nets:</p>
<pre><code>['101101', '10201', '102201', '102201', '105501', '105501', '106601', '108801',
'108801', '110011']
</code></pre>
<p>Clearly index 0 is larger then 1. Any idea what's going on? I have a feeling it's got something to do with trailing/leading zeroes, but I had a quick look and I can't see the problem.</p>
<p>Bonus points if you know where the puzzle comes from :P</p>
| 3 | 2009-10-03T13:22:03Z | 1,721,461 | <p>No need to convert to int. mult already is an int and as you have checked it is a palindrome it will look the same as reversed, so just:</p>
<pre><code>list.append(mult)
</code></pre>
| 1 | 2009-11-12T11:04:10Z | [
"python",
"list",
"sorting"
] |
How to get a http page using mechanize cookies? | 1,513,823 | <p>There is a Python mechanize object with a form with almost all values set, but not yet submitted. Now I want to fetch another page using cookies from mechanize instance, but without resetting the page, forms and so on, e.g. so that the values remain set (I just need to get body string of another page, nothing else). So is there a way to:</p>
<ol>
<li>Tell mechanize not to reset the page (perhaps, through <code>UserAgentBase</code>)?</li>
<li>Make <code>urllib2</code> use mechanize's cookie jar? NB: <code>urllib2.HTTPCookieProcessor(self.br._ua_handlers["_cookies"].cookiejar)</code> doesn't work</li>
<li>Any other way to pass cookie to <code>urllib</code>?</li>
</ol>
| 3 | 2009-10-03T14:08:10Z | 1,513,870 | <p>No idea whether this will work, but why don't you try deepcopying the mechanize instance, eg</p>
<pre><code>from copy import deepcopy
br = Browser()
br.open("http://www.example.com/")
# Make a copy for doing other stuff with
br2 = deepcopy(br)
# Do stuff with br2
# Now do stuff with br
</code></pre>
| 2 | 2009-10-03T14:29:37Z | [
"python",
"mechanize"
] |
How to get a http page using mechanize cookies? | 1,513,823 | <p>There is a Python mechanize object with a form with almost all values set, but not yet submitted. Now I want to fetch another page using cookies from mechanize instance, but without resetting the page, forms and so on, e.g. so that the values remain set (I just need to get body string of another page, nothing else). So is there a way to:</p>
<ol>
<li>Tell mechanize not to reset the page (perhaps, through <code>UserAgentBase</code>)?</li>
<li>Make <code>urllib2</code> use mechanize's cookie jar? NB: <code>urllib2.HTTPCookieProcessor(self.br._ua_handlers["_cookies"].cookiejar)</code> doesn't work</li>
<li>Any other way to pass cookie to <code>urllib</code>?</li>
</ol>
| 3 | 2009-10-03T14:08:10Z | 1,513,899 | <p>Some wild ideas:</p>
<ul>
<li>Fetch the second page before filling in the form? </li>
<li>Or fetch the new page and then goBack()? Although maybe that will reset the values.</li>
</ul>
| 2 | 2009-10-03T14:39:21Z | [
"python",
"mechanize"
] |
How to get a http page using mechanize cookies? | 1,513,823 | <p>There is a Python mechanize object with a form with almost all values set, but not yet submitted. Now I want to fetch another page using cookies from mechanize instance, but without resetting the page, forms and so on, e.g. so that the values remain set (I just need to get body string of another page, nothing else). So is there a way to:</p>
<ol>
<li>Tell mechanize not to reset the page (perhaps, through <code>UserAgentBase</code>)?</li>
<li>Make <code>urllib2</code> use mechanize's cookie jar? NB: <code>urllib2.HTTPCookieProcessor(self.br._ua_handlers["_cookies"].cookiejar)</code> doesn't work</li>
<li>Any other way to pass cookie to <code>urllib</code>?</li>
</ol>
| 3 | 2009-10-03T14:08:10Z | 1,514,850 | <p>And the correct answer:</p>
<pre><code>opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.br._ua_handlers["_cookies"].cookiejar))
opener.open(imgurl)
</code></pre>
| 5 | 2009-10-03T21:03:46Z | [
"python",
"mechanize"
] |
Python Implementation of the Object Pool Design Pattern | 1,514,120 | <p>I need an <a href="http://en.wikipedia.org/wiki/Object_pool">Object Pool</a>, and rather than implement it myself, I thought I would look around for a ready-made and tested Python library.</p>
<p>What I found was plenty of other people <a href="http://mail.python.org/pipermail/python-list/2009-July/719988.html">looking</a>, but not getting many straight answers, so I have brought it over here to Stack Overflow.</p>
<p>In my case, I have a large number of threads (using the <code>threading</code> module), which need to occasionally call a remote SOAP-based server. They could each establish their own connection to the server, but setting up a socket and completing the authentication process is expensive (it is throttled by the server), so I want to share a pool of connections, creating more only as needed.</p>
<p>If the items to pool were worker subprocesses, I might have chosen <code>multiprocessing.pool</code>, but they are not. If they were worker threads, I might have chosen <a href="http://code.activestate.com/recipes/203871/">this implementation</a>, but they are not.</p>
<p>If they were MySQL connections, I might have chosen <a href="http://code.google.com/p/pysqlpool/">pysqlpool</a>, but they are not. Similarly the <a href="http://www.sqlalchemy.org/docs/04/pooling.html">SQLAlchemy Pool</a> is out.</p>
<p>If there was one thread, using a variable number of connections/objects, I would consider <a href="http://www.devpicayune.com/entry/object-pooling-in-python">this implementation</a>, but I need it to be thread-safe.</p>
<p>I know I could implement this again fairly quickly, but given there are many people looking for it, I thought a canonical answer on Stack Overflow would be nice.</p>
| 18 | 2009-10-03T15:55:44Z | 1,514,269 | <p>It seems to me, from your description, that what you need is a pool of <em>connections</em>, not of objects. For simple thread-safety, just keep the reusable connections in a <code>Queue.Queue</code> instance, call it <code>pool</code>. When a thread instantiates a connection-wrapping object, the object gets its connection via <code>pool.get()</code> (which automaticaly enqueues it to wait if there are no connections currently availabe and dequeues it when a connection's ready for it); when the object's done using its connection, it puts it back in the pool via <code>pool.put</code>.</p>
<p>There's so little universally-required, general-purpose functionality in this, beyond what <code>Queue.Queue</code> already gives you, that it's not surprising no module providing it is well known or popular -- hard to make a module widespread when it has about 6 lines of functional code in all (e.g. to call a user-supplied connection factory to populate the queue either in advance or just-in-time up to some maximum number -- not a big added value generally, anyway). "Thick glue", thickly wrapping the underlying functionality from a standard library module without substantial added value, is an architectural minus, after all;-).</p>
| 20 | 2009-10-03T16:57:21Z | [
"python",
"design-patterns",
"data-structures"
] |
Python Implementation of the Object Pool Design Pattern | 1,514,120 | <p>I need an <a href="http://en.wikipedia.org/wiki/Object_pool">Object Pool</a>, and rather than implement it myself, I thought I would look around for a ready-made and tested Python library.</p>
<p>What I found was plenty of other people <a href="http://mail.python.org/pipermail/python-list/2009-July/719988.html">looking</a>, but not getting many straight answers, so I have brought it over here to Stack Overflow.</p>
<p>In my case, I have a large number of threads (using the <code>threading</code> module), which need to occasionally call a remote SOAP-based server. They could each establish their own connection to the server, but setting up a socket and completing the authentication process is expensive (it is throttled by the server), so I want to share a pool of connections, creating more only as needed.</p>
<p>If the items to pool were worker subprocesses, I might have chosen <code>multiprocessing.pool</code>, but they are not. If they were worker threads, I might have chosen <a href="http://code.activestate.com/recipes/203871/">this implementation</a>, but they are not.</p>
<p>If they were MySQL connections, I might have chosen <a href="http://code.google.com/p/pysqlpool/">pysqlpool</a>, but they are not. Similarly the <a href="http://www.sqlalchemy.org/docs/04/pooling.html">SQLAlchemy Pool</a> is out.</p>
<p>If there was one thread, using a variable number of connections/objects, I would consider <a href="http://www.devpicayune.com/entry/object-pooling-in-python">this implementation</a>, but I need it to be thread-safe.</p>
<p>I know I could implement this again fairly quickly, but given there are many people looking for it, I thought a canonical answer on Stack Overflow would be nice.</p>
| 18 | 2009-10-03T15:55:44Z | 5,020,415 | <p>I had a similar problem and I must say Queue.Queue is quite good, however there is a missing piece of the puzzle. The following class helps deal with ensuring the object taken gets returned to the pool. Example is included.</p>
<p>I've allowed 2 ways to use this class, with keyword or encapsulating object with destructor. The with keyword is preferred but if you can't / don't want to use it for some reason (most common is the need for multiple objects from multiple queues) at least you have an option. Standard disclaimers about destructor not being called apply if you choose to use that method.</p>
<p>Hopes this helps someone with the same problem as the OP and myself.</p>
<pre><code>class qObj():
_q = None
o = None
def __init__(self, dQ, autoGet = False):
self._q = dQ
if autoGet == True:
self.o = self._q.get()
def __enter__(self):
if self.o == None:
self.o = self._q.get()
return self.o
else:
return self.o
def __exit__(self, type, value, traceback):
if self.o != None:
self._q.put(self.o)
self.o = None
def __del__(self):
if self.o != None:
self._q.put(self.o)
self.o = None
if __name__ == "__main__":
import Queue
def testObj(Q):
someObj = qObj(Q, True)
print 'Inside func: {0}'.format(someObj.o)
aQ = Queue.Queue()
aQ.put("yam")
with qObj(aQ) as obj:
print "Inside with: {0}".format(obj)
print 'Outside with: {0}'.format(aQ.get())
aQ.put("sam")
testObj(aQ)
print 'Outside func: {0}'.format(aQ.get())
'''
Expected Output:
Inside with: yam
Outside with: yam
Inside func: sam
Outside func: sam
'''
</code></pre>
| 3 | 2011-02-16T18:16:32Z | [
"python",
"design-patterns",
"data-structures"
] |
Is it reasonable to save data as python modules? | 1,514,228 | <p>This is what I've done for a project. I have a few data structures that are bascially dictionaries with some methods that operate on the data. When I save them to disk, I write them out to .py files as code that when imported as a module will load the same data into such a data structure.</p>
<p>Is this reasonable? Are there any big disadvantages? The advantage I see is that when I want to operate with the saved data, I can quickly import the modules I need. Also, the modules can be used seperate from the rest of the application because you don't need a separate parser or loader functionality.</p>
| 3 | 2009-10-03T16:40:01Z | 1,514,234 | <p>The biggest drawback is that it's a potential security problem since it's hard to guarantee that the files won't contains arbitrary code, which could be really bad. So don't use this approach if anyone else than you have write-access to the files.</p>
| 3 | 2009-10-03T16:42:14Z | [
"python",
"data-persistence",
"dynamic-import"
] |
Is it reasonable to save data as python modules? | 1,514,228 | <p>This is what I've done for a project. I have a few data structures that are bascially dictionaries with some methods that operate on the data. When I save them to disk, I write them out to .py files as code that when imported as a module will load the same data into such a data structure.</p>
<p>Is this reasonable? Are there any big disadvantages? The advantage I see is that when I want to operate with the saved data, I can quickly import the modules I need. Also, the modules can be used seperate from the rest of the application because you don't need a separate parser or loader functionality.</p>
| 3 | 2009-10-03T16:40:01Z | 1,514,240 | <p>A reasonable option might be to use the <a href="http://docs.python.org/library/pickle.html" rel="nofollow">Pickle</a> module, which is specifically designed to save and restore python structures to disk.</p>
| 3 | 2009-10-03T16:45:48Z | [
"python",
"data-persistence",
"dynamic-import"
] |
Is it reasonable to save data as python modules? | 1,514,228 | <p>This is what I've done for a project. I have a few data structures that are bascially dictionaries with some methods that operate on the data. When I save them to disk, I write them out to .py files as code that when imported as a module will load the same data into such a data structure.</p>
<p>Is this reasonable? Are there any big disadvantages? The advantage I see is that when I want to operate with the saved data, I can quickly import the modules I need. Also, the modules can be used seperate from the rest of the application because you don't need a separate parser or loader functionality.</p>
| 3 | 2009-10-03T16:40:01Z | 1,514,248 | <p>It's reasonable, and I do it all the time. Obviously it's not a format you use to exchange data, so it's not a good format for anything like a save file. </p>
<p>But for example, when I do migrations of websites to Plone, I often get data about the site (such as a list of which pages should be migrated, or a list of how old urls should be mapped to new ones, aor lists of tags). These you typically get in Word och Excel format. Also the data often needs massaging a bit, and I end up with what for all intents and purposes are a dictionaries mapping one URL to some other information.</p>
<p>Sure, I <em>could</em> save that as CVS, and parse it into a dictionary. But instead I typically save it as a Python file with a dictionary. Saves code.</p>
<p>So, yes, it's reasonable, no it's not a format you should use for any sort of save file. It however often used for data that straddles the border to configuration, like above.</p>
| 3 | 2009-10-03T16:48:05Z | [
"python",
"data-persistence",
"dynamic-import"
] |
Is it reasonable to save data as python modules? | 1,514,228 | <p>This is what I've done for a project. I have a few data structures that are bascially dictionaries with some methods that operate on the data. When I save them to disk, I write them out to .py files as code that when imported as a module will load the same data into such a data structure.</p>
<p>Is this reasonable? Are there any big disadvantages? The advantage I see is that when I want to operate with the saved data, I can quickly import the modules I need. Also, the modules can be used seperate from the rest of the application because you don't need a separate parser or loader functionality.</p>
| 3 | 2009-10-03T16:40:01Z | 1,514,250 | <p>By operating this way, you may gain some modicum of convenience, but you pay many kinds of price for that. The space it takes to save your data, and the time it takes to both save and reload it, go up substantially; and your security exposure is unbounded -- you must ferociously guard the paths from which you reload modules, as it would provide an easy avenue for any attacker to inject code of their choice to be executed under your userid (<code>pickle</code> itself is not rock-solid, security-wise, but, compared to this arrangement, it shines;-).</p>
<p>All in all, I prefer a simpler and more traditional arrangement: executable code lives in one module (on a typical code-loading path, that does not need to be R/W once the module's compiled) -- it gets loaded just once and from an already-compiled form. Data live in their own files (or portions of DB, etc) in any of the many suitable formats, mostly standard ones (possibly including multi-language ones such as JSON, CSV, XML, ... &c, if I want to keep the option open to easily load those data from other languages in the future).</p>
| 7 | 2009-10-03T16:48:31Z | [
"python",
"data-persistence",
"dynamic-import"
] |
Is it reasonable to save data as python modules? | 1,514,228 | <p>This is what I've done for a project. I have a few data structures that are bascially dictionaries with some methods that operate on the data. When I save them to disk, I write them out to .py files as code that when imported as a module will load the same data into such a data structure.</p>
<p>Is this reasonable? Are there any big disadvantages? The advantage I see is that when I want to operate with the saved data, I can quickly import the modules I need. Also, the modules can be used seperate from the rest of the application because you don't need a separate parser or loader functionality.</p>
| 3 | 2009-10-03T16:40:01Z | 1,515,466 | <p>Alex Martelli's answer is absolutely insightful and I agree with him. However, I'll go one step further and make a specific recommendation: use JSON.</p>
<p>JSON is simple, and Python's data structures map well into it; and there are several standard libraries and tools for working with JSON. The <code>json</code> module in Python 3.0 and newer is based on <a href="http://pypi.python.org/pypi/simplejson/" rel="nofollow">simplejson</a>, so I would use <code>simplejson</code> in Python 2.x and <code>json</code> in Python 3.0 and newer.</p>
<p>Second choice is XML. XML is more complicated, and harder to just look at (or just edit with a text editor) but there is a vast wealth of tools to validate it, filter it, edit it, etc.</p>
<p>Also, if your data storage and retrieval needs become at all nontrivial, consider using an actual database. <a href="http://sqlite.org/" rel="nofollow">SQLite</a> is terrific: it's small, and for small databases runs very fast, but it is a real actual SQL database. I would definitely use a Python ORM instead of learning SQL to interact with the database; my favorite ORM for SQLite would be <a href="http://autumn-orm.org/" rel="nofollow">Autumn</a> (small and simple), or the ORM from <a href="http://www.djangoproject.com/" rel="nofollow">Django</a> (you don't even need to learn how to create tables in SQL!) Then if you ever outgrow SQLite, you can move up to a real database such as <a href="http://www.postgresql.org/" rel="nofollow">PostgreSQL</a>. If you find yourself writing lots of loops that search through your saved data, and especially if you need to enforce dependencies (such as if foo is deleted, bar must be deleted too) consider going to a database.</p>
| 3 | 2009-10-04T02:44:48Z | [
"python",
"data-persistence",
"dynamic-import"
] |
Installing python module | 1,514,371 | <p>I'm new to python and is trying to install the pyimage module.
<a href="http://code.google.com/p/pyimage/" rel="nofollow">http://code.google.com/p/pyimage/</a></p>
<p>I'm on Windows, and have downloaded and installed 2.6 and 3.1.</p>
<p>I downloaded pyimage, and used cmd and cd to get to its dir.</p>
<p>I then got this:</p>
<pre><code>C:\Users\Jourkey\Desktop\pyimage-0.8.13\pyimage-0.8.13>python setup.py install
'python' is not recognized as an internal or external command,
operable program or batch file.
</code></pre>
<p>How do I install this?</p>
<p>Thanks!</p>
| 0 | 2009-10-03T17:37:47Z | 1,514,395 | <p>It is giving you that error because Python is not in your path. By default, the Python executable is not added to the path. You will have to do it manually. An in-depth tutorial endorsed by the Python website may be found
<a href="http://showmedo.com/videos/video?name=960000&fromSeriesID=96" rel="nofollow">here.</a></p>
| 3 | 2009-10-03T17:42:51Z | [
"python",
"module"
] |
Installing python module | 1,514,371 | <p>I'm new to python and is trying to install the pyimage module.
<a href="http://code.google.com/p/pyimage/" rel="nofollow">http://code.google.com/p/pyimage/</a></p>
<p>I'm on Windows, and have downloaded and installed 2.6 and 3.1.</p>
<p>I downloaded pyimage, and used cmd and cd to get to its dir.</p>
<p>I then got this:</p>
<pre><code>C:\Users\Jourkey\Desktop\pyimage-0.8.13\pyimage-0.8.13>python setup.py install
'python' is not recognized as an internal or external command,
operable program or batch file.
</code></pre>
<p>How do I install this?</p>
<p>Thanks!</p>
| 0 | 2009-10-03T17:37:47Z | 1,514,455 | <p>To put Python on your system's environment PATH variable, so that running python at a command prompt will work, follow the instructions in <a href="http://showmedo.com/videos/video?name=960000&fromSeriesID=96" rel="nofollow">this video</a>.</p>
| 1 | 2009-10-03T18:08:10Z | [
"python",
"module"
] |
GqlQuery OrderBy a property in a ReferenceProperty | 1,514,450 | <p>I don't know how to make a GqlQuery that order by a property of the ReferenceProperty.</p>
<p>In this case, I want to get all the Seat but order by the id of the Room</p>
<p>The GqlQuery reference does not allow a join, so how do you approach in this case?</p>
<pre><code>class Room(db.Model):
id = db.IntegerProperty()
dimension = db.StringProperty(multiline=True)
</code></pre>
<p>a room has many seats, each with an id</p>
<pre><code>class Seat(db.Model):
id = db.IntegerProperty()
roomId = db.ReferenceProperty(Room)
seats_query = GqlQuery("SELECT * FROM Seat ")
seats = seats_query.fetch(1000)
</code></pre>
<p>Alex is right on his point, so I decided not to touch GqlQuery, and tried to play with Django template instead, I have found the solution to sort Seat by Room'id without having to add new field in Seat class. </p>
<p>I put the code here if anyone has interests ;)) Cheers ;))</p>
<pre><code> {% regroup seats|dictsort:"roomId.id" by roomId.id as room_list %}
<ul>
{% for room in room_list %}
<li>Room: {{room.grouper}}
<ul>
{% for item in room.list %}
<li>Seat no: {{item.id}} </li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
</code></pre>
| 1 | 2009-10-03T18:05:44Z | 1,514,466 | <p>In general, to work around non-relational DBs lack of JOIN functionality, you denormalize; specifically, you redundantly put data pieces in more than one place, so they can be effectively accessed in your queries (this does make it more cumbersome to update your store, but then, non-relational DBs in general are heavily slanted to read-mostly applications).</p>
<p>In this case, you add to <code>Seat</code> a property with the room's id -- since you have peculiarly called <code>roomId</code> (rather than, say, <code>room</code>) the <em>reference</em> to the seat's room, I guess you'd have this denormalized bit as <code>roomIdId</code>.</p>
| 0 | 2009-10-03T18:14:55Z | [
"python",
"django",
"google-app-engine"
] |
GqlQuery OrderBy a property in a ReferenceProperty | 1,514,450 | <p>I don't know how to make a GqlQuery that order by a property of the ReferenceProperty.</p>
<p>In this case, I want to get all the Seat but order by the id of the Room</p>
<p>The GqlQuery reference does not allow a join, so how do you approach in this case?</p>
<pre><code>class Room(db.Model):
id = db.IntegerProperty()
dimension = db.StringProperty(multiline=True)
</code></pre>
<p>a room has many seats, each with an id</p>
<pre><code>class Seat(db.Model):
id = db.IntegerProperty()
roomId = db.ReferenceProperty(Room)
seats_query = GqlQuery("SELECT * FROM Seat ")
seats = seats_query.fetch(1000)
</code></pre>
<p>Alex is right on his point, so I decided not to touch GqlQuery, and tried to play with Django template instead, I have found the solution to sort Seat by Room'id without having to add new field in Seat class. </p>
<p>I put the code here if anyone has interests ;)) Cheers ;))</p>
<pre><code> {% regroup seats|dictsort:"roomId.id" by roomId.id as room_list %}
<ul>
{% for room in room_list %}
<li>Room: {{room.grouper}}
<ul>
{% for item in room.list %}
<li>Seat no: {{item.id}} </li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
</code></pre>
| 1 | 2009-10-03T18:05:44Z | 6,353,840 | <p>I think in you case it will work as you want:</p>
<pre><code>class Seat(db.Model):
id = db.IntegerProperty()
roomId = db.ReferenceProperty(Room,collection_name='seats')
</code></pre>
<p>And after that you may use something like this:</p>
<pre><code>rooms = Room.all().order('id')
for room in rooms:
seat_at_room = room.seats.order('id')
</code></pre>
| 0 | 2011-06-15T06:22:33Z | [
"python",
"django",
"google-app-engine"
] |
C#: Does a dictionary in C# have something similar to the Python setdefault? | 1,514,457 | <p>Trying to translate <a href="http://stackoverflow.com/questions/110344/algorithm-to-calculate-the-number-of-divisors-of-a-given-number/118712#118712">some methods</a> written in Python over into C#. The line looks like this:</p>
<pre><code>d[p] = d.setdefault(p, 0) + 1
</code></pre>
<p>What exactly does setdefault do? And is there anything similar I can use in a C# dictionary? Or rather, how can I translate that line into C#?</p>
| 3 | 2009-10-03T18:10:29Z | 1,514,470 | <p>From the <a href="http://docs.python.org/library/stdtypes.html" rel="nofollow">Python docs</a>:</p>
<blockquote>
<p><code>setdefault(key[, default])</code></p>
<p>If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.</p>
</blockquote>
<p>There is no direct implementation of this in the .NET framework, but you can define an extension method:</p>
<pre><code>public static V SetDefault<K,V>(this IDictionary<K,V> dict, K key, V @default)
{
V value;
if (!dict.TryGetValue(key, out value))
{
dict.Add(key, @default);
return @default;
}
else
{
return value;
}
}
</code></pre>
<p>Usage:</p>
<pre><code>string key;
Dictionary<string, int> dict;
dict[key] = dict.SetDefault(key, 0) + 1;
</code></pre>
| 12 | 2009-10-03T18:16:12Z | [
"c#",
"python",
"dictionary"
] |
C#: Does a dictionary in C# have something similar to the Python setdefault? | 1,514,457 | <p>Trying to translate <a href="http://stackoverflow.com/questions/110344/algorithm-to-calculate-the-number-of-divisors-of-a-given-number/118712#118712">some methods</a> written in Python over into C#. The line looks like this:</p>
<pre><code>d[p] = d.setdefault(p, 0) + 1
</code></pre>
<p>What exactly does setdefault do? And is there anything similar I can use in a C# dictionary? Or rather, how can I translate that line into C#?</p>
| 3 | 2009-10-03T18:10:29Z | 1,514,475 | <p>d.setdefault(p, 0) will return the value of the entry with key p if it exists and if it does not then it will set the value for the key p to 0.</p>
| 0 | 2009-10-03T18:21:39Z | [
"c#",
"python",
"dictionary"
] |
C#: Does a dictionary in C# have something similar to the Python setdefault? | 1,514,457 | <p>Trying to translate <a href="http://stackoverflow.com/questions/110344/algorithm-to-calculate-the-number-of-divisors-of-a-given-number/118712#118712">some methods</a> written in Python over into C#. The line looks like this:</p>
<pre><code>d[p] = d.setdefault(p, 0) + 1
</code></pre>
<p>What exactly does setdefault do? And is there anything similar I can use in a C# dictionary? Or rather, how can I translate that line into C#?</p>
| 3 | 2009-10-03T18:10:29Z | 1,514,477 | <p><strong>Edit</strong> -- warning: the following works only for this <em>specific</em> case, <strong>not</strong> for the general case -- see below.</p>
<pre><code>int value = 0;
d.TryGetValue(p, out value);
d[p] = value + 1;
</code></pre>
<p>this is equivalent to the following Python snippet (which is better than the one you show):</p>
<pre><code>d[p] = d.get(p, 0) + 1
</code></pre>
<p><code>setdefault</code> is like <code>get</code> (fetch if present, else use some other value) plus the side effect of injecting the key / other value pair in the dict if the key wasn't present there; but here this side effect is useless, since you're about to assign <code>d[p]</code> anyway, so using <code>setdefault</code> in this case is just goofy (complicates things and slow you down to no good purpose).</p>
<p>In C#, <code>TryGetValue</code>, as the name suggests, tries to get the value corresponding to the key into its <code>out</code> parameter, but, if the key's not present, then it
(<strong>warning: the following phrase is <em>not</em> correct:</strong>)
just leaves said value alone
(<strong>edit:</strong>) What it actually does if the key's not present is <em>not</em> to "leave the value alone" (it can't, since it's an <code>out</code> value; see the comments), but rather to set it to the default value for the type -- here, since 0 (the default value) is what we want, we're fine, but this doesn't make <code>TryGetValue</code> a general-purpose substitute for Python's <code>dict.get</code>.</p>
<p><code>TryGetValue</code> also returns a boolean result, telling you whether it did manage to get the value or not, but you don't need it in this case (just because the default behavior happens to suit us). To build the general equivalent of Python's <code>dict.get</code>, you need another idiom:</p>
<pre><code>if (!TryGetValue(d, k)) {
k = whatyouwant;
}
</code></pre>
<p>Now <em>this</em> idiom is indeed the general-purpose equivalent to Python's <code>k = d.get(k, whatyouwant)</code>.</p>
| 6 | 2009-10-03T18:23:16Z | [
"c#",
"python",
"dictionary"
] |
C#: Does a dictionary in C# have something similar to the Python setdefault? | 1,514,457 | <p>Trying to translate <a href="http://stackoverflow.com/questions/110344/algorithm-to-calculate-the-number-of-divisors-of-a-given-number/118712#118712">some methods</a> written in Python over into C#. The line looks like this:</p>
<pre><code>d[p] = d.setdefault(p, 0) + 1
</code></pre>
<p>What exactly does setdefault do? And is there anything similar I can use in a C# dictionary? Or rather, how can I translate that line into C#?</p>
| 3 | 2009-10-03T18:10:29Z | 3,427,050 | <p>If you want to have the item default to the default instance of object, you might want to consider this (from <a href="http://neofight.wordpress.com/2010/08/06/setdefault-for-c-dictionary-idictionary/" rel="nofollow">here</a>)</p>
<pre><code>public static TValue SetDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
{
TValue result;
if (!dictionary.TryGetValue(key, out result))
{
return dictionary[key] = (TValue)Activator.CreateInstance(typeof(TValue));
}
return result;
}
</code></pre>
<p>This leads to the rather nice syntax of:</p>
<pre><code>var children = new Dictionary<string, List<Node>>();
d.SetDefault(âleftâ).Add(childNode);
</code></pre>
| 1 | 2010-08-06T19:24:50Z | [
"c#",
"python",
"dictionary"
] |
C#: Does a dictionary in C# have something similar to the Python setdefault? | 1,514,457 | <p>Trying to translate <a href="http://stackoverflow.com/questions/110344/algorithm-to-calculate-the-number-of-divisors-of-a-given-number/118712#118712">some methods</a> written in Python over into C#. The line looks like this:</p>
<pre><code>d[p] = d.setdefault(p, 0) + 1
</code></pre>
<p>What exactly does setdefault do? And is there anything similar I can use in a C# dictionary? Or rather, how can I translate that line into C#?</p>
| 3 | 2009-10-03T18:10:29Z | 10,455,782 | <p>I know I'm 3 years late to the party, but a variation that works and is useful:</p>
<pre><code>public static TV SetDefault<TK, TV>(this IDictionary<TK, TV> dict, TK key) where TV: new() {
TV value;
if (!dict.TryGetValue(key, out value)) dict.Add(key, value = new TV());
return value;
}
</code></pre>
<p>That is, for value types that can be initialized without a parameter, do so.</p>
<pre><code>var lookup = new Dictionary<string, HashSet<SomeType>>();
lookup.SetDefault("kittens").Add(mySomeType);
</code></pre>
| 0 | 2012-05-04T20:34:09Z | [
"c#",
"python",
"dictionary"
] |
Fitting a step function | 1,514,484 | <p>I am trying to fit a step function using scipy.optimize.leastsq. Consider the following example:</p>
<pre><code>import numpy as np
from scipy.optimize import leastsq
def fitfunc(p, x):
y = np.zeros(x.shape)
y[x < p[0]] = p[1]
y[p[0] < x] = p[2]
return y
errfunc = lambda p, x, y: fitfunc(p, x) - y # Distance to the target function
x = np.arange(1000)
y = np.random.random(1000)
y[x < 250.] -= 10
p0 = [500.,0.,0.]
p1, success = leastsq(errfunc, p0, args=(x, y))
print p1
</code></pre>
<p>the parameters are the location of the step and the level on either side. What's strange is that the first free parameter never varies, if you run that scipy will give </p>
<pre><code>[ 5.00000000e+02 -4.49410173e+00 4.88624449e-01]
</code></pre>
<p>when the first parameter would be optimal when set to 250 and the second to -10.</p>
<p>Does anyone have any insight as to why this might not be working and how to get it to work?</p>
<p>If I run</p>
<pre><code>print np.sum(errfunc(p1, x, y)**2.)
print np.sum(errfunc([250.,-10.,0.], x, y)**2.)
</code></pre>
<p>I find:</p>
<pre><code>12547.1054663
320.679545235
</code></pre>
<p>where the first number is what leastsq is finding, and the second is the value for the actual optimal function it should be finding.</p>
| 3 | 2009-10-03T18:28:22Z | 1,514,670 | <p>Most probably your optimization is stuck in a <em>local minima</em>. I don't know what leastsq really works like, but if you give it an initial estimate of (0, 0, 0), it gets stuck there, too.</p>
<p>You can check the gradient at the initial estimate numerically (evaluate at +/- epsilon for a very small epsilon and divide bei 2*epsilon, take difference) and I bet it will be sth around 0.</p>
| 0 | 2009-10-03T19:53:35Z | [
"python",
"scipy",
"curve-fitting",
"best-fit-curve"
] |
Fitting a step function | 1,514,484 | <p>I am trying to fit a step function using scipy.optimize.leastsq. Consider the following example:</p>
<pre><code>import numpy as np
from scipy.optimize import leastsq
def fitfunc(p, x):
y = np.zeros(x.shape)
y[x < p[0]] = p[1]
y[p[0] < x] = p[2]
return y
errfunc = lambda p, x, y: fitfunc(p, x) - y # Distance to the target function
x = np.arange(1000)
y = np.random.random(1000)
y[x < 250.] -= 10
p0 = [500.,0.,0.]
p1, success = leastsq(errfunc, p0, args=(x, y))
print p1
</code></pre>
<p>the parameters are the location of the step and the level on either side. What's strange is that the first free parameter never varies, if you run that scipy will give </p>
<pre><code>[ 5.00000000e+02 -4.49410173e+00 4.88624449e-01]
</code></pre>
<p>when the first parameter would be optimal when set to 250 and the second to -10.</p>
<p>Does anyone have any insight as to why this might not be working and how to get it to work?</p>
<p>If I run</p>
<pre><code>print np.sum(errfunc(p1, x, y)**2.)
print np.sum(errfunc([250.,-10.,0.], x, y)**2.)
</code></pre>
<p>I find:</p>
<pre><code>12547.1054663
320.679545235
</code></pre>
<p>where the first number is what leastsq is finding, and the second is the value for the actual optimal function it should be finding.</p>
| 3 | 2009-10-03T18:28:22Z | 1,514,730 | <p>It turns out that the fitting is much better if I add the epsfcn= argument to leastsq:</p>
<pre><code>p1, success = leastsq(errfunc, p0, args=(x, y), epsfcn=10.)
</code></pre>
<p>and the result is</p>
<pre><code>[ 248.00000146 -8.8273455 0.40818216]
</code></pre>
<p>My basic understanding is that the first free parameter has to be moved more than the spacing between neighboring points to affect the square of the residuals, and epsfcn has something to do with how big steps to use to find the gradient, or something similar.</p>
| 1 | 2009-10-03T20:15:59Z | [
"python",
"scipy",
"curve-fitting",
"best-fit-curve"
] |
Fitting a step function | 1,514,484 | <p>I am trying to fit a step function using scipy.optimize.leastsq. Consider the following example:</p>
<pre><code>import numpy as np
from scipy.optimize import leastsq
def fitfunc(p, x):
y = np.zeros(x.shape)
y[x < p[0]] = p[1]
y[p[0] < x] = p[2]
return y
errfunc = lambda p, x, y: fitfunc(p, x) - y # Distance to the target function
x = np.arange(1000)
y = np.random.random(1000)
y[x < 250.] -= 10
p0 = [500.,0.,0.]
p1, success = leastsq(errfunc, p0, args=(x, y))
print p1
</code></pre>
<p>the parameters are the location of the step and the level on either side. What's strange is that the first free parameter never varies, if you run that scipy will give </p>
<pre><code>[ 5.00000000e+02 -4.49410173e+00 4.88624449e-01]
</code></pre>
<p>when the first parameter would be optimal when set to 250 and the second to -10.</p>
<p>Does anyone have any insight as to why this might not be working and how to get it to work?</p>
<p>If I run</p>
<pre><code>print np.sum(errfunc(p1, x, y)**2.)
print np.sum(errfunc([250.,-10.,0.], x, y)**2.)
</code></pre>
<p>I find:</p>
<pre><code>12547.1054663
320.679545235
</code></pre>
<p>where the first number is what leastsq is finding, and the second is the value for the actual optimal function it should be finding.</p>
| 3 | 2009-10-03T18:28:22Z | 1,514,752 | <p>I don't think that least squares fitting is the way to go about coming up with an approximation for a step. I don't believe it will give you a satisfactory description of the discontinuity. Least squares would not be my first thought when attacking this problem. </p>
<p>Why wouldn't you use a Fourier series approximation instead? You'll always be stuck with Gibbs' phenomenon at the discontinuity, but the rest of the function can be approximated as well as you and your CPU can afford.</p>
<p>What exactly are you going to use this for? Some context might help.</p>
| 1 | 2009-10-03T20:25:57Z | [
"python",
"scipy",
"curve-fitting",
"best-fit-curve"
] |
Fitting a step function | 1,514,484 | <p>I am trying to fit a step function using scipy.optimize.leastsq. Consider the following example:</p>
<pre><code>import numpy as np
from scipy.optimize import leastsq
def fitfunc(p, x):
y = np.zeros(x.shape)
y[x < p[0]] = p[1]
y[p[0] < x] = p[2]
return y
errfunc = lambda p, x, y: fitfunc(p, x) - y # Distance to the target function
x = np.arange(1000)
y = np.random.random(1000)
y[x < 250.] -= 10
p0 = [500.,0.,0.]
p1, success = leastsq(errfunc, p0, args=(x, y))
print p1
</code></pre>
<p>the parameters are the location of the step and the level on either side. What's strange is that the first free parameter never varies, if you run that scipy will give </p>
<pre><code>[ 5.00000000e+02 -4.49410173e+00 4.88624449e-01]
</code></pre>
<p>when the first parameter would be optimal when set to 250 and the second to -10.</p>
<p>Does anyone have any insight as to why this might not be working and how to get it to work?</p>
<p>If I run</p>
<pre><code>print np.sum(errfunc(p1, x, y)**2.)
print np.sum(errfunc([250.,-10.,0.], x, y)**2.)
</code></pre>
<p>I find:</p>
<pre><code>12547.1054663
320.679545235
</code></pre>
<p>where the first number is what leastsq is finding, and the second is the value for the actual optimal function it should be finding.</p>
| 3 | 2009-10-03T18:28:22Z | 1,515,267 | <p>I propose approximating the step function. Instead of
inifinite slope at the "change point" make it linear over
one x distance (1.0 in the example). E.g. if the x
parameter, xp, for the function is defined as the midpoint
on this line then the value at xp-0.5 is the lower y value
and the value at xp+0.5 is the higher y value and
intermediate values of the function in the
interval [xp-0.5; xp+0.5] is a linear
interpolation between these two points.</p>
<p>If it can be assumed that the step function (or its
approximation) goes from a lower value to a higher value
then I think the initial guess for the last two parameters
should be the lowest y value and the highest y value
respectively instead of 0.0 and 0.0.</p>
<p><hr /></p>
<p>I have 2 corrections:</p>
<p>1) np.random.random() returns random numbers in the range
0.0 to 1.0. Thus the mean is +0.5 and is also the value of
the third parameter (instead 0.0). And the second paramter
is then -9.5 (+0.5 - 10.0) instead of -10.0.</p>
<p>Thus</p>
<pre><code>print np.sum(errfunc([250.,-10.,0.], x, y)**2.)
</code></pre>
<p>should be</p>
<pre><code>print np.sum(errfunc([250.,-9.5,0.5], x, y)**2.)
</code></pre>
<p>2) In the original fitfunc() one value of y becomes 0.0 if x
is exactly equal to p[0]. Thus it is not a step function in
that case (more like a sum of two step functions). E.g. this
happens when the start value of the first parameter is 500.</p>
| 1 | 2009-10-04T00:43:15Z | [
"python",
"scipy",
"curve-fitting",
"best-fit-curve"
] |
How to declare an array in Python? | 1,514,553 | <p>How do I declare an array in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>?</p>
<p>I can't find any reference to arrays in the documentation. </p>
| 198 | 2009-10-03T19:03:40Z | 1,514,557 | <pre><code>variable = []
</code></pre>
<p>Now <code>variable</code> refers to an empty list<sup>*</sup>.</p>
<p>Of course this is an assignment, not a declaration. There's no way to say in Python "this variable should never refer to anything other than a list", since Python is dynamically typed.</p>
<hr>
<p><sup>*</sup>The default built-in Python type is called a <em>list</em>, not an array. It is an ordered container of arbitrary length that can hold a heterogenous collection of objects (their types do not matter and can be freely mixed). This should not be confused with the <a href="https://docs.python.org/2/library/array.html"><code>array</code> module</a>, which offers a type closer to the C <code>array</code> type; the contents must be homogenous (all of the same type), but the length is still dynamic.</p>
| 168 | 2009-10-03T19:07:12Z | [
"python",
"arrays"
] |
How to declare an array in Python? | 1,514,553 | <p>How do I declare an array in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>?</p>
<p>I can't find any reference to arrays in the documentation. </p>
| 198 | 2009-10-03T19:03:40Z | 1,514,559 | <p>This is how:</p>
<pre><code>my_array = [1, 'rebecca', 'allard', 15]
</code></pre>
| 12 | 2009-10-03T19:07:49Z | [
"python",
"arrays"
] |
How to declare an array in Python? | 1,514,553 | <p>How do I declare an array in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>?</p>
<p>I can't find any reference to arrays in the documentation. </p>
| 198 | 2009-10-03T19:03:40Z | 1,514,561 | <p>You don't declare anything in Python. You just use it. I recommend you start out with something like <a href="http://diveintopython.net">http://diveintopython.net</a>.</p>
| 15 | 2009-10-03T19:08:05Z | [
"python",
"arrays"
] |
How to declare an array in Python? | 1,514,553 | <p>How do I declare an array in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>?</p>
<p>I can't find any reference to arrays in the documentation. </p>
| 198 | 2009-10-03T19:03:40Z | 1,514,564 | <p>I would normally just do <code>a = [1,2,3]</code> which is actually a <code>list</code> but for <code>arrays</code> look at this formal <a href="http://docs.python.org/library/array.html">definition</a></p>
| 9 | 2009-10-03T19:09:13Z | [
"python",
"arrays"
] |
How to declare an array in Python? | 1,514,553 | <p>How do I declare an array in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>?</p>
<p>I can't find any reference to arrays in the documentation. </p>
| 198 | 2009-10-03T19:03:40Z | 1,514,649 | <p>You don't actually declare things, but this is how you create an array in Python:</p>
<pre><code>from array import array
intarray = array('i')
</code></pre>
<p>For more info see the array module: <a href="http://docs.python.org/library/array.html">http://docs.python.org/library/array.html</a></p>
<p>Now possible you don't want an array, but a list, but others have answered that already. :)</p>
| 56 | 2009-10-03T19:44:18Z | [
"python",
"arrays"
] |
How to declare an array in Python? | 1,514,553 | <p>How do I declare an array in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>?</p>
<p>I can't find any reference to arrays in the documentation. </p>
| 198 | 2009-10-03T19:03:40Z | 1,515,282 | <p>Following on from Lennart, there's also <a href="http://numpy.scipy.org/">numpy</a> which implements homogeneous multi-dimensional arrays.</p>
| 6 | 2009-10-04T00:50:24Z | [
"python",
"arrays"
] |
How to declare an array in Python? | 1,514,553 | <p>How do I declare an array in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>?</p>
<p>I can't find any reference to arrays in the documentation. </p>
| 198 | 2009-10-03T19:03:40Z | 4,476,624 | <p>I think you (meant)want an list with the first 30 cells already filled.
So</p>
<pre><code> f = []
for i in range(30):
f.append(0)
</code></pre>
<p>An example to where this could be used is in Fibonacci sequence.
See problem 2 in <a href="http://projecteuler.net/">Project Euler</a></p>
| 33 | 2010-12-18T04:25:20Z | [
"python",
"arrays"
] |
How to declare an array in Python? | 1,514,553 | <p>How do I declare an array in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>?</p>
<p>I can't find any reference to arrays in the documentation. </p>
| 198 | 2009-10-03T19:03:40Z | 6,768,818 | <p>for calculations, use <a href="http://numpy.scipy.org/">numpy</a> arrays like this:</p>
<pre><code>import numpy as np
a = np.ones((3,2)) # a 2D array with 3 rows, 2 columns, filled with ones
b = np.array([1,2,3]) # a 1D array initialised using a list [1,2,3]
c = np.linspace(2,3,100) # an array with 100 points beteen (and including) 2 and 3
print(a*1.5) # all elements of a times 1.5
print(a.T+b) # b added to the transpose of a
</code></pre>
<p>these numpy arrays can be saved and loaded from disk (even compressed) and complex calculations with large amounts of elements is C-like fast. Much used in scientific environments. See <a href="http://docs.scipy.org/doc/numpy-1.6.0/user/whatisnumpy.html">here</a> for more...</p>
| 9 | 2011-07-20T21:31:58Z | [
"python",
"arrays"
] |
How to declare an array in Python? | 1,514,553 | <p>How do I declare an array in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>?</p>
<p>I can't find any reference to arrays in the documentation. </p>
| 198 | 2009-10-03T19:03:40Z | 13,300,517 | <p>How about this...</p>
<pre><code>>>> a = range(12)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>> a[7]
6
</code></pre>
| 5 | 2012-11-09T00:51:43Z | [
"python",
"arrays"
] |
How to declare an array in Python? | 1,514,553 | <p>How do I declare an array in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>?</p>
<p>I can't find any reference to arrays in the documentation. </p>
| 198 | 2009-10-03T19:03:40Z | 15,822,462 | <p>Python calls them <a href="http://docs.python.org/2/tutorial/introduction.html#lists" rel="nofollow">lists</a>. You can write a list literal with square brackets and commas:</p>
<pre><code>>>> [6,28,496,8128]
[6, 28, 496, 8128]
</code></pre>
| 4 | 2013-04-04T21:55:40Z | [
"python",
"arrays"
] |
How to declare an array in Python? | 1,514,553 | <p>How do I declare an array in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>?</p>
<p>I can't find any reference to arrays in the documentation. </p>
| 198 | 2009-10-03T19:03:40Z | 21,780,274 | <p>I had an array of strings and needed an array of the same length of booleans initiated to True. This is what I did</p>
<pre><code>strs = ["Hi","Bye"]
bools = [ True for s in strs ]
</code></pre>
| 2 | 2014-02-14T13:07:38Z | [
"python",
"arrays"
] |
How to declare an array in Python? | 1,514,553 | <p>How do I declare an array in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>?</p>
<p>I can't find any reference to arrays in the documentation. </p>
| 198 | 2009-10-03T19:03:40Z | 36,042,565 | <p>This is surprisingly complex topic in Python. </p>
<h1>Practical answer</h1>
<p>Arrays are represented by class <code>list</code> (see <a href="https://docs.python.org/2/tutorial/datastructures.html">reference</a> and do not mix them with <a href="https://wiki.python.org/moin/Generators">generators</a>).</p>
<p>Check out usage examples:</p>
<pre><code># empty array
arr = []
# init with values (can contain mixed types)
arr = [1, "eels"]
# get item by index (can be negative to access end of array)
arr = [1, 2, 3, 4, 5, 6]
arr[0] # 1
arr[-1] # 6
# get length
length = len(arr)
# supports append and insert
arr.append(8)
arr.insert(6, 7)
</code></pre>
<h1>Theoretical answer</h1>
<p>Under the hood Python's <code>list</code> is a wrapper for a real array which contains references to items. Also, underlying array is created with some extra space.</p>
<p>Consequences of this are:</p>
<ul>
<li>random access is really cheap (<code>arr[6653]</code> is same to <code>arr[0]</code>)</li>
<li><code>append</code> operation is 'for free' while some extra space</li>
<li><code>insert</code> operation is expensive</li>
</ul>
<p>Check this <a href="https://wiki.python.org/moin/TimeComplexity">awesome table of operations complexity</a>.</p>
<p>Also, please see this picture, where I've tried to show most important differences between array, array of references and linked list:
<a href="http://i.stack.imgur.com/B2Q7K.png"><img src="http://i.stack.imgur.com/B2Q7K.png" alt="arrays, arrays everywhere"></a></p>
| 7 | 2016-03-16T17:16:04Z | [
"python",
"arrays"
] |
How to declare an array in Python? | 1,514,553 | <p>How do I declare an array in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>?</p>
<p>I can't find any reference to arrays in the documentation. </p>
| 198 | 2009-10-03T19:03:40Z | 38,303,109 | <p>To add to Lennart's answer, an array may be created like this:</p>
<pre><code>from array import array
float_array = array("f",values)
</code></pre>
<p>where <em>values</em> can take the form of a tuple, list, or np.array, but not array:</p>
<pre><code>values = [1,2,3]
values = (1,2,3)
values = np.array([1,2,3],'f')
# 'i' will work here too, but if array is 'i' then values have to be int
wrong_values = array('f',[1,2,3])
# TypeError: 'array.array' object is not callable
</code></pre>
<p>and the output will still be the same:</p>
<pre><code>print(float_array)
print(float_array[1])
print(isinstance(float_array[1],float))
# array('f', [1.0, 2.0, 3.0])
# 2.0
# True
</code></pre>
<p>Most methods for list work with array as well, common
ones being pop(), extend(), and append().</p>
<p>Judging from the answers and comments, it appears that the array
data structure isn't that popular. I like it though, the same
way as one might prefer a tuple over a list.</p>
<p>The array structure has stricter rules than a list or np.array, and this can
reduce errors and make debugging easier, especially when working with numerical
data.</p>
<p>Attempts to insert/append a float to an int array will throw a TypeError:</p>
<pre><code>values = [1,2,3]
int_array = array("i",values)
int_array.append(float(1))
# or int_array.extend([float(1)])
# TypeError: integer argument expected, got float
</code></pre>
<p>Keeping values which are meant to be integers (e.g. list of indices) in the array
form may therefore prevent a "TypeError: list indices must be integers, not float", since arrays can be iterated over, similar to np.array and lists:</p>
<pre><code>int_array = array('i',[1,2,3])
data = [11,22,33,44,55]
sample = []
for i in int_array:
sample.append(data[i])
</code></pre>
<p>Annoyingly, appending an int to a float array will cause the int to become a float, without throwing an exception.</p>
<p>np.array retain the same data type for its entries too, but instead of giving an error it will change its data type to fit new entries (usually to double or str):</p>
<pre><code>import numpy as np
numpy_int_array = np.array([1,2,3],'i')
for i in numpy_int_array:
print(type(i))
# <class 'numpy.int32'>
numpy_int_array_2 = np.append(numpy_int_array,int(1))
# still <class 'numpy.int32'>
numpy_float_array = np.append(numpy_int_array,float(1))
# <class 'numpy.float64'> for all values
numpy_str_array = np.append(numpy_int_array,"1")
# <class 'numpy.str_'> for all values
data = [11,22,33,44,55]
sample = []
for i in numpy_int_array_2:
sample.append(data[i])
# no problem here, but TypeError for the other two
</code></pre>
<p>This is true during assignment as well. If the data type is specified, np.array will, wherever possible, transform the entries to that data type:</p>
<pre><code>int_numpy_array = np.array([1,2,float(3)],'i')
# 3 becomes an int
int_numpy_array_2 = np.array([1,2,3.9],'i')
# 3.9 gets truncated to 3 (same as int(3.9))
invalid_array = np.array([1,2,"string"],'i')
# ValueError: invalid literal for int() with base 10: 'string'
# Same error as int('string')
str_numpy_array = np.array([1,2,3],'str')
print(str_numpy_array)
print([type(i) for i in str_numpy_array])
# ['1' '2' '3']
# <class 'numpy.str_'>
</code></pre>
<p>or, in essence:</p>
<pre><code>data = [1.2,3.4,5.6]
list_1 = np.array(data,'i').tolist()
list_2 = [int(i) for i in data]
print(list_1 == list_2)
# True
</code></pre>
<p>while array will simply give:</p>
<pre><code>invalid_array = array([1,2,3.9],'i')
# TypeError: integer argument expected, got float
</code></pre>
<p>Because of this, it is not a good idea to use np.array for type-specific commands. The array structure is useful here. list preserves the data type of the values.</p>
<p>And for something I find rather pesky: the data type is specified as the first argument in array(), but (usually) the second in np.array(). :|</p>
<p>The relation to C is referred to here:
<a href="http://stackoverflow.com/questions/176011/python-list-vs-array-when-to-use">Python List vs. Array - when to use?</a></p>
<p>Have fun exploring!</p>
<p>Note: The typed and rather strict nature of array leans more towards C rather than Python, and by design Python does not have many type-specific constraints in its functions. Its unpopularity also creates a positive feedback in collaborative work, and replacing it mostly involves an additional [int(x) for x in file]. It is therefore entirely viable and reasonable to ignore the existence of array. It shouldn't hinder most of us in any way. :D</p>
| 4 | 2016-07-11T09:09:04Z | [
"python",
"arrays"
] |
How to declare an array in Python? | 1,514,553 | <p>How do I declare an array in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>?</p>
<p>I can't find any reference to arrays in the documentation. </p>
| 198 | 2009-10-03T19:03:40Z | 39,003,823 | <p>A couple of contributions suggested that arrays in python are represented by lists. Perhaps theoretically/under the hood that is correct however a major distinction between the two is the fact that lists accept mixed data types and mixed numeric types, on the other hand array requires a type-code restricting all elements to the determined type:</p>
<pre><code>list_01 = [4, 6.2, 7-2j, 'flo', 'cro']
list_01
Out[85]: [4, 6.2, (7-2j), 'flo', 'cro']
</code></pre>
<p>This is not possible using array().</p>
| 3 | 2016-08-17T18:24:28Z | [
"python",
"arrays"
] |
Neural Network Example Source-code (preferably Python) | 1,514,573 | <p>I wonder if anyone has some example code of a Neural network in python. If someone know of some sort of tutorial with a complete walkthrough that would be awesome, but just example source would be great as well!</p>
<p>Thanks</p>
| 11 | 2009-10-03T19:13:20Z | 1,514,631 | <p>Here is a simple example by Armin Rigo: <a href="http://codespeak.net/pypy/dist/demo/bpnn.py" rel="nofollow">http://codespeak.net/pypy/dist/demo/bpnn.py</a>.
If you want to use more sophisticated stuff, there is also <a href="http://pybrain.org" rel="nofollow">http://pybrain.org</a>.</p>
<p><strong>Edit:</strong> Link is broken. Anyway, the current way to go with neural nets in python is probably <a href="http://deeplearning.net/software/theano/index.html" rel="nofollow">Theano</a>.</p>
| 7 | 2009-10-03T19:35:38Z | [
"python",
"neural-network"
] |
Neural Network Example Source-code (preferably Python) | 1,514,573 | <p>I wonder if anyone has some example code of a Neural network in python. If someone know of some sort of tutorial with a complete walkthrough that would be awesome, but just example source would be great as well!</p>
<p>Thanks</p>
| 11 | 2009-10-03T19:13:20Z | 1,514,671 | <p>Take a look at <a href="http://my.safaribooksonline.com/9780596529321/whats%5Fin%5Fa%5Fsearch%5Fengine#X2ludGVybmFsX1NlY3Rpb25Db250ZW50P3htbGlkPTk3ODA1OTY1MjkzMjEvbGVhcm5pbmdfZnJvbV9jbGlja3M=">Learning from Clicks</a> from the book <a href="http://my.safaribooksonline.com/9780596529321">Programming Collective Intelligence</a>. </p>
| 4 | 2009-10-03T19:53:43Z | [
"python",
"neural-network"
] |
Neural Network Example Source-code (preferably Python) | 1,514,573 | <p>I wonder if anyone has some example code of a Neural network in python. If someone know of some sort of tutorial with a complete walkthrough that would be awesome, but just example source would be great as well!</p>
<p>Thanks</p>
| 11 | 2009-10-03T19:13:20Z | 1,515,871 | <p>You might want to take a look at <a href="http://montepython.sourceforge.net/" rel="nofollow"><strong>Monte</strong></a>:</p>
<blockquote>
<p>Monte (python) is a Python framework
for building gradient based learning
machines, like neural networks,
conditional random fields, logistic
regression, etc. Monte contains
modules (that hold parameters, a
cost-function and a gradient-function)
and trainers (that can adapt a
module's parameters by minimizing its
cost-function on training data).</p>
<p>Modules are usually composed of other
modules, which can in turn contain
other modules, etc. Gradients of
decomposable systems like these can be
computed with back-propagation.</p>
</blockquote>
| 2 | 2009-10-04T07:59:46Z | [
"python",
"neural-network"
] |
Neural Network Example Source-code (preferably Python) | 1,514,573 | <p>I wonder if anyone has some example code of a Neural network in python. If someone know of some sort of tutorial with a complete walkthrough that would be awesome, but just example source would be great as well!</p>
<p>Thanks</p>
| 11 | 2009-10-03T19:13:20Z | 12,436,399 | <p>Found this interresting discusion on ubuntu forums
<a href="http://ubuntuforums.org/showthread.php?t=320257" rel="nofollow">http://ubuntuforums.org/showthread.php?t=320257</a></p>
<pre><code>import time
import random
# Learning rate:
# Lower = slower
# Higher = less precise
rate=.2
# Create random weights
inWeight=[random.uniform(0, 1), random.uniform(0, 1)]
# Start neuron with no stimuli
inNeuron=[0.0, 0.0]
# Learning table (or gate)
test =[[0.0, 0.0, 0.0]]
test+=[[0.0, 1.0, 1.0]]
test+=[[1.0, 0.0, 1.0]]
test+=[[1.0, 1.0, 1.0]]
# Calculate response from neural input
def outNeuron(midThresh):
global inNeuron, inWeight
s=inNeuron[0]*inWeight[0] + inNeuron[1]*inWeight[1]
if s>midThresh:
return 1.0
else:
return 0.0
# Display results of test
def display(out, real):
if out == real:
print str(out)+" should be "+str(real)+" ***"
else:
print str(out)+" should be "+str(real)
while 1:
# Loop through each lesson in the learning table
for i in range(len(test)):
# Stimulate neurons with test input
inNeuron[0]=test[i][0]
inNeuron[1]=test[i][1]
# Adjust weight of neuron #1
# based on feedback, then display
out = outNeuron(2)
inWeight[0]+=rate*(test[i][2]-out)
display(out, test[i][2])
# Adjust weight of neuron #2
# based on feedback, then display
out = outNeuron(2)
inWeight[1]+=rate*(test[i][2]-out)
display(out, test[i][2])
# Delay
time.sleep(1)
</code></pre>
<p>EDIT: there is also a framework named chainer
<a href="https://pypi.python.org/pypi/chainer/1.0.0" rel="nofollow">https://pypi.python.org/pypi/chainer/1.0.0</a></p>
| 4 | 2012-09-15T10:00:25Z | [
"python",
"neural-network"
] |
Neural Network Example Source-code (preferably Python) | 1,514,573 | <p>I wonder if anyone has some example code of a Neural network in python. If someone know of some sort of tutorial with a complete walkthrough that would be awesome, but just example source would be great as well!</p>
<p>Thanks</p>
| 11 | 2009-10-03T19:13:20Z | 18,524,373 | <p>Here is a probabilistic neural network tutorial :<a href="http://www.youtube.com/watch?v=uAKu4g7lBxU" rel="nofollow">http://www.youtube.com/watch?v=uAKu4g7lBxU</a></p>
<p>And my Python Implementation:</p>
<pre><code>import math
data = {'o' : [(0.2, 0.5), (0.5, 0.7)],
'x' : [(0.8, 0.8), (0.4, 0.5)],
'i' : [(0.8, 0.5), (0.6, 0.3), (0.3, 0.2)]}
class Prob_Neural_Network(object):
def __init__(self, data):
self.data = data
def predict(self, new_point, sigma):
res_dict = {}
np = new_point
for k, v in self.data.iteritems():
res_dict[k] = sum(self.gaussian_func(np[0], np[1], p[0], p[1], sigma) for p in v)
return max(res_dict.iteritems(), key=lambda k : k[1])
def gaussian_func(self, x, y, x_0, y_0, sigma):
return math.e ** (-1 *((x - x_0) ** 2 + (y - y_0) ** 2) / ((2 * (sigma ** 2))))
prob_nn = Prob_Neural_Network(data)
res = prob_nn.predict((0.2, 0.6), 0.1)
</code></pre>
<p>Result:</p>
<pre><code>>>> res
('o', 0.6132686067117191)
</code></pre>
| 2 | 2013-08-30T03:19:19Z | [
"python",
"neural-network"
] |
Writing Cocoa applications in Python 3 | 1,514,638 | <p>It looks like PyObjC is not ported to Python 3 yet.</p>
<p>Meanwhile is there a way to write Cocoa applications using Python 3?</p>
<p>I am intending to start a new MacOSX GUI application project and though5 would want to use Python 3.x instead of Python 2.x.</p>
| 1 | 2009-10-03T19:39:32Z | 1,514,697 | <p>For full-blown Cocoa, I think PyObjC is pretty much the only game in town. If you are coming to Cocoa from a Python background rather than to Python from an Obj-C Cocoa background, surely the learning curve of the Cocoa APIs is <em>much</em> steeper than the differences between Python 2.x and Python 3.x. So I think, at the moment, the best strategy is writing your app in Python 2.x while trying to make it as Python 3.x friendly as possible, including periodically running <a href="http://docs.python.org/library/2to3.html" rel="nofollow">2to3</a> on it as a check. And I'm sure <a href="http://pyobjc.sourceforge.net/development.html" rel="nofollow">patches for PyObjC</a> to help with Python 3 support would be very welcome. If you are just looking for simple GUI interfaces rather than a full-blown Cocoa app, you <em>might</em> be able to get by with calls out to other packages like <a href="http://cocoadialog.sourceforge.net/" rel="nofollow">CocoaDialog</a> or a Python 2.x-PyObjC dialog app :=) </p>
| 3 | 2009-10-03T20:04:32Z | [
"python",
"cocoa",
"python-3.x",
"pyobjc"
] |
Display Pretty Code in Django | 1,514,874 | <p>I'm looking for something I can use within django to display preformatted code. Ideally this would include out-of-the-box syntax highlighting for various programming languages, although just starting with something that displayed html and xml well would be a good starting point.</p>
<p>Does something like this exist? </p>
<p>Basically I am looking for something like the widget dpaste (and also stack overflow) use to display code.</p>
<p>e.g. <a href="http://dpaste.com/hold/102141/" rel="nofollow">http://dpaste.com/hold/102141/</a></p>
<p>or </p>
<pre><code><?xml version="1.0" encoding='UTF-8'?>
<painting>
<img src="madonna.jpg" alt='Foligno Madonna, by Raphael'/>
<caption>This is Raphael's "Foligno" Madonna, painted in
<date>1511</date>-<date>1512</date>.</caption>
</painting>
</code></pre>
<p>I'm aware of <a href="http://stackoverflow.com/questions/1432439/display-django-code-from-a-django-template">this question</a>, but mine is not about the mechanics of escaping the code, it's about the UI.</p>
| 3 | 2009-10-03T21:11:56Z | 1,514,879 | <p>You could use <a href="http://pygments.org" rel="nofollow">Pygments</a> to do the syntax highlighting and get HTML to display.</p>
<p>Example code :</p>
<pre><code>from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
highlighted = highlight('# Some Python code', PythonLexer(), HtmlFormatter())
</code></pre>
<p>Also see the <a href="http://pygments.org/docs/" rel="nofollow">official documentation</a>.</p>
| 8 | 2009-10-03T21:13:49Z | [
"python",
"html",
"django"
] |
Display Pretty Code in Django | 1,514,874 | <p>I'm looking for something I can use within django to display preformatted code. Ideally this would include out-of-the-box syntax highlighting for various programming languages, although just starting with something that displayed html and xml well would be a good starting point.</p>
<p>Does something like this exist? </p>
<p>Basically I am looking for something like the widget dpaste (and also stack overflow) use to display code.</p>
<p>e.g. <a href="http://dpaste.com/hold/102141/" rel="nofollow">http://dpaste.com/hold/102141/</a></p>
<p>or </p>
<pre><code><?xml version="1.0" encoding='UTF-8'?>
<painting>
<img src="madonna.jpg" alt='Foligno Madonna, by Raphael'/>
<caption>This is Raphael's "Foligno" Madonna, painted in
<date>1511</date>-<date>1512</date>.</caption>
</painting>
</code></pre>
<p>I'm aware of <a href="http://stackoverflow.com/questions/1432439/display-django-code-from-a-django-template">this question</a>, but mine is not about the mechanics of escaping the code, it's about the UI.</p>
| 3 | 2009-10-03T21:11:56Z | 1,516,227 | <p>I have found SyntaxHighlighter (<a href="http://alexgorbatchev.com" rel="nofollow">http://alexgorbatchev.com</a>) to work well within the Django part of my site.</p>
| 2 | 2009-10-04T11:58:42Z | [
"python",
"html",
"django"
] |
Why my code is getting NZEC run time error? | 1,515,019 | <p><a href="https://www.spoj.pl/problems/ORDERS/" rel="nofollow">Question source: SPOJ.. ORDERS</a></p>
<pre><code>def swap(ary,idx1,idx2):
tmp = ary[idx1]
ary[idx1] = ary[idx2]
ary[idx2] = tmp
def mkranks(size):
tmp = []
for i in range(1, size + 1):
tmp = tmp + [i]
return tmp
def permutations(ordered, movements):
size = len(ordered)
for i in range(1, size): # The leftmost one never moves
for j in range(0, int(movements[i])):
swap(ordered, i-j, i-j-1)
return ordered
numberofcases = input()
for i in range(0, numberofcases):
sizeofcase = input()
tmp = raw_input()
movements = ""
for i in range(0, len(tmp)):
if i % 2 != 1:
movements = movements + tmp[i]
ordered = mkranks(sizeofcase)
ordered = permutations(ordered, movements)
output = ""
for i in range(0, sizeofcase - 1):
output = output + str(ordered[i]) + " "
output = output + str(ordered[sizeofcase - 1])
print output
</code></pre>
| 0 | 2009-10-03T22:28:02Z | 1,515,063 | <p>Having made your code a bit more Pythonic (but without altering its flow/algorithm):</p>
<pre><code>def swap(ary, idx1, idx2):
ary[idx1], ary[idx2] = [ary[i] for i in (idx2, idx1)]
def permutations(ordered, movements):
size = len(ordered)
for i in range(1, len(ordered)):
for j in range(movements[i]):
swap(ordered, i-j, i-j-1)
return ordered
numberofcases = input()
for i in range(numberofcases):
sizeofcase = input()
movements = [int(s) for s in raw_input().split()]
ordered = [str(i) for i in range(1, sizeofcase+1)]
ordered = permutations(ordered, movements)
output = " ".join(ordered)
print output
</code></pre>
<p>I see it runs correctly in the sample case given at the SPOJ URL you indicate. What is your failing case?</p>
| 1 | 2009-10-03T22:50:24Z | [
"python"
] |
Entity groups in Google App Engine Datastore | 1,515,135 | <p>So I have an app that if I'm honest doesn't really need transactional integrity (lots of updates, none of them critical). So I was planning on simply leaving entity groups by the wayside for now. But I'd still like to understand it (coming from a relational background).</p>
<p>The way I see it, all queries for my app will be on a user by user basis. Therefore I do not need to group any higher than a user entity, according to the <a href="http://code.google.com/appengine/docs/python/datastore/keysandentitygroups.html#Entity%5FGroups%5FAncestors%5Fand%5FPaths" rel="nofollow">docs recommendations</a>. But I wasn't planning on having a specific user entity, instead relying on UserProperty in the entities themselves. </p>
<p>The way I see it, if I want transactions (on a per-user basis), I will need some kind of root user entity as the parent of all entities that are part of the hierarchy of her data, no matter how thin this entity would actually be i.e. basically no properties. </p>
<p>Is this correct?</p>
<p>Apologies for verboseness, I only really pinged what schema-less actually meant in practice tonight...</p>
| 6 | 2009-10-03T23:27:57Z | 1,652,322 | <p>You are essentially correct. You need to group them if you want transactional capability. However, you can group several entities together without creating an actual root entity, in the sense of an entity in the datastore. You instead create a sort of virtual root entity. One important use case of this feature is the ability to create a child object before you create it parent.</p>
<blockquote>
<p>You can create an entity with an
ancestor path without first creating
the parent entity. To do so, you
create a Key for the ancestor using a
kind and key name, then use it as the
parent of the new entity. All entities
with the same root ancestor belong to
the same entity group, whether or not
the root of the path represents an
actual entity.</p>
</blockquote>
<p>That quote is from <a href="http://code.google.com/appengine/docs/python/datastore/keysandentitygroups.html#Entity%5FGroups%5FAncestors%5Fand%5FPaths" rel="nofollow">the same doc you linked to</a>.</p>
| 3 | 2009-10-30T21:05:25Z | [
"python",
"google-app-engine",
"schemaless"
] |
Entity groups in Google App Engine Datastore | 1,515,135 | <p>So I have an app that if I'm honest doesn't really need transactional integrity (lots of updates, none of them critical). So I was planning on simply leaving entity groups by the wayside for now. But I'd still like to understand it (coming from a relational background).</p>
<p>The way I see it, all queries for my app will be on a user by user basis. Therefore I do not need to group any higher than a user entity, according to the <a href="http://code.google.com/appengine/docs/python/datastore/keysandentitygroups.html#Entity%5FGroups%5FAncestors%5Fand%5FPaths" rel="nofollow">docs recommendations</a>. But I wasn't planning on having a specific user entity, instead relying on UserProperty in the entities themselves. </p>
<p>The way I see it, if I want transactions (on a per-user basis), I will need some kind of root user entity as the parent of all entities that are part of the hierarchy of her data, no matter how thin this entity would actually be i.e. basically no properties. </p>
<p>Is this correct?</p>
<p>Apologies for verboseness, I only really pinged what schema-less actually meant in practice tonight...</p>
| 6 | 2009-10-03T23:27:57Z | 2,016,369 | <blockquote>
<p>The way I see it, if I want transactions (on a per-user basis), I will need some kind of root user entity as the parent of all entities that are part of the hierarchy of her data, no matter how thin this entity would actually be i.e. basically no properties.</p>
</blockquote>
<p>I wouldn't just create a root user entity and throw everything in its entity group. Think about what you need transactions for. If you have no properties on your user entity, what would you be using it in transactions with?</p>
<p>I don't know about your data, but let's assume it's a blog system and you have users, posts and comments. The Post model holds a number_of_comments so you don't have to count them. You might want transactions to ensure when you create a comment, the number_of_comments property can be updated safely.</p>
<p>In this case, it would be an unnecessary overhead to have all of a users posts and comments in a single entity group. Instead, you can post the comments in the same entity group as the post they belong to. There would be no need to put the posts into the same group as a user, and in fact this would be a bad idea, since comments posted in any of a users post would all be contending to write the same entity group.</p>
<p>I wrote a <a href="http://blog.dantup.com/2010/01/app-engine-entity-groups-contention-and-transactions">short article about entity groups</a> on my blog today. You might find it useful.</p>
| 11 | 2010-01-06T21:26:32Z | [
"python",
"google-app-engine",
"schemaless"
] |
Simple example of how to use ast.NodeVisitor? | 1,515,357 | <p>Does anyone have a simple example using ast.NodeVisitor to walk the abstract syntax tree in Python 2.6? The difference between visit and generic_visit is unclear to me, and I cannot find any example using google codesearch or plain google.</p>
| 31 | 2009-10-04T01:38:14Z | 1,515,380 | <p><code>generic_visit</code> is called when a custom visitor (ie visit_Name) can't be found. Here's a piece of code I wrote recently with ast.NodeVisitor: <a href="https://github.com/pypy/pypy/blob/master/py/_code/_assertionnew.py" rel="nofollow">https://github.com/pypy/pypy/blob/master/py/_code/_assertionnew.py</a> It interprets the AST nodes to gain debugging information about some of them and falls back in with <code>generic_visit</code> when a special implementation isn't provided.</p>
| 5 | 2009-10-04T01:52:15Z | [
"python",
"python-2.6",
"abstract-syntax-tree"
] |
Simple example of how to use ast.NodeVisitor? | 1,515,357 | <p>Does anyone have a simple example using ast.NodeVisitor to walk the abstract syntax tree in Python 2.6? The difference between visit and generic_visit is unclear to me, and I cannot find any example using google codesearch or plain google.</p>
| 31 | 2009-10-04T01:38:14Z | 1,515,403 | <p><code>ast.visit</code> -- unless you override it in a subclass, of course -- when called to visit an <code>ast.Node</code> of class <code>foo</code>, calls <code>self.visit_foo</code> if that method exists, otherwise <code>self.generic_visit</code>. The latter, again in its implementation in class <code>ast</code> itself, just calls <code>self.visit</code> on every child node (and performs no other action).</p>
<p>So, consider, for example:</p>
<pre><code>>>> class v(ast.NodeVisitor):
... def generic_visit(self, node):
... print type(node).__name__
... ast.NodeVisitor.generic_visit(self, node)
...
</code></pre>
<p>Here, we're overriding <code>generic_visit</code> to print the class name, but <em>also</em> calling up to the base class (so that all children will also be visited). So for example...:</p>
<pre><code>>>> x = v()
>>> t = ast.parse('d[x] += v[y, x]')
>>> x.visit(t)
</code></pre>
<p>emits:</p>
<pre><code>Module
AugAssign
Subscript
Name
Load
Index
Name
Load
Store
Add
Subscript
Name
Load
Index
Tuple
Name
Load
Name
Load
Load
Load
</code></pre>
<p>But suppose we didn't care for Load nodes (and children thereof -- if they had any;-). Then a simple way to deal with that might be, e.g.:</p>
<pre><code>>>> class w(v):
... def visit_Load(self, node): pass
...
</code></pre>
<p>Now when we're visiting a Load node, <code>visit</code> dispatches, NOT to <code>generic_visit</code> any more, but to our new <code>visit_Load</code>... which doesn't do anything at all. So:</p>
<pre><code>>>> y = w()
>>> y.visit(t)
Module
AugAssign
Subscript
Name
Index
Name
Store
Add
Subscript
Name
Index
Tuple
Name
Name
</code></pre>
<p>or, suppose we also wanted to see the actual names for Name nodes; then...:</p>
<pre><code>>>> class z(v):
... def visit_Name(self, node): print 'Name:', node.id
...
>>> z().visit(t)
Module
AugAssign
Subscript
Name: d
Index
Name: x
Store
Add
Subscript
Name: v
Index
Tuple
Name: y
Name: x
Load
Load
</code></pre>
<p>But, NodeVisitor is a class because this lets it store information during a visit. Suppose all we want is the set of names in a "module". Then we don't need to override <code>generic_visit</code> any more, but rather...:</p>
<pre><code>>>> class allnames(ast.NodeVisitor):
... def visit_Module(self, node):
... self.names = set()
... self.generic_visit(node)
... print sorted(self.names)
... def visit_Name(self, node):
... self.names.add(node.id)
...
>>> allnames().visit(t)
['d', 'v', 'x', 'y']
</code></pre>
<p>This kind of thing is a more typical use case than ones requiring overrides of <code>generic_visit</code> -- normally, you're only interested in a few kinds of nodes, like we are here in Module and Name, so we can just override <code>visit_Module</code> and <code>visit_Name</code> and let ast's <code>visit</code> do the dispatching on our behalf.</p>
| 59 | 2009-10-04T02:05:23Z | [
"python",
"python-2.6",
"abstract-syntax-tree"
] |
Simple example of how to use ast.NodeVisitor? | 1,515,357 | <p>Does anyone have a simple example using ast.NodeVisitor to walk the abstract syntax tree in Python 2.6? The difference between visit and generic_visit is unclear to me, and I cannot find any example using google codesearch or plain google.</p>
| 31 | 2009-10-04T01:38:14Z | 26,374,977 | <p>Looking at the code in <a href="https://github.com/python/cpython/blob/master/Lib/ast.py">ast.py</a> it's not that hard to copy paste and roll your own walker. E.g.</p>
<pre><code>import ast
def str_node(node):
if isinstance(node, ast.AST):
fields = [(name, str_node(val)) for name, val in ast.iter_fields(node) if name not in ('left', 'right')]
rv = '%s(%s' % (node.__class__.__name__, ', '.join('%s=%s' % field for field in fields))
return rv + ')'
else:
return repr(node)
def ast_visit(node, level=0):
print(' ' * level + str_node(node))
for field, value in ast.iter_fields(node):
if isinstance(value, list):
for item in value:
if isinstance(item, ast.AST):
ast_visit(item, level=level+1)
elif isinstance(value, ast.AST):
ast_visit(value, level=level+1)
ast_visit(ast.parse('a + b'))
</code></pre>
<p>Prints out</p>
<pre><code>Module(body=[<_ast.Expr object at 0x02808510>])
Expr(value=BinOp(op=Add()))
BinOp(op=Add())
Name(id='a', ctx=Load())
Load()
Add()
Name(id='b', ctx=Load())
Load()
</code></pre>
| 7 | 2014-10-15T05:17:50Z | [
"python",
"python-2.6",
"abstract-syntax-tree"
] |
Declaring Unknown Type Variable in Python? | 1,515,412 | <p>I have a situation in Python(cough, homework) where I need to multiply EACH ELEMENT in a given list of objects a specified number of times and return the output of the elements. The problem is that the sample inputs given are of different types. For example, one case may input a list of strings whose elements I need to multiply while the others may be ints. So my return type needs to vary. I would like to do this without having to test what every type of object is. Is there a way to do this? I know in C# i could just use "var" but I don't know if such a thing exists in Python?</p>
<p>I realize that variables don't have to be declared, but in this case I can't see any way around it. Here's the function I made:</p>
<pre><code>def multiplyItemsByFour(argsList):
output = ????
for arg in argsList:
output += arg * 4
return output
</code></pre>
<p>See how I need to add to the output variable. If I just try to take away the output assignment on the first line, I get an error that the variable was not defined. But if I assign it a 0 or a "" for an empty string, an exception could be thrown since you can't add 3 to a string or "a" to an integer, etc... </p>
<p>Here are some sample inputs and outputs:</p>
<pre><code>Input: ('a','b') Output: 'aaaabbbb'
Input: (2,3,4) Output: 36
</code></pre>
<p>Thanks!</p>
| 2 | 2009-10-04T02:10:00Z | 1,515,418 | <p>You don't need to declare variable types in python; a variable has the type of whatever's assigned to it. </p>
<p>EDIT:</p>
<p>To solve the re-stated problem, try this:</p>
<pre><code>def multiplyItemsByFour(argsList):
output = argsList.pop(0) * 4
for arg in argsList:
output += arg * 4
return output
</code></pre>
<p>(This is probably not the most pythonic way of doing this, but it should at least start off your output variable as the right type, assuming the whole list is of the same type)</p>
| 1 | 2009-10-04T02:12:44Z | [
"python",
"types"
] |
Declaring Unknown Type Variable in Python? | 1,515,412 | <p>I have a situation in Python(cough, homework) where I need to multiply EACH ELEMENT in a given list of objects a specified number of times and return the output of the elements. The problem is that the sample inputs given are of different types. For example, one case may input a list of strings whose elements I need to multiply while the others may be ints. So my return type needs to vary. I would like to do this without having to test what every type of object is. Is there a way to do this? I know in C# i could just use "var" but I don't know if such a thing exists in Python?</p>
<p>I realize that variables don't have to be declared, but in this case I can't see any way around it. Here's the function I made:</p>
<pre><code>def multiplyItemsByFour(argsList):
output = ????
for arg in argsList:
output += arg * 4
return output
</code></pre>
<p>See how I need to add to the output variable. If I just try to take away the output assignment on the first line, I get an error that the variable was not defined. But if I assign it a 0 or a "" for an empty string, an exception could be thrown since you can't add 3 to a string or "a" to an integer, etc... </p>
<p>Here are some sample inputs and outputs:</p>
<pre><code>Input: ('a','b') Output: 'aaaabbbb'
Input: (2,3,4) Output: 36
</code></pre>
<p>Thanks!</p>
| 2 | 2009-10-04T02:10:00Z | 1,515,424 | <p>No need to test the objects, just multiply away!</p>
<pre><code>'this is a string' * 6
14 * 6
[1,2,3] * 6
</code></pre>
<p>all just work</p>
| 0 | 2009-10-04T02:17:24Z | [
"python",
"types"
] |
Declaring Unknown Type Variable in Python? | 1,515,412 | <p>I have a situation in Python(cough, homework) where I need to multiply EACH ELEMENT in a given list of objects a specified number of times and return the output of the elements. The problem is that the sample inputs given are of different types. For example, one case may input a list of strings whose elements I need to multiply while the others may be ints. So my return type needs to vary. I would like to do this without having to test what every type of object is. Is there a way to do this? I know in C# i could just use "var" but I don't know if such a thing exists in Python?</p>
<p>I realize that variables don't have to be declared, but in this case I can't see any way around it. Here's the function I made:</p>
<pre><code>def multiplyItemsByFour(argsList):
output = ????
for arg in argsList:
output += arg * 4
return output
</code></pre>
<p>See how I need to add to the output variable. If I just try to take away the output assignment on the first line, I get an error that the variable was not defined. But if I assign it a 0 or a "" for an empty string, an exception could be thrown since you can't add 3 to a string or "a" to an integer, etc... </p>
<p>Here are some sample inputs and outputs:</p>
<pre><code>Input: ('a','b') Output: 'aaaabbbb'
Input: (2,3,4) Output: 36
</code></pre>
<p>Thanks!</p>
| 2 | 2009-10-04T02:10:00Z | 1,515,425 | <p>Python is dynamically typed, you don't need to declare the type of a variable, because a variable doesn't have a type, only values do. (Any variable can store any value, a value never changes its type during its lifetime.)</p>
<pre><code>def do_something(x):
return x * 5
</code></pre>
<p>This will work for any <code>x</code> you pass to it, the actual result depending on what type the value in <code>x</code> has. If <code>x</code> contains a number it will just do regular multiplication, if it contains a string the string will be repeated five times in a row, for lists and such it will repeat the list five times, and so on. For custom types (classes) it depends on whether the class has an operation defined for the multiplication operator.</p>
| 1 | 2009-10-04T02:17:38Z | [
"python",
"types"
] |
Declaring Unknown Type Variable in Python? | 1,515,412 | <p>I have a situation in Python(cough, homework) where I need to multiply EACH ELEMENT in a given list of objects a specified number of times and return the output of the elements. The problem is that the sample inputs given are of different types. For example, one case may input a list of strings whose elements I need to multiply while the others may be ints. So my return type needs to vary. I would like to do this without having to test what every type of object is. Is there a way to do this? I know in C# i could just use "var" but I don't know if such a thing exists in Python?</p>
<p>I realize that variables don't have to be declared, but in this case I can't see any way around it. Here's the function I made:</p>
<pre><code>def multiplyItemsByFour(argsList):
output = ????
for arg in argsList:
output += arg * 4
return output
</code></pre>
<p>See how I need to add to the output variable. If I just try to take away the output assignment on the first line, I get an error that the variable was not defined. But if I assign it a 0 or a "" for an empty string, an exception could be thrown since you can't add 3 to a string or "a" to an integer, etc... </p>
<p>Here are some sample inputs and outputs:</p>
<pre><code>Input: ('a','b') Output: 'aaaabbbb'
Input: (2,3,4) Output: 36
</code></pre>
<p>Thanks!</p>
| 2 | 2009-10-04T02:10:00Z | 1,515,435 | <pre><code>def fivetimes(anylist):
return anylist * 5
</code></pre>
<p>As you see, if you're given a list argument, there's no need for any assignment whatsoever in order to "multiply it a given number of times and return the output". You talk about a <em>given</em> list; how is it <em>given</em> to you, if not (the most natural way) as an argument to your function? Not that it matters much -- if it's a global variable, a property of the object that's your argument, and so forth, this still doesn't necessitate any assignment.</p>
<p>If you were "homeworkically" forbidden from using the <code>*</code> operator of lists, and just required to implement it yourself, this would require assignment, but no declaration:</p>
<pre><code>def multiply_the_hard_way(inputlist, multiplier):
outputlist = []
for i in range(multiplier):
outputlist.extend(inputlist)
return outputlist
</code></pre>
<p>You can simply make the empty list "magicaly appear": there's no need to "declare" it as being anything whatsoever, it's an empty list and the Python compiler knows it as well as you or any reader of your code does. Binding it to the name <code>outputlist</code> doesn't require you to perform any special ritual either, just the binding (aka assignment) itself: names don't have types, only <em>objects</em> have types... that's Python!-)</p>
<p><strong>Edit</strong>: OP now says output must not be a list, but rather int, float, or maybe string, and he is given no indication of what. I've asked for clarification -- multiplying a list ALWAYS returns a list, so clearly he must mean something different from what he originally said, that he had to multiply a list. Meanwhile, here's another attempt at mind-reading. Perhaps he must return a list where EACH ITEM of the input list is multiplied by the same factor (whether that item is an int, float, string, list, ...). Well then:</p>
<pre><code>define multiply_each_item(somelist, multiplier):
return [item * multiplier for item in somelist]
</code></pre>
<p>Look ma, no hands^H^H^H^H^H assignment. (This is known as a "list comprehension", btw).</p>
<p>Or maybe (unlikely, but my mind-reading hat may be suffering interference from my tinfoil hat, will need to go to the mad hatter's shop to have them tuned) he needs to (say) multiply each list item <em>as if</em> they were the same type as the first item, but return them as their original type, so that for example</p>
<pre><code>>>> mystic(['zap', 1, 23, 'goo'], 2)
['zapzap', 11, 2323, 'googoo']
>>> mystic([23, '12', 15, 2.5], 2)
[46, '24', 30, 4.0]
</code></pre>
<p>Even this highly-mystical spec COULD be accomodated...:</p>
<pre><code>>>> def mystic(alist, mul):
... multyp = type(alist[0])
... return [type(x)(mul*multyp(x)) for x in alist]
...
</code></pre>
<p>...though I very much doubt it's the spec actually encoded in the mysterious runes of that homework assignment. Just about ANY precise spec can be either implemented or proven to be likely impossible as stated (by requiring you to solve the Halting Problem or demanding that P==NP, say;-). That may take some work ("prove the 4-color theorem", for example;-)... but still less than it takes to magically divine what the actual spec IS, from a collection of mutually contradictory observations, no examples, etc. Though in our daily work as software developer (ah for the good old times when all we had to face was homework!-) we DO meet a lot of such cases of course (and have to solve them to earn our daily bread;-).</p>
<p><em>EditEdit</em>: finally seeing a precise spec I point out I already implemented that one, anyway, here it goes again:</p>
<pre><code>def multiplyItemsByFour(argsList):
return [item * 4 for item in argsList]
</code></pre>
<p><em>EditEditEdit</em>: finally/finally seeing a MORE precise spec, with (luxury!-) <em>examples</em>:</p>
<pre><code>Input: ('a','b') Output: 'aaaabbbb' Input: (2,3,4) Output: 36
</code></pre>
<p>So then what's wanted it the <em>summation</em> (and you can't use <code>sum</code> as it wouldn't work on strings) of the items in the input list, each multiplied by four. My preferred solution:</p>
<pre><code>def theFinalAndTrulyRealProblemAsPosed(argsList):
items = iter(argsList)
output = next(items, []) * 4
for item in items:
output += item * 4
return output
</code></pre>
<p>If you're forbidden from using some of these constructs, such as built-ins <code>items</code> and <code>iter</code>, there are many other possibilities (slightly inferior ones) such as:</p>
<pre><code>def theFinalAndTrulyRealProblemAsPosed(argsList):
if not argsList: return None
output = argsList[0] * 4
for item in argsList[1:]:
output += item * 4
return output
</code></pre>
<p>For an empty <code>argsList</code>, the first version returns <code>[]</code>, the second one returns <code>None</code> -- not sure what you're supposed to do in that corner case anyway.</p>
| 6 | 2009-10-04T02:26:46Z | [
"python",
"types"
] |
Declaring Unknown Type Variable in Python? | 1,515,412 | <p>I have a situation in Python(cough, homework) where I need to multiply EACH ELEMENT in a given list of objects a specified number of times and return the output of the elements. The problem is that the sample inputs given are of different types. For example, one case may input a list of strings whose elements I need to multiply while the others may be ints. So my return type needs to vary. I would like to do this without having to test what every type of object is. Is there a way to do this? I know in C# i could just use "var" but I don't know if such a thing exists in Python?</p>
<p>I realize that variables don't have to be declared, but in this case I can't see any way around it. Here's the function I made:</p>
<pre><code>def multiplyItemsByFour(argsList):
output = ????
for arg in argsList:
output += arg * 4
return output
</code></pre>
<p>See how I need to add to the output variable. If I just try to take away the output assignment on the first line, I get an error that the variable was not defined. But if I assign it a 0 or a "" for an empty string, an exception could be thrown since you can't add 3 to a string or "a" to an integer, etc... </p>
<p>Here are some sample inputs and outputs:</p>
<pre><code>Input: ('a','b') Output: 'aaaabbbb'
Input: (2,3,4) Output: 36
</code></pre>
<p>Thanks!</p>
| 2 | 2009-10-04T02:10:00Z | 1,515,493 | <p>My guess is that the purpose of your homework is to expose you to "duck typing". The basic idea is that you don't worry about the types too much, you just worry about whether the <em>behaviors</em> work correctly. A classic example:</p>
<pre><code>def add_two(a, b):
return a + b
print add_two(1, 2) # prints 3
print add_two("foo", "bar") # prints "foobar"
print add_two([0, 1, 2], [3, 4, 5]) # prints [0, 1, 2, 3, 4, 5]
</code></pre>
<p>Notice that when you <code>def</code> a function in Python, you don't declare a return type anywhere. It is perfectly okay for the same function to return different types based on its arguments. It's considered a virtue, even; consider that in Python we only need one definition of <code>add_two()</code> and we can add integers, add floats, concatenate strings, and join lists with it. Statically typed languages would require multiple implementations, unless they had an escape such as <code>variant</code>, but Python is dynamically typed. (Python is strongly typed, but dynamically typed. Some will tell you Python is weakly typed, but it isn't. In a weakly typed language such as JavaScript, the expression <code>1 + "1"</code> will give you a result of 2; in Python this expression just raises a <code>TypeError</code> exception.)</p>
<p>It is considered very poor style to try to test the arguments to figure out their types, and then do things based on the types. If you need to make your code robust, you can always use a <code>try</code> block:</p>
<pre><code>def safe_add_two(a, b):
try:
return a + b
except TypeError:
return None
</code></pre>
<p>See also the Wikipedia page on <a href="http://en.wikipedia.org/wiki/Duck_typing" rel="nofollow">duck typing</a>.</p>
| 2 | 2009-10-04T03:04:56Z | [
"python",
"types"
] |
Declaring Unknown Type Variable in Python? | 1,515,412 | <p>I have a situation in Python(cough, homework) where I need to multiply EACH ELEMENT in a given list of objects a specified number of times and return the output of the elements. The problem is that the sample inputs given are of different types. For example, one case may input a list of strings whose elements I need to multiply while the others may be ints. So my return type needs to vary. I would like to do this without having to test what every type of object is. Is there a way to do this? I know in C# i could just use "var" but I don't know if such a thing exists in Python?</p>
<p>I realize that variables don't have to be declared, but in this case I can't see any way around it. Here's the function I made:</p>
<pre><code>def multiplyItemsByFour(argsList):
output = ????
for arg in argsList:
output += arg * 4
return output
</code></pre>
<p>See how I need to add to the output variable. If I just try to take away the output assignment on the first line, I get an error that the variable was not defined. But if I assign it a 0 or a "" for an empty string, an exception could be thrown since you can't add 3 to a string or "a" to an integer, etc... </p>
<p>Here are some sample inputs and outputs:</p>
<pre><code>Input: ('a','b') Output: 'aaaabbbb'
Input: (2,3,4) Output: 36
</code></pre>
<p>Thanks!</p>
| 2 | 2009-10-04T02:10:00Z | 1,515,497 | <p>Try this:</p>
<pre><code>def timesfourlist(list):
nextstep = map(times_four, list)
sum(nextstep)
</code></pre>
<p>map performs the function passed in on each element of the list(returning a new list) and then sum does the += on the list.</p>
| 0 | 2009-10-04T03:08:21Z | [
"python",
"types"
] |
Declaring Unknown Type Variable in Python? | 1,515,412 | <p>I have a situation in Python(cough, homework) where I need to multiply EACH ELEMENT in a given list of objects a specified number of times and return the output of the elements. The problem is that the sample inputs given are of different types. For example, one case may input a list of strings whose elements I need to multiply while the others may be ints. So my return type needs to vary. I would like to do this without having to test what every type of object is. Is there a way to do this? I know in C# i could just use "var" but I don't know if such a thing exists in Python?</p>
<p>I realize that variables don't have to be declared, but in this case I can't see any way around it. Here's the function I made:</p>
<pre><code>def multiplyItemsByFour(argsList):
output = ????
for arg in argsList:
output += arg * 4
return output
</code></pre>
<p>See how I need to add to the output variable. If I just try to take away the output assignment on the first line, I get an error that the variable was not defined. But if I assign it a 0 or a "" for an empty string, an exception could be thrown since you can't add 3 to a string or "a" to an integer, etc... </p>
<p>Here are some sample inputs and outputs:</p>
<pre><code>Input: ('a','b') Output: 'aaaabbbb'
Input: (2,3,4) Output: 36
</code></pre>
<p>Thanks!</p>
| 2 | 2009-10-04T02:10:00Z | 1,515,624 | <p>Are you sure this is for Python beginners? To me, the cleanest way to do this is with reduce() and lambda, both of which are not typical beginner tools, and sometimes discouraged even for experienced Python programmers:</p>
<pre><code>def multiplyItemsByFour(argsList):
if not argsList:
return None
newItems = [item * 4 for item in argsList]
return reduce(lambda x, y: x + y, newItems)
</code></pre>
<p>Like Alex Martelli, I've thrown in a quick test for an empty list at the beginning which returns None. Note that if you are using Python 3, you must import functools to use reduce().</p>
<p>Essentially, the reduce(lambda...) solution is very similar to the other suggestions to set up an accumulator using the first input item, and then processing the rest of the input items; but is simply more concise.</p>
| 2 | 2009-10-04T04:48:36Z | [
"python",
"types"
] |
Declaring Unknown Type Variable in Python? | 1,515,412 | <p>I have a situation in Python(cough, homework) where I need to multiply EACH ELEMENT in a given list of objects a specified number of times and return the output of the elements. The problem is that the sample inputs given are of different types. For example, one case may input a list of strings whose elements I need to multiply while the others may be ints. So my return type needs to vary. I would like to do this without having to test what every type of object is. Is there a way to do this? I know in C# i could just use "var" but I don't know if such a thing exists in Python?</p>
<p>I realize that variables don't have to be declared, but in this case I can't see any way around it. Here's the function I made:</p>
<pre><code>def multiplyItemsByFour(argsList):
output = ????
for arg in argsList:
output += arg * 4
return output
</code></pre>
<p>See how I need to add to the output variable. If I just try to take away the output assignment on the first line, I get an error that the variable was not defined. But if I assign it a 0 or a "" for an empty string, an exception could be thrown since you can't add 3 to a string or "a" to an integer, etc... </p>
<p>Here are some sample inputs and outputs:</p>
<pre><code>Input: ('a','b') Output: 'aaaabbbb'
Input: (2,3,4) Output: 36
</code></pre>
<p>Thanks!</p>
| 2 | 2009-10-04T02:10:00Z | 1,515,738 | <p>If you just want to fill in the blank in your code, you could try setting <code>object=arglist[0].__class__()</code> to give it the zero equivalent value of that class.</p>
<pre><code>>>> def multiplyItemsByFour(argsList):
output = argsList[0].__class__()
for arg in argsList:
output += arg * 4
return output
>>> multiplyItemsByFour('ab')
'aaaabbbb'
>>> multiplyItemsByFour((2,3,4))
36
>>> multiplyItemsByFour((2.0,3.3))
21.199999999999999
</code></pre>
<p>This will crash if the list is empty, but you can check for that case at the beginning of the function and return whatever you feel appropriate.</p>
| 0 | 2009-10-04T06:18:49Z | [
"python",
"types"
] |
Declaring Unknown Type Variable in Python? | 1,515,412 | <p>I have a situation in Python(cough, homework) where I need to multiply EACH ELEMENT in a given list of objects a specified number of times and return the output of the elements. The problem is that the sample inputs given are of different types. For example, one case may input a list of strings whose elements I need to multiply while the others may be ints. So my return type needs to vary. I would like to do this without having to test what every type of object is. Is there a way to do this? I know in C# i could just use "var" but I don't know if such a thing exists in Python?</p>
<p>I realize that variables don't have to be declared, but in this case I can't see any way around it. Here's the function I made:</p>
<pre><code>def multiplyItemsByFour(argsList):
output = ????
for arg in argsList:
output += arg * 4
return output
</code></pre>
<p>See how I need to add to the output variable. If I just try to take away the output assignment on the first line, I get an error that the variable was not defined. But if I assign it a 0 or a "" for an empty string, an exception could be thrown since you can't add 3 to a string or "a" to an integer, etc... </p>
<p>Here are some sample inputs and outputs:</p>
<pre><code>Input: ('a','b') Output: 'aaaabbbb'
Input: (2,3,4) Output: 36
</code></pre>
<p>Thanks!</p>
| 2 | 2009-10-04T02:10:00Z | 1,515,784 | <p>You gave these sample inputs and outputs:</p>
<p>Input: ('a','b') Output: 'aaaabbbb' Input: (2,3,4) Output: 36</p>
<p>I don't want to write the solution to your homework for you, but I do want to steer you in the correct direction. But I'm still not sure I understand what your problem is, because the problem as I understand it seems a bit difficult for an intro to Python class.</p>
<p>The most straightforward way to solve this requires that the arguments be passed in a list. Then, you can look at the first item in the list, and work from that. Here is a function that requires the caller to pass in a list of two items:</p>
<pre><code>def handle_list_of_len_2(lst):
return lst[0] * 4 + lst[1] * 4
</code></pre>
<p>Now, how can we make this extend past two items? Well, in your sample code you weren't sure what to assign to your variable output. How about assigning lst[0]? Then it always has the correct type. Then you could loop over all the other elements in lst and accumulate to your output variable using += as you wrote. If you don't know how to loop over a list of items but skip the first thing in the list, Google search for "python list slice".</p>
<p>Now, how can we make this not require the user to pack up everything into a list, but just call the function? What we really want is some way to accept whatever arguments the user wants to pass to the function, and make a list out of them. Perhaps there is special syntax for declaring a function where you tell Python you just want the arguments bundled up into a list. You might check a <a href="http://www.rexx.com/~dkuhlman/python_101/python_101.html" rel="nofollow">good tutorial</a> and see what it says about how to define a function.</p>
<p>Now that we have covered (very generally) how to accumulate an answer using +=, let's consider other ways to accumulate an answer. If you know how to use a list comprehension, you could use one of those to return a new list based on the argument list, with the multiply performed on each argument; you could then somehow reduce the list down to a single item and return it. Python 2.3 and newer have a built-in function called <code>sum()</code> and you might want to read up on that. [EDIT: Oh drat, <code>sum()</code> only works on numbers. See note added at end.]</p>
<p>I hope this helps. If you are still very confused, I suggest you contact your teacher and ask for clarification. Good luck.</p>
<p>P.S. Python 2.x have a built-in function called <code>reduce()</code> and it is possible to implement <code>sum()</code> using <code>reduce()</code>. However, the creator of Python thinks it is better to just use <code>sum()</code> and in fact he removed <code>reduce()</code> from Python 3.0 (well, he moved it into a module called <code>functools</code>).</p>
<p>P.P.S. If you get the list comprehension working, here's one more thing to think about. If you use a list comprehension and then pass the result to <code>sum()</code>, you build a list to be used once and then discarded. Wouldn't it be neat if we could get the result, but instead of building the whole list and then discarding it we could just have the <code>sum()</code> function consume the list items as fast as they are generated? You might want to read this: <a href="http://stackoverflow.com/questions/47789/generator-expressions-vs-list-comprehension">http://stackoverflow.com/questions/47789/generator-expressions-vs-list-comprehension</a></p>
<p>EDIT: Oh drat, I assumed that Python's <code>sum()</code> builtin would use duck typing. Actually it is documented to work on numbers, only. I'm disappointed! I'll have to search and see if there were any discussions about that, and see why they did it the way they did; they probably had good reasons. Meanwhile, you might as well use your += solution. Sorry about that.</p>
<p>EDIT: Okay, reading through other answers, I now notice two ways suggested for peeling off the first element in the list.</p>
<p>For simplicity, because you seem like a Python beginner, I suggested simply using <code>output = lst[0]</code> and then using list slicing to skip past the first item in the list. However, Wooble in his answer suggested using <code>output = lst.pop(0)</code> which is a very clean solution: it gets the zeroth thing on the list, and then you can just loop over the list and you automatically skip the zeroth thing. However, this "mutates" the list! It's better if a function like this does not have "side effects" such as modifying the list passed to it. (Unless the list is a special list made just for that function call, such as a <code>*args</code> list.) Another way would be to use the "list slice" trick to make a copy of the list that has the first item removed. Alex Martelli provided an example of how to make an "iterator" using a Python feature called <code>iter()</code>, and then using iterator to get the "next" thing. Since the iterator hasn't been used yet, the next thing is the zeroth thing in the list. That's not really a beginner solution but it is the most elegant way to do this in Python; you could pass a really huge list to the function, and Alex Martelli's solution will neither mutate the list nor waste memory by making a copy of the list.</p>
| 1 | 2009-10-04T06:53:59Z | [
"python",
"types"
] |
Declaring Unknown Type Variable in Python? | 1,515,412 | <p>I have a situation in Python(cough, homework) where I need to multiply EACH ELEMENT in a given list of objects a specified number of times and return the output of the elements. The problem is that the sample inputs given are of different types. For example, one case may input a list of strings whose elements I need to multiply while the others may be ints. So my return type needs to vary. I would like to do this without having to test what every type of object is. Is there a way to do this? I know in C# i could just use "var" but I don't know if such a thing exists in Python?</p>
<p>I realize that variables don't have to be declared, but in this case I can't see any way around it. Here's the function I made:</p>
<pre><code>def multiplyItemsByFour(argsList):
output = ????
for arg in argsList:
output += arg * 4
return output
</code></pre>
<p>See how I need to add to the output variable. If I just try to take away the output assignment on the first line, I get an error that the variable was not defined. But if I assign it a 0 or a "" for an empty string, an exception could be thrown since you can't add 3 to a string or "a" to an integer, etc... </p>
<p>Here are some sample inputs and outputs:</p>
<pre><code>Input: ('a','b') Output: 'aaaabbbb'
Input: (2,3,4) Output: 36
</code></pre>
<p>Thanks!</p>
| 2 | 2009-10-04T02:10:00Z | 1,515,808 | <p>Very easy in Python. You need to get the type of the data in your list - use the type() function on the first item - type(argsList[0]). Then to initialize output (where you now have ????) you need the 'zero' or nul value for that type. So just as int() or float() or str() returns the zero or nul for their type so to will type(argsList[0])() return the zero or nul value for whatever type you have in your list.</p>
<p>So, here is your function with one minor modification:</p>
<pre><code>def multiplyItemsByFour(argsList):
output = type(argsList[0])()
for arg in argsList:
output += arg * 4
return output
</code></pre>
<p>Works with::
argsList = <code>[1, 2, 3, 4]</code> or <code>[1.0, 2.0, 3.0, 4.0]</code> or <code>"abcdef"</code> ... etc,</p>
| 2 | 2009-10-04T07:09:05Z | [
"python",
"types"
] |
Declaring Unknown Type Variable in Python? | 1,515,412 | <p>I have a situation in Python(cough, homework) where I need to multiply EACH ELEMENT in a given list of objects a specified number of times and return the output of the elements. The problem is that the sample inputs given are of different types. For example, one case may input a list of strings whose elements I need to multiply while the others may be ints. So my return type needs to vary. I would like to do this without having to test what every type of object is. Is there a way to do this? I know in C# i could just use "var" but I don't know if such a thing exists in Python?</p>
<p>I realize that variables don't have to be declared, but in this case I can't see any way around it. Here's the function I made:</p>
<pre><code>def multiplyItemsByFour(argsList):
output = ????
for arg in argsList:
output += arg * 4
return output
</code></pre>
<p>See how I need to add to the output variable. If I just try to take away the output assignment on the first line, I get an error that the variable was not defined. But if I assign it a 0 or a "" for an empty string, an exception could be thrown since you can't add 3 to a string or "a" to an integer, etc... </p>
<p>Here are some sample inputs and outputs:</p>
<pre><code>Input: ('a','b') Output: 'aaaabbbb'
Input: (2,3,4) Output: 36
</code></pre>
<p>Thanks!</p>
| 2 | 2009-10-04T02:10:00Z | 1,518,443 | <p>Thanks to Alex Martelli, you have the best possible solution:</p>
<pre><code>def theFinalAndTrulyRealProblemAsPosed(argsList):
items = iter(argsList)
output = next(items, []) * 4
for item in items:
output += item * 4
return output
</code></pre>
<p>This is beautiful and elegant. First we create an iterator with <code>iter()</code>, then we use <code>next()</code> to get the first object in the list. Then we accumulate as we iterate through the rest of the list, and we are done. We never need to know the type of the objects in argsList, and indeed they can be of different types as long as all the types can have operator <code>+</code> applied with them. This is duck typing.</p>
<p>For a moment there last night I was confused and thought that you wanted a function that, instead of taking an explicit list, just took one or more arguments.</p>
<pre><code>def four_x_args(*args):
return theFinalAndTrulyRealProblemAsPosed(args)
</code></pre>
<p>The <code>*args</code> argument to the function tells Python to gather up all arguments to this function and make a tuple out of them; then the tuple is bound to the name <code>args</code>. You can easily make a list out of it, and then you could use the <code>.pop(0)</code> method to get the first item from the list. This costs the memory and time to build the list, which is why the <code>iter()</code> solution is so elegant.</p>
<pre><code>def four_x_args(*args):
argsList = list(args) # convert from tuple to list
output = argsList.pop(0) * 4
for arg in argsList:
output += arg * 4
return output
</code></pre>
<p>This is just Wooble's solution, rewritten to use *args.</p>
<p>Examples of calling it:</p>
<pre><code>print four_x_args(1) # prints 4
print four_x_args(1, 2) # prints 12
print four_x_args('a') # prints 'aaaa'
print four_x_args('ab', 'c') # prints 'ababababcccc'
</code></pre>
<p>Finally, I'm going to be malicious and complain about the solution you accepted. That solution depends on the object's base class having a sensible null or zero, but not all classes have this. <code>int()</code> returns <code>0</code>, and <code>str()</code> returns <code>''</code> (null string), so they work. But how about this:</p>
<pre><code>class NaturalNumber(int):
"""
Exactly like an int, but only values >= 1 are possible.
"""
def __new__(cls, initial_value=1):
try:
n = int(initial_value)
if n < 1:
raise ValueError
except ValueError:
raise ValueError, "NaturalNumber() initial value must be an int() >= 1"
return super(NaturalNumber, cls).__new__ (cls, n)
argList = [NaturalNumber(n) for n in xrange(1, 4)]
print theFinalAndTrulyRealProblemAsPosed(argList) # prints correct answer: 24
print NaturalNumber() # prints 1
print type(argList[0])() # prints 1, same as previous line
print multiplyItemsByFour(argList) # prints 25!
</code></pre>
<p>Good luck in your studies, and I hope you enjoy Python as much as I do.</p>
| 0 | 2009-10-05T05:55:38Z | [
"python",
"types"
] |
Django 1.0 Testing: how do I get a session to persist between test code and view being tested? | 1,515,446 | <p>I am trying to test how a view behaves when there is certain data stored in the session. To do so I have created the session in the test method and invoked an interactive shell at the very beginning of the view:</p>
<p><strong>Test Method:</strong></p>
<pre><code>def test_user_with_unused_tests(self):
"User is given a test and sent to test start"
# todo: insure that the user is given a test that he hasn't done
#login
login = self.client.login(username='xxx', password='xxx')
self.failUnless(login)
# build the screener
user = User(username='xxx', password='xxx')
user_screener = UserScreener(user=user)
# put the screener in session
self.client.session['user_screener'] = user_screener
</code></pre>
<p><strong>View That Is Tested:</strong></p>
<pre><code>@login_required
def screener_start(request):
import code
code.interact(local=locals())
</code></pre>
<p>But apparently the session does not persist between my test method and the call to the view:</p>
<p><strong>Evidence of Nonpersistence:</strong></p>
<pre><code>>>> request.session.values()
[1, 'django.contrib.auth.backends.ModelBackend']
</code></pre>
<p>Is there any way to fix this? Am I missing something essential?</p>
<p>I am using Django 1.0.</p>
<p>Thanks ahead of time for your thoughts.</p>
| 2 | 2009-10-04T02:31:58Z | 8,656,609 | <p>Looks like you need a <code>setUp</code> method, please lookup <a href="http://docs.python.org/library/unittest.html" rel="nofollow">http://docs.python.org/library/unittest.html</a> for <code>setUp</code> and <code>tearDown</code> method documentation. The setUp will be run for all tests, the code for each individual test will be destroyed at the end of each test run.</p>
<p>Essentially, you need to put your login logic in the <code>setUp</code> and the actual test logic in the test method.</p>
<p>Hope this helps</p>
| 0 | 2011-12-28T13:36:23Z | [
"python",
"django",
"testing"
] |
Using Django as a Backend for Cappuccino | 1,515,578 | <p>I'm new to both Django and Cappuccino. I have a Django site setup and running through Apache via mod_wsgi. I want to use Django as the backend for a Cappuccino application, but a VirtualHost setup in Apache and mod_wsgi to serve a Django application serves static files out of a different location than the normal web root (e.g. <a href="http://example.com/media/" rel="nofollow">http://example.com/media/</a> or <a href="http://media.example.com" rel="nofollow">http://media.example.com</a>).</p>
<p>How could I setup the environment so that <a href="http://example.com" rel="nofollow">http://example.com</a> serves my Cappuccino Javascript/HTML/CSS files, while also letting me use the typical Django URL system to create endpoints for AJAX calls (e.g. <a href="http://example.com/some/json/" rel="nofollow">http://example.com/some/json/</a>)?</p>
| 2 | 2009-10-04T04:18:21Z | 1,515,700 | <p>Have you read:</p>
<p><a href="http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines" rel="nofollow">http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines</a></p>
<p>This goes into various aspects of using WSGIScriptAlias for mod_wsgi and Alias directives for static files.</p>
<p>I'd suggest you ensure your read that, or reread it, and then post what configuration you have tried already as that will help explain what you are trying to do and can then just correct it.</p>
| 1 | 2009-10-04T05:44:47Z | [
"python",
"django",
"apache",
"mod-wsgi",
"cappuccino"
] |
Using Django as a Backend for Cappuccino | 1,515,578 | <p>I'm new to both Django and Cappuccino. I have a Django site setup and running through Apache via mod_wsgi. I want to use Django as the backend for a Cappuccino application, but a VirtualHost setup in Apache and mod_wsgi to serve a Django application serves static files out of a different location than the normal web root (e.g. <a href="http://example.com/media/" rel="nofollow">http://example.com/media/</a> or <a href="http://media.example.com" rel="nofollow">http://media.example.com</a>).</p>
<p>How could I setup the environment so that <a href="http://example.com" rel="nofollow">http://example.com</a> serves my Cappuccino Javascript/HTML/CSS files, while also letting me use the typical Django URL system to create endpoints for AJAX calls (e.g. <a href="http://example.com/some/json/" rel="nofollow">http://example.com/some/json/</a>)?</p>
| 2 | 2009-10-04T04:18:21Z | 1,516,924 | <p>Here is the configuration I came up with that works:</p>
<p>Django Media Settings:</p>
<pre><code>MEDIA_ROOT = '/Users/Me/Development/Web Projects/mysite/mysite/public_html'
MEDIA_URL = 'http:/mysite.local/'
ADMIN_MEDIA_PREFIX = '/'
</code></pre>
<p>Apache VirtualHost Configuration:</p>
<pre><code><VirtualHost *:80>
ServerAdmin webmaster@mysite.local
ServerName mysite.local
ErrorLog "/private/var/log/apache2/mysite.local-error_log"
CustomLog "/private/var/log/apache2/mysite.local-access_log" common
WSGIScriptAlias / "/Users/Me/Development/Web Projects/MySite/django.wsgi"
<Directory "/Users/Me/Development/Web Projects/MySite/">
Allow from all
</Directory>
AliasMatch ^/(.*\.[A-Za-z0-9]{1,5})$ "/Users/Me/Development/Web Projects/MySite/public_html/$1"
<Directory "/Users/Me/Development/Web Projects/MySite/public_html">
Order deny,allow
Allow from all
</Directory>
</VirtualHost>
</code></pre>
<p>Basically this setup will serve any request with a file extension (I limited mine to an extension of 5 characters or less) as a static file, and all other requests will go to my Django app.</p>
| 0 | 2009-10-04T17:24:12Z | [
"python",
"django",
"apache",
"mod-wsgi",
"cappuccino"
] |
How do you convert a string to a function in python? | 1,515,601 | <p>How do you convert a string (for example, input from a textbox) into a proper function?</p>
| 1 | 2009-10-04T04:36:16Z | 1,515,603 | <p>You can use <code>eval</code>. But be very careful! This opens up lots of security holes.</p>
<pre><code>>>> s = '3+4'
>>> eval(s)
7
</code></pre>
<p>If you want it callable:</p>
<pre><code>>>> s = '3+4'
>>> f = eval('lambda: ' + s)
>>> f()
7
</code></pre>
<p>More information on <code>eval</code> <a href="http://docs.python.org/library/functions.html" rel="nofollow">here</a>.</p>
| 6 | 2009-10-04T04:37:44Z | [
"python"
] |
How do you convert a string to a function in python? | 1,515,601 | <p>How do you convert a string (for example, input from a textbox) into a proper function?</p>
| 1 | 2009-10-04T04:36:16Z | 1,515,612 | <pre><code>def func():
print "hello"
# just eval it
eval(raw_input())
# if you just want to ask for name
fName=raw_input()
if fName in globals():
globals()[fName]()
</code></pre>
<p>And there could be various other ways depending on what is the objective?</p>
| 0 | 2009-10-04T04:42:33Z | [
"python"
] |
How do you convert a string to a function in python? | 1,515,601 | <p>How do you convert a string (for example, input from a textbox) into a proper function?</p>
| 1 | 2009-10-04T04:36:16Z | 5,253,997 | <p>try this </p>
<pre><code>func = ___import___('func_name')
</code></pre>
<p>or</p>
<pre><code>if hasattr(your_module, func_name): func = getattr(your_module, func_name)
</code></pre>
<p>or</p>
<pre><code>if func_name in globals(): func = globals[func_name]
</code></pre>
<p>or something etc</p>
| 1 | 2011-03-10T00:15:18Z | [
"python"
] |
is there any latest version of pyUIQ? | 1,515,630 | <p>i have tried to install python for symbian uiq 3..i have tried signed and unsigned version,but both installation failed..anyone faced same problem?so,do you have any solution? i am using sony ericsson G900..</p>
| 1 | 2009-10-04T04:52:25Z | 1,515,667 | <p>The latest release version of PyUIQ is 0.2, from YEARS ago, available <a href="http://sourceforge.net/projects/pyuiq/" rel="nofollow">here</a>. No sources in the CVS repo on sourceforge, either... looks pretty much like a dead project to me:-(. What do you need exactly?</p>
| 1 | 2009-10-04T05:19:27Z | [
"python",
"symbian"
] |
is there any latest version of pyUIQ? | 1,515,630 | <p>i have tried to install python for symbian uiq 3..i have tried signed and unsigned version,but both installation failed..anyone faced same problem?so,do you have any solution? i am using sony ericsson G900..</p>
| 1 | 2009-10-04T04:52:25Z | 1,516,008 | <p>Even though the pyUIQ version available is very old, you should be able to install it if you sign it properly. <a href="https://www.symbiansigned.com/app/page/public/openSignedOnline.do" rel="nofollow">Open Signed Online</a> should do it.</p>
| 0 | 2009-10-04T09:23:08Z | [
"python",
"symbian"
] |
Case insensitive urls for Django? | 1,515,634 | <p>It seems by default django's url solver perform case sensitive search for solving url and differentiate between '/Login' and 'login'. My url patterns are as follows.</p>
<pre><code>urlpatterns = patterns('',
(r'^admin/(.*)', admin.site.root),
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_DOC_ROOT, 'show_indexes': True}),
(r'^login/$', 'django.contrib.auth.views.login'),
(r'^logout/$', do_logout),
)
</code></pre>
<p>Can anyone please guide me, how to make django urls case insensitive?</p>
| 28 | 2009-10-04T04:56:10Z | 1,515,657 | <p>Just put <code>(?i)</code> at the start of every <code>r'...'</code> string, i.e.:</p>
<pre><code>urlpatterns = patterns('',
(r'^(?i)admin/(.*)', admin.site.root),
(r'^(?i)static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_DOC_ROOT, 'show_indexes': True}),
(r'^(?i)login/$', 'django.contrib.auth.views.login'),
(r'^(?i)logout/$', do_logout),
)
</code></pre>
<p>to tell every RE to match case-insensitively -- and, of course, live happily ever after!-)</p>
| 71 | 2009-10-04T05:12:44Z | [
"python",
"django"
] |
Non Blocking Server in Python | 1,515,686 | <p>Can someone please tell how to write a Non-Blocking server code using the socket library alone.Thanks</p>
| 0 | 2009-10-04T05:35:02Z | 1,515,694 | <p>Not sure what you mean by "socket library alone" - you surely will need other modules from the standard Python library.</p>
<p>The lowest level of non-blocking code is the <a href="http://docs.python.org/library/select.html" rel="nofollow">select module</a>. This allows you to have many simultaneous client connections, and reports which of them have input pending to process. So you select both the server (accept) socket, plus any client connections that you have already accepted. A thin layer on top of that is the asyncore module.</p>
| 0 | 2009-10-04T05:42:05Z | [
"python",
"sockets",
"nonblocking"
] |
Non Blocking Server in Python | 1,515,686 | <p>Can someone please tell how to write a Non-Blocking server code using the socket library alone.Thanks</p>
| 0 | 2009-10-04T05:35:02Z | 1,515,698 | <p>Why <code>socket</code> alone? It's <em>so</em> much simpler to use another standard library module, <code>asyncore</code> -- and if you can't, at the <strong>very</strong> least <code>select</code>!</p>
<p>If you're constrained by your homework's condition to only use <code>socket</code>, then I hope you can at least add <code>threading</code> (or <code>multiprocessing</code>), otherwise you're <em>seriously</em> out of luck -- you can make sockets with <code>timeout</code>, but juggling timing-out sockets without the needed help from any of the other obvious standard library modules (to support either async <strong>or</strong> threaded serving) is a serious mess indeed-y...;-).</p>
| 2 | 2009-10-04T05:44:01Z | [
"python",
"sockets",
"nonblocking"
] |
Non Blocking Server in Python | 1,515,686 | <p>Can someone please tell how to write a Non-Blocking server code using the socket library alone.Thanks</p>
| 0 | 2009-10-04T05:35:02Z | 1,515,708 | <p>Frankly, just don't (unless it's for an exercise). The <a href="http://twistedmatrix.com/">Twisted Framework</a> will do everything network-related for you, so you have to write only your protocol without caring about the transport layer. Writing socket code is not easy, so why not use code somebody else wrote and tested.</p>
| 5 | 2009-10-04T05:48:39Z | [
"python",
"sockets",
"nonblocking"
] |
Non Blocking Server in Python | 1,515,686 | <p>Can someone please tell how to write a Non-Blocking server code using the socket library alone.Thanks</p>
| 0 | 2009-10-04T05:35:02Z | 5,049,206 | <p>Use eventlets or gevent. It monkey patches existing libraries. socket module can be used without any changes. Though code appears synchronous, it executes asynchronously.</p>
<p>Example:
<a href="http://eventlet.net/doc/examples.html#socket-connect" rel="nofollow">http://eventlet.net/doc/examples.html#socket-connect</a></p>
| 0 | 2011-02-19T06:10:10Z | [
"python",
"sockets",
"nonblocking"
] |
How to remove existing background color of text when highlighting? | 1,515,809 | <p>I'm writing a small utility in Python that does some pattern matching of text. Text that matches the pattern the user has entered gets highlighted yellow. </p>
<p>I'm achieving this using a Tkinter <code>Text</code> widget, and setting up a tag on the Text widget named <code>"match"</code> that gives any text with the tag name <code>"match"</code> a yellow background. </p>
<p>This all looks nice, except when I try to highlight the text using the mouse (e.g. when wanting to copy/paste). When I highlight the text with the mouse, any of the tagged text that already has a yellow background retains its yellow background, even after being highlighted. This means you can't properly read the text when it's been highlighted by the mouse, as the white text (text goes white when highlighted by mouse) on a yellow background provides bad contrast.</p>
<p>What I would like to happen is that, when I highlight the text in the Text widget using the mouse, all of the text gets the standard blue background color/white text color that you'd normally get on a Windows machine when highlighting a section of text.</p>
<p>Here's a quick code snippet to demonstrate what I mean:</p>
<pre><code>from tkinter import *
root = Tk()
w = Text(root)
w.tag_config("match",background="yellow")
w.config(highlightbackground="red")
w.pack()
w.insert(INSERT,"some non-matching text.")
w.insert(INSERT,"some matching text.","match")
root.mainloop()
</code></pre>
<p>If you run this, and then highlight all of the text in the Text widget, you'll see that the text with the yellow background becomes very hard to read. </p>
<p>Note that in the code snippet above I've tried changing the highlight background color using:</p>
<pre><code>w.config(highlightbackground="red")
</code></pre>
<p>But this hasn't worked.</p>
| 1 | 2009-10-04T07:09:10Z | 1,516,840 | <p>I think you need to set <code>selectbackground</code>, not <code>highlightbackground</code> which means something completely different (the bg color for the "highlight rectangle" drawn around a widget when it gets focus). However, I believe the <code>sel</code> pseudo-tag (representing the selection, which is what I think you're calling "the highlight") is "below" user-created tags such as your <code>match</code>; if so, then the bg color for the user-created tag would show, not the bg color for the <code>sel</code> pseudo-tag (aka <code>selectbackground</code>).</p>
<p>With Tk 8.5 you could remedy that by binding to the <code><Selection></code> pseudo-event a function that places an appropriately colored user tag "on top" of pseudo-tag <code>sel</code>; however, there is no such event in Tk 8.4, which is what most likely you're using today. <a href="http://www.tkdocs.com/tutorial/install.html" rel="nofollow">TK's docs</a> say that 8.5 comes with Python 3.1 on the ActiveState distribution of Python for Windows; unfortunately there are only "TODO" placeholders regarding other platforms or other versions of Python -- I don't know how to best obtain Tk 8.5 for the specific platform(s) and python version(s) of your interest.</p>
| 0 | 2009-10-04T16:42:59Z | [
"python",
"colors",
"background",
"tkinter",
"highlight"
] |
How to remove existing background color of text when highlighting? | 1,515,809 | <p>I'm writing a small utility in Python that does some pattern matching of text. Text that matches the pattern the user has entered gets highlighted yellow. </p>
<p>I'm achieving this using a Tkinter <code>Text</code> widget, and setting up a tag on the Text widget named <code>"match"</code> that gives any text with the tag name <code>"match"</code> a yellow background. </p>
<p>This all looks nice, except when I try to highlight the text using the mouse (e.g. when wanting to copy/paste). When I highlight the text with the mouse, any of the tagged text that already has a yellow background retains its yellow background, even after being highlighted. This means you can't properly read the text when it's been highlighted by the mouse, as the white text (text goes white when highlighted by mouse) on a yellow background provides bad contrast.</p>
<p>What I would like to happen is that, when I highlight the text in the Text widget using the mouse, all of the text gets the standard blue background color/white text color that you'd normally get on a Windows machine when highlighting a section of text.</p>
<p>Here's a quick code snippet to demonstrate what I mean:</p>
<pre><code>from tkinter import *
root = Tk()
w = Text(root)
w.tag_config("match",background="yellow")
w.config(highlightbackground="red")
w.pack()
w.insert(INSERT,"some non-matching text.")
w.insert(INSERT,"some matching text.","match")
root.mainloop()
</code></pre>
<p>If you run this, and then highlight all of the text in the Text widget, you'll see that the text with the yellow background becomes very hard to read. </p>
<p>Note that in the code snippet above I've tried changing the highlight background color using:</p>
<pre><code>w.config(highlightbackground="red")
</code></pre>
<p>But this hasn't worked.</p>
| 1 | 2009-10-04T07:09:10Z | 1,516,883 | <p>Tags have priority. Tags with a high priority have preference over those that have a lower priority. When you select a range of text it is given the tag "sel". You simply need to raise the priority of the "sel" tag to be above the priority of your "match" tag:</p>
<pre><code>w.tag_raise("sel")
</code></pre>
<p>Alex Martelli writes in the comments "it will do the OP absoluely [sic] no good if he sets highlightbackground instead of selectbackground" but that is incorrect. While he is correct that setting highlightbackground has nothing to do with the selection, it has no bearing on this solution. </p>
<p>Raising the priority of the "sel" tag works with the code in the original question, with or without the addition of the code that sets highlightbackground. </p>
<p>For more information on the text widget check out the <a href="http://www.tkdocs.com/tutorial/text.html" rel="nofollow">text widget tutorial on tkdocs.com</a>. It has code examples in Tcl, Python, Ruby and Perl. </p>
| 3 | 2009-10-04T17:04:59Z | [
"python",
"colors",
"background",
"tkinter",
"highlight"
] |
how to run both python 2.6 and 3.0 on the same windows XP box? | 1,515,850 | <p>What kind of setup do people use to run both python 2.6 and python 3.0 on the same windows machine?</p>
| 3 | 2009-10-04T07:45:12Z | 1,515,858 | <p>Why do you want to do it? Everything that's in 3.0 is in 2.6, you can use the new features in 3.0 with <code>from __future__ import</code>. Run 2.6 until you're ready to upgrade to 3.0 for everything, then upgrade. You're not intended to have multiple versions of Python on the same machine. If you really want to, you can specify alternative install directories, but I really don't see how it's worth the hassle.</p>
| 0 | 2009-10-04T07:51:15Z | [
"python",
"windows-xp"
] |
how to run both python 2.6 and 3.0 on the same windows XP box? | 1,515,850 | <p>What kind of setup do people use to run both python 2.6 and python 3.0 on the same windows machine?</p>
| 3 | 2009-10-04T07:45:12Z | 1,515,859 | <p>No problem, each version is installed in its own directory. On my Windows box, I have <code>C:\Python26\</code> and <code>C:\Python31\</code>. The <em>Start Menu</em> items are also distinct. Just use the standard installers from the Python Programming Language <a href="http://www.python.org/download/" rel="nofollow">Official Website</a>, or the ready-to-install distributions from <a href="http://www.activestate.com/activepython/" rel="nofollow">ActiveState</a>.</p>
<p>A direct way to select the wanted version is to name it explicitly on the command line.</p>
<pre><code>C:\> C:\Python25\python ver.py
2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)]
C:\> C:\Python31\python ver.py
3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)]
</code></pre>
<p>Where <code>ver.py</code> is:</p>
<pre><code>import sys
print (sys.version)
</code></pre>
| 9 | 2009-10-04T07:51:59Z | [
"python",
"windows-xp"
] |
how to run both python 2.6 and 3.0 on the same windows XP box? | 1,515,850 | <p>What kind of setup do people use to run both python 2.6 and python 3.0 on the same windows machine?</p>
| 3 | 2009-10-04T07:45:12Z | 1,515,971 | <p>-You could use a batch file to launch with the appropriate version.</p>
<p>-Eclipse with pydev allows you to choose which version to launch with.</p>
<p>-Re-associate the .py/.pyw extension with your preferred version. </p>
| 1 | 2009-10-04T09:00:29Z | [
"python",
"windows-xp"
] |
how to run both python 2.6 and 3.0 on the same windows XP box? | 1,515,850 | <p>What kind of setup do people use to run both python 2.6 and python 3.0 on the same windows machine?</p>
| 3 | 2009-10-04T07:45:12Z | 1,517,045 | <p><a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">Virtualenv</a> is the solution of choice on Unix and Mac platforms. </p>
<blockquote>
<p>virtualenv is a tool to create
isolated Python environments.</p>
<p>The basic problem being addressed is
one of dependencies and versions, and
indirectly permissions. Imagine you
have an application that needs version
1 of LibFoo, but another application
requires version 2. How can you use
both these applications? If you
install everything into
/usr/lib/python2.4/site-packages (or
whatever your platform's standard
location is), it's easy to end up in a
situation where you unintentionally
upgrade an application that shouldn't
be upgraded.</p>
<p>Or more generally, what if you want to
install an application and leave it
be? If an application works, any
change in its libraries or the
versions of those libraries can break
the application.</p>
<p>Also, what if you can't install
packages into the global site-packages
directory? For instance, on a shared
host.</p>
</blockquote>
<p>I have not tried this, but the presence of documentation relating to use in Windows makes me think that it now works on Windows.</p>
| 1 | 2009-10-04T18:25:45Z | [
"python",
"windows-xp"
] |
how to run both python 2.6 and 3.0 on the same windows XP box? | 1,515,850 | <p>What kind of setup do people use to run both python 2.6 and python 3.0 on the same windows machine?</p>
| 3 | 2009-10-04T07:45:12Z | 1,517,110 | <blockquote>
<p>Interesting, but I want to be able to learn the 3.0 syntax (print()) etc but still need to maintain some 2.5 and 2.6 code..</p>
</blockquote>
<p>Python has <a href="http://docs.python.org/library/%5F%5Ffuture%5F%5F.html" rel="nofollow"><code>__future__</code> "Future statement definitions"</a>, which make new features available in older versions of Python, the print function is one of them:</p>
<pre><code>Python 2.6.1 (r261:67515, Jul 7 2009, 23:51:51)
>>> from __future__ import print_function
>>> print("Example", end=" Hurray!\n")
Example Hurray!
</code></pre>
<p>Another big Python 3.0 change is the default string becoming Unicode:</p>
<pre><code>>>> from __future__ import unicode_literals
>>> type('abc')
<type 'unicode'>
>>> 'a'
u'a'
</code></pre>
<p>Most of the others are now part of Python 2.6, so aren't of interest (like the <code>with_statement</code>). The only one I didn't mention is <code>from __future__ import braces</code> to allow "C like" <code>if(){}</code> braces</p>
| 1 | 2009-10-04T18:55:08Z | [
"python",
"windows-xp"
] |
Does C++ have an equivilent to Python's __setitem__ | 1,515,899 | <p>Just as the title asks, does C++ have the equivalent of Python's <strong>setitem</strong> and <strong>getitem</strong> for classes?</p>
<p>Basically it allows you to do something like the following.</p>
<pre><code>MyClass anObject;
anObject[0] = 1;
anObject[1] = "foo";
</code></pre>
| 2 | 2009-10-04T08:18:08Z | 1,515,903 | <p>basically, you overload the subscript operator (<code>operator[]</code>), and it returns a reference (so it can be read as well as written to)</p>
| 6 | 2009-10-04T08:19:58Z | [
"c++",
"python"
] |
Does C++ have an equivilent to Python's __setitem__ | 1,515,899 | <p>Just as the title asks, does C++ have the equivalent of Python's <strong>setitem</strong> and <strong>getitem</strong> for classes?</p>
<p>Basically it allows you to do something like the following.</p>
<pre><code>MyClass anObject;
anObject[0] = 1;
anObject[1] = "foo";
</code></pre>
| 2 | 2009-10-04T08:18:08Z | 1,515,911 | <p>You can overload the [] operator, but it's not quite the same as a separate getitem/setitem method pair, in that you don't get to specify different handling for getting and setting.</p>
<p>But you can get close by returning a temporary object that overrides the assignment operator.</p>
| 6 | 2009-10-04T08:24:03Z | [
"c++",
"python"
] |
Does C++ have an equivilent to Python's __setitem__ | 1,515,899 | <p>Just as the title asks, does C++ have the equivalent of Python's <strong>setitem</strong> and <strong>getitem</strong> for classes?</p>
<p>Basically it allows you to do something like the following.</p>
<pre><code>MyClass anObject;
anObject[0] = 1;
anObject[1] = "foo";
</code></pre>
| 2 | 2009-10-04T08:18:08Z | 1,516,083 | <p>There's an interesting discussion about what's possible (and what's not) in C++ with subscript operators in <a href="http://www.ddj.com/cpp/184406037" rel="nofollow">this article</a>.</p>
| 3 | 2009-10-04T10:10:00Z | [
"c++",
"python"
] |
Does C++ have an equivilent to Python's __setitem__ | 1,515,899 | <p>Just as the title asks, does C++ have the equivalent of Python's <strong>setitem</strong> and <strong>getitem</strong> for classes?</p>
<p>Basically it allows you to do something like the following.</p>
<pre><code>MyClass anObject;
anObject[0] = 1;
anObject[1] = "foo";
</code></pre>
| 2 | 2009-10-04T08:18:08Z | 1,516,248 | <p>To expand on Earwicker post:</p>
<pre><code>#include <string>
#include <iostream>
template <typename Type>
class Vector
{
public:
template <typename Element>
class ReferenceWrapper
{
public:
explicit ReferenceWrapper(Element& elem)
: elem_(elem)
{
}
// Similar to Python's __getitem__.
operator const Type&() const
{
return elem_;
}
// Similar to Python's __setitem__.
ReferenceWrapper& operator=(const Type& rhs)
{
elem_ = rhs;
return *this;
}
// Helper when Type is defined in another namespace.
friend std::ostream& operator<<(std::ostream& os, const ReferenceWrapper& rhs)
{
return os << rhs.operator const Type&();
}
private:
Element& elem_;
};
explicit Vector(size_t sz)
: vec_(sz)
{
}
ReferenceWrapper<const Type> operator[](size_t ix) const
{
return ReferenceWrapper<const Type>(vec_[ix]);
}
ReferenceWrapper<Type> operator[](size_t ix)
{
return ReferenceWrapper<Type>(vec_[ix]);
}
private:
std::vector<Type> vec_;
};
int main()
{
Vector<std::string> v(10);
std::cout << v[5] << "\n";
v[5] = "42";
std::cout << v[5] << "\n";
}
</code></pre>
| 1 | 2009-10-04T12:10:04Z | [
"c++",
"python"
] |
Does C++ have an equivilent to Python's __setitem__ | 1,515,899 | <p>Just as the title asks, does C++ have the equivalent of Python's <strong>setitem</strong> and <strong>getitem</strong> for classes?</p>
<p>Basically it allows you to do something like the following.</p>
<pre><code>MyClass anObject;
anObject[0] = 1;
anObject[1] = "foo";
</code></pre>
| 2 | 2009-10-04T08:18:08Z | 1,516,272 | <p>It's not portable, but MSVC has <a href="http://msdn.microsoft.com/en-us/library/yhfk0thd%28VS.80%29.aspx" rel="nofollow">__declspec(property)</a>, which also allows indexers:</p>
<pre><code>struct Foo
{
void SetFoo(int index, int value) { ... }
int GetFoo(int index) { ... }
__declspec(property(propget=GetFoo, propput=SetFoo)) int Foo[];
}
</code></pre>
<p>other than that, Earwicker did outline the portable solution, but he's right that you'll run into many problems. </p>
| 1 | 2009-10-04T12:19:00Z | [
"c++",
"python"
] |
How can google app engine report progress back on file upload | 1,515,978 | <p>I have been trying to use an ajax-style file upload component (like the dojox file upload component) with google app engine, and have a progress bar. </p>
<p>The javascript side of things is fine, but i am wondering how to organise things on the server side? </p>
<p>Is is possible to access the data as it is being uploaded within google app engine, something with BaseHTTPServer perhaps? I could then poll this from the client. </p>
<p>Even if it wasn't possible to do the progress, at least it would be great to be able to terminate a large file and let the user know it was to big without making the user upload 1MB (the google app engine limit) and then find out it was to big. </p>
<p>There are some similar questions: <a href="http://stackoverflow.com/questions/1298565/file-upload-progress">Similar stack overflow question 1</a>, <a href="http://stackoverflow.com/questions/1478434/how-is-the-file-uploading-progress-reported">Similar stack overflow question 2</a>.</p>
<p>The following google app engine python code is just the basic post handler for a simple file upload (which works fine) but im looking for something that operates at a bit of a lower level. By the time the post handler gets it, the file has all been uploaded. </p>
<p>On a LAMP stack you can poll a server side script that watches a temporary file size grow. When the file is moved from the temporary folder you know its completed. By using this method you can see the progress of multiple files without the use of flash, I'm not sure how to do the same thing with google app engine. </p>
<pre><code>class fileupload(webapp.RequestHandler):
"""
"""
def post(self):
if "image" in self.request.arguments():
content = "<html><body>Error</body></html>"
form = self.request.params['image']
logging.info(form)
try:
filename = form.filename
siz = len(form.value)
###--- Show data
logging.info("Filename: %s" % form.filename)
logging.info("Size: %s" % siz)
content = "<html><body>File has been uploaded Name: %s Size: %s</body></html>" % (filename, siz)
logging.info("DONE")
except:
logging.info("Error: bad form or something like that")
logging.info("writing out response")
self.response.out.write(content)
</code></pre>
| 0 | 2009-10-04T09:04:13Z | 1,516,097 | <p>You can limit file size on a client site using <a href="http://code.google.com/p/swfupload/" rel="nofollow">swfupload</a>. </p>
<p>It's a flash component with javascript api that exposes flash uploading capabilities.
The check of a file size is done in the client browser. (in function <a href="http://code.google.com/p/swfupload/source/browse/swfupload/trunk/core/Flash/SWFUpload.as#1341" rel="nofollow">CheckFileSize</a>) </p>
<p>The library has also other goodies like progress bar, check it home page for full feature list.</p>
| 1 | 2009-10-04T10:20:48Z | [
"python",
"google-app-engine",
"progress-bar"
] |
How can google app engine report progress back on file upload | 1,515,978 | <p>I have been trying to use an ajax-style file upload component (like the dojox file upload component) with google app engine, and have a progress bar. </p>
<p>The javascript side of things is fine, but i am wondering how to organise things on the server side? </p>
<p>Is is possible to access the data as it is being uploaded within google app engine, something with BaseHTTPServer perhaps? I could then poll this from the client. </p>
<p>Even if it wasn't possible to do the progress, at least it would be great to be able to terminate a large file and let the user know it was to big without making the user upload 1MB (the google app engine limit) and then find out it was to big. </p>
<p>There are some similar questions: <a href="http://stackoverflow.com/questions/1298565/file-upload-progress">Similar stack overflow question 1</a>, <a href="http://stackoverflow.com/questions/1478434/how-is-the-file-uploading-progress-reported">Similar stack overflow question 2</a>.</p>
<p>The following google app engine python code is just the basic post handler for a simple file upload (which works fine) but im looking for something that operates at a bit of a lower level. By the time the post handler gets it, the file has all been uploaded. </p>
<p>On a LAMP stack you can poll a server side script that watches a temporary file size grow. When the file is moved from the temporary folder you know its completed. By using this method you can see the progress of multiple files without the use of flash, I'm not sure how to do the same thing with google app engine. </p>
<pre><code>class fileupload(webapp.RequestHandler):
"""
"""
def post(self):
if "image" in self.request.arguments():
content = "<html><body>Error</body></html>"
form = self.request.params['image']
logging.info(form)
try:
filename = form.filename
siz = len(form.value)
###--- Show data
logging.info("Filename: %s" % form.filename)
logging.info("Size: %s" % siz)
content = "<html><body>File has been uploaded Name: %s Size: %s</body></html>" % (filename, siz)
logging.info("DONE")
except:
logging.info("Error: bad form or something like that")
logging.info("writing out response")
self.response.out.write(content)
</code></pre>
| 0 | 2009-10-04T09:04:13Z | 1,516,405 | <p>App Engine won't return any data from the request handler until the after the request is completed, so any progress checking would have to be done client-side. IIRC your request won't even be loaded into the application server until the upload is complete.</p>
| 1 | 2009-10-04T13:28:02Z | [
"python",
"google-app-engine",
"progress-bar"
] |
How can google app engine report progress back on file upload | 1,515,978 | <p>I have been trying to use an ajax-style file upload component (like the dojox file upload component) with google app engine, and have a progress bar. </p>
<p>The javascript side of things is fine, but i am wondering how to organise things on the server side? </p>
<p>Is is possible to access the data as it is being uploaded within google app engine, something with BaseHTTPServer perhaps? I could then poll this from the client. </p>
<p>Even if it wasn't possible to do the progress, at least it would be great to be able to terminate a large file and let the user know it was to big without making the user upload 1MB (the google app engine limit) and then find out it was to big. </p>
<p>There are some similar questions: <a href="http://stackoverflow.com/questions/1298565/file-upload-progress">Similar stack overflow question 1</a>, <a href="http://stackoverflow.com/questions/1478434/how-is-the-file-uploading-progress-reported">Similar stack overflow question 2</a>.</p>
<p>The following google app engine python code is just the basic post handler for a simple file upload (which works fine) but im looking for something that operates at a bit of a lower level. By the time the post handler gets it, the file has all been uploaded. </p>
<p>On a LAMP stack you can poll a server side script that watches a temporary file size grow. When the file is moved from the temporary folder you know its completed. By using this method you can see the progress of multiple files without the use of flash, I'm not sure how to do the same thing with google app engine. </p>
<pre><code>class fileupload(webapp.RequestHandler):
"""
"""
def post(self):
if "image" in self.request.arguments():
content = "<html><body>Error</body></html>"
form = self.request.params['image']
logging.info(form)
try:
filename = form.filename
siz = len(form.value)
###--- Show data
logging.info("Filename: %s" % form.filename)
logging.info("Size: %s" % siz)
content = "<html><body>File has been uploaded Name: %s Size: %s</body></html>" % (filename, siz)
logging.info("DONE")
except:
logging.info("Error: bad form or something like that")
logging.info("writing out response")
self.response.out.write(content)
</code></pre>
| 0 | 2009-10-04T09:04:13Z | 4,482,642 | <p>This won't work for every browser, but it's a nice way of doing multiple file uploads via AJAX:</p>
<pre><code>function upload_files(entityKey, files, url, progress_callback) {
var xhr = new XMLHttpRequest(), formData = new FormData();
xhr.upload['onprogress'] = progress_callback;
formData.append('entityKey', entityKey);
$.each(files, function(i, file) { formData.append('file[]', file);});
xhr.open("post", url, true);
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.send(formData);
}
</code></pre>
<p>The entityKey is an example of a parameter on the server. The 'files' parameter comes from the 'files' attribute of the file-type input form element (as an array to support multiple). The 'progress_callback' parameter is a function that takes an object that has (at least) a 'loaded' and a 'total' field (unit is bytes). It doesn't care about the server response.</p>
| 1 | 2010-12-19T11:07:47Z | [
"python",
"google-app-engine",
"progress-bar"
] |
How to set explicitly the terminal size when using pexpect | 1,516,025 | <p>I have a ncurses app that checks terminal size at startup and exits immediately if it doesn't fit.</p>
<p>In Linux, the default size is 80x24, this app requires at least 25. The fix is easy, I'm just resizing the terminal emulation window (in X) before running the ncurses app.</p>
<p>I would like to automate the ncurses app with pexpect, but I'm getting stuck because it considers the terminal size smaller than required when launched through pexpect, so it doesn't run. Any way to specify the terminal size with pexpect explicitly at startup?</p>
| 4 | 2009-10-04T09:35:43Z | 1,516,182 | <p>Try setting the LINES and COLUMNS environment variables before you use pexpect.</p>
<p>Pexpect will pass on the environment to the subtask, and some (all?) curses programs read these environment variables before starting.</p>
<p>eg</p>
<pre><code>import os
os.environ['LINES'] = "25"
os.environ['COLUMNS'] = "80"
# run pexpect stuff as before
</code></pre>
| 4 | 2009-10-04T11:20:19Z | [
"python",
"linux",
"pexpect"
] |
How to set explicitly the terminal size when using pexpect | 1,516,025 | <p>I have a ncurses app that checks terminal size at startup and exits immediately if it doesn't fit.</p>
<p>In Linux, the default size is 80x24, this app requires at least 25. The fix is easy, I'm just resizing the terminal emulation window (in X) before running the ncurses app.</p>
<p>I would like to automate the ncurses app with pexpect, but I'm getting stuck because it considers the terminal size smaller than required when launched through pexpect, so it doesn't run. Any way to specify the terminal size with pexpect explicitly at startup?</p>
| 4 | 2009-10-04T09:35:43Z | 10,946,444 | <p>You can also use :</p>
<pre><code>import pexpect
child = pexpect.spawn(cmd)
child.setwinsize(400,400)
</code></pre>
| 3 | 2012-06-08T09:41:01Z | [
"python",
"linux",
"pexpect"
] |
chess AI for GAE | 1,516,223 | <p>I am looking for a Chess AI that can be run on Google App Engine. Most chess AI's seem to be written in C and so can not be run on the GAE. It needs to be strong enough to beat a casual player, but efficient enough that it can calculate a move within a single request (less than 10 secs).</p>
<p>Ideally it would be written in Python for easier integration with existing code.</p>
<p>I came across a few promising projects but they don't look mature:</p>
<ul>
<li><a href="http://code.google.com/p/chess-free">http://code.google.com/p/chess-free</a></li>
<li><a href="http://mariobalibrera.com/mics/ai.html">http://mariobalibrera.com/mics/ai.html</a></li>
</ul>
| 5 | 2009-10-04T11:57:20Z | 1,516,512 | <p>This problem is a poor match for the GAE architecture, which is designed for efficient CRUD operations, and not CPU-intensive tasks. In practice, anything that takes more than a few tens of milliseconds per request will blow out your CPU quota pretty quickly.</p>
| 1 | 2009-10-04T14:14:28Z | [
"python",
"google-app-engine",
"artificial-intelligence",
"chess"
] |
chess AI for GAE | 1,516,223 | <p>I am looking for a Chess AI that can be run on Google App Engine. Most chess AI's seem to be written in C and so can not be run on the GAE. It needs to be strong enough to beat a casual player, but efficient enough that it can calculate a move within a single request (less than 10 secs).</p>
<p>Ideally it would be written in Python for easier integration with existing code.</p>
<p>I came across a few promising projects but they don't look mature:</p>
<ul>
<li><a href="http://code.google.com/p/chess-free">http://code.google.com/p/chess-free</a></li>
<li><a href="http://mariobalibrera.com/mics/ai.html">http://mariobalibrera.com/mics/ai.html</a></li>
</ul>
| 5 | 2009-10-04T11:57:20Z | 1,516,519 | <p>What's wrong with <a href="http://pychess.googlepages.com/" rel="nofollow">PyChess</a>? It's pure Python, fairly mature, and will certainly be able to beat a casual player.</p>
<p>It's been a while since I've used PyChess, but a quick glance through <a href="http://code.google.com/p/pychess/source/browse/trunk/lib/pychess/Players/PyChess.py?r=1496" rel="nofollow">some of the source</a>
<em>does</em> indicate that you can set a time limit on how long to search for a move.</p>
<p>The PyChess engine that is written in pure Python is in <a href="http://code.google.com/p/pychess/source/browse/#svn/trunk/lib/pychess/Utils" rel="nofollow">pychess.Utils</a>. Specifically, if you look at <a href="http://code.google.com/p/pychess/source/browse/trunk/lib/pychess/Utils/#Utils/lutils" rel="nofollow">pychess.Utils.lutils</a>, you can see for instance <a href="http://code.google.com/p/pychess/source/browse/trunk/lib/pychess/Utils/lutils/lmovegen.py" rel="nofollow">the move generator written in Python</a>. </p>
| 5 | 2009-10-04T14:18:27Z | [
"python",
"google-app-engine",
"artificial-intelligence",
"chess"
] |
Python: List Sorting with Multiple Attributes and Mixed Order | 1,516,249 | <p>I have to sort a python list, with multiple attributes. I can do that in ascending order for ALL attributes easily with</p>
<pre><code>L.sort(key=operator.attrgetter(attribute))....
</code></pre>
<p>but the problem is, that I have use mixed configurations for ascending/descending... I have to "imitate" a bit the SQL Order By where you can do something like "name ASC, year DESC".
Is there a way to do this easily in python without having to implement a custom compare function?</p>
| 12 | 2009-10-04T12:10:07Z | 1,516,265 | <p>You can't, but writing the compare function is easy:</p>
<pre><code>def my_cmp(a, b):
return cmp(a.foo, b.foo) or cmp(b.bar, a.bar)
L.sort(my_cmp)
</code></pre>
| 4 | 2009-10-04T12:16:59Z | [
"python",
"list",
"sorting"
] |
Python: List Sorting with Multiple Attributes and Mixed Order | 1,516,249 | <p>I have to sort a python list, with multiple attributes. I can do that in ascending order for ALL attributes easily with</p>
<pre><code>L.sort(key=operator.attrgetter(attribute))....
</code></pre>
<p>but the problem is, that I have use mixed configurations for ascending/descending... I have to "imitate" a bit the SQL Order By where you can do something like "name ASC, year DESC".
Is there a way to do this easily in python without having to implement a custom compare function?</p>
| 12 | 2009-10-04T12:10:07Z | 1,516,290 | <p>A custom function will render your code more readable. If you have many sorting operations and you don't want to create those functions though, you can use lambda's:</p>
<pre><code>L.sort(lambda x, y: cmp(x.name, y.name) or -cmp(x.year, y.year))
</code></pre>
| 6 | 2009-10-04T12:26:50Z | [
"python",
"list",
"sorting"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.