content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Python List not getting in rendered in javascript I have a javascript which takes two variables i.e two lists one is a list of numbers and the other list of strings from django/python numbersvar = [0,1,2,3] stringsvar = ['a','b','c'] The numbersvar is rendered perfectly but when I do {{stringsvar}} it does not render it. A: Maybe it will be better to use a json module to create a javascript lists? >>> a = ['stste', 'setset', 'serthjsetj'] >>> b = json.dumps(a) >>> b '["stste", "setset", "serthjsetj"]' >>> json.loads(b) [u'stste', u'setset', u'serthjsetj'] A: What does stringsvar contain? The list, or the string representation of the list? I suggest you pass the correct javascript string representation of the list from the view method to the template to render. Python and javascript array literals have the same syntax, so you could do: def my_view(request): return render_template("...", stringsvar=str(the_list)) And in the template: <script language="javascript"> stringsvar = {{ stringsvar }}; ... </script> Or you can use the json serializer, this has the added benefit that you will be able to pass other kinds of values as well. from django.core import serializers def my_view(request): return render_template("...", stringsvar=serializers.serialize("json", the_list))
Python List not getting in rendered in javascript
I have a javascript which takes two variables i.e two lists one is a list of numbers and the other list of strings from django/python numbersvar = [0,1,2,3] stringsvar = ['a','b','c'] The numbersvar is rendered perfectly but when I do {{stringsvar}} it does not render it.
[ "Maybe it will be better to use a json module to create a javascript lists?\n>>> a = ['stste', 'setset', 'serthjsetj']\n>>> b = json.dumps(a)\n>>> b\n'[\"stste\", \"setset\", \"serthjsetj\"]'\n>>> json.loads(b)\n[u'stste', u'setset', u'serthjsetj']\n\n", "What does stringsvar contain? The list, or the string representation of the list?\nI suggest you pass the correct javascript string representation of the list from the view method to the template to render. Python and javascript array literals have the same syntax, so you could do:\ndef my_view(request):\n return render_template(\"...\", stringsvar=str(the_list))\n\nAnd in the template:\n<script language=\"javascript\">\nstringsvar = {{ stringsvar }};\n...\n</script>\n\nOr you can use the json serializer, this has the added benefit that you will be able to pass other kinds of values as well.\nfrom django.core import serializers\ndef my_view(request):\n return render_template(\"...\", stringsvar=serializers.serialize(\"json\", the_list))\n\n" ]
[ 3, 0 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0002100233_javascript_python.txt
Q: Is there a javascript equivalent to unpack sequences like in python? Is there a javascript equivalent to unpack sequences like in python? a, b = (1, 2) A: [a, b] = [1, 2] Update: Browser compatibility matrix: Firefox: all versions Opera: 9.x only Chrome: 49 and higher MSIE: no EdgeHTML: 14 (Browser version 31, released Feb. 2016) Safari: 7.1 (8 for Safari Mobile) A: There isn't. JavaScript doesn't have such syntax sugar.
Is there a javascript equivalent to unpack sequences like in python?
Is there a javascript equivalent to unpack sequences like in python? a, b = (1, 2)
[ "[a, b] = [1, 2]\n\nUpdate:\nBrowser compatibility matrix:\n\nFirefox: all versions\nOpera: 9.x only\nChrome: 49 and higher\nMSIE: no\nEdgeHTML: 14 (Browser version 31, released Feb. 2016)\nSafari: 7.1 (8 for Safari Mobile)\n\n", "There isn't. JavaScript doesn't have such syntax sugar.\n" ]
[ 15, 8 ]
[ "An object cannot contain a reference to an integer, only its value. So I can't see any way to do what you ask in javascript.\n" ]
[ -4 ]
[ "iterable_unpacking", "javascript", "python" ]
stackoverflow_0002100731_iterable_unpacking_javascript_python.txt
Q: Python sockets, how to escape from infinite loop and handle exceptions I have a script that connects to a remote server. The code is below s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((remote_host,remote_port)) s.setblocking(False) while True: try: data = s.recv(1024) if not data: break pkt_type = ord(data[2]) # get pkt type if pkt_type == Reset: s.send(data) if pkt_type == Authenticate: processAuthenticate(s,data) break except: pass while(True) . . . I wait for reset and echo back to the server, then wait for an Authenticate packet, twiddle a few bit and echo that back to the server. Once this is done successfully I can now request data from the the server. This is done in the next while(true) loop. Is this the best way of doing this. Sometimes when I run the script I get an error, what is the simplest way of handling the exception and preventing execuation of the next wile loop? Thanks A: A Finite State Machine (FSM) is pretty much the canonical way to do this sort of thing. A good reference for doing FSMs in Python is this: http://wiki.python.org/moin/FiniteStateMachine A: EDIT: Looks like a FSM should be handy here. Actually, I suggest you take a look at Twisted Reactor - haven't used it myself (yet), but it does all the bulk work and nasty stuff that you would have to implement yourself if using a FSM and an event loop (which your while -loop essentially is) EDIT 2: A few notes (while waiting for your complete code) the fact that you have 2 consecutive while(true) is, well, odd you probably want to move the except: statement up, before the if not data statement and replace pass with continue ord(data[2]) suggests that you are using a binary protocol, you really should consider using the struct modules unpack() and pack() instead. A: In addition to the above tips, you need to buffer the data - when using a stream protocol you can't just assume that you will get all the data you want in one call to recv. Instead you must take what you read from recv and add it to a buffer, then examine the buffer to see if it contains all the data for a message yet. If it does, extract the message, handle it, then repeat with the rest of the buffer. When you can't extract any further messages, you go back and read more from the socket.
Python sockets, how to escape from infinite loop and handle exceptions
I have a script that connects to a remote server. The code is below s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((remote_host,remote_port)) s.setblocking(False) while True: try: data = s.recv(1024) if not data: break pkt_type = ord(data[2]) # get pkt type if pkt_type == Reset: s.send(data) if pkt_type == Authenticate: processAuthenticate(s,data) break except: pass while(True) . . . I wait for reset and echo back to the server, then wait for an Authenticate packet, twiddle a few bit and echo that back to the server. Once this is done successfully I can now request data from the the server. This is done in the next while(true) loop. Is this the best way of doing this. Sometimes when I run the script I get an error, what is the simplest way of handling the exception and preventing execuation of the next wile loop? Thanks
[ "A Finite State Machine (FSM) is pretty much the canonical way to do this sort of thing. A good reference for doing FSMs in Python is this: http://wiki.python.org/moin/FiniteStateMachine\n", "EDIT:\nLooks like a FSM should be handy here.\nActually, I suggest you take a look at Twisted Reactor - haven't used it myself (yet), but it does all the bulk work and nasty stuff that you would have to implement yourself if using a FSM and an event loop (which your while -loop essentially is)\nEDIT 2:\nA few notes (while waiting for your complete code)\n\nthe fact that you have 2 consecutive while(true) is, well, odd\nyou probably want to move the except: statement up, before the if not data statement and replace pass with continue\nord(data[2]) suggests that you are using a binary protocol, you really should consider using the struct modules unpack() and pack() instead.\n\n", "In addition to the above tips, you need to buffer the data - when using a stream protocol you can't just assume that you will get all the data you want in one call to recv. Instead you must take what you read from recv and add it to a buffer, then examine the buffer to see if it contains all the data for a message yet. If it does, extract the message, handle it, then repeat with the rest of the buffer. When you can't extract any further messages, you go back and read more from the socket.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "communication_protocol", "python", "sockets" ]
stackoverflow_0002100224_communication_protocol_python_sockets.txt
Q: Making a web interface to a script that takes 30 minutes to execute I wrote a python script to process some data from CSV files. The script takes between 3 to 30 minutes to complete, depending on the size of the CSV. Now I want to put in a web interface to this, so I can upload the CSV data files from anywhere. I wrote a basic HTTP POST upload page and used Python's CGI module - but the script just times out after some time. The script outputs HTTP headers at the start, and outputs bits of data after iterating over every line of the CSV. As an example, this print statement would trigger every 30 seconds or so. # at the very top, with the 'import's print "Content-type: text/html\n\n Processing ... <br />" # the really long loop. for currentRecord in csvRecords: count = count + 1 print "On line " + str(count) + " <br />" I assumed the browser would receive the headers, and wait since it keeps on receiving little bits of data. But what actually seems to happen is it doesn't receive any data at all, and Error 504 times out when given a CSV with lots of lines. Perhaps there's some caching happening somewhere? From the logs, [Wed Jan 20 16:59:09 2010] [error] [client ::1] Script timed out before returning headers: datacruncher.py, referer: http://localhost/index.htm [Wed Jan 20 17:04:09 2010] [warn] [client ::1] Timeout waiting for output from CGI script /Library/WebServer/CGI-Executables/datacruncher.py, referer: http://localhost/index.htm What's the best way to resolve this, or, is it not appropriate to run such scripts in a browser? Edit: This is a script for my own use - I normally intend to use it on my computer, but I thought a web-based interface could come in handy while travelling, or for example from a phone. Also, there's really nothing to download - the script will most probably e-mail a report off at the end. A: I would separate the work like this: A web app URL that accept the POSTed CSV file. The web app puts the CSV content into an off line queue, for instance a database table. The web app's response should be an unique ID for the queued item (use an auto-incremented ID column, for instance). The client must store this ID for part 3. A stand-alone service app that polls the queue for work, and does the processing. Upon completion of the processing, store the results in another database table, using the unique ID as a key. A web app URL that can get processed results, http://server/getresults/uniqueid/. If the processing is finished (i.e. the unique ID is found in the results database table), then return the results. If not finished, the response should be a code that indicates this. For instance a custom HTTP header, a HTTP status response, response body 'PENDING' or similar. A: I've had this situation before and I used cronjobs. The HTTP script would just write in a queue a job to be performed (a DB or a file in a directory) and the cronjob would read it and execute that job. A: You'll probably need to do a stdout.flush(), as the script isn't really writing anything yet to the webserver until you've written a page buffer's worth of data - which doesn't happen before the timeout. But the proper way to solve this is, as others suggested, to do the processing in a separate thread/process, and show the user an auto-refreshed page which shows the status, with a progress bar or some other fancy visual to keep them from being bored. A: See Randal Schwartz's Watching long processes through CGI. The article uses Perl, but the technique does not depend on the language. A: Very similar question here. I suggest spawning off the lengthy process and returning an ajax based progress bar to the user. This way they user has the luxury of the web-interface and you have the luxury of no time-outs. A: imho the best way would be to run an independent script which posts updates somewhere (flat file, database, etc...). I don't know how to fork an independent process from python so i can't give any code examples. To show progress on a WebSite implement an ajax request to a page that reads those status updates and for example shows a nice progress bar. Add something like setTimeout("refreshProgressBar[...]) or meta-refresh for auto-refresh.
Making a web interface to a script that takes 30 minutes to execute
I wrote a python script to process some data from CSV files. The script takes between 3 to 30 minutes to complete, depending on the size of the CSV. Now I want to put in a web interface to this, so I can upload the CSV data files from anywhere. I wrote a basic HTTP POST upload page and used Python's CGI module - but the script just times out after some time. The script outputs HTTP headers at the start, and outputs bits of data after iterating over every line of the CSV. As an example, this print statement would trigger every 30 seconds or so. # at the very top, with the 'import's print "Content-type: text/html\n\n Processing ... <br />" # the really long loop. for currentRecord in csvRecords: count = count + 1 print "On line " + str(count) + " <br />" I assumed the browser would receive the headers, and wait since it keeps on receiving little bits of data. But what actually seems to happen is it doesn't receive any data at all, and Error 504 times out when given a CSV with lots of lines. Perhaps there's some caching happening somewhere? From the logs, [Wed Jan 20 16:59:09 2010] [error] [client ::1] Script timed out before returning headers: datacruncher.py, referer: http://localhost/index.htm [Wed Jan 20 17:04:09 2010] [warn] [client ::1] Timeout waiting for output from CGI script /Library/WebServer/CGI-Executables/datacruncher.py, referer: http://localhost/index.htm What's the best way to resolve this, or, is it not appropriate to run such scripts in a browser? Edit: This is a script for my own use - I normally intend to use it on my computer, but I thought a web-based interface could come in handy while travelling, or for example from a phone. Also, there's really nothing to download - the script will most probably e-mail a report off at the end.
[ "I would separate the work like this:\n\nA web app URL that accept the POSTed CSV file. The web app puts the CSV content into an off line queue, for instance a database table. The web app's response should be an unique ID for the queued item (use an auto-incremented ID column, for instance). The client must store this ID for part 3.\nA stand-alone service app that polls the queue for work, and does the processing. Upon completion of the processing, store the results in another database table, using the unique ID as a key.\nA web app URL that can get processed results, http://server/getresults/uniqueid/. If the processing is finished (i.e. the unique ID is found in the results database table), then return the results. If not finished, the response should be a code that indicates this. For instance a custom HTTP header, a HTTP status response, response body 'PENDING' or similar.\n\n", "I've had this situation before and I used cronjobs. The HTTP script would just write in a queue a job to be performed (a DB or a file in a directory) and the cronjob would read it and execute that job.\n", "You'll probably need to do a stdout.flush(), as the script isn't really writing anything yet to the webserver until you've written a page buffer's worth of data - which doesn't happen before the timeout.\nBut the proper way to solve this is, as others suggested, to do the processing in a separate thread/process, and show the user an auto-refreshed page which shows the status, with a progress bar or some other fancy visual to keep them from being bored.\n", "See Randal Schwartz's Watching long processes through CGI. The article uses Perl, but the technique does not depend on the language.\n", "Very similar question here. I suggest spawning off the lengthy process and returning an ajax based progress bar to the user. This way they user has the luxury of the web-interface and you have the luxury of no time-outs.\n", "imho the best way would be to run an independent script which posts updates somewhere (flat file, database, etc...). I don't know how to fork an independent process from python so i can't give any code examples.\nTo show progress on a WebSite implement an ajax request to a page that reads those status updates and for example shows a nice progress bar.\nAdd something like setTimeout(\"refreshProgressBar[...]) or meta-refresh for auto-refresh.\n" ]
[ 12, 5, 4, 2, 2, 1 ]
[]
[]
[ "http_headers", "http_status_code_504", "python", "timeout" ]
stackoverflow_0002101052_http_headers_http_status_code_504_python_timeout.txt
Q: tips on creating RSS/XML easily in python I have a list if these 3 items: title and link and a html based description and I am looking for a library or external tool which can be fed these 3 items and create a rss xml page. Does such a thing exist? A: I suggest you use a template and feed the list of items to the template. Example Jinja2 template (Atom, not RSS, but you get the idea), assuming that the items are 3-tuples (title, link, html): <?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <author>Author's name</author> <title>Feed title</title> {%for item in items %} <entry> <title>{{item[0]}}</title> <link href="{{item[1]}}"/> <content type="html">{{item[2]}}</content> </entry> {%endfor%} </feed> Code to feed content to the template and output the result: import jinja2 env = jinja2.Environment(loader=jinja2.FileSystemLoader(".")) print env.get_template("feedtemplate.xml").render(items=get_list_of_items()) A: How about django's RSS Framework? A: This might not be the answer you search for, but any RSS dialect is a fairly simple standard (holding for 0.9 and 2 especially, and with constraints for 1, too). You could consider writing it by hand, if you don't have any additional constraints (like, you already use Django, or it will get more complex in the nearer future, or it should automatically be distributed, or you want to create RSS 1, RSS 2 and Atom all at once and don't have the time to read 3 specs). Specifications: RSS 0.91 RSS 1.0 RSS 2.0 Atom
tips on creating RSS/XML easily in python
I have a list if these 3 items: title and link and a html based description and I am looking for a library or external tool which can be fed these 3 items and create a rss xml page. Does such a thing exist?
[ "I suggest you use a template and feed the list of items to the template.\nExample Jinja2 template (Atom, not RSS, but you get the idea), assuming that the items are 3-tuples (title, link, html):\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<feed xmlns=\"http://www.w3.org/2005/Atom\">\n <author>Author's name</author>\n <title>Feed title</title>\n {%for item in items %}\n <entry>\n <title>{{item[0]}}</title>\n <link href=\"{{item[1]}}\"/>\n <content type=\"html\">{{item[2]}}</content>\n </entry>\n {%endfor%}\n</feed>\n\nCode to feed content to the template and output the result:\nimport jinja2\nenv = jinja2.Environment(loader=jinja2.FileSystemLoader(\".\"))\nprint env.get_template(\"feedtemplate.xml\").render(items=get_list_of_items())\n\n", "How about django's RSS Framework?\n", "This might not be the answer you search for, but any RSS dialect is a fairly simple standard (holding for 0.9 and 2 especially, and with constraints for 1, too).\nYou could consider writing it by hand, if you don't have any additional constraints (like, you already use Django, or it will get more complex in the nearer future, or it should automatically be distributed, or you want to create RSS 1, RSS 2 and Atom all at once and don't have the time to read 3 specs).\nSpecifications:\n\nRSS 0.91\nRSS 1.0\nRSS 2.0\nAtom\n\n" ]
[ 12, 2, 1 ]
[]
[]
[ "python", "rss", "xml" ]
stackoverflow_0002099666_python_rss_xml.txt
Q: How to call a function and change a variable I am calling a function several times as I am testing several responses. I am asking on how I call a function earlier in the program, changing a variable in this function and then calling it. Below is a snippet of the code. class AbsoluteMove(unittest.TestCase): def Ssh(self): p=pexpect.spawn('ssh user@10.10.10.10') self.command = './ptzpanposition -c 0 -u degx10' p.sendline("cd /bin") i=p.expect('user@user-NA:') p.sendline(self.command) i=p.expect('user@-userNA:') self.Value = p.before class VerifyTilt(AbsoluteMove): def runTest(self): self.dest.PanTilt._y=2.0 try: result = self.client.service.AbsoluteMove(self.token, self.dest, self.speed) except suds.WebFault as detail: print detail self.command = './ptzpanposition -c 0 -u degx10' AbsoluteMove.Ssh(self) # Position of the camera verified through Ssh (No decimal point added to the Ssh value) self.assertEqual(self.Value, '20') I want to change the 'self.command' variable in AbsoluteMove.Ssh() and then run this function. Does anyone know how to do this? Thanks for any help A: is it doable to add another parameter to Absolute Move? A: You'll need to have a wrapper for the runTest function. Notice that I commented the self.command='./ptzpanposition -c 0 -u degx10' in runTest class VerifyTilt(AbsoluteMove): def testWrapper(self): self.command = './ptzpanposition -c 0 -u degx10' runTest() self.command = 'some other command' runTest() def runTest(self): self.dest.PanTilt._y=2 try: result = self.client.service.AbsoluteMove(self.token, self.dest, self.speed) except suds.WebFault as detail: print detail # self.command = './ptzpanposition -c 0 -u degx10' AbsoluteMove.Ssh(self) # Position of the camera verified through Ssh (No decimal point added to the Ssh value) self.assertEqual(self.Value, '200') A: What it looks like is that self.command is just a string, and since AbsoluteMove.Ssh() takes no arguments it must use that string somehow..., so you could just change the value of self.command. A better design would have two commands, and an argument to AbsoluteMove.Ssh() to choose between them. A: Sorry for wasting time, I had declared the variable in the Ssh() function. I removed this and the variables were changed later down the code. The code will work this way thanks.
How to call a function and change a variable
I am calling a function several times as I am testing several responses. I am asking on how I call a function earlier in the program, changing a variable in this function and then calling it. Below is a snippet of the code. class AbsoluteMove(unittest.TestCase): def Ssh(self): p=pexpect.spawn('ssh user@10.10.10.10') self.command = './ptzpanposition -c 0 -u degx10' p.sendline("cd /bin") i=p.expect('user@user-NA:') p.sendline(self.command) i=p.expect('user@-userNA:') self.Value = p.before class VerifyTilt(AbsoluteMove): def runTest(self): self.dest.PanTilt._y=2.0 try: result = self.client.service.AbsoluteMove(self.token, self.dest, self.speed) except suds.WebFault as detail: print detail self.command = './ptzpanposition -c 0 -u degx10' AbsoluteMove.Ssh(self) # Position of the camera verified through Ssh (No decimal point added to the Ssh value) self.assertEqual(self.Value, '20') I want to change the 'self.command' variable in AbsoluteMove.Ssh() and then run this function. Does anyone know how to do this? Thanks for any help
[ "is it doable to add another parameter to Absolute Move?\n", "You'll need to have a wrapper for the runTest function. Notice that I commented the self.command='./ptzpanposition -c 0 -u degx10' in runTest\nclass VerifyTilt(AbsoluteMove):\n def testWrapper(self):\n self.command = './ptzpanposition -c 0 -u degx10'\n runTest()\n self.command = 'some other command'\n runTest() \n\n def runTest(self):\n\n self.dest.PanTilt._y=2\n\n try:\n result = self.client.service.AbsoluteMove(self.token, self.dest, self.speed)\n except suds.WebFault as detail:\n print detail\n\n # self.command = './ptzpanposition -c 0 -u degx10'\n AbsoluteMove.Ssh(self)\n\n # Position of the camera verified through Ssh (No decimal point added to the Ssh value)\n self.assertEqual(self.Value, '200')\n\n", "What it looks like is that self.command is just a string, and since AbsoluteMove.Ssh() takes no arguments it must use that string somehow..., so you could just change the value of self.command. A better design would have two commands, and an argument to AbsoluteMove.Ssh() to choose between them.\n", "Sorry for wasting time,\nI had declared the variable in the Ssh() function. I removed this and the variables were changed later down the code. The code will work this way thanks.\n" ]
[ 1, 0, 0, 0 ]
[]
[]
[ "inheritance", "python", "variables" ]
stackoverflow_0002100847_inheritance_python_variables.txt
Q: Parsing a stdout in Python In Python I need to get the version of an external binary I need to call in my script. Let's say that I want to use Wget in Python and I want to know its version. I will call os.system( "wget --version | grep Wget" ) and then I will parse the outputted string. How to redirect the stdout of the os.command in a string in Python? A: One "old" way is: fin,fout=os.popen4("wget --version | grep Wget") print fout.read() The other modern way is to use a subprocess module: import subprocess cmd = subprocess.Popen('wget --version', shell=True, stdout=subprocess.PIPE) for line in cmd.stdout: if "Wget" in line: print line A: Use the subprocess module: from subprocess import Popen, PIPE p1 = Popen(["wget", "--version"], stdout=PIPE) p2 = Popen(["grep", "Wget"], stdin=p1.stdout, stdout=PIPE) output = p2.communicate()[0]
Parsing a stdout in Python
In Python I need to get the version of an external binary I need to call in my script. Let's say that I want to use Wget in Python and I want to know its version. I will call os.system( "wget --version | grep Wget" ) and then I will parse the outputted string. How to redirect the stdout of the os.command in a string in Python?
[ "One \"old\" way is:\nfin,fout=os.popen4(\"wget --version | grep Wget\")\nprint fout.read()\n\nThe other modern way is to use a subprocess module:\nimport subprocess\ncmd = subprocess.Popen('wget --version', shell=True, stdout=subprocess.PIPE)\nfor line in cmd.stdout:\n if \"Wget\" in line:\n print line\n\n", "Use the subprocess module:\nfrom subprocess import Popen, PIPE\np1 = Popen([\"wget\", \"--version\"], stdout=PIPE)\np2 = Popen([\"grep\", \"Wget\"], stdin=p1.stdout, stdout=PIPE)\noutput = p2.communicate()[0]\n\n" ]
[ 42, 10 ]
[ "Use subprocess instead.\n", "If you are on *nix, I would recommend you to use commands module.\nimport commands\n\nstatus, res = commands.getstatusoutput(\"wget --version | grep Wget\")\n\nprint status # Should be zero in case of of success, otherwise would have an error code\nprint res # Contains stdout\n\n" ]
[ -2, -3 ]
[ "python" ]
stackoverflow_0002101426_python.txt
Q: why 1 is ok,but 2 is error,use django and jquery django view: def json_view(request): import json tag=request.GET.get('tag') if tag=='userName': username=request.GET.get('userName') result='successName' if username: try: user=User.objects.get(username=username) result='existName' except User.DoesNotExist: pass return HttpResponse(json.dumps({'result': result})) if tag=='email': email=request.GET.get('email') result='emailSuccess' if email: try: user=User.objects.get(email=email) result='notOnly' except User.DoesNotExist: pass return HttpResponse(json.dumps({'result': result})) 1.: $.getJSON('/json_view/', { tag: "userName", userName: G }, function (H) { if (H.result == "successName") { F.showOk(h.ok); d = true } else { if (H.result == "existName") { F.showErr(h.userNameExist); d = false } } }) 2.: $.getJSON('/json_view/', { tag: "email", email: F }, function (G) { if (G.result == "emailSuccess") { E.showOk(h.ok); B = true } else { if (G.result == "notOnly") { E.showErr(h.emailExist); B = false } } }) why? thanks the error is: GET http://127.0.0.1:8000/json_view/?tag=email&email=zjm1126%40qq.com 500 INTERNAL SERVER ERROR A: Write a unit test that isolates the problem. Documentation: http://docs.djangoproject.com/en/dev/topics/testing/ The body of the test should be something like: from django.test.client import Client c = Client() response = c.get('/json_view/', {'tag': 'email', 'email': '...'})
why 1 is ok,but 2 is error,use django and jquery
django view: def json_view(request): import json tag=request.GET.get('tag') if tag=='userName': username=request.GET.get('userName') result='successName' if username: try: user=User.objects.get(username=username) result='existName' except User.DoesNotExist: pass return HttpResponse(json.dumps({'result': result})) if tag=='email': email=request.GET.get('email') result='emailSuccess' if email: try: user=User.objects.get(email=email) result='notOnly' except User.DoesNotExist: pass return HttpResponse(json.dumps({'result': result})) 1.: $.getJSON('/json_view/', { tag: "userName", userName: G }, function (H) { if (H.result == "successName") { F.showOk(h.ok); d = true } else { if (H.result == "existName") { F.showErr(h.userNameExist); d = false } } }) 2.: $.getJSON('/json_view/', { tag: "email", email: F }, function (G) { if (G.result == "emailSuccess") { E.showOk(h.ok); B = true } else { if (G.result == "notOnly") { E.showErr(h.emailExist); B = false } } }) why? thanks the error is: GET http://127.0.0.1:8000/json_view/?tag=email&email=zjm1126%40qq.com 500 INTERNAL SERVER ERROR
[ "Write a unit test that isolates the problem. Documentation: http://docs.djangoproject.com/en/dev/topics/testing/\nThe body of the test should be something like:\nfrom django.test.client import Client\nc = Client()\nresponse = c.get('/json_view/', {'tag': 'email', 'email': '...'})\n\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002099345_django_python.txt
Q: What is the name for [x for x in some_list] type of construct in python? Couldn't really find it, but probably it's me not knowing how to search properly :( Just wanted to find out what the name is for: [x for x in some_list] type of construct? A: It's a list comprehension
What is the name for [x for x in some_list] type of construct in python?
Couldn't really find it, but probably it's me not knowing how to search properly :( Just wanted to find out what the name is for: [x for x in some_list] type of construct?
[ "It's a list comprehension\n" ]
[ 14 ]
[]
[]
[ "python" ]
stackoverflow_0002101826_python.txt
Q: How can I serialize Python objects to XML? I need to serialize my Python objects into XML data. I tried to use Django, but it only works for QuerySet objects and not for any simple Python object. How can I serialize a Python object into XML data? A: http://freshmeat.net/projects/gnosisxml/ A: You could also have a look at the objectify module from lxml.
How can I serialize Python objects to XML?
I need to serialize my Python objects into XML data. I tried to use Django, but it only works for QuerySet objects and not for any simple Python object. How can I serialize a Python object into XML data?
[ "http://freshmeat.net/projects/gnosisxml/\n", "You could also have a look at the objectify module from lxml.\n" ]
[ 3, 3 ]
[]
[]
[ "python", "serialization", "xml_serialization" ]
stackoverflow_0002101902_python_serialization_xml_serialization.txt
Q: Is it possible to make user input invisible as a 'sudo' password input? I'm using raw_input() to receive password from user in interactive mode, but I want to make input symbols invisible for security reasons, as it is when you're typing your password using sudo or connecting to a database. How I should do it? A: You need the getpass module. from getpass import getpass password = getpass()
Is it possible to make user input invisible as a 'sudo' password input?
I'm using raw_input() to receive password from user in interactive mode, but I want to make input symbols invisible for security reasons, as it is when you're typing your password using sudo or connecting to a database. How I should do it?
[ "You need the getpass module.\nfrom getpass import getpass\npassword = getpass()\n\n" ]
[ 18 ]
[]
[]
[ "console", "input", "interaction", "python" ]
stackoverflow_0002101975_console_input_interaction_python.txt
Q: What program to write pdf including other pdf on Linux from Python? On an Ubuntu server, I want to create pdfs which include other static pdfs. I have tried using ReportLab with pyPdf. Ideally I would use ReportLab to do the whole thing, but in order to import the pdfs requires their PageCatcher which has a large recurring fee. So I use pyPdf to merge a page created with ReportLab and my other pdfs. The problem is that even though this looks fine in Acrobat and Foxit, part of one of the pages prints garbled on a Xerox 7400 color printer. I can't figure out the issue, but would be willing to buy a more integrated solution if it existed and was reasonably priced. I thought PDF Creator Pilot was it until I saw that it was Windows only. So is there a reasonably priced ($1K or less) solution or a different suggestion? A: I have had a lot of success with the Java library iText. They have a great library of samples for pretty much anything you could think of doing with PDF files. This example is for concatenating PDF files and sounds like it would do what you need: http://itextpdf.com/examples/index.php?page=example&id=123. There is also PDFBox which is another great Java based PDF manipulation library. I realize that you are looking for a Python based solution but there may not be many other options. If you are using the Jython interpreter instead of CPython, integrating in iText should be trivial. If not, then you could consider calling out to it as a separate process. I realize that may not be idea for your situation but I figured I would mention it as an option. A: Another non-Python answer. If you are just merging pages, then pdftk does that well (along with a lot of other things).
What program to write pdf including other pdf on Linux from Python?
On an Ubuntu server, I want to create pdfs which include other static pdfs. I have tried using ReportLab with pyPdf. Ideally I would use ReportLab to do the whole thing, but in order to import the pdfs requires their PageCatcher which has a large recurring fee. So I use pyPdf to merge a page created with ReportLab and my other pdfs. The problem is that even though this looks fine in Acrobat and Foxit, part of one of the pages prints garbled on a Xerox 7400 color printer. I can't figure out the issue, but would be willing to buy a more integrated solution if it existed and was reasonably priced. I thought PDF Creator Pilot was it until I saw that it was Windows only. So is there a reasonably priced ($1K or less) solution or a different suggestion?
[ "I have had a lot of success with the Java library iText. They have a great library of samples for pretty much anything you could think of doing with PDF files. This example is for concatenating PDF files and sounds like it would do what you need: http://itextpdf.com/examples/index.php?page=example&id=123. There is also PDFBox which is another great Java based PDF manipulation library.\nI realize that you are looking for a Python based solution but there may not be many other options. If you are using the Jython interpreter instead of CPython, integrating in iText should be trivial. If not, then you could consider calling out to it as a separate process. I realize that may not be idea for your situation but I figured I would mention it as an option.\n", "Another non-Python answer. If you are just merging pages, then pdftk does that well (along with a lot of other things).\n" ]
[ 1, 0 ]
[]
[]
[ "pdf", "pdf_generation", "pypdf", "python", "reportlab" ]
stackoverflow_0002071727_pdf_pdf_generation_pypdf_python_reportlab.txt
Q: Subtract dict A from dict B (deep del)? If I have a deeply nested dict is there a built-in way to subtract/remove list of "paths" (eg: keyA.keyB.key1, keyA.keyC.key2, etc) or a the keys of a second dict from the original dict? Or maybe there is a common module which has functionality like this? A: Here's a suggestion: D = { "keyA": { "keyB" : { "keyC" : 42, "keyD": 13 }, "keyE" : 55 } } def remove_path(dictionary, path): for node in path[:-1]: dictionary = dictionary[node] del dictionary[path[-1]] remove_path(D, ["keyA", "keyB", "keyD"]) print D # prints {'keyA': {'keyB': {'keyC': 42}, 'keyE': 55}} You'll probably want to introduce some error checking, too. A: Just in case the other answers aren't what you're looking for, here's one that subtracts one dictionary from another. def subtract(a, b): """ Remove the keys in b from a. """ for k in b: if k in a: if isinstance(b[k], dict): subtract(a[k], b[k]) else: del a[k] A: Another solution: d = { 'A' : { 'C' : { 'D' : { 'E' : 4, }, 'F' : 5, }, }, 'B' : 2, } def DeepDictDel(path, dict): for key in path.split('.'): owner = dict dict = dict[key] del owner[key] print d # prints {'A': {'C': {'D': {'E': 4}, 'F': 5}}, 'B': 2} DeepDictDel('A.C.D', d) print d # prints {'A': {'C': {'F': 5}}, 'B': 2}
Subtract dict A from dict B (deep del)?
If I have a deeply nested dict is there a built-in way to subtract/remove list of "paths" (eg: keyA.keyB.key1, keyA.keyC.key2, etc) or a the keys of a second dict from the original dict? Or maybe there is a common module which has functionality like this?
[ "Here's a suggestion:\nD = { \"keyA\": { \n \"keyB\" : {\n \"keyC\" : 42,\n \"keyD\": 13\n },\n \"keyE\" : 55\n }\n }\n\ndef remove_path(dictionary, path):\n for node in path[:-1]:\n dictionary = dictionary[node]\n del dictionary[path[-1]]\n\nremove_path(D, [\"keyA\", \"keyB\", \"keyD\"])\n\nprint D # prints {'keyA': {'keyB': {'keyC': 42}, 'keyE': 55}}\n\nYou'll probably want to introduce some error checking, too.\n", "Just in case the other answers aren't what you're looking for, here's one that subtracts one dictionary from another.\ndef subtract(a, b):\n \"\"\" Remove the keys in b from a. \"\"\"\n for k in b:\n if k in a:\n if isinstance(b[k], dict):\n subtract(a[k], b[k])\n else:\n del a[k]\n\n", "Another solution:\nd = {\n 'A' : {\n 'C' : {\n 'D' : {\n 'E' : 4,\n },\n 'F' : 5,\n },\n },\n 'B' : 2,\n}\n\ndef DeepDictDel(path, dict):\n for key in path.split('.'):\n owner = dict\n dict = dict[key]\n\n del owner[key]\n\n\nprint d # prints {'A': {'C': {'D': {'E': 4}, 'F': 5}}, 'B': 2}\nDeepDictDel('A.C.D', d)\nprint d # prints {'A': {'C': {'F': 5}}, 'B': 2}\n\n" ]
[ 2, 2, 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0002100697_dictionary_python.txt
Q: Json communication between flash and javascript note: using django/python/javascript/flash So its been two days since I'm stuck at the error. I did the things you told me to and found a couple of ways around it but nothing worked. These are the results. Javascript does not receive the normal string it has to be a json object so. in views.py somestring = json.dumps("HELLO WORLD") which renders this in HTML &quot;HELLO WORLD&quot; and in javascript it is rendered like this a240527176321_quote_hello Now, since it is a json object I need to convert it back in flash. But when it gets in flash where I receive it like this function something(hellovar){ ..... ...... } it does not even come inside the function. Any thoughts? A: why do you communicate between flash and js via json? actionscript has a very powerfull build in ExternalInterface to communicate with javascript.
Json communication between flash and javascript
note: using django/python/javascript/flash So its been two days since I'm stuck at the error. I did the things you told me to and found a couple of ways around it but nothing worked. These are the results. Javascript does not receive the normal string it has to be a json object so. in views.py somestring = json.dumps("HELLO WORLD") which renders this in HTML &quot;HELLO WORLD&quot; and in javascript it is rendered like this a240527176321_quote_hello Now, since it is a json object I need to convert it back in flash. But when it gets in flash where I receive it like this function something(hellovar){ ..... ...... } it does not even come inside the function. Any thoughts?
[ "why do you communicate between flash and js via json? actionscript has a very powerfull build in ExternalInterface to communicate with javascript.\n" ]
[ 1 ]
[]
[]
[ "flash", "json", "python" ]
stackoverflow_0002102294_flash_json_python.txt
Q: Django primary key When querying in django say People.objects.all(pk=code), what does pk=code mean? A: Calling People.objects.all(pk=code) (calling all) will result in the pk=code being ignored and a QuerySet for all People returned. Calling People.objects.get(pk=code) (calling get) will result in the People object with pk=code returned, or an error if not found. A: It's a query to get the People object that has a primary key of whatever the value of "code" is. By default, all Django model instances have a primary key that uniquely identifies the object. Generally it's an auto-incrementing integer, but you could define it to be whatever you want, so long as it's certain to be unique. http://docs.djangoproject.com/en/dev/topics/db/models/#id1 Edit: Now that I look at the code snippet a little closer, rather than just assuming what it said, it doesn't make much sense. The all() method should be a get(). It doesn't make any sense to give a pk to all() since it just returns all the objects of that type. http://docs.djangoproject.com/en/dev/ref/models/querysets/#all http://docs.djangoproject.com/en/dev/ref/models/querysets/#id5
Django primary key
When querying in django say People.objects.all(pk=code), what does pk=code mean?
[ "Calling People.objects.all(pk=code) (calling all) will result in the pk=code being ignored and a QuerySet for all People returned.\nCalling People.objects.get(pk=code) (calling get) will result in the People object with pk=code returned, or an error if not found.\n", "It's a query to get the People object that has a primary key of whatever the value of \"code\" is.\nBy default, all Django model instances have a primary key that uniquely identifies the object. Generally it's an auto-incrementing integer, but you could define it to be whatever you want, so long as it's certain to be unique.\nhttp://docs.djangoproject.com/en/dev/topics/db/models/#id1\nEdit: Now that I look at the code snippet a little closer, rather than just assuming what it said, it doesn't make much sense. The all() method should be a get(). It doesn't make any sense to give a pk to all() since it just returns all the objects of that type.\nhttp://docs.djangoproject.com/en/dev/ref/models/querysets/#all\nhttp://docs.djangoproject.com/en/dev/ref/models/querysets/#id5\n" ]
[ 7, 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002101838_django_python.txt
Q: Python Send Keystrokes to Non-Active Application I'm automating some common GUI tasks I have to do in an application, and I'm using a Python program and SendKeys to do it. So far I've had to activate the application I'm sending keys to (since SendKeys just sends the keystrokes to the active window), but I'd like to be able to send keystrokes to an application in the background. Is there a way to do that, or am I dreaming an impossible dream? Thanks for your help. A: SendKeys is a Python module for Windows that can send one or more keystrokes or keystroke combinations to the active window. If you need to do some automated work in the background, make another user/session and do it in that. However if you must do something of this like on windows, I always reach for autoit. It's M$ only and perfectly suited to automating tasks on that OS. A: pywinauto is another MS-only GUI automation tool, this one written in Python. A: This is a frequent question in the autohotkey.com forums. Search under "sending commands to controls". Basically, if you have the control ID, then it doesn't need to be visible in order to operate on it. There're more details on the forums. good luck!
Python Send Keystrokes to Non-Active Application
I'm automating some common GUI tasks I have to do in an application, and I'm using a Python program and SendKeys to do it. So far I've had to activate the application I'm sending keys to (since SendKeys just sends the keystrokes to the active window), but I'd like to be able to send keystrokes to an application in the background. Is there a way to do that, or am I dreaming an impossible dream? Thanks for your help.
[ "SendKeys is a Python module for Windows that can send one or more keystrokes or keystroke combinations to the active window.\n\nIf you need to do some automated work in the background, make another user/session and do it in that.\nHowever if you must do something of this like on windows, I always reach for autoit.\nIt's M$ only and perfectly suited to automating tasks on that OS.\n", "pywinauto is another MS-only GUI automation tool, this one written in Python.\n", "This is a frequent question in the autohotkey.com forums. Search under \n\"sending commands to controls\". Basically, if you have the control ID, then it doesn't need to be visible in order to operate on it. There're more details on the forums.\ngood luck!\n" ]
[ 3, 3, 2 ]
[]
[]
[ "python", "sendkeys" ]
stackoverflow_0002098480_python_sendkeys.txt
Q: Why python multiprocessing module cause CPU completely run out? Possible Duplicate: Multiprocessing launching too many instances of Python VM I am trying python 2.6 multiprocessing module with this simple code snippet. from multiprocessing import Pool p = Pool(5) def f(x): return x*x print p.map(f, [1,2,3]) But this code cause my OS stopped responding. It looks like the CPU is too busy. What's wrong with my code? BTW : it seems that multiprocessing module is a bit dangerous. I had to restart my computer. A: You aren't protecting the entry point at all, so each subprocess is trying to start the same map call and so on (into infinity!). Try the following: if __name__ == "__main__": print p.map(f, [1,2,3]) See this section of the module's documentation.
Why python multiprocessing module cause CPU completely run out?
Possible Duplicate: Multiprocessing launching too many instances of Python VM I am trying python 2.6 multiprocessing module with this simple code snippet. from multiprocessing import Pool p = Pool(5) def f(x): return x*x print p.map(f, [1,2,3]) But this code cause my OS stopped responding. It looks like the CPU is too busy. What's wrong with my code? BTW : it seems that multiprocessing module is a bit dangerous. I had to restart my computer.
[ "You aren't protecting the entry point at all, so each subprocess is trying to start the same map call and so on (into infinity!). Try the following:\nif __name__ == \"__main__\":\n print p.map(f, [1,2,3])\n\nSee this section of the module's documentation.\n" ]
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0002102354_python.txt
Q: wxPython - lines drawn with Device Context disappear when focus changes I've written this small app that draws lines between two points selected by the user and it works but how do I keep the lines I draw from disappearing whenever the window is minimized or gets covered by another open window? class SimpleDraw(wx.Frame): def __init__(self, parent, id, title, size=(640, 480)): self.points = [] wx.Frame.__init__(self, parent, id, title, size) self.Bind(wx.EVT_LEFT_DOWN, self.DrawDot) self.SetBackgroundColour("WHITE") self.Centre() self.Show(True) def DrawDot(self, event): self.points.append(event.GetPosition()) if len(self.points) == 2: dc = wx.ClientDC(self) dc.SetPen(wx.Pen("#000000", 10, wx.SOLID)) x1, y1 = self.points[0] x2, y2 = self.points[1] dc.DrawLine(x1, y1, x2, y2) # reset the list to empty self.points = [] if __name__ == "__main__": app = wx.App() SimpleDraw(None, -1, "Title Here!") app.MainLoop() A: Your issue is that you are only drawing when the user clicks. The resize/erase (when another window covers yours) problems are because your window doesn't maintain a "buffer" which it can redraw. Here, I've modified your sample, it seems to be working okay. import wx class SimpleDraw(wx.Frame): def __init__(self, parent, id, title, size=(640, 480)): self.points = [] wx.Frame.__init__(self, parent, id, title, size) self.Bind(wx.EVT_LEFT_DOWN, self.DrawDot) self.Bind(wx.EVT_PAINT, self.Paint) self.SetBackgroundColour("WHITE") self.Centre() self.Show(True) self.buffer = wx.EmptyBitmap(640, 480) # draw to this dc = wx.BufferedDC(wx.ClientDC(self), self.buffer) dc.Clear() # black window otherwise def DrawDot(self, event): self.points.append(event.GetPosition()) if len(self.points) == 2: dc = wx.BufferedDC(wx.ClientDC(self), self.buffer) dc.Clear() dc.SetPen(wx.Pen("#000000", 10, wx.SOLID)) x1, y1 = self.points[0] x2, y2 = self.points[1] dc.DrawLine(x1, y1, x2, y2) # reset the list to empty self.points = [] def Paint(self, event): wx.BufferedPaintDC(self, self.buffer) if __name__ == "__main__": app = wx.App(0) SimpleDraw(None, -1, "Title Here!") app.MainLoop() A: You have to structure your program differently in a GUI environment. Typically, you maintain a data structure called your model. In your case, you already have a start of one, self.points. Then you only draw on the window in response to a paint event. The windowing system will send you paint events when the window needs painting, including when it is first displayed, when it is maximized, and when it is revealed from beneath another window. In your program, you'd bind the LeftDown event to a function that modifies self.points and invalidates the window, which would usually cause the windowing system to send you paint events. You'd bind the Paint event to a function that draws on the window.
wxPython - lines drawn with Device Context disappear when focus changes
I've written this small app that draws lines between two points selected by the user and it works but how do I keep the lines I draw from disappearing whenever the window is minimized or gets covered by another open window? class SimpleDraw(wx.Frame): def __init__(self, parent, id, title, size=(640, 480)): self.points = [] wx.Frame.__init__(self, parent, id, title, size) self.Bind(wx.EVT_LEFT_DOWN, self.DrawDot) self.SetBackgroundColour("WHITE") self.Centre() self.Show(True) def DrawDot(self, event): self.points.append(event.GetPosition()) if len(self.points) == 2: dc = wx.ClientDC(self) dc.SetPen(wx.Pen("#000000", 10, wx.SOLID)) x1, y1 = self.points[0] x2, y2 = self.points[1] dc.DrawLine(x1, y1, x2, y2) # reset the list to empty self.points = [] if __name__ == "__main__": app = wx.App() SimpleDraw(None, -1, "Title Here!") app.MainLoop()
[ "Your issue is that you are only drawing when the user clicks. The resize/erase (when another window covers yours) problems are because your window doesn't maintain a \"buffer\" which it can redraw.\nHere, I've modified your sample, it seems to be working okay.\nimport wx\n\nclass SimpleDraw(wx.Frame):\n def __init__(self, parent, id, title, size=(640, 480)):\n self.points = []\n wx.Frame.__init__(self, parent, id, title, size)\n\n self.Bind(wx.EVT_LEFT_DOWN, self.DrawDot)\n self.Bind(wx.EVT_PAINT, self.Paint)\n\n self.SetBackgroundColour(\"WHITE\")\n self.Centre()\n self.Show(True)\n self.buffer = wx.EmptyBitmap(640, 480) # draw to this\n dc = wx.BufferedDC(wx.ClientDC(self), self.buffer)\n dc.Clear() # black window otherwise\n\n\n def DrawDot(self, event):\n self.points.append(event.GetPosition())\n if len(self.points) == 2:\n dc = wx.BufferedDC(wx.ClientDC(self), self.buffer)\n dc.Clear()\n dc.SetPen(wx.Pen(\"#000000\", 10, wx.SOLID))\n x1, y1 = self.points[0]\n x2, y2 = self.points[1]\n dc.DrawLine(x1, y1, x2, y2)\n # reset the list to empty\n self.points = []\n\n\n def Paint(self, event):\n wx.BufferedPaintDC(self, self.buffer)\n\n\nif __name__ == \"__main__\":\n app = wx.App(0)\n SimpleDraw(None, -1, \"Title Here!\")\n app.MainLoop()\n\n", "You have to structure your program differently in a GUI environment. Typically, you maintain a data structure called your model. In your case, you already have a start of one, self.points. Then you only draw on the window in response to a paint event. The windowing system will send you paint events when the window needs painting, including when it is first displayed, when it is maximized, and when it is revealed from beneath another window.\nIn your program, you'd bind the LeftDown event to a function that modifies self.points and invalidates the window, which would usually cause the windowing system to send you paint events. You'd bind the Paint event to a function that draws on the window.\n" ]
[ 1, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002098482_python_wxpython.txt
Q: How can multiple calculations be launched in parallel, while stopping them all when the first one returns? [Python] How can multiple calculations be launched in parallel, while stopping them all when the first one returns? The application I have in mind is the following: there are multiple ways of calculating a certain value; each method takes a different amount of time depending on the function parameters; by launching calculations in parallel, the fastest calculation would automatically be "selected" each time, and the other calculations would be stopped. Now, there are some "details" that make this question more difficult: The parameters of the function to be calculated include functions (that are calculated from data points; they are not top-level module functions). In fact, the calculation is the convolution of two functions. I'm not sure how such function parameters could be passed to a subprocess (they are not pickeable). I do not have access to all calculation codes: some calculations are done internally by Scipy (probably via Fortran or C code). I'm not sure whether threads offer something similar to the termination signals that can be sent to processes. Is this something that Python can do relatively easily? A: I would look at the multiprocessing module if you haven't already. It offers a way of offloading tasks to separate processes whilst providing you with a simple, threading like interface. It provides the same kinds of primatives as you get in the threading module, for example, worker pools and queues for passing messages between your tasks, but it allows you to sidestep the issue of the GIL since your tasks actually run in separate processes. The actual semantics of what you want are quite specific so I don't think there is a routine that fits the bill out-of-the-box, but you can surely knock one up. Note: if you want to pass functions around, they cannot be bound functions since these are not pickleable, which is a requirement for sharing data between your tasks. A: Because of the global interpreter lock you would be hard pressed to get any speedup this way. In reality even multithreaded programs in Python only run on one core. Thus, you would just be doing N processes at 1/N times the speed. Even if one finished in half the time of the others you would still lose time in the big picture. A: Processes can be started and killed trivially. You can do this. import subprocess watch = [] for s in ( "process1.py", "process2.py", "process3.py" ): sp = subprocess.Popen( s ) watch.append( sp ) Now you're simply waiting for one of those to finish. When one finishes, kill the others. import time winner= None while winner is None: time.sleep(10) for w in watch: if w.poll() is not None: winner= w break for w in watch: if w.poll() is None: w.kill() These are processes -- not threads. No GIL considerations. Make the operating system schedule them; that's what it does best. Further, each process is simply a script that simply solves the problem using one of your alternative algorithms. They're completely independent and stand-alone. Simple to design, build and test.
How can multiple calculations be launched in parallel, while stopping them all when the first one returns? [Python]
How can multiple calculations be launched in parallel, while stopping them all when the first one returns? The application I have in mind is the following: there are multiple ways of calculating a certain value; each method takes a different amount of time depending on the function parameters; by launching calculations in parallel, the fastest calculation would automatically be "selected" each time, and the other calculations would be stopped. Now, there are some "details" that make this question more difficult: The parameters of the function to be calculated include functions (that are calculated from data points; they are not top-level module functions). In fact, the calculation is the convolution of two functions. I'm not sure how such function parameters could be passed to a subprocess (they are not pickeable). I do not have access to all calculation codes: some calculations are done internally by Scipy (probably via Fortran or C code). I'm not sure whether threads offer something similar to the termination signals that can be sent to processes. Is this something that Python can do relatively easily?
[ "I would look at the multiprocessing module if you haven't already. It offers a way of offloading tasks to separate processes whilst providing you with a simple, threading like interface.\nIt provides the same kinds of primatives as you get in the threading module, for example, worker pools and queues for passing messages between your tasks, but it allows you to sidestep the issue of the GIL since your tasks actually run in separate processes. \nThe actual semantics of what you want are quite specific so I don't think there is a routine that fits the bill out-of-the-box, but you can surely knock one up.\nNote: if you want to pass functions around, they cannot be bound functions since these are not pickleable, which is a requirement for sharing data between your tasks.\n", "Because of the global interpreter lock you would be hard pressed to get any speedup this way. In reality even multithreaded programs in Python only run on one core. Thus, you would just be doing N processes at 1/N times the speed. Even if one finished in half the time of the others you would still lose time in the big picture.\n", "Processes can be started and killed trivially. \nYou can do this.\nimport subprocess\nwatch = []\nfor s in ( \"process1.py\", \"process2.py\", \"process3.py\" ):\n sp = subprocess.Popen( s )\n watch.append( sp )\n\nNow you're simply waiting for one of those to finish. When one finishes, kill the others.\nimport time\nwinner= None\nwhile winner is None:\n time.sleep(10)\n for w in watch:\n if w.poll() is not None:\n winner= w\n break\nfor w in watch:\n if w.poll() is None: w.kill()\n\nThese are processes -- not threads. No GIL considerations. Make the operating system schedule them; that's what it does best.\nFurther, each process is simply a script that simply solves the problem using one of your alternative algorithms. They're completely independent and stand-alone. Simple to design, build and test.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "multiple_processes", "parallel_processing", "python" ]
stackoverflow_0002102216_multiple_processes_parallel_processing_python.txt
Q: why this dos command does not work inside python? I try to move some dos command from my batch file into python but get this error, The filename, directory name, or volume label syntax is incorrect, for the following statement. subprocess.Popen('rd /s /q .\ProcessControlSimulator\bin', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) if I just copy that dos command into window console, it works. The os.getcwd() gave me expected working directory. My questions are: 1. why is that? 2. how to avoid that? do I need to get current working directory and construct an abstract path for that command? how to do that? thanks A: \ (backslash) is an escape character within string constants, so your string ends up changed. Use double \s (like so \\) within string constants: subprocess.Popen('rd /s /q .\\ProcessControlSimulator\\bin', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) A: My advice is try not to use system commands unnecessarily. You are using Python, so use the available modules that come with it. From what i see, you are trying to remove directories right? Then you can use modules like shutil. Example: import shutil import os path = os.path.join("c:\\","ProcessControlSimulator","bin") #example only try: shutil.rmtree(path) except Exception,e: print e else: print "removed" there are others also, like os.removedirs, os.remove you can take a look at from the docs. A: You've got unescaped backslashes. You can use a python raw string to avoid having to escape your slashes, or double them up: subprocess.Popen(r'rd /s /q .\ProcessControlSimulator\bin', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) or subprocess.Popen('rd /s /q .\\ProcessControlSimulator\\bin', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) A: You can't just copy it one-to-one. For example, your escape characters () become incorrect. You may need a double \ in this case. Also, there are specific API calls for creating and killing directories, look at os.path
why this dos command does not work inside python?
I try to move some dos command from my batch file into python but get this error, The filename, directory name, or volume label syntax is incorrect, for the following statement. subprocess.Popen('rd /s /q .\ProcessControlSimulator\bin', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) if I just copy that dos command into window console, it works. The os.getcwd() gave me expected working directory. My questions are: 1. why is that? 2. how to avoid that? do I need to get current working directory and construct an abstract path for that command? how to do that? thanks
[ "\\ (backslash) is an escape character within string constants, so your string ends up changed. Use double \\s (like so \\\\) within string constants:\n\nsubprocess.Popen('rd /s /q .\\\\ProcessControlSimulator\\\\bin', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n\n", "My advice is try not to use system commands unnecessarily. You are using Python, so use the available modules that come with it. From what i see, you are trying to remove directories right? Then you can use modules like shutil. Example:\nimport shutil\nimport os\npath = os.path.join(\"c:\\\\\",\"ProcessControlSimulator\",\"bin\") #example only\ntry:\n shutil.rmtree(path)\nexcept Exception,e:\n print e\nelse:\n print \"removed\"\n\nthere are others also, like os.removedirs, os.remove you can take a look at from the docs.\n", "You've got unescaped backslashes. You can use a python raw string to avoid having to escape your slashes, or double them up:\nsubprocess.Popen(r'rd /s /q .\\ProcessControlSimulator\\bin', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n\nor\nsubprocess.Popen('rd /s /q .\\\\ProcessControlSimulator\\\\bin', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n\n", "You can't just copy it one-to-one. For example, your escape characters () become incorrect. You may need a double \\ in this case.\nAlso, there are specific API calls for creating and killing directories, look at os.path\n" ]
[ 12, 9, 7, 2 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0002102452_python_subprocess.txt
Q: problem in installing django problem with installing django i am geting folllowing error E:\Softwares\Django-1.1.1.tar\Django-1.1.1\Django-1.1.1>setup.py install Traceback (most recent call last): File "E:\Softwares\Django-1.1.1.tar\Django-1.1.1\Django-1.1.1\setup.py", line 48, in ? root_dir = os.path.dirname(__file__) NameError: name '__file__' is not defined A: The Python version you are using, 2.2, is more than seven years old. Django is only compatible with versions 2.4 upwards. A: You should usepython setup.py install
problem in installing django
problem with installing django i am geting folllowing error E:\Softwares\Django-1.1.1.tar\Django-1.1.1\Django-1.1.1>setup.py install Traceback (most recent call last): File "E:\Softwares\Django-1.1.1.tar\Django-1.1.1\Django-1.1.1\setup.py", line 48, in ? root_dir = os.path.dirname(__file__) NameError: name '__file__' is not defined
[ "The Python version you are using, 2.2, is more than seven years old. Django is only compatible with versions 2.4 upwards.\n", "You should usepython setup.py install\n" ]
[ 4, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002101132_django_python.txt
Q: Prepare a string for Google Ajax Search? I have strings such as ["Tabula Rasa", "façade", "DJ Tiësto"] I'm accessing Google Ajax API in Python using the base url: base = 'http://ajax.googleapis.com/ajax/services/search/web' '?v=1.0&q=%s' I'm having issues using these strings plain and noticed I have to transform certain characters, eg. "Tabula Rasa" --> "Tabula%20Rasa" But I have a huge list of these strings and I do not know of a way I can automatically prepare these string for the URL query. Any help would be very much appreciated. A: What you're looking for is urllib.quote(): >>> urllib.quote("Tabula Rasa") 'Tabula%20Rasa' The non-ASCII strings may need to be recoded into the encoding expected by the Google AJAX API, if you don't have them in the same encoding already.
Prepare a string for Google Ajax Search?
I have strings such as ["Tabula Rasa", "façade", "DJ Tiësto"] I'm accessing Google Ajax API in Python using the base url: base = 'http://ajax.googleapis.com/ajax/services/search/web' '?v=1.0&q=%s' I'm having issues using these strings plain and noticed I have to transform certain characters, eg. "Tabula Rasa" --> "Tabula%20Rasa" But I have a huge list of these strings and I do not know of a way I can automatically prepare these string for the URL query. Any help would be very much appreciated.
[ "What you're looking for is urllib.quote():\n>>> urllib.quote(\"Tabula Rasa\")\n'Tabula%20Rasa'\n\nThe non-ASCII strings may need to be recoded into the encoding expected by the Google AJAX API, if you don't have them in the same encoding already.\n" ]
[ 2 ]
[]
[]
[ "google_ajax_api", "google_api", "python", "url" ]
stackoverflow_0002103317_google_ajax_api_google_api_python_url.txt
Q: determine the type of a value which is represented as string in python When I read a comma seperated file or string with the csv parser in python all items are represented as a string. see example below. import csv a = "1,2,3,4,5" r = csv.reader([a]) for row in r: d = row d ['1', '2', '3', '4', '5'] type(d[0]) <type 'str'> I want to determine for each value if it is a string, float, integer or date. How can I do this in python? A: You could do something like this: from datetime import datetime tests = [ # (Type, Test) (int, int), (float, float), (datetime, lambda value: datetime.strptime(value, "%Y/%m/%d")) ] def getType(value): for typ, test in tests: try: test(value) return typ except ValueError: continue # No match return str >>> getType('2010/1/12') <type 'datetime.datetime'> >>> getType('2010.2') <type 'float'> >>> getType('2010') <type 'int'> >>> getType('2013test') <type 'str'> The key is in the tests order, for example the int test should be before the float test. And for dates you can add more tests for formats you want to support, but obviously you can't cover all possible cases. A: This cannot be done in a reliable manner and that is not due to limitations in Python or any other programming language for that matter. A human being could not do this in a predictable manner without guessing and following a few rules (usually called Heuristics when used in this context). So lets first design a few heuristics then encode them in Python. Things to consider are: All the values are valid strings we know that because that is the basis of our problem so there is no point in checking for this at all. We should check everything else we can whatever falls through we can just leave as a string. Dates are the most obvious thing to check first if they are formatted in predictable manner such as [YYYY]-[MM]-[DD]. (ISO ISO 8601 date format) they are easy to distinguish from other bits of text that contain numbers. If the dates are in a format with just numbers like YYYYMMDD then we are stuck as these dates will be indistinguishable from ordinary numbers. We will do integers next because all integers are valid floats but not all floats are valid integers. We could just check if the text contains on digits (or digits and the letters A-F if hexadecimal numbers are possible) in this case treat the value as an integer. Floats would be next as they are numbers with some formatting (the decimal point). It is easy to recognise 3.14159265 as a floating point number. However 5.0 which can be written simply as 5 is also a valid float but would have been caught in the previous steps and not be recognised as a float even if it was intended to be. Any values that are left unconverted can be treated as strings. Due to the possible overlaps I have mentioned above such a scheme can never be 100% reliable. Also any new data type that you need to support (complex number perhaps) would need its own set of heuristics and would have to placed in the most appropriate place in the chain of checks. The more likely a check is to match only the data type desired the higher up the chain it should be. Now lets make this real in Python, most of the heuristics I mentioned above are taken care of for us by Python we just need to decide on the order in which to apply them: from datetime import datetime heuristics = (lambda value: datetime.strptime(value, "%Y-%m-%d"), int, float) def convert(value): for type in heuristics: try: return type(value) except ValueError: continue # All other heuristics failed it is a string return value values = ['3.14159265', '2010-01-20', '16', 'some words'] for value in values: converted_value = convert(value) print converted_value, type(converted_value) This outputs the following: 3.14159265 <type 'float'> 2010-01-20 00:00:00 <type 'datetime.datetime'> 16 <type 'int'> some words <type 'str'> A: There's no real answer to this as far as I can tell since these are just strings. They're not integers or floats or whatever. Those are roles you decide. eg. Is 1 an integer or a float? A couple of things come to mind though. One is to do some kind of pattern matching (eg. If it contains a decimal point, it's a float etc.). For parsing/guessing dates, you can try this or this. You could also try 'casting' the element into whatever you want and catch exceptions to try the others. You can do something like try int, if it fails, try float and if that fails, try date etc. A: What you want to acheive is difficult because the types are ambiguous: "1" could either be a string, or an int for example. At any rate, you could try something like this: Dates: presumably they are in a known format: if so, you can try instantiating a datetime from the timestamp string (datetime.strptime()) and if it fails you know its not a datetime. Floats: ensure all characters are either a digit and there is at least one "." in the string. Then convert to float (float(value)) Integers: regex the string and match digits. Ensure the string is the same lenght as the source string then convert (int(value)) If none of the above worked, it's a string. A: Well..you can't. How would you decide if "5" is meant as a string or an integer? How would you decide if "20100120" is meant as an integer or a date? You can of course make educated guesses, and implement some kind of parse order. First try it as a date, then as a float, then as an int, and lastly as a string. A: From the manual: Return a reader object which will iterate over lines in the given csvfile. csvfile can be any object which supports the iterator protocol and returns a string each time its next() method is called — file objects and list objects are both suitable. The interface requires that a string be returned each time next() is called. A: The date is a bit harder. It depends on the format and how regular it is. Here is a clue to get you started on the rest. >>> int('a') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'a' >>> int('1') 1 >>> float('1') 1.0 >>> float('1.0') 1.0 But notice: >>> int(1.0) 1
determine the type of a value which is represented as string in python
When I read a comma seperated file or string with the csv parser in python all items are represented as a string. see example below. import csv a = "1,2,3,4,5" r = csv.reader([a]) for row in r: d = row d ['1', '2', '3', '4', '5'] type(d[0]) <type 'str'> I want to determine for each value if it is a string, float, integer or date. How can I do this in python?
[ "You could do something like this:\nfrom datetime import datetime\n\ntests = [\n # (Type, Test)\n (int, int),\n (float, float),\n (datetime, lambda value: datetime.strptime(value, \"%Y/%m/%d\"))\n]\n\ndef getType(value):\n for typ, test in tests:\n try:\n test(value)\n return typ\n except ValueError:\n continue\n # No match\n return str\n\n>>> getType('2010/1/12')\n<type 'datetime.datetime'>\n>>> getType('2010.2')\n<type 'float'>\n>>> getType('2010')\n<type 'int'>\n>>> getType('2013test')\n<type 'str'>\n\nThe key is in the tests order, for example the int test should be before the float test. And for dates you can add more tests for formats you want to support, but obviously you can't cover all possible cases.\n", "This cannot be done in a reliable manner and that is not due to limitations in Python or any other programming language for that matter. A human being could not do this in a predictable manner without guessing and following a few rules (usually called Heuristics when used in this context). \nSo lets first design a few heuristics then encode them in Python. Things to consider are:\n\nAll the values are valid strings we know that because that is the basis of our problem so there is no point in checking for this at all. We should check everything else we can whatever falls through we can just leave as a string.\nDates are the most obvious thing to check first if they are formatted in predictable manner such as [YYYY]-[MM]-[DD]. (ISO ISO 8601 date format) they are easy to distinguish from other bits of text that contain numbers. If the dates are in a format with just numbers like YYYYMMDD then we are stuck as these dates will be indistinguishable from ordinary numbers.\nWe will do integers next because all integers are valid floats but not all floats are valid integers. We could just check if the text contains on digits (or digits and the letters A-F if hexadecimal numbers are possible) in this case treat the value as an integer.\nFloats would be next as they are numbers with some formatting (the decimal point). It is easy to recognise 3.14159265 as a floating point number. However 5.0 which can be written simply as 5 is also a valid float but would have been caught in the previous steps and not be recognised as a float even if it was intended to be.\nAny values that are left unconverted can be treated as strings.\n\nDue to the possible overlaps I have mentioned above such a scheme can never be 100% reliable. Also any new data type that you need to support (complex number perhaps) would need its own set of heuristics and would have to placed in the most appropriate place in the chain of checks. The more likely a check is to match only the data type desired the higher up the chain it should be.\nNow lets make this real in Python, most of the heuristics I mentioned above are taken care of for us by Python we just need to decide on the order in which to apply them:\nfrom datetime import datetime\n\nheuristics = (lambda value: datetime.strptime(value, \"%Y-%m-%d\"),\n int, float)\n\ndef convert(value):\n for type in heuristics:\n try:\n return type(value)\n except ValueError:\n continue\n # All other heuristics failed it is a string\n return value\n\nvalues = ['3.14159265', '2010-01-20', '16', 'some words']\n\nfor value in values:\n converted_value = convert(value)\n print converted_value, type(converted_value)\n\nThis outputs the following:\n3.14159265 <type 'float'>\n2010-01-20 00:00:00 <type 'datetime.datetime'>\n16 <type 'int'>\nsome words <type 'str'>\n\n", "There's no real answer to this as far as I can tell since these are just strings. They're not integers or floats or whatever. Those are roles you decide. eg. Is 1 an integer or a float? \nA couple of things come to mind though. One is to do some kind of pattern matching (eg. If it contains a decimal point, it's a float etc.). For parsing/guessing dates, you can try this or this. \nYou could also try 'casting' the element into whatever you want and catch exceptions to try the others. You can do something like try int, if it fails, try float and if that fails, try date etc.\n", "What you want to acheive is difficult because the types are ambiguous: \"1\" could either be a string, or an int for example. At any rate, you could try something like this:\n\nDates: presumably they are in a known format: if so, you can try instantiating a datetime from the timestamp string (datetime.strptime()) and if it fails you know its not a datetime.\nFloats: ensure all characters are either a digit and there is at least one \".\" in the string. Then convert to float (float(value))\nIntegers: regex the string and match digits. Ensure the string is the same lenght as the source string then convert (int(value))\nIf none of the above worked, it's a string.\n\n", "Well..you can't.\nHow would you decide if \"5\" is meant as a string or an integer?\nHow would you decide if \"20100120\" is meant as an integer or a date?\nYou can of course make educated guesses, and implement some kind of parse order. First try it as a date, then as a float, then as an int, and lastly as a string.\n", "From the manual:\n\nReturn a reader object which will\n iterate over lines in the given\n csvfile. csvfile can be any object\n which supports the iterator protocol\n and returns a string each time its\n next() method is called — file objects\n and list objects are both suitable.\n\nThe interface requires that a string be returned each time next() is called.\n", "The date is a bit harder. It depends on the format and how regular it is. Here is a clue to get you started on the rest.\n>>> int('a')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nValueError: invalid literal for int() with base 10: 'a'\n>>> int('1')\n1\n>>> float('1')\n1.0\n>>> float('1.0')\n1.0\n\nBut notice:\n>>> int(1.0)\n1\n\n" ]
[ 15, 7, 2, 1, 1, 0, 0 ]
[]
[]
[ "casting", "csv", "python", "types" ]
stackoverflow_0002103071_casting_csv_python_types.txt
Q: Python newbie class design question I'm trying to figure out the best way to design a couple of classes. I'm pretty new to Python (and OOP in general) and just want to make sure that I'm doing this right. I have two classes: "Users" and "User". class User(object): def __init__(self): pass class Users(object): def __init__(self): self.users = [] def add(self, user_id, email): u = User() u.user_id = user_id u.email = email self.users.append(u) users = Users() users.add(user_id = 1, email = 'bob@example.com') If I want to retrieve my users, I use: for u in users.users: print u.email "users.users" seems to be a bit redundant. Am I doing this right? A: I would say not really. Your Users class appears to just be a list of users, so I would just make it a list rather than a whole class. Here's what I would do: class User(object): def __init__(self, user_id=None, email=None): self.user_id, self.email = user_id, email users = [] users.append(User(user_id = 1, email = 'bob@example.com')) for u in users: print u.email If you want Users to be a class of its own for some other reason, you could have it inherit from list, or (if not) you could add these to the definition: class Users(object): # rest of code def __iter__(self): return iter(self.users) That way, you can simply say: users = Users() ... for u in users: print u.email A: Put this in your Users: def __iter__(self): return iter(self.users) Now you can: for u in users: print u.email Docs A: You probably just want a list of User objects rather than a class which contains multiple users. class User(object): def __init__(self, user_id, email): self.user_id = user_id self.email = email users = [] users.append(User(user_id = 1, email = 'bob@example.com')) All member attributes for User should reside in the User class, not the Users class. A: I don't see anything wrong with users.users, but if you prefer a nicer way to do it you could override __iter__ in Users. class Users(object): def __init__(self): self.users = [] def add(self, user_id, email): u = User() u.user_id = user_id u.email = email self.users.append(u) def __iter__(self): return iter(self.users) Now you can do this: for u in users: print u.email The __iter__ special method makes your object behave as an iterator A: There's no "black" and "white" here, just shades of grey. You don't need a special Users class if it's just going to be a list. Another way: class User: all_users = [] def __init__(self, id, email): self.id = id # No need to call it user_id - it's a User object, after all! self.email = email self.all_users.append(self) #automatically add to list of all users def __str__(self): return '%s(%s)' % (self.id, self.email) Then, if you typed the above into user.py: >>> from user import * >>> bob = User('bob', 'bob@test.com') >>> alice = User('alice', 'alice@test.com') >>> for u in User.all_users: ... print u ... bob(bob@test.com) alice(alice@test.com) >>> Just an example to get you thinking.
Python newbie class design question
I'm trying to figure out the best way to design a couple of classes. I'm pretty new to Python (and OOP in general) and just want to make sure that I'm doing this right. I have two classes: "Users" and "User". class User(object): def __init__(self): pass class Users(object): def __init__(self): self.users = [] def add(self, user_id, email): u = User() u.user_id = user_id u.email = email self.users.append(u) users = Users() users.add(user_id = 1, email = 'bob@example.com') If I want to retrieve my users, I use: for u in users.users: print u.email "users.users" seems to be a bit redundant. Am I doing this right?
[ "I would say not really. Your Users class appears to just be a list of users, so I would just make it a list rather than a whole class. Here's what I would do:\nclass User(object):\n def __init__(self, user_id=None, email=None):\n self.user_id, self.email = user_id, email\n\nusers = []\nusers.append(User(user_id = 1, email = 'bob@example.com'))\n\nfor u in users:\n print u.email\n\nIf you want Users to be a class of its own for some other reason, you could have it inherit from list, or (if not) you could add these to the definition:\nclass Users(object):\n # rest of code\n def __iter__(self):\n return iter(self.users)\n\nThat way, you can simply say:\nusers = Users()\n...\nfor u in users:\n print u.email\n\n", "Put this in your Users:\ndef __iter__(self):\n return iter(self.users)\n\nNow you can:\nfor u in users:\n print u.email\n\nDocs\n", "You probably just want a list of User objects rather than a class which contains multiple users.\nclass User(object):\n def __init__(self, user_id, email):\n self.user_id = user_id\n self.email = email\n\nusers = []\nusers.append(User(user_id = 1, email = 'bob@example.com'))\n\nAll member attributes for User should reside in the User class, not the Users class. \n", "I don't see anything wrong with users.users, but if you prefer a nicer way to do it you could override __iter__ in Users.\nclass Users(object):\n def __init__(self):\n self.users = []\n\n def add(self, user_id, email):\n u = User()\n u.user_id = user_id\n u.email = email\n self.users.append(u)\n\n def __iter__(self):\n return iter(self.users)\n\nNow you can do this:\nfor u in users:\n print u.email\n\nThe __iter__ special method makes your object behave as an iterator\n", "There's no \"black\" and \"white\" here, just shades of grey. You don't need a special Users class if it's just going to be a list.\nAnother way:\nclass User:\n all_users = []\n\n def __init__(self, id, email):\n self.id = id # No need to call it user_id - it's a User object, after all!\n self.email = email\n self.all_users.append(self) #automatically add to list of all users\n\n def __str__(self):\n return '%s(%s)' % (self.id, self.email)\n\nThen, if you typed the above into user.py:\n\n>>> from user import *\n>>> bob = User('bob', 'bob@test.com')\n>>> alice = User('alice', 'alice@test.com')\n>>> for u in User.all_users:\n... print u\n...\nbob(bob@test.com)\nalice(alice@test.com)\n>>>\n\nJust an example to get you thinking.\n" ]
[ 17, 11, 6, 4, 1 ]
[]
[]
[ "iterator", "oop", "python" ]
stackoverflow_0002103532_iterator_oop_python.txt
Q: Re-creating threading and concurrency knowledge in increasingly popular languages I am primarily a Java developer, and I've been reading a lot of in-depth work on threads and concurrency. Many very smart people (Doug Lea, Brian Goetz, etc) have authored books on these topics and made contributions to new concurrency libraries for Java. As I start to learn more about Python, Ruby, and other languages, I'm wondering: does all of that work have to be re-created for these languages? Will there be, or does there need to be, a "Doug Lea of Python," or a "Brian Goetz of Ruby," who make similarly powerful contributions to the concurrency features of those languages? Does all of this concurrency work done in Java have to be re-created for future languages? Or will the work done in Java establish lessons and guidance for future languages? A: The basic principles of concurrent programming existed before java and were summarized in those java books you're talking about. The java.util.concurrent library was similarly derived from previous code and research papers on concurrent programming. However, some implementation issues are specific to Java. It has a specified memory model, and the concurrent utilities in Java are tailored to the specifics of that. With some modification those can be ported to other languages/environments with different memory model characteristics. So, you might need a book to teach you the canonical usage of the concurrency tools in other languages but it wouldn't be reinventing the wheel. A: Keep in mind that threads are just one of several possible models for dealing with "concurrency". Python, for example, has one of the most advanced asynchronous (event based) non-threaded models in Twisted. Non-blocking models are quite powerful and are used as alternatives to threads in most of the highest scaling apps out there (eg. nginx, lighttpd). Your assumption that other popular languages need threads may simply be a symptom of a java centric (and hence thread-centric) world view. Take a look at the C10K page for a slightly dated but highly informative look at several models for how to handle large volumes of concurrent requests. A: I think the answer is both yes and no. Java arguably has the most well-defined memory model and execution semantics of the most commonly used imperative languages (Java, C++, Python, Ruby, etc). In some sense, other languages either lack this completely or are playing catch-up (if that's even possible given the immaturity of the threading models). C++ is probably the notable exception - it has been treading the same ground for C++0x and has possibly gone beyond the current state of the Java model from my impression. I say no because the communities are not isolated. Many of the guys working on this stuff are involved (at least from a guidance point of view, if not from a direct hand in the specs) in more than one language. So, there is a lot of crosstalk between guys working on JMM and guys working on C++0x specs as they are essentially solving the same problems with many of the same underlying drivers (from the hardware guys at the bottom and the users at the top). And I'm pretty sure there is cross-talk at some level between the JVM / CLR camps as well. As others have mentioned, there are also other models for concurrency: actors in Erlang and Scala, agents/STM in Clojure, FP's rise in F#, Scala, Haskell, the CCR and PLINQ stuff in CLR land, etc. It's an exciting time right now! We can use as many concurrency experts as we can find I think.... :) A: This is not flame bait, but IMHO Java has one of the simpler and more restricted models for threading and concurrency available. That's not necessarily a bad thing, but at the level of granularity it offers it means that the perspective it gives you of what concurrency is and how to deal with it is inherently limited if you have a "java centric" view (as someone else put it). If you're serious about concurrency, then it's worth exploring other languages precisely because different models and idioms exist. Some of the hottest areas are lock-free programming (you'll see a lot of it, but often done badly, in C++) and functional programming (which has been around for a while but arguably, is becoming increasingly relevant. A prime example in the case of concurrency is probably Erlang). A: Kamaelia is a project (which I started, and continue to work on) that has specifically the goal of making concurrency a tool you want to use, rather than a pain to use. In practical terms this means that it is primarily a shared-nothing model with message passing model (based on a world view from Occam & Unix pipes). Underlying that goal is a desire to make concurrency easy to use for the average developer, shielding them from the nastier problems caused by a number of approaches to concurrency. (There's a bunch of presentations on slideshare explaining the why & how there) Additionally it provides a simple software transactional memory model for the situations where you must share data, and uses a deliberately simple API. Kamaelia's primary implementation is in python, with a toy implementation in Ruby & C++. Someone else has ported the underlying approach to E and also to Java. (though the Java person has disappeared) (The toy implementations are sanity checks the ideas can work in other languages, if needing to be recast as local idioms) Perhaps your question shouldn't be "what can these languages learn", but "what can the Java community learn by looking elsewhere?". Many people who learn python are liguistically immigrants from elsewhere and bring their knowledge of other languages with them, and so from where I sit it looks like python already looks out to other languages for inspiration. Picking something concrete, for example, this speak and write application - which is a tool for teaching a small child to read and write, based around pen input, handwriting recognition, and speech synth - uses several dozen concurrent subsystems, runs at an acceptable speed on a single core machine, would be easily amenable to running on a many-core machine. However, the reason for the number of concurrent subsystems however has nothing to do with "wanting to make the application parallel", but more to do with "How can I make the application easier to write, extend and maintain?". The fact it ends up embarassingly parallel is a secondary bonus. There's a full tutorial - Pragmatic Concurrency - linked from the front page. (Notes, slides, video & code bundle) The model can be improved, and suggestions are welcome - life would be very boring if we all just "stopped" trying to make better tools - but ignoring what already exists seems a little ... parochial. If that seems a little harsh, please look at today's dilbert.
Re-creating threading and concurrency knowledge in increasingly popular languages
I am primarily a Java developer, and I've been reading a lot of in-depth work on threads and concurrency. Many very smart people (Doug Lea, Brian Goetz, etc) have authored books on these topics and made contributions to new concurrency libraries for Java. As I start to learn more about Python, Ruby, and other languages, I'm wondering: does all of that work have to be re-created for these languages? Will there be, or does there need to be, a "Doug Lea of Python," or a "Brian Goetz of Ruby," who make similarly powerful contributions to the concurrency features of those languages? Does all of this concurrency work done in Java have to be re-created for future languages? Or will the work done in Java establish lessons and guidance for future languages?
[ "The basic principles of concurrent programming existed before java and were summarized in those java books you're talking about. The java.util.concurrent library was similarly derived from previous code and research papers on concurrent programming.\nHowever, some implementation issues are specific to Java. It has a specified memory model, and the concurrent utilities in Java are tailored to the specifics of that. With some modification those can be ported to other languages/environments with different memory model characteristics.\nSo, you might need a book to teach you the canonical usage of the concurrency tools in other languages but it wouldn't be reinventing the wheel.\n", "Keep in mind that threads are just one of several possible models for dealing with \"concurrency\". Python, for example, has one of the most advanced asynchronous (event based) non-threaded models in Twisted. Non-blocking models are quite powerful and are used as alternatives to threads in most of the highest scaling apps out there (eg. nginx, lighttpd). \nYour assumption that other popular languages need threads may simply be a symptom of a java centric (and hence thread-centric) world view. Take a look at the C10K page for a slightly dated but highly informative look at several models for how to handle large volumes of concurrent requests.\n", "I think the answer is both yes and no. Java arguably has the most well-defined memory model and execution semantics of the most commonly used imperative languages (Java, C++, Python, Ruby, etc). In some sense, other languages either lack this completely or are playing catch-up (if that's even possible given the immaturity of the threading models). \nC++ is probably the notable exception - it has been treading the same ground for C++0x and has possibly gone beyond the current state of the Java model from my impression.\nI say no because the communities are not isolated. Many of the guys working on this stuff are involved (at least from a guidance point of view, if not from a direct hand in the specs) in more than one language. So, there is a lot of crosstalk between guys working on JMM and guys working on C++0x specs as they are essentially solving the same problems with many of the same underlying drivers (from the hardware guys at the bottom and the users at the top). And I'm pretty sure there is cross-talk at some level between the JVM / CLR camps as well. \nAs others have mentioned, there are also other models for concurrency: actors in Erlang and Scala, agents/STM in Clojure, FP's rise in F#, Scala, Haskell, the CCR and PLINQ stuff in CLR land, etc. It's an exciting time right now! We can use as many concurrency experts as we can find I think.... :)\n", "This is not flame bait, but IMHO Java has one of the simpler and more restricted models for threading and concurrency available.\nThat's not necessarily a bad thing, but at the level of granularity it offers it means that the perspective it gives you of what concurrency is and how to deal with it is inherently limited if you have a \"java centric\" view (as someone else put it).\nIf you're serious about concurrency, then it's worth exploring other languages precisely because different models and idioms exist.\nSome of the hottest areas are lock-free programming (you'll see a lot of it, but often done badly, in C++) and functional programming (which has been around for a while but arguably, is becoming increasingly relevant. A prime example in the case of concurrency is probably Erlang).\n", "Kamaelia is a project (which I started, and continue to work on) that has specifically the goal of making concurrency a tool you want to use, rather than a pain to use. In practical terms this means that it is primarily a shared-nothing model with message passing model (based on a world view from Occam & Unix pipes).\nUnderlying that goal is a desire to make concurrency easy to use for the average developer, shielding them from the nastier problems caused by a number of approaches to concurrency. (There's a bunch of presentations on slideshare explaining the why & how there)\nAdditionally it provides a simple software transactional memory model for the situations where you must share data, and uses a deliberately simple API.\nKamaelia's primary implementation is in python, with a toy implementation in Ruby & C++. Someone else has ported the underlying approach to E and also to Java. (though the Java person has disappeared) (The toy implementations are sanity checks the ideas can work in other languages, if needing to be recast as local idioms)\nPerhaps your question shouldn't be \"what can these languages learn\", but \"what can the Java community learn by looking elsewhere?\". Many people who learn python are liguistically immigrants from elsewhere and bring their knowledge of other languages with them, and so from where I sit it looks like python already looks out to other languages for inspiration.\nPicking something concrete, for example, this speak and write application - which is a tool for teaching a small child to read and write, based around pen input, handwriting recognition, and speech synth - uses several dozen concurrent subsystems, runs at an acceptable speed on a single core machine, would be easily amenable to running on a many-core machine. However, the reason for the number of concurrent subsystems however has nothing to do with \"wanting to make the application parallel\", but more to do with \"How can I make the application easier to write, extend and maintain?\". The fact it ends up embarassingly parallel is a secondary bonus.\nThere's a full tutorial - Pragmatic Concurrency - linked from the front page. (Notes, slides, video & code bundle)\nThe model can be improved, and suggestions are welcome - life would be very boring if we all just \"stopped\" trying to make better tools - but ignoring what already exists seems a little ... parochial. If that seems a little harsh, please look at today's dilbert.\n" ]
[ 11, 5, 3, 1, 1 ]
[]
[]
[ "concurrency", "java", "multithreading", "python", "ruby" ]
stackoverflow_0000440036_concurrency_java_multithreading_python_ruby.txt
Q: Two forms in django templates without conflict I'm creating a template with two different forms but I have the following problem: when I submit the first one the second is also validated and get validation errors. What can I do to avoid this conflict? Thanks and sorry for my english. A: use the prefix argument on your forms
Two forms in django templates without conflict
I'm creating a template with two different forms but I have the following problem: when I submit the first one the second is also validated and get validation errors. What can I do to avoid this conflict? Thanks and sorry for my english.
[ "use the prefix argument on your forms\n" ]
[ 5 ]
[]
[]
[ "django", "django_forms", "django_templates", "python" ]
stackoverflow_0002103805_django_django_forms_django_templates_python.txt
Q: Django: Check on type of relation a form has I have a situation where I need to check if a form has m2m relation before saving it in views.py as I am using the same views.py for different models. Example: #models.py class BaseClass(models.Model): # Some generic stuff. class SomeClass(BaseClass): # This class doesnt have any many2many relations class SomeOtherClass(BaseClass): # This class has many2many relations #views.py def do_some_stuff(request): # Instantiate a form # Save it in a normal way form.save() # Now, in here while saving I need to check if the form has any # m2m relations so I can use the save_m2m() function after form.save() I just need an extra check in there to be on the safer side. Is there any way around this? Thanks in advance A: if hasattr(form, 'save_m2m'): form.save_m2m() You should bear in mind that save_m2m is only necessary (and only exists) when you call form.save with commit=False argument. If you save it with commit=True which is the default, there's no need in save_m2m. A: I just figured out the probable solution for this. You could use something like this: if len(form_instance._meta.many_to_many) > 0: for i in form_instance._meta.many_to_many: if type(i) = ManyToManyField: form_instance.save_m2m() break A: Antony is right and it is even easier, I quote from the documentation: Another side effect of using commit=False is seen when your model has a many-to-many relation with another model. If your model has a many-to-many relation and you specify commit=False when you save a form, Django cannot immediately save the form data for the many-to-many relation. This is because it isn't possible to save many-to-many data for an instance until the instance exists in the database. To work around this problem,every time you save a form using commit=False, Django adds a save_m2m() method to your ModelForm subclass. According to that, if you don't save a form with commit=False the method save_m2m() does not even exist, no matter if many-to-many relationships exist. True to the Python motto "easier to ask forgiveness than permission" you can also do: try: form.save_m2m() except: pass if you really want to. A: In fact, save_m2m() is always injected into ModelForm instance after save(commit=False). Even if there're no ManyToMany fields in the model. Here's the source of save_m2m function: def save_m2m(): opts = instance._meta cleaned_data = form.cleaned_data for f in opts.many_to_many: if fields and f.name not in fields: continue if f.name in cleaned_data: f.save_form_data(instance, cleaned_data[f.name]) If there are no ManyToMany fields (instance._meta.many_to_many=[]) nothing will be done. So you can safely call save_m2m in all cases.
Django: Check on type of relation a form has
I have a situation where I need to check if a form has m2m relation before saving it in views.py as I am using the same views.py for different models. Example: #models.py class BaseClass(models.Model): # Some generic stuff. class SomeClass(BaseClass): # This class doesnt have any many2many relations class SomeOtherClass(BaseClass): # This class has many2many relations #views.py def do_some_stuff(request): # Instantiate a form # Save it in a normal way form.save() # Now, in here while saving I need to check if the form has any # m2m relations so I can use the save_m2m() function after form.save() I just need an extra check in there to be on the safer side. Is there any way around this? Thanks in advance
[ "if hasattr(form, 'save_m2m'):\n form.save_m2m()\n\nYou should bear in mind that save_m2m is only necessary (and only exists) when you call form.save with commit=False argument. If you save it with commit=True which is the default, there's no need in save_m2m.\n", "I just figured out the probable solution for this.\nYou could use something like this:\nif len(form_instance._meta.many_to_many) > 0:\n for i in form_instance._meta.many_to_many:\n if type(i) = ManyToManyField:\n form_instance.save_m2m()\n break\n\n", "Antony is right and it is even easier, I quote from the documentation:\n\nAnother side effect of using commit=False is seen when your model has a many-to-many relation with another model. If your model has a many-to-many relation and you specify commit=False when you save a form, Django cannot immediately save the form data for the many-to-many relation. This is because it isn't possible to save many-to-many data for an instance until the instance exists in the database.\nTo work around this problem,every time you save a form using commit=False, Django adds a save_m2m() method to your ModelForm subclass.\n\nAccording to that, if you don't save a form with commit=False the method save_m2m() does not even exist, no matter if many-to-many relationships exist.\nTrue to the Python motto \"easier to ask forgiveness than permission\" you can also do:\ntry:\n form.save_m2m()\nexcept:\n pass\n\nif you really want to.\n", "In fact, save_m2m() is always injected into ModelForm instance after save(commit=False). Even if there're no ManyToMany fields in the model.\nHere's the source of save_m2m function:\ndef save_m2m():\n opts = instance._meta\n cleaned_data = form.cleaned_data\n for f in opts.many_to_many:\n if fields and f.name not in fields:\n continue\n if f.name in cleaned_data:\n f.save_form_data(instance, cleaned_data[f.name])\n\nIf there are no ManyToMany fields (instance._meta.many_to_many=[]) nothing will be done. \nSo you can safely call save_m2m in all cases.\n" ]
[ 0, 0, 0, 0 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0002100297_django_django_views_python.txt
Q: Efficiently search two-tuple What's the best one-liner replacement for the code below? I'm sure there's a smarter way. choices = ((1, 'ONE'), (2, 'TWO'), (3, 'THREE')) some_int = 2 for choice in choices: if choice[0] == some_int: label = choice[1] break; # label == 'TWO' A: labels = dict(choices) label = labels[some_int] you could, of course, join this into an one-liner, if you don't need labels anywhere else. A: You could use a dict. >>> choices = { 1: 'ONE', 2: 'TWO', 3: 'THREE' } >>> label = choices[2] >>> label 'TWO' A: For a one-off search, if you're committed to starting with that data structure and can't amortize the time it takes to build it into a dictionary, and don't know whether the starting structure is sorted (so that bisection-search is not an option), there are no substantially faster algorithms than simple linear search. You can express it elegantly, e.g. in Python 2.6 or better: label = next((lab for cho, lab in choices if cho==someint), None) assuming you want the label to be None if no choice matches -- or if you want an exception to be raised in that case, just label = next(lab for cho, lab in choices if cho==someint) or in older Python versions label = (lab for cho, lab in choices if cho==someint).next() but I doubt performance will change much (easy to measure with timeit if you care, but in that case you need to provide some realistic examples of choices -- typical lengths, chance of no choice being acceptable, etc, etc). A: If you're really looking for a one liner... label = dict(choices)[some_int] that is, >>> choices = ((1, 'ONE'), (2, 'TWO'), (3, 'THREE')) >>> dict(choices)[1] 'ONE'
Efficiently search two-tuple
What's the best one-liner replacement for the code below? I'm sure there's a smarter way. choices = ((1, 'ONE'), (2, 'TWO'), (3, 'THREE')) some_int = 2 for choice in choices: if choice[0] == some_int: label = choice[1] break; # label == 'TWO'
[ "labels = dict(choices)\nlabel = labels[some_int]\n\nyou could, of course, join this into an one-liner, if you don't need labels anywhere else.\n", "You could use a dict.\n>>> choices = { 1: 'ONE', 2: 'TWO', 3: 'THREE' }\n>>> label = choices[2]\n>>> label\n'TWO'\n\n", "For a one-off search, if you're committed to starting with that data structure and can't amortize the time it takes to build it into a dictionary, and don't know whether the starting structure is sorted (so that bisection-search is not an option), there are no substantially faster algorithms than simple linear search. You can express it elegantly, e.g. in Python 2.6 or better:\nlabel = next((lab for cho, lab in choices if cho==someint), None)\n\nassuming you want the label to be None if no choice matches -- or if you want an exception to be raised in that case, just\nlabel = next(lab for cho, lab in choices if cho==someint)\n\nor in older Python versions\nlabel = (lab for cho, lab in choices if cho==someint).next()\n\nbut I doubt performance will change much (easy to measure with timeit if you care, but in that case you need to provide some realistic examples of choices -- typical lengths, chance of no choice being acceptable, etc, etc).\n", "If you're really looking for a one liner...\nlabel = dict(choices)[some_int]\n\nthat is,\n>>> choices = ((1, 'ONE'), (2, 'TWO'), (3, 'THREE'))\n>>> dict(choices)[1]\n'ONE'\n\n" ]
[ 14, 6, 5, 3 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0002104095_python_tuples.txt
Q: Python tool to balance parentheses, quotes, and brackets Does anyone know of an already-written Python script, tool, or editor that will check for unbalanced multi-line tokens? (parentheses, quotes, {}, [], etc.) I've been writing Python code in IDLE, and every so often I'll get "EOF token in multi-line statement" and start swearing, because it means that somewhere in about 200 lines of code I forgot a closing parenthesis or quote and IDLE can't tell me where. This seems like a fairly straightforward thing, I just don't really have the time or headspace to work it out myself right now. Much thanks A: I use Eclipse with PyDev. It's very good for this sort of thing, and lots more. A: emacs will automatically highlight matching pairs of parentheses/brackets/quotes/etc. as you type them, and it will inform you immediately if you mismatch them (e.g. if you type a [ followed by a )). I'm sure vim also does this, but since I don't use vim, I can't say with certainty. A: PyDev is the best IDE to develop in Python. Has this feature and a lot of more. A: If you use the vim text editor, there is a syntax highlighter for Python that might be of some help. Vim's python indenting rules also line up a new line with an unmatched open parenthesis from the previous line. That's been my visual cue that something is unbalanced.
Python tool to balance parentheses, quotes, and brackets
Does anyone know of an already-written Python script, tool, or editor that will check for unbalanced multi-line tokens? (parentheses, quotes, {}, [], etc.) I've been writing Python code in IDLE, and every so often I'll get "EOF token in multi-line statement" and start swearing, because it means that somewhere in about 200 lines of code I forgot a closing parenthesis or quote and IDLE can't tell me where. This seems like a fairly straightforward thing, I just don't really have the time or headspace to work it out myself right now. Much thanks
[ "I use Eclipse with PyDev. It's very good for this sort of thing, and lots more.\n", "emacs will automatically highlight matching pairs of parentheses/brackets/quotes/etc. as you type them, and it will inform you immediately if you mismatch them (e.g. if you type a [ followed by a )). I'm sure vim also does this, but since I don't use vim, I can't say with certainty.\n", "PyDev is the best IDE to develop in Python. Has this feature and a lot of more.\n", "If you use the vim text editor, there is a syntax highlighter for Python that might be of some help. Vim's python indenting rules also line up a new line with an unmatched open parenthesis from the previous line. That's been my visual cue that something is unbalanced.\n" ]
[ 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002104227_python.txt
Q: Django/Python: How do you start a new process in Python? After a customer uploads an image I want to re-size an image to 8 different sizes and then send them up to S3 and save them to the file system. Obviously this could take a long time (seconds) and I would want to do it in a "multithreaded" way (I quote that because I don't care if it's actually multithreaded or if it's some other functionality). My understanding is that because of the GIL in Python you cannot successfully use multithreading for things like this because it uses the same process and therefore works exactly the same as if you did it in your code's normal flow (vs multithreading). Is there some other, better way of opening a new process in Python for this sort of task? A: If you want to call an external process, use the subprocess module. If on the other hand you want to side-step the GIL and spin of some Python task, use the multiprocessing module. It provides an interface very much like the threading package's but utilizes subprocesses so you are not bound by the constraints of the GIL.
Django/Python: How do you start a new process in Python?
After a customer uploads an image I want to re-size an image to 8 different sizes and then send them up to S3 and save them to the file system. Obviously this could take a long time (seconds) and I would want to do it in a "multithreaded" way (I quote that because I don't care if it's actually multithreaded or if it's some other functionality). My understanding is that because of the GIL in Python you cannot successfully use multithreading for things like this because it uses the same process and therefore works exactly the same as if you did it in your code's normal flow (vs multithreading). Is there some other, better way of opening a new process in Python for this sort of task?
[ "If you want to call an external process, use the subprocess module. \nIf on the other hand you want to side-step the GIL and spin of some Python task, use the multiprocessing module. It provides an interface very much like the threading package's but utilizes subprocesses so you are not bound by the constraints of the GIL.\n" ]
[ 2 ]
[]
[]
[ "django", "multithreading", "python" ]
stackoverflow_0002104235_django_multithreading_python.txt
Q: wx.DatePickerCtrl in dialog ignores value entered after hitting return on wxGTK I have a dialog with a date picker control. Hitting enter in the date picker closes the dialog (as expected). However, the date picker doesn't pick up the value entered by the user on wxGTK. Run the sample attached, click the button, enter a new date in the date picker, using the keyboard, and hit enter. The print statement shows the previous value of the date picker, not the value just entered. On wxMSW it works as expected. Using wxPython 2.8.10.1 in both cases. Any ideas? Work-around? Thanks, Frank import wx class Dialog(wx.Dialog): def __init__(self, *args, **kwargs): super(Dialog, self).__init__(*args, **kwargs) self.datepicker = wx.DatePickerCtrl(self) self.button = wx.Button(self, label='OK') self.button.SetDefault() self.button.Bind(wx.EVT_BUTTON, self.onButton) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.datepicker) sizer.Add(self.button) self.SetSizerAndFit(sizer) def onButton(self, event): print self.datepicker.GetValue() self.Close() class Frame(wx.Frame): def __init__(self, *args, **kwargs): super(Frame, self).__init__(*args, **kwargs) self.button = wx.Button(self, label='Press me to open dialog') self.button.Bind(wx.EVT_BUTTON, self.onButton) def onButton(self, event): dialog = Dialog(self, size=(200,30)) dialog.Show() app = wx.App() frame = Frame(None, size=(200,50)) frame.Show() app.MainLoop() A: I had a similar problem. I tried to just call datepicker.Navigate() every time before retrieving the date from the DatePickerCtrl with datepicker.GetValue(). It seemed to work. A: This seems to work-around the issue: import wx class Dialog(wx.Dialog): def __init__(self, *args, **kwargs): super(Dialog, self).__init__(*args, **kwargs) self.datepicker = wx.DatePickerCtrl(self) # On wxGTK, intercept all keys: if wx.Platform == '__WXGTK__': comboCtrl = self.datepicker.GetChildren()[0] comboCtrl.Bind(wx.EVT_KEY_DOWN, self.onKey) self.button = wx.Button(self, label='OK') self.button.SetDefault() self.button.Bind(wx.EVT_BUTTON, self.onButton) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.datepicker) sizer.Add(self.button) self.SetSizerAndFit(sizer) def onButton(self, event): print self.datepicker.GetValue() self.Close() def onKey(self, event): keyCode = event.GetKeyCode() if keyCode == wx.WXK_RETURN: # Move to the next field so that the contents of the text control, # that might be edited by the user, are updated by the datepicker: self.datepicker.Navigate() # Next, click the default button of the dialog: button = self.GetDefaultItem() click = wx.CommandEvent() click.SetEventType(wx.EVT_BUTTON.typeId) wx.PostEvent(button, click) elif keyCode == wx.WXK_TAB: self.datepicker.Navigate(not event.ShiftDown()) else: event.Skip() class Frame(wx.Frame): def __init__(self, *args, **kwargs): super(Frame, self).__init__(*args, **kwargs) self.button = wx.Button(self, label='Press me to open dialog') self.button.Bind(wx.EVT_BUTTON, self.onButton) def onButton(self, event): dialog = Dialog(self, size=(200,30)) dialog.Show() app = wx.App() frame = Frame(None, size=(200,50)) frame.Show() app.MainLoop()
wx.DatePickerCtrl in dialog ignores value entered after hitting return on wxGTK
I have a dialog with a date picker control. Hitting enter in the date picker closes the dialog (as expected). However, the date picker doesn't pick up the value entered by the user on wxGTK. Run the sample attached, click the button, enter a new date in the date picker, using the keyboard, and hit enter. The print statement shows the previous value of the date picker, not the value just entered. On wxMSW it works as expected. Using wxPython 2.8.10.1 in both cases. Any ideas? Work-around? Thanks, Frank import wx class Dialog(wx.Dialog): def __init__(self, *args, **kwargs): super(Dialog, self).__init__(*args, **kwargs) self.datepicker = wx.DatePickerCtrl(self) self.button = wx.Button(self, label='OK') self.button.SetDefault() self.button.Bind(wx.EVT_BUTTON, self.onButton) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.datepicker) sizer.Add(self.button) self.SetSizerAndFit(sizer) def onButton(self, event): print self.datepicker.GetValue() self.Close() class Frame(wx.Frame): def __init__(self, *args, **kwargs): super(Frame, self).__init__(*args, **kwargs) self.button = wx.Button(self, label='Press me to open dialog') self.button.Bind(wx.EVT_BUTTON, self.onButton) def onButton(self, event): dialog = Dialog(self, size=(200,30)) dialog.Show() app = wx.App() frame = Frame(None, size=(200,50)) frame.Show() app.MainLoop()
[ "I had a similar problem. I tried to just call datepicker.Navigate() every time before retrieving the date from the DatePickerCtrl with datepicker.GetValue(). It seemed to work.\n", "This seems to work-around the issue:\nimport wx\n\nclass Dialog(wx.Dialog):\n def __init__(self, *args, **kwargs):\n super(Dialog, self).__init__(*args, **kwargs)\n self.datepicker = wx.DatePickerCtrl(self)\n\n # On wxGTK, intercept all keys:\n if wx.Platform == '__WXGTK__':\n comboCtrl = self.datepicker.GetChildren()[0]\n comboCtrl.Bind(wx.EVT_KEY_DOWN, self.onKey)\n\n self.button = wx.Button(self, label='OK')\n self.button.SetDefault()\n self.button.Bind(wx.EVT_BUTTON, self.onButton)\n sizer = wx.BoxSizer(wx.VERTICAL)\n sizer.Add(self.datepicker)\n sizer.Add(self.button)\n self.SetSizerAndFit(sizer)\n\n def onButton(self, event):\n print self.datepicker.GetValue()\n self.Close()\n\n def onKey(self, event):\n keyCode = event.GetKeyCode()\n if keyCode == wx.WXK_RETURN:\n # Move to the next field so that the contents of the text control,\n # that might be edited by the user, are updated by the datepicker:\n self.datepicker.Navigate()\n # Next, click the default button of the dialog:\n button = self.GetDefaultItem()\n click = wx.CommandEvent()\n click.SetEventType(wx.EVT_BUTTON.typeId)\n wx.PostEvent(button, click)\n elif keyCode == wx.WXK_TAB:\n self.datepicker.Navigate(not event.ShiftDown())\n else:\n event.Skip()\n\n\nclass Frame(wx.Frame):\n def __init__(self, *args, **kwargs):\n super(Frame, self).__init__(*args, **kwargs)\n self.button = wx.Button(self, label='Press me to open dialog')\n self.button.Bind(wx.EVT_BUTTON, self.onButton)\n\n def onButton(self, event):\n dialog = Dialog(self, size=(200,30))\n dialog.Show() \n\napp = wx.App()\nframe = Frame(None, size=(200,50))\nframe.Show()\napp.MainLoop()\n\n" ]
[ 1, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0001568491_python_wxpython.txt
Q: Can a process keep running after the user sees the "Thanks. You're done!" page I'm trying to understand threading better. If I create a program that allows people to upload a photo and then I create a new process to resize the image in a hundred ways (taking 5 seconds or longer), and the main program returns a response HTML page to the user saying "Thanks. You're done!", can the other process still be working at this point? Assume that I'm using the multiprocessing module vs GIL threading with subprocess. A: Considering a Message or Job Queue is a good idea when you have background processing to do. This way you won't have to write your own code to handle job scheduling, priority etc. You can also add more servers to the queue when the first one starts running out of capacity.There's a package called Celery that is supposed to provide MQ access to django apps. In your case, you might create an animated 'throbber' on your page that periodically polls the server though ajax. When the image processing is done, you can update the page.
Can a process keep running after the user sees the "Thanks. You're done!" page
I'm trying to understand threading better. If I create a program that allows people to upload a photo and then I create a new process to resize the image in a hundred ways (taking 5 seconds or longer), and the main program returns a response HTML page to the user saying "Thanks. You're done!", can the other process still be working at this point? Assume that I'm using the multiprocessing module vs GIL threading with subprocess.
[ "Considering a Message or Job Queue is a good idea when you have background processing to do. This way you won't have to write your own code to handle job scheduling, priority etc. You can also add more servers to the queue when the first one starts running out of capacity.There's a package called Celery that is supposed to provide MQ access to django apps.\nIn your case, you might create an animated 'throbber' on your page that periodically polls the server though ajax. When the image processing is done, you can update the page.\n" ]
[ 9 ]
[]
[]
[ "django", "multithreading", "python" ]
stackoverflow_0002104313_django_multithreading_python.txt
Q: Load and Reuse Django Template Filters Is it possible to load a django template tag/filter to use as a function in one of my template tags? I'm trying to load up some of the django.contrib.humanize filters so I can apply them to the results of some of my custom template tags. I can't seem to import them at all, and I don't want to have to rewrite any of that code. A: Template tags are just Python functions; you can import their module and call them with impunity, the only requirement being that you pass them appropriate arguments. The django.contrib.humanize.templatetags.humanize module has separate functions to do the work, so it's even easier in that specific case.
Load and Reuse Django Template Filters
Is it possible to load a django template tag/filter to use as a function in one of my template tags? I'm trying to load up some of the django.contrib.humanize filters so I can apply them to the results of some of my custom template tags. I can't seem to import them at all, and I don't want to have to rewrite any of that code.
[ "Template tags are just Python functions; you can import their module and call them with impunity, the only requirement being that you pass them appropriate arguments. The django.contrib.humanize.templatetags.humanize module has separate functions to do the work, so it's even easier in that specific case.\n" ]
[ 3 ]
[]
[]
[ "django", "python", "templatetags" ]
stackoverflow_0002104767_django_python_templatetags.txt
Q: Python: Replacing item in a list of lists Heres my code: data = [ [5,3,0,0,7,0,0,0,0], [6,0,0,1,9,5,0,0,0], [0,9,8,0,0,0,0,6,0], [8,0,0,0,6,0,0,0,3], [4,0,0,8,0,3,0,0,1], [7,0,0,0,2,0,0,0,6], [0,6,0,0,0,0,2,8,0], [0,0,0,4,1,9,0,0,5], [0,0,0,0,8,0,0,7,9] ] element = 4 x = 0 y = 0 data[x][y] = element I want to replace the element at coordinates 0,0 but when i print data it hasnt changed the element. *******EDIT******: OK SO HERES MY FULL CODE:** data = [ [5,3,0,0,7,0,0,0,0], [6,0,0,1,9,5,0,0,0], [0,9,8,0,0,0,0,6,0], [8,0,0,0,6,0,0,0,3], [4,0,0,8,0,3,0,0,1], [7,0,0,0,2,0,0,0,6], [0,6,0,0,0,0,2,8,0], [0,0,0,4,1,9,0,0,5], [0,0,0,0,8,0,0,7,9] ] z = [] #row 6 x1 = 6 for y in range(9): print data[x1][y] z.append(data[x1][y]) #column 8 y1 = 8 for x in range(9): print data[x][y1] z.append(data[x][y1]) #finds the block coordinates x = 6 y = 8 basex = x - x%3 basey = y - y%3 for x1 in range(basex,basex+3): for y1 in range(basey,basey+3): print x1,y1, data[x1][y1] z.append(data[x1][y1]) item = [1,2,3,4,5,6,7,8,9] for element in item: if element not in z: print element data[x][y] = element print data[x][y] A: Works just fine for me... >>> data = [ ... [5,3,0,0,7,0,0,0,0], ... [6,0,0,1,9,5,0,0,0], ... [0,9,8,0,0,0,0,6,0], ... [8,0,0,0,6,0,0,0,3], ... [4,0,0,8,0,3,0,0,1], ... [7,0,0,0,2,0,0,0,6], ... [0,6,0,0,0,0,2,8,0], ... [0,0,0,4,1,9,0,0,5], ... [0,0,0,0,8,0,0,7,9] ... ] >>> element = 4 >>> x = 0 >>> y = 0 >>> print data[0][0] 5 >>> data[x][y] = element >>> print data[0][0] 4 >>> A: You seem to have tabbed out your last line, which gives me an error in the Python interpreter. If I remove that tab, it works. Your array data has changed. Maybe you aren't printing it out so you don't know that it changed? A: What version of python are you running? Can you try it from the command line and post the results, like below? It seems to be working for me. I basically copied and pasted straight from your post. Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> data = [ ... [5,3,0,0,7,0,0,0,0], ... [6,0,0,1,9,5,0,0,0], ... [0,9,8,0,0,0,0,6,0], ... [8,0,0,0,6,0,0,0,3], ... [4,0,0,8,0,3,0,0,1], ... [7,0,0,0,2,0,0,0,6], ... [0,6,0,0,0,0,2,8,0], ... [0,0,0,4,1,9,0,0,5], ... [0,0,0,0,8,0,0,7,9] ... ] >>> >>> element = 4 >>> x = 0 >>> y = 0 >>> >>> data [[5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9]] >>> data[x][y] = element >>> data [[4, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9]] >>> A: The only thing wrong I see in your code is that the very last line is at a different indentation level. Putting it at the same level of the rest of the code works fine. :) You may also be interested in the pprint module: >>> from pprint import pprint >>> pprint(data) [[4, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9]] A little easier to read! A: You need to break for look as soon as you find the necessary element: item = [1,2,3,4,5,6,7,8,9] for element in item: if element not in z: print element break data[x][y] = element print data[x][y] A: Ah... now that you've posted all your code, it makes much more sense... The reason it's not working the way you expected is because 'element' doesn't exist outside the context of the loop. You'll need to store the value you want to use in a variable that exists in the correct scope. A: It still works with the edited code. I changed the last few lines of your code to this: print "before =", data[x][y] print "element =", element data[x][y] = element print "after =", data[x][y] And those print this: before = 0 element = 9 after = 9 As has been mentioned, the last value of element from the for loop will be what its value is after the for loop is complete. That's why you get 9 here. A: for loops in Python do not create a new scope; the name you use to hold the current value in the loop will persist after the loop is done, and will retain the last value it had while the loop was running.
Python: Replacing item in a list of lists
Heres my code: data = [ [5,3,0,0,7,0,0,0,0], [6,0,0,1,9,5,0,0,0], [0,9,8,0,0,0,0,6,0], [8,0,0,0,6,0,0,0,3], [4,0,0,8,0,3,0,0,1], [7,0,0,0,2,0,0,0,6], [0,6,0,0,0,0,2,8,0], [0,0,0,4,1,9,0,0,5], [0,0,0,0,8,0,0,7,9] ] element = 4 x = 0 y = 0 data[x][y] = element I want to replace the element at coordinates 0,0 but when i print data it hasnt changed the element. *******EDIT******: OK SO HERES MY FULL CODE:** data = [ [5,3,0,0,7,0,0,0,0], [6,0,0,1,9,5,0,0,0], [0,9,8,0,0,0,0,6,0], [8,0,0,0,6,0,0,0,3], [4,0,0,8,0,3,0,0,1], [7,0,0,0,2,0,0,0,6], [0,6,0,0,0,0,2,8,0], [0,0,0,4,1,9,0,0,5], [0,0,0,0,8,0,0,7,9] ] z = [] #row 6 x1 = 6 for y in range(9): print data[x1][y] z.append(data[x1][y]) #column 8 y1 = 8 for x in range(9): print data[x][y1] z.append(data[x][y1]) #finds the block coordinates x = 6 y = 8 basex = x - x%3 basey = y - y%3 for x1 in range(basex,basex+3): for y1 in range(basey,basey+3): print x1,y1, data[x1][y1] z.append(data[x1][y1]) item = [1,2,3,4,5,6,7,8,9] for element in item: if element not in z: print element data[x][y] = element print data[x][y]
[ "Works just fine for me...\n>>> data = [\n... [5,3,0,0,7,0,0,0,0],\n... [6,0,0,1,9,5,0,0,0],\n... [0,9,8,0,0,0,0,6,0],\n... [8,0,0,0,6,0,0,0,3],\n... [4,0,0,8,0,3,0,0,1],\n... [7,0,0,0,2,0,0,0,6],\n... [0,6,0,0,0,0,2,8,0],\n... [0,0,0,4,1,9,0,0,5],\n... [0,0,0,0,8,0,0,7,9]\n... ]\n>>> element = 4\n>>> x = 0\n>>> y = 0\n>>> print data[0][0]\n5\n>>> data[x][y] = element\n>>> print data[0][0]\n4\n>>> \n\n", "You seem to have tabbed out your last line, which gives me an error in the Python interpreter. If I remove that tab, it works.\nYour array data has changed. Maybe you aren't printing it out so you don't know that it changed?\n", "What version of python are you running? Can you try it from the command line and post the results, like below? It seems to be working for me. I basically copied and pasted straight from your post.\nPython 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) \n[GCC 4.4.1] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> data = [\n... [5,3,0,0,7,0,0,0,0],\n... [6,0,0,1,9,5,0,0,0],\n... [0,9,8,0,0,0,0,6,0],\n... [8,0,0,0,6,0,0,0,3],\n... [4,0,0,8,0,3,0,0,1],\n... [7,0,0,0,2,0,0,0,6],\n... [0,6,0,0,0,0,2,8,0],\n... [0,0,0,4,1,9,0,0,5],\n... [0,0,0,0,8,0,0,7,9]\n... ]\n>>> \n>>> element = 4\n>>> x = 0\n>>> y = 0\n>>> \n>>> data\n[[5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9]]\n>>> data[x][y] = element\n>>> data\n[[4, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9]]\n>>> \n\n", "The only thing wrong I see in your code is that the very last line is at a different indentation level. Putting it at the same level of the rest of the code works fine. :)\nYou may also be interested in the pprint module:\n>>> from pprint import pprint\n>>> pprint(data)\n[[4, 3, 0, 0, 7, 0, 0, 0, 0],\n [6, 0, 0, 1, 9, 5, 0, 0, 0],\n [0, 9, 8, 0, 0, 0, 0, 6, 0],\n [8, 0, 0, 0, 6, 0, 0, 0, 3],\n [4, 0, 0, 8, 0, 3, 0, 0, 1],\n [7, 0, 0, 0, 2, 0, 0, 0, 6],\n [0, 6, 0, 0, 0, 0, 2, 8, 0],\n [0, 0, 0, 4, 1, 9, 0, 0, 5],\n [0, 0, 0, 0, 8, 0, 0, 7, 9]]\n\nA little easier to read!\n", "You need to break for look as soon as you find the necessary element:\nitem = [1,2,3,4,5,6,7,8,9]\nfor element in item:\n if element not in z:\n print element\n break\n\ndata[x][y] = element \nprint data[x][y]\n\n", "Ah... now that you've posted all your code, it makes much more sense...\nThe reason it's not working the way you expected is because 'element' doesn't exist outside the context of the loop. You'll need to store the value you want to use in a variable that exists in the correct scope.\n", "It still works with the edited code. I changed the last few lines of your code to this:\nprint \"before =\", data[x][y]\nprint \"element =\", element\ndata[x][y] = element \nprint \"after =\", data[x][y]\n\nAnd those print this:\nbefore = 0\nelement = 9\nafter = 9\n\nAs has been mentioned, the last value of element from the for loop will be what its value is after the for loop is complete. That's why you get 9 here.\n", "for loops in Python do not create a new scope; the name you use to hold the current value in the loop will persist after the loop is done, and will retain the last value it had while the loop was running.\n" ]
[ 1, 1, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002104796_python.txt
Q: QObject (QPlainTextEdit) & Multithreading issues Im currently trying to learn Networking with Python asyncore and pyqt4. I coded a small server, which basically listens on some port, and resends all messages it recieves to the sender. Since both qts QApplication.exec_() and asyncore.loop() are functions which never return i could not start them both in one thread, so i stared asyncore.loop() in a seperate daemon thread. Whenever my server class (derived from asyncore.dispatcher) establishes or drops a connection, or sends/recieves a message, it calls methods of my window class (derived from QtGui.QMainWindow), which displays the information in a QPlainTextEdit. But the text is not visible, unless you mark the text with the mouse. Python console displays following error msg: QObject::connect: Cannot queue arguments of type 'QTextBlock' (Make sure 'QTextBlock' is registered using qRegisterMetaType().) QObject::connect: Cannot queue arguments of type 'QTextCursor' (Make sure 'QTextCursor' is registered using qRegisterMetaType().) I read on some forum, that this may be caused by calling qt-functions from another Thread, and that using signals & slots instead of plain function calling may fix the issue, but i have tried signals aswell, and i still get this error. So, (if that is really the cause of my problems) whats the correct way to call methods of an qt object from another thread ? EDIT More Info: the asyncore.loop() call is located in the child thread, well its not really blocking, but only during the runtime of asyncore.loop() my Server class (asyncore.dispatcher) can do networking. So, during the runtime of asyncore.loop() the methods of my Server class ARE called by asyncore.loop() (=child thread), and in these i tried to emit signals to the window class running in the main thread EDIT: Seems like i got it working now, i had some errors in my code, everything works as intended with signals now. EDIT: small example: http://paste2.org/p/635612 (dead link) A: It appears you're trying to access QtGui classes from a thread other than the main thread. Like in some other GUI toolkits (e.g. Java Swing), that's not allowed. From the Threads and QObjects web page: Although QObject is reentrant, the GUI classes, notably QWidget and all its subclasses, are not reentrant. They can only be used from the main thread. A solution is to use signals and slots for communication between the main thread (where the GUI objects live) and your secondary thread(s). Basically, you emit signals in one thread that get delivered to the QObjects via the other thread. The page I linked to above has a good discussion of this. Actually, the whole section on Thread Support in Qt is a good read. One potential issue you could run into is that, normally, to get full signals and slots support working across threads, you need to start an event loop in the child thread using QThread::exec() (or the PyQt equivalent) so that signals can be delivered to slots in the QObjects that live there. In your case, it sounds like you're making a blocking call to asyncore.loop(), which will prevent you from doing this. But, if you only need to emit signals in one direction (from the child thread to widgets in the main thread), I don't think you'll have a problem.
QObject (QPlainTextEdit) & Multithreading issues
Im currently trying to learn Networking with Python asyncore and pyqt4. I coded a small server, which basically listens on some port, and resends all messages it recieves to the sender. Since both qts QApplication.exec_() and asyncore.loop() are functions which never return i could not start them both in one thread, so i stared asyncore.loop() in a seperate daemon thread. Whenever my server class (derived from asyncore.dispatcher) establishes or drops a connection, or sends/recieves a message, it calls methods of my window class (derived from QtGui.QMainWindow), which displays the information in a QPlainTextEdit. But the text is not visible, unless you mark the text with the mouse. Python console displays following error msg: QObject::connect: Cannot queue arguments of type 'QTextBlock' (Make sure 'QTextBlock' is registered using qRegisterMetaType().) QObject::connect: Cannot queue arguments of type 'QTextCursor' (Make sure 'QTextCursor' is registered using qRegisterMetaType().) I read on some forum, that this may be caused by calling qt-functions from another Thread, and that using signals & slots instead of plain function calling may fix the issue, but i have tried signals aswell, and i still get this error. So, (if that is really the cause of my problems) whats the correct way to call methods of an qt object from another thread ? EDIT More Info: the asyncore.loop() call is located in the child thread, well its not really blocking, but only during the runtime of asyncore.loop() my Server class (asyncore.dispatcher) can do networking. So, during the runtime of asyncore.loop() the methods of my Server class ARE called by asyncore.loop() (=child thread), and in these i tried to emit signals to the window class running in the main thread EDIT: Seems like i got it working now, i had some errors in my code, everything works as intended with signals now. EDIT: small example: http://paste2.org/p/635612 (dead link)
[ "It appears you're trying to access QtGui classes from a thread other than the main thread. Like in some other GUI toolkits (e.g. Java Swing), that's not allowed. From the Threads and QObjects web page:\n\nAlthough QObject is reentrant, the GUI\n classes, notably QWidget and all its\n subclasses, are not reentrant. They\n can only be used from the main thread.\n\nA solution is to use signals and slots for communication between the main thread (where the GUI objects live) and your secondary thread(s). Basically, you emit signals in one thread that get delivered to the QObjects via the other thread. The page I linked to above has a good discussion of this. Actually, the whole section on Thread Support in Qt is a good read. \nOne potential issue you could run into is that, normally, to get full signals and slots support working across threads, you need to start an event loop in the child thread using QThread::exec() (or the PyQt equivalent) so that signals can be delivered to slots in the QObjects that live there. In your case, it sounds like you're making a blocking call to asyncore.loop(), which will prevent you from doing this. But, if you only need to emit signals in one direction (from the child thread to widgets in the main thread), I don't think you'll have a problem.\n" ]
[ 15 ]
[]
[]
[ "asyncore", "multithreading", "pyqt4", "python", "qt4" ]
stackoverflow_0002104779_asyncore_multithreading_pyqt4_python_qt4.txt
Q: why no color output with Python? I have a batch file which calls .Net solution to build the project. On the dos console window, the warning and error will be in different color, green and red, looks nice. When the batch file called from Python, no color at all, all in a single color. Is it possible to get the same colorful result with python? my call to the batch file is like this: p = subprocess.Popen('manualBuild.bat', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in p.stdout.readlines(): print line, retval = p.wait() thanks A: Some programs test to see if they're actually connected to a console/terminal, and suppress attribute changes if they're not in order to make it easier to parse/process the output. I know that on *nix systems you can use unbuffer to fool the program, but I don't know if there's a Windows equivalent. A: If this were UNIX, I'd suggest you don't get the output in a variable but just let the program print it out (ie. don't pass stdout to subprocess). Maybe you can try that once?
why no color output with Python?
I have a batch file which calls .Net solution to build the project. On the dos console window, the warning and error will be in different color, green and red, looks nice. When the batch file called from Python, no color at all, all in a single color. Is it possible to get the same colorful result with python? my call to the batch file is like this: p = subprocess.Popen('manualBuild.bat', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in p.stdout.readlines(): print line, retval = p.wait() thanks
[ "Some programs test to see if they're actually connected to a console/terminal, and suppress attribute changes if they're not in order to make it easier to parse/process the output. I know that on *nix systems you can use unbuffer to fool the program, but I don't know if there's a Windows equivalent.\n", "If this were UNIX, I'd suggest you don't get the output in a variable but just let the program print it out (ie. don't pass stdout to subprocess). Maybe you can try that once?\n" ]
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002104785_python.txt
Q: Django queryset that returns all unassigned fks I have 2 models with a 1-1 relation (essentially a resource pool). For the example code, I will simply use nuts and bolts. There will be many more nuts (available resources) than bolts (which will each require 1 nut). However, if a nut can only be assigned to one bolt. The constraint is easy enough to set up with the unique=True named param to the ForeignKey method. The problem arises from the ModelForm. When rendered, the form will contain every nut in the dropdown. I would like to restrict it to only show nuts that haven't already been claimed by a bolt. I am aware of the fields attribute of the ModelForm class, but am unable to come up with a query set filter that adequately addresses the issue. Here is example code of my problem: from django.db import models from django.forms import ModelForm # Create your models here. class Nut(models.Model): size = models.CharField() class Bolt(models.Model): size = models.CharField() nut = models.ForeignKey( Nut, unique=True ) class BoltForm(ModelForm): def __init__(self, *args, **kwargs): super(BoltForm, self).__init__(*args, **kwargs) self.fields['nut'].queryset = # All unassigned nuts A: Try this: self.fields['nut'].queryset = Nut.objects.exclude( pk__in=Bolt.objects.values('nut').query) Update: Of three expressions generating the same sql query: pk__in=Bolt.objects.values('nut') pk__in=Bolt.objects.values_list('nut') pk__in=Bolt.objects.values('nut').query I'd choose the last one as most straight-forward (although in other two cases the list and dict aren't created in fact: django 'understands' the intention without explicit mentioning of .query) Also, consider Daniel Roseman's answer. It is another approach to do the same thing. A: Nut.objects.filter(bolt=None)
Django queryset that returns all unassigned fks
I have 2 models with a 1-1 relation (essentially a resource pool). For the example code, I will simply use nuts and bolts. There will be many more nuts (available resources) than bolts (which will each require 1 nut). However, if a nut can only be assigned to one bolt. The constraint is easy enough to set up with the unique=True named param to the ForeignKey method. The problem arises from the ModelForm. When rendered, the form will contain every nut in the dropdown. I would like to restrict it to only show nuts that haven't already been claimed by a bolt. I am aware of the fields attribute of the ModelForm class, but am unable to come up with a query set filter that adequately addresses the issue. Here is example code of my problem: from django.db import models from django.forms import ModelForm # Create your models here. class Nut(models.Model): size = models.CharField() class Bolt(models.Model): size = models.CharField() nut = models.ForeignKey( Nut, unique=True ) class BoltForm(ModelForm): def __init__(self, *args, **kwargs): super(BoltForm, self).__init__(*args, **kwargs) self.fields['nut'].queryset = # All unassigned nuts
[ "Try this:\nself.fields['nut'].queryset = Nut.objects.exclude(\n pk__in=Bolt.objects.values('nut').query)\n\nUpdate:\nOf three expressions generating the same sql query:\npk__in=Bolt.objects.values('nut')\npk__in=Bolt.objects.values_list('nut')\npk__in=Bolt.objects.values('nut').query\n\nI'd choose the last one as most straight-forward (although in other two cases the list and dict aren't created in fact: django 'understands' the intention without explicit mentioning of .query)\nAlso, consider Daniel Roseman's answer. It is another approach to do the same thing.\n", "Nut.objects.filter(bolt=None)\n\n" ]
[ 4, 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002104921_django_django_models_python.txt
Q: Adding arrays with different number of dimensions Let's say I have a 2D Numpy array: >>> a = np.random.random((4,6)) and I want to add a 1D array to each row: >>> c = np.random.random((6,)) >>> a + c This works. Now if I try adding a 1D array to each column, I get an error: >>> b = np.random.random((4,)) >>> a + b Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: shape mismatch: objects cannot be broadcast to a single shape I can fix this by using np.newaxis: >>> a + b[:,np.newaxis] which does work as expected. What are the shape-matching rules to avoid having to use np.newaxis? Is it that the last element of the numpy shape tuple has to match? Does this rule also apply to higher dimensions? For example, the following works: >>> a = np.random.random((2,3,4,5)) >>> b = np.random.random((4,5)) >>> a + b So my question is whether this is documented anywhere, and if it is a behavior that can be relied on, or whether it is best to always use np.newaxis? A: This is a distinctive feature of numpy called 'broadcasting': if you can multiply a vector by a scalar why not allow multiplying a matrix by a vector? Just like every element of a vector is multiplied by a scalar in the first case, every cell in the matrix row is multiplied by the corresponding vector element in the second case. Broadcasting is done using four rules which are a bit complicated in formulation but are rather intuitive once understood: All input arrays with ndim smaller than the input array of largest ndim, have 1’s prepended to their shapes. The size in each dimension of the output shape is the maximum of all the input sizes in that dimension. An input can be used in the calculation if its size in a particular dimension either matches the output size in that dimension, or has value exactly 1. If an input has a dimension size of 1 in its shape, the first data entry in that dimension will be used for all calculations along that dimension. In other words, the stepping machinery of the ufunc will simply not step along that dimension (the stride will be 0 for that dimension). For example, The operation is possible (doesn't result in shape mismatch error you mentioned) in three cases: The arrays all have exactly the same shape. The arrays all have the same number of dimensions and the length of each dimensions is either a common length or 1. The arrays that have too few dimensions can have their shapes prepended with a dimension of length 1 to satisfy property 2. More examples can be found in my recent article on broadcasting [1] or in the official docs [2]. References Broadcasting in NumPy, 2021 https://towardsdatascience.com/58856f926d73 NumPy Reference. Broadcasting http://docs.scipy.org/doc/numpy/reference/ufuncs.html#broadcasting A: Let me see if I get it... >>> from numpy import ones, newaxis >>> A = ones((4,3)) # 4 rows x 3 cols >>> A.shape (4, 3) >>> A array([[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]]) >>> >>> ones((4,1)) # 4 rows x 1 col array([[ 1.], [ 1.], [ 1.], [ 1.]]) >>> A + ones((4,1)) array([[ 2., 2., 2.], [ 2., 2., 2.], [ 2., 2., 2.], [ 2., 2., 2.]]) >>> >>> ones((1,3)) # 1 row x 3 cols array([[ 1., 1., 1.]]) >>> A + ones((1,3)) array([[ 2., 2., 2.], [ 2., 2., 2.], [ 2., 2., 2.], [ 2., 2., 2.]]) >>> >>> B = ones((3,)) # a 1D array >>> B array([ 1., 1., 1.]) >>> B.shape (3,) >>> A + B array([[ 2., 2., 2.], [ 2., 2., 2.], [ 2., 2., 2.], [ 2., 2., 2.]]) >>> >>> C = ones((4,)) # a 1D array >>> C.shape (4,) >>> C array([ 1., 1., 1., 1.]) >>> A + C Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: shape mismatch: objects cannot be broadcast to a single shape >>> >>> D = C[:,newaxis] >>> D.shape (4, 1) >>> A + D array([[ 2., 2., 2.], [ 2., 2., 2.], [ 2., 2., 2.], [ 2., 2., 2.]]) The broadcast needed to do 4 x 3 vector plus a 1D vector with 3 elements succeeds. The broadcast needed to do 4 x 3 vector plus a 1D vector with 4 elements fails. >>> D = C[:,newaxis] converts C to a 2D vector of a compatible shape.
Adding arrays with different number of dimensions
Let's say I have a 2D Numpy array: >>> a = np.random.random((4,6)) and I want to add a 1D array to each row: >>> c = np.random.random((6,)) >>> a + c This works. Now if I try adding a 1D array to each column, I get an error: >>> b = np.random.random((4,)) >>> a + b Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: shape mismatch: objects cannot be broadcast to a single shape I can fix this by using np.newaxis: >>> a + b[:,np.newaxis] which does work as expected. What are the shape-matching rules to avoid having to use np.newaxis? Is it that the last element of the numpy shape tuple has to match? Does this rule also apply to higher dimensions? For example, the following works: >>> a = np.random.random((2,3,4,5)) >>> b = np.random.random((4,5)) >>> a + b So my question is whether this is documented anywhere, and if it is a behavior that can be relied on, or whether it is best to always use np.newaxis?
[ "This is a distinctive feature of numpy called 'broadcasting':\nif you can multiply a vector by a scalar why not allow multiplying a matrix by a vector? Just like every element of a vector is multiplied by a scalar in the first case, every cell in the matrix row is multiplied by the corresponding vector element in the second case.\nBroadcasting is done using four rules which are a bit complicated in formulation but are rather intuitive once understood:\n\n\nAll input arrays with ndim smaller than the input array of largest ndim,\nhave 1’s prepended to their shapes.\nThe size in each dimension of the output shape is the maximum of all the\ninput sizes in that dimension.\nAn input can be used in the calculation if its size in a\nparticular dimension either matches\nthe output size in that dimension, or\nhas value exactly 1.\nIf an input has a dimension size of 1 in its shape, the first data entry\nin that dimension will be used for all\ncalculations along that dimension. In\nother words, the stepping machinery of\nthe ufunc will simply not step along\nthat dimension (the stride will be 0\nfor that dimension).\n\n\nFor example,\n\nThe operation is possible (doesn't result in shape mismatch error you mentioned) in three cases:\n\n\nThe arrays all have exactly the same shape.\nThe arrays all have the same number of dimensions and the length of each dimensions is either a common length or 1.\nThe arrays that have too few dimensions can have their shapes prepended with a dimension of length 1 to satisfy property 2.\n\n\nMore examples can be found in my recent article on broadcasting [1] or in the official docs [2].\nReferences\n\nBroadcasting in NumPy, 2021 https://towardsdatascience.com/58856f926d73\nNumPy Reference. Broadcasting http://docs.scipy.org/doc/numpy/reference/ufuncs.html#broadcasting\n\n", "Let me see if I get it...\n>>> from numpy import ones, newaxis\n>>> A = ones((4,3)) # 4 rows x 3 cols\n>>> A.shape\n(4, 3)\n>>> A\narray([[ 1., 1., 1.],\n [ 1., 1., 1.],\n [ 1., 1., 1.],\n [ 1., 1., 1.]])\n>>> \n>>> ones((4,1)) # 4 rows x 1 col\narray([[ 1.],\n [ 1.],\n [ 1.],\n [ 1.]])\n>>> A + ones((4,1))\narray([[ 2., 2., 2.],\n [ 2., 2., 2.],\n [ 2., 2., 2.],\n [ 2., 2., 2.]])\n>>> \n>>> ones((1,3)) # 1 row x 3 cols\narray([[ 1., 1., 1.]])\n>>> A + ones((1,3)) \narray([[ 2., 2., 2.],\n [ 2., 2., 2.],\n [ 2., 2., 2.],\n [ 2., 2., 2.]])\n>>> \n>>> B = ones((3,)) # a 1D array\n>>> B\narray([ 1., 1., 1.])\n>>> B.shape\n(3,)\n>>> A + B\narray([[ 2., 2., 2.],\n [ 2., 2., 2.],\n [ 2., 2., 2.],\n [ 2., 2., 2.]])\n>>> \n>>> C = ones((4,)) # a 1D array\n>>> C.shape\n(4,)\n>>> C\narray([ 1., 1., 1., 1.])\n>>> A + C\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nValueError: shape mismatch: objects cannot be broadcast to a single shape\n>>> \n>>> D = C[:,newaxis]\n>>> D.shape\n(4, 1)\n>>> A + D\narray([[ 2., 2., 2.],\n [ 2., 2., 2.],\n [ 2., 2., 2.],\n [ 2., 2., 2.]])\n\nThe broadcast needed to do 4 x 3 vector plus a 1D vector with 3 elements succeeds.\nThe broadcast needed to do 4 x 3 vector plus a 1D vector with 4 elements fails.\n>>> D = C[:,newaxis]\n\nconverts C to a 2D vector of a compatible shape.\n" ]
[ 13, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0002104643_numpy_python.txt
Q: Error Installing Gitosis on Fedora Core I'm trying to follow these instructions on installing gitosis: http://scie.nti.st/2007/11/14/hosting-git-repositories-the-easy-and-secure-way and these: http://www.webtop.com.au/installing-git-and-gitosis-on-fedora-10 And at the point where I need to clone the gitosis-admin.git repository from the server I'm setting up, I am receiving this error: ERROR:gitosis.app:Unable to read config file: [Errno 13] Permission denied: '/home/git/.gitosis.conf' fatal: The remote end hung up unexpectedly I have followed every set of instructions imaginable at this point, and I can't seem to find anyone else who has received this error. Any ideas would be greatly appreciated. Thanks, Dave Morris A: Make sure you're running that command as the git user, and make sure that the git user owns the /home/git directory. Are you running git clone git@yourserver:gitosis-admin.git ? It sounds like one of those things is not the case.
Error Installing Gitosis on Fedora Core
I'm trying to follow these instructions on installing gitosis: http://scie.nti.st/2007/11/14/hosting-git-repositories-the-easy-and-secure-way and these: http://www.webtop.com.au/installing-git-and-gitosis-on-fedora-10 And at the point where I need to clone the gitosis-admin.git repository from the server I'm setting up, I am receiving this error: ERROR:gitosis.app:Unable to read config file: [Errno 13] Permission denied: '/home/git/.gitosis.conf' fatal: The remote end hung up unexpectedly I have followed every set of instructions imaginable at this point, and I can't seem to find anyone else who has received this error. Any ideas would be greatly appreciated. Thanks, Dave Morris
[ "Make sure you're running that command as the git user, and make sure that the git user owns the /home/git directory. \nAre you running git clone git@yourserver:gitosis-admin.git ?\nIt sounds like one of those things is not the case.\n" ]
[ 0 ]
[]
[]
[ "fedora", "git", "gitosis", "linux", "python" ]
stackoverflow_0002105390_fedora_git_gitosis_linux_python.txt
Q: In Jinja2, how can I use macros in combination with block tags? I'm a front end developer, and I've been trying to get a hang on using Jinja2 effectively. I want to tweak a current site so it has multiple base templates using inheritance, it fully uses block tags to substitute content and override it, and uses macros to support passing of arguments. My base template contains this code (edited for simplicity): <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> {% from "foo.html" import macro1, macro2, macro3 %} {% macro base_template(title=none, arg2=none, urls={}, arg3=false) %} <html> <title>{{ title }} | Site.com</title> .... {{ caller() }} .... </html> {% endmacro %} {% block content %}{% endblock %} And my pages that extend it look like this: {% extends "base.html" %} {% block content %} {% call base_template(title="home", arg2="active", arg3="true") %} (html code here) {% endcall %} {% endblock %} So basically all the pages extend base, they call a macro and pass arguments to that macro. I don't quite understand it all, but the main point is that this allows default values and a degree of flexibility that doesn't require redefining an entire block: it gives some degree of flexibility and power. Again this is heavily simplified. The only problem is, this negates my ability to use blocks. Macros are for flexibility, but with blocks, I have the ability to override something entirely, or use it's parents contents and add to it, which I can't do with Macros (at least I don't think). The problem is, I can't wrap things in blocks, else they won't see the values in the macro. For instance, doing this: {% block title %}<title>{{ title }} | Site.com</title>{% endblock %} Will fail because it will say title is undefined. Ultimately I am looking for a way to utilize both the power and organiztional aspects of blocks, but still be able to utilize the logic & terseness of macros. If anyone could give me any help as to how I might go about this problem, I would really appreciate it. A: Blocks are only definable at a template's top level. If you extend a template, any values set in the child template using a set tag will be accessible from the template it is extending. For example, if you have a template named layout.html: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <title>{{ title }} | Site.com</title> .... {% block content %}{% endblock content %} .... </html> And you have this child template, index.html: {% extends "layout.html" %} {% set title = 'Homepage' %} {% block content %} (html code here) {% endblock content %} Then the reference to title in the parent would resolve to 'Homepage'. You can do this with any type of variable. For what you're doing, I don't think there is any need for macros - if you take advantage of this feature and place blocks well, you will be able to do pretty much everything you need to do as far as layouts are concerned. I would look at some of the templates used by Plurk Solace, which is written by one of the Jinja2 authors, if you want to get a good idea of when to use various features of Jinja2.
In Jinja2, how can I use macros in combination with block tags?
I'm a front end developer, and I've been trying to get a hang on using Jinja2 effectively. I want to tweak a current site so it has multiple base templates using inheritance, it fully uses block tags to substitute content and override it, and uses macros to support passing of arguments. My base template contains this code (edited for simplicity): <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> {% from "foo.html" import macro1, macro2, macro3 %} {% macro base_template(title=none, arg2=none, urls={}, arg3=false) %} <html> <title>{{ title }} | Site.com</title> .... {{ caller() }} .... </html> {% endmacro %} {% block content %}{% endblock %} And my pages that extend it look like this: {% extends "base.html" %} {% block content %} {% call base_template(title="home", arg2="active", arg3="true") %} (html code here) {% endcall %} {% endblock %} So basically all the pages extend base, they call a macro and pass arguments to that macro. I don't quite understand it all, but the main point is that this allows default values and a degree of flexibility that doesn't require redefining an entire block: it gives some degree of flexibility and power. Again this is heavily simplified. The only problem is, this negates my ability to use blocks. Macros are for flexibility, but with blocks, I have the ability to override something entirely, or use it's parents contents and add to it, which I can't do with Macros (at least I don't think). The problem is, I can't wrap things in blocks, else they won't see the values in the macro. For instance, doing this: {% block title %}<title>{{ title }} | Site.com</title>{% endblock %} Will fail because it will say title is undefined. Ultimately I am looking for a way to utilize both the power and organiztional aspects of blocks, but still be able to utilize the logic & terseness of macros. If anyone could give me any help as to how I might go about this problem, I would really appreciate it.
[ "Blocks are only definable at a template's top level. If you extend a template, any values set in the child template using a set tag will be accessible from the template it is extending. For example, if you have a template named layout.html:\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n\"http://www.w3.org/TR/html4/strict.dtd\">\n<html>\n <title>{{ title }} | Site.com</title>\n ....\n {% block content %}{% endblock content %}\n ....\n</html>\n\nAnd you have this child template, index.html:\n{% extends \"layout.html\" %}\n{% set title = 'Homepage' %}\n{% block content %}\n(html code here)\n{% endblock content %}\n\nThen the reference to title in the parent would resolve to 'Homepage'. You can do this with any type of variable. For what you're doing, I don't think there is any need for macros - if you take advantage of this feature and place blocks well, you will be able to do pretty much everything you need to do as far as layouts are concerned. I would look at some of the templates used by Plurk Solace, which is written by one of the Jinja2 authors, if you want to get a good idea of when to use various features of Jinja2.\n" ]
[ 22 ]
[]
[]
[ "django", "django_templates", "jinja2", "python", "templates" ]
stackoverflow_0002104957_django_django_templates_jinja2_python_templates.txt
Q: SVN serve and PySVN Error message: Expected FS format between '1' and '3'; found format '4' For research purposes, I copied a SVN repo to my Windows machine using svnsync so I can replay on my machine without loading the actual server. I've been using PySVN in scripts to control the revision number I want the repo to be in and have been using it fine so far. Now I got a repo from a different project and svnsync got it fine. When I try to run the script in Ubuntu I get: Expected FS format between '1' and '3'; found format '4' From what I was able to learn from other questions on StackOverFlow and elsewhere, it seems that my ubuntu pysvn is out of date for a 1.6 subversion version and would only work for 1.5. Did I understand this correctly? Because on the pysvn download page it says that "This release of pysvn has been tested against Subversion 1.5.6 and Subversion 1.6.5" When I do sudo apt-get install python-svn it tells me that python-svn is already the newest version. So I'm assuming that PySVN doesn't support 1.6 Subversion repos. But if I try running the exact same script on a Windows box, with only pysvn module on it (no svn installation), and the local repo files, it runs fine and I can checkout files! So I'm confused. Why does PySVN run with FS format 4 repos on windows and not on Ubuntu? A: Which version of ubuntu you have? 9.04? It does not have subversion 1.6 afair. What versions do dpkg -l subversion dpkg -l python-svn report?
SVN serve and PySVN Error message: Expected FS format between '1' and '3'; found format '4'
For research purposes, I copied a SVN repo to my Windows machine using svnsync so I can replay on my machine without loading the actual server. I've been using PySVN in scripts to control the revision number I want the repo to be in and have been using it fine so far. Now I got a repo from a different project and svnsync got it fine. When I try to run the script in Ubuntu I get: Expected FS format between '1' and '3'; found format '4' From what I was able to learn from other questions on StackOverFlow and elsewhere, it seems that my ubuntu pysvn is out of date for a 1.6 subversion version and would only work for 1.5. Did I understand this correctly? Because on the pysvn download page it says that "This release of pysvn has been tested against Subversion 1.5.6 and Subversion 1.6.5" When I do sudo apt-get install python-svn it tells me that python-svn is already the newest version. So I'm assuming that PySVN doesn't support 1.6 Subversion repos. But if I try running the exact same script on a Windows box, with only pysvn module on it (no svn installation), and the local repo files, it runs fine and I can checkout files! So I'm confused. Why does PySVN run with FS format 4 repos on windows and not on Ubuntu?
[ "Which version of ubuntu you have? 9.04? It does not have subversion 1.6 afair.\nWhat versions do\ndpkg -l subversion\ndpkg -l python-svn\n\nreport?\n" ]
[ 1 ]
[]
[]
[ "pysvn", "python", "svn", "ubuntu" ]
stackoverflow_0002105456_pysvn_python_svn_ubuntu.txt
Q: os.walk() python: xml representation of a directory structure, recursion So I am trying to use os.walk() to generate an XML representation of a directory structure. I seem to be getting a ton of duplicates. It properly places directories within each other and files in the right place for the first portion of the xml file; however, after it does it correctly it then continues traversing incorrectly. I am not quite sure why.... Here is my code: def dirToXML(self,directory): curdir = os.getcwd() os.chdir(directory) xmlOutput="" tree = os.walk(directory) for root, dirs, files in tree: pathName = string.split(directory, os.sep) xmlOutput+="<dir><name><![CDATA["+pathName.pop()+"]]></name>" if len(files)>0: xmlOutput+=self.fileToXML(files) for subdir in dirs: xmlOutput+=self.dirToXML(os.path.join(root,subdir)) xmlOutput+="</dir>" os.chdir(curdir) return xmlOutput The fileToXML, simply parses out the list so no need to worry about that. The Directory Structure is simply: images/ images/testing.xml images/structure.xml images/Hellos images/Goodbyes images/Goodbyes/foo images/Goodbyes/bar images/Goodbyes/square and the resulting xml file became: <structure> <dir> <name>images</name> <files> <file> <name>structure.xml</name> </file> <file> <name>testing.xml</name> </file> </files> <dir> <name>Hellos</name> </dir> <dir> <name>Goodbyes</name> <dir> <name>foo</name> </dir> <dir> <name>bar</name> </dir> <dir> <name>square</name> </dir> </dir> <dir> <name>foo</name> </dir> <dir> <name>bar</name> </dir> <dir> <name>square</name> </dir> </dir> <dir> <name>Hellos</name> </dir> <dir> <name>Goodbyes</name> <dir> <name>foo</name> </dir> <dir> <name>bar</name> </dir> <dir> <name>square</name> </dir> </dir> <dir> <name>foo</name> </dir> <dir> <name>bar</name> </dir> <dir> <name>square</name> </dir> </structure> Any help would be much appreciated! A: I'd recommend against using os.walk(), since you have to do so much to massage its output. Instead, just use a recursive function that uses os.listdir(), os.path.join(), os.path.isdir(), etc. import os from xml.sax.saxutils import escape as xml_escape def DirAsXML(path): result = '<dir>\n<name>%s</name>\n' % xml_escape(os.path.basename(path)) dirs = [] files = [] for item in os.listdir(path): itempath = os.path.join(path, item) if os.path.isdir(itempath): dirs.append(item) elif os.path.isfile(itempath): files.append(item) if files: result += ' <files>\n' \ + '\n'.join(' <file>\n <name>%s</name>\n </file>' % xml_escape(f) for f in files) + '\n </files>\n' if dirs: for d in dirs: x = DirAsXML(os.path.join(path, d)) result += '\n'.join(' ' + line for line in x.split('\n')) result += '</dir>' return result if __name__ == '__main__': print '<structure>\n' + DirAsXML(os.getcwd()) + '\n</structure>' Personally, I'd recommend a much less verbose XML schema, putting names in attributes and getting rid of the <files> group: import os from xml.sax.saxutils import quoteattr as xml_quoteattr def DirAsLessXML(path): result = '<dir name=%s>\n' % xml_quoteattr(os.path.basename(path)) for item in os.listdir(path): itempath = os.path.join(path, item) if os.path.isdir(itempath): result += '\n'.join(' ' + line for line in DirAsLessXML(os.path.join(path, item)).split('\n')) elif os.path.isfile(itempath): result += ' <file name=%s />\n' % xml_quoteattr(item) result += '</dir>' return result if __name__ == '__main__': print '<structure>\n' + DirAsLessXML(os.getcwd()) + '\n</structure>' This gives an output like: <structure> <dir name="local"> <dir name=".hg"> <file name="00changelog.i" /> <file name="branch" /> <file name="branch.cache" /> <file name="dirstate" /> <file name="hgrc" /> <file name="requires" /> <dir name="store"> <file name="00changelog.i" /> etc. If os.walk() worked more like expat's callbacks, you'd have an easier time of it. A: Remove the two lines: for subdir in dirs: xmlOutput+=self.dirToXML(os.path.join(root,subdir)) you are recursing into the subdirectories; but that's redundant, because os.walk recurses itself. A: I was attempting to use os.walk, but I saw that it didn't work with the recursive tree structure that I wanted to create in xml. I modified my code as follows and it produce the result I need: def dirToXML(self,directory): curdir = os.getcwd() os.chdir(directory) xmlOutput="" pathName = string.split(directory, os.sep) xmlOutput+="<dir><name><![CDATA["+pathName.pop()+"]]></name>" for item in os.listdir(directory): if os.path.isfile(os.path.join(directory, item)): xmlOutput+="<file><name><![CDATA["+item+"]]></name></file>" else : xmlOutput+=self.dirToXML(os.path.join(directory,item)) xmlOutput+="</dir>" os.chdir(curdir) return xmlOutput
os.walk() python: xml representation of a directory structure, recursion
So I am trying to use os.walk() to generate an XML representation of a directory structure. I seem to be getting a ton of duplicates. It properly places directories within each other and files in the right place for the first portion of the xml file; however, after it does it correctly it then continues traversing incorrectly. I am not quite sure why.... Here is my code: def dirToXML(self,directory): curdir = os.getcwd() os.chdir(directory) xmlOutput="" tree = os.walk(directory) for root, dirs, files in tree: pathName = string.split(directory, os.sep) xmlOutput+="<dir><name><![CDATA["+pathName.pop()+"]]></name>" if len(files)>0: xmlOutput+=self.fileToXML(files) for subdir in dirs: xmlOutput+=self.dirToXML(os.path.join(root,subdir)) xmlOutput+="</dir>" os.chdir(curdir) return xmlOutput The fileToXML, simply parses out the list so no need to worry about that. The Directory Structure is simply: images/ images/testing.xml images/structure.xml images/Hellos images/Goodbyes images/Goodbyes/foo images/Goodbyes/bar images/Goodbyes/square and the resulting xml file became: <structure> <dir> <name>images</name> <files> <file> <name>structure.xml</name> </file> <file> <name>testing.xml</name> </file> </files> <dir> <name>Hellos</name> </dir> <dir> <name>Goodbyes</name> <dir> <name>foo</name> </dir> <dir> <name>bar</name> </dir> <dir> <name>square</name> </dir> </dir> <dir> <name>foo</name> </dir> <dir> <name>bar</name> </dir> <dir> <name>square</name> </dir> </dir> <dir> <name>Hellos</name> </dir> <dir> <name>Goodbyes</name> <dir> <name>foo</name> </dir> <dir> <name>bar</name> </dir> <dir> <name>square</name> </dir> </dir> <dir> <name>foo</name> </dir> <dir> <name>bar</name> </dir> <dir> <name>square</name> </dir> </structure> Any help would be much appreciated!
[ "I'd recommend against using os.walk(), since you have to do so much to massage its output. Instead, just use a recursive function that uses os.listdir(), os.path.join(), os.path.isdir(), etc.\nimport os\nfrom xml.sax.saxutils import escape as xml_escape\n\ndef DirAsXML(path):\n result = '<dir>\\n<name>%s</name>\\n' % xml_escape(os.path.basename(path))\n dirs = []\n files = []\n for item in os.listdir(path):\n itempath = os.path.join(path, item)\n if os.path.isdir(itempath):\n dirs.append(item)\n elif os.path.isfile(itempath):\n files.append(item)\n if files:\n result += ' <files>\\n' \\\n + '\\n'.join(' <file>\\n <name>%s</name>\\n </file>'\n % xml_escape(f) for f in files) + '\\n </files>\\n'\n if dirs:\n for d in dirs:\n x = DirAsXML(os.path.join(path, d))\n result += '\\n'.join(' ' + line for line in x.split('\\n'))\n result += '</dir>'\n return result\n\nif __name__ == '__main__':\n print '<structure>\\n' + DirAsXML(os.getcwd()) + '\\n</structure>'\n\nPersonally, I'd recommend a much less verbose XML schema, putting names in attributes and getting rid of the <files> group:\nimport os\nfrom xml.sax.saxutils import quoteattr as xml_quoteattr\n\ndef DirAsLessXML(path):\n result = '<dir name=%s>\\n' % xml_quoteattr(os.path.basename(path))\n for item in os.listdir(path):\n itempath = os.path.join(path, item)\n if os.path.isdir(itempath):\n result += '\\n'.join(' ' + line for line in \n DirAsLessXML(os.path.join(path, item)).split('\\n'))\n elif os.path.isfile(itempath):\n result += ' <file name=%s />\\n' % xml_quoteattr(item)\n result += '</dir>'\n return result\n\nif __name__ == '__main__':\n print '<structure>\\n' + DirAsLessXML(os.getcwd()) + '\\n</structure>'\n\nThis gives an output like:\n<structure>\n<dir name=\"local\">\n <dir name=\".hg\">\n <file name=\"00changelog.i\" />\n <file name=\"branch\" />\n <file name=\"branch.cache\" />\n <file name=\"dirstate\" />\n <file name=\"hgrc\" />\n <file name=\"requires\" />\n <dir name=\"store\">\n <file name=\"00changelog.i\" />\n\netc.\nIf os.walk() worked more like expat's callbacks, you'd have an easier time of it.\n", "Remove the two lines:\n for subdir in dirs:\n xmlOutput+=self.dirToXML(os.path.join(root,subdir))\n\nyou are recursing into the subdirectories; but that's redundant, because os.walk recurses itself.\n", "I was attempting to use os.walk, but I saw that it didn't work with the recursive tree structure that I wanted to create in xml. I modified my code as follows and it produce the result I need: \ndef dirToXML(self,directory):\n curdir = os.getcwd()\n os.chdir(directory)\n xmlOutput=\"\"\n\n pathName = string.split(directory, os.sep)\n xmlOutput+=\"<dir><name><![CDATA[\"+pathName.pop()+\"]]></name>\"\n for item in os.listdir(directory):\n if os.path.isfile(os.path.join(directory, item)):\n xmlOutput+=\"<file><name><![CDATA[\"+item+\"]]></name></file>\"\n else :\n xmlOutput+=self.dirToXML(os.path.join(directory,item))\n xmlOutput+=\"</dir>\"\n\n os.chdir(curdir)\n return xmlOutput \n\n" ]
[ 9, 6, 0 ]
[]
[]
[ "directory_structure", "os.walk", "python", "recursion", "xml" ]
stackoverflow_0002104997_directory_structure_os.walk_python_recursion_xml.txt
Q: OOP Design - In Python, is this a quality OO Design or an epic fail? In a system that accepts orders which have payments which have gateway transactions should the objects be like this: class Order(object): ... Inside init ... self.total_in_dollars = <Dollar Amount> self.is_paid = <Boolean Value> class Payment(object): ... Inside init ... self.order = order_instance self.amount = order.total_in_dollars class GatewayTransaction(object): ... Inside init ... self.payment = payment_instance self.amount = <Dollar Amount> It seems this would be the way to do it (obviously this is not real code with integer dollar amounts, etc but you get the picture). I did it this way because an order can exist without payment and a payment can exist before an actual PayPal transaction occurs. Does this lack in your opinion? Am I backwards in my thinking? OR, Should it be more like this: class GatewayTransaction(object): payment = payment_instance amount = <Dollar Amount> class Payment(object): amount = <Dollar Amount> gateway_transaction = gateway_transaction_instance class Order(object): amount_in_dollars = <Dollar Amount> payment = payment_instance A: You appear to be assigning what should obviously be instance variables as class variables, which is clearly a very wrong tack to take. IOW, the variables should be self.total_in_dollars (for instance of Order) and so forth, assigned in __init__, not class-variables, assigned in the class statement! Simply creating an instance of Order without a corresponding one of Payment is fine (and should obviously set is_paid to False), based just on the total (and presumably some numeric ID so customers &c can in the future refer to a specific order). Don't duplicate information needlessly! Since a Payment instance will always have a reference to an Order instance, it should not copy self.order.total_in_dollars over to self.amount -- better to have that information in one place (you can make a readonly property if you want to access it nicely); and even more so for the transaction instances. If an Order instance carried further metadata that influences how the corresponding Payment instance is created and behaves, that's OK, but strongly suggests making the creation of the Payment instance the job of a factory-method of class Object (which can then also keep track of already-generated instances and ensure there will never be more than one Payment instance for a single given Order instance). Edit: now that the OP has somewhat edited the A, I can confirm the opinion that the dependencies in the first version are roughly correct (except, again, the amount should not get copied all over the place) and those in the second versions are, prima facie, not correct (the presence of a mutual/circular dependency for example is always a design smell unless clearly and explicitly justified by special application needs -- even when the need to navigate back and forth exists, one of the two links should be a weak reference, at least). Edit: as the OP explicitly asks for more detail on the factory method I suggested, what I had in mind was something like this: import weakref class Payment(object): def __init__(self, order): self.order = weakref.proxy(order, self.ordergone) def ordergone(self, *_): self.order = None @property def amount(self): if self.order is None: return None else: return self.order.total_in_dollars class Order(object): def __init__(self, amount): self.total_in_dollars = amount self.is_paid = False self._payment = None @property def payment(self): if self._payment is None: self._payment = Payment(self) return self._payment A: Give the objects constructors that take the appropriate other object that you want it to refer to, then make the fields into properties that verify the type you assign to them. A: I would approach this differently - by writing the some code for dealing with Orders, Payments etc. This would clarify my design needs, e.g. it would turn out that Payment.amount could be greater that Order.total_in_dollars, because of some processing fees. But then, it could turn out that maybe those processing fees should be stored separately, or even they could/should have their own model. And yes, this is TDD.
OOP Design - In Python, is this a quality OO Design or an epic fail?
In a system that accepts orders which have payments which have gateway transactions should the objects be like this: class Order(object): ... Inside init ... self.total_in_dollars = <Dollar Amount> self.is_paid = <Boolean Value> class Payment(object): ... Inside init ... self.order = order_instance self.amount = order.total_in_dollars class GatewayTransaction(object): ... Inside init ... self.payment = payment_instance self.amount = <Dollar Amount> It seems this would be the way to do it (obviously this is not real code with integer dollar amounts, etc but you get the picture). I did it this way because an order can exist without payment and a payment can exist before an actual PayPal transaction occurs. Does this lack in your opinion? Am I backwards in my thinking? OR, Should it be more like this: class GatewayTransaction(object): payment = payment_instance amount = <Dollar Amount> class Payment(object): amount = <Dollar Amount> gateway_transaction = gateway_transaction_instance class Order(object): amount_in_dollars = <Dollar Amount> payment = payment_instance
[ "You appear to be assigning what should obviously be instance variables as class variables, which is clearly a very wrong tack to take. IOW, the variables should be self.total_in_dollars (for instance of Order) and so forth, assigned in __init__, not class-variables, assigned in the class statement!\nSimply creating an instance of Order without a corresponding one of Payment is fine (and should obviously set is_paid to False), based just on the total (and presumably some numeric ID so customers &c can in the future refer to a specific order).\nDon't duplicate information needlessly! Since a Payment instance will always have a reference to an Order instance, it should not copy self.order.total_in_dollars over to self.amount -- better to have that information in one place (you can make a readonly property if you want to access it nicely); and even more so for the transaction instances.\nIf an Order instance carried further metadata that influences how the corresponding Payment instance is created and behaves, that's OK, but strongly suggests making the creation of the Payment instance the job of a factory-method of class Object (which can then also keep track of already-generated instances and ensure there will never be more than one Payment instance for a single given Order instance).\nEdit: now that the OP has somewhat edited the A, I can confirm the opinion that the dependencies in the first version are roughly correct (except, again, the amount should not get copied all over the place) and those in the second versions are, prima facie, not correct (the presence of a mutual/circular dependency for example is always a design smell unless clearly and explicitly justified by special application needs -- even when the need to navigate back and forth exists, one of the two links should be a weak reference, at least).\nEdit: as the OP explicitly asks for more detail on the factory method I suggested, what I had in mind was something like this:\nimport weakref\n\nclass Payment(object):\n def __init__(self, order):\n self.order = weakref.proxy(order, self.ordergone)\n def ordergone(self, *_):\n self.order = None\n @property\n def amount(self):\n if self.order is None: return None\n else: return self.order.total_in_dollars\n\nclass Order(object):\n def __init__(self, amount):\n self.total_in_dollars = amount\n self.is_paid = False\n self._payment = None\n @property\n def payment(self):\n if self._payment is None:\n self._payment = Payment(self)\n return self._payment\n\n", "Give the objects constructors that take the appropriate other object that you want it to refer to, then make the fields into properties that verify the type you assign to them.\n", "I would approach this differently - by writing the some code for dealing with Orders, Payments etc. This would clarify my design needs, e.g. it would turn out that Payment.amount could be greater that Order.total_in_dollars, because of some processing fees. But then, it could turn out that maybe those processing fees should be stored separately, or even they could/should have their own model.\nAnd yes, this is TDD.\n" ]
[ 6, 2, 2 ]
[]
[]
[ "django", "oop", "python" ]
stackoverflow_0002105376_django_oop_python.txt
Q: Help creating model for Django app I'm trying to make a childcare administration app with Django but I've some problems with the payments code. Each kid has to pay monthly 10 times a year. These payments have some particularities: Some kids could pay a different amount of money depending on the economical situation of the parents. The amount of the payments could change over the year. The payments could be payed in different oportunities. Workshops and food are added to the total value of the payment(they're optional). I'm having problem in order to model this app. I was thinking about creating a kid model and a payment model: class Kid(models.Model): food = models.BooleanField() workshop = models.BooleanField() special_price = models.DecimalField(blank=True) class Payment(models.Model): kid = models.ForeignKey(Kid) date = models.DateField() amount = models.DecimalField()` Suppose I want to know in a given date how much moneya kid(the parents) have to pay. I don't know how to solve the changing values problem(the food and workshop values also could change over the year). Hope you understood me, Thanks. mF. A: No matter how your final models will look like, assuming that you will keep Payment model, you could add to it two fields: payment_date = model.DateField() already_paid = models.BooleanField() Then, to get overdue payments, you will be able to make a query: Payment.objects.filter(payment_date__lte=datetime.date.today(), already_paid=False) Having those Payment objects, you will be able to calculate the exact amount. A: I would make the payment calculated off of the attributes of the child so by updating the child the payment would change. The payment would not be a entry in the database until it had been paid, the payment would be calculated each time the user requests it. class Child(object): def __init__(self,income,paydate,meals=False,workshops=False): self.income = income self.paydate = paydate ... I would also have a pricing rules model that in combination with the child object would give you the payment amount. Again updating the PricingRules would change the payment. class PricingRules(object): def __init__(self,income_scale,paydate,meal_price,workshop_price,num_payments): ... I would avoid having a PricingRules object for each Child. There would then be the Payment object class Payment(object): def __init__(self,amount,date_paid): ... I've avoided showing any code that is specific to the ORM being used, I believe the design should stand on its own, and I also like to keep the possibility open of using the objects without the ORM. Using constructors is also my personal style, I like knowing that when an object is created from a class that it will be in a state that is well defined and stable. Without more detail regarding the business logic I have more questions than answer beyond this point.
Help creating model for Django app
I'm trying to make a childcare administration app with Django but I've some problems with the payments code. Each kid has to pay monthly 10 times a year. These payments have some particularities: Some kids could pay a different amount of money depending on the economical situation of the parents. The amount of the payments could change over the year. The payments could be payed in different oportunities. Workshops and food are added to the total value of the payment(they're optional). I'm having problem in order to model this app. I was thinking about creating a kid model and a payment model: class Kid(models.Model): food = models.BooleanField() workshop = models.BooleanField() special_price = models.DecimalField(blank=True) class Payment(models.Model): kid = models.ForeignKey(Kid) date = models.DateField() amount = models.DecimalField()` Suppose I want to know in a given date how much moneya kid(the parents) have to pay. I don't know how to solve the changing values problem(the food and workshop values also could change over the year). Hope you understood me, Thanks. mF.
[ "No matter how your final models will look like, assuming that you will keep Payment model, you could add to it two fields:\n payment_date = model.DateField()\n already_paid = models.BooleanField()\n\nThen, to get overdue payments, you will be able to make a query:\n Payment.objects.filter(payment_date__lte=datetime.date.today(), already_paid=False)\n\nHaving those Payment objects, you will be able to calculate the exact amount.\n", "I would make the payment calculated off of the attributes of the child so by updating the child the payment would change. The payment would not be a entry in the database until it had been paid, the payment would be calculated each time the user requests it.\nclass Child(object):\n def __init__(self,income,paydate,meals=False,workshops=False):\n self.income = income\n self.paydate = paydate\n ...\n\nI would also have a pricing rules model that in combination with the child object would give you the payment amount. Again updating the PricingRules would change the payment.\nclass PricingRules(object):\n def __init__(self,income_scale,paydate,meal_price,workshop_price,num_payments):\n ...\n\nI would avoid having a PricingRules object for each Child. There would then be the Payment object\nclass Payment(object):\n def __init__(self,amount,date_paid):\n ...\n\nI've avoided showing any code that is specific to the ORM being used, I believe the design should stand on its own, and I also like to keep the possibility open of using the objects without the ORM. Using constructors is also my personal style, I like knowing that when an object is created from a class that it will be in a state that is well defined and stable. Without more detail regarding the business logic I have more questions than answer beyond this point.\n" ]
[ 0, 0 ]
[]
[]
[ "django", "models", "python" ]
stackoverflow_0002104033_django_models_python.txt
Q: App Engine urlfetch is raising exceptions when i think it should not be I've written my first Python application with the App Engine APIs, it is intended to monitor a list of servers and notify me when one of them goes down, by sending a message to my iPhone using Prowl, or sending me an email, or both. Problem is, a few times a week it notifies me a server is down even when it clearly isn't. I've tested it with servers i know should be up virtually all the time like google.com or amazon.com but i get notifications with them too. I've got a copy of the code running at http://aeservmon.appspot.com, you can see that google.com was added Jan 3rd but is only listed as being up for 6 days. Below is the relevant section of the code from checkservers.py that does the checking with urlfetch, i assumed that the DownloadError exception would only be raised when the server couldn't be contacted, but perhaps I'm wrong. What am I missing? Full source on github under mrsteveman1/aeservmon (i can only post one link as a new user, sorry!) def testserver(self,server): if server.ssl: prefix = "https://" else: prefix = "http://" try: url = prefix + "%s" % server.serverdomain result = urlfetch.fetch(url, headers = {'Cache-Control' : 'max-age=30'} ) except DownloadError: logging.info('%s could not be reached' % server.serverdomain) self.serverisdown(server,000) return if result.status_code == 500: logging.info('%s returned 500' % server.serverdomain) self.serverisdown(server,result.status_code) else: logging.info('%s is up, status code %s' % (server.serverdomain,result.status_code)) self.serverisup(server,result.status_code) UPDATE Jan 21: Today I found one of the exceptions in the logs: ApplicationError: 5 Traceback (most recent call last): File "/base/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 507, in __call__ handler.get(*groups) File "/base/data/home/apps/aeservmon/1.339312180538855414/checkservers.py", line 149, in get self.testserver(server) File "/base/data/home/apps/aeservmon/1.339312180538855414/checkservers.py", line 106, in testserver result = urlfetch.fetch(url, headers = {'Cache-Control' : 'max-age=30'} ) File "/base/python_lib/versions/1/google/appengine/api/urlfetch.py", line 241, in fetch return rpc.get_result() File "/base/python_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 501, in get_result return self.__get_result_hook(self) File "/base/python_lib/versions/1/google/appengine/api/urlfetch.py", line 331, in _get_fetch_result raise DownloadError(str(err)) DownloadError: ApplicationError: 5 A: other folks have been reporting issues with the fetch service (e.g. http://code.google.com/p/googleappengine/issues/detail?id=1902&q=urlfetch&colspec=ID%20Type%20Status%20Priority%20Stars%20Owner%20Summary%20Log%20Component) can you print the exception, it may have more detail, e.g.: "DownloadError: ApplicationError: 2 something bad"
App Engine urlfetch is raising exceptions when i think it should not be
I've written my first Python application with the App Engine APIs, it is intended to monitor a list of servers and notify me when one of them goes down, by sending a message to my iPhone using Prowl, or sending me an email, or both. Problem is, a few times a week it notifies me a server is down even when it clearly isn't. I've tested it with servers i know should be up virtually all the time like google.com or amazon.com but i get notifications with them too. I've got a copy of the code running at http://aeservmon.appspot.com, you can see that google.com was added Jan 3rd but is only listed as being up for 6 days. Below is the relevant section of the code from checkservers.py that does the checking with urlfetch, i assumed that the DownloadError exception would only be raised when the server couldn't be contacted, but perhaps I'm wrong. What am I missing? Full source on github under mrsteveman1/aeservmon (i can only post one link as a new user, sorry!) def testserver(self,server): if server.ssl: prefix = "https://" else: prefix = "http://" try: url = prefix + "%s" % server.serverdomain result = urlfetch.fetch(url, headers = {'Cache-Control' : 'max-age=30'} ) except DownloadError: logging.info('%s could not be reached' % server.serverdomain) self.serverisdown(server,000) return if result.status_code == 500: logging.info('%s returned 500' % server.serverdomain) self.serverisdown(server,result.status_code) else: logging.info('%s is up, status code %s' % (server.serverdomain,result.status_code)) self.serverisup(server,result.status_code) UPDATE Jan 21: Today I found one of the exceptions in the logs: ApplicationError: 5 Traceback (most recent call last): File "/base/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 507, in __call__ handler.get(*groups) File "/base/data/home/apps/aeservmon/1.339312180538855414/checkservers.py", line 149, in get self.testserver(server) File "/base/data/home/apps/aeservmon/1.339312180538855414/checkservers.py", line 106, in testserver result = urlfetch.fetch(url, headers = {'Cache-Control' : 'max-age=30'} ) File "/base/python_lib/versions/1/google/appengine/api/urlfetch.py", line 241, in fetch return rpc.get_result() File "/base/python_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 501, in get_result return self.__get_result_hook(self) File "/base/python_lib/versions/1/google/appengine/api/urlfetch.py", line 331, in _get_fetch_result raise DownloadError(str(err)) DownloadError: ApplicationError: 5
[ "other folks have been reporting issues with the fetch service (e.g. http://code.google.com/p/googleappengine/issues/detail?id=1902&q=urlfetch&colspec=ID%20Type%20Status%20Priority%20Stars%20Owner%20Summary%20Log%20Component)\ncan you print the exception, it may have more detail, e.g.:\n\"DownloadError: ApplicationError: 2 something bad\"\n\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "monitoring", "python" ]
stackoverflow_0002105971_google_app_engine_monitoring_python.txt
Q: Do OO design principles apply to Python? It seems like many OO discussions use Java or C# as examples (e.g. Head First Design Patterns). Do these patterns apply equally to Python? Or if I follow the design patterns, will I just end up writing Java in Python (which apparently is a very bad thing)? A: The biggest differences are that Python is duck typed, meaning that you won't need to plan out class hierarchies in as much detail as in Java, and has first class functions. The strategy pattern, for example, becomes much simpler and more obvious when you can just pass a function in, rather than having to make interfaces, etc. just to simulate higher order functions. More generally, Python has syntactic sugar for a lot of common design patterns, such as the iterator and the aforementioned strategy. It might be useful to understand these patterns (I've read Head First and found it pretty useful), but think about Pythonic ways to implement them rather than just doing things the same way you would in Java. A: Python has it's own design idioms. Some of the standard patterns apply, others don't. Something like strategy or factories have in-language support that make them transparent. For instance, with first-class types anything can be a factory. There's no need for a factory type, you can use the class directly to construct any object you want. Basically, Python has its own design idioms that are somewhat different largely because it's so dynamic and has incredible introspection capabilities. Example: x = list my_list = x(range(0,5)) #creates a new list by invoking list's constructor By assigning the class-type to a callable object you can essentially remove any 'factory' types in your code. You are only left with callables that produce objects that should conform to some given conventions. Furthermore, there are design patterns in Python that just can't be represented in other statically-typed languages efficiently. Metaclasses and function decorators are good examples of this. A: It depends on the pattern. Some things are difficult to do in Python: Singleton is an example. You replace this pattern with another, such as, in the case of Singleton, Borg. It's not insane to use design patterns in Python-- the Iterator pattern, for instance, is integrated into the syntax. However, many things simply aren't done as OO- or pattern-heavy stuff. Python is made to be procedural or functional when it best suits the task, and OO too. Overall, I'd just say to use your best judgment. If it seems like using Design Pattern Alpha-Gamma is overkill and overcomplication, then it probably is. If it seems like the pattern is perfect for what you want, it probably is. A: Design patterns are little more than duct-tape to fix a languages deficiencies. A: Short answer: Yes; Python is an OO language. Slightly longer answer: Yes; you can design using OO principles and then implement in any language (even assembler). The benefit of using an OO language is that it incorporates support for many common OO concepts, so you don't risk unnecessary bugs having to simulate them by convention. Of course there will always be language-specific details with greater or lesser applicability; you asked about "design principles", which should be expressed above that level of detail. Long, verbose, boring answer: (The development of programming languages isn't a simple linear progression, but let me oversimplify and ignore that fact to make an observation that spans about 40 years' of programming experience.) There's always going to be a role for language features vs. design principles and patterns. At every stage, attentive practitioners have noticed: "Here's a problem we keep solving by hand in our current language(s)." "Here's a bug we keep writing in our current language(s)." "Here are some good practices we keep observing in our best programs." And so the next generation of language(s) tend provide support for observed good behavior, tend to incorporate concepts so they don't have to be done by convention/agreement (or accidentally broken by the same), and enforce practices that prevent easily avoidable errors. Regardless of how sophisticated, specialized, or generalized our tools, there are always programmers who "just turn the crank" and others who keep looking watching for how the "best and brightest" (in the mind of the beholder) use the tools. They then describe and promote those practices. Correctly defined (and whether called "style", "guidelines", "patterns", "principles", etc.), those practices end up forming "the next level" that we're always trying to reach, regardless of where we are currently standing. A: On further thought, some patterns, such as Borg, may be more specific to Python (though similar things can be said about other patterns and languages). The iterator pattern is also used in Python, albeit in a slightly different form. Duncan Booth has written an article on patterns in python. A: I'd say they apply to Python once you're already doing object-oriented programming with Python. Keep in mind that Python can do a lot more than OOP, and you should use common sense in choosing the appropriate paradigm for the job. If you decide that your program is best represented as a collection of objects, then sure, go ahead and use the design patterns, but don't be afraid to do something completely different if it's called for. A: yes, of course they apply. But as noted above, many patterns are built into the language, or made irrelevant by higher level features of the language. A: The use of Java or C# is probably due to the mainstream popularity of the language. But design principle and/or design patterns apply irrespective of the language you use. The implementation of the same design pattern in Python would obviously be different than in Java or C#. A: Yes, you can use plenty of design patterns in Python. A design pattern is just a repeatable implementation of a higher level task. The reason why Python & design patterns don't work the same as other languages is because Python includes most of the basic patterns built in. This means that patterns that emerge in Python are likely to be higher level design patterns instead of the menial tasks for which patterns are usually needed.
Do OO design principles apply to Python?
It seems like many OO discussions use Java or C# as examples (e.g. Head First Design Patterns). Do these patterns apply equally to Python? Or if I follow the design patterns, will I just end up writing Java in Python (which apparently is a very bad thing)?
[ "The biggest differences are that Python is duck typed, meaning that you won't need to plan out class hierarchies in as much detail as in Java, and has first class functions. The strategy pattern, for example, becomes much simpler and more obvious when you can just pass a function in, rather than having to make interfaces, etc. just to simulate higher order functions. More generally, Python has syntactic sugar for a lot of common design patterns, such as the iterator and the aforementioned strategy. It might be useful to understand these patterns (I've read Head First and found it pretty useful), but think about Pythonic ways to implement them rather than just doing things the same way you would in Java.\n", "Python has it's own design idioms. Some of the standard patterns apply, others don't. Something like strategy or factories have in-language support that make them transparent. \nFor instance, with first-class types anything can be a factory. There's no need for a factory type, you can use the class directly to construct any object you want.\nBasically, Python has its own design idioms that are somewhat different largely because it's so dynamic and has incredible introspection capabilities.\nExample:\nx = list\nmy_list = x(range(0,5)) #creates a new list by invoking list's constructor\n\nBy assigning the class-type to a callable object you can essentially remove any 'factory' types in your code. You are only left with callables that produce objects that should conform to some given conventions.\nFurthermore, there are design patterns in Python that just can't be represented in other statically-typed languages efficiently. Metaclasses and function decorators are good examples of this.\n", "It depends on the pattern. Some things are difficult to do in Python: Singleton is an example. You replace this pattern with another, such as, in the case of Singleton, Borg.\nIt's not insane to use design patterns in Python-- the Iterator pattern, for instance, is integrated into the syntax. However, many things simply aren't done as OO- or pattern-heavy stuff. Python is made to be procedural or functional when it best suits the task, and OO too.\nOverall, I'd just say to use your best judgment. If it seems like using Design Pattern Alpha-Gamma is overkill and overcomplication, then it probably is. If it seems like the pattern is perfect for what you want, it probably is.\n", "Design patterns are little more than duct-tape to fix a languages deficiencies.\n", "Short answer: Yes; Python is an OO language.\nSlightly longer answer: Yes; you can design using OO principles and then implement in any language (even assembler).\n\nThe benefit of using an OO language is that it incorporates support for many common OO concepts, so you don't risk unnecessary bugs having to simulate them by convention. Of course there will always be language-specific details with greater or lesser applicability; you asked about \"design principles\", which should be expressed above that level of detail.\n\nLong, verbose, boring answer: (The development of programming languages isn't a simple linear progression, but let me oversimplify and ignore that fact to make an observation that spans about 40 years' of programming experience.)\n\nThere's always going to be a role for language features vs. design principles and patterns. At every stage, attentive practitioners have noticed:\n\n\"Here's a problem we keep solving by hand in our current language(s).\"\n\n\"Here's a bug we keep writing in our current language(s).\"\n\n\"Here are some good practices we keep observing in our best programs.\"\n\n\nAnd so the next generation of language(s) tend provide support for observed good behavior, tend to incorporate concepts so they don't have to be done by convention/agreement (or accidentally broken by the same), and enforce practices that prevent easily avoidable errors.\nRegardless of how sophisticated, specialized, or generalized our tools, there are always programmers who \"just turn the crank\" and others who keep looking watching for how the \"best and brightest\" (in the mind of the beholder) use the tools. They then describe and promote those practices. Correctly defined (and whether called \"style\", \"guidelines\", \"patterns\", \"principles\", etc.), those practices end up forming \"the next level\" that we're always trying to reach, regardless of where we are currently standing.\n\n", "On further thought, some patterns, such as Borg, may be more specific to Python (though similar things can be said about other patterns and languages).\nThe iterator pattern is also used in Python, albeit in a slightly different form.\nDuncan Booth has written an article on patterns in python.\n", "I'd say they apply to Python once you're already doing object-oriented programming with Python. Keep in mind that Python can do a lot more than OOP, and you should use common sense in choosing the appropriate paradigm for the job. If you decide that your program is best represented as a collection of objects, then sure, go ahead and use the design patterns, but don't be afraid to do something completely different if it's called for.\n", "yes, of course they apply. But as noted above, many patterns are built into the language, or made irrelevant by higher level features of the language.\n", "The use of Java or C# is probably due to the mainstream popularity of the language. \nBut design principle and/or design patterns apply irrespective of the language you use. The implementation of the same design pattern in Python would obviously be different than in Java or C#. \n", "Yes, you can use plenty of design patterns in Python. A design pattern is just a repeatable implementation of a higher level task. The reason why Python & design patterns don't work the same as other languages is because Python includes most of the basic patterns built in. This means that patterns that emerge in Python are likely to be higher level design patterns instead of the menial tasks for which patterns are usually needed.\n" ]
[ 36, 13, 4, 4, 4, 3, 1, 1, 0, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0000546479_oop_python.txt
Q: Identifying numeric and array types in numpy Is there an existing function in numpy that will tell me if a value is either a numeric type or a numpy array? I'm writing some data-processing code which needs to handle numbers in several different representations (by "number" I mean any representation of a numeric quantity which can be manipulated using the standard arithmetic operators, +, -, *, /, **). Some examples of the behavior I'm looking for >>> is_numeric(5) True >>> is_numeric(123.345) True >>> is_numeric('123.345') False >>> is_numeric(decimal.Decimal('123.345')) True >>> is_numeric(True) False >>> is_numeric([1, 2, 3]) False >>> is_numeric([1, '2', 3]) False >>> a = numpy.array([1, 2.3, 4.5, 6.7, 8.9]) >>> is_numeric(a) True >>> is_numeric(a[0]) True >>> is_numeric(a[1]) True >>> is_numeric(numpy.array([numpy.array([1]), numpy.array([2])]) True >>> is_numeric(numpy.array(['1']) False If no such function exists, I know it shouldn't be hard to write one, something like isinstance(n, (int, float, decimal.Decimal, numpy.number, numpy.ndarray)) but are there other numeric types I should include in the list? A: As others have answered, there could be other numeric types besides the ones you mention. One approach would be to check explicitly for the capabilities you want, with something like # Python 2 def is_numeric(obj): attrs = ['__add__', '__sub__', '__mul__', '__div__', '__pow__'] return all(hasattr(obj, attr) for attr in attrs) # Python 3 def is_numeric(obj): attrs = ['__add__', '__sub__', '__mul__', '__truediv__', '__pow__'] return all(hasattr(obj, attr) for attr in attrs) This works for all your examples except the last one, numpy.array(['1']). That's because numpy.ndarray has the special methods for numeric operations but raises TypeError if you try to use them inappropriately with string or object arrays. You could add an explicit check for this like ... and not (isinstance(obj, ndarray) and obj.dtype.kind in 'OSU') This may be good enough. But... you can never be 100% sure that somebody won't define another type with the same behavior, so a more foolproof way is to actually try to do a calculation and catch the exception, something like def is_numeric_paranoid(obj): try: obj+obj, obj-obj, obj*obj, obj**obj, obj/obj except ZeroDivisionError: return True except Exception: return False else: return True but depending on how often you plan to call use it and with what arguments, this may not be practical (it can be potentially slow, e.g. with large arrays). A: Also, numpy has numpy.isreal and other similar functions (numpy.is + Tab should list them). They all have their fun corner cases but one of those could be useful. A: In general, the flexible, fast, and pythonic way to handle unknown types is to just perform some operation on them and catch an exception on invalid types. try: a = 5+'5' except TypeError: print "Oops" Seems to me that this approach is easier than special-casing out some function to determine absolute type certainty. A: Your is_numeric is ill-defined. See my comments to your question. Other numerical types could be: long, complex, fractions.Fraction, numpy.bool_, numpy.ubyte, ... operator.isNumberType() returns True for Python numbers and numpy.array. Since Python 2.6 you can use isinstance(d, numbers.Number) instead of deprecated operator.isNumberType(). Generally it is better to check the capabilities of the object (e.g., whether you can add an integer to it) and not its type. A: isinstance(numpy.int32(4), numbers.Number) returns False, so that doesn't quite work. operator.isNumberType() does work on all the variants of numpy numbers, however, including numpy.array([1]).
Identifying numeric and array types in numpy
Is there an existing function in numpy that will tell me if a value is either a numeric type or a numpy array? I'm writing some data-processing code which needs to handle numbers in several different representations (by "number" I mean any representation of a numeric quantity which can be manipulated using the standard arithmetic operators, +, -, *, /, **). Some examples of the behavior I'm looking for >>> is_numeric(5) True >>> is_numeric(123.345) True >>> is_numeric('123.345') False >>> is_numeric(decimal.Decimal('123.345')) True >>> is_numeric(True) False >>> is_numeric([1, 2, 3]) False >>> is_numeric([1, '2', 3]) False >>> a = numpy.array([1, 2.3, 4.5, 6.7, 8.9]) >>> is_numeric(a) True >>> is_numeric(a[0]) True >>> is_numeric(a[1]) True >>> is_numeric(numpy.array([numpy.array([1]), numpy.array([2])]) True >>> is_numeric(numpy.array(['1']) False If no such function exists, I know it shouldn't be hard to write one, something like isinstance(n, (int, float, decimal.Decimal, numpy.number, numpy.ndarray)) but are there other numeric types I should include in the list?
[ "As others have answered, there could be other numeric types besides the ones you mention.\nOne approach would be to check explicitly for the capabilities you want, with something like\n# Python 2\ndef is_numeric(obj):\n attrs = ['__add__', '__sub__', '__mul__', '__div__', '__pow__']\n return all(hasattr(obj, attr) for attr in attrs)\n\n# Python 3\ndef is_numeric(obj):\n attrs = ['__add__', '__sub__', '__mul__', '__truediv__', '__pow__']\n return all(hasattr(obj, attr) for attr in attrs)\n\nThis works for all your examples except the last one, numpy.array(['1']). That's because numpy.ndarray has the special methods for numeric operations but raises TypeError if you try to use them inappropriately with string or object arrays. You could add an explicit check for this like\n ... and not (isinstance(obj, ndarray) and obj.dtype.kind in 'OSU')\n\nThis may be good enough. \nBut... you can never be 100% sure that somebody won't define another type with the same behavior, so a more foolproof way is to actually try to do a calculation and catch the exception, something like\ndef is_numeric_paranoid(obj):\n try:\n obj+obj, obj-obj, obj*obj, obj**obj, obj/obj\n except ZeroDivisionError:\n return True\n except Exception:\n return False\n else:\n return True\n\nbut depending on how often you plan to call use it and with what arguments, this may not be practical (it can be potentially slow, e.g. with large arrays).\n", "Also, numpy has numpy.isreal and other similar functions (numpy.is + Tab should list them).\nThey all have their fun corner cases but one of those could be useful.\n", "In general, the flexible, fast, and pythonic way to handle unknown types is to just perform some operation on them and catch an exception on invalid types. \ntry:\n a = 5+'5'\nexcept TypeError:\n print \"Oops\"\n\nSeems to me that this approach is easier than special-casing out some function to determine absolute type certainty.\n", "Your is_numeric is ill-defined. See my comments to your question.\nOther numerical types could be: long, complex, fractions.Fraction, numpy.bool_, numpy.ubyte, ...\noperator.isNumberType() returns True for Python numbers and numpy.array.\nSince Python 2.6 you can use isinstance(d, numbers.Number) instead of deprecated operator.isNumberType().\nGenerally it is better to check the capabilities of the object (e.g., whether you can add an integer to it) and not its type.\n", "isinstance(numpy.int32(4), numbers.Number) returns False, so that doesn't quite work. operator.isNumberType() does work on all the variants of numpy numbers, however, including numpy.array([1]).\n" ]
[ 20, 7, 6, 1, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0000500328_numpy_python.txt
Q: Can you separate python projects logically into separate files/classes like in C#/Java? I'm looking to develop a project in python and all of the python I have done is minor scripting with no regard to classes or structure. I haven't seen much about this, so is this how larger python projects are done? Also, do things like "namespaces" and "projects" exist in this realm? As well as object oriented principles such as inheriting from other classes? A: Yes, you can, and you should! :) Here is a nice introduction to Python Modules (including packages). Correction: you probably should not put each single class into a separate file (like Java mandates and many C++ places do). The language is pretty lax about it as you can see in the linked tutorial, keep an open eye on other projects, use common sense, and do whatever makes sense to you (or whatever is being done in your team/project - unless it is very wrong). A: You can put code (classes, function defs, etc) into python modules (individual source files), which are then imported with import. Typically like functionality (like in the Python standard library) is contained within a single module. A: You can do that, but usually they are arranged a bit different. You can take a look to the source code of one python application. Here's one: "JaikuEngine" which powers the website http://www.jaiku.com/ A: Yes. You can put python classes into separate files, use namespaces for scoping, then place this into Modules which can be loaded from other scripts.
Can you separate python projects logically into separate files/classes like in C#/Java?
I'm looking to develop a project in python and all of the python I have done is minor scripting with no regard to classes or structure. I haven't seen much about this, so is this how larger python projects are done? Also, do things like "namespaces" and "projects" exist in this realm? As well as object oriented principles such as inheriting from other classes?
[ "Yes, you can, and you should! :)\nHere is a nice introduction to Python Modules (including packages).\n\nCorrection: you probably should not put each single class into a separate file (like Java mandates and many C++ places do). The language is pretty lax about it as you can see in the linked tutorial, keep an open eye on other projects, use common sense, and do whatever makes sense to you (or whatever is being done in your team/project - unless it is very wrong). \n", "You can put code (classes, function defs, etc) into python modules (individual source files), which are then imported with import. Typically like functionality (like in the Python standard library) is contained within a single module.\n", "You can do that, but usually they are arranged a bit different.\nYou can take a look to the source code of one python application. \nHere's one: \"JaikuEngine\" which powers the website http://www.jaiku.com/\n", "Yes. \nYou can put python classes into separate files, use namespaces for scoping, then place this into Modules which can be loaded from other scripts.\n" ]
[ 3, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002106271_python.txt
Q: Where (at which point in the code) does pyAMF client accept SSL certificate? I've set up a server listening on an SSL port. I am able to connect to it and with proper credentials I am able to access the services (echo service in the example below) The code below works fine, but I don't understand at which point the client accepts the certificate Server: import os.path import logging import cherrypy from pyamf.remoting.gateway.wsgi import WSGIGateway logging.basicConfig( level=logging.DEBUG, format='%(asctime)s %(levelname)-5.5s [%(name)s] %(message)s' ) def auth(username, password): users = {"user": "pwd"} if (users.has_key(username) and users[username] == password): return True return False def echo(data): return data class Root(object): @cherrypy.expose def index(self): return "This is your main website" gateway = WSGIGateway({'myservice.echo': echo,}, logger=logging, debug=True, authenticator=auth) localDir = os.path.abspath(os.path.dirname(__file__)) CA = os.path.join(localDir, 'new.cert.cert') KEY = os.path.join(localDir, 'new.cert.key') global_conf = {'global': {'server.socket_port': 8443, 'environment': 'production', 'log.screen': True, 'server.ssl_certificate': CA, 'server.ssl_private_key': KEY}} cherrypy.tree.graft(gateway, '/gateway/') cherrypy.quickstart(Root(), config=global_conf) Client: import logging from pyamf.remoting.client import RemotingService logging.basicConfig( level=logging.DEBUG, format='%(asctime)s %(levelname)-5.5s [%(name)s] %(message)s' ) client = RemotingService('https://localhost:8443/gateway', logger=logging) client.setCredentials('user', 'pwd') service = client.getService('myservice') print service.echo('Echo this') Now, when I run this, it runs OK, the client log is below: 2010-01-18 00:50:56,323 INFO [root] Connecting to https://localhost:8443/gateway 2010-01-18 00:50:56,323 DEBUG [root] Referer: None 2010-01-18 00:50:56,323 DEBUG [root] User-Agent: PyAMF/0.5.1 2010-01-18 00:50:56,323 DEBUG [root] Adding request myservice.echo('Echo this',) 2010-01-18 00:50:56,324 DEBUG [root] Executing single request: /1 2010-01-18 00:50:56,324 DEBUG [root] AMF version: 0 2010-01-18 00:50:56,324 DEBUG [root] Client type: 0 2010-01-18 00:50:56,326 DEBUG [root] Sending POST request to /gateway 2010-01-18 00:50:56,412 DEBUG [root] Waiting for response... 2010-01-18 00:50:56,467 DEBUG [root] Got response status: 200 2010-01-18 00:50:56,467 DEBUG [root] Content-Type: application/x-amf 2010-01-18 00:50:56,467 DEBUG [root] Content-Length: 41 2010-01-18 00:50:56,467 DEBUG [root] Server: PyAMF/0.5.1 Python/2.5.2 2010-01-18 00:50:56,467 DEBUG [root] Read 41 bytes for the response 2010-01-18 00:50:56,468 DEBUG [root] Response: <Envelope amfVersion=0 clientType=0> (u'/1', <Response status=/onResult>u'Echo this'</Response>) </Envelope> 2010-01-18 00:50:56,468 DEBUG [root] Removing request: /1 Echo this The line 2010-01-18 00:50:56,467 DEBUG [root] Read 41 bytes for the response looks suspicious, since the response is too short (the certificate is ~1K) and I'd expect the cert transfer to be in the debug log. Question: At which point does the client accept the certificate? Where would it be stored by default? Which config parameter sets the default location? A: PyAMF uses httplib under the hood to power the remoting requests. When connecting via https://, httplib.HTTPSConnection is used as the connection attribute to the RemotingService. It states in the docs that (in reference to HTTPSConnection): Note: This does not do any certificate verification So, in answer to your question certificates are basically ignored, even if you supply key_file/cert_file arguments to connection. The actual ignoring is done when the connect method is called - when the request is actually made to the gateway .. [root] Sending POST request to /gateway The Read 41 bytes for the response is the unencrypted http response length. This answer may not contain all the info you require but should go some way to explaining the behaviour you're seeing.
Where (at which point in the code) does pyAMF client accept SSL certificate?
I've set up a server listening on an SSL port. I am able to connect to it and with proper credentials I am able to access the services (echo service in the example below) The code below works fine, but I don't understand at which point the client accepts the certificate Server: import os.path import logging import cherrypy from pyamf.remoting.gateway.wsgi import WSGIGateway logging.basicConfig( level=logging.DEBUG, format='%(asctime)s %(levelname)-5.5s [%(name)s] %(message)s' ) def auth(username, password): users = {"user": "pwd"} if (users.has_key(username) and users[username] == password): return True return False def echo(data): return data class Root(object): @cherrypy.expose def index(self): return "This is your main website" gateway = WSGIGateway({'myservice.echo': echo,}, logger=logging, debug=True, authenticator=auth) localDir = os.path.abspath(os.path.dirname(__file__)) CA = os.path.join(localDir, 'new.cert.cert') KEY = os.path.join(localDir, 'new.cert.key') global_conf = {'global': {'server.socket_port': 8443, 'environment': 'production', 'log.screen': True, 'server.ssl_certificate': CA, 'server.ssl_private_key': KEY}} cherrypy.tree.graft(gateway, '/gateway/') cherrypy.quickstart(Root(), config=global_conf) Client: import logging from pyamf.remoting.client import RemotingService logging.basicConfig( level=logging.DEBUG, format='%(asctime)s %(levelname)-5.5s [%(name)s] %(message)s' ) client = RemotingService('https://localhost:8443/gateway', logger=logging) client.setCredentials('user', 'pwd') service = client.getService('myservice') print service.echo('Echo this') Now, when I run this, it runs OK, the client log is below: 2010-01-18 00:50:56,323 INFO [root] Connecting to https://localhost:8443/gateway 2010-01-18 00:50:56,323 DEBUG [root] Referer: None 2010-01-18 00:50:56,323 DEBUG [root] User-Agent: PyAMF/0.5.1 2010-01-18 00:50:56,323 DEBUG [root] Adding request myservice.echo('Echo this',) 2010-01-18 00:50:56,324 DEBUG [root] Executing single request: /1 2010-01-18 00:50:56,324 DEBUG [root] AMF version: 0 2010-01-18 00:50:56,324 DEBUG [root] Client type: 0 2010-01-18 00:50:56,326 DEBUG [root] Sending POST request to /gateway 2010-01-18 00:50:56,412 DEBUG [root] Waiting for response... 2010-01-18 00:50:56,467 DEBUG [root] Got response status: 200 2010-01-18 00:50:56,467 DEBUG [root] Content-Type: application/x-amf 2010-01-18 00:50:56,467 DEBUG [root] Content-Length: 41 2010-01-18 00:50:56,467 DEBUG [root] Server: PyAMF/0.5.1 Python/2.5.2 2010-01-18 00:50:56,467 DEBUG [root] Read 41 bytes for the response 2010-01-18 00:50:56,468 DEBUG [root] Response: <Envelope amfVersion=0 clientType=0> (u'/1', <Response status=/onResult>u'Echo this'</Response>) </Envelope> 2010-01-18 00:50:56,468 DEBUG [root] Removing request: /1 Echo this The line 2010-01-18 00:50:56,467 DEBUG [root] Read 41 bytes for the response looks suspicious, since the response is too short (the certificate is ~1K) and I'd expect the cert transfer to be in the debug log. Question: At which point does the client accept the certificate? Where would it be stored by default? Which config parameter sets the default location?
[ "PyAMF uses httplib under the hood to power the remoting requests. When connecting via https://, httplib.HTTPSConnection is used as the connection attribute to the RemotingService.\nIt states in the docs that (in reference to HTTPSConnection):\n\nNote: This does not do any certificate verification\n\nSo, in answer to your question certificates are basically ignored, even if you supply key_file/cert_file arguments to connection.\nThe actual ignoring is done when the connect method is called - when the request is actually made to the gateway ..\n\n[root] Sending POST request to /gateway\n\nThe Read 41 bytes for the response is the unencrypted http response length.\nThis answer may not contain all the info you require but should go some way to explaining the behaviour you're seeing.\n" ]
[ 2 ]
[]
[]
[ "certificate", "cherrypy", "pyamf", "python", "ssl" ]
stackoverflow_0002084292_certificate_cherrypy_pyamf_python_ssl.txt
Q: Passing C function pointers between two python modules I'm writing an application working with plugins. There are two types of plugins: Engine and Model. Engine objects have an update() method that call the Model.velocity() method. For performance reasons these methods are allowed to be written in C. This means that sometimes they will be written in Python and sometimes written in C. The problem is that this forces to do an expensive Python function call of Model.velocity() in Engine.update() (and also reacquiring the GIL). I thought about adding something like Model.get_velocity_c_func() to the API, that would allow Model implementations to return a pointer to the C version of their velocity() method if available, making possible for Engine to do a faster C function call. What data type should I use to pass the function pointer ? And is this a good design at all, maybe there is an easier way ? A: The CObject (PyCOBject) data type exists for this purpose. It holds a void*, but you can store any data you wish. You do have to be careful not to pass the wrong CObject to the wrong functions, as some other library's CObjects will look just like your own. If you want more type security, you could easily roll your own PyType for this; all it has to do, after all, is contain a pointer of the right type.
Passing C function pointers between two python modules
I'm writing an application working with plugins. There are two types of plugins: Engine and Model. Engine objects have an update() method that call the Model.velocity() method. For performance reasons these methods are allowed to be written in C. This means that sometimes they will be written in Python and sometimes written in C. The problem is that this forces to do an expensive Python function call of Model.velocity() in Engine.update() (and also reacquiring the GIL). I thought about adding something like Model.get_velocity_c_func() to the API, that would allow Model implementations to return a pointer to the C version of their velocity() method if available, making possible for Engine to do a faster C function call. What data type should I use to pass the function pointer ? And is this a good design at all, maybe there is an easier way ?
[ "The CObject (PyCOBject) data type exists for this purpose. It holds a void*, but you can store any data you wish. You do have to be careful not to pass the wrong CObject to the wrong functions, as some other library's CObjects will look just like your own.\nIf you want more type security, you could easily roll your own PyType for this; all it has to do, after all, is contain a pointer of the right type.\n" ]
[ 1 ]
[]
[]
[ "c", "function_pointers", "python" ]
stackoverflow_0002106324_c_function_pointers_python.txt
Q: CherryPy changes my response code In my python application using mod_wsgi and cherrypy ontop of Apache my response code get changed to a 500 from a 403. I am explicitly setting this to 403. i.e. cherrypy.response.status = 403 I do not understand where and why the response code that the client receives is 500. Does anyone have any experience with this problem> A: The HTTP 500 error is used for internal server errors. Something in the server or your application is likely throwing an exception, so no matter what you set the response code to be before this, CherryPy will send a 500 back. You can look into whatever tools CherryPy includes for debugging or logging (I'm not familiar with them). You can also set breakpoints into your code and continue stepping into the CherryPy internals until it hits the error case.
CherryPy changes my response code
In my python application using mod_wsgi and cherrypy ontop of Apache my response code get changed to a 500 from a 403. I am explicitly setting this to 403. i.e. cherrypy.response.status = 403 I do not understand where and why the response code that the client receives is 500. Does anyone have any experience with this problem>
[ "The HTTP 500 error is used for internal server errors. Something in the server or your application is likely throwing an exception, so no matter what you set the response code to be before this, CherryPy will send a 500 back.\nYou can look into whatever tools CherryPy includes for debugging or logging (I'm not familiar with them). You can also set breakpoints into your code and continue stepping into the CherryPy internals until it hits the error case.\n" ]
[ 1 ]
[]
[]
[ "apache", "cherrypy", "mod_wsgi", "python" ]
stackoverflow_0002106377_apache_cherrypy_mod_wsgi_python.txt
Q: pydev issue with gobject It seems that Pydev (1.5.4) on Eclipse (3.5.1) with Python 2.6 isn't able to correctly cross-reference the package gobject. Putting import gobject works OK but any more than that (e.g. class X(gobject.GObject) causes Pydev to report "unresolved reference" errors. What could be the problem? Note that every other package I use doesn't trigger this error. A: The issue is related to this limitation of PyDev: I have a library installed and Pydev does not find it Well, problems have been reported on Mac and Linux, and the main reason seems to be symlinks. Pydev will only find extensions that are 'really' below the python install directory. This happens because the 'less common denominator', which in this case is windows, does not have symlinks. A workaround to this problem includes manually adding the given folder installation to the pythonpath or changing the installation of the package to be under the site-packages folder. To adjust for this limitation, find the absolute path to the library and update the libraries associated with the interpreter for Pydev.
pydev issue with gobject
It seems that Pydev (1.5.4) on Eclipse (3.5.1) with Python 2.6 isn't able to correctly cross-reference the package gobject. Putting import gobject works OK but any more than that (e.g. class X(gobject.GObject) causes Pydev to report "unresolved reference" errors. What could be the problem? Note that every other package I use doesn't trigger this error.
[ "The issue is related to this limitation of PyDev:\n\nI have a library installed and Pydev\n does not find it\nWell, problems have been reported on\n Mac and Linux, and the main reason\n seems to be symlinks. Pydev will only\n find extensions that are 'really'\n below the python install directory.\n This happens because the 'less common\n denominator', which in this case is\n windows, does not have symlinks. A\n workaround to this problem includes\n manually adding the given folder\n installation to the pythonpath or\n changing the installation of the\n package to be under the site-packages\n folder.\n\nTo adjust for this limitation, find the absolute path to the library and update the libraries associated with the interpreter for Pydev.\n" ]
[ 1 ]
[]
[]
[ "gobject", "linux", "pydev", "python" ]
stackoverflow_0002106349_gobject_linux_pydev_python.txt
Q: What is the purpose of pinax's groups? I viewed the DjangoCon 2009 talks about pinax by James Tauber and pydanny and heared about pinax's groups. But I don't get the actual usecases they describe, even after reading the documentation. So what is the real purpose of groups and what advantages do I get in using them? It would be nice if you could provide a simple usecase to let me understand groups better. A: Say you have a wiki app or a todo app and you don't want your site just to have one wiki and one todo list. Say that you want your site to have teams where each team gets its own wiki and todo list. The groups app in Pinax provides the base for you to built your teams app on. It helps you create a new model (Team in this example) with membership management and plug in the wiki and todo apps. The groups app does this in a way that means that the author of the wiki app or todo app doesn't need to know about your teams app, they just need to know about Pinax's group app. Apps like the wiki app or todo app are hence referred to as being "group-aware". So any time you have groups of members on your site (examples are interest groups, teams, projects, guilds, tribes, committees, circles, departments, clubs) and you have content apps (examples are wikis, tasks, forums, bookmarks) whose content is scoped to each group, the Pinax groups functionality lets you do this in a way that decouples the development of the content app from the group app. Hope this helps!
What is the purpose of pinax's groups?
I viewed the DjangoCon 2009 talks about pinax by James Tauber and pydanny and heared about pinax's groups. But I don't get the actual usecases they describe, even after reading the documentation. So what is the real purpose of groups and what advantages do I get in using them? It would be nice if you could provide a simple usecase to let me understand groups better.
[ "Say you have a wiki app or a todo app and you don't want your site just to have one wiki and one todo list. Say that you want your site to have teams where each team gets its own wiki and todo list.\nThe groups app in Pinax provides the base for you to built your teams app on. It helps you create a new model (Team in this example) with membership management and plug in the wiki and todo apps.\nThe groups app does this in a way that means that the author of the wiki app or todo app doesn't need to know about your teams app, they just need to know about Pinax's group app. Apps like the wiki app or todo app are hence referred to as being \"group-aware\".\nSo any time you have groups of members on your site (examples are interest groups, teams, projects, guilds, tribes, committees, circles, departments, clubs) and you have content apps (examples are wikis, tasks, forums, bookmarks) whose content is scoped to each group, the Pinax groups functionality lets you do this in a way that decouples the development of the content app from the group app.\nHope this helps!\n" ]
[ 6 ]
[]
[]
[ "django", "pinax", "python" ]
stackoverflow_0002098190_django_pinax_python.txt
Q: using django and twisted together 1)I want to devlop a website that has forums and chat.The chat and forums are linked in some way.Meaning for each thread the users can chat in the chat room for that thread or can post a reply to the forum. I was thinking of using django for forums and twisted for chat thing.Can i combine the two? The chat application devloped using twisted is linked to the forum. 2)If i use twisted and django what kind of web host shold i use while putting by website on web ?Shold i use a VPS? Or can i get a host that supports both? A: I would not combine the two per se; calls into Django would happen synchronously which means that Twisted's event loop would be blocked. Better to treat the Twisted process as a standalone app using Django and to have a classic web server handle the Django app. You are not likely to find a shared host that will allow you to run a Twisted app, so I would go the VPS route. A: I have a project going that might be just what you are looking for (at least to get started). It is called Hotdot: http://github.com/clemesha/hotdot . Also, I wrote up more details about this topic here: http://clemesha.org/blog/2009/dec/17/realtime-web-apps-python-django-orbited-twisted/ A: If forum application needs to get something from chat application, it's simplier to make forum application communicate with chat application with plain HTTP requests and to make them run separately.
using django and twisted together
1)I want to devlop a website that has forums and chat.The chat and forums are linked in some way.Meaning for each thread the users can chat in the chat room for that thread or can post a reply to the forum. I was thinking of using django for forums and twisted for chat thing.Can i combine the two? The chat application devloped using twisted is linked to the forum. 2)If i use twisted and django what kind of web host shold i use while putting by website on web ?Shold i use a VPS? Or can i get a host that supports both?
[ "I would not combine the two per se; calls into Django would happen synchronously which means that Twisted's event loop would be blocked. Better to treat the Twisted process as a standalone app using Django and to have a classic web server handle the Django app.\nYou are not likely to find a shared host that will allow you to run a Twisted app, so I would go the VPS route.\n", "I have a project going that might be just what you are looking for (at least to get started). It is called Hotdot: http://github.com/clemesha/hotdot . \nAlso, I wrote up more details about this topic here: http://clemesha.org/blog/2009/dec/17/realtime-web-apps-python-django-orbited-twisted/\n", "If forum application needs to get something from chat application, it's simplier to make forum application communicate with chat application with plain HTTP requests and to make them run separately.\n" ]
[ 13, 10, 1 ]
[]
[]
[ "chat", "django", "forums", "python", "twisted" ]
stackoverflow_0002099189_chat_django_forums_python_twisted.txt
Q: how can i active my account,i send email to me use django-registration Thank you for registering an account at example.com. To activate your registration, please visit the following page: http://example.com/activate/d5544f645c80f8a6c9af934c03a2ee2d7902dc1f/ This page will expire in 7 days. example.com????? i click the url,but not active my account. why???? A: Googling produces this: http://codespatter.com/2009/01/05/django-settings-site-domain-examplecom/ You can change it through the Django admin interface, phpMyAdmin, or however you feel comfortable. It’s in the django_site table. When setting SITE_ID in settings.py it is the ID in this table. So it looks like you need to go into that table and change example.com to 127.0.0.1:8000. A: Are you running this in your local or remote environment? Of course you can't activate it because the activation URL points to example.com, which is used as an example. You need to point it to your own domain.
how can i active my account,i send email to me use django-registration
Thank you for registering an account at example.com. To activate your registration, please visit the following page: http://example.com/activate/d5544f645c80f8a6c9af934c03a2ee2d7902dc1f/ This page will expire in 7 days. example.com????? i click the url,but not active my account. why????
[ "Googling produces this: http://codespatter.com/2009/01/05/django-settings-site-domain-examplecom/\n\nYou can change it through the Django admin interface, phpMyAdmin, or however you feel comfortable. It’s in the django_site table. When setting SITE_ID in settings.py it is the ID in this table.\n\nSo it looks like you need to go into that table and change example.com to 127.0.0.1:8000.\n", "Are you running this in your local or remote environment? Of course you can't activate it because the activation URL points to example.com, which is used as an example. You need to point it to your own domain.\n" ]
[ 2, 0 ]
[]
[]
[ "django", "python", "registration" ]
stackoverflow_0002106559_django_python_registration.txt
Q: python, regex to find anchor link html I need a regex in python to find a links html in a larger set of html. so if I have: <ul class="something"> <li id="li_id"> <a href="#" title="myurl">URL Text</a> </li> </ul> I would get back: <a href="#" title="myurl">URL Text</a> I'd like to do it with a regex and not beautifulsoup or something similar to that. Does anyone have a snippet laying around I could use for this? Thanks A: Soup is good for you: >>> from BeautifulSoup import BeautifulSoup >>> soup = BeautifulSoup('''<ul class="something"> ... <li id="li_id"> ... <a href="#" title="myurl">URL Text</a> ... </li> ... </ul>''') There are many arguments you can pass to the findAll method; more here. The one line below will get you started by returning a list of all links matching some conditions. >>> soup.findAll(href='#', title='myurl') [<a href="#" title="myurl">URL Text</a>] Edit: based on OP's comment, added info included: So let's say you're interested in only tags within list elements of a certain class <li class="li_class">. You could do something like this: >>> soup = BeautifulSoup('''<li class="li_class"> <a href="#" title="myurl">URL Text</a> <a href="#" title="myurl2">URL Text2</a></li><li class="foo"> <a href="#" title="myurl3">URL Text3</a></li>''') # just some sample html >>> for elem in soup.findAll("li", "li_class"): ... pprint(elem.findAll('a')) # requires `from pprint import pprint` ... [<a href="#" title="myurl">URL Text</a>, <a href="#" title="myurl2">URL Text2</a>] Soup recipe: Download the one file required. Place dl'd file in site-packages dir or similar. Enjoy your soup. A: you really shouldn't use regexes to parse html.. ever. try beautifulsoup or lxml. but... you asked. so a quick and naive version might look like this: import re html = """ <ul class="something"> <li id="li_id"> <a href="#" title="myurl">URL Text</a> </li> </ul> """ m = re.search('(<a .*>)', html) if m: print m.group(1) I can think of a lot of ways this would break. A: you can try this since your requirement is simple. No need BeautifulSoup or regex >>> s=""" ... <ul class="something"> ... <li id="li_id"> ... <a href="#" title="myurl">URL Text</a> ... </li> ... </ul> ... """ >>> for item in s.split("</a>"): ... if "<a href=" in item : ... print item [ item.find("<a href=") : ] + "</a>" ... <a href="#" title="myurl">URL Text</a> You can include a check of '<li class="li_class">' in the if statement as desired.
python, regex to find anchor link html
I need a regex in python to find a links html in a larger set of html. so if I have: <ul class="something"> <li id="li_id"> <a href="#" title="myurl">URL Text</a> </li> </ul> I would get back: <a href="#" title="myurl">URL Text</a> I'd like to do it with a regex and not beautifulsoup or something similar to that. Does anyone have a snippet laying around I could use for this? Thanks
[ "Soup is good for you:\n>>> from BeautifulSoup import BeautifulSoup\n>>> soup = BeautifulSoup('''<ul class=\"something\">\n... <li id=\"li_id\">\n... <a href=\"#\" title=\"myurl\">URL Text</a>\n... </li>\n... </ul>''')\n\nThere are many arguments you can pass to the findAll method; more here. The one line below will get you started by returning a list of all links matching some conditions.\n>>> soup.findAll(href='#', title='myurl')\n[<a href=\"#\" title=\"myurl\">URL Text</a>]\n\nEdit: based on OP's comment, added info included:\nSo let's say you're interested in only tags within list elements of a certain class <li class=\"li_class\">. You could do something like this:\n>>> soup = BeautifulSoup('''<li class=\"li_class\">\n <a href=\"#\" title=\"myurl\">URL Text</a>\n <a href=\"#\" title=\"myurl2\">URL Text2</a></li><li class=\"foo\">\n <a href=\"#\" title=\"myurl3\">URL Text3</a></li>''') # just some sample html\n\n>>> for elem in soup.findAll(\"li\", \"li_class\"):\n... pprint(elem.findAll('a')) # requires `from pprint import pprint`\n... \n[<a href=\"#\" title=\"myurl\">URL Text</a>,\n <a href=\"#\" title=\"myurl2\">URL Text2</a>]\n\nSoup recipe:\n\nDownload the one file required.\nPlace dl'd file in site-packages dir or similar.\nEnjoy your soup.\n\n", "you really shouldn't use regexes to parse html.. ever. \ntry beautifulsoup or lxml.\nbut... you asked.\nso a quick and naive version might look like this:\nimport re\n\nhtml = \"\"\"\n<ul class=\"something\">\n<li id=\"li_id\">\n<a href=\"#\" title=\"myurl\">URL Text</a>\n</li>\n</ul>\n\"\"\"\n\nm = re.search('(<a .*>)', html)\nif m:\n print m.group(1)\n\nI can think of a lot of ways this would break.\n", "you can try this since your requirement is simple. No need BeautifulSoup or regex\n>>> s=\"\"\"\n... <ul class=\"something\">\n... <li id=\"li_id\">\n... <a href=\"#\" title=\"myurl\">URL Text</a>\n... </li>\n... </ul>\n... \"\"\"\n>>> for item in s.split(\"</a>\"):\n... if \"<a href=\" in item :\n... print item [ item.find(\"<a href=\") : ] + \"</a>\"\n...\n<a href=\"#\" title=\"myurl\">URL Text</a>\n\nYou can include a check of '<li class=\"li_class\">' in the if statement as desired.\n" ]
[ 4, 3, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002106597_python_regex.txt
Q: Python win32 service I am fairly new to python, and have no experience with writing services for windows. I have tried to hack together a windows service based on afew tutorials i have found out there. I need this service to constantly monitor a directory for changes and when it sees a change it runs a script. Here is what i have so far: import win32service import win32serviceutil import time class aservice(win32serviceutil.ServiceFramework): _svc_name_ = "aservice" _svc_display_name_ = "aservice - It Does nothing" def __init__(self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.isAlive = True def SvcDoRun(self): import servicemanager while self.isAlive: # This is where i am trying to run my code...is that right? self.main() #servicemanager.LogInfoMsg("aservice - is alive and well") #time.sleep(5) #servicemanager.LogInfoMsg("aservice - Stopped") def SvcStop(self): import servicemanager servicemanager.LogInfoMsg("aservice - Recieved stop signal") self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) self.isAlive = False #this will make SvcDoRun() break the while loop at the next iteration. # This code monitors a directory for changes and calls a script when there is a change # At the moment, it creates a log file instead of calling the script def main(self): import os import win32file import win32con ACTIONS = { 1: "Created", 2: "Deleted", 3: "Updated", 4: "Renamed from something", 5: "Ranamed to something" } FILE_LIST_DIRECTORY = 0x0001 path_to_watch = "folder" hDir = win32file.CreateFile ( path_to_watch, FILE_LIST_DIRECTORY, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, win32con.FILE_FLAG_BACKUP_SEMANTICS, None ) while 1: results = win32file.ReadDirectoryChangesW ( hDir, 1024, True, win32con.FILE_NOTIFY_CHANGE_FILE_NAME | win32con.FILE_NOTIFY_CHANGE_DIR_NAME | win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES | win32con.FILE_NOTIFY_CHANGE_SIZE | win32con.FILE_NOTIFY_CHANGE_LAST_WRITE | win32con.FILE_NOTIFY_CHANGE_SECURITY, None, None ) for action, file in results: #import script log = open ('log.txt', 'w') full_filename = os.path.join(path_to_watch) log.write(full_filename + ACTIONS.get(action, "Unknown")) log.close() if __name__ == '__main__': win32serviceutil.HandleCommandLine(aservice) Any ideas on what i am doing wrong? EDIT: Here is the event log error i am getting for it. Event Type: Error Event Source: aservice Event Category: None Event ID: 3 Date: 21/01/2010 Time: 11:27:43 AM User: N/A Computer: Description: The instance's SvcRun() method failed Traceback (most recent call last): File "C:\Python25\Lib\site-packages\win32\lib\win32serviceutil.py", line 806, in SvcRun self.SvcDoRun() File "D:\TEST\simpleservice2.py", line 35, in SvcDoRun self.main() File "D:\TEST\simpleservice2.py", line 72, in main None error: (2, 'CreateFile', 'The system cannot find the file specified.') %2: %3 A: One thing to keep in mind with Windows services is that by default, they run under the LOCAL_SYSTEM account. This means that permissions to local volumes apply (LOCAL_SYSTEM can certainly be denied access to any given folder), and that LOCAL_SYSTEM does not have any access to any network volumes. A: I'm not familiar with pywin32's ServiceFramework, but based on your code and the error message, I bet you have a problem with path_to_watch. I assume you sanitized the folder name for your example, and you're not actually looking for folder. How about: Are you using the full path to the folder? The current working directory of the service may not be what you expect. Are you escaping any backslashes in the folder path? Try using: path_to_watch = r"c:\foo\bar" + "\\"
Python win32 service
I am fairly new to python, and have no experience with writing services for windows. I have tried to hack together a windows service based on afew tutorials i have found out there. I need this service to constantly monitor a directory for changes and when it sees a change it runs a script. Here is what i have so far: import win32service import win32serviceutil import time class aservice(win32serviceutil.ServiceFramework): _svc_name_ = "aservice" _svc_display_name_ = "aservice - It Does nothing" def __init__(self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.isAlive = True def SvcDoRun(self): import servicemanager while self.isAlive: # This is where i am trying to run my code...is that right? self.main() #servicemanager.LogInfoMsg("aservice - is alive and well") #time.sleep(5) #servicemanager.LogInfoMsg("aservice - Stopped") def SvcStop(self): import servicemanager servicemanager.LogInfoMsg("aservice - Recieved stop signal") self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) self.isAlive = False #this will make SvcDoRun() break the while loop at the next iteration. # This code monitors a directory for changes and calls a script when there is a change # At the moment, it creates a log file instead of calling the script def main(self): import os import win32file import win32con ACTIONS = { 1: "Created", 2: "Deleted", 3: "Updated", 4: "Renamed from something", 5: "Ranamed to something" } FILE_LIST_DIRECTORY = 0x0001 path_to_watch = "folder" hDir = win32file.CreateFile ( path_to_watch, FILE_LIST_DIRECTORY, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, win32con.FILE_FLAG_BACKUP_SEMANTICS, None ) while 1: results = win32file.ReadDirectoryChangesW ( hDir, 1024, True, win32con.FILE_NOTIFY_CHANGE_FILE_NAME | win32con.FILE_NOTIFY_CHANGE_DIR_NAME | win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES | win32con.FILE_NOTIFY_CHANGE_SIZE | win32con.FILE_NOTIFY_CHANGE_LAST_WRITE | win32con.FILE_NOTIFY_CHANGE_SECURITY, None, None ) for action, file in results: #import script log = open ('log.txt', 'w') full_filename = os.path.join(path_to_watch) log.write(full_filename + ACTIONS.get(action, "Unknown")) log.close() if __name__ == '__main__': win32serviceutil.HandleCommandLine(aservice) Any ideas on what i am doing wrong? EDIT: Here is the event log error i am getting for it. Event Type: Error Event Source: aservice Event Category: None Event ID: 3 Date: 21/01/2010 Time: 11:27:43 AM User: N/A Computer: Description: The instance's SvcRun() method failed Traceback (most recent call last): File "C:\Python25\Lib\site-packages\win32\lib\win32serviceutil.py", line 806, in SvcRun self.SvcDoRun() File "D:\TEST\simpleservice2.py", line 35, in SvcDoRun self.main() File "D:\TEST\simpleservice2.py", line 72, in main None error: (2, 'CreateFile', 'The system cannot find the file specified.') %2: %3
[ "One thing to keep in mind with Windows services is that by default, they run under the LOCAL_SYSTEM account. This means that permissions to local volumes apply (LOCAL_SYSTEM can certainly be denied access to any given folder), and that LOCAL_SYSTEM does not have any access to any network volumes.\n", "I'm not familiar with pywin32's ServiceFramework, but based on your code and the error message, I bet you have a problem with path_to_watch.\nI assume you sanitized the folder name for your example, and you're not actually looking for folder.\nHow about:\n\nAre you using the full path to the folder? The current working directory of the service may not be what you expect.\nAre you escaping any backslashes in the folder path?\n\nTry using:\npath_to_watch = r\"c:\\foo\\bar\" + \"\\\\\" \n\n" ]
[ 2, 1 ]
[]
[]
[ "python", "pywin32", "service", "winapi" ]
stackoverflow_0002106366_python_pywin32_service_winapi.txt
Q: Is a reason I can't add a ManyToManyField? So I'm building a Django application, and these are a few models I have: class MagicType(models.Model): name = models.CharField(max_length=155) parent = models.ForeignKey('self', null=True, blank=True) class Spell(models.Model): name = models.CharField(max_length=250, db_index=True) magic_words = models.CharField(max_length=250, db_index=True) magic_types = models.ManyToManyField(MagicType) When syncing the models I'm getting this error: AttributeError: 'ManyToManyField' object has no attribute '_get_m2m_column_name' Is there a reason this is happening? How can I fix this? Help would be very much appreciated. EDIT: I'm using django-evolution http://code.google.com/p/django-evolution/ A: Is MagicType declared in the same models file (and before) Spell? Does magic_types = models.ManyToManyField('MagicType') work (with 'MagicType' quoted)? A: I suggest you use django-extensions , this will give you a commnad sqldiiff that works better than evolution, because there is a problem creating the intermediate table between MagicType and MagicType. I suggest you run the command sqlall yourapp and execute directly the sql code of the creation of the new intermediate table. Evolution doesn't it for you :(
Is a reason I can't add a ManyToManyField?
So I'm building a Django application, and these are a few models I have: class MagicType(models.Model): name = models.CharField(max_length=155) parent = models.ForeignKey('self', null=True, blank=True) class Spell(models.Model): name = models.CharField(max_length=250, db_index=True) magic_words = models.CharField(max_length=250, db_index=True) magic_types = models.ManyToManyField(MagicType) When syncing the models I'm getting this error: AttributeError: 'ManyToManyField' object has no attribute '_get_m2m_column_name' Is there a reason this is happening? How can I fix this? Help would be very much appreciated. EDIT: I'm using django-evolution http://code.google.com/p/django-evolution/
[ "Is MagicType declared in the same models file (and before) Spell?\nDoes magic_types = models.ManyToManyField('MagicType') work (with 'MagicType' quoted)? \n", "I suggest you use django-extensions , this will give you a commnad sqldiiff that works better than evolution, because there is a problem creating the intermediate table between MagicType and MagicType.\nI suggest you run the command sqlall yourapp and execute directly the sql code of the creation of the new intermediate table. Evolution doesn't it for you :(\n" ]
[ 3, 3 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002098696_django_django_models_python.txt
Q: Restart a Python Program I'm writing a Python program that, if the user changes settings while running it, needs to be restarted to apply the changed settings. Is there a way of doing this? I'm thinking something along the lines of: import sys command_line = ' '.join(sys.argv) # Now do something with command_line # Now call my custom exit procedure Note: I'm on Windows, if that makes a difference A: I would bypass all the angst you're likely to get from trying to re-run yourself and leave it in the hands of the environment. By that, I mean: Have a controlling program which does nothing more than run your program (with the same parameters it was given) in a loop while your program exits with a specific "restart" code. This could be as simple as a cmd file or as complex as another (very simple) Python program that uses os.system). Basically, as long as the controlling program gets the code "restart", it will re-run your program with exactly the same parameters. Any other code will cause it to exit with that code. When you want to exit fully, have your real Python program exit with return code 0 (or anything that's not the "restart" code in an error situation). If you just want to cycle to another iteration of your program (to re-read the config for example), exit with the "restart" code recognised by the controlling program. But you may also want to think about re-engineering your application so that it can re-read its configuration at any time. This will make the whole problem go away. You don't mention why that's not an option so I'm assuming you have some reason why it won't work. But, if you don't, that's the path I'd be choosing. To provide some sample code for the first option (this is on Windows but under Cygwin - the same basic rules should apply for Windows native Python but you should check the return values from os.system).: > cat phase1.py #!/usr/bin/python import os status = 9 while status == 9: status = int(os.system ("./phase2.py") / 256) # exit code is upper 8 bits print "Controller: %d"%(status)   > cat phase2.py #!/usr/bin/python import sys import time time.sleep(1) val = int(time.time())%10 if val == 0: rc = 0 else: rc = 9 print "Program: %d -> %d"%(val,rc) sys.exit(rc)   > ./phase1.py Program: 2 -> 9 Controller: 9 Program: 3 -> 9 Controller: 9 Program: 4 -> 9 Controller: 9 Program: 5 -> 9 Controller: 9 Program: 7 -> 9 Controller: 9 Program: 8 -> 9 Controller: 9 Program: 9 -> 9 Controller: 9 Program: 0 -> 0 Controller: 0 You can see the controller using an exit code of 9 to decide whether to re-run the program. The program itself is a dumb one which returns 9 unless it's on a 10-second multiple. A: On unix, you can use os.execl family of functions: These functions all execute a new program, replacing the current process; they do not return. On Unix, the new executable is loaded into the current process, and will have the same process id as the caller. Errors will be reported as OSError exceptions. On windows, take a look at the os.spawnl family, which are less efficient than the unix calls.
Restart a Python Program
I'm writing a Python program that, if the user changes settings while running it, needs to be restarted to apply the changed settings. Is there a way of doing this? I'm thinking something along the lines of: import sys command_line = ' '.join(sys.argv) # Now do something with command_line # Now call my custom exit procedure Note: I'm on Windows, if that makes a difference
[ "I would bypass all the angst you're likely to get from trying to re-run yourself and leave it in the hands of the environment.\nBy that, I mean:\n\nHave a controlling program which does nothing more than run your program (with the same parameters it was given) in a loop while your program exits with a specific \"restart\" code. This could be as simple as a cmd file or as complex as another (very simple) Python program that uses os.system). Basically, as long as the controlling program gets the code \"restart\", it will re-run your program with exactly the same parameters. Any other code will cause it to exit with that code.\nWhen you want to exit fully, have your real Python program exit with return code 0 (or anything that's not the \"restart\" code in an error situation).\nIf you just want to cycle to another iteration of your program (to re-read the config for example), exit with the \"restart\" code recognised by the controlling program.\n\nBut you may also want to think about re-engineering your application so that it can re-read its configuration at any time. This will make the whole problem go away. You don't mention why that's not an option so I'm assuming you have some reason why it won't work.\nBut, if you don't, that's the path I'd be choosing.\nTo provide some sample code for the first option (this is on Windows but under Cygwin - the same basic rules should apply for Windows native Python but you should check the return values from os.system).:\n> cat phase1.py\n#!/usr/bin/python\nimport os\nstatus = 9\nwhile status == 9:\n status = int(os.system (\"./phase2.py\") / 256) # exit code is upper 8 bits\n print \"Controller: %d\"%(status)\n\n \n> cat phase2.py\n#!/usr/bin/python\nimport sys\nimport time\ntime.sleep(1)\nval = int(time.time())%10\nif val == 0:\n rc = 0\nelse:\n rc = 9\nprint \"Program: %d -> %d\"%(val,rc)\nsys.exit(rc)\n\n \n> ./phase1.py\nProgram: 2 -> 9\nController: 9\nProgram: 3 -> 9\nController: 9\nProgram: 4 -> 9\nController: 9\nProgram: 5 -> 9\nController: 9\nProgram: 7 -> 9\nController: 9\nProgram: 8 -> 9\nController: 9\nProgram: 9 -> 9\nController: 9\nProgram: 0 -> 0\nController: 0\n\nYou can see the controller using an exit code of 9 to decide whether to re-run the program. The program itself is a dumb one which returns 9 unless it's on a 10-second multiple.\n", "On unix, you can use os.execl family of functions:\n\nThese functions all execute a new program, replacing the current process; they do not return. On Unix, the new executable is loaded into the current process, and will have the same process id as the caller. Errors will be reported as OSError exceptions.\n\nOn windows, take a look at the os.spawnl family, which are less efficient than the unix calls.\n" ]
[ 8, 6 ]
[]
[]
[ "python", "restart" ]
stackoverflow_0002107317_python_restart.txt
Q: indentation problem in my python program I am using the following code and geting some indentation problem from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __unicode__(self): return self.question I am geting following error File "E:\Softwares\Django-1.1.1.tar\.py", line 7 def __unicode__(self): ^ IndentationError: unexpected indent A: Most likely you're using a mix of tabs and spaces in your indentation... Use all spaces / all tabs instead. (The most widely adopted style is to use 4 spaces per level of indent.) To fix this particular instance of the problem, check make the def __unicode__(self): line start with the same indent as the pub_date = ... line. Use the same indent + four extra spaces for the return ... line. A: agree with the others, and you can use editor that can visualize the space to check. e.g. vim set list listchars=tab:»·,trail:· (gedit also has such plugins, i think). A: I'm taking a wild guess here, and the fact that there's a filename* in your traceback speaks against my guess, but hey… Since your tabs/spaces seem more or less okay (assuming a verbatim copy/paste), is it possible that you pasted the code into the interactive interpreter? The newline after the field definitions would make the interpreter think that the class definition is done, and thus assume being back at global scope. That would mean that the def is indeed falsely indented. * .py is not exactly a great filename for a python script, btw
indentation problem in my python program
I am using the following code and geting some indentation problem from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __unicode__(self): return self.question I am geting following error File "E:\Softwares\Django-1.1.1.tar\.py", line 7 def __unicode__(self): ^ IndentationError: unexpected indent
[ "Most likely you're using a mix of tabs and spaces in your indentation... Use all spaces / all tabs instead. (The most widely adopted style is to use 4 spaces per level of indent.)\nTo fix this particular instance of the problem, check make the def __unicode__(self): line start with the same indent as the pub_date = ... line. Use the same indent + four extra spaces for the return ... line.\n", "agree with the others, and you can use editor that can visualize the space to check. e.g.\nvim set list listchars=tab:»·,trail:· (gedit also has such plugins, i think).\n", "I'm taking a wild guess here, and the fact that there's a filename* in your traceback speaks against my guess, but hey…\nSince your tabs/spaces seem more or less okay (assuming a verbatim copy/paste), is it possible that you pasted the code into the interactive interpreter?\nThe newline after the field definitions would make the interpreter think that the class definition is done, and thus assume being back at global scope. That would mean that the def is indeed falsely indented.\n* .py is not exactly a great filename for a python script, btw\n" ]
[ 3, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002107327_django_python.txt
Q: Iterating over a large Django queryset while the data is changing elsewhere Iterating over a queryset, like so: class Book(models.Model): # <snip some other stuff> activity = models.PositiveIntegerField(default=0) views = models.PositiveIntegerField(default=0) def calculate_statistics(): self.activity = book.views * 4 book.save() def cron_job_calculate_all_book_statistics(): for book in Book.objects.all(): book.calculate_statistics() ...works just fine. However, this is a cron task. book.views is being incremented while this is happening. If book.views is modified while this cronjob is running, it gets reverted. Now, book.views is not being modified by the cronjob, but it is being cached during the .all() queryset call. When book.save(), I have a feeling it is using the old book.views value. Is there a way to make sure that only the activity field is updated? Alternatively, let's say there are 100,000 books. This will take quite a while to run. But the book.views will be from when the queryset originally starts running. Is the solution to just use an .iterator()? UPDATE: Here's effectively what I am doing. If you have ideas about how to make this work well inline, then I'm all for it. def calculate_statistics(self): self.activity = self.views + self.hearts.count() * 2 # Can't do self.comments.count with a comments GenericRelation, because Comment uses # a TextField for object_pk, and that breaks the whole system. Lame. self.activity += Comment.objects.for_model(self).count() * 4 self.save() A: The following will do the job for you in Django 1.1, no loop necessary: from django.db.models import F Book.objects.all().update(activity=F('views')*4) You can have a more complicated calculation too: for book in Book.objects.all().iterator(): Book.objects.filter(pk=book.pk).update(activity=book.calculate_activity()) Both these options have the potential to leave the activity field out of sync with the rest, but I assume you're ok with that, given that you're calculating it in a cron job. A: In addition to what others have said if you are iterating over a large queryset you should use iterator(): Book.objects.filter(stuff).order_by(stuff).iterator() this will cause Django to not cache the items as it iterates (which could use a ton of memory for a large result set). A: No matter how you solve this, beware of transaction-related issues. E.g. default transaction isolation level is set to REPEATABLE READ, at least for MySQL backend. This, plus the fact that both Django and db backend work in a specific autocommit mode with an ongoing transaction means, that even if you use (very nice) whrde suggestion, value of `views' could be no longer valid. I could be wrong here, but feel warned.
Iterating over a large Django queryset while the data is changing elsewhere
Iterating over a queryset, like so: class Book(models.Model): # <snip some other stuff> activity = models.PositiveIntegerField(default=0) views = models.PositiveIntegerField(default=0) def calculate_statistics(): self.activity = book.views * 4 book.save() def cron_job_calculate_all_book_statistics(): for book in Book.objects.all(): book.calculate_statistics() ...works just fine. However, this is a cron task. book.views is being incremented while this is happening. If book.views is modified while this cronjob is running, it gets reverted. Now, book.views is not being modified by the cronjob, but it is being cached during the .all() queryset call. When book.save(), I have a feeling it is using the old book.views value. Is there a way to make sure that only the activity field is updated? Alternatively, let's say there are 100,000 books. This will take quite a while to run. But the book.views will be from when the queryset originally starts running. Is the solution to just use an .iterator()? UPDATE: Here's effectively what I am doing. If you have ideas about how to make this work well inline, then I'm all for it. def calculate_statistics(self): self.activity = self.views + self.hearts.count() * 2 # Can't do self.comments.count with a comments GenericRelation, because Comment uses # a TextField for object_pk, and that breaks the whole system. Lame. self.activity += Comment.objects.for_model(self).count() * 4 self.save()
[ "The following will do the job for you in Django 1.1, no loop necessary:\nfrom django.db.models import F\nBook.objects.all().update(activity=F('views')*4)\n\nYou can have a more complicated calculation too:\nfor book in Book.objects.all().iterator():\n Book.objects.filter(pk=book.pk).update(activity=book.calculate_activity())\n\nBoth these options have the potential to leave the activity field out of sync with the rest, but I assume you're ok with that, given that you're calculating it in a cron job.\n", "In addition to what others have said if you are iterating over a large queryset you should use iterator():\nBook.objects.filter(stuff).order_by(stuff).iterator()\n\nthis will cause Django to not cache the items as it iterates (which could use a ton of memory for a large result set).\n", "No matter how you solve this, beware of transaction-related issues. E.g. default transaction isolation level is set to REPEATABLE READ, at least for MySQL backend. This, plus the fact that both Django and db backend work in a specific autocommit mode with an ongoing transaction means, that even if you use (very nice) whrde suggestion, value of `views' could be no longer valid. I could be wrong here, but feel warned.\n" ]
[ 4, 3, 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002104404_django_django_models_python.txt
Q: Error when adding a ManyToManyField in Django Ok, so I posted a question recently regarding an error when adding a ManyToManyField The Models are the ones below class MagicType(models.Model): name = models.CharField(max_length=155) parent = models.ForeignKey('self', null=True, blank=True) class Spell(models.Model): name = models.CharField(max_length=250, db_index=True) magic_words = models.CharField(max_length=250, db_index=True) magic_types = models.ManyToManyField(MagicType) This is the error I get when migrating with django-evolution: AttributeError: 'ManyToManyField' object has no attribute '_get_m2m_column_name' So, is there a way of manually setting a ManyToManyField without specifying it within the two models? let's say with a model like this class SpellToMagicType(models.Model): magic_type = models.ForeignKey(MagicType) spell = models.ForeignKey(Spell) but how would I go on about using this within Django's ORM? Help would be very much appreciated. Thanks! A: Same thing, i answer your another question Is a reason I can't add a ManyToManyField? basicly this error is because your code in models (ORM) change but your database isn't, and django-evolution doesn't fix many problems with changes in the database, i suggest you look for django-extensions (http://code.google.com/p/django-command-extensions/) and the command sqldiff, but look my another answer A: This is more or less the way I would have done it. In fact, I was puzzled about why this didn't work, and tried it myself in a clean Django 1.1 environment -- it works swimmingly. Have you tried putting this model in a clean environment yourself and seeing what you get?
Error when adding a ManyToManyField in Django
Ok, so I posted a question recently regarding an error when adding a ManyToManyField The Models are the ones below class MagicType(models.Model): name = models.CharField(max_length=155) parent = models.ForeignKey('self', null=True, blank=True) class Spell(models.Model): name = models.CharField(max_length=250, db_index=True) magic_words = models.CharField(max_length=250, db_index=True) magic_types = models.ManyToManyField(MagicType) This is the error I get when migrating with django-evolution: AttributeError: 'ManyToManyField' object has no attribute '_get_m2m_column_name' So, is there a way of manually setting a ManyToManyField without specifying it within the two models? let's say with a model like this class SpellToMagicType(models.Model): magic_type = models.ForeignKey(MagicType) spell = models.ForeignKey(Spell) but how would I go on about using this within Django's ORM? Help would be very much appreciated. Thanks!
[ "Same thing, i answer your another question Is a reason I can't add a ManyToManyField? basicly this error is because your code in models (ORM) change but your database isn't, and django-evolution doesn't fix many problems with changes in the database, i suggest you look for django-extensions (http://code.google.com/p/django-command-extensions/) and the command sqldiff, but look my another answer\n", "This is more or less the way I would have done it. In fact, I was puzzled about why this didn't work, and tried it myself in a clean Django 1.1 environment -- it works swimmingly.\nHave you tried putting this model in a clean environment yourself and seeing what you get?\n" ]
[ 3, 1 ]
[]
[]
[ "django", "django_evolution", "django_models", "django_orm", "python" ]
stackoverflow_0002106491_django_django_evolution_django_models_django_orm_python.txt
Q: Re-open files in Python? Say I have this simple python script: file = open('C:\\some_text.txt') print file.readlines() print file.readlines() When it is run, the first print prints a list containing the text of the file, while the second print prints a blank list. Not completely unexpected I guess. But is there a way to 'wind back' the file so that I can read it again? Or is the fastest way just to re-open it? A: You can reset the file pointer by calling seek(): file.seek(0) will do it. You need that line after your first readlines(). Note that file has to support random access for the above to work. A: For small files, it's probably much faster to just keep the file's contents in memory file = open('C:\\some_text.txt') fileContents = file.readlines() print fileContents print fileContents # This line will work as well. Of course, if it's a big file, this could put strain on your RAM. A: Remember that you can always use the with statement to open and close files: from __future__ import with_statement with open('C:\\some_text.txt') as file: data = file.readlines() #File is now closed for line in data: print line
Re-open files in Python?
Say I have this simple python script: file = open('C:\\some_text.txt') print file.readlines() print file.readlines() When it is run, the first print prints a list containing the text of the file, while the second print prints a blank list. Not completely unexpected I guess. But is there a way to 'wind back' the file so that I can read it again? Or is the fastest way just to re-open it?
[ "You can reset the file pointer by calling seek():\nfile.seek(0)\n\nwill do it. You need that line after your first readlines(). Note that file has to support random access for the above to work.\n", "For small files, it's probably much faster to just keep the file's contents in memory\nfile = open('C:\\\\some_text.txt')\nfileContents = file.readlines()\nprint fileContents\nprint fileContents # This line will work as well.\n\nOf course, if it's a big file, this could put strain on your RAM.\n", "Remember that you can always use the with statement to open and close files:\nfrom __future__ import with_statement\n\nwith open('C:\\\\some_text.txt') as file:\n data = file.readlines()\n#File is now closed\nfor line in data:\n print line\n\n" ]
[ 79, 3, 3 ]
[]
[]
[ "file", "python" ]
stackoverflow_0002106820_file_python.txt
Q: should not access parent frame untill closes the child? I have two frames one parent and child. the parent will invoke the child. The program should not allow the user to access the parent until the user closes the child How can i achive it? Need a solution without hiding the parent A: See the wx.Window.MakeModal() method (Frame inherits from Window).
should not access parent frame untill closes the child?
I have two frames one parent and child. the parent will invoke the child. The program should not allow the user to access the parent until the user closes the child How can i achive it? Need a solution without hiding the parent
[ "See the wx.Window.MakeModal() method (Frame inherits from Window).\n" ]
[ 2 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002107489_python_wxpython.txt
Q: How do I rotate/flip an image without using photologue/ImageModel? I need a functionality in Django to rotate an image posted by users using a form. I need a method I can maybe put in imageutils.py and then use it in my form. How can it be achieved? A: Use the Python Imaging Library directly: from PIL import Image im = Image.open("yourfilename.jpg") im = im.rotate(90) im.save("yourrotatedfilename.jpg", "JPEG") This is tested, and works. You'll need to have the Python Imaging Library installed and on your Python path, obviously, and you'll need to find the appropriate place to run this code (which is probably when your form is being saved). This makes the assumption that you're dealing with JPEG files, but PIL a bunch of formats are supported.
How do I rotate/flip an image without using photologue/ImageModel?
I need a functionality in Django to rotate an image posted by users using a form. I need a method I can maybe put in imageutils.py and then use it in my form. How can it be achieved?
[ "Use the Python Imaging Library directly:\nfrom PIL import Image\nim = Image.open(\"yourfilename.jpg\")\nim = im.rotate(90)\nim.save(\"yourrotatedfilename.jpg\", \"JPEG\")\n\nThis is tested, and works. You'll need to have the Python Imaging Library installed and on your Python path, obviously, and you'll need to find the appropriate place to run this code (which is probably when your form is being saved).\nThis makes the assumption that you're dealing with JPEG files, but PIL a bunch of formats are supported.\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002107888_django_python.txt
Q: How to update xml file using lxml and python? <example> <login> <id>1</id> <username>kites</username> <password>kites</password> </login> </example> How can i update password using lxml? and now can i add one more record to the same file? please provide me a sample code A: example = etree.Element("example") login = etree.SubElement(example, "login") password = etree.SubElement(login,"password") password.text = "newPassword" This is a good tutorial
How to update xml file using lxml and python?
<example> <login> <id>1</id> <username>kites</username> <password>kites</password> </login> </example> How can i update password using lxml? and now can i add one more record to the same file? please provide me a sample code
[ "example = etree.Element(\"example\")\nlogin = etree.SubElement(example, \"login\")\npassword = etree.SubElement(login,\"password\")\npassword.text = \"newPassword\"\n\nThis is a good tutorial\n" ]
[ 4 ]
[]
[]
[ "lxml", "python", "xml" ]
stackoverflow_0002108334_lxml_python_xml.txt
Q: Save method manytomany I've got a model called Card which has a ManyToMany relationship to Tag. When I save a Card, I'd like to create a Product as well, which I want to have the same ManyToMany relationship to tag. How do I access the instance's tags? self.tags.all() gives an empty list, while if I check after saving, the card actually has tags. My code is below. For the record, I am using Django 1.0.5. class Card(models.Model): product = models.ForeignKey(Product, editable=False, null=True) name = models.CharField('name', max_length=50, unique=True, help_text='A short and unique name or title of the object.') identifier = models.SlugField('identifier', unique=True, help_text='A unique identifier constructed from the name of the object. Only change this if you know what it does.', db_index=True) tags = models.ManyToManyField(Tag, verbose_name='tags', db_index=True) price = models.DecimalField('price', max_digits=15, decimal_places=2, db_index=True) def add_product(self): product = Product( name = self.name, identifier = self.identifier, price = self.price ) product.save() return product def save(self, *args, **kwargs): # Step 1: Create product if not self.id: self.product = self.add_product() # Step 2: Create Card super(Card, self).save(*args, **kwargs) # Step 3: Copy cards many to many to product # How do I do this? print self.tags.all() # gives an empty list?? A: Are you using the django-admin to save the model and tags? The many-to-many fields don't get saved there until after the post-save signal of the model. What you can do in this case is overide the admin classes save_model method. E.g.: class CardAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): obj.save() form.save_m2m() #from this point on the tags are accessible print obj.tags.all() A: You aren't adding any tags to the Card. You can't add ManyToMany relationships until after you save the Card, and there's no time between the save call and the call to self.tags.all() for them to be set.
Save method manytomany
I've got a model called Card which has a ManyToMany relationship to Tag. When I save a Card, I'd like to create a Product as well, which I want to have the same ManyToMany relationship to tag. How do I access the instance's tags? self.tags.all() gives an empty list, while if I check after saving, the card actually has tags. My code is below. For the record, I am using Django 1.0.5. class Card(models.Model): product = models.ForeignKey(Product, editable=False, null=True) name = models.CharField('name', max_length=50, unique=True, help_text='A short and unique name or title of the object.') identifier = models.SlugField('identifier', unique=True, help_text='A unique identifier constructed from the name of the object. Only change this if you know what it does.', db_index=True) tags = models.ManyToManyField(Tag, verbose_name='tags', db_index=True) price = models.DecimalField('price', max_digits=15, decimal_places=2, db_index=True) def add_product(self): product = Product( name = self.name, identifier = self.identifier, price = self.price ) product.save() return product def save(self, *args, **kwargs): # Step 1: Create product if not self.id: self.product = self.add_product() # Step 2: Create Card super(Card, self).save(*args, **kwargs) # Step 3: Copy cards many to many to product # How do I do this? print self.tags.all() # gives an empty list??
[ "Are you using the django-admin to save the model and tags? The many-to-many fields don't get saved there until after the post-save signal of the model. What you can do in this case is overide the admin classes save_model method. E.g.:\nclass CardAdmin(admin.ModelAdmin):\n\n def save_model(self, request, obj, form, change):\n obj.save()\n form.save_m2m()\n #from this point on the tags are accessible\n print obj.tags.all()\n\n", "You aren't adding any tags to the Card. You can't add ManyToMany relationships until after you save the Card, and there's no time between the save call and the call to self.tags.all() for them to be set.\n" ]
[ 2, 0 ]
[]
[]
[ "django", "many_to_many", "methods", "python", "save" ]
stackoverflow_0002108039_django_many_to_many_methods_python_save.txt
Q: How to add a padding to the data to make it acceptable for AES256 encryption algorithm in pycrypto library Can someone tell me how to add a padding to the data to make it acceptable for AES256 encryption algorithm in pycrypto library (Python). Thanks a lot in advance.. :) A: Looking at the documentation, it seems that it's up to you, the library user, to pad the data yourself. The documentation states that the block size for AES is always 16 bytes, so you need to pad the data to a multiple of 16 bytes. How the padding is done depends on the type of the data. For strings the best approach is probably to encode the string to a specific encoding and then take the length of that encoding. That way you're not relying on all characters being represented by an 8-bit codepoint: plaintext = data.encode('utf-8') l = len(plaintext) ciphertext = cipher.encrypt(plaintext + ((16 - len%16) * PADDING_BYTE)) A similar approach will work when you're data is an array of bytes. 0 should work fine as the PADDING_BYTE, but you need to take care to remove the padding when you're decrypting the data. It might be worth while including the length of the data in the ciphertext, e.g. prepend the length of the data to the plaintext before encryption, but then you need to jump through some hoops to make sure the padding is generated correctly. Edit: oh yes, just like the RFC GregS links to mentions, the standard way of handling the length problem is the use the length of the padding as the padding byte. I.e. if you need 6 bytes of padding the padding byte is 0x06. Note that if you don't need any padding, you to add a whole block of padding bytes (16 bytes of 0xa0) so that you can recover the message correctly. A: Use a standard padding scheme, such as the scheme outlined in PKCS-5, section 6.1.1 step #4 (replace the 8 in that example with 16 if you are using AES).
How to add a padding to the data to make it acceptable for AES256 encryption algorithm in pycrypto library
Can someone tell me how to add a padding to the data to make it acceptable for AES256 encryption algorithm in pycrypto library (Python). Thanks a lot in advance.. :)
[ "Looking at the documentation, it seems that it's up to you, the library user, to pad the data yourself. The documentation states that the block size for AES is always 16 bytes, so you need to pad the data to a multiple of 16 bytes.\nHow the padding is done depends on the type of the data. For strings the best approach is probably to encode the string to a specific encoding and then take the length of that encoding. That way you're not relying on all characters being represented by an 8-bit codepoint:\nplaintext = data.encode('utf-8')\nl = len(plaintext)\nciphertext = cipher.encrypt(plaintext + ((16 - len%16) * PADDING_BYTE))\n\nA similar approach will work when you're data is an array of bytes.\n0 should work fine as the PADDING_BYTE, but you need to take care to remove the padding when you're decrypting the data. It might be worth while including the length of the data in the ciphertext, e.g. prepend the length of the data to the plaintext before encryption, but then you need to jump through some hoops to make sure the padding is generated correctly.\nEdit: oh yes, just like the RFC GregS links to mentions, the standard way of handling the length problem is the use the length of the padding as the padding byte. I.e. if you need 6 bytes of padding the padding byte is 0x06. Note that if you don't need any padding, you to add a whole block of padding bytes (16 bytes of 0xa0) so that you can recover the message correctly.\n", "Use a standard padding scheme, such as the scheme outlined in PKCS-5, section 6.1.1 step #4 (replace the 8 in that example with 16 if you are using AES).\n" ]
[ 5, 3 ]
[]
[]
[ "encryption", "pycrypto", "python" ]
stackoverflow_0002108047_encryption_pycrypto_python.txt
Q: Django/Python mailing list implementation My site requires sending periodic update emails to all our registered clients. To keep our lists clear, I want to track all failed deliveries and purge the mailing lists accordingly. I am assuming I am not the first nor the last to do this. Can anyone recommend an existing app/library that I can use to accomplish this goal ? Thank you A: I think you need a mailing list server like mailman, there is django-mailman (a django's admin interface for mailman), and follow this steps: Install mailman Install django-mailman Complete your user's registration algorithm for your users and register them in mailman. When you need send a mail, send it to you mailman list. Have a lot of fun! A: You should have a look at mailchimp
Django/Python mailing list implementation
My site requires sending periodic update emails to all our registered clients. To keep our lists clear, I want to track all failed deliveries and purge the mailing lists accordingly. I am assuming I am not the first nor the last to do this. Can anyone recommend an existing app/library that I can use to accomplish this goal ? Thank you
[ "I think you need a mailing list server like mailman, there is django-mailman (a django's admin interface for mailman), and follow this steps:\n\nInstall mailman\nInstall django-mailman\nComplete your user's registration algorithm for your users and register them in mailman.\nWhen you need send a mail, send it to you mailman list.\nHave a lot of fun!\n\n", "You should have a look at mailchimp\n" ]
[ 4, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002104133_django_python.txt
Q: Facebook Page details and the RESTful API? Hi I have a list of Facebook Page urls eg... http://www.facebook.com/daftpunk http://www.facebook.com/DavidGuetta ... What's the best way to: Check if these urls are actually for Facebook Pages and not Profiles Collect details such as # of fans from these Pages Help would be very much appreciated. A: Without scraping any content (which is against Facebook's terms of service anyway): Extract the username part of the URL i.e. the bit after the www.facebook.com/ Do an FQL query of the form select fan_count from page where username='michaeljackson' If a result is return, you know it's a Page and not a user's profile. See the Page FQL table for other data you can retrieve in the same call. A: use urllib2 or pyfacebook to fetch the content use BeautifulSoup or lxml to parse it use the re module (regular expressions) to extract content for your verification and data gathering A: The # of fans is in an a tag with the class 'FanManager'. you can use Beautiful Soup to get the contents of this a tag, and regular expressions to get the data from the string (ex: 1,000,000 fans) as an int or whatever you would like. To see if the page exists, check some of the tags to see if you are on the 404 page. A: You can use scrapy or BeautifulSoup to scrape the content.
Facebook Page details and the RESTful API?
Hi I have a list of Facebook Page urls eg... http://www.facebook.com/daftpunk http://www.facebook.com/DavidGuetta ... What's the best way to: Check if these urls are actually for Facebook Pages and not Profiles Collect details such as # of fans from these Pages Help would be very much appreciated.
[ "Without scraping any content (which is against Facebook's terms of service anyway):\n\nExtract the username part of the URL\ni.e. the bit after the\nwww.facebook.com/\nDo an FQL query of the form select\nfan_count from\npage where\nusername='michaeljackson'\nIf a result is return, you know it's a\nPage and not a user's profile.\n\nSee the Page FQL table for other data you can retrieve in the same call.\n", "use urllib2 or pyfacebook to fetch the content\nuse BeautifulSoup or lxml to parse it\nuse the re module (regular expressions) to extract content for your verification and data gathering\n", "The # of fans is in an a tag with the class 'FanManager'. you can use Beautiful Soup to get the contents of this a tag, and regular expressions to get the data from the string (ex: 1,000,000 fans) as an int or whatever you would like.\nTo see if the page exists, check some of the tags to see if you are on the 404 page.\n", "You can use scrapy or BeautifulSoup to scrape the content.\n" ]
[ 3, 2, 1, 0 ]
[]
[]
[ "facebook", "pyfacebook", "python" ]
stackoverflow_0002104996_facebook_pyfacebook_python.txt
Q: Google App Engine and OpenID I am trying to implement OpenID in a GoogleAppEngine project. In this case, which OpenIDStore I have to use. Thanks A: I try with AEoid which seems alright. Here's live example and my code
Google App Engine and OpenID
I am trying to implement OpenID in a GoogleAppEngine project. In this case, which OpenIDStore I have to use. Thanks
[ "I try with AEoid which seems alright. Here's live example and my code\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "openid", "python" ]
stackoverflow_0002101817_google_app_engine_openid_python.txt
Q: Creating a FeaturedContent feature in Django using contenttypes I'm using the contenttypes framework to create a "featured content" feature on my site. I've basically done this by defining a model like so: class FeaturedContent(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') What I would like to be able to do now is have a tick box on every model edit/create page from within my admin area, which when ticked and submitted adds the content reference to FeaturedContent. When unticked, likewise the reference is deleted. If there are any better methods to do this please let me know. From what I can see, using contenttypes is the way to go. Many thanks! A: You will need to create a stackedinline admin, for each of your models that need this option in the admin. Something like the following: class ObjectInline(admin.StackedInline): model = YourFancyModelthatisFeatured extra = 0 class FancyModelAdmin(admin.ModelAdmin): inlines = [ObjectInline] But this will give the inlines in their default widget, so you will also need to define a form to customize to the checkbox widget.
Creating a FeaturedContent feature in Django using contenttypes
I'm using the contenttypes framework to create a "featured content" feature on my site. I've basically done this by defining a model like so: class FeaturedContent(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') What I would like to be able to do now is have a tick box on every model edit/create page from within my admin area, which when ticked and submitted adds the content reference to FeaturedContent. When unticked, likewise the reference is deleted. If there are any better methods to do this please let me know. From what I can see, using contenttypes is the way to go. Many thanks!
[ "You will need to create a stackedinline admin, for each of your models that need this option in the admin.\nSomething like the following:\nclass ObjectInline(admin.StackedInline):\n model = YourFancyModelthatisFeatured\n extra = 0\n\nclass FancyModelAdmin(admin.ModelAdmin):\n inlines = [ObjectInline]\n\nBut this will give the inlines in their default widget, so you will also need to define a form to customize to the checkbox widget.\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002109281_django_django_models_python.txt
Q: Getting information about static files in Python App Engine; workarounds I'm working on an App Engine project that will have customizable themes. I'd like to be able to use jQuery UI themes. The problem is figuring out what the CSS file is going to be named. (Typically, "jquery-ui-1.7.2.custom.css". Version numbers will change, and people tend to rename things, but there should only be one CSS file, and I'm OK with it being an error condition if there's two or more for some reason.) Because it's a static file (static files are uploaded to App Engine separately from the rest of the application's resources), I can't just glob the directory for a CSS file. I can't just assume that it's hard-coded, and I really don't want to make it a configuration setting, because that's a bad user experience. Guido told me to symlink it so that App Engine sees two copies and can treat one as static and the other as an application resource, but symlinks don't work on Windows, and since this will ultimately be open source, I can't control which SDK the user uses. Another suggestion was to use a deploy-time script, but Mac users have this nice "Deploy" button in their version of the SDK and I'd rather not have to tell them, "Oh hey, sorry for the inconvenience, but you can't use that for this project." I clearly need an out-of-the-box solution to this one, but I'm at a loss. Anyone have any good suggestions for how to get a custom jQuery UI theme out of the ThemeRoller and into an App Engine app? Some post-processing is already needed, because the only files in the zip file that ThemeRoller gives you are in the "css" directory. Maybe I can write something that takes a raw theme as input and spits out something useful on the other side (the deploy-time script trick, but somehow less user-unfriendly). The trick here is presentation — I want the user to spend as little time on the command line as possible. An ideal solution assumes the person performing this task is non-technical for the most part. No part of the solution can be much harder than installing something like WordPress or Drupal, and in a perfect world, it should be way, way easier. A: To accomplish what you are asking, I would use the datastore for serving the CSS files. Since this would allow easy listing, sorting and even modification and uploading. Other than that, your next best options would be to store the CSS data inside a script (a dictionary where the filename is the key name, and the CSS code is the value). Or, as you suggested, to run a script before deploying to AppEngine. Personally, I would go for the storing in the datastore option, since it will allow for a great deal more user customization (such as each user being able to provide their own CSS file), just be sure to use memcache to avoid needing to access the datastore when possible (which should be a very common occurrence), as well as using HTTP headers to tell the browser to cache the CSS file locally.
Getting information about static files in Python App Engine; workarounds
I'm working on an App Engine project that will have customizable themes. I'd like to be able to use jQuery UI themes. The problem is figuring out what the CSS file is going to be named. (Typically, "jquery-ui-1.7.2.custom.css". Version numbers will change, and people tend to rename things, but there should only be one CSS file, and I'm OK with it being an error condition if there's two or more for some reason.) Because it's a static file (static files are uploaded to App Engine separately from the rest of the application's resources), I can't just glob the directory for a CSS file. I can't just assume that it's hard-coded, and I really don't want to make it a configuration setting, because that's a bad user experience. Guido told me to symlink it so that App Engine sees two copies and can treat one as static and the other as an application resource, but symlinks don't work on Windows, and since this will ultimately be open source, I can't control which SDK the user uses. Another suggestion was to use a deploy-time script, but Mac users have this nice "Deploy" button in their version of the SDK and I'd rather not have to tell them, "Oh hey, sorry for the inconvenience, but you can't use that for this project." I clearly need an out-of-the-box solution to this one, but I'm at a loss. Anyone have any good suggestions for how to get a custom jQuery UI theme out of the ThemeRoller and into an App Engine app? Some post-processing is already needed, because the only files in the zip file that ThemeRoller gives you are in the "css" directory. Maybe I can write something that takes a raw theme as input and spits out something useful on the other side (the deploy-time script trick, but somehow less user-unfriendly). The trick here is presentation — I want the user to spend as little time on the command line as possible. An ideal solution assumes the person performing this task is non-technical for the most part. No part of the solution can be much harder than installing something like WordPress or Drupal, and in a perfect world, it should be way, way easier.
[ "To accomplish what you are asking, I would use the datastore for serving the CSS files. Since this would allow easy listing, sorting and even modification and uploading.\nOther than that, your next best options would be to store the CSS data inside a script (a dictionary where the filename is the key name, and the CSS code is the value). Or, as you suggested, to run a script before deploying to AppEngine.\nPersonally, I would go for the storing in the datastore option, since it will allow for a great deal more user customization (such as each user being able to provide their own CSS file), just be sure to use memcache to avoid needing to access the datastore when possible (which should be a very common occurrence), as well as using HTTP headers to tell the browser to cache the CSS file locally.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "jquery_ui", "python", "themes" ]
stackoverflow_0002099008_google_app_engine_jquery_ui_python_themes.txt
Q: Performance of python library keyczar in Windows I am running this code to see the performance impact of the keyczar encryption library from google: from keyczar import keyczar, keys def main(iters): key = keys.RsaPrivateKey.Generate() msg = "ciao" crypt = None for i in range(iters): print i, "\r", crypt = key.Encrypt(msg) for i in range(iters): print i, "\r", key.Decrypt(crypt) if __name__ == '__main__': main(500) Under Windows, 500 iterations takes about 16 minutes. Under an Ubuntu 9.04 partition on the same machine, 500 iterations takes about 6 seconds. I've tried profiling this (cProfile + pstats) but I don't have much experience in interpreting the results. Can someone tell me why the same code runs 150+ times slower under Windows? Edit 2010-01-16 Here is my generate_key.py script: from keyczar import keyczar, keys key = keys.RsaPrivateKey.Generate() Here is my command line to create a stats file in generate_key: C:\temp\python-keyczar-0.6b\tests\keyczar>python -m cProfile -o generate_key generate_key.py Here is my python session to expand the results: >>> import pstats >>> p = pstats.Stats('generate_key') >>> p.strip_dirs().sort_stats(-1).print_stats(25) Sat Jan 16 12:18:43 2010 generate_key 83493 function calls (82974 primitive calls) in 5.131 CPU seconds Ordered by: standard name List reduced from 564 to 25 due to restriction <25> ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 <string>:1(<module>) 1 0.000 0.000 0.210 0.210 AES.py:1(<module>) 1 0.022 0.022 0.210 0.210 AES.py:1(__bootstrap__) 1 0.000 0.000 0.000 0.000 DSA.py:115(DSAobj) 1 0.001 0.001 0.005 0.005 DSA.py:14(<module>) 1 0.000 0.000 0.000 0.000 DSA.py:174(DSAobj_c) 1 0.000 0.000 0.000 0.000 DSA.py:26(error) 1 0.000 0.000 0.001 0.001 RSA.py:125(size) 1 0.000 0.000 0.000 0.000 RSA.py:13(<module>) 1 0.000 0.000 0.000 0.000 RSA.py:140(publickey) 1 0.000 0.000 0.000 0.000 RSA.py:146(RSAobj_c) 1 0.000 0.000 0.000 0.000 RSA.py:23(error) 1 0.000 0.000 4.816 4.816 RSA.py:26(generate) 1 0.000 0.000 0.000 0.000 RSA.py:63(construct) 1 0.000 0.000 0.000 0.000 RSA.py:85(RSAobj) 1 0.003 0.003 0.004 0.004 SHA.py:4(<module>) 1 0.000 0.000 0.000 0.000 __future__.py:48(<module>) 1 0.000 0.000 0.000 0.000 __future__.py:74(_Feature) 7 0.000 0.000 0.000 0.000 __future__.py:75(__init__) 8 0.000 0.000 0.000 0.000 __init__.py:1(<module>) 1 0.000 0.000 0.000 0.000 __init__.py:11(<module>) 1 0.000 0.000 0.000 0.000 __init__.py:13(<module>) 1 0.000 0.000 0.000 0.000 __init__.py:18(<module>) 1 0.000 0.000 0.000 0.000 __init__.py:20(<module>) 2 0.000 0.000 0.000 0.000 __init__.py:24(<module>) <pstats.Stats instance at 0x023F5E40> >>> So the Windows code does execute in python. Most of the runtime is spent here: def generate(bits, randfunc, progress_func=None): """generate(bits:int, randfunc:callable, progress_func:callable) Generate an RSA key of length 'bits', using 'randfunc' to get random data and 'progress_func', if present, to display the progress of the key generation. """ obj=RSAobj() # Generate the prime factors of n if progress_func: progress_func('p,q\n') p = q = 1L while number.size(p*q) < bits: p = pubkey.getPrime(bits/2, randfunc) q = pubkey.getPrime(bits/2, randfunc) # p shall be smaller than q (for calc of u) if p > q: (p, q)=(q, p) obj.p = p obj.q = q if progress_func: progress_func('u\n') obj.u = pubkey.inverse(obj.p, obj.q) obj.n = obj.p*obj.q obj.e = 65537L if progress_func: progress_func('d\n') obj.d=pubkey.inverse(obj.e, (obj.p-1)*(obj.q-1)) assert bits <= 1+obj.size(), "Generated key is too small" return obj I am running PyCrypto downloade from here. A: PyCrypto has a C module called _fastmath which uses GNU MP for the public key operations. If it is not available, it instead uses Python's native long integers, which are much much slower. The two files are src/_fastmath.c and lib/Crypto/PublicKey/_slowmath.py It's likely that Python on Windows does not include GNU MP, so on Windows it's instead using _slowmath.py A: For that kind of difference, I would suspect that linux is using a c-module to to the work. Perhaps the Windows version failed to install a dll somewhere, so is falling back to Python code Are you running the same version of Python on both platforms?
Performance of python library keyczar in Windows
I am running this code to see the performance impact of the keyczar encryption library from google: from keyczar import keyczar, keys def main(iters): key = keys.RsaPrivateKey.Generate() msg = "ciao" crypt = None for i in range(iters): print i, "\r", crypt = key.Encrypt(msg) for i in range(iters): print i, "\r", key.Decrypt(crypt) if __name__ == '__main__': main(500) Under Windows, 500 iterations takes about 16 minutes. Under an Ubuntu 9.04 partition on the same machine, 500 iterations takes about 6 seconds. I've tried profiling this (cProfile + pstats) but I don't have much experience in interpreting the results. Can someone tell me why the same code runs 150+ times slower under Windows? Edit 2010-01-16 Here is my generate_key.py script: from keyczar import keyczar, keys key = keys.RsaPrivateKey.Generate() Here is my command line to create a stats file in generate_key: C:\temp\python-keyczar-0.6b\tests\keyczar>python -m cProfile -o generate_key generate_key.py Here is my python session to expand the results: >>> import pstats >>> p = pstats.Stats('generate_key') >>> p.strip_dirs().sort_stats(-1).print_stats(25) Sat Jan 16 12:18:43 2010 generate_key 83493 function calls (82974 primitive calls) in 5.131 CPU seconds Ordered by: standard name List reduced from 564 to 25 due to restriction <25> ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 <string>:1(<module>) 1 0.000 0.000 0.210 0.210 AES.py:1(<module>) 1 0.022 0.022 0.210 0.210 AES.py:1(__bootstrap__) 1 0.000 0.000 0.000 0.000 DSA.py:115(DSAobj) 1 0.001 0.001 0.005 0.005 DSA.py:14(<module>) 1 0.000 0.000 0.000 0.000 DSA.py:174(DSAobj_c) 1 0.000 0.000 0.000 0.000 DSA.py:26(error) 1 0.000 0.000 0.001 0.001 RSA.py:125(size) 1 0.000 0.000 0.000 0.000 RSA.py:13(<module>) 1 0.000 0.000 0.000 0.000 RSA.py:140(publickey) 1 0.000 0.000 0.000 0.000 RSA.py:146(RSAobj_c) 1 0.000 0.000 0.000 0.000 RSA.py:23(error) 1 0.000 0.000 4.816 4.816 RSA.py:26(generate) 1 0.000 0.000 0.000 0.000 RSA.py:63(construct) 1 0.000 0.000 0.000 0.000 RSA.py:85(RSAobj) 1 0.003 0.003 0.004 0.004 SHA.py:4(<module>) 1 0.000 0.000 0.000 0.000 __future__.py:48(<module>) 1 0.000 0.000 0.000 0.000 __future__.py:74(_Feature) 7 0.000 0.000 0.000 0.000 __future__.py:75(__init__) 8 0.000 0.000 0.000 0.000 __init__.py:1(<module>) 1 0.000 0.000 0.000 0.000 __init__.py:11(<module>) 1 0.000 0.000 0.000 0.000 __init__.py:13(<module>) 1 0.000 0.000 0.000 0.000 __init__.py:18(<module>) 1 0.000 0.000 0.000 0.000 __init__.py:20(<module>) 2 0.000 0.000 0.000 0.000 __init__.py:24(<module>) <pstats.Stats instance at 0x023F5E40> >>> So the Windows code does execute in python. Most of the runtime is spent here: def generate(bits, randfunc, progress_func=None): """generate(bits:int, randfunc:callable, progress_func:callable) Generate an RSA key of length 'bits', using 'randfunc' to get random data and 'progress_func', if present, to display the progress of the key generation. """ obj=RSAobj() # Generate the prime factors of n if progress_func: progress_func('p,q\n') p = q = 1L while number.size(p*q) < bits: p = pubkey.getPrime(bits/2, randfunc) q = pubkey.getPrime(bits/2, randfunc) # p shall be smaller than q (for calc of u) if p > q: (p, q)=(q, p) obj.p = p obj.q = q if progress_func: progress_func('u\n') obj.u = pubkey.inverse(obj.p, obj.q) obj.n = obj.p*obj.q obj.e = 65537L if progress_func: progress_func('d\n') obj.d=pubkey.inverse(obj.e, (obj.p-1)*(obj.q-1)) assert bits <= 1+obj.size(), "Generated key is too small" return obj I am running PyCrypto downloade from here.
[ "PyCrypto has a C module called _fastmath which uses GNU MP for the public key operations. If it is not available, it instead uses Python's native long integers, which are much much slower.\nThe two files are src/_fastmath.c and lib/Crypto/PublicKey/_slowmath.py\nIt's likely that Python on Windows does not include GNU MP, so on Windows it's instead using _slowmath.py\n", "For that kind of difference, I would suspect that linux is using a c-module to to the work. Perhaps the Windows version failed to install a dll somewhere, so is falling back to Python code\nAre you running the same version of Python on both platforms?\n" ]
[ 1, 0 ]
[]
[]
[ "keyczar", "profiling", "python" ]
stackoverflow_0002074195_keyczar_profiling_python.txt
Q: A good django search app? — How to perform fuzzy search with Haystack? I'm using django-haystack at the moment with apache-solr as the backend. Problem is I cannot get the app to perform the search functionality I'm looking for Searching for sub-parts in a word eg. Searching for "buntu" does not give me "ubuntu" Searching for similar words eg. Searching for "ubantu" would give "ubuntu" Any help would be very much appreciated. A: This is really about how you pass the query back to Haystack (and therefore to Solr). You can do a 'fuzzy' search in Solr/Lucene by using a ~ after the word: ubuntu~ would return both buntu and ubantu. See the Lucene documentation on this. How you pass this through via Haystack depends on how you're using it at the moment. Assuming you're using the default SearchForm, the best thing would be to either override the form's clean_q method to add the tilde on the end of every word in the search results, or override the search method to do the same thing there before passing it to the SearchQuerySet.
A good django search app? — How to perform fuzzy search with Haystack?
I'm using django-haystack at the moment with apache-solr as the backend. Problem is I cannot get the app to perform the search functionality I'm looking for Searching for sub-parts in a word eg. Searching for "buntu" does not give me "ubuntu" Searching for similar words eg. Searching for "ubantu" would give "ubuntu" Any help would be very much appreciated.
[ "This is really about how you pass the query back to Haystack (and therefore to Solr). You can do a 'fuzzy' search in Solr/Lucene by using a ~ after the word:\nubuntu~\n\nwould return both buntu and ubantu. See the Lucene documentation on this.\nHow you pass this through via Haystack depends on how you're using it at the moment. Assuming you're using the default SearchForm, the best thing would be to either override the form's clean_q method to add the tilde on the end of every word in the search results, or override the search method to do the same thing there before passing it to the SearchQuerySet.\n" ]
[ 9 ]
[]
[]
[ "django", "django_haystack", "fuzzy_search", "python", "solr" ]
stackoverflow_0002110411_django_django_haystack_fuzzy_search_python_solr.txt
Q: Python zipfile hangs when writing I am trying to use the zipfile module in Python to create simple zip files: import zipfile files = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') zip_file_name = 'zipfile_test.zip' zfh = zipfile.ZipFile(zip_file_name, 'w') for file in files: print 'Archiving file %s' % file zfh.write(zip_file_name) zfh.close() The files a-h are in my working directory and are empty, use touch a b c d e f g h to test. After adding the first 7 items to the zip file, it hangs on the last one but keeps writing to the zip file until space is exhausted. This happens on the two systems I have tested it on, one with Python 2.4.3, the other with Python 2.6.2. If the number of files is less than 6 or 7, the zip file is created without any problems. Otherwise it fails after between 7-15 files and start writing junk to the end of the file. I have tried changing: zfh.write(zip_file_name) to: zfh.write(zip_file_name, zip_file_name, zipfile.ZIP_DEFLATED) which sometimes allows me to write a couple more files but inevitably fails as well. What am I doing wrong? A: You're putting the zip file into the zip file: zfh.write(zip_file_name) Should be: zfh.write(file)
Python zipfile hangs when writing
I am trying to use the zipfile module in Python to create simple zip files: import zipfile files = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') zip_file_name = 'zipfile_test.zip' zfh = zipfile.ZipFile(zip_file_name, 'w') for file in files: print 'Archiving file %s' % file zfh.write(zip_file_name) zfh.close() The files a-h are in my working directory and are empty, use touch a b c d e f g h to test. After adding the first 7 items to the zip file, it hangs on the last one but keeps writing to the zip file until space is exhausted. This happens on the two systems I have tested it on, one with Python 2.4.3, the other with Python 2.6.2. If the number of files is less than 6 or 7, the zip file is created without any problems. Otherwise it fails after between 7-15 files and start writing junk to the end of the file. I have tried changing: zfh.write(zip_file_name) to: zfh.write(zip_file_name, zip_file_name, zipfile.ZIP_DEFLATED) which sometimes allows me to write a couple more files but inevitably fails as well. What am I doing wrong?
[ "You're putting the zip file into the zip file:\nzfh.write(zip_file_name)\n\nShould be:\nzfh.write(file)\n\n" ]
[ 10 ]
[]
[]
[ "python", "python_zipfile" ]
stackoverflow_0002110739_python_python_zipfile.txt
Q: Django - How to model this correctly? I want to model the following situation. I have a table of items, and a table of players, and a player can have many items and have multiple copies of the same item. I can easily model the player having multiple items: class Item(models.Model): name = models.CharField(max_length = 200, blank = False) class Player(models.Model): items = models.ManyToManyField(Term) But I want to know the number of each item the player has i.e. each items frequency. How can I best model this in Django. (I've simplfied my actual models/problem to get my point accross :) ) Cheers, Pete A: Use an explicit through table with a quantity field. A: If the items are non-unique you can use a PlayerItem model and define it as a through model as Daniel Roseman suggested. To avoid saving the same item twice you can use unique_together: class Item(models.Model): name = models.CharField(max_length = 200, blank = False) class Player(models.Model): items = models.ManyToManyField(Item, through='PlayerItem') class PlayerItem(models.Model): player = models.ForeignKey(Player) item = models.ForeignKey(Item) quantity = models.IntegerField(default=1) class Meta: unique_together = ('player', 'item') However if the items will vary slightly or you need to store acquisition date for instance, you need a different setup: class Item(models.Model): name = models.CharField(max_length = 200, blank = False) class Player(models.Model): items = models.ManyToManyField(Item, through='PlayerItem') class PlayerItem(models.Model): player = models.ForeignKey(Player) item = models.ForeignKey(Item) acquired = models.DateTimeField(default=datetime.datetime.now) This time you will be saving duplicates of (player, item) tuple, one for each item. And then you can get the number of a specific item via count(). I would also like to note that you can't reach PlayerItem model from neither Item nor Player. In both cases you need to query PlayerItem directly to access the extra fields. (as documented)
Django - How to model this correctly?
I want to model the following situation. I have a table of items, and a table of players, and a player can have many items and have multiple copies of the same item. I can easily model the player having multiple items: class Item(models.Model): name = models.CharField(max_length = 200, blank = False) class Player(models.Model): items = models.ManyToManyField(Term) But I want to know the number of each item the player has i.e. each items frequency. How can I best model this in Django. (I've simplfied my actual models/problem to get my point accross :) ) Cheers, Pete
[ "Use an explicit through table with a quantity field.\n", "If the items are non-unique you can use a PlayerItem model and define it as a through model as Daniel Roseman suggested. To avoid saving the same item twice you can use unique_together:\nclass Item(models.Model):\n name = models.CharField(max_length = 200, blank = False)\n\nclass Player(models.Model):\n items = models.ManyToManyField(Item, through='PlayerItem')\n\nclass PlayerItem(models.Model):\n player = models.ForeignKey(Player)\n item = models.ForeignKey(Item)\n quantity = models.IntegerField(default=1)\n\n class Meta:\n unique_together = ('player', 'item')\n\nHowever if the items will vary slightly or you need to store acquisition date for instance, you need a different setup:\nclass Item(models.Model):\n name = models.CharField(max_length = 200, blank = False)\n\nclass Player(models.Model):\n items = models.ManyToManyField(Item, through='PlayerItem')\n\nclass PlayerItem(models.Model):\n player = models.ForeignKey(Player)\n item = models.ForeignKey(Item)\n acquired = models.DateTimeField(default=datetime.datetime.now)\n\nThis time you will be saving duplicates of (player, item) tuple, one for each item. And then you can get the number of a specific item via count().\nI would also like to note that you can't reach PlayerItem model from neither Item nor Player. In both cases you need to query PlayerItem directly to access the extra fields. (as documented)\n" ]
[ 5, 0 ]
[]
[]
[ "django", "model", "python" ]
stackoverflow_0002109293_django_model_python.txt
Q: Cleaning up nested for loops in python I have this code: def GetSteamAccts(): #Get list of steam logins on this computer. templist = [] Steamapp_Folders = ["C:\\Program Files (x86)\\Steam\\steamapps\\", "C:\\Program Files\\Steam\\steamapps\\"] #Check both of these directories. for SF_i in range(len(Steamapp_Folders)): if os.path.exists(Steamapp_Folders[SF_i]): #If the directory even exists... Steam_AppDir_Items = os.listdir(Steamapp_Folders[SF_i]) #List items under steam install directory. for S_AD_i in range(len(Steam_AppDir_Items)): #Make sure the user doesn't have any files in here... if os.path.isdir(Steamapp_Folders + Steam_AppDir_Items[S_AD_i]): #If our path is a directory... templist.append(Steam_AppDir_Items[S_AD_i]) #Add it to our list of logins. #(If some idiot puts extra folders in here, #it's their own damn fault when it shows on the list.) return templist #Return a (not so) properly filtered list of steam logins. My problem is, it looks AWFULLY ugly to me. I made a list of 2 paths (only 1 will ever exist), loop over those paths, then I have to get a list of the items in those paths, and then traverse those and filter out non-directories from that in order to get a pseudo-list of steam logins on a users computer. (Basically just getting a list of any existing directories (directories only!) under either of those 2 paths) Is there a shorter way of doing this (Other than condensing for loops into single lines?)? I would much rather be given an english-worded solution so I can put it together myself; rather than code. It's the only way I'll truly learn the proper way. Even a nice little hint or excerpt so I can figure it out on my own would be nice. And: Do lists in for loops always have to be traversed like: for x in range(len(somelist)): or is there something shorter than using range(len( ? A: for i in range(len(somelist)): something( somelist[i] ) should be written as for x in somelist: something( x ) Also you can write everything much shorter: def GetSteamAccts(): Steamapp_Folders = [f for f in ("C:\\Program Files (x86)\\Steam\\steamapps\\", "C:\\Program Files\\Steam\\steamapps\\") if os.path.isdir(f)] return [os.path.join(root, folder) for root in Steamapp_Folders for folder in os.listdir(root) if os.path.isdir( os.path.join(root, folder)) ] This looks cleaner and actually does what you wanted: ;-) def subfoldernames( root ): for folder in os.listdir(root): path = os.path.join(root, folder) if os.path.isdir(path): yield folder # just the name, not the path # same, just shorter: def subfoldernames( root ): # this returns a generator, written as a generator expression return ( folder for folder in os.listdir( root ) if os.path.isdir(os.path.join( root, folder )) ) def GetSteamAccts(): Steamapp_Folders = ("C:\\Program Files (x86)\\Steam\\steamapps\\", "C:\\Program Files\\Steam\\steamapps\\") for folder in Steamapp_Folders: if os.path.isdir(folder): # only the subfolders of the first path that exists are returned return list(subfoldernames( folder )) A: And: Do lists in for loops always have to be traversed like: for x in range(len(somelist)): or is there something shorter than using range(len( ? Sure there is, if you want to access the item only and you are not interested in its index you could do this: for x in somelist: If you want the index as well you could do this: for index, x in enumerate(somelist): A: You should lose the idea that a for loop always iterates over numbers from zero to something, like in other languages. You're just traversing lists, so use the for loop like this: def GetSteamAccts(): templist = [] Steamapp_Folders = ["C:\\Program Files (x86)\\Steam\\steamapps\\", "C:\\Program Files\\Steam\\steamapps\\"] #Check both of these directories. for steamapp_folder in Steamapp_Folders: if os.path.exists(steamapp_folder): for steam_appDir_item in os.listdir(steamapp_folder): if os.path.isdir(os.path.join(steamapp_folder, steam_appDir_item)): templist.append(steam_appDir_item) return templist In Python, a for loop goes over anything that can be iterated. For those few times where you actually need the numbers (and only the numbers), there's range. For those times where you need the numbers and the items, use this: for number, item in enumerate(my_list): When combining fors and ifs, you should also take a look at generator expressions and list comprehensions (see the docs). A: As others have mentioned, removing the assumption about integer indexes removes a large amount of the complexity. Going a bit further, you can replace patterns where you build up a list by appending in a for loop with a list comprehension. How much (or whether) these improve readability is debatable once you get into several layers of nesting, but they do make the code much more concise: def GetSteamAccts(): Steamapp_Folders = ["C:\\Program Files (x86)\\Steam\\steamapps\\", "C:\\Program Files\\Steam\\steamapps\\"] #Check both of these directories. return [ item for folder in Steamapp_Folders if os.path.exists(folder) for item in os.listdir(folder) if os.path.isdir(os.path.join(folder, item)) ] A: I'd suggest something like this: def check_subfolder(*args): for folder in args: for root, dirs, _ in os.walk(folder): return [os.path.join(root, i) for i in dirs] # since only 1 will ever exist it's just saves on all those if statements. Of course, first for loop could be moved out of the function, because it's not essential for the logic of the code. edit: updated to return subdirs of the first existing directory, as per question.
Cleaning up nested for loops in python
I have this code: def GetSteamAccts(): #Get list of steam logins on this computer. templist = [] Steamapp_Folders = ["C:\\Program Files (x86)\\Steam\\steamapps\\", "C:\\Program Files\\Steam\\steamapps\\"] #Check both of these directories. for SF_i in range(len(Steamapp_Folders)): if os.path.exists(Steamapp_Folders[SF_i]): #If the directory even exists... Steam_AppDir_Items = os.listdir(Steamapp_Folders[SF_i]) #List items under steam install directory. for S_AD_i in range(len(Steam_AppDir_Items)): #Make sure the user doesn't have any files in here... if os.path.isdir(Steamapp_Folders + Steam_AppDir_Items[S_AD_i]): #If our path is a directory... templist.append(Steam_AppDir_Items[S_AD_i]) #Add it to our list of logins. #(If some idiot puts extra folders in here, #it's their own damn fault when it shows on the list.) return templist #Return a (not so) properly filtered list of steam logins. My problem is, it looks AWFULLY ugly to me. I made a list of 2 paths (only 1 will ever exist), loop over those paths, then I have to get a list of the items in those paths, and then traverse those and filter out non-directories from that in order to get a pseudo-list of steam logins on a users computer. (Basically just getting a list of any existing directories (directories only!) under either of those 2 paths) Is there a shorter way of doing this (Other than condensing for loops into single lines?)? I would much rather be given an english-worded solution so I can put it together myself; rather than code. It's the only way I'll truly learn the proper way. Even a nice little hint or excerpt so I can figure it out on my own would be nice. And: Do lists in for loops always have to be traversed like: for x in range(len(somelist)): or is there something shorter than using range(len( ?
[ "for i in range(len(somelist)):\n something( somelist[i] )\n\nshould be written as\nfor x in somelist: \n something( x )\n\nAlso you can write everything much shorter:\ndef GetSteamAccts():\n Steamapp_Folders = [f for f in (\"C:\\\\Program Files (x86)\\\\Steam\\\\steamapps\\\\\", \n \"C:\\\\Program Files\\\\Steam\\\\steamapps\\\\\") \n if os.path.isdir(f)]\n return [os.path.join(root, folder) \n for root in Steamapp_Folders \n for folder in os.listdir(root) \n if os.path.isdir( os.path.join(root, folder)) ]\n\nThis looks cleaner and actually does what you wanted: ;-)\ndef subfoldernames( root ):\n for folder in os.listdir(root):\n path = os.path.join(root, folder)\n if os.path.isdir(path):\n yield folder # just the name, not the path\n\n# same, just shorter:\ndef subfoldernames( root ):\n # this returns a generator, written as a generator expression\n return ( folder for folder in os.listdir( root ) \n if os.path.isdir(os.path.join( root, folder )) )\n\ndef GetSteamAccts():\n Steamapp_Folders = (\"C:\\\\Program Files (x86)\\\\Steam\\\\steamapps\\\\\", \n \"C:\\\\Program Files\\\\Steam\\\\steamapps\\\\\")\n for folder in Steamapp_Folders:\n if os.path.isdir(folder):\n # only the subfolders of the first path that exists are returned\n return list(subfoldernames( folder )) \n\n", "\nAnd: Do lists in for loops always have\n to be traversed like:\nfor x in range(len(somelist)): or is\n there something shorter than using\n range(len( ?\n\nSure there is, if you want to access the item only and you are not interested in its index you could do this:\nfor x in somelist:\n\nIf you want the index as well you could do this:\nfor index, x in enumerate(somelist):\n\n", "You should lose the idea that a for loop always iterates over numbers from zero to something, like in other languages. You're just traversing lists, so use the for loop like this:\ndef GetSteamAccts():\n templist = []\n Steamapp_Folders = [\"C:\\\\Program Files (x86)\\\\Steam\\\\steamapps\\\\\", \"C:\\\\Program Files\\\\Steam\\\\steamapps\\\\\"] #Check both of these directories.\n for steamapp_folder in Steamapp_Folders:\n if os.path.exists(steamapp_folder):\n for steam_appDir_item in os.listdir(steamapp_folder):\n if os.path.isdir(os.path.join(steamapp_folder, steam_appDir_item)):\n templist.append(steam_appDir_item)\n return templist\n\nIn Python, a for loop goes over anything that can be iterated. For those few times where you actually need the numbers (and only the numbers), there's range. For those times where you need the numbers and the items, use this:\nfor number, item in enumerate(my_list):\n\nWhen combining fors and ifs, you should also take a look at generator expressions and list comprehensions (see the docs).\n", "As others have mentioned, removing the assumption about integer indexes removes a large amount of the complexity. \nGoing a bit further, you can replace patterns where you build up a list by appending in a for loop with a list comprehension. How much (or whether) these improve readability is debatable once you get into several layers of nesting, but they do make the code much more concise:\ndef GetSteamAccts():\n Steamapp_Folders = [\"C:\\\\Program Files (x86)\\\\Steam\\\\steamapps\\\\\", \"C:\\\\Program Files\\\\Steam\\\\steamapps\\\\\"] #Check both of these directories.\n return [ item for folder in Steamapp_Folders if os.path.exists(folder)\n for item in os.listdir(folder) if os.path.isdir(os.path.join(folder, item)) ]\n\n", "I'd suggest something like this:\ndef check_subfolder(*args):\n for folder in args:\n for root, dirs, _ in os.walk(folder):\n return [os.path.join(root, i) for i in dirs] # since only 1 will ever exist\n\nit's just saves on all those if statements. Of course, first for loop could be moved out of the function, because it's not essential for the logic of the code.\nedit: updated to return subdirs of the first existing directory, as per question.\n" ]
[ 9, 5, 4, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002110753_python.txt
Q: Looping over datasets in Python I'm trying to write a Python script that will perform the same action on multiple databases. There are too many for me to input them by hand, so I'd like to write a script that will loop over them. Right now, I've gotten as far as the following before getting stuck: countylist = ['01001','01002','01003','01004'] for item in countylist: # Local variables... file_1 = "F:\\file1.shp" file_2 = "F:\\fileCOUNTYLIST.shp" output_2 = "F:\\outputCOUNTYLIST.shp" Basically, I need the items to go where I wrote COUNTYLIST (so the program would call "F:\file01001.shp", "F:\file01002.shp", etc). I couldn't find an answer online. How do I do this? Thanks a lot! A: countylist = ['01001','01002','01003','01004'] file_1 = "F:\\file1.shp" for item in countylist: file_2 = "F:\\file%s.shp" % item output_2 = "F:\\output%s.shp" % item # Here, I do my commands that are dependent on # the name of the file changing. # Here, outside of the loop, file_2 and output_2 have the last # value assigned to them. A: Simple concatenation will do: for item in countylist: file_2 = 'F:\\file' + item + '.shp' output_2 = 'F:\\output' + item + '.shp' A: How about: countylist = ['01001','01002','01003','01004'] for item in countylist: # Local variables... file_1 = "F:\\file1.shp" file_2 = "F:\\file%s.shp" % countylist output_2 = "F:\\output%s.shp" % countylist A: Nobody's used this variation yet, how about the format method for strings... countylist = ['01001','01002','01003','01004'] for item in countylist: file_1 = "F:\\file1.shp" file_2 = "F:\\file{0}.shp".format(item) output_2 = "F:\\output{0}.shp".format(item) This style is more flexible because you can not only use the numbered arguments, but also keywords like file_2="F:\\file{countylist}.shp".format(countylist=item) from the manual, "This method of string formatting is the new standard in Python 3.0, and should be preferred to the % formatting described in String Formatting Operations in new code." so it's good to know. Important Note: I think this method is only available in Python 2.6 and above!
Looping over datasets in Python
I'm trying to write a Python script that will perform the same action on multiple databases. There are too many for me to input them by hand, so I'd like to write a script that will loop over them. Right now, I've gotten as far as the following before getting stuck: countylist = ['01001','01002','01003','01004'] for item in countylist: # Local variables... file_1 = "F:\\file1.shp" file_2 = "F:\\fileCOUNTYLIST.shp" output_2 = "F:\\outputCOUNTYLIST.shp" Basically, I need the items to go where I wrote COUNTYLIST (so the program would call "F:\file01001.shp", "F:\file01002.shp", etc). I couldn't find an answer online. How do I do this? Thanks a lot!
[ "countylist = ['01001','01002','01003','01004']\nfile_1 = \"F:\\\\file1.shp\"\nfor item in countylist:\n file_2 = \"F:\\\\file%s.shp\" % item\n output_2 = \"F:\\\\output%s.shp\" % item\n # Here, I do my commands that are dependent on\n # the name of the file changing.\n\n# Here, outside of the loop, file_2 and output_2 have the last\n# value assigned to them.\n\n", "Simple concatenation will do:\nfor item in countylist:\n file_2 = 'F:\\\\file' + item + '.shp'\n output_2 = 'F:\\\\output' + item + '.shp'\n\n", "How about:\ncountylist = ['01001','01002','01003','01004']\nfor item in countylist:\n\n # Local variables...\n file_1 = \"F:\\\\file1.shp\"\n file_2 = \"F:\\\\file%s.shp\" % countylist\n output_2 = \"F:\\\\output%s.shp\" % countylist\n\n", "Nobody's used this variation yet, how about the format method for strings...\ncountylist = ['01001','01002','01003','01004']\nfor item in countylist:\n file_1 = \"F:\\\\file1.shp\"\n file_2 = \"F:\\\\file{0}.shp\".format(item)\n output_2 = \"F:\\\\output{0}.shp\".format(item)\n\nThis style is more flexible because you can not only use the numbered arguments, but also keywords like\n file_2=\"F:\\\\file{countylist}.shp\".format(countylist=item)\n\nfrom the manual, \"This method of string formatting is the new standard in Python 3.0, and should be preferred to the % formatting described in String Formatting Operations in new code.\" so it's good to know.\nImportant Note: I think this method is only available in Python 2.6 and above!\n" ]
[ 3, 1, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0002111072_python_string.txt
Q: create a grayscale image I am reading binary data from one file that specifies intensity values across x and y coordinates (not a open-source image format) and want to convert it to a PNG image (or other widely supported format). I have the data loaded into an array (using the array module) where each element is a integer from 0 to 255. To save this to a PNG I can create a 3 item tuple of each element (x) like so: t = (x, x, x) add apply it across the array using the map(), then save the image using putdata(). However, the conversion to the array of tuples takes a long time (few minutes). Is there a way to specify the rgb value using only one integer (not a tuple). I guessing an alternative would be to use NumPy, but I don't know where to start, so any help in this regard would also be appreciated. Thanks in advance for the help. A: When you create the new image, give it the mode L: im = Image.new('L', size) im.putdata([x1, x2, x3, ...]) Where data is a list of values not tuples. A: There are several ways to do this, but if you already have the data in memory, look into using Image.frombuffer or Image.fromstring using the 'L' mode (for 8-bit greyscale data). A: Would im.putpixel(xy, colour) be what you are looking for?
create a grayscale image
I am reading binary data from one file that specifies intensity values across x and y coordinates (not a open-source image format) and want to convert it to a PNG image (or other widely supported format). I have the data loaded into an array (using the array module) where each element is a integer from 0 to 255. To save this to a PNG I can create a 3 item tuple of each element (x) like so: t = (x, x, x) add apply it across the array using the map(), then save the image using putdata(). However, the conversion to the array of tuples takes a long time (few minutes). Is there a way to specify the rgb value using only one integer (not a tuple). I guessing an alternative would be to use NumPy, but I don't know where to start, so any help in this regard would also be appreciated. Thanks in advance for the help.
[ "When you create the new image, give it the mode L:\nim = Image.new('L', size)\nim.putdata([x1, x2, x3, ...])\n\nWhere data is a list of values not tuples.\n", "There are several ways to do this, but if you already have the data in memory, look into using Image.frombuffer or Image.fromstring using the 'L' mode (for 8-bit greyscale data).\n", "Would im.putpixel(xy, colour) be what you are looking for?\n" ]
[ 22, 3, 0 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0002111150_python_python_imaging_library.txt
Q: Django template ifequal tag I'm using an ifequal tag in my django template inside a loop where atleast one of the items should equal the other at some point in the loop but for some reason it never displays what it should. I was wondering if there are any weird cases that i should know about. I have a list of int city ID's that should be checked as check boxes. so as i loop through all of the cities, for each one i loop through the ones that are supposed to be checked to see if the equal anywhere in the list. But for whatever reason none of them ever match. I verified that the data is right using the django shell, so i know its there, i think i'm missing some small detail with how i'm using it. Heres the code: View: def editprof(request): try: if request.session['id']: loggedin = True except KeyError: loggedin = False try: citylist = CityList.objects.all() userid = request.session['id'] user = MemberProfile.objects.get(pk=userid) p = decrypt_pwd(user.Password) pflags = user.PublicVisibleFlags log_val(pflags[0]) pflags = pflags.split(',') mflags = user.MemberVisibleFlags log_val(mflags[0]) mflags = mflags.split(',') return render_to_response('editprof.html', {'user':user, 'p':p, 'loggedin':loggedin, 'citylist':citylist, 'pflags':pflags, 'mflags':mflags}) except KeyError: return HttpResponse('You must be logged in to view this page!') except MemberProfile.DoesNotExist: return HttpResponse('DatabaseError') Template clip: {% for city in citylist %} <tr> <td><input type='checkbox' name='public' value='{{ city.id }}' {% for id in pflags %}{% ifequal id city.id %}checked{% endifequal %}{% endfor %} /></td> <td><input type='checkbox' name='private' value='{{ city.id }}' {% for id in mflags %}{% ifequal id city.id %}checked{% endifequal %}{% endfor %} /></td> <td>{{ city.CityName }}</td> </tr> {% endfor %} MemberProfile Model: class MemberProfile(models.Model): Username = models.CharField(max_length=12,unique=True) Password = models.CharField(max_length=12) SecurityLevel = models.IntegerField() AccountExpirationDate = models.DateField() CityList = models.TextField() Address1 = models.CharField(max_length=30) Address2 = models.CharField(max_length=30) City = models.CharField(max_length=20) State = models.CharField(max_length=2) Zip = models.CharField(max_length=10) Email = models.EmailField() AltEmail = models.EmailField() HomePhone = models.CharField(max_length=18) BusinessPhone = models.CharField(max_length=18) Fax = models.CharField(max_length=18) Cell = models.CharField(max_length=18) AltPhone = models.CharField(max_length=18) PublicVisibleFlags = models.TextField() MemberVisibleFlags = models.TextField() WhoAmI = models.TextField() CompanyName = models.CharField(max_length=30) ServicesOffered = models.TextField() NumberOfUnits = models.IntegerField() SCREIAOffice = models.CharField(max_length=10) LastModifyBy = models.CharField(max_length=12) LastModifyDate = models.DateField(auto_now=True) def __unicode__(self): return self.Username Console Test: >>> from screia.core.models import MemberProfile >>> user = MemberProfile.objects.get(pk=1) >>> pflags = user.PublicVisibleFlags.split(',') >>> print pflags [u'1', u'4', u'7', u'12', u'25'] >>> i = 0 >>> while i < len(pflags): ... pflags[i] = int(pflags[i]) ... i+=1 ... >>> print pflags [1, 4, 7, 12, 25] Log Value: 1 A: {% for id in pflags %}{% ifequal id city.id %} ... {% endfor %} Could it be that id is a string and city.id is an integer? A: The code you've posted would go into infinite loops if either pflags or mflags were non-empty. Consider e.g. this snippet from your code: i = 0 while i < len(pflags): pflags[i] = int(pflags[i]) that's it -- end of loop -- no incrementing of i whatsoever. This is an infinite loop unless len(pflags) is 0! Therefore, either you've posted code different from what you're using (in which case it's pretty peculiar for you to expect help;-), or both of those are indeed empty and therefore the inner loops in the template execute 0 times each. I suspect the second possibility obtains, but of course I can't see those xxxFlags values to confirm my suspicion (you can, and should: log them, for Pete's sake!-).
Django template ifequal tag
I'm using an ifequal tag in my django template inside a loop where atleast one of the items should equal the other at some point in the loop but for some reason it never displays what it should. I was wondering if there are any weird cases that i should know about. I have a list of int city ID's that should be checked as check boxes. so as i loop through all of the cities, for each one i loop through the ones that are supposed to be checked to see if the equal anywhere in the list. But for whatever reason none of them ever match. I verified that the data is right using the django shell, so i know its there, i think i'm missing some small detail with how i'm using it. Heres the code: View: def editprof(request): try: if request.session['id']: loggedin = True except KeyError: loggedin = False try: citylist = CityList.objects.all() userid = request.session['id'] user = MemberProfile.objects.get(pk=userid) p = decrypt_pwd(user.Password) pflags = user.PublicVisibleFlags log_val(pflags[0]) pflags = pflags.split(',') mflags = user.MemberVisibleFlags log_val(mflags[0]) mflags = mflags.split(',') return render_to_response('editprof.html', {'user':user, 'p':p, 'loggedin':loggedin, 'citylist':citylist, 'pflags':pflags, 'mflags':mflags}) except KeyError: return HttpResponse('You must be logged in to view this page!') except MemberProfile.DoesNotExist: return HttpResponse('DatabaseError') Template clip: {% for city in citylist %} <tr> <td><input type='checkbox' name='public' value='{{ city.id }}' {% for id in pflags %}{% ifequal id city.id %}checked{% endifequal %}{% endfor %} /></td> <td><input type='checkbox' name='private' value='{{ city.id }}' {% for id in mflags %}{% ifequal id city.id %}checked{% endifequal %}{% endfor %} /></td> <td>{{ city.CityName }}</td> </tr> {% endfor %} MemberProfile Model: class MemberProfile(models.Model): Username = models.CharField(max_length=12,unique=True) Password = models.CharField(max_length=12) SecurityLevel = models.IntegerField() AccountExpirationDate = models.DateField() CityList = models.TextField() Address1 = models.CharField(max_length=30) Address2 = models.CharField(max_length=30) City = models.CharField(max_length=20) State = models.CharField(max_length=2) Zip = models.CharField(max_length=10) Email = models.EmailField() AltEmail = models.EmailField() HomePhone = models.CharField(max_length=18) BusinessPhone = models.CharField(max_length=18) Fax = models.CharField(max_length=18) Cell = models.CharField(max_length=18) AltPhone = models.CharField(max_length=18) PublicVisibleFlags = models.TextField() MemberVisibleFlags = models.TextField() WhoAmI = models.TextField() CompanyName = models.CharField(max_length=30) ServicesOffered = models.TextField() NumberOfUnits = models.IntegerField() SCREIAOffice = models.CharField(max_length=10) LastModifyBy = models.CharField(max_length=12) LastModifyDate = models.DateField(auto_now=True) def __unicode__(self): return self.Username Console Test: >>> from screia.core.models import MemberProfile >>> user = MemberProfile.objects.get(pk=1) >>> pflags = user.PublicVisibleFlags.split(',') >>> print pflags [u'1', u'4', u'7', u'12', u'25'] >>> i = 0 >>> while i < len(pflags): ... pflags[i] = int(pflags[i]) ... i+=1 ... >>> print pflags [1, 4, 7, 12, 25] Log Value: 1
[ "{% for id in pflags %}{% ifequal id city.id %} ... {% endfor %}\n\nCould it be that id is a string and city.id is an integer?\n", "The code you've posted would go into infinite loops if either pflags or mflags were non-empty.\nConsider e.g. this snippet from your code:\n i = 0\n while i < len(pflags):\n pflags[i] = int(pflags[i])\n\nthat's it -- end of loop -- no incrementing of i whatsoever. This is an infinite loop unless len(pflags) is 0!\nTherefore, either you've posted code different from what you're using (in which case it's pretty peculiar for you to expect help;-), or both of those are indeed empty and therefore the inner loops in the template execute 0 times each.\nI suspect the second possibility obtains, but of course I can't see those xxxFlags values to confirm my suspicion (you can, and should: log them, for Pete's sake!-).\n" ]
[ 5, 1 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0002099064_django_django_templates_python.txt
Q: lxml and loops to create xml rss in python I have been using lxml to create the xml of rss feed. But I am having trouble with the tags and cant really figure out how to to add a dynamic number of elements. Given that lxml seems to just have functions as parameters of functions, I cant seem to figure out how to loop for a dynamic number of items without remaking the entire page. rss = page = ( E.rss( E.channel( E.title("Page Title"), E.link(""), E.description(""), E.item( E.title("Hello!!!!!!!!!!!!!!!!!!!!! "), E.link("htt://"), E.description("this is a"), ), ) ) ) A: Jason has answered your question; but – just FYI – you can pass any number of function arguments dynamically as a list: E.channel(*args), where args would be [E.title(...), E.link(...),...]. Similarly, keyword arguments can be passed using dict and two stars (**). See documentation. A: This lxml tutorial says: To create child elements and add them to a parent element, you can use the append() method: >>> root.append( etree.Element("child1") ) However, this is so common that there is a shorter and much more efficient way to do this: the SubElement factory. It accepts the same arguments as the Element factory, but additionally requires the parent as first argument: >>> child2 = etree.SubElement(root, "child2") >>> child3 = etree.SubElement(root, "child3") So you should be able to create the document, then say channel = rss.find("channel") and use either of the above methods to add more items to the channel element. A: channel = E.channel(E.title("Page Title"), E.link(""),E.description("")) for (title, link, description) in container: try: mytitle = E.title(title) mylink = E.link(link) mydesc = E.description(description) item = E.item(mytitle, mylink, mydesc) except ValueError: print repr(title) print repr(link) print repr(description) raise channel.append(item) top = page = E.top(channel)
lxml and loops to create xml rss in python
I have been using lxml to create the xml of rss feed. But I am having trouble with the tags and cant really figure out how to to add a dynamic number of elements. Given that lxml seems to just have functions as parameters of functions, I cant seem to figure out how to loop for a dynamic number of items without remaking the entire page. rss = page = ( E.rss( E.channel( E.title("Page Title"), E.link(""), E.description(""), E.item( E.title("Hello!!!!!!!!!!!!!!!!!!!!! "), E.link("htt://"), E.description("this is a"), ), ) ) )
[ "Jason has answered your question; but – just FYI – you can pass any number of function arguments dynamically as a list: E.channel(*args), where args would be [E.title(...), E.link(...),...]. Similarly, keyword arguments can be passed using dict and two stars (**). See documentation.\n", "This lxml tutorial says:\n\nTo create child elements and add them to a parent element, you can use the append() method:\n>>> root.append( etree.Element(\"child1\") )\n\nHowever, this is so common that there is a shorter and much more efficient way to do this: the SubElement factory. It accepts the same arguments as the Element factory, but additionally requires the parent as first argument:\n>>> child2 = etree.SubElement(root, \"child2\")\n>>> child3 = etree.SubElement(root, \"child3\")\n\n\nSo you should be able to create the document, then say channel = rss.find(\"channel\") and use either of the above methods to add more items to the channel element.\n", "channel = E.channel(E.title(\"Page Title\"), E.link(\"\"),E.description(\"\"))\n for (title, link, description) in container:\n try:\n mytitle = E.title(title)\n mylink = E.link(link)\n mydesc = E.description(description)\n item = E.item(mytitle, mylink, mydesc)\n except ValueError:\n print repr(title)\n print repr(link)\n print repr(description)\n raise\n channel.append(item)\n top = page = E.top(channel)\n\n" ]
[ 6, 5, 3 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0002104751_lxml_python.txt
Q: Are there any declaration keywords in Python? Are there any declaration keywords in Python, like local, global, private, public etc.? I know that variable types are not specified in Python; but how do you know if the code x = 5 creates a new variable, or sets an existing one? A: I really like the understanding that Van Gale is providing, but it doesn't really answer the question of, "how do you know if this statement: creates a new variable or sets an existing variable?" If you want to know how to recognize it when looking at code, you simply look for a previous assignment. Avoid global variables, which is good practice anyway, and you'll be all set. Programmatically, you could try to reference the variable, and see if you get a "Name Error" exception try: x except NameError: # x doesn't exist, do something else: # x exists, do something else I've never needed to do this... and I doubt you will really need to either. soapbox alert !!! Even though Python looks kinda loosey-goosey to someone who is used to having to type the class name (or type) over and over and over... it's actually exactly as strict as you want to make it. If you want strict types, you would do it explictly: assert(isinstance(variable, type)) Decorators exist to do this in a very convenient way for function calls... Before long, you might just come to the conclusion that static type checking (at compile time) doesn't actually make your code that much better. There's only a small benefit for the cost of having to have redundant type information all over the place. I'm currently working in actionscript, and typing things like: var win:ThingPicker = PopUpManager.createPopUp(fEmotionsButton, ThingPicker, false) as ThingPicker; which in python would look like: win = createPopup(parent, ThingPicker) And I can see, looking at the actionscript code, that there's simply no benefit to the static type-checking. The variable's lifetime is so short that I would have to be completely drunk to do the wrong thing with it... and have the compiler save me by pointing out a type error. A: An important thing to understand about Python is there are no variables, only "names". In your example, you have an object "5" and you are creating a name "x" that references the object "5". If later you do: x = "Some string" that is still perfectly valid. Name "x" is now pointing to object "Some string". It's not a conflict of types because the name itself doesn't have a type, only the object. If you try x = 5 + "Some string" you will get a type error because you can't add two incompatible types. In other words, it's not type free. Python objects are strongly typed. Here are some very good discussions about Python typing: Strong Typing vs. Strong Testing Typing: Strong vs. Weak, Static vs. Dynamic Edit: to finish tying this in with your question, a name can reference an existing object or a new one. # Create a new int object >>> x = 500 # Another name to same object >>> y = x # Create another new int object >>> x = 600 # y still references original object >>> print y 500 # This doesn't update x, it creates a new object and x becomes # a reference to the new int object (which is int because that # is the defined result of adding to int objects). >>> x = x + y >>> print x 1100 # Make original int object 500 go away >>> del y Edit 2: The most complete discussion of the difference between mutable objects (that can be changed) and immutable objects (that cannot be changed) in the the official documentation of the Python Data Model. A: It's worth mentioning that there is a global keyword, so if you want to refer to the global x: x = 4 def foo(): x = 7 # x is local to your function You need to do this: x = 4 def foo(): global x # let python know you want to use the top-level x x = 7 A: It doesn't look like the asker is trying to assign a type, just to specify that this a declaration, not an assignment. Looks like you are looking for something like javascript has: var x = 5; The concept of the declaration keyword in javascript is to ensure that you are making a new object in the current scope and are not simply changing some other variable of the same name. Python does not have this feature. The programmer has to make sure that he or she is not reassigning preexisting names. A: I just realized there's a more direct answer too: x = 5 def test(): print 'x' in globals() if __name__ == "__main__": test() So if 'variablename' in globals(): the statement is an assignment otherwise the statement is a declaration
Are there any declaration keywords in Python?
Are there any declaration keywords in Python, like local, global, private, public etc.? I know that variable types are not specified in Python; but how do you know if the code x = 5 creates a new variable, or sets an existing one?
[ "I really like the understanding that Van Gale is providing, but it doesn't really answer the question of, \"how do you know if this statement: creates a new variable or sets an existing variable?\"\nIf you want to know how to recognize it when looking at code, you simply look for a previous assignment. Avoid global variables, which is good practice anyway, and you'll be all set.\nProgrammatically, you could try to reference the variable, and see if you get a \"Name Error\" exception\ntry:\n x\nexcept NameError:\n # x doesn't exist, do something\nelse:\n # x exists, do something else\n\nI've never needed to do this... and I doubt you will really need to either. \nsoapbox alert !!!\nEven though Python looks kinda loosey-goosey to someone who is used to having to type the class name (or type) over and over and over... it's actually exactly as strict as you want to make it.\nIf you want strict types, you would do it explictly:\nassert(isinstance(variable, type))\n\nDecorators exist to do this in a very convenient way for function calls...\nBefore long, you might just come to the conclusion that static type checking (at compile time) doesn't actually make your code that much better. There's only a small benefit for the cost of having to have redundant type information all over the place.\nI'm currently working in actionscript, and typing things like:\nvar win:ThingPicker = PopUpManager.createPopUp(fEmotionsButton, \n ThingPicker, false) as ThingPicker;\n\nwhich in python would look like:\nwin = createPopup(parent, ThingPicker)\n\nAnd I can see, looking at the actionscript code, that there's simply no benefit to the static type-checking. The variable's lifetime is so short that I would have to be completely drunk to do the wrong thing with it... and have the compiler save me by pointing out a type error. \n", "An important thing to understand about Python is there are no variables, only \"names\".\nIn your example, you have an object \"5\" and you are creating a name \"x\" that references the object \"5\".\nIf later you do:\nx = \"Some string\"\n\nthat is still perfectly valid. Name \"x\" is now pointing to object \"Some string\".\nIt's not a conflict of types because the name itself doesn't have a type, only the object.\nIf you try x = 5 + \"Some string\" you will get a type error because you can't add two incompatible types.\nIn other words, it's not type free. Python objects are strongly typed.\nHere are some very good discussions about Python typing:\n\nStrong Typing vs. Strong Testing\nTyping: Strong vs. Weak, Static vs. Dynamic\n\nEdit: to finish tying this in with your question, a name can reference an existing object or a new one.\n# Create a new int object\n>>> x = 500\n# Another name to same object\n>>> y = x\n# Create another new int object \n>>> x = 600\n# y still references original object\n>>> print y\n500\n# This doesn't update x, it creates a new object and x becomes\n# a reference to the new int object (which is int because that\n# is the defined result of adding to int objects).\n>>> x = x + y\n>>> print x\n1100\n# Make original int object 500 go away\n>>> del y\n\nEdit 2: The most complete discussion of the difference between mutable objects (that can be changed) and immutable objects (that cannot be changed) in the the official documentation of the Python Data Model.\n", "It's worth mentioning that there is a global keyword, so if you want to refer to the global x:\nx = 4\ndef foo():\n x = 7 # x is local to your function\n\nYou need to do this:\nx = 4\ndef foo():\n global x # let python know you want to use the top-level x\n x = 7\n\n", "It doesn't look like the asker is trying to assign a type, just to specify that this a declaration, not an assignment.\nLooks like you are looking for something like javascript has:\nvar x = 5;\n\nThe concept of the declaration keyword in javascript is to ensure that you are making a new object in the current scope and are not simply changing some other variable of the same name.\nPython does not have this feature. The programmer has to make sure that he or she is not reassigning preexisting names.\n", "I just realized there's a more direct answer too:\nx = 5\n\ndef test():\n print 'x' in globals()\n\nif __name__ == \"__main__\":\n test()\n\nSo if 'variablename' in globals():\n the statement is an assignment\notherwise\n the statement is a declaration\n" ]
[ 15, 14, 12, 7, 0 ]
[]
[]
[ "python", "variables" ]
stackoverflow_0000571514_python_variables.txt
Q: Hooking into django views Simple question. I have bunch of django views. Is there a way to tell django that for each view, use foo(view) instead? Example: Instead of writing @foo @bar @baz def view(request): # do something all the time, I'd like to have def view(request): markers = ['some', 'markers'] and hook this into django: for view in all_the_views_in_my_app: view = do_something_based_on_the_marker(view) I'd like to have this done at server startup time. Any thoughts? A: Depending on what you want to do (or achieve), you can write a custom middelware and implement the method process_view (and/or any other method that you need): process_view() is called just before Django calls the view. It should return either None or an HttpResponse object. If it returns None, Django will continue processing this request, executing any other process_view() middleware and, then, the appropriate view. If it returns an HttpResponse object, Django won't bother calling ANY other request, view or exception middleware, or the appropriate view; it'll return that HttpResponse. Response middleware is always called on every response. A: I don't know why you want to do this. I don't know either why you don't want to use decorators. But you could use this ugly (and likely error prone) hack as a start: def view(request): pass view.markers = ['some', 'markers'] some other place: from app import views [x for x in views.__dict__.values() if hasattr(x,'markers')]
Hooking into django views
Simple question. I have bunch of django views. Is there a way to tell django that for each view, use foo(view) instead? Example: Instead of writing @foo @bar @baz def view(request): # do something all the time, I'd like to have def view(request): markers = ['some', 'markers'] and hook this into django: for view in all_the_views_in_my_app: view = do_something_based_on_the_marker(view) I'd like to have this done at server startup time. Any thoughts?
[ "Depending on what you want to do (or achieve), you can write a custom middelware and implement the method process_view (and/or any other method that you need):\n\nprocess_view() is called just before Django calls the view. It should return either None or an HttpResponse object. If it returns None, Django will continue processing this request, executing any other process_view() middleware and, then, the appropriate view. If it returns an HttpResponse object, Django won't bother calling ANY other request, view or exception middleware, or the appropriate view; it'll return that HttpResponse. Response middleware is always called on every response.\n\n", "I don't know why you want to do this. I don't know either why you don't want to use decorators. But you could use this ugly (and likely error prone) hack as a start:\ndef view(request):\n pass\nview.markers = ['some', 'markers']\n\nsome other place:\nfrom app import views\n[x for x in views.__dict__.values() if hasattr(x,'markers')]\n\n" ]
[ 2, 1 ]
[]
[]
[ "django", "django_views", "hook", "python" ]
stackoverflow_0002110399_django_django_views_hook_python.txt
Q: python virtual environment on source control I have created a python web virtual environment contains all django, pylons related packages. I use the host ubuntu desktop PC at home and I have ubuntu virtual machine running on windows PC laptop. Both the operating systems are linux only. I will be using the same environment for production that will be ubuntu server. Is it possible to store the my python virtual environment to the version control and use the same files for ubuntu desktop, laptop ubuntu desktop VM and ubuntu server in production? A: You might want to look into virtualenv. This will allow you to set up your working environment, 'freeze' the list of packages that are needed to replicate it, and store that list of requirements in version control so that others can check it out and rebuild the environment with a single step. A: You can but you don't really need 'version' control for that. You need to setup your environment. It's a one time job to setup your environment. After that you'll just use it. Why version control it? A: If you already have a VM set up, you can export it so that others can copy it and start their own instance with everything installed. VirtualBox and VMWare both support VMDK images, and Xen has its own type of VM images. That is probably not a solution for setting up servers. I like using Turnkey Linux's appliances for development/staging/deployment servers. They are solid Ubuntu servers preconfigured for a particular application: Django, Rails, LAMP, etc. They come as Ubuntu LiveCD ISO files (for installation) or as virtual machine VMDK packages, and can be deployed to Amazon EC2. You might still have to customize that environment further prior to deploying and testing your code, but it can get you further along than a bare Linux server.
python virtual environment on source control
I have created a python web virtual environment contains all django, pylons related packages. I use the host ubuntu desktop PC at home and I have ubuntu virtual machine running on windows PC laptop. Both the operating systems are linux only. I will be using the same environment for production that will be ubuntu server. Is it possible to store the my python virtual environment to the version control and use the same files for ubuntu desktop, laptop ubuntu desktop VM and ubuntu server in production?
[ "You might want to look into virtualenv. This will allow you to set up your working environment, 'freeze' the list of packages that are needed to replicate it, and store that list of requirements in version control so that others can check it out and rebuild the environment with a single step.\n", "You can but you don't really need 'version' control for that. You need to setup your environment. It's a one time job to setup your environment. After that you'll just use it. Why version control it? \n", "If you already have a VM set up, you can export it so that others can copy it and start their own instance with everything installed. VirtualBox and VMWare both support VMDK images, and Xen has its own type of VM images.\nThat is probably not a solution for setting up servers. I like using Turnkey Linux's appliances for development/staging/deployment servers. They are solid Ubuntu servers preconfigured for a particular application: Django, Rails, LAMP, etc. They come as Ubuntu LiveCD ISO files (for installation) or as virtual machine VMDK packages, and can be deployed to Amazon EC2. You might still have to customize that environment further prior to deploying and testing your code, but it can get you further along than a bare Linux server.\n" ]
[ 2, 0, 0 ]
[]
[]
[ "installation", "linux", "python", "virtualenv" ]
stackoverflow_0002108105_installation_linux_python_virtualenv.txt
Q: Am I doing these unit tests right? I'm new to unit tests for my own projects, so this is my first attempt to write a unit test from scratch. I'm using python, and the unittest module. The TodoList class being tested here is a wrapper for actual lists, with a few extra methods for stuff like saving to disc. It also defines a few methods for getting items by their ID in the list (which isn't the same as the list index). Tests (I've cut out a few helper methods, and a good few tests for the sake of not having people to scroll forever): class TodoListTests(unittest.TestCase): def setUp(self): self.testdata = open("./testdata.json", "r") self.testdata_text = self.testdata.read() self.testdata.close() def tearDown(self): try: os.remove("./todo.json") except OSError: # File not created, no need to delete. pass def create_todolist_and_safe_list(self): self.create_data_file() self.todolist = todolist.TodoList("./todo.json") self.list = json.loads(self.testdata_text) def create_data_file(self): datafile = open("./todo.json", "w") datafile.write(self.testdata_text) datafile.close() # Snip out a few more helper methods def test_loop(self): self.create_todolist_and_safe_list() test_list = [] for item in self.todolist: test_list.append(item) self.assertEquals(test_list, self.list) def test_save(self): self.create_todolist_and_safe_list() self.todolist.save() newfile_text = self.get_data_file_as_string() self.assertEquals(newfile_text, self.testdata_text) # Snip out the rest of the tests. Full link to source A: I think that you are going in the right way. But I will send some suggestions; Move the self.testdata.close() from setUp() to the tearDown() function. Surround the others open/close with try/finally blocks. So, if a file didn't open with success it will be closed. try: file.open() finally: file.close() Organize better your test folders. I suggest you to create a folder named _tests and inside this folder you should put the tests module (at your case you only have one module). Then, for each module create a folder with the name of the module and puts the files used by the tests of a module inside this folder. To know more about TDD and tests you should read the book Test Driven Development: By Example A: No, it doesn't quite look like you are. Unit tests should be small, fast, and uncomplicated. Doing 'complicated' tests (anything that relies on an external database, file system, configuration, environment, or really anything outside the test itself and the code being tested) is valuable, but shouldn't be a part of your "core unit tests". Unit tests should validate that the code follows the spec. One test should validate that with the correct input, you get the expected output. Another unit test should exist to validate proper behaviour on incorrect input. This often repeats for different kinds of correct or incorrect input, but there are usually a lot more tests for incorrect input than anything. Still, without a spec you don't really have much to unit test. The usual problem is a lack of technical specification (the spec) that tells you what a correct or incorrect input is and what to do in each case. Besides the fact that you're hitting the file system though, your tests look good.
Am I doing these unit tests right?
I'm new to unit tests for my own projects, so this is my first attempt to write a unit test from scratch. I'm using python, and the unittest module. The TodoList class being tested here is a wrapper for actual lists, with a few extra methods for stuff like saving to disc. It also defines a few methods for getting items by their ID in the list (which isn't the same as the list index). Tests (I've cut out a few helper methods, and a good few tests for the sake of not having people to scroll forever): class TodoListTests(unittest.TestCase): def setUp(self): self.testdata = open("./testdata.json", "r") self.testdata_text = self.testdata.read() self.testdata.close() def tearDown(self): try: os.remove("./todo.json") except OSError: # File not created, no need to delete. pass def create_todolist_and_safe_list(self): self.create_data_file() self.todolist = todolist.TodoList("./todo.json") self.list = json.loads(self.testdata_text) def create_data_file(self): datafile = open("./todo.json", "w") datafile.write(self.testdata_text) datafile.close() # Snip out a few more helper methods def test_loop(self): self.create_todolist_and_safe_list() test_list = [] for item in self.todolist: test_list.append(item) self.assertEquals(test_list, self.list) def test_save(self): self.create_todolist_and_safe_list() self.todolist.save() newfile_text = self.get_data_file_as_string() self.assertEquals(newfile_text, self.testdata_text) # Snip out the rest of the tests. Full link to source
[ "I think that you are going in the right way. But I will send some suggestions;\n\nMove the self.testdata.close() from setUp() to the tearDown() function.\nSurround the others open/close with try/finally blocks. So, if a file didn't open with success it will be closed.\n\n\n try:\n file.open()\n finally:\n file.close()\n\n\n\nOrganize better your test folders. I suggest you to create a folder named _tests and inside this folder you should put the tests module (at your case you only have one module). Then, for each module create a folder with the name of the module and puts the files used by the tests of a module inside this folder.\n\nTo know more about TDD and tests you should read the book Test Driven Development: By Example\n", "No, it doesn't quite look like you are.\nUnit tests should be small, fast, and uncomplicated.\nDoing 'complicated' tests (anything that relies on an external database, file system, configuration, environment, or really anything outside the test itself and the code being tested) is valuable, but shouldn't be a part of your \"core unit tests\".\nUnit tests should validate that the code follows the spec. One test should validate that with the correct input, you get the expected output. Another unit test should exist to validate proper behaviour on incorrect input. This often repeats for different kinds of correct or incorrect input, but there are usually a lot more tests for incorrect input than anything.\nStill, without a spec you don't really have much to unit test.\nThe usual problem is a lack of technical specification (the spec) that tells you what a correct or incorrect input is and what to do in each case.\nBesides the fact that you're hitting the file system though, your tests look good.\n" ]
[ 3, 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0002112014_python_unit_testing.txt
Q: iterable long-object? This is a problem from euler-project. No.13 import math #no.13 sum = [] number = 0 a = 37107287533902102798797998220837590246510135740250463769376774900097126481248969700780504170182605387432498619952474105947423330951305812372661730962991942213363574161572522430563301811072406154908250230675882075393461711719803104210475137780632466768926167069662363382013637841838368417873436172675728112879812849979408065481931592621691275889832738442742289174325203219235894228767964876702721893184745144573600130643909116721685684458871160315327670386486105843025439939619828917593665686757934951621764571418565606295021572231965867550793241933316490635246274190492910143244581382266334794475817892575867718337217661963751590579239728245598838407582035653253593990084026335689488301894586282278288018119938482628201427819413994056758715117009439035398664372827112653829987240784473053190104293586865155060062958648615320752733719591914205172558297169388870771546649911559348760353292171497005693854370070576826684624621495650076471787294438377604532826541087568284431911906346940378552177792951453612327252500029607107508256381565671088525835072145876576172410976447339110607218265236877223636045174237069058518606604482076212098132878607339694128114266041808683061932846081119106155694051268969251934325451728388641918047049293215058642563049483624672216484350762017279180399446930047329563406911573244438690812579451408905770622942919710792820955037687525678773091862540744969844508330393682126183363848253301546861961243487676812975343759465158038628759287849020152168555482871720121925776695478182833757993103614740356856449095527097864797581167263201004368978425535399209318374414978068609844840309812907779179908821879532736447567559084803087086987551392711854517078544161852424320693150332599594068957565367821070749269665376763262354472106979395067965269474259770973916669376304263398708541052684708299085211399427365734116182760315001271653786073615010808570091499395125570281987460043753582903531743471732693212357815498262974255273730794953759765105305946966067683156574377167401875275889028025717332296191766687138199318110487701902712526768027607800301367868099252546340106163286652636270218540497705585629946580636237993140746255962240744869082311749777923654662572469233228109171419143028819710328859780666976089293863828502533340334413065578016127815921815005561868836468420090470230530811728164304876237919698424872550366387845831148769693215490281042402013833512446218144177347063783299490636259666498587618221225225512486764533677201869716985443124195724099139590089523100588229554825530026352078153229679624948164195386821877476085327132285723110424803456124867697064507995236377742425354112916842768655389262050249103265729672370191327572567528565324825826546309220705859652229798860272258331913126375147341994889534765745501184957014548792889848568277260777137214037988797153829820378303147352772158034814451349137322665138134829543829199918180278916522431027392251122869539409579530664052326325380441000596549391598795936352974615218550237130764225512118369380358038858490341698116222072977186158236678424689157993532961922624679571944012690438771072750481023908955235974572318970677254791506150550495392297953090112996751986188088225875314529584099251203829009407770775672113067397083047244838165338735023408456470580773088295917476714036319800818712901187549131054712658197623331044818386269515456334926366572897563400500428462801835170705278318394258821455212272512503275512160354698120058176216521282765275169129689778932238195734329339946437501907836945765883352399886755061649651847751807381688378610915273579297013376217784275219262340194239963916804498399317331273132924185707147349566916674687634660915035914677504995186714302352196288948901024233251169136196266227326746080059154747183079839286853520694694454072476841822524674417161514036427982273348055556214818971426179103425986472045168939894221798260880768528778364618279934631376775430780936333301898264209010848802521674670883215120185883543223812876952786713296124747824645386369930090493103636197638780396218407357239979422340623539380833965132740801111666627891981488087797941876876144230030984490851411606618262936828367647447792391803351109890697907148578694408955299065364044742557608365997664579509666024396409905389607120198219976047599490197230297649139826800329731560371200413779037855660850892521673093931987275027546890690370753941304265231501194809377245048795150954100921645863754710598436791786391670211874924319957006419179697775990283006991536871371193661495281130587638027841075444973307840789923115535562561142322423255033685442488917353448899115014406480203690680639606723221932041495354150312888033953605329934036800697771065056663195481234880673210146739058568557934581403627822703280826165707739483275922328459417065250945123252306082291880205877731971983945018088807242966198081119777158542502016545090413245809786882778948721859617721078384350691861554356628840622574736922845095162084960398013400172393067166682355524525280460972253503534226472524250874054075591789781264330331690 s = str(a) for f in range(100): for i in range(50): sum.append(s[i+f*100]) a = int(''.join(str(i) for i in a)) number += a print number I get this error message. ... a = int(''.join(str(i) for i in a)) TypeError: 'long' object is not iterable My long object contains 5000 numbers. How could I solve this problem? Thanks in advance. EDIT: I thought it would be better to reshape the number. But it doesn't work yet. import math import numpy #euler-project no.13 #next line: a not visible because it contains 5000 numbers!!! a = 37107287533902102798797998220837590246510135740250463769376774900097126481248969700780504170182605387432498619952474105947423330951305812372661730962991942213363574161572522430563301811072406154908250230675882075393461711719803104210475137780632466768926167069662363382013637841838368417873436172675728112879812849979408065481931592621691275889832738442742289174325203219235894228767964876702721893184745144573600130643909116721685684458871160315327670386486105843025439939619828917593665686757934951621764571418565606295021572231965867550793241933316490635246274190492910143244581382266334794475817892575867718337217661963751590579239728245598838407582035653253593990084026335689488301894586282278288018119938482628201427819413994056758715117009439035398664372827112653829987240784473053190104293586865155060062958648615320752733719591914205172558297169388870771546649911559348760353292171497005693854370070576826684624621495650076471787294438377604532826541087568284431911906346940378552177792951453612327252500029607107508256381565671088525835072145876576172410976447339110607218265236877223636045174237069058518606604482076212098132878607339694128114266041808683061932846081119106155694051268969251934325451728388641918047049293215058642563049483624672216484350762017279180399446930047329563406911573244438690812579451408905770622942919710792820955037687525678773091862540744969844508330393682126183363848253301546861961243487676812975343759465158038628759287849020152168555482871720121925776695478182833757993103614740356856449095527097864797581167263201004368978425535399209318374414978068609844840309812907779179908821879532736447567559084803087086987551392711854517078544161852424320693150332599594068957565367821070749269665376763262354472106979395067965269474259770973916669376304263398708541052684708299085211399427365734116182760315001271653786073615010808570091499395125570281987460043753582903531743471732693212357815498262974255273730794953759765105305946966067683156574377167401875275889028025717332296191766687138199318110487701902712526768027607800301367868099252546340106163286652636270218540497705585629946580636237993140746255962240744869082311749777923654662572469233228109171419143028819710328859780666976089293863828502533340334413065578016127815921815005561868836468420090470230530811728164304876237919698424872550366387845831148769693215490281042402013833512446218144177347063783299490636259666498587618221225225512486764533677201869716985443124195724099139590089523100588229554825530026352078153229679624948164195386821877476085327132285723110424803456124867697064507995236377742425354112916842768655389262050249103265729672370191327572567528565324825826546309220705859652229798860272258331913126375147341994889534765745501184957014548792889848568277260777137214037988797153829820378303147352772158034814451349137322665138134829543829199918180278916522431027392251122869539409579530664052326325380441000596549391598795936352974615218550237130764225512118369380358038858490341698116222072977186158236678424689157993532961922624679571944012690438771072750481023908955235974572318970677254791506150550495392297953090112996751986188088225875314529584099251203829009407770775672113067397083047244838165338735023408456470580773088295917476714036319800818712901187549131054712658197623331044818386269515456334926366572897563400500428462801835170705278318394258821455212272512503275512160354698120058176216521282765275169129689778932238195734329339946437501907836945765883352399886755061649651847751807381688378610915273579297013376217784275219262340194239963916804498399317331273132924185707147349566916674687634660915035914677504995186714302352196288948901024233251169136196266227326746080059154747183079839286853520694694454072476841822524674417161514036427982273348055556214818971426179103425986472045168939894221798260880768528778364618279934631376775430780936333301898264209010848802521674670883215120185883543223812876952786713296124747824645386369930090493103636197638780396218407357239979422340623539380833965132740801111666627891981488087797941876876144230030984490851411606618262936828367647447792391803351109890697907148578694408955299065364044742557608365997664579509666024396409905389607120198219976047599490197230297649139826800329731560371200413779037855660850892521673093931987275027546890690370753941304265231501194809377245048795150954100921645863754710598436791786391670211874924319957006419179697775990283006991536871371193661495281130587638027841075444973307840789923115535562561142322423255033685442488917353448899115014406480203690680639606723221932041495354150312888033953605329934036800697771065056663195481234880673210146739058568557934581403627822703280826165707739483275922328459417065250945123252306082291880205877731971983945018088807242966198081119777158542502016545090413245809786882778948721859617721078384350691861554356628840622574736922845095162084960398013400172393067166682355524525280460972253503534226472524250874054075591789781264330331690 b = numpy.arange(a).reshape(100,50) print b 2.EDIT: import math #no.13 a = """3710728753390210279879799822083759024651013574025046376""".split() #contains much more numbers b = [int(x) for x in a] #b --> list print b[1] I got an error again. IndexError: list index out of range But i dont know why. I think b is a normal list isn't it? EDIT No. 3: import math #no.13 #Work out the first ten digits of the sum #of the following one-hundred 50-digit numbers. #a is the number b = [] #next line: a = list("3710728753390210279879..................") a = list("37107287533902102798797998220837590246510135740250463769376774900097126481248969700780504170182605387432498619952474105947423330951305812372661730962991942213363574161572522430563301811072406154908250230675882075393461711719803104210475137780632466768926167069662363382013637841838368417873436172675728112879812849979408065481931592621691275889832738442742289174325203219235894228767964876702721893184745144573600130643909116721685684458871160315327670386486105843025439939619828917593665686757934951621764571418565606295021572231965867550793241933316490635246274190492910143244581382266334794475817892575867718337217661963751590579239728245598838407582035653253593990084026335689488301894586282278288018119938482628201427819413994056758715117009439035398664372827112653829987240784473053190104293586865155060062958648615320752733719591914205172558297169388870771546649911559348760353292171497005693854370070576826684624621495650076471787294438377604532826541087568284431911906346940378552177792951453612327252500029607107508256381565671088525835072145876576172410976447339110607218265236877223636045174237069058518606604482076212098132878607339694128114266041808683061932846081119106155694051268969251934325451728388641918047049293215058642563049483624672216484350762017279180399446930047329563406911573244438690812579451408905770622942919710792820955037687525678773091862540744969844508330393682126183363848253301546861961243487676812975343759465158038628759287849020152168555482871720121925776695478182833757993103614740356856449095527097864797581167263201004368978425535399209318374414978068609844840309812907779179908821879532736447567559084803087086987551392711854517078544161852424320693150332599594068957565367821070749269665376763262354472106979395067965269474259770973916669376304263398708541052684708299085211399427365734116182760315001271653786073615010808570091499395125570281987460043753582903531743471732693212357815498262974255273730794953759765105305946966067683156574377167401875275889028025717332296191766687138199318110487701902712526768027607800301367868099252546340106163286652636270218540497705585629946580636237993140746255962240744869082311749777923654662572469233228109171419143028819710328859780666976089293863828502533340334413065578016127815921815005561868836468420090470230530811728164304876237919698424872550366387845831148769693215490281042402013833512446218144177347063783299490636259666498587618221225225512486764533677201869716985443124195724099139590089523100588229554825530026352078153229679624948164195386821877476085327132285723110424803456124867697064507995236377742425354112916842768655389262050249103265729672370191327572567528565324825826546309220705859652229798860272258331913126375147341994889534765745501184957014548792889848568277260777137214037988797153829820378303147352772158034814451349137322665138134829543829199918180278916522431027392251122869539409579530664052326325380441000596549391598795936352974615218550237130764225512118369380358038858490341698116222072977186158236678424689157993532961922624679571944012690438771072750481023908955235974572318970677254791506150550495392297953090112996751986188088225875314529584099251203829009407770775672113067397083047244838165338735023408456470580773088295917476714036319800818712901187549131054712658197623331044818386269515456334926366572897563400500428462801835170705278318394258821455212272512503275512160354698120058176216521282765275169129689778932238195734329339946437501907836945765883352399886755061649651847751807381688378610915273579297013376217784275219262340194239963916804498399317331273132924185707147349566916674687634660915035914677504995186714302352196288948901024233251169136196266227326746080059154747183079839286853520694694454072476841822524674417161514036427982273348055556214818971426179103425986472045168939894221798260880768528778364618279934631376775430780936333301898264209010848802521674670883215120185883543223812876952786713296124747824645386369930090493103636197638780396218407357239979422340623539380833965132740801111666627891981488087797941876876144230030984490851411606618262936828367647447792391803351109890697907148578694408955299065364044742557608365997664579509666024396409905389607120198219976047599490197230297649139826800329731560371200413779037855660850892521673093931987275027546890690370753941304265231501194809377245048795150954100921645863754710598436791786391670211874924319957006419179697775990283006991536871371193661495281130587638027841075444973307840789923115535562561142322423255033685442488917353448899115014406480203690680639606723221932041495354150312888033953605329934036800697771065056663195481234880673210146739058568557934581403627822703280826165707739483275922328459417065250945123252306082291880205877731971983945018088807242966198081119777158542502016545090413245809786882778948721859617721078384350691861554356628840622574736922845095162084960398013400172393067166682355524525280460972253503534226472524250874054075591789781264330331690") sum = 0 #len(a) = 5000 for y in range(99): #100 is correct but why for x in range(49): #50 numbers --> range(49) b.append(a[x+y*50]) c = int(''.join(str(i) for i in b)) sum += c b = [] c = 0 print y print sum I have a last question? Why is 100 correct and not 99? And do you think my Editing-style is bad? Should I remove the rest? Thanks. A: I am not sure what the overall goal of your program is but the error you are getting is because in the line: a = int(''.join(str(i) for i in a)) You are trying to iterate over a long and in Python as the error message indicates a long is not an iterable you cannot process it one digit at a time directly. You can convert the long to a string and process that one character at a time. In your program you have already converted the number a to the sting s with the line: s = str(a) so you can fix your problem by changing the problematic line above with the code below: a = int(''.join(str(i) for i in s)) A: I assume you are trying to solve Project Euler #13. Your variable a should be a list of integers, not one big long integer: a = [ 37107287533902102798797998220837590246510135740250, 46376937677490009712648124896970078050417018260538, 74324986199524741059474233309513058123726617309629, ... ] or to avoid typing the commas: a = """37107287533902102798797998220837590246510135740250 46376937677490009712648124896970078050417018260538 74324986199524741059474233309513058123726617309629 ... """.split() a = [int(x) for x in a] You might also find the sum builtin useful. A: Your second code snippet is really close. A smaller version of what you're doing is: a = """12345""".split() b = [int(x) for x in a] b now equals ['12345'], a list with a single string in it. That's why b[1] raises an error, because it's asking for the second element in a one-element list. Split defaults to using whitespace as the delimiter, so with no whitespace the string is unchanged. Here's the correct code, though I've no comments on its speed for your purposes: a = """12345""" b = [int(x) for x in a] or, to jump right into using a loop construct: a = """12345""" for each in a: num = int(each) ... sum the new number ... Hope that helps! A: As the OP knows, but maybe others don't, the problem statement is: "work out the first ten digits of the sum of the following one-hundred 50-digit numbers," followed naturally by 100 50-digit integers. The problem is designed to make it difficult to simply add the numbers together. Now, there is some ambiguity about the word "first", but if I recall I believe they are talking about the highest-value digits of the sum. @kame, a hint: how would you do this by hand? emulate that in Python. edit: if you save the numbers as text in 'data.txt', this will give them to you in the form needed to continue: FH = open('data.txt') data = FH.read() FH.close() L = data.strip().split('\n') L = [list(e.strip()) for e in L] L2 = list() for e in L: L2.append([int(c) for c in e]) for e in L2: print e
iterable long-object?
This is a problem from euler-project. No.13 import math #no.13 sum = [] number = 0 a = 37107287533902102798797998220837590246510135740250463769376774900097126481248969700780504170182605387432498619952474105947423330951305812372661730962991942213363574161572522430563301811072406154908250230675882075393461711719803104210475137780632466768926167069662363382013637841838368417873436172675728112879812849979408065481931592621691275889832738442742289174325203219235894228767964876702721893184745144573600130643909116721685684458871160315327670386486105843025439939619828917593665686757934951621764571418565606295021572231965867550793241933316490635246274190492910143244581382266334794475817892575867718337217661963751590579239728245598838407582035653253593990084026335689488301894586282278288018119938482628201427819413994056758715117009439035398664372827112653829987240784473053190104293586865155060062958648615320752733719591914205172558297169388870771546649911559348760353292171497005693854370070576826684624621495650076471787294438377604532826541087568284431911906346940378552177792951453612327252500029607107508256381565671088525835072145876576172410976447339110607218265236877223636045174237069058518606604482076212098132878607339694128114266041808683061932846081119106155694051268969251934325451728388641918047049293215058642563049483624672216484350762017279180399446930047329563406911573244438690812579451408905770622942919710792820955037687525678773091862540744969844508330393682126183363848253301546861961243487676812975343759465158038628759287849020152168555482871720121925776695478182833757993103614740356856449095527097864797581167263201004368978425535399209318374414978068609844840309812907779179908821879532736447567559084803087086987551392711854517078544161852424320693150332599594068957565367821070749269665376763262354472106979395067965269474259770973916669376304263398708541052684708299085211399427365734116182760315001271653786073615010808570091499395125570281987460043753582903531743471732693212357815498262974255273730794953759765105305946966067683156574377167401875275889028025717332296191766687138199318110487701902712526768027607800301367868099252546340106163286652636270218540497705585629946580636237993140746255962240744869082311749777923654662572469233228109171419143028819710328859780666976089293863828502533340334413065578016127815921815005561868836468420090470230530811728164304876237919698424872550366387845831148769693215490281042402013833512446218144177347063783299490636259666498587618221225225512486764533677201869716985443124195724099139590089523100588229554825530026352078153229679624948164195386821877476085327132285723110424803456124867697064507995236377742425354112916842768655389262050249103265729672370191327572567528565324825826546309220705859652229798860272258331913126375147341994889534765745501184957014548792889848568277260777137214037988797153829820378303147352772158034814451349137322665138134829543829199918180278916522431027392251122869539409579530664052326325380441000596549391598795936352974615218550237130764225512118369380358038858490341698116222072977186158236678424689157993532961922624679571944012690438771072750481023908955235974572318970677254791506150550495392297953090112996751986188088225875314529584099251203829009407770775672113067397083047244838165338735023408456470580773088295917476714036319800818712901187549131054712658197623331044818386269515456334926366572897563400500428462801835170705278318394258821455212272512503275512160354698120058176216521282765275169129689778932238195734329339946437501907836945765883352399886755061649651847751807381688378610915273579297013376217784275219262340194239963916804498399317331273132924185707147349566916674687634660915035914677504995186714302352196288948901024233251169136196266227326746080059154747183079839286853520694694454072476841822524674417161514036427982273348055556214818971426179103425986472045168939894221798260880768528778364618279934631376775430780936333301898264209010848802521674670883215120185883543223812876952786713296124747824645386369930090493103636197638780396218407357239979422340623539380833965132740801111666627891981488087797941876876144230030984490851411606618262936828367647447792391803351109890697907148578694408955299065364044742557608365997664579509666024396409905389607120198219976047599490197230297649139826800329731560371200413779037855660850892521673093931987275027546890690370753941304265231501194809377245048795150954100921645863754710598436791786391670211874924319957006419179697775990283006991536871371193661495281130587638027841075444973307840789923115535562561142322423255033685442488917353448899115014406480203690680639606723221932041495354150312888033953605329934036800697771065056663195481234880673210146739058568557934581403627822703280826165707739483275922328459417065250945123252306082291880205877731971983945018088807242966198081119777158542502016545090413245809786882778948721859617721078384350691861554356628840622574736922845095162084960398013400172393067166682355524525280460972253503534226472524250874054075591789781264330331690 s = str(a) for f in range(100): for i in range(50): sum.append(s[i+f*100]) a = int(''.join(str(i) for i in a)) number += a print number I get this error message. ... a = int(''.join(str(i) for i in a)) TypeError: 'long' object is not iterable My long object contains 5000 numbers. How could I solve this problem? Thanks in advance. EDIT: I thought it would be better to reshape the number. But it doesn't work yet. import math import numpy #euler-project no.13 #next line: a not visible because it contains 5000 numbers!!! a = 37107287533902102798797998220837590246510135740250463769376774900097126481248969700780504170182605387432498619952474105947423330951305812372661730962991942213363574161572522430563301811072406154908250230675882075393461711719803104210475137780632466768926167069662363382013637841838368417873436172675728112879812849979408065481931592621691275889832738442742289174325203219235894228767964876702721893184745144573600130643909116721685684458871160315327670386486105843025439939619828917593665686757934951621764571418565606295021572231965867550793241933316490635246274190492910143244581382266334794475817892575867718337217661963751590579239728245598838407582035653253593990084026335689488301894586282278288018119938482628201427819413994056758715117009439035398664372827112653829987240784473053190104293586865155060062958648615320752733719591914205172558297169388870771546649911559348760353292171497005693854370070576826684624621495650076471787294438377604532826541087568284431911906346940378552177792951453612327252500029607107508256381565671088525835072145876576172410976447339110607218265236877223636045174237069058518606604482076212098132878607339694128114266041808683061932846081119106155694051268969251934325451728388641918047049293215058642563049483624672216484350762017279180399446930047329563406911573244438690812579451408905770622942919710792820955037687525678773091862540744969844508330393682126183363848253301546861961243487676812975343759465158038628759287849020152168555482871720121925776695478182833757993103614740356856449095527097864797581167263201004368978425535399209318374414978068609844840309812907779179908821879532736447567559084803087086987551392711854517078544161852424320693150332599594068957565367821070749269665376763262354472106979395067965269474259770973916669376304263398708541052684708299085211399427365734116182760315001271653786073615010808570091499395125570281987460043753582903531743471732693212357815498262974255273730794953759765105305946966067683156574377167401875275889028025717332296191766687138199318110487701902712526768027607800301367868099252546340106163286652636270218540497705585629946580636237993140746255962240744869082311749777923654662572469233228109171419143028819710328859780666976089293863828502533340334413065578016127815921815005561868836468420090470230530811728164304876237919698424872550366387845831148769693215490281042402013833512446218144177347063783299490636259666498587618221225225512486764533677201869716985443124195724099139590089523100588229554825530026352078153229679624948164195386821877476085327132285723110424803456124867697064507995236377742425354112916842768655389262050249103265729672370191327572567528565324825826546309220705859652229798860272258331913126375147341994889534765745501184957014548792889848568277260777137214037988797153829820378303147352772158034814451349137322665138134829543829199918180278916522431027392251122869539409579530664052326325380441000596549391598795936352974615218550237130764225512118369380358038858490341698116222072977186158236678424689157993532961922624679571944012690438771072750481023908955235974572318970677254791506150550495392297953090112996751986188088225875314529584099251203829009407770775672113067397083047244838165338735023408456470580773088295917476714036319800818712901187549131054712658197623331044818386269515456334926366572897563400500428462801835170705278318394258821455212272512503275512160354698120058176216521282765275169129689778932238195734329339946437501907836945765883352399886755061649651847751807381688378610915273579297013376217784275219262340194239963916804498399317331273132924185707147349566916674687634660915035914677504995186714302352196288948901024233251169136196266227326746080059154747183079839286853520694694454072476841822524674417161514036427982273348055556214818971426179103425986472045168939894221798260880768528778364618279934631376775430780936333301898264209010848802521674670883215120185883543223812876952786713296124747824645386369930090493103636197638780396218407357239979422340623539380833965132740801111666627891981488087797941876876144230030984490851411606618262936828367647447792391803351109890697907148578694408955299065364044742557608365997664579509666024396409905389607120198219976047599490197230297649139826800329731560371200413779037855660850892521673093931987275027546890690370753941304265231501194809377245048795150954100921645863754710598436791786391670211874924319957006419179697775990283006991536871371193661495281130587638027841075444973307840789923115535562561142322423255033685442488917353448899115014406480203690680639606723221932041495354150312888033953605329934036800697771065056663195481234880673210146739058568557934581403627822703280826165707739483275922328459417065250945123252306082291880205877731971983945018088807242966198081119777158542502016545090413245809786882778948721859617721078384350691861554356628840622574736922845095162084960398013400172393067166682355524525280460972253503534226472524250874054075591789781264330331690 b = numpy.arange(a).reshape(100,50) print b 2.EDIT: import math #no.13 a = """3710728753390210279879799822083759024651013574025046376""".split() #contains much more numbers b = [int(x) for x in a] #b --> list print b[1] I got an error again. IndexError: list index out of range But i dont know why. I think b is a normal list isn't it? EDIT No. 3: import math #no.13 #Work out the first ten digits of the sum #of the following one-hundred 50-digit numbers. #a is the number b = [] #next line: a = list("3710728753390210279879..................") a = list("37107287533902102798797998220837590246510135740250463769376774900097126481248969700780504170182605387432498619952474105947423330951305812372661730962991942213363574161572522430563301811072406154908250230675882075393461711719803104210475137780632466768926167069662363382013637841838368417873436172675728112879812849979408065481931592621691275889832738442742289174325203219235894228767964876702721893184745144573600130643909116721685684458871160315327670386486105843025439939619828917593665686757934951621764571418565606295021572231965867550793241933316490635246274190492910143244581382266334794475817892575867718337217661963751590579239728245598838407582035653253593990084026335689488301894586282278288018119938482628201427819413994056758715117009439035398664372827112653829987240784473053190104293586865155060062958648615320752733719591914205172558297169388870771546649911559348760353292171497005693854370070576826684624621495650076471787294438377604532826541087568284431911906346940378552177792951453612327252500029607107508256381565671088525835072145876576172410976447339110607218265236877223636045174237069058518606604482076212098132878607339694128114266041808683061932846081119106155694051268969251934325451728388641918047049293215058642563049483624672216484350762017279180399446930047329563406911573244438690812579451408905770622942919710792820955037687525678773091862540744969844508330393682126183363848253301546861961243487676812975343759465158038628759287849020152168555482871720121925776695478182833757993103614740356856449095527097864797581167263201004368978425535399209318374414978068609844840309812907779179908821879532736447567559084803087086987551392711854517078544161852424320693150332599594068957565367821070749269665376763262354472106979395067965269474259770973916669376304263398708541052684708299085211399427365734116182760315001271653786073615010808570091499395125570281987460043753582903531743471732693212357815498262974255273730794953759765105305946966067683156574377167401875275889028025717332296191766687138199318110487701902712526768027607800301367868099252546340106163286652636270218540497705585629946580636237993140746255962240744869082311749777923654662572469233228109171419143028819710328859780666976089293863828502533340334413065578016127815921815005561868836468420090470230530811728164304876237919698424872550366387845831148769693215490281042402013833512446218144177347063783299490636259666498587618221225225512486764533677201869716985443124195724099139590089523100588229554825530026352078153229679624948164195386821877476085327132285723110424803456124867697064507995236377742425354112916842768655389262050249103265729672370191327572567528565324825826546309220705859652229798860272258331913126375147341994889534765745501184957014548792889848568277260777137214037988797153829820378303147352772158034814451349137322665138134829543829199918180278916522431027392251122869539409579530664052326325380441000596549391598795936352974615218550237130764225512118369380358038858490341698116222072977186158236678424689157993532961922624679571944012690438771072750481023908955235974572318970677254791506150550495392297953090112996751986188088225875314529584099251203829009407770775672113067397083047244838165338735023408456470580773088295917476714036319800818712901187549131054712658197623331044818386269515456334926366572897563400500428462801835170705278318394258821455212272512503275512160354698120058176216521282765275169129689778932238195734329339946437501907836945765883352399886755061649651847751807381688378610915273579297013376217784275219262340194239963916804498399317331273132924185707147349566916674687634660915035914677504995186714302352196288948901024233251169136196266227326746080059154747183079839286853520694694454072476841822524674417161514036427982273348055556214818971426179103425986472045168939894221798260880768528778364618279934631376775430780936333301898264209010848802521674670883215120185883543223812876952786713296124747824645386369930090493103636197638780396218407357239979422340623539380833965132740801111666627891981488087797941876876144230030984490851411606618262936828367647447792391803351109890697907148578694408955299065364044742557608365997664579509666024396409905389607120198219976047599490197230297649139826800329731560371200413779037855660850892521673093931987275027546890690370753941304265231501194809377245048795150954100921645863754710598436791786391670211874924319957006419179697775990283006991536871371193661495281130587638027841075444973307840789923115535562561142322423255033685442488917353448899115014406480203690680639606723221932041495354150312888033953605329934036800697771065056663195481234880673210146739058568557934581403627822703280826165707739483275922328459417065250945123252306082291880205877731971983945018088807242966198081119777158542502016545090413245809786882778948721859617721078384350691861554356628840622574736922845095162084960398013400172393067166682355524525280460972253503534226472524250874054075591789781264330331690") sum = 0 #len(a) = 5000 for y in range(99): #100 is correct but why for x in range(49): #50 numbers --> range(49) b.append(a[x+y*50]) c = int(''.join(str(i) for i in b)) sum += c b = [] c = 0 print y print sum I have a last question? Why is 100 correct and not 99? And do you think my Editing-style is bad? Should I remove the rest? Thanks.
[ "I am not sure what the overall goal of your program is but the error you are getting is because in the line:\na = int(''.join(str(i) for i in a)) \n\nYou are trying to iterate over a long and in Python as the error message indicates a long is not an iterable you cannot process it one digit at a time directly. You can convert the long to a string and process that one character at a time. In your program you have already converted the number a to the sting s with the line: s = str(a) so you can fix your problem by changing the problematic line above with the code below:\na = int(''.join(str(i) for i in s))\n\n", "I assume you are trying to solve Project Euler #13.\nYour variable a should be a list of integers, not one big long integer:\na = [\n 37107287533902102798797998220837590246510135740250,\n 46376937677490009712648124896970078050417018260538,\n 74324986199524741059474233309513058123726617309629,\n ...\n]\n\nor to avoid typing the commas:\na = \"\"\"37107287533902102798797998220837590246510135740250\n46376937677490009712648124896970078050417018260538\n74324986199524741059474233309513058123726617309629\n...\n\"\"\".split()\na = [int(x) for x in a]\n\nYou might also find the sum builtin useful.\n", "Your second code snippet is really close. A smaller version of what you're doing is:\na = \"\"\"12345\"\"\".split()\nb = [int(x) for x in a]\n\nb now equals ['12345'], a list with a single string in it. That's why b[1] raises an error, because it's asking for the second element in a one-element list. Split defaults to using whitespace as the delimiter, so with no whitespace the string is unchanged. Here's the correct code, though I've no comments on its speed for your purposes:\na = \"\"\"12345\"\"\"\nb = [int(x) for x in a]\n\nor, to jump right into using a loop construct:\na = \"\"\"12345\"\"\"\nfor each in a:\n num = int(each)\n ... sum the new number ...\n\nHope that helps!\n", "As the OP knows, but maybe others don't, the problem statement is: \"work out the first ten digits of the sum of the following one-hundred 50-digit numbers,\" followed naturally by 100 50-digit integers.\nThe problem is designed to make it difficult to simply add the numbers together.\nNow, there is some ambiguity about the word \"first\", but if I recall I believe they are talking about the highest-value digits of the sum.\n@kame, a hint: how would you do this by hand? emulate that in Python.\nedit:\nif you save the numbers as text in 'data.txt', this will give them to you in the form needed to continue:\nFH = open('data.txt')\ndata = FH.read()\nFH.close()\nL = data.strip().split('\\n')\nL = [list(e.strip()) for e in L]\nL2 = list()\nfor e in L:\n L2.append([int(c) for c in e]) \nfor e in L2: print e\n\n" ]
[ 3, 2, 1, 0 ]
[]
[]
[ "iterable", "long_integer", "python" ]
stackoverflow_0002105569_iterable_long_integer_python.txt
Q: Math functions as well as flags from django.db import models from django.contrib.auth.models import User class Product(models.Model): name = models.CharField(max_length = 127) description = models.TextField() code = models.CharField(max_length = 30) lot_no = models.CharField(max_length = 30) inventory = models.IntegerField() commited = models.IntegerField() available = models.IntegerField() reorder = models.IntegerField() created_date = models.DateField(auto_now_add = True) comment_user = models.ForeignKey(User, null=True) comment_txt = models.TextField() def __unicode__(self): return self.code + " - " + self.name + " - " + self.lot_no + " - " + str(self.created_date) I was wondering how I would be able to have a math function such that available = inventory - comitted such that when someone enters in values for inventory and comitted it will subtract the 2 and place that value into available. Than if reorder being inventory - available is <= available it will flag as red textbox or something of the sort. Thank you A: I don't understand your last sentence, but for the rest of it, showing a calculated field in the admin list_display is easy - just create a method on the model or the admin. In your case, the easiest thing is to drop the existing 'available' field and use a model method marked as a property. @property def available(self): return self.inventory - self.committed A: for example if reorder is <= available than the reorder integerfield would come up as a red flag saying you need to reorder or something of the sort.
Math functions as well as flags
from django.db import models from django.contrib.auth.models import User class Product(models.Model): name = models.CharField(max_length = 127) description = models.TextField() code = models.CharField(max_length = 30) lot_no = models.CharField(max_length = 30) inventory = models.IntegerField() commited = models.IntegerField() available = models.IntegerField() reorder = models.IntegerField() created_date = models.DateField(auto_now_add = True) comment_user = models.ForeignKey(User, null=True) comment_txt = models.TextField() def __unicode__(self): return self.code + " - " + self.name + " - " + self.lot_no + " - " + str(self.created_date) I was wondering how I would be able to have a math function such that available = inventory - comitted such that when someone enters in values for inventory and comitted it will subtract the 2 and place that value into available. Than if reorder being inventory - available is <= available it will flag as red textbox or something of the sort. Thank you
[ "I don't understand your last sentence, but for the rest of it, showing a calculated field in the admin list_display is easy - just create a method on the model or the admin. In your case, the easiest thing is to drop the existing 'available' field and use a model method marked as a property.\n@property\ndef available(self):\n return self.inventory - self.committed\n\n", "for example if reorder is <= available than the reorder integerfield would come up as a red flag saying you need to reorder or something of the sort.\n" ]
[ 0, 0 ]
[]
[]
[ "django_admin", "python" ]
stackoverflow_0002111945_django_admin_python.txt
Q: Import vs C's #include In C: #include "foo.h" int main() { } I believe that "foo.h" effectively gets copied and pasted in at the spot of the "#include". Python imports are different though, I'm finding. I just refactored a bit of GAE code that initially had ALL request handlers in one big index.py file. NEW directory tree: + | +- [handlers] // all inherit webapp.RequestHandler +- [models] // all inherit db.Model | +- globals.py // contains global variables for site-wide settings +- index.py // contains all handler redirects [handlers] is the folder with the handlers [models] is the folder with the models So, index.py goes from globals import * # we need all of the globals # ... from handlers.FirstPage import FirstPage from handlers.SecondPage import SecondPage #.. etc. SHOULDN'T handlers.FirstPage and handlers.SecondPage "see" everything in globals, since globals is imported "first", before handlers.*? A: While in C it works more or less "copy-pasting" the code, in Python is quite different. Remember the Zen of Python? Explicit is better than implicit. ... Namespaces are one honking great idea -- let's do more of those! Each time you import a module, you execute its code, but you keep all the scopes of the definitions. So, when you import handlers you give index access to the scope of globals, but the handlers module has no access to globals module unless you explicitly allow it to access to the scope, importing it. A: yes, they're imported first, but they're imported first into index.py. To be "visible" globals need to be imported in respective files too.
Import vs C's #include
In C: #include "foo.h" int main() { } I believe that "foo.h" effectively gets copied and pasted in at the spot of the "#include". Python imports are different though, I'm finding. I just refactored a bit of GAE code that initially had ALL request handlers in one big index.py file. NEW directory tree: + | +- [handlers] // all inherit webapp.RequestHandler +- [models] // all inherit db.Model | +- globals.py // contains global variables for site-wide settings +- index.py // contains all handler redirects [handlers] is the folder with the handlers [models] is the folder with the models So, index.py goes from globals import * # we need all of the globals # ... from handlers.FirstPage import FirstPage from handlers.SecondPage import SecondPage #.. etc. SHOULDN'T handlers.FirstPage and handlers.SecondPage "see" everything in globals, since globals is imported "first", before handlers.*?
[ "While in C it works more or less \"copy-pasting\" the code, in Python is quite different.\nRemember the Zen of Python?\nExplicit is better than implicit.\n...\nNamespaces are one honking great idea -- let's do more of those!\n\nEach time you import a module, you execute its code, but you keep all the scopes of the definitions. So, when you import handlers you give index access to the scope of globals, but the handlers module has no access to globals module unless you explicitly allow it to access to the scope, importing it.\n", "yes, they're imported first, but they're imported first into index.py. To be \"visible\" globals need to be imported in respective files too.\n" ]
[ 3, 1 ]
[]
[]
[ "import", "python" ]
stackoverflow_0002112707_import_python.txt
Q: In Python in Google App Engine, how do you capture output produced by the print statement? I am working in the Google Application Engine environment where I am loading doctests and python code from strings to test Python homework assignments. My basic implementation (Provided by Alex Martelli) appears to work for all of my problems except for those containing the print statement. Something seems to go wrong when I attempt to execute the print command within GAE. How would you modify this example to capture anything written out by the print statement? #This and most other code works class X(object): pass x=X() exec 'a=23' in vars(x) #This throws an error. class X(object): pass x=X() exec 'print 23' in vars(x) A: I think Hooked has the right answer, but I think you'd be better off storing the value of sys.stdout before you modify it and restoring that value afterwards rather than restoring sys.__stdout__ because (I think) the App Engine runtime tinkers with sys.stdout in its own way. That leaves you with something like import StringIO import sys # Store App Engine's modified stdout so we can restore it later gae_stdout = sys.stdout # Redirect stdout to a StringIO object new_stdout = StringIO.StringIO() sys.stdout = new_stdout # Run your code here, however you're doing that # Get whatever was printed to stdout using the `print` statement (if necessary) printed = new_stdout.getvalue() # Restore App Engine's original stdout sys.stdout = gae_stdout A: For this problem I like to capture the string output directly. Inside your function I would use something like: import StringIO, sys # create file-like string to capture output codeOut = StringIO.StringIO() # capture output and errors sys.stdout = codeOut err = '' try : exec code in code_namespace except Exception: err = str(sys.exc_info()[1]) And finish with: # restore stdout and stderr sys.stdout = sys.__stdout__ To restore normal the function of print.
In Python in Google App Engine, how do you capture output produced by the print statement?
I am working in the Google Application Engine environment where I am loading doctests and python code from strings to test Python homework assignments. My basic implementation (Provided by Alex Martelli) appears to work for all of my problems except for those containing the print statement. Something seems to go wrong when I attempt to execute the print command within GAE. How would you modify this example to capture anything written out by the print statement? #This and most other code works class X(object): pass x=X() exec 'a=23' in vars(x) #This throws an error. class X(object): pass x=X() exec 'print 23' in vars(x)
[ "I think Hooked has the right answer, but I think you'd be better off storing the value of sys.stdout before you modify it and restoring that value afterwards rather than restoring sys.__stdout__ because (I think) the App Engine runtime tinkers with sys.stdout in its own way.\nThat leaves you with something like\nimport StringIO\nimport sys\n\n# Store App Engine's modified stdout so we can restore it later\ngae_stdout = sys.stdout\n\n# Redirect stdout to a StringIO object\nnew_stdout = StringIO.StringIO()\nsys.stdout = new_stdout\n\n# Run your code here, however you're doing that\n\n# Get whatever was printed to stdout using the `print` statement (if necessary)\nprinted = new_stdout.getvalue()\n\n# Restore App Engine's original stdout\nsys.stdout = gae_stdout\n\n", "For this problem I like to capture the string output directly. Inside your function I would use something like:\nimport StringIO, sys\n\n# create file-like string to capture output\ncodeOut = StringIO.StringIO()\n\n# capture output and errors\nsys.stdout = codeOut\nerr = ''\n\ntry : \n exec code in code_namespace\nexcept Exception:\n err = str(sys.exc_info()[1])\n\nAnd finish with:\n# restore stdout and stderr\nsys.stdout = sys.__stdout__ \nTo restore normal the function of print.\n" ]
[ 5, 4 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002112396_google_app_engine_python.txt
Q: Pylons Uploading Distorted Images on Windows I'm creating an web app in Pylons, and am working on an image upload action. This is currently running using egg:paste#http on my windows machine, in the basic development configuration described in the pylons documentation quickstart. When I POST an image to my application, then move the image to the web root directory, then pull the uploaded image up in the browser, the image appears distorted. This is what I got when i uploaded a GIF of the Yahoo! logo, but most files don't show up in the browser at all, presumably because of corruption: distorted yahoo logo http://www.freeimagehosting.net/uploads/d2c92aef00.png This is the basic code I'm working with (straight out of the pylons documentation): os_path = os.path.join(config.images_dir, request.POST['image'].filename) save_file = open(os_path, 'w') shutil.copyfileobj(request.POST['image'].file, save_file) request.POST['image'].file.close() save_file.close() request.POST['image'] is a cgi.FieldStorage object. I thought this may be an issue with Windows line endings somehow, but I'm not sure how to check that or correct for it. What is causing my uploaded images to be distorted / corrupt? A: You are probably just missing the 'b' (binary) flag for effectively writing the file as binary: save_file = open(os_path, 'wb') But I don't see why you need the shutil.copyfileobj call in there, why not do something like this: file_save_path = os.path.join(config.images_dir, request.POST['image'].filename) file_contents = request.POST['image'].file.read() # insert sanity checks here... save_file = open(file_save_path, 'wb') save_file.write(file_contents) save_file.close() Or make the last three lines a bit more pythonic (making sure the file handle gets closed even if the write fails): with open(file_save_path, 'wb') as save_file: save_file.write(file_contents) It's possible you need a from __future__ import with_statements at the top of your file if you're below Python 2.6.
Pylons Uploading Distorted Images on Windows
I'm creating an web app in Pylons, and am working on an image upload action. This is currently running using egg:paste#http on my windows machine, in the basic development configuration described in the pylons documentation quickstart. When I POST an image to my application, then move the image to the web root directory, then pull the uploaded image up in the browser, the image appears distorted. This is what I got when i uploaded a GIF of the Yahoo! logo, but most files don't show up in the browser at all, presumably because of corruption: distorted yahoo logo http://www.freeimagehosting.net/uploads/d2c92aef00.png This is the basic code I'm working with (straight out of the pylons documentation): os_path = os.path.join(config.images_dir, request.POST['image'].filename) save_file = open(os_path, 'w') shutil.copyfileobj(request.POST['image'].file, save_file) request.POST['image'].file.close() save_file.close() request.POST['image'] is a cgi.FieldStorage object. I thought this may be an issue with Windows line endings somehow, but I'm not sure how to check that or correct for it. What is causing my uploaded images to be distorted / corrupt?
[ "You are probably just missing the 'b' (binary) flag for effectively writing the file as binary:\nsave_file = open(os_path, 'wb')\n\nBut I don't see why you need the shutil.copyfileobj call in there, why not do something like this:\nfile_save_path = os.path.join(config.images_dir, request.POST['image'].filename)\nfile_contents = request.POST['image'].file.read()\n\n# insert sanity checks here...\n\nsave_file = open(file_save_path, 'wb')\nsave_file.write(file_contents)\nsave_file.close()\n\nOr make the last three lines a bit more pythonic (making sure the file handle gets closed even if the write fails):\nwith open(file_save_path, 'wb') as save_file:\n save_file.write(file_contents)\n\nIt's possible you need a\nfrom __future__ import with_statements\n\nat the top of your file if you're below Python 2.6.\n" ]
[ 3 ]
[]
[]
[ "file_upload", "image", "paster", "pylons", "python" ]
stackoverflow_0002113126_file_upload_image_paster_pylons_python.txt
Q: Does python have the equivalent of Perl's regex "local" variable? While searching for a solution to a python regular expression problem I found this page which demonstrates that [some version of] perl allows variables within regular expressions. e.g. a perl regex something like: ^(?{ local $d=0}\((?{ $d++ }.*?\)(?d--) Where variable $d is incremented and decremented depending on which part of the regex you're in. (See the link for a real example) Is there something equivalent in python? Note: I realize that you can achieve this goal with a real parser and a grammar, but I don't want to add another dependency to overcome this tiny problem for a script I'm writing. And no, this script doesn't have to have nine nines of uptime. A: No. You need a grammer - pyparsing is nice (and easy)
Does python have the equivalent of Perl's regex "local" variable?
While searching for a solution to a python regular expression problem I found this page which demonstrates that [some version of] perl allows variables within regular expressions. e.g. a perl regex something like: ^(?{ local $d=0}\((?{ $d++ }.*?\)(?d--) Where variable $d is incremented and decremented depending on which part of the regex you're in. (See the link for a real example) Is there something equivalent in python? Note: I realize that you can achieve this goal with a real parser and a grammar, but I don't want to add another dependency to overcome this tiny problem for a script I'm writing. And no, this script doesn't have to have nine nines of uptime.
[ "No. You need a grammer - pyparsing is nice (and easy)\n" ]
[ 2 ]
[]
[]
[ "perl", "python", "regex" ]
stackoverflow_0002113843_perl_python_regex.txt
Q: Preserving argument default values while method chaining If I have to wrap an existing method, let us say wrapee() from a new method, say wrapper(), and the wrapee() provides default values for some arguments, how do I preserve its semantics without introducing unnecessary dependencies and maintenance? Let us say, the goal is to be able to use wrapper() in place of wrapee() without having to change the client code. E.g., if wrapee() is defined as: def wrapee(param1, param2="Some Value"): # Do something Then, one way to define wrapper() is: def wrapper(param1, param2="Some Value"): # Do something wrapee(param1, param2) # Do something else. However, wrapper() has to make assumptions on the default value for param2 which I don't like. If I have the control on wrapee(), I would define it like this: def wrapee(param1, param2=None): param2 = param2 or "Some Value" # Do something Then, wrapper() would change to: def wrapper(param1, param2=None): # Do something wrapee(param1, param2) # Do something else. If I don't have control on how wrapee() is defined, how best to define wrapper()? One option that comes into mind is to use to create a dict with non-None arguments and pass it as dictionary arguments, but it seems unnecessarily tedious. Update: The solution is to use both the list and dictionary arguments like this: def wrapper(param1, *args, **argv): # Do something wrapee(param1, *args, **argv) # Do something else. All the following calls are then valid: wrapper('test1') wrapper('test1', 'test2') wrapper('test1', param2='test2') wrapper(param2='test2', param1='test1') A: Check out argument lists in the Python docs. >>> def wrapper(param1, *stuff, **kargs): ... print(param1) ... print(stuff) ... print(args) ... >>> wrapper(3, 4, 5, foo=2) 3 (4, 5) {'foo': 2} Then to pass the args along: wrapee(param1, *stuff, **kargs) The *stuff is a variable number of non-named arguments, and the **kargs is a variable number of named arguments. A: I'd hardly say that it isn't tedious, but the only approach that I can think of is to introspect the function that you are wrapping to determine if any of its parameters have default values. You can get the list of parameters and then determine which one is the first that has default values: from inspect import getargspec method_signature = getargspec(method) param_names = method_signature[0] default_values = method_signature[3] params = [] # If any of method's parameters has default values, we need # to know the index of the first one that does. param_with_default_loc = -1 if default_values is not None and len(default_values) > 0: param_slice_index = len(default_values) * -1 param_with_default = param_names[param_slice_index:][0] param_with_default_loc = param_names.index(param_with_default) At that point, you can iterate over param_names, copying into the dict that is passed to wrappee. Once your index >= param_with_default_loc, you can obtain the default values by looking in the default_values list with an index of your index - param_with_default_loc. Does that make any sesne? Of course, to make this generic, you would to define it as a wrapper function, adding yet another layer of wrapping. A: def wrapper(param1, param2=None): if param2: wrapee(param1, param2) else: wrapee(param1) A: is this what you want? #!/usr/bin/python from functools import wraps def my_decorator(f): @wraps(f) def wrapper(*args, **kwds): print 'Calling decorated function' return f(*args, **kwds) return wrapper def f1(x, y): print x, y def f2(x, y="ok"): print x, y my_decorator(f1)(1,2) my_decorator(f2)(1,2) my_decorator(f2)(1) adapted from http://koala/doc/python2.6-doc/html/library/functools.html#module-functools
Preserving argument default values while method chaining
If I have to wrap an existing method, let us say wrapee() from a new method, say wrapper(), and the wrapee() provides default values for some arguments, how do I preserve its semantics without introducing unnecessary dependencies and maintenance? Let us say, the goal is to be able to use wrapper() in place of wrapee() without having to change the client code. E.g., if wrapee() is defined as: def wrapee(param1, param2="Some Value"): # Do something Then, one way to define wrapper() is: def wrapper(param1, param2="Some Value"): # Do something wrapee(param1, param2) # Do something else. However, wrapper() has to make assumptions on the default value for param2 which I don't like. If I have the control on wrapee(), I would define it like this: def wrapee(param1, param2=None): param2 = param2 or "Some Value" # Do something Then, wrapper() would change to: def wrapper(param1, param2=None): # Do something wrapee(param1, param2) # Do something else. If I don't have control on how wrapee() is defined, how best to define wrapper()? One option that comes into mind is to use to create a dict with non-None arguments and pass it as dictionary arguments, but it seems unnecessarily tedious. Update: The solution is to use both the list and dictionary arguments like this: def wrapper(param1, *args, **argv): # Do something wrapee(param1, *args, **argv) # Do something else. All the following calls are then valid: wrapper('test1') wrapper('test1', 'test2') wrapper('test1', param2='test2') wrapper(param2='test2', param1='test1')
[ "Check out argument lists in the Python docs.\n>>> def wrapper(param1, *stuff, **kargs):\n... print(param1)\n... print(stuff)\n... print(args)\n...\n>>> wrapper(3, 4, 5, foo=2)\n3\n(4, 5)\n{'foo': 2}\n\nThen to pass the args along:\nwrapee(param1, *stuff, **kargs)\n\nThe *stuff is a variable number of non-named arguments, and the **kargs is a variable number of named arguments.\n", "I'd hardly say that it isn't tedious, but the only approach that I can think of is to introspect the function that you are wrapping to determine if any of its parameters have default values. You can get the list of parameters and then determine which one is the first that has default values:\nfrom inspect import getargspec\n\nmethod_signature = getargspec(method)\nparam_names = method_signature[0]\ndefault_values = method_signature[3]\nparams = []\n\n# If any of method's parameters has default values, we need\n# to know the index of the first one that does.\nparam_with_default_loc = -1\nif default_values is not None and len(default_values) > 0:\n param_slice_index = len(default_values) * -1\n param_with_default = param_names[param_slice_index:][0]\n param_with_default_loc = param_names.index(param_with_default)\n\nAt that point, you can iterate over param_names, copying into the dict that is passed to wrappee. Once your index >= param_with_default_loc, you can obtain the default values by looking in the default_values list with an index of your index - param_with_default_loc.\nDoes that make any sesne?\nOf course, to make this generic, you would to define it as a wrapper function, adding yet another layer of wrapping.\n", "def wrapper(param1, param2=None):\n if param2:\n wrapee(param1, param2)\n else:\n wrapee(param1)\n\n", "is this what you want?\n#!/usr/bin/python\n\nfrom functools import wraps\ndef my_decorator(f):\n @wraps(f)\n def wrapper(*args, **kwds):\n print 'Calling decorated function'\n return f(*args, **kwds)\n return wrapper\n\n\ndef f1(x, y):\n print x, y\n\ndef f2(x, y=\"ok\"):\n print x, y\n\nmy_decorator(f1)(1,2)\nmy_decorator(f2)(1,2)\nmy_decorator(f2)(1)\n\nadapted from http://koala/doc/python2.6-doc/html/library/functools.html#module-functools\n" ]
[ 3, 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002114510_python.txt
Q: libnet creates UDP packets with invalid checksums I'm using pylibnet to construct and send UDP packets. The UDP packets I construct in this way all seem to have invalid checksums. Example: # python Python 2.4.3 (#1, Sep 3 2009, 15:37:12) [GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> import libnet >>> from libnet.constants import * >>> >>> net = libnet.context(RAW4, 'venet0:0') >>> ip = net.name2addr4('www.stackoverflow.com', RESOLVE) >>> data = 'This is my payload.' >>> udptag = net.build_udp(sp=54321, dp=54321, payload=data) >>> packetlen = IPV4_H + UDP_H + len(data) >>> iptag = net.autobuild_ipv4(len=packetlen, prot=IPPROTO_UDP, dst=ip) >>> >>> net.write() Capturing the above packet on the sending host reveals an invalid checksum: # tcpdump -i venet0:0 -n -v -v port 54321 tcpdump: WARNING: arptype 65535 not supported by libpcap - falling back to cooked socket tcpdump: listening on venet0:0, link-type LINUX_SLL (Linux cooked), capture size 96 bytes 08:16:10.303719 IP (tos 0x0, ttl 64, id 1, offset 0, flags [none], proto: UDP (17), length: 47) 192.168.55.10.54321 > 69.59.196.211.54321: [bad udp cksum 50c3!] UDP, length 0 Am I doing something wrong here? A: It's nothing to do with tcpdump bugs or checksum offloading. Libnet calculates the checksum in user mode as well (FYI). The problem has to do with the fact that you did not specify a length for the UDP header. This is not automagically calculated in pylibnet or libnet so you have to specify it for the time being. Below is the corrected version of your code. I will apply a patch to pylibnet to automagically detect the header length in rc6. Stay tuned to http://sourceforge.net/projects/pylibnet for updates. I will be pushing a new release fixing this issue. By the way, please feel free to contact me via sourceforge's pylibnet page if you have bug or feature requests. I love to hear from developers using my software :) import libnet from libnet.constants import * net = libnet.context(RAW4, 'venet0:0') ip = net.name2addr4('www.stackoverflow.com', RESOLVE) data = 'This is my payload.' udptag = net.build_udp(len=UDP_H+len(data), sp=54321, dp=54321, payload=data) packetlen = IPV4_H + UDP_H + len(data) iptag = net.autobuild_ipv4(len=packetlen, prot=IPPROTO_UDP, dst=ip) net.write() A: The job of calculating checksums is usually not performed in the user-space library but at the device driver or in hardware. I believe you are seeing the result of "checksum offloading", where the physical device calculates the checksums on outgoing packets, saving CPU cycles on the host. Many (if not all) modern Ethernet adapters do this, and the drivers do not calculate the checksum. Since tcpdump is capturing the packets in the driver, before they get to the physical device, it just gets garbage in the checksum field (probably what's left over in the buffer) and complains. There were several "bugs" reported against Wireshark in the 2005-2008 timeframe covering this, and Wireshark (which is just a GUI wrapper on tcpdump or its Windoze equivalent) now has an option to disable checksum validation for the offload case. http://wiki.wireshark.org/TCP_Checksum_Verification In any event, I would not expect pylibnet (or libnet) to be responsible for the checksums. See also http://www.wireshark.org/docs/wsug_html_chunked/ChAdvChecksums.html#id4744523 A: I have updated pylibnet to include an auto size determination for the length fields in most headers. This way if you forget to specify the length of the header for any of the headers that require it, it will attempt to automagically determine it. Saves you the headache of figuring out why your checksum is bad;)
libnet creates UDP packets with invalid checksums
I'm using pylibnet to construct and send UDP packets. The UDP packets I construct in this way all seem to have invalid checksums. Example: # python Python 2.4.3 (#1, Sep 3 2009, 15:37:12) [GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> import libnet >>> from libnet.constants import * >>> >>> net = libnet.context(RAW4, 'venet0:0') >>> ip = net.name2addr4('www.stackoverflow.com', RESOLVE) >>> data = 'This is my payload.' >>> udptag = net.build_udp(sp=54321, dp=54321, payload=data) >>> packetlen = IPV4_H + UDP_H + len(data) >>> iptag = net.autobuild_ipv4(len=packetlen, prot=IPPROTO_UDP, dst=ip) >>> >>> net.write() Capturing the above packet on the sending host reveals an invalid checksum: # tcpdump -i venet0:0 -n -v -v port 54321 tcpdump: WARNING: arptype 65535 not supported by libpcap - falling back to cooked socket tcpdump: listening on venet0:0, link-type LINUX_SLL (Linux cooked), capture size 96 bytes 08:16:10.303719 IP (tos 0x0, ttl 64, id 1, offset 0, flags [none], proto: UDP (17), length: 47) 192.168.55.10.54321 > 69.59.196.211.54321: [bad udp cksum 50c3!] UDP, length 0 Am I doing something wrong here?
[ "It's nothing to do with tcpdump bugs or checksum offloading. Libnet calculates the checksum in user mode as well (FYI). The problem has to do with the fact that you did not specify a length for the UDP header. This is not automagically calculated in pylibnet or libnet so you have to specify it for the time being. Below is the corrected version of your code. I will apply a patch to pylibnet to automagically detect the header length in rc6. Stay tuned to http://sourceforge.net/projects/pylibnet for updates. I will be pushing a new release fixing this issue. By the way, please feel free to contact me via sourceforge's pylibnet page if you have bug or feature requests. I love to hear from developers using my software :)\n\nimport libnet\nfrom libnet.constants import *\n\nnet = libnet.context(RAW4, 'venet0:0')\nip = net.name2addr4('www.stackoverflow.com', RESOLVE)\ndata = 'This is my payload.'\nudptag = net.build_udp(len=UDP_H+len(data), sp=54321, dp=54321, payload=data)\npacketlen = IPV4_H + UDP_H + len(data)\niptag = net.autobuild_ipv4(len=packetlen, prot=IPPROTO_UDP, dst=ip)\n\nnet.write()\n\n", "The job of calculating checksums is usually not performed in the user-space library but at the device driver or in hardware. I believe you are seeing the result of \"checksum offloading\", where the physical device calculates the checksums on outgoing packets, saving CPU cycles on the host. Many (if not all) modern Ethernet adapters do this, and the drivers do not calculate the checksum. Since tcpdump is capturing the packets in the driver, before they get to the physical device, it just gets garbage in the checksum field (probably what's left over in the buffer) and complains. \nThere were several \"bugs\" reported against Wireshark in the 2005-2008 timeframe covering this, and Wireshark (which is just a GUI wrapper on tcpdump or its Windoze equivalent) now has an option to disable checksum validation for the offload case.\nhttp://wiki.wireshark.org/TCP_Checksum_Verification\nIn any event, I would not expect pylibnet (or libnet) to be responsible for the checksums.\nSee also http://www.wireshark.org/docs/wsug_html_chunked/ChAdvChecksums.html#id4744523\n", "I have updated pylibnet to include an auto size determination for the length fields in most headers. This way if you forget to specify the length of the header for any of the headers that require it, it will attempt to automagically determine it. Saves you the headache of figuring out why your checksum is bad;)\n" ]
[ 3, 1, 1 ]
[]
[]
[ "libnet", "python", "udp" ]
stackoverflow_0001903500_libnet_python_udp.txt
Q: which style is preferred? Option 1: def f1(c): d = { "USA": "N.Y.", "China": "Shanghai" } if c in d: return d[c] return "N/A" Option 2: def f2(c): d = { "USA": "N.Y.", "China": "Shanghai" } try: return d[c] except: return "N/A" So that I can then call: for c in ("China", "Japan"): for f in (f1, f2): print "%s => %s" % (c, f(c)) The options are to either determine whether the key is in directory before hand (f1), or just fallback to the exception (f2). Which one is preferred? Why? A: Neither, I would go for def f2(c): d = { "USA": "N.Y.", "China": "Shanghai" } return d.get(c, "N/A") This way is shorter and "get" is designed for the job. Also an except without an explicit exception is bad pratice, so use except KeyError: not just except. Exceptions do not have much overhead in python. It is generally better to use them if there are not better alternatives or sometimes even when it saves an attribute lookup (to use instead of hasattr). Edit: to clear up general point about exceptions. paxdiablo is correct on the general point. Python is mainly designed for "its easier to ask forgivness then permission" i.e try then see what fails (exceptions), then "look before you leap" see whats there and then apply. This is because attribute lookup in python can be expensive, so calling the same stuff again (to check boundries) is a waste of resources. However, internal stuff in python has normally got nicer helpers so its better to use them. A: In general terms (not necessarily Python), I tend to prefer the "try-then-tell-me-if-it-went-wrong" method (exceptions) in all but the simplest cases. This is because, in threaded environments or during database access, the underlying data can change between the key check and the value extraction. If you're not changing the associative array outside of the current thread, then you can do the "check-first-then-extract" method. But that's for the general case. Here, specifically, you can use the get method which allows you to specify a default if the key doesn't exist: return d.get (c, "N/A") I'll clarify what I stated in the first paragraph. In situations where the underlying data can change between checking and using, you should always use an exception-type operation (unless you have an operation that will not cause a problem, such as d.get(), mentioned above). Consider for example the following two thread time-lines: +------------------------------+--------------------+ | Thread1 | Thread2 | +------------------------------+--------------------+ | Check is NY exists as a key. | | | | Delete NY key/val. | | Extract value for NY. | | +------------------------------+--------------------+ When thread 1 attempts to extract the value, it will get an exception anyway, so you may as well just code for the possibility and remove the initial check. The comment about databases is also relevant since that's another situation where the underlying data can change. That's why I tend to prefer atomic SQL (where possible) rather than something like getting a list of keys then processing them with individual statements. A: Typically, exceptions carry some overhead, and are meant for truly 'exceptional' cases. In this case, this sounds like a normal part of the execution, not an 'exceptional' or 'error' state. In general, I think your code will benefit by using the "if/else" convention, and saving exceptions for only when they are truly needed. A: Neither. return d.get(c, 'N/A') A: I'm with David on this one: def f2(c): d = { "USA": "N.Y.", "China": "Shanghai" } return d.get(c, "N/A") ...is exactly how I'd write it. To address your other options: In 'f1()', there's nothing wrong with this, per se, but dictionaries have a get() method for pretty much this exact use case: "get this from the dict, and if it's not there, return this other thing instead". That's all your code is saying, using get() is just more concise. In 'f2()', using 'except' by itself like that is frowned upon, and in addition, you don't really do anything useful in response to the exception -- in your case the calling code will never know there was an exception. So why use the construct if it doesn't add value to your function or the code that calls it? A: I see people using "get", which I recommend. However, if you find yourself in a similar situation in the future, catch the exception you mean: try: return d[k] except KeyError: return "N/A" This way, other exceptions (including KeyboardInterrupt) don't get caught. You almost never want to catch KeyboardInterrupt. A: I agree that in this case, dict.get is the best solution. In general, I think your choice will depend on how likely the exceptions are. If you expect the key lookups to mostly pass, then the try/catch is a better choice IMO. Similarly, if they will be failing often, an if statement is better. Performance of exceptions versus attribute lookups is not so different in Python, so I'd worry more about the logic of using exceptions/look-before-you-leap than about the performance aspects.
which style is preferred?
Option 1: def f1(c): d = { "USA": "N.Y.", "China": "Shanghai" } if c in d: return d[c] return "N/A" Option 2: def f2(c): d = { "USA": "N.Y.", "China": "Shanghai" } try: return d[c] except: return "N/A" So that I can then call: for c in ("China", "Japan"): for f in (f1, f2): print "%s => %s" % (c, f(c)) The options are to either determine whether the key is in directory before hand (f1), or just fallback to the exception (f2). Which one is preferred? Why?
[ "Neither, I would go for\ndef f2(c):\n d = {\n \"USA\": \"N.Y.\",\n \"China\": \"Shanghai\"\n }\n\n return d.get(c, \"N/A\")\n\nThis way is shorter and \"get\" is designed for the job.\nAlso an except without an explicit exception is bad pratice, so use except KeyError: not just except. \nExceptions do not have much overhead in python. It is generally better to use them if there are not better alternatives or sometimes even when it saves an attribute lookup (to use instead of hasattr). \nEdit: to clear up general point about exceptions. \npaxdiablo is correct on the general point. Python is mainly designed for \"its easier to ask forgivness then permission\" i.e try then see what fails (exceptions), then \"look before you leap\" see whats there and then apply. This is because attribute lookup in python can be expensive, so calling the same stuff again (to check boundries) is a waste of resources. However, internal stuff in python has normally got nicer helpers so its better to use them.\n", "In general terms (not necessarily Python), I tend to prefer the \"try-then-tell-me-if-it-went-wrong\" method (exceptions) in all but the simplest cases. This is because, in threaded environments or during database access, the underlying data can change between the key check and the value extraction.\nIf you're not changing the associative array outside of the current thread, then you can do the \"check-first-then-extract\" method.\nBut that's for the general case. Here, specifically, you can use the get method which allows you to specify a default if the key doesn't exist:\nreturn d.get (c, \"N/A\")\n\n\nI'll clarify what I stated in the first paragraph. In situations where the underlying data can change between checking and using, you should always use an exception-type operation (unless you have an operation that will not cause a problem, such as d.get(), mentioned above). Consider for example the following two thread time-lines:\n+------------------------------+--------------------+\n| Thread1 | Thread2 |\n+------------------------------+--------------------+\n| Check is NY exists as a key. | |\n| | Delete NY key/val. |\n| Extract value for NY. | |\n+------------------------------+--------------------+\n\nWhen thread 1 attempts to extract the value, it will get an exception anyway, so you may as well just code for the possibility and remove the initial check.\nThe comment about databases is also relevant since that's another situation where the underlying data can change. That's why I tend to prefer atomic SQL (where possible) rather than something like getting a list of keys then processing them with individual statements.\n", "Typically, exceptions carry some overhead, and are meant for truly 'exceptional' cases. In this case, this sounds like a normal part of the execution, not an 'exceptional' or 'error' state. \nIn general, I think your code will benefit by using the \"if/else\" convention, and saving exceptions for only when they are truly needed.\n", "Neither.\nreturn d.get(c, 'N/A')\n\n", "I'm with David on this one: \ndef f2(c):\n d = {\n \"USA\": \"N.Y.\",\n \"China\": \"Shanghai\"\n }\n\n return d.get(c, \"N/A\")\n\n...is exactly how I'd write it. \nTo address your other options: \nIn 'f1()', there's nothing wrong with this, per se, but dictionaries have a get() method for pretty much this exact use case: \"get this from the dict, and if it's not there, return this other thing instead\". That's all your code is saying, using get() is just more concise. \nIn 'f2()', using 'except' by itself like that is frowned upon, and in addition, you don't really do anything useful in response to the exception -- in your case the calling code will never know there was an exception. So why use the construct if it doesn't add value to your function or the code that calls it? \n", "I see people using \"get\", which I recommend. However, if you find yourself in a similar situation in the future, catch the exception you mean:\ntry:\n return d[k]\nexcept KeyError:\n return \"N/A\"\n\nThis way, other exceptions (including KeyboardInterrupt) don't get caught. You almost never want to catch KeyboardInterrupt.\n", "I agree that in this case, dict.get is the best solution.\nIn general, I think your choice will depend on how likely the exceptions are. If you expect the key lookups to mostly pass, then the try/catch is a better choice IMO. Similarly, if they will be failing often, an if statement is better.\nPerformance of exceptions versus attribute lookups is not so different in Python, so I'd worry more about the logic of using exceptions/look-before-you-leap than about the performance aspects.\n" ]
[ 22, 11, 9, 7, 4, 1, 0 ]
[]
[]
[ "coding_style", "exception", "python" ]
stackoverflow_0002114540_coding_style_exception_python.txt
Q: explorer right click context menu with python? I'm wondering how to go about adding a menu item to explorers right click context menu. For instance, when I right click on a file I get things like winrars "Add to archive" I want something like that and I'm wondering how to do it with python. A: To Add more items to explorer right click menu, you just need to add some registry keys. For example, take a look at this site, there is some examples and some tools. http://windowsxp.mvps.org/context_folders.htm A: Adding Entries to the Standard Context Menu _winreg - Windows registry access
explorer right click context menu with python?
I'm wondering how to go about adding a menu item to explorers right click context menu. For instance, when I right click on a file I get things like winrars "Add to archive" I want something like that and I'm wondering how to do it with python.
[ "To Add more items to explorer right click menu, you just need to add some registry keys.\nFor example, take a look at this site, there is some examples and some tools.\nhttp://windowsxp.mvps.org/context_folders.htm\n", "Adding Entries to the Standard Context Menu\n_winreg - Windows registry access\n" ]
[ 6, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002114853_python.txt
Q: What is the deal with the pony in Python community? Pony references are in several places: http://www.mail-archive.com/python-dev@python.org/msg44751.html http://pypi.python.org/pypi/django-pony/ http://djangopony.com/ Is there a cultural reference that I am missing? What is the deal with ponies? A: When you start listing what you want, "I want a fast HTTP parser", "I want ORM that just works", "I want higher order functions", the idea is that while you're wishing for things, you might as well wish for a pony too. This is probably a reference to a Calvin and Hobbes strip from "Someone under the bed is drooling", in which Susie Derkins says that as long as she's dreaming, she might as well wish for a pony. A: Its a Django unofficial mascot. See this blog post for an explanation. Python generally uses Monty Python references (and sometimes snake references, for the misguided). A: It's the Django mascot.
What is the deal with the pony in Python community?
Pony references are in several places: http://www.mail-archive.com/python-dev@python.org/msg44751.html http://pypi.python.org/pypi/django-pony/ http://djangopony.com/ Is there a cultural reference that I am missing? What is the deal with ponies?
[ "When you start listing what you want, \"I want a fast HTTP parser\", \"I want ORM that just works\", \"I want higher order functions\", the idea is that while you're wishing for things, you might as well wish for a pony too. This is probably a reference to a Calvin and Hobbes strip from \"Someone under the bed is drooling\", in which Susie Derkins says that as long as she's dreaming, she might as well wish for a pony.\n\n", "Its a Django unofficial mascot. See this blog post for an explanation.\nPython generally uses Monty Python references (and sometimes snake references, for the misguided). \n", "It's the Django mascot.\n" ]
[ 69, 15, 3 ]
[]
[]
[ "django", "pony", "python" ]
stackoverflow_0002115360_django_pony_python.txt
Q: What should I name my global module in Python? I'm writing an application in Python, and I've got a number of universal variables (such as the reference to the main window, the user settings, and the list of active items in the UI) which have to be accessible from all parts of the program1. I only just realized I've named the module globals.py and I'm importing the object which contains those variables with a from globals import globals statement at the top of my files. Obviously, this works, but I'm a little leery about naming my global object the same as the Python builtin. Unfortunately, I can't think of a much better naming convention for it. global and all are also Python builtins, universal seems imprecise, state isn't really the right idea. I'm leaning towards static or env, although both have a specific meaning in computer terms which suggests a different concept. So, what (in Python) would you call the module which contains variables global to all your other modules? 1 I realize I could pass these (or the single object containing them) as a variable into every other function I call. This ends up being infeasible, not just because it makes the startup code and function signatures really ugly. A: I would try to avoid such a global container module altogether, and instead put these variables into their own modules, which can then be imported from all parts of the system. For example, the main window would probably go into a variable in main.py. User settings could go into usersettings.py which would provide functions to view and change the settings. If another part of the system needs to access the user settings, that's a simple matter of: from usersettings import get_setting, set_setting ... # Do stuff with settings A similar approach could probably be used for other stuff that needs to be globally accessible. This leads to clearer separation of concerns and more testable code, since you can test modules in isolation without depending on the globals module all the time. A: `config` or `settings` A: I'd call it env. There's little risk that someone will confuse it with os.environ (especially if you organize your code so that you can call it myapp.environ). I'd also make everything exposed by myapp.environ a property of a class, so that I can put breakpoints in the setter when the day comes that I need to. A: global is a keyword, not a built-in. 'globals' is not a keyword, but is a built-in function. It can be assigned to, but is bad practice. Code checkers like pylint and pychecker can catch these accidental assignments. How about config? A: top? top_level? A: from globals import Globals This will fix the conflict and also follows PEP 8 recommendations. Also, in other cases like this, Roget's Thesaurus is your friend. I always keep a copy nearby.
What should I name my global module in Python?
I'm writing an application in Python, and I've got a number of universal variables (such as the reference to the main window, the user settings, and the list of active items in the UI) which have to be accessible from all parts of the program1. I only just realized I've named the module globals.py and I'm importing the object which contains those variables with a from globals import globals statement at the top of my files. Obviously, this works, but I'm a little leery about naming my global object the same as the Python builtin. Unfortunately, I can't think of a much better naming convention for it. global and all are also Python builtins, universal seems imprecise, state isn't really the right idea. I'm leaning towards static or env, although both have a specific meaning in computer terms which suggests a different concept. So, what (in Python) would you call the module which contains variables global to all your other modules? 1 I realize I could pass these (or the single object containing them) as a variable into every other function I call. This ends up being infeasible, not just because it makes the startup code and function signatures really ugly.
[ "I would try to avoid such a global container module altogether, and instead put these variables into their own modules, which can then be imported from all parts of the system.\nFor example, the main window would probably go into a variable in main.py. User settings could go into usersettings.py which would provide functions to view and change the settings.\nIf another part of the system needs to access the user settings, that's a simple matter of:\nfrom usersettings import get_setting, set_setting\n...\n# Do stuff with settings\n\nA similar approach could probably be used for other stuff that needs to be globally accessible. This leads to clearer separation of concerns and more testable code, since you can test modules in isolation without depending on the globals module all the time.\n", "`config` or `settings`\n\n", "I'd call it env. There's little risk that someone will confuse it with os.environ (especially if you organize your code so that you can call it myapp.environ).\nI'd also make everything exposed by myapp.environ a property of a class, so that I can put breakpoints in the setter when the day comes that I need to.\n", "global is a keyword, not a built-in. 'globals' is not a keyword, but is a built-in function. It can be assigned to, but is bad practice. Code checkers like pylint and pychecker can catch these accidental assignments. How about config?\n", "top? top_level?\n", "from globals import Globals\n\nThis will fix the conflict and also follows PEP 8 recommendations.\nAlso, in other cases like this, Roget's Thesaurus is your friend. I always keep a copy nearby.\n" ]
[ 3, 1, 1, 0, 0, 0 ]
[]
[]
[ "global_variables", "naming_conventions", "python" ]
stackoverflow_0002107682_global_variables_naming_conventions_python.txt
Q: "Featuring" content in a Django website I'm working on a new Django project, and the client wants to "feature" content on the homepage and a few other sections of the website. Content in this case could be a blog post, an event, a news story, etc. Each item would have a "start featuring" datetime and an "stop featuring" datetime. I've done this a few different ways in the past, but wonder if anybody has any great methods of archiving this. A: Have you looked at the contenttypes framework? You could set up a FeaturedItem model, with start and end datetimes, and a generic foreign key. This allows the relationship to be with any model. If you heavily feature objects from particular models, look at the section on reverse generic relations. A: I'm trying something similar, using the contenttypes framework but the problem comes when displaying the relationship in the admin area. I've been trying to hack this together to simply show a checkbox with "Featured?" next to it. class FeaturedContent(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') I'm not yet clear on how to implement the checkbox.
"Featuring" content in a Django website
I'm working on a new Django project, and the client wants to "feature" content on the homepage and a few other sections of the website. Content in this case could be a blog post, an event, a news story, etc. Each item would have a "start featuring" datetime and an "stop featuring" datetime. I've done this a few different ways in the past, but wonder if anybody has any great methods of archiving this.
[ "Have you looked at the contenttypes framework? You could set up a FeaturedItem model, with start and end datetimes, and a generic foreign key. This allows the relationship to be with any model.\nIf you heavily feature objects from particular models, look at the section on reverse generic relations.\n", "I'm trying something similar, using the contenttypes framework but the problem comes when displaying the relationship in the admin area. I've been trying to hack this together to simply show a checkbox with \"Featured?\" next to it.\nclass FeaturedContent(models.Model):\n content_type = models.ForeignKey(ContentType)\n object_id = models.PositiveIntegerField()\n content_object = generic.GenericForeignKey('content_type', 'object_id')\n\nI'm not yet clear on how to implement the checkbox.\n" ]
[ 7, 0 ]
[]
[]
[ "content_management_system", "django", "python" ]
stackoverflow_0001631592_content_management_system_django_python.txt
Q: Python Program converted into Java Sooo I started taking my second computer science class ever! For my first class we used python and for this class we're using Java. Our first assignment (pretty much just practice) is to convert this craps program from Python to Java and I'm just having a hell of a time. Could someone please help with what I've done and umm give me some advice? Maybe a good site for a beginner.... Someone that kinda knows Python (only from a first CS course perspective). 1) In python def winCraps(): roll = rollDice() if roll == 7 or roll == 11: return True elif roll == 2 or roll == 3 or roll == 12: return False else: return rollForPoint(roll) This is my attempt at the conversion of it over to java public int winCraps{ roll = rollDice(); if (roll = 7 && 11){ return (true); } else (roll =2 && 3 && 12){ return(false); } else{ return rollforPoint(roll); } } 2) Python def rollDice(): raw_input("Press <Enter> to roll...") die1 = randrange(1,7) die2 = randrange(1,7) sum = die1 + die2 print "You rolled", die1, "+", die2, "=", sum return sum This one confused the hell out of me. What would randrange be in Java?? Java static int rollDice(){ System.out.print("Press <Enter> to roll..."); double die1 = Math.random(); double die2 = Math.random(); die1 = (int) die1*6+1; die2 = (int) die2*6+1; int sum = (int)die1 + (int)die2; System.out.println("You rolled "+die1+ " + "+die2+ " = "+sum+"."); return sum; } *please bear in mind that I'm just learning this stuff lol A: You need to fix your if statements the "==" operator checks for equality, and you must put the variable you are checking against in each section of the statement. public int winCraps{ roll = rollDice(); if (roll == 7 || roll == 11) { return true; } else if(roll == 2 || roll == 3 || roll == 12) { return false; } else{ return rollforPoint(roll); } } In you rollDice() method, the way you assign values to each die is incorrect. I recommend reading up on random numbers (since this is homework, I'll leave that to you). Also, remember in java you must always end each statement with a semicolon A: What would randrange be in Java? You can get a random integer in a specific range from Java's Random class by calling the nextInt(int n) method. For example, Random rand = new Random(); int a = rand.nextInt(7); will give you a random integer >= 0 and < 7. This isn't exactly the same as randrange in Python, but you could use it as the index to an array of objects, or as the value of a roll of a single die. A: Randrange can be replaced by methods in java.util.Random. Like Python, Java has an extensive standard library which you should reference. A: 1) In Java "OR" operator is "||" not "&&" and comparison operator is "==" as in Python So if roll == 7 or roll == 11: Should be if( roll == 7 || roll == 11 ) { and not if( roll = 7 && 11 ){ 2) randrange is : random generator from there you can search: Random in Java Which will lead you to something like: Random.nextInt() Use this algorithm ( a) search Internet for Python function, b) understand what it does c) search it in java ) for the next assignment you have and you're done. You can always ask here again, that's what this site is all about after all A: I'd recommend that you look up the docs on randrange(). Once you know exactly what it does, google for the those keywords, plus the word Java. One thing you'll quickly discover in working with languages is that the APIs can be very different. There might not be an equivalent of randrange in Java, but you might be able to find two or three functions that you can combine to do the same thing. A: System.out.print isn't going to cause the system to wait for someone to hit the enter key. For that, you need to do something with System.in, most likely System.in.read(), as it blocks while waiting for input. Also, in Java, a program starts executing with the main method. To be exact, an executable class starts something like this: // You'll need the Random class, as per other answers import java.util.Random; // assuming WinCraps is the class name public class WinCraps { // args in this example is a string array of command-line arguments public static void main(String[] args) { // This is where your main method (that calls winCraps?) would be } // Other methods } Also, any method in this class called directly from main must also be static. A: Write out in English what the Python program does. Go through it line by line and explain to yourself what computations are evoked, in other words...what is happening? Afterwards, write the Java program from that description. Never ever try to convert the text of a program from one language to another. You'll run into a LOT of problems that way because every language is different, no matter how similar they look.
Python Program converted into Java
Sooo I started taking my second computer science class ever! For my first class we used python and for this class we're using Java. Our first assignment (pretty much just practice) is to convert this craps program from Python to Java and I'm just having a hell of a time. Could someone please help with what I've done and umm give me some advice? Maybe a good site for a beginner.... Someone that kinda knows Python (only from a first CS course perspective). 1) In python def winCraps(): roll = rollDice() if roll == 7 or roll == 11: return True elif roll == 2 or roll == 3 or roll == 12: return False else: return rollForPoint(roll) This is my attempt at the conversion of it over to java public int winCraps{ roll = rollDice(); if (roll = 7 && 11){ return (true); } else (roll =2 && 3 && 12){ return(false); } else{ return rollforPoint(roll); } } 2) Python def rollDice(): raw_input("Press <Enter> to roll...") die1 = randrange(1,7) die2 = randrange(1,7) sum = die1 + die2 print "You rolled", die1, "+", die2, "=", sum return sum This one confused the hell out of me. What would randrange be in Java?? Java static int rollDice(){ System.out.print("Press <Enter> to roll..."); double die1 = Math.random(); double die2 = Math.random(); die1 = (int) die1*6+1; die2 = (int) die2*6+1; int sum = (int)die1 + (int)die2; System.out.println("You rolled "+die1+ " + "+die2+ " = "+sum+"."); return sum; } *please bear in mind that I'm just learning this stuff lol
[ "You need to fix your if statements the \"==\" operator checks for equality, and you must put the variable you are checking against in each section of the statement.\npublic int winCraps{\n roll = rollDice();\n if (roll == 7 || roll == 11) {\n return true;\n }\n else if(roll == 2 || roll == 3 || roll == 12) {\n return false;\n }\n else{\n return rollforPoint(roll);\n }\n}\n\nIn you rollDice() method, the way you assign values to each die is incorrect. I recommend reading up on random numbers (since this is homework, I'll leave that to you).\nAlso, remember in java you must always end each statement with a semicolon\n", "\nWhat would randrange be in Java?\n\nYou can get a random integer in a specific range from Java's Random class by calling the nextInt(int n) method. For example,\nRandom rand = new Random();\nint a = rand.nextInt(7);\n\nwill give you a random integer >= 0 and < 7. This isn't exactly the same as randrange in Python, but you could use it as the index to an array of objects, or as the value of a roll of a single die.\n", "Randrange can be replaced by methods in java.util.Random. Like Python, Java has an extensive standard library which you should reference.\n", "1) In Java \"OR\" operator is \"||\" not \"&&\" and comparison operator is \"==\" as in Python \nSo\nif roll == 7 or roll == 11:\n\nShould be \nif( roll == 7 || roll == 11 ) {\n\nand not \n if( roll = 7 && 11 ){\n\n2) randrange is : random generator from there you can search: Random in Java \nWhich will lead you to something like: Random.nextInt() \nUse this algorithm ( a) search Internet for Python function, b) understand what it does c) search it in java ) for the next assignment you have and you're done.\nYou can always ask here again, that's what this site is all about after all\n", "I'd recommend that you look up the docs on randrange(). Once you know exactly what it does, google for the those keywords, plus the word Java.\nOne thing you'll quickly discover in working with languages is that the APIs can be very different. There might not be an equivalent of randrange in Java, but you might be able to find two or three functions that you can combine to do the same thing.\n", "System.out.print isn't going to cause the system to wait for someone to hit the enter key. For that, you need to do something with System.in, most likely System.in.read(), as it blocks while waiting for input.\nAlso, in Java, a program starts executing with the main method. To be exact, an executable class starts something like this:\n// You'll need the Random class, as per other answers\nimport java.util.Random;\n// assuming WinCraps is the class name\npublic class WinCraps {\n // args in this example is a string array of command-line arguments\n public static void main(String[] args) {\n // This is where your main method (that calls winCraps?) would be\n }\n\n // Other methods\n}\n\nAlso, any method in this class called directly from main must also be static.\n", "Write out in English what the Python program does. Go through it line by line and explain to yourself what computations are evoked, in other words...what is happening?\nAfterwards, write the Java program from that description.\nNever ever try to convert the text of a program from one language to another. You'll run into a LOT of problems that way because every language is different, no matter how similar they look.\n" ]
[ 2, 2, 1, 1, 0, 0, 0 ]
[ "One major error in your first program that you have in the Java conversion is the conditionals.\nSomething like (roll =2 && 3 && 12) assigns 2 to roll and then applies AND operators. You also forgot the if. You have elseif in Python.\nYou want something like:\nelse if(roll==2 || roll==3 || roll==12)\nAs for random numbers, there is a function for that in Java.\n" ]
[ -1 ]
[ "java", "python" ]
stackoverflow_0002112952_java_python.txt