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: Inheritance in Python We just started learning about class inheritance and attribute lookup in python. I have a question about the following code: class a : n = 1 class b : n = 2 class c : n = 3 class d (a,b) : pass class e (d,c) : pass I know that e.n would equal 1 due to the nature of attribute lookup procedure (depth first search). However, how would I access, say, class c's n from class e? I've tried e.c.n, but that gives me an error. Can someone tell me what I'm doing wrong? Thanks in advance! A: You can't get there from here. Class attributes are replaced. Use the class reference directly (c.n). A: >>> e.__bases__[1].n 3
Inheritance in Python
We just started learning about class inheritance and attribute lookup in python. I have a question about the following code: class a : n = 1 class b : n = 2 class c : n = 3 class d (a,b) : pass class e (d,c) : pass I know that e.n would equal 1 due to the nature of attribute lookup procedure (depth first search). However, how would I access, say, class c's n from class e? I've tried e.c.n, but that gives me an error. Can someone tell me what I'm doing wrong? Thanks in advance!
[ "You can't get there from here. Class attributes are replaced. Use the class reference directly (c.n).\n", ">>> e.__bases__[1].n\n3\n\n" ]
[ 1, 1 ]
[]
[]
[ "attributes", "inheritance", "python" ]
stackoverflow_0002278955_attributes_inheritance_python.txt
Q: Python UUID represented as special characters When creating a UUID in Python, likeso: >>> uuid.uuid1() UUID('a8098c1a-f86e-11da-bd1a-00112444be1e') How could one map that UUID into a string made up of the capitalized alphabet A-Z minus the characters D, F, I, O, Q, and U, plus the numerical digits, plus the characters "+" and "=". i.e. the from an integer or string onto the set of 32 (relatively OCR friendly) characters: [ABCEGHJKLMNPRSTVWXYZ1234567890+=] I'll call this the OCRf set (for OCR friendly). I'd like to have an isomorphic function: def uuid_to_ocr_friendly_chars(uid) """takes uid, an integer, and transposes it into a string made of the the OCRf set """ ... My first thought is to go through the process of changing the uuid to base 32. e.g. OCRf = "ABCEGHJKLMNPRSTVWXYZ1234567890+=" def uuid_to_ocr_friendly_chars(uid): ocfstr = '' while uid > 1: ocfstr += OCRf[uid % 32] uid /= 32 return ocfstr However, I'd like to know if this method is the best and fastest way to go about this conversion - or if there's a simpler and faster method (e.g. a builtin, a smarter algorithm, or just a better method). I'm grateful for your input. Thank you. A: How important is it to you to "squeeze" the representation by 18.75%, i.e., from 32 to 26 characters? Because, if saving this small percentage of bytes isn't absolutely crucial, something like uid.hex.upper().replace('D','Z') will do what you ask (not using the whole alphabet you make available, but the only cost of this is missing that 18.75% "squeezing"). If squeezing down every last byte is crucial, I'd work on substrings of 20 bits each -- that's 5 hex characters, 4 characters in your funky alphabet. There are 6 of those (plus 8 bits left over, for which you can take the hex.upper().replace as above since there's nothing to gain in doing anything fancier). You can easily get the substrings by slicing .hex and turn each into an int with an int(theslice, 16). Then, you can basically apply the same algorithm you're using above -- but the arithmetic is all done on much-smaller numbers, so the speed gain should be material. Also, don't build the string by looping on += -- make a list of all the "digits", and ''.join them all at the end -- that's also a performance improvement. A: >>> OCRf = 'ABCEGHJKLMNPRSTVWXYZ1234567890+=' >>> uuid = 'a8098c1a-f86e-11da-bd1a-00112444be1e' >>> binstr = bin(int(uuid.replace("-",""),16))[2:].zfill(130) >>> ocfstr = "".join(OCRf[int(binstr[i:i+5],2)] for i in range(0,130,5)) >>> ocfstr 'HLBJJB2+ETCKSP7JWACGYGMVW+' To convert back again >>> "%x"%(int("".join(bin(OCRf.index(i))[2:].zfill(5) for i in ocfstr),2)) 'a8098c1af86e11dabd1a00112444be1e' A: transtbl = string.maketrans( 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567', 'ABCEGHJKLMNPRSTVWXYZ1234567890+=' ) uuidstr = uuid.uuid1() print base64.b32encode(str(uuidstr).replace('-', '').decode('hex')).rstrip('=').translate(transtbl) Yes, this method does make me a bit ill, thanks for asking.
Python UUID represented as special characters
When creating a UUID in Python, likeso: >>> uuid.uuid1() UUID('a8098c1a-f86e-11da-bd1a-00112444be1e') How could one map that UUID into a string made up of the capitalized alphabet A-Z minus the characters D, F, I, O, Q, and U, plus the numerical digits, plus the characters "+" and "=". i.e. the from an integer or string onto the set of 32 (relatively OCR friendly) characters: [ABCEGHJKLMNPRSTVWXYZ1234567890+=] I'll call this the OCRf set (for OCR friendly). I'd like to have an isomorphic function: def uuid_to_ocr_friendly_chars(uid) """takes uid, an integer, and transposes it into a string made of the the OCRf set """ ... My first thought is to go through the process of changing the uuid to base 32. e.g. OCRf = "ABCEGHJKLMNPRSTVWXYZ1234567890+=" def uuid_to_ocr_friendly_chars(uid): ocfstr = '' while uid > 1: ocfstr += OCRf[uid % 32] uid /= 32 return ocfstr However, I'd like to know if this method is the best and fastest way to go about this conversion - or if there's a simpler and faster method (e.g. a builtin, a smarter algorithm, or just a better method). I'm grateful for your input. Thank you.
[ "How important is it to you to \"squeeze\" the representation by 18.75%, i.e., from 32 to 26 characters? Because, if saving this small percentage of bytes isn't absolutely crucial, something like uid.hex.upper().replace('D','Z') will do what you ask (not using the whole alphabet you make available, but the only cost of this is missing that 18.75% \"squeezing\").\nIf squeezing down every last byte is crucial, I'd work on substrings of 20 bits each -- that's 5 hex characters, 4 characters in your funky alphabet. There are 6 of those (plus 8 bits left over, for which you can take the hex.upper().replace as above since there's nothing to gain in doing anything fancier). You can easily get the substrings by slicing .hex and turn each into an int with an int(theslice, 16). Then, you can basically apply the same algorithm you're using above -- but the arithmetic is all done on much-smaller numbers, so the speed gain should be material. Also, don't build the string by looping on += -- make a list of all the \"digits\", and ''.join them all at the end -- that's also a performance improvement.\n", ">>> OCRf = 'ABCEGHJKLMNPRSTVWXYZ1234567890+='\n>>> uuid = 'a8098c1a-f86e-11da-bd1a-00112444be1e'\n>>> binstr = bin(int(uuid.replace(\"-\",\"\"),16))[2:].zfill(130)\n>>> ocfstr = \"\".join(OCRf[int(binstr[i:i+5],2)] for i in range(0,130,5))\n>>> ocfstr\n'HLBJJB2+ETCKSP7JWACGYGMVW+'\n\nTo convert back again\n>>> \"%x\"%(int(\"\".join(bin(OCRf.index(i))[2:].zfill(5) for i in ocfstr),2))\n'a8098c1af86e11dabd1a00112444be1e'\n\n", "transtbl = string.maketrans(\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n 'ABCEGHJKLMNPRSTVWXYZ1234567890+='\n)\n\nuuidstr = uuid.uuid1()\n\nprint base64.b32encode(str(uuidstr).replace('-', '').decode('hex')).rstrip('=').translate(transtbl)\n\nYes, this method does make me a bit ill, thanks for asking.\n" ]
[ 2, 1, 1 ]
[]
[]
[ "algorithm", "isomorphism", "python", "transpose", "uuid" ]
stackoverflow_0002278239_algorithm_isomorphism_python_transpose_uuid.txt
Q: Error in downloading and saving image using python I written a code for downloading and saving images from a site .It worked nicely,but for some urls it is being showing an error.I have paste code below import urllib2 import webbrowser imageurl='http://www.example.com/'+image[s] opener1 = urllib2.build_opener() page1=opener1.open(imageurl) my_picture=page1.read() image1=image[s].replace("/","") fout = open('images/tony/'+image1, "wb") fout.write(my_picture) fout.close() Actually i get many values of image[s] and is working almost condition.But when the value of image[s]=images/PG013001 GROUP 2.jpg, the compiler gives an error File "leather.py", line 37, in get_leather page1=opener1.open(imageurl) File "D:\Program Files\Python\lib\urllib2.py", line 395, in open response = meth(req, response) File "D:\Program Files\Python\lib\urllib2.py", line 508, in http_response 'http', request, response, code, msg, hdrs) File "D:\Program Files\Python\lib\urllib2.py", line 433, in error return self._call_chain(*args) File "D:\Program Files\Python\lib\urllib2.py", line 367, in _call_chain result = func(*args) File "D:\Program Files\Python\lib\urllib2.py", line 516, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 404: Not Found I thought the corresponding imageurl ie 'http://www.example.com/images/PG013001 GROUP 2.jpg' doesn,t exist but when it is checked it exist.Please suggest a fix regards A: You should fix the link. Try this: >>> import urllib >>> urllib.quote("images/PG013001 GROUP 2.jpg") 'images/PG013001%20GROUP%202.jpg' A: Urls can't include spaces directly; it's simply not allowed. What you want to do is to quote, or encode the spaces in the filename, so that the url becomes legal. Here's wikipedia on the matter. So, you want to quote the urls that you pass to urllib2. In your code, you could do that by changing the one line to look like this: page1=opener1.open(urllib2.quote(imageurl)) That oughta do it.
Error in downloading and saving image using python
I written a code for downloading and saving images from a site .It worked nicely,but for some urls it is being showing an error.I have paste code below import urllib2 import webbrowser imageurl='http://www.example.com/'+image[s] opener1 = urllib2.build_opener() page1=opener1.open(imageurl) my_picture=page1.read() image1=image[s].replace("/","") fout = open('images/tony/'+image1, "wb") fout.write(my_picture) fout.close() Actually i get many values of image[s] and is working almost condition.But when the value of image[s]=images/PG013001 GROUP 2.jpg, the compiler gives an error File "leather.py", line 37, in get_leather page1=opener1.open(imageurl) File "D:\Program Files\Python\lib\urllib2.py", line 395, in open response = meth(req, response) File "D:\Program Files\Python\lib\urllib2.py", line 508, in http_response 'http', request, response, code, msg, hdrs) File "D:\Program Files\Python\lib\urllib2.py", line 433, in error return self._call_chain(*args) File "D:\Program Files\Python\lib\urllib2.py", line 367, in _call_chain result = func(*args) File "D:\Program Files\Python\lib\urllib2.py", line 516, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 404: Not Found I thought the corresponding imageurl ie 'http://www.example.com/images/PG013001 GROUP 2.jpg' doesn,t exist but when it is checked it exist.Please suggest a fix regards
[ "You should fix the link. Try this:\n>>> import urllib\n>>> urllib.quote(\"images/PG013001 GROUP 2.jpg\")\n'images/PG013001%20GROUP%202.jpg'\n\n", "Urls can't include spaces directly; it's simply not allowed. What you want to do is to quote, or encode the spaces in the filename, so that the url becomes legal. Here's wikipedia on the matter.\nSo, you want to quote the urls that you pass to urllib2. In your code, you could do that by changing the one line to look like this:\npage1=opener1.open(urllib2.quote(imageurl))\n\nThat oughta do it.\n" ]
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002278982_python.txt
Q: Python function composition I've tried to implement function composition with nice syntax and here is what I've got: from functools import partial class _compfunc(partial): def __lshift__(self, y): f = lambda *args, **kwargs: self.func(y(*args, **kwargs)) return _compfunc(f) def __rshift__(self, y): f = lambda *args, **kwargs: y(self.func(*args, **kwargs)) return _compfunc(f) def composable(f): return _compfunc(f) @composable def f1(x): return x * 2 @composable def f2(x): return x + 3 @composable def f3(x): return (-1) * x print f1(2) #4 print f2(2) #5 print (f1 << f2 << f1)(2) #14 print (f3 >> f2)(2) #1 print (f2 >> f3)(2) #-5 It works fine with integers, but fails on lists/tuples: @composable def f4(a): a.append(0) print f4([1, 2]) #None Where is a mistake? A: append does in-place addition, as Ignacio Vazquez-Abrams said (well, implied) -- so, while you could fix that by just adding a return to your function, it would have the side-effect of changing the argument it was passed, too: @composable def f4(a): a.append(0) return a It would be best to use the following even more concise code which also creates and returns a new object: @composable def f4(a): return a + [0]
Python function composition
I've tried to implement function composition with nice syntax and here is what I've got: from functools import partial class _compfunc(partial): def __lshift__(self, y): f = lambda *args, **kwargs: self.func(y(*args, **kwargs)) return _compfunc(f) def __rshift__(self, y): f = lambda *args, **kwargs: y(self.func(*args, **kwargs)) return _compfunc(f) def composable(f): return _compfunc(f) @composable def f1(x): return x * 2 @composable def f2(x): return x + 3 @composable def f3(x): return (-1) * x print f1(2) #4 print f2(2) #5 print (f1 << f2 << f1)(2) #14 print (f3 >> f2)(2) #1 print (f2 >> f3)(2) #-5 It works fine with integers, but fails on lists/tuples: @composable def f4(a): a.append(0) print f4([1, 2]) #None Where is a mistake?
[ "append does in-place addition, as Ignacio Vazquez-Abrams said (well, implied) -- so, while you could fix that by just adding a return to your function, it would have the side-effect of changing the argument it was passed, too:\n@composable\ndef f4(a):\n a.append(0)\n return a\n\nIt would be best to use the following even more concise code which also creates and returns a new object:\n@composable\ndef f4(a):\n return a + [0]\n\n" ]
[ 9 ]
[]
[]
[ "function_composition", "python" ]
stackoverflow_0002279423_function_composition_python.txt
Q: Multiple consumers & producers connected to a message queue, Is that possible in AMQP? I'd like to create a farm of processes that are able to OCR text. I've thought about using a single queue of messages which is read by multiple OCR processes. I would like to ensure that: each message in queue is eventually processed the work is more or less equally distributed an image will be parsed only by one OCR process An OCR process won't get multiple messages at once (so that any other free OCR process can handle the message). Is that possible to do using AMQP? I'm planning to use python and rabbitmq A: Yes, as @nailxx points out. The AMQP programming model is slightly different from JMS in that you only have queues, which can be shared between workers, or used privately by a single worker. You can also easily set up RabbitMQ to do PubSub use cases or what in JMS are called topics. Please go to our Getting Started page on the RabbitMQ web site to find a ton of helpful info about this. Now, for your use case in particular, there are already plenty of tools available. One that people are using a lot, and that is well supported, is Celery. Here is a blog post about it, that I think will help you get started: If you have any questions please email us or post to the rabbitmq-discuss mailing list. A: Yes, that's possible. Server cluster for a real-time MMO game I'm working on operate this way. We use ActiveMQ, but I think all this possible with RabbitMQ as well. All items that you mentioned you get out of the box, except last one. each message in queue is eventually processed - this is one of main responsibilities of message brokers the work is more or less equally distributed - this is another one :) an image will be parsed only by one OCR process - the distinction of /topic and /queue exists for this. Topics are like broadcast signals, queues are tasks. You need a /queue in your scenario To make last one work in desired way, consumers send AMQ-specific argument when subscribing to the queue: activemq.prefetchSize: 1 This setting guarantees that consumer will not take any more messages after it took one and until it send an ack to AMQ. I believe something similar exists in RabbitMQ.
Multiple consumers & producers connected to a message queue, Is that possible in AMQP?
I'd like to create a farm of processes that are able to OCR text. I've thought about using a single queue of messages which is read by multiple OCR processes. I would like to ensure that: each message in queue is eventually processed the work is more or less equally distributed an image will be parsed only by one OCR process An OCR process won't get multiple messages at once (so that any other free OCR process can handle the message). Is that possible to do using AMQP? I'm planning to use python and rabbitmq
[ "Yes, as @nailxx points out. The AMQP programming model is slightly different from JMS in that you only have queues, which can be shared between workers, or used privately by a single worker. You can also easily set up RabbitMQ to do PubSub use cases or what in JMS are called topics. Please go to our Getting Started page on the RabbitMQ web site to find a ton of helpful info about this.\nNow, for your use case in particular, there are already plenty of tools available. One that people are using a lot, and that is well supported, is Celery. Here is a blog post about it, that I think will help you get started: \nIf you have any questions please email us or post to the rabbitmq-discuss mailing list.\n", "Yes, that's possible. Server cluster for a real-time MMO game I'm working on operate this way. We use ActiveMQ, but I think all this possible with RabbitMQ as well.\nAll items that you mentioned you get out of the box, except last one.\n\neach message in queue is eventually processed - this is one of main responsibilities of message brokers\nthe work is more or less equally distributed - this is another one :)\nan image will be parsed only by one OCR process - the distinction of /topic and /queue exists for this. Topics are like broadcast signals, queues are tasks. You need a /queue in your scenario\n\nTo make last one work in desired way, consumers send AMQ-specific argument when subscribing to the queue:\nactivemq.prefetchSize: 1\n\nThis setting guarantees that consumer will not take any more messages after it took one and until it send an ack to AMQ. I believe something similar exists in RabbitMQ.\n" ]
[ 5, 3 ]
[]
[]
[ "amqp", "message_queue", "py_amqplib", "python", "rabbitmq" ]
stackoverflow_0002161206_amqp_message_queue_py_amqplib_python_rabbitmq.txt
Q: PyScripter Rpyc maybe somebody could give me a couple guidelines how to install Rpyc to PyScripter. I use PyScripter 1.9.9.7 with Python 2.6. I have tried to google it and found some instructions, but still have not succeeded... Thanks! A: Grab the file rpyc-2.60-py24.zip from here: http://code.google.com/p/pyscripter/downloads/list Under your python2.6 install directory go to the following subdirectory \Lib\site-packages\ check if you already have an rpyc subdirectory, \Lib\site-packages\Rpyc\ if you do, delete it or delete its contents. Now unzip the contents of rpyc-2.60-py24.zip into \Lib\site-packages\ maintainng the directory structure within the zip. Startup pyscripter and within the interpreter window, right click and select: Python Engine->Remote Pyscripter should respsond with: * Remote Python engine is active * Best of luck!
PyScripter Rpyc
maybe somebody could give me a couple guidelines how to install Rpyc to PyScripter. I use PyScripter 1.9.9.7 with Python 2.6. I have tried to google it and found some instructions, but still have not succeeded... Thanks!
[ "Grab the file rpyc-2.60-py24.zip from here:\nhttp://code.google.com/p/pyscripter/downloads/list\nUnder your python2.6 install directory go to the following subdirectory\n\\Lib\\site-packages\\\ncheck if you already have an rpyc subdirectory,\n\\Lib\\site-packages\\Rpyc\\\nif you do, delete it or delete its contents.\nNow unzip the contents of rpyc-2.60-py24.zip into\n\\Lib\\site-packages\\\nmaintainng the directory structure within the zip.\nStartup pyscripter and within the interpreter window, right click and\nselect:\nPython Engine->Remote\nPyscripter should respsond with:\n* Remote Python engine is active *\nBest of luck!\n" ]
[ 4 ]
[]
[]
[ "pyscripter", "python", "rpyc" ]
stackoverflow_0002276323_pyscripter_python_rpyc.txt
Q: Question regarding UDP communication in twisted framework I would like to find out if Twisted imposes restriction on maximum size of UDP packets. The allowable limit on linux platforms is upto 64k (although I intend to send packets of about 10k bytes consisting of JPEG images) but I am not able to send more than approx. 2500 bytes A: It's very unlikely that Twisted is imposing any limit but there's no reason some other part of the network wouldn't drop the packets if they're too large. It's very rare for people to send UDP packets of such a large size for precisely that sort of reason. Most game applications for example try to keep them below 1.5K these days, and below 512 bytes in the not-too-distant past.
Question regarding UDP communication in twisted framework
I would like to find out if Twisted imposes restriction on maximum size of UDP packets. The allowable limit on linux platforms is upto 64k (although I intend to send packets of about 10k bytes consisting of JPEG images) but I am not able to send more than approx. 2500 bytes
[ "It's very unlikely that Twisted is imposing any limit but there's no reason some other part of the network wouldn't drop the packets if they're too large. It's very rare for people to send UDP packets of such a large size for precisely that sort of reason. Most game applications for example try to keep them below 1.5K these days, and below 512 bytes in the not-too-distant past.\n" ]
[ 1 ]
[ "Are you sure that it is not a receive problem?\nThere is no indication that your packets won't be fragmented en route to the destination\n" ]
[ -1 ]
[ "python", "twisted", "udp" ]
stackoverflow_0002278665_python_twisted_udp.txt
Q: Unit testing functions that access files I have two functions—one that builds the path to a set of files and another that reads the files. Below are the two functions: def pass_file_name(self): self.log_files= [] file_name = self.path+"\\access_"+self.appliacation+".log" if os.path.isfile(file_name): self.log_files.append(file_name) for i in xrange(7): file_name = self.path+"\\access_"+self.appliacation+".log"+"."+str(i+1) if os.path.isfile(file_name): self.log_files.append(file_name) return self.log_files def read_log_files (self, log_file_names): self.log_entrys = [] self.log_line = [] for i in log_file_names: self.f = open(i) for line in self.f: self.log_line = line.split(" ") #print self.log_line self.log_entrys.append(self.log_line) return self.log_entrys What would be the best way to unit test these two functions? A: You have two units here: One that generate file paths Second that reads them Thus there should be two unit-test-cases (i.e. classes with tests). First would test only file paths generation. Second would test reading from predefined set of files you prepared in special subdirectory of tests directory, it should test in isolation from first test case. In your case, you could probably have very short log files for tests. In this case for better readability and maintenance it is good idea to embed them right in test code. But in this case you'll have to improve your reading function a bit so it can take either file name or file-like object: from cStringIO import StringIO # ... def test_some_log_reading_scenario(self): log1 = '\n'.join([ 'log line', 'another log line' ]) log2 = '\n'.join([ 'another log another line', 'lala blah blah' ]) # ... result = myobj.read_log_files([StringIO(log1), StringIO(log2)]) # assert result A: Personally, I'd build a test harness that set up the required files before testing those two functions. For each test case (where you expect the file to be present - remember to test failure cases too!), write some known logs into the appropriately named files; then call the functions under test and check the results. A: I'm no expert but I'll give it a go. First a bit of refactoring: make them functional (remove all class stuff), remove unneeded things. This should make it much easier to test. You can always make the class call these functions if you really want it in a class. def pass_file_name(base_filename, exists): """return a list of filenames that exist based upon `base_filename`. use `os.path.isfile` for `exists`""" log_files = [] if exists(base_filename): log_files.append(base_filename) for i in range(1, 8): filename = base_filename + "." + str(i) if exists(filename): log_files.append(filename) return log_files def read_log_files (self, log_files): """read and parse each line from log_files use `pass_file_name` for `log_files`""" log_entrys = [] for filename in log_files: with open(filename) as myfile: for line in myfile: log_entrys.append(line.split()) return log_entrys Now we can easily test pass_file_name by passing in a custom function to exists. class Test_pass_file_name(unittest.TestCase): def test_1(self): """assume every file exists make sure all logs file are there""" exists = lambda _: True log_files = pass_file_name("a", exists) self.assertEqual(log_files, ["a", "a.1", "a.2", "a.3", "a.4", "a.5", "a.6", "a.7"]) def test_2(self): """assume no files exists make sure nothing returned""" exists = lambda _: False log_files = pass_file_name("a", exists) self.assertEqual(log_files, []) # ...more tests here ... As we assume os.path.isfile works we should have got pretty good testing of the first function. Though you could always have the test actually create some files then call pass_file_name with exists = os.path.isfile. The second one is harder to test; I have been told that the best (unit)tests don't touch the network, databases, GUI or the hard-drive. So maybe some more refactoring would make it easier. Mocking open could work; or would could actually write some long file in the test function and read them in. How do I mock an open used in a with statement (using the Mock framework in Python)? A: Bind the open name in the module to a function that mocks the file opening.
Unit testing functions that access files
I have two functions—one that builds the path to a set of files and another that reads the files. Below are the two functions: def pass_file_name(self): self.log_files= [] file_name = self.path+"\\access_"+self.appliacation+".log" if os.path.isfile(file_name): self.log_files.append(file_name) for i in xrange(7): file_name = self.path+"\\access_"+self.appliacation+".log"+"."+str(i+1) if os.path.isfile(file_name): self.log_files.append(file_name) return self.log_files def read_log_files (self, log_file_names): self.log_entrys = [] self.log_line = [] for i in log_file_names: self.f = open(i) for line in self.f: self.log_line = line.split(" ") #print self.log_line self.log_entrys.append(self.log_line) return self.log_entrys What would be the best way to unit test these two functions?
[ "You have two units here:\n\nOne that generate file paths\nSecond that reads them\n\nThus there should be two unit-test-cases (i.e. classes with tests). First would test only file paths generation. Second would test reading from predefined set of files you prepared in special subdirectory of tests directory, it should test in isolation from first test case.\nIn your case, you could probably have very short log files for tests. In this case for better readability and maintenance it is good idea to embed them right in test code. But in this case you'll have to improve your reading function a bit so it can take either file name or file-like object:\nfrom cStringIO import StringIO\n\n# ...\ndef test_some_log_reading_scenario(self):\n log1 = '\\n'.join([\n 'log line',\n 'another log line'\n ])\n log2 = '\\n'.join([\n 'another log another line',\n 'lala blah blah'\n ])\n # ...\n result = myobj.read_log_files([StringIO(log1), StringIO(log2)])\n # assert result\n\n", "Personally, I'd build a test harness that set up the required files before testing those two functions. \nFor each test case (where you expect the file to be present - remember to test failure cases too!), write some known logs into the appropriately named files; then call the functions under test and check the results.\n", "I'm no expert but I'll give it a go. First a bit of refactoring: make them functional (remove all class stuff), remove unneeded things. This should make it much easier to test. You can always make the class call these functions if you really want it in a class. \ndef pass_file_name(base_filename, exists):\n \"\"\"return a list of filenames that exist\n based upon `base_filename`.\n use `os.path.isfile` for `exists`\"\"\"\n\n log_files = []\n if exists(base_filename):\n log_files.append(base_filename)\n for i in range(1, 8):\n filename = base_filename + \".\" + str(i)\n if exists(filename):\n log_files.append(filename)\n return log_files\n\ndef read_log_files (self, log_files):\n \"\"\"read and parse each line from log_files\n use `pass_file_name` for `log_files`\"\"\"\n\n log_entrys = []\n for filename in log_files:\n with open(filename) as myfile:\n for line in myfile:\n log_entrys.append(line.split())\n return log_entrys\n\nNow we can easily test pass_file_name by passing in a custom function to exists. \nclass Test_pass_file_name(unittest.TestCase):\n def test_1(self):\n \"\"\"assume every file exists\n make sure all logs file are there\"\"\"\n exists = lambda _: True\n log_files = pass_file_name(\"a\", exists)\n self.assertEqual(log_files,\n [\"a\", \"a.1\", \"a.2\", \"a.3\", \n \"a.4\", \"a.5\", \"a.6\", \"a.7\"])\n\n def test_2(self):\n \"\"\"assume no files exists\n make sure nothing returned\"\"\"\n exists = lambda _: False\n log_files = pass_file_name(\"a\", exists)\n self.assertEqual(log_files, [])\n\n # ...more tests here ...\n\nAs we assume os.path.isfile works we should have got pretty good testing of the first function. Though you could always have the test actually create some files then call pass_file_name with exists = os.path.isfile. \nThe second one is harder to test; I have been told that the best (unit)tests don't touch the network, databases, GUI or the hard-drive. So maybe some more refactoring would make it easier. Mocking open could work; or would could actually write some long file in the test function and read them in. \nHow do I mock an open used in a with statement (using the Mock framework in Python)?\n", "Bind the open name in the module to a function that mocks the file opening.\n" ]
[ 8, 3, 2, 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0002279835_python_unit_testing.txt
Q: Formatting data from a python array I'm learning python for the first time. I have an aim which is to take data from an API and output it as xml. The output is stored in an array ("projectData"), here is an example of the output: [{'code': 'demo', 'created_at': datetime.datetime(2008, 6, 11, 7, 35, 19, tzinfo=<api.LocalTimezone object at 0x10072ab10>), 'created_by': None, 'id': 4, 'image': 'https://website.com/files/0000/0000/blah.jpg', 'name': 'Demo Project', 'description': 'This is for demonstration purposes', 'due': '2009-05-30', 'start': '2009-05-06', 'status': 'Active', 'stype': 'Demo', 'tag_list': [], 'type': 'Project', 'updated_at': datetime.datetime(2009, 5, 27, 1, 41, 55, tzinfo=<api.LocalTimezone object at 0x10072ab10>), 'updated_by': {'id': 24, 'name': 'Test', 'type': 'HumanUser'}, 'users': [{'id': 19, 'name': 'User 1', 'type': 'HumanUser'}, {'id': 18, 'name': 'User 2', 'type': 'HumanUser'}, {'id': 17, 'name': 'User 3', 'type': 'HumanUser'}, {'id': 16, 'name': 'User 4', 'type': 'HumanUser'}, {'id': 15, 'name': 'User 5', 'type': 'HumanUser'}, {'id': 14, 'name': 'User 6', 'type': 'HumanUser'}, {'id': 13, 'name': 'User 7', 'type': 'HumanUser'}, {'id': 12, 'name': 'User 8', 'type': 'HumanUser'}, {'id': 20, 'name': 'Client 1', 'type': 'HumanUser'}]}, (etc.) I've written some code which will output it as xml like so: for _project in projectData: print "<Project>" for key in _project: value = _project[key] print "\t<" + str(key) + ">" + str(value) + "</" + str(key) + ">" print("</Project>\n") Which actually gives me a result that works for me. However, because I'm new to this, I suspect that this isn't a very efficient approach, and may be susceptible to all sorts of bugs, I was hoping that someone more knowledgeable might have some pointers for me. The next thing I want to try with this is make it recursive, so that the "updated_by" element for example returns its own xml Thanks. A: Consider using something like genshi or etree instead of building the XML by hand. A: Here's an example using lxml.etree, incomplete.. and probably a bit naive. Really you should define a schema and make sure your output is consistent with it. Edit, said it was incomplete, added None type and assumed a created_by is like an updated_by when populated import datetime projects = [{'code': 'demo', 'created_at': datetime.datetime(2008, 6, 11, 7, 35, 19), 'created_by': None, 'id': 4, 'image': 'https://website.com/files/0000/0000/blah.jpg', 'name': 'Demo Project', 'description': 'This is for demonstration purposes', 'due': '2009-05-30', 'start': '2009-05-06', 'status': 'Active', 'stype': 'Demo', 'tag_list': [], 'type': 'Project', 'updated_at': datetime.datetime(2009, 5, 27, 1, 41, 55), 'updated_by': {'id': 24, 'name': 'Test', 'type': 'HumanUser'}, 'users': [{'id': 19, 'name': 'User 1', 'type': 'HumanUser'}, {'id': 18, 'name': 'User 2', 'type': 'HumanUser'}, {'id': 17, 'name': 'User 3', 'type': 'HumanUser'}, {'id': 16, 'name': 'User 4', 'type': 'HumanUser'}, {'id': 15, 'name': 'User 5', 'type': 'HumanUser'}, {'id': 14, 'name': 'User 6', 'type': 'HumanUser'}, {'id': 13, 'name': 'User 7', 'type': 'HumanUser'}, {'id': 12, 'name': 'User 8', 'type': 'HumanUser'}, {'id': 20, 'name': 'Client 1', 'type': 'HumanUser'}]}, ] from lxml import etree def E(tag, parent=None, content=None, children=None, **kw): e = etree.Element(tag) if not content is None: e.text = str(content) for k,v in kw.items(): e.set(k, str(v)) if not parent is None: parent.append(e) if not children is None: for c in children: e.append(c) return e def processProject(data): attrs = ('name','type','id') p = E('Project') for item in attrs: p.set(item,str(data[item])) for k,v in [ x for x in data.items() if x[0] not in attrs ]: if v is None: E(k,parent=p) elif isinstance(v,basestring): E(k,content=v,parent=p) elif isinstance(v,(float,long,int)): E(k,content=str(v),parent=p) elif isinstance(v,datetime.datetime): E(k,content=v.strftime('%Y-%m-%d %H%M'),parent=p) elif k == 'users': users = E(k,parent=p) for u in v: E('user',parent=users,**dict([ (x,str(y)) for (x,y) in u.items()])) elif k in ('updated_by','created_by'): E(k,parent=p,**dict([ (x,str(y)) for (x,y) in v.items()])) elif k == 'tag_list': taglist = E(k,parent=p) for t in v: E('tag',parent=taglist,content=t) return p >>> projxml = processProject(projects[0]) >>> etree.dump(projxml) <Project name="Demo Project" type="Project" id="4"> <status>Active</status> <code>demo</code> <created_at>2008-06-11 0735</created_at> <due>2009-05-30</due> <created_by/> <updated_at>2009-05-27 0141</updated_at> <start>2009-05-06</start> <image>https://website.com/files/0000/0000/blah.jpg</image> <updated_by type="HumanUser" id="24" name="Test"/> <users> <user type="HumanUser" id="19" name="User 1"/> <user type="HumanUser" id="18" name="User 2"/> <user type="HumanUser" id="17" name="User 3"/> <user type="HumanUser" id="16" name="User 4"/> <user type="HumanUser" id="15" name="User 5"/> <user type="HumanUser" id="14" name="User 6"/> <user type="HumanUser" id="13" name="User 7"/> <user type="HumanUser" id="12" name="User 8"/> <user type="HumanUser" id="20" name="Client 1"/> </users> <tag_list/> <stype>Demo</stype> <description>This is for demonstration purposes</description> </Project> A: Consider using some kind of template tool (even string.Template) instead of lots of string manipulation. For example, a generic dictionary-to-tag is pretty simple with the silly little built-in Template class. import string tag= string.Template( "<$tag>$value</$tag>" ) for k,v in someProjectDictionary: print tag.substitute( key=k, value=v ) However, graduating to Jinja or Mako makes this much, much simpler, since your entire XML document becomes simple iteration within the template language. {% for p in project_data %} <project> {% for k in p %} <{{k}}>{{p[k]}}</{{k}}> {% endfor %} </project> {% endfor %} You can create a separate file for this and use Jinja to handle the substitution into your XML template from your data. from jinja2 import Environment, PackageLoader env = Environment(loader=PackageLoader('yourapplication', 'templates')) template = env.get_template('mytemplate.html') print template.render(project_data=the_project_data_list)
Formatting data from a python array
I'm learning python for the first time. I have an aim which is to take data from an API and output it as xml. The output is stored in an array ("projectData"), here is an example of the output: [{'code': 'demo', 'created_at': datetime.datetime(2008, 6, 11, 7, 35, 19, tzinfo=<api.LocalTimezone object at 0x10072ab10>), 'created_by': None, 'id': 4, 'image': 'https://website.com/files/0000/0000/blah.jpg', 'name': 'Demo Project', 'description': 'This is for demonstration purposes', 'due': '2009-05-30', 'start': '2009-05-06', 'status': 'Active', 'stype': 'Demo', 'tag_list': [], 'type': 'Project', 'updated_at': datetime.datetime(2009, 5, 27, 1, 41, 55, tzinfo=<api.LocalTimezone object at 0x10072ab10>), 'updated_by': {'id': 24, 'name': 'Test', 'type': 'HumanUser'}, 'users': [{'id': 19, 'name': 'User 1', 'type': 'HumanUser'}, {'id': 18, 'name': 'User 2', 'type': 'HumanUser'}, {'id': 17, 'name': 'User 3', 'type': 'HumanUser'}, {'id': 16, 'name': 'User 4', 'type': 'HumanUser'}, {'id': 15, 'name': 'User 5', 'type': 'HumanUser'}, {'id': 14, 'name': 'User 6', 'type': 'HumanUser'}, {'id': 13, 'name': 'User 7', 'type': 'HumanUser'}, {'id': 12, 'name': 'User 8', 'type': 'HumanUser'}, {'id': 20, 'name': 'Client 1', 'type': 'HumanUser'}]}, (etc.) I've written some code which will output it as xml like so: for _project in projectData: print "<Project>" for key in _project: value = _project[key] print "\t<" + str(key) + ">" + str(value) + "</" + str(key) + ">" print("</Project>\n") Which actually gives me a result that works for me. However, because I'm new to this, I suspect that this isn't a very efficient approach, and may be susceptible to all sorts of bugs, I was hoping that someone more knowledgeable might have some pointers for me. The next thing I want to try with this is make it recursive, so that the "updated_by" element for example returns its own xml Thanks.
[ "Consider using something like genshi or etree instead of building the XML by hand.\n", "Here's an example using lxml.etree, incomplete.. and probably a bit naive. Really you should define a schema and make sure your output is consistent with it.\nEdit, said it was incomplete, added None type and assumed a created_by is like an updated_by when populated\nimport datetime\n\nprojects = [{'code': 'demo',\n 'created_at': datetime.datetime(2008, 6, 11, 7, 35, 19),\n 'created_by': None,\n 'id': 4,\n 'image': 'https://website.com/files/0000/0000/blah.jpg',\n 'name': 'Demo Project',\n 'description': 'This is for demonstration purposes',\n 'due': '2009-05-30',\n 'start': '2009-05-06',\n 'status': 'Active',\n 'stype': 'Demo',\n 'tag_list': [],\n 'type': 'Project',\n 'updated_at': datetime.datetime(2009, 5, 27, 1, 41, 55),\n 'updated_by': {'id': 24, 'name': 'Test', 'type': 'HumanUser'},\n 'users': [{'id': 19, 'name': 'User 1', 'type': 'HumanUser'},\n {'id': 18, 'name': 'User 2', 'type': 'HumanUser'},\n {'id': 17, 'name': 'User 3', 'type': 'HumanUser'},\n {'id': 16, 'name': 'User 4', 'type': 'HumanUser'},\n {'id': 15, 'name': 'User 5', 'type': 'HumanUser'},\n {'id': 14, 'name': 'User 6', 'type': 'HumanUser'},\n {'id': 13, 'name': 'User 7', 'type': 'HumanUser'},\n {'id': 12, 'name': 'User 8', 'type': 'HumanUser'},\n {'id': 20, 'name': 'Client 1', 'type': 'HumanUser'}]},\n ]\n\nfrom lxml import etree\n\ndef E(tag, parent=None, content=None, children=None, **kw):\n e = etree.Element(tag)\n if not content is None:\n e.text = str(content)\n for k,v in kw.items():\n e.set(k, str(v))\n if not parent is None:\n parent.append(e)\n if not children is None:\n for c in children:\n e.append(c)\n return e\n\ndef processProject(data):\n attrs = ('name','type','id')\n p = E('Project')\n for item in attrs:\n p.set(item,str(data[item]))\n for k,v in [ x for x in data.items() if x[0] not in attrs ]:\n if v is None:\n E(k,parent=p)\n elif isinstance(v,basestring):\n E(k,content=v,parent=p)\n elif isinstance(v,(float,long,int)):\n E(k,content=str(v),parent=p)\n elif isinstance(v,datetime.datetime):\n E(k,content=v.strftime('%Y-%m-%d %H%M'),parent=p)\n elif k == 'users':\n users = E(k,parent=p)\n for u in v:\n E('user',parent=users,**dict([ (x,str(y)) for (x,y) in u.items()]))\n elif k in ('updated_by','created_by'):\n E(k,parent=p,**dict([ (x,str(y)) for (x,y) in v.items()]))\n elif k == 'tag_list':\n taglist = E(k,parent=p)\n for t in v:\n E('tag',parent=taglist,content=t)\n return p\n\n>>> projxml = processProject(projects[0])\n>>> etree.dump(projxml)\n<Project name=\"Demo Project\" type=\"Project\" id=\"4\">\n <status>Active</status>\n <code>demo</code>\n <created_at>2008-06-11 0735</created_at>\n <due>2009-05-30</due>\n <created_by/>\n <updated_at>2009-05-27 0141</updated_at>\n <start>2009-05-06</start>\n <image>https://website.com/files/0000/0000/blah.jpg</image>\n <updated_by type=\"HumanUser\" id=\"24\" name=\"Test\"/>\n <users>\n <user type=\"HumanUser\" id=\"19\" name=\"User 1\"/>\n <user type=\"HumanUser\" id=\"18\" name=\"User 2\"/>\n <user type=\"HumanUser\" id=\"17\" name=\"User 3\"/>\n <user type=\"HumanUser\" id=\"16\" name=\"User 4\"/>\n <user type=\"HumanUser\" id=\"15\" name=\"User 5\"/>\n <user type=\"HumanUser\" id=\"14\" name=\"User 6\"/>\n <user type=\"HumanUser\" id=\"13\" name=\"User 7\"/>\n <user type=\"HumanUser\" id=\"12\" name=\"User 8\"/>\n <user type=\"HumanUser\" id=\"20\" name=\"Client 1\"/>\n </users>\n <tag_list/>\n <stype>Demo</stype>\n <description>This is for demonstration purposes</description>\n</Project>\n\n", "Consider using some kind of template tool (even string.Template) instead of lots of string manipulation.\nFor example, a generic dictionary-to-tag is pretty simple with the silly little built-in Template class.\nimport string\ntag= string.Template( \"<$tag>$value</$tag>\" )\nfor k,v in someProjectDictionary:\n print tag.substitute( key=k, value=v )\n\nHowever, graduating to Jinja or Mako makes this much, much simpler, since your entire XML document becomes simple iteration within the template language.\n{% for p in project_data %}\n<project>\n {% for k in p %}\n <{{k}}>{{p[k]}}</{{k}}>\n {% endfor %}\n</project>\n{% endfor %} \n\nYou can create a separate file for this and use Jinja to handle the substitution into your XML template from your data.\nfrom jinja2 import Environment, PackageLoader\nenv = Environment(loader=PackageLoader('yourapplication', 'templates'))\ntemplate = env.get_template('mytemplate.html')\nprint template.render(project_data=the_project_data_list)\n\n" ]
[ 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002280190_python.txt
Q: Pearson Similarity Score, how can I optimise this further? I have an implemented of Pearson's Similarity score for comparing two dictionaries of values. More time is spent in this method than anywhere else (potentially many millions of calls), so this is clearly the critical method to optimise. Even the slightest optimisation could have a big impact on my code, so I'm keen to explore even the smallest improvements. Here's what I have so far: def simple_pearson(v1,v2): si = [val for val in v1 if val in v2] n = len(si) if n==0: return 0.0 sum1 = 0.0 sum2 = 0.0 sum1_sq = 0.0 sum2_sq = 0.0 p_sum = 0.0 for v in si: val_1 = v1[v] val_2 = v2[v] sum1+=val_1 sum2+=val_2 sum1_sq+=pow(val_1,2) sum2_sq+=pow(val_2,2) p_sum+=val_1*val_2 # Calculate Pearson score num = p_sum-(sum1*sum2/n) temp = (sum1_sq-pow(sum1,2)/n) * (sum2_sq-pow(sum2,2)/n) if temp < 0.0: temp = -temp den = sqrt(temp) if den==0: return 1.0 r = num/den return r A: The real speed increase would be gained by moving to numpy or scipy. Short of that, there are microoptimizations: e.g. x*x is faster than pow(x,2); you could extract the values at the same time as the keys by doing, instead of: si = [val for val in v1 if val in v2] something like vs = [ (v1[val],v2[val]) for val in v1 if val in v2] and then sum1 = sum(x for x, y in vs) and so on; whether each of these brings time advantage needs microbenchmarking. Depending on how you're using these coefficients returning the square would save you a sqrt (that's a similar idea to using squares of distances between points, in geometry, rather than the distances themselves, and for the same reason -- saves you a sqrt; which makes sense because the coefficient IS a distance, kinda...;-). A: If you can use scipy, you could use the pearson function: http://www.scipy.org/doc/api_docs/SciPy.stats.stats.html#pearsonr Or you could copy/paste the code (it has a liberal license) from http://svn.scipy.org/svn/scipy/trunk/scipy/stats/stats.py (search for def pearson()). In the code np is just numpy (the code does import numpy as np). A: Scipy is the fastest! I have don some tests with the code above and also with a version I found on my comp, see below for results and the code: pearson 14.7597990757 sim_pearson 15.6806837987 scipy:pearsonr 0.451986019188 try: import psyco psyco.full() except ImportError: pass from math import sqrt def sim_pearson(set1, set2): si={} for item in set1: if item in set2: si[item] = 1 #number of elements n = len(si) #if none common, return 0 similarity if n == 0: return 0 #add up all the preferences sum1 = sum([set1[item] for item in si]) sum2 = sum([set2[item] for item in si]) #sum up the squares sum_sq1 = sum([pow(set1[item], 2) for item in si]) sum_sq2 = sum([pow(set2[item], 2) for item in si]) #sum up the products sum_p = sum([set1[item] * set2[item] for item in si]) nom = sum_p - ((sum1 * sum2) / n ) den = sqrt( (sum_sq1 - (sum1)**2 / n) * (sum_sq2 - (sum2)**2 / n) ) if den==0: return 0 return nom/den # from http://stackoverflow.com/questions/1307016/pearson-similarity-score-how-can-i-optimise-this-further def pearson(v1, v2): vs = [(v1[val],v2[val]) for val in v1 if val in v2] n = len(vs) if n==0: return 0.0 sum1,sum2,sum1_sq,sum2_sq,p_sum = 0.0, 0.0, 0.0, 0.0, 0.0 for v1,v2 in vs: sum1+=v1 sum2+=v2 sum1_sq+=v1*v1 sum2_sq+=v2*v2 p_sum+=v1*v2 # Calculate Pearson score num = p_sum-(sum1*sum2/n) temp = max((sum1_sq-pow(sum1,2)/n) * (sum2_sq-pow(sum2,2)/n),0) if temp: return num / sqrt(temp) return 1.0 if __name__ == "__main__": import timeit tsetup = """ from random import randrange from __main__ import pearson, sim_pearson from scipy.stats import pearsonr v1 = [randrange(0,1000) for x in range(1000)] v2 = [randrange(0,1000) for x in range(1000)] #gc.enable() """ t1 = timeit.Timer(stmt="pearson(v1,v2)", setup=tsetup) t2 = timeit.Timer(stmt="sim_pearson(v1,v2)", setup=tsetup) t3 = timeit.Timer(stmt="pearsonr(v1,v2)", setup=tsetup) tt = 1000 print 'pearson', t1.timeit(tt) print 'sim_pearson', t2.timeit(tt) print 'scipy:pearsonr', t3.timeit(tt) A: I'd suggest changing: [val for val in v1 if val in v2] to set(v1) & set(v2) do if not n: return 0.0 # and similar for den instead of if n == 0: return 0.0 and it's worth replacing last 6 lines with: try: return num / sqrt(abs(temp)) except ZeroDivisionError: return 1.0 A: Since it looks like you're doing quite a bit of numeric computation you should give Psyco a shot. It's a JIT compiler that analyzes running code and optimizes certain operations. Install it, then at the top of your file put: try: import psyco psyco.full() except ImportError: pass This will enable Psyco's JIT and should speed up your code somewhat, for free :) (actually not, it takes up more memory) A: If the inputs to any of your math functions are fairly constrained, you can use a lookup table instead of the math function. This can earn you some performance (speed) at the cost of extra memory to store the table. A: I'm not sure if this holds in Python. But calculating the sqrt is a processor intensive calculation. You might go for a fast approximation newton A: I'll post what I've got so far as an answer to differentiate it from the question. This is a combination of some techniques described above that seem to have given the best improvement s far. def pearson(v1,v2): vs = [(v1[val],v2[val]) for val in v1 if val in v2] n = len(vs) if n==0: return 0.0 sum1,sum2,sum1_sq,sum2_sq,p_sum = 0.0, 0.0, 0.0, 0.0, 0.0 for v1,v2 in vs: sum1+=v1 sum2+=v2 sum1_sq+=v1*v1 sum2_sq+=v2*v2 p_sum+=v1*v2 # Calculate Pearson score num = p_sum-(sum1*sum2/n) temp = max((sum1_sq-pow(sum1,2)/n) * (sum2_sq-pow(sum2,2)/n),0) if temp: return num / sqrt(temp) return 1.0 Edit: It looks like psyco gives a 15% improvment for this version which isn't massive but is enough to justify its use.
Pearson Similarity Score, how can I optimise this further?
I have an implemented of Pearson's Similarity score for comparing two dictionaries of values. More time is spent in this method than anywhere else (potentially many millions of calls), so this is clearly the critical method to optimise. Even the slightest optimisation could have a big impact on my code, so I'm keen to explore even the smallest improvements. Here's what I have so far: def simple_pearson(v1,v2): si = [val for val in v1 if val in v2] n = len(si) if n==0: return 0.0 sum1 = 0.0 sum2 = 0.0 sum1_sq = 0.0 sum2_sq = 0.0 p_sum = 0.0 for v in si: val_1 = v1[v] val_2 = v2[v] sum1+=val_1 sum2+=val_2 sum1_sq+=pow(val_1,2) sum2_sq+=pow(val_2,2) p_sum+=val_1*val_2 # Calculate Pearson score num = p_sum-(sum1*sum2/n) temp = (sum1_sq-pow(sum1,2)/n) * (sum2_sq-pow(sum2,2)/n) if temp < 0.0: temp = -temp den = sqrt(temp) if den==0: return 1.0 r = num/den return r
[ "The real speed increase would be gained by moving to numpy or scipy. Short of that, there are microoptimizations: e.g. x*x is faster than pow(x,2); you could extract the values at the same time as the keys by doing, instead of:\nsi = [val for val in v1 if val in v2]\n\nsomething like\nvs = [ (v1[val],v2[val]) for val in v1 if val in v2]\n\nand then\nsum1 = sum(x for x, y in vs)\n\nand so on; whether each of these brings time advantage needs microbenchmarking. Depending on how you're using these coefficients returning the square would save you a sqrt (that's a similar idea to using squares of distances between points, in geometry, rather than the distances themselves, and for the same reason -- saves you a sqrt; which makes sense because the coefficient IS a distance, kinda...;-).\n", "If you can use scipy, you could use the pearson function: http://www.scipy.org/doc/api_docs/SciPy.stats.stats.html#pearsonr\nOr you could copy/paste the code (it has a liberal license) from http://svn.scipy.org/svn/scipy/trunk/scipy/stats/stats.py (search for def pearson()).\nIn the code np is just numpy (the code does import numpy as np).\n", "Scipy is the fastest!\nI have don some tests with the code above and also with a version I found on my comp, see below for results and the code:\n\npearson 14.7597990757\nsim_pearson 15.6806837987\nscipy:pearsonr 0.451986019188\n\n\n\ntry:\n import psyco\n psyco.full()\nexcept ImportError:\n pass\n\nfrom math import sqrt\n\ndef sim_pearson(set1, set2):\n si={}\n for item in set1:\n if item in set2:\n si[item] = 1\n\n #number of elements\n n = len(si)\n\n #if none common, return 0 similarity\n if n == 0: return 0\n\n #add up all the preferences\n sum1 = sum([set1[item] for item in si])\n sum2 = sum([set2[item] for item in si])\n\n #sum up the squares\n sum_sq1 = sum([pow(set1[item], 2) for item in si])\n sum_sq2 = sum([pow(set2[item], 2) for item in si])\n\n #sum up the products\n sum_p = sum([set1[item] * set2[item] for item in si])\n\n nom = sum_p - ((sum1 * sum2) / n )\n den = sqrt( (sum_sq1 - (sum1)**2 / n) * (sum_sq2 - (sum2)**2 / n) )\n\n if den==0: return 0\n return nom/den\n\n\n\n# from http://stackoverflow.com/questions/1307016/pearson-similarity-score-how-can-i-optimise-this-further\ndef pearson(v1, v2):\n vs = [(v1[val],v2[val]) for val in v1 if val in v2]\n\n n = len(vs)\n\n if n==0: return 0.0\n\n sum1,sum2,sum1_sq,sum2_sq,p_sum = 0.0, 0.0, 0.0, 0.0, 0.0\n\n for v1,v2 in vs:\n sum1+=v1\n sum2+=v2\n sum1_sq+=v1*v1\n sum2_sq+=v2*v2\n p_sum+=v1*v2\n\n # Calculate Pearson score\n num = p_sum-(sum1*sum2/n)\n temp = max((sum1_sq-pow(sum1,2)/n) * (sum2_sq-pow(sum2,2)/n),0)\n if temp:\n return num / sqrt(temp)\n return 1.0\n\n\n\n\n\n\nif __name__ == \"__main__\":\n import timeit\n\n tsetup = \"\"\"\nfrom random import randrange\nfrom __main__ import pearson, sim_pearson\nfrom scipy.stats import pearsonr\nv1 = [randrange(0,1000) for x in range(1000)]\nv2 = [randrange(0,1000) for x in range(1000)]\n#gc.enable()\n\"\"\"\n t1 = timeit.Timer(stmt=\"pearson(v1,v2)\", setup=tsetup)\n t2 = timeit.Timer(stmt=\"sim_pearson(v1,v2)\", setup=tsetup)\n t3 = timeit.Timer(stmt=\"pearsonr(v1,v2)\", setup=tsetup)\n\n tt = 1000\n\n print 'pearson', t1.timeit(tt)\n print 'sim_pearson', t2.timeit(tt)\n print 'scipy:pearsonr', t3.timeit(tt)\n\n\n", "I'd suggest changing:\n[val for val in v1 if val in v2]\n\nto\nset(v1) & set(v2)\n\ndo\nif not n: return 0.0 # and similar for den\n\ninstead of\nif n == 0: return 0.0\n\nand it's worth replacing last 6 lines with:\ntry:\n return num / sqrt(abs(temp))\nexcept ZeroDivisionError:\n return 1.0\n\n", "Since it looks like you're doing quite a bit of numeric computation you should give Psyco a shot. It's a JIT compiler that analyzes running code and optimizes certain operations. Install it, then at the top of your file put:\ntry:\n import psyco\n psyco.full()\nexcept ImportError:\n pass\n\nThis will enable Psyco's JIT and should speed up your code somewhat, for free :) (actually not, it takes up more memory)\n", "If the inputs to any of your math functions are fairly constrained, you can use a lookup table instead of the math function. This can earn you some performance (speed) at the cost of extra memory to store the table.\n", "I'm not sure if this holds in Python. But calculating the sqrt is a processor intensive calculation.\nYou might go for a fast approximation newton\n", "I'll post what I've got so far as an answer to differentiate it from the question. This is a combination of some techniques described above that seem to have given the best improvement s far.\ndef pearson(v1,v2):\n vs = [(v1[val],v2[val]) for val in v1 if val in v2]\n\n n = len(vs)\n\n if n==0: return 0.0\n\n sum1,sum2,sum1_sq,sum2_sq,p_sum = 0.0, 0.0, 0.0, 0.0, 0.0\n\n for v1,v2 in vs:\n sum1+=v1\n sum2+=v2\n sum1_sq+=v1*v1\n sum2_sq+=v2*v2\n p_sum+=v1*v2\n\n # Calculate Pearson score\n num = p_sum-(sum1*sum2/n)\n temp = max((sum1_sq-pow(sum1,2)/n) * (sum2_sq-pow(sum2,2)/n),0)\n if temp:\n return num / sqrt(temp)\n return 1.0\n\nEdit: It looks like psyco gives a 15% improvment for this version which isn't massive but is enough to justify its use.\n" ]
[ 4, 2, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "optimization", "pearson", "python", "similarity" ]
stackoverflow_0001307016_optimization_pearson_python_similarity.txt
Q: Emacs defadvice on python-mode function In python-mode, there is a function called py-execute-region which sends a highlighted region of code to the Python buffer for evaluation. After evaluation, the cursor is in the Python buffer, but I would prefer that it remain in the script buffer so I can continue producing more code. I wrote a simple advising function: (defadvice py-execute-region (after py-execute-region-other-window activate) """ After execution, return cursor to script buffer """ (other-window 1) ) But this does not do anything at all. I've tried other variants like using 'around' rather than 'after'; setting a variable to the script buffer name and then pop-to-buffer to that buffer and stuff like that. No success! I wonder if the mechanics of this is obvious to someone... Thanks! A: In this case the solution appears to be (custom-set-variables '(py-shell-switch-buffers-on-execute nil)) A: Use around-advice to wrap the function in a call to save-window-excursion, which will restore the previous window configuration after the command completes. (defadvice py-execute-region (around preserve-window-configuration activate) "After execution, return cursor to script buffer" (save-window-excursion ad-do-it)) Keep in mind, though, that if the Python buffer wasn't already shown, it will still be hidden after the command completes. To remedy that, you can add another piece of advice to call switch-to-buffer-other-window at the end: (defadvice py-execute-region (after show-pybuf-other-window activate) "After execution, show the python buffer in another window." (switch-to-buffer-other-window "[PYTHON BUFFER NAME]")) Also, make sure you don't use """triple quotes""" in elisp. I don't think they work. A: What you have there works fine for me. And it should auto-activate, so a separate activation should be unnecessary. However, you do need to de-active and re-activate advice for changes to take effect: 1) define and activate advice 2) it doesn't do what you want, so change the advice 3) deactivate it: (ad-deactivate 'py-execute-region) 4) reactivate it: (ad-activate 'py-execute-region) Step 4 should pick up the changes you made in step 2. Alternately, you can change the code in step 2 and then just re-evaluate the code in step 4 (assuming the activate flag is set). A: I haven't actually tried this out, but I did do something similar for find-file, and over there I needed to call interactive before calling other-window. I actually have no real idea of Emacs Lisp, but this may work. (defadvice py-execute-region (after py-execute-region-other-window activate) (interactive) (other-window 1) )
Emacs defadvice on python-mode function
In python-mode, there is a function called py-execute-region which sends a highlighted region of code to the Python buffer for evaluation. After evaluation, the cursor is in the Python buffer, but I would prefer that it remain in the script buffer so I can continue producing more code. I wrote a simple advising function: (defadvice py-execute-region (after py-execute-region-other-window activate) """ After execution, return cursor to script buffer """ (other-window 1) ) But this does not do anything at all. I've tried other variants like using 'around' rather than 'after'; setting a variable to the script buffer name and then pop-to-buffer to that buffer and stuff like that. No success! I wonder if the mechanics of this is obvious to someone... Thanks!
[ "In this case the solution appears to be\n(custom-set-variables\n '(py-shell-switch-buffers-on-execute nil))\n\n", "Use around-advice to wrap the function in a call to\nsave-window-excursion, which will restore the previous window\nconfiguration after the command completes.\n(defadvice py-execute-region\n (around preserve-window-configuration activate)\n \"After execution, return cursor to script buffer\"\n (save-window-excursion ad-do-it))\n\nKeep in mind, though, that if the Python buffer wasn't already shown,\nit will still be hidden after the command completes. To remedy that,\nyou can add another piece of advice to call switch-to-buffer-other-window at the\nend:\n(defadvice py-execute-region\n (after show-pybuf-other-window activate)\n \"After execution, show the python buffer in another window.\"\n (switch-to-buffer-other-window \"[PYTHON BUFFER NAME]\"))\n\nAlso, make sure you don't use \"\"\"triple quotes\"\"\" in elisp. I don't\nthink they work.\n", "What you have there works fine for me. And it should auto-activate, so a separate activation should be unnecessary. However, you do need to de-active and re-activate advice for changes to take effect:\n1) define and activate advice\n2) it doesn't do what you want, so change the advice\n3) deactivate it: (ad-deactivate 'py-execute-region)\n4) reactivate it: (ad-activate 'py-execute-region)\nStep 4 should pick up the changes you made in step 2. Alternately, you can change the code in step 2 and then just re-evaluate the code in step 4 (assuming the activate flag is set).\n", "I haven't actually tried this out, but I did do something similar for find-file, and over there I needed to call interactive before calling other-window. I actually have no real idea of Emacs Lisp, but this may work.\n(defadvice py-execute-region \n (after py-execute-region-other-window activate) \n (interactive)\n (other-window 1) \n)\n\n" ]
[ 9, 2, 1, 1 ]
[]
[]
[ "advising_functions", "defadvice", "elisp", "emacs", "python" ]
stackoverflow_0001416882_advising_functions_defadvice_elisp_emacs_python.txt
Q: Discovering referers to SQLAlchemy object I have a lot of model classes with ralations between them with a CRUD interface to edit. The problem is that some objects can't be deleted since there are other objects refering to them. Sometimes I can setup ON DELETE rule to handle this case, but in most cases I don't want automatic deletion of related objects till they are unbound manually. Anyway, I'd like to present editor a list of objects refering to currently viewed one and highlight those that prevent its deletion due to FOREIGN KEY constraint. Is there a ready solution to automatically discover referers? Update The task seems to be quite common (e.g. django ORM shows all dependencies), so I wonder that there is no solution to it yet. There are two directions suggested: Enumerate all relations of current object and go through their backref. But there is no guarantee that all relations have backref defined. Moreover, there are some cases when backref is meaningless. Although I can define it everywhere I don't like doing this way and it's not reliable. (Suggested by van and stephan) Check all tables of MetaData object and collect dependencies from their foreign_keys property (the code of sqlalchemy_schemadisplay can be used as example, thanks to stephan's comments). This will allow to catch all dependencies between tables, but what I need is dependencies between model classes. Some foreign keys are defined in intermediate tables and have no models corresponding to them (used as secondary in relations). Sure, I can go farther and find related model (have to find a way to do it yet), but it looks too complicated. Solution Below is a method of base model class (designed for declarative extention) that I use as solution. It is not perfect and doesn't meet all my requirements, but it works for current state of my project. The result is collected as dictionary of dictionaries, so I can show them groupped by objects and their properties. I havn't decided yet whether it's good idea, since the list of referers sometimes is huge and I'm forced to limit it to some reasonable number. def _get_referers(self): db = object_session(self) cls, ident = identity_key(instance=self) medatada = cls.__table__.metadata result = {} # _mapped_models is my extension. It is collected by metaclass, so I didn't # look for other ways to find all model classes. for other_class in medatada._mapped_models: queries = {} for prop in class_mapper(other_class).iterate_properties: if not (isinstance(prop, PropertyLoader) and \ issubclass(cls, prop.mapper.class_)): continue query = db.query(prop.parent) comp = prop.comparator if prop.uselist: query = query.filter(comp.contains(self)) else: query = query.filter(comp==self) count = query.count() if count: queries[prop] = (count, query) if queries: result[other_class] = queries return result Thanks to all who helped me, especially stephan and van. A: SQL: I have to absolutely disagree with S.Lott' answer. I am not aware of out-of-the-box solution, but it is definitely possible to discover all the tables that have ForeignKey constraints to a given table. One needs to use properly the INFORMATION_SCHEMA views such as REFERENTIAL_CONSTRAINTS, KEY_COLUMN_USAGE, TABLE_CONSTRAINTS, etc. See SQL Server example. With some limitations and extensions, most versions of new relational databases support INFORMATION_SCHEMA standard. When you have all the FK information and the object (row) in the table, it is a matter of running few SELECT statements to get all other rows in other tables that refer to given row and prevent it from being deleted. SqlAlchemy: As noted by stephan in his comment, if you use orm with backref for relations, then it should be quite easy for you to get the list of parent objects that keep reference to the object you are trying to delete, because those objects are basically mapped properties of your object (child1.Parent). If you work with Table objects of sql alchemy (or not always use backref for relations), then you would have to get values of foreign_keys for all the tables, and then for all those ForeignKeys call references(...) method, providing your table as a parameter. In this way you will find all the FKs (and tables) that have reference to the table your object maps to. Then you can query all the objects that keep reference to your object by constructing the query for each of those FKs. A: In general, there's no way to "discover" all of the references in a relational database. In some databases, they may use declarative referential integrity in the form of explicit Foreign Key or Check constraints. But there's no requirement to do this. It can be incomplete or inconsistent. Any query can include a FK relationship that is not declared. Without the universe of all queries, you can't know the relationships which are used but not declared. To find "referers" in general, you must actually know the database design and have all queries. A: For each model class, you can easily see if all its one-to-many relations are empty simply by asking for the list in each case and seeing how many entries it contains. (There is probably a more efficient way implemented in terms of COUNT, too.) If there are any foreign keys relating to the object, and you have your object relations set up correctly, then at least one of these lists will be non-zero in length.
Discovering referers to SQLAlchemy object
I have a lot of model classes with ralations between them with a CRUD interface to edit. The problem is that some objects can't be deleted since there are other objects refering to them. Sometimes I can setup ON DELETE rule to handle this case, but in most cases I don't want automatic deletion of related objects till they are unbound manually. Anyway, I'd like to present editor a list of objects refering to currently viewed one and highlight those that prevent its deletion due to FOREIGN KEY constraint. Is there a ready solution to automatically discover referers? Update The task seems to be quite common (e.g. django ORM shows all dependencies), so I wonder that there is no solution to it yet. There are two directions suggested: Enumerate all relations of current object and go through their backref. But there is no guarantee that all relations have backref defined. Moreover, there are some cases when backref is meaningless. Although I can define it everywhere I don't like doing this way and it's not reliable. (Suggested by van and stephan) Check all tables of MetaData object and collect dependencies from their foreign_keys property (the code of sqlalchemy_schemadisplay can be used as example, thanks to stephan's comments). This will allow to catch all dependencies between tables, but what I need is dependencies between model classes. Some foreign keys are defined in intermediate tables and have no models corresponding to them (used as secondary in relations). Sure, I can go farther and find related model (have to find a way to do it yet), but it looks too complicated. Solution Below is a method of base model class (designed for declarative extention) that I use as solution. It is not perfect and doesn't meet all my requirements, but it works for current state of my project. The result is collected as dictionary of dictionaries, so I can show them groupped by objects and their properties. I havn't decided yet whether it's good idea, since the list of referers sometimes is huge and I'm forced to limit it to some reasonable number. def _get_referers(self): db = object_session(self) cls, ident = identity_key(instance=self) medatada = cls.__table__.metadata result = {} # _mapped_models is my extension. It is collected by metaclass, so I didn't # look for other ways to find all model classes. for other_class in medatada._mapped_models: queries = {} for prop in class_mapper(other_class).iterate_properties: if not (isinstance(prop, PropertyLoader) and \ issubclass(cls, prop.mapper.class_)): continue query = db.query(prop.parent) comp = prop.comparator if prop.uselist: query = query.filter(comp.contains(self)) else: query = query.filter(comp==self) count = query.count() if count: queries[prop] = (count, query) if queries: result[other_class] = queries return result Thanks to all who helped me, especially stephan and van.
[ "SQL: I have to absolutely disagree with S.Lott' answer.\nI am not aware of out-of-the-box solution, but it is definitely possible to discover all the tables that have ForeignKey constraints to a given table. One needs to use properly the INFORMATION_SCHEMA views such as REFERENTIAL_CONSTRAINTS, KEY_COLUMN_USAGE, TABLE_CONSTRAINTS, etc. See SQL Server example. With some limitations and extensions, most versions of new relational databases support INFORMATION_SCHEMA standard. When you have all the FK information and the object (row) in the table, it is a matter of running few SELECT statements to get all other rows in other tables that refer to given row and prevent it from being deleted.\nSqlAlchemy: As noted by stephan in his comment, if you use orm with backref for relations, then it should be quite easy for you to get the list of parent objects that keep reference to the object you are trying to delete, because those objects are basically mapped properties of your object (child1.Parent).\nIf you work with Table objects of sql alchemy (or not always use backref for relations), then you would have to get values of foreign_keys for all the tables, and then for all those ForeignKeys call references(...) method, providing your table as a parameter. In this way you will find all the FKs (and tables) that have reference to the table your object maps to. Then you can query all the objects that keep reference to your object by constructing the query for each of those FKs.\n", "In general, there's no way to \"discover\" all of the references in a relational database.\nIn some databases, they may use declarative referential integrity in the form of explicit Foreign Key or Check constraints.\nBut there's no requirement to do this. It can be incomplete or inconsistent.\nAny query can include a FK relationship that is not declared. Without the universe of all queries, you can't know the relationships which are used but not declared.\nTo find \"referers\" in general, you must actually know the database design and have all queries.\n", "For each model class, you can easily see if all its one-to-many relations are empty simply by asking for the list in each case and seeing how many entries it contains. (There is probably a more efficient way implemented in terms of COUNT, too.) If there are any foreign keys relating to the object, and you have your object relations set up correctly, then at least one of these lists will be non-zero in length.\n" ]
[ 6, 1, 0 ]
[]
[]
[ "orm", "python", "sqlalchemy" ]
stackoverflow_0002279919_orm_python_sqlalchemy.txt
Q: How to run server script indefinitely I would like to run an asynchronous program on a remote linux server indefinitely. This script doesn't output anything to the server itself(other than occasionally writing information to a mysql database). So far the only option I have been able to find is the nohup command: nohup script_name & From what I understand, nohup allows the command to run even after I log out of my SSH session while the '&' character lets the command run in the background. My question is simple: is this the best way to do what I would like? I am only trying to run a single script for long periods of time while occasionally stopping it to make updates. Also, if nohup is indeed the best option, what is the proper way to terminate the script when I need to? There seems to be some disagreement over what is the best way to kill a nohup process. Thanks A: What you are basically asking is "How do I create a daemon process?" What you want to do is "daemonize", there are many examples of this floating around on the web. The process is basically that you fork(), the child creates a new session, the parent exits, the child duplicates and then closes open file handles to the controlling terminal (STDIN, STDOUT, STDERR). There is a package available that will do all of this for you called python-daemon. To perform graceful shutdowns, look at the signal library for creating a signal handler. Also, searching the web for "python daemon" will bring up many reimplementations of the common C daemonizing process: http://code.activestate.com/recipes/66012/ A: If you can modify the script, then you can catch SIGHUP signals and avoid the need for nohup. In a bash script you would write: trap " echo ignoring hup; " SIGHUP You can employ the same technique to terminate the program: catch, say, a SIGUSR1 signal in a handler, set a flag and then gracefully exit from your main loop. This way you can send this signal of your choice to stop your program in a predictable way. A: There are some situations when you want to execute/start some scripts on a remote machine/server (which will terminate automatically) and disconnect from the server. eg: A script running on a box which when executed 1) takes a model and copies it to a custer (remote server) 2) creates a script for running a simulation with the wodel and push it to server 3) starts the script on the server and disconnect 4) The duty of the script thus started is to run the simulation in the server and once completed (will take days to complete) copy the results back to client. I would use the following command: ssh remoteserver 'nohup /path/to/script `</dev/null` >nohup.out 2>&1 &' eg: echo '#!/bin/bash rm -rf statuslist mkdir statuslist chmod u+x ~/monitor/concat.sh chmod u+x ~/monitor/script.sh nohup ./monitor/concat.sh & ' > script.sh chmod u+x script.sh rsync -azvp script.sh remotehost:/tmp ssh remoteshot '/tmp/script.sh `</dev/null` >nohup.out 2>&1 &' Hope this helps ;-) A: That is the simplest way to do it if you want to (or have to) avoid changing the script itself. If the script is always to be run like this, you can write a mini script containing the line you just typed and run that instead. (or use an alias, if appropriate) To answer you second question: $ nohup ./test & [3] 11789 $ Sending output to nohup.out $jobs [1]- Running emacs *h & [3]+ Running nohup ./test & $ kill %3 $ jobs [1]- Running emacs *h & [3]+ Exit 143 nohup ./test Ctrl+c works too, (sends a SIGINT) as does kill (sends a SIGTERM)
How to run server script indefinitely
I would like to run an asynchronous program on a remote linux server indefinitely. This script doesn't output anything to the server itself(other than occasionally writing information to a mysql database). So far the only option I have been able to find is the nohup command: nohup script_name & From what I understand, nohup allows the command to run even after I log out of my SSH session while the '&' character lets the command run in the background. My question is simple: is this the best way to do what I would like? I am only trying to run a single script for long periods of time while occasionally stopping it to make updates. Also, if nohup is indeed the best option, what is the proper way to terminate the script when I need to? There seems to be some disagreement over what is the best way to kill a nohup process. Thanks
[ "What you are basically asking is \"How do I create a daemon process?\" What you want to do is \"daemonize\", there are many examples of this floating around on the web. The process is basically that you fork(), the child creates a new session, the parent exits, the child duplicates and then closes open file handles to the controlling terminal (STDIN, STDOUT, STDERR).\nThere is a package available that will do all of this for you called python-daemon.\nTo perform graceful shutdowns, look at the signal library for creating a signal handler. \nAlso, searching the web for \"python daemon\" will bring up many reimplementations of the common C daemonizing process: http://code.activestate.com/recipes/66012/\n", "If you can modify the script, then you can catch SIGHUP signals and avoid the need for nohup. In a bash script you would write:\ntrap \" echo ignoring hup; \" SIGHUP\n\nYou can employ the same technique to terminate the program: catch, say, a SIGUSR1 signal in a handler, set a flag and then gracefully exit from your main loop. This way you can send this signal of your choice to stop your program in a predictable way.\n", "There are some situations when you want to execute/start some scripts on a remote machine/server (which will terminate automatically) and disconnect from the server.\neg: A script running on a box which when executed 1) takes a model and copies it to a custer (remote server) 2) creates a script for running a simulation with the wodel and push it to server 3) starts the script on the server and disconnect 4) The duty of the script thus started is to run the simulation in the server and once completed (will take days to complete) copy the results back to client.\nI would use the following command:\nssh remoteserver 'nohup /path/to/script `</dev/null` >nohup.out 2>&1 &'\n\neg:\necho '#!/bin/bash \nrm -rf statuslist \nmkdir statuslist \nchmod u+x ~/monitor/concat.sh \nchmod u+x ~/monitor/script.sh \nnohup ./monitor/concat.sh & \n' > script.sh \n\nchmod u+x script.sh\n\nrsync -azvp script.sh remotehost:/tmp\n\nssh remoteshot '/tmp/script.sh `</dev/null` >nohup.out 2>&1 &'\n\nHope this helps ;-)\n", "That is the simplest way to do it if you want to (or have to) avoid changing the script itself. If the script is always to be run like this, you can write a mini script containing the line you just typed and run that instead. (or use an alias, if appropriate) \nTo answer you second question:\n $ nohup ./test &\n[3] 11789\n $ Sending output to nohup.out\n\n$jobs\n[1]- Running emacs *h &\n[3]+ Running nohup ./test &\n$ kill %3\n$ jobs\n[1]- Running emacs *h &\n[3]+ Exit 143 nohup ./test\n\nCtrl+c works too, (sends a SIGINT) as does kill (sends a SIGTERM)\n" ]
[ 3, 2, 1, 0 ]
[]
[]
[ "linux", "nohup", "python" ]
stackoverflow_0001927144_linux_nohup_python.txt
Q: Python imports with different directory structures I'm working on a project where all the code in the source tree is separated into module directories, e.g.: modules/check/lib/check.py modules/edit/lib/edit.py During installation, the Python files are put in the same directory program_name under Python's site-packages. All the modules therefore use the syntax import program_name.edit. Because of the directory and import structure, the source modules are unable to import each other, so you'd have to install them each time you want to run anything in the source tree. My questions are therefore: Without modifying the directory structure, how can I make sure that modules/check/lib/check.py imports from modules/edit/lib/edit.py and that site-packages/program_name/check.py imports from site-packages/program_name/edit.py? And for a possible reorganization, what are best practices for the directory structure and imports in an environment like this? A: You can just add the /modules/ directories to your PYTHONPATH in your dev environment. Once installed in site-packages, calling import edit inside check.py will import the correct module since they are in the same directory. Calling import edit from your dev environ will import the one you added to your PYTHONPATH A: Why don't you install symlinks underneath prog_name on your dev machine?
Python imports with different directory structures
I'm working on a project where all the code in the source tree is separated into module directories, e.g.: modules/check/lib/check.py modules/edit/lib/edit.py During installation, the Python files are put in the same directory program_name under Python's site-packages. All the modules therefore use the syntax import program_name.edit. Because of the directory and import structure, the source modules are unable to import each other, so you'd have to install them each time you want to run anything in the source tree. My questions are therefore: Without modifying the directory structure, how can I make sure that modules/check/lib/check.py imports from modules/edit/lib/edit.py and that site-packages/program_name/check.py imports from site-packages/program_name/edit.py? And for a possible reorganization, what are best practices for the directory structure and imports in an environment like this?
[ "You can just add the /modules/ directories to your PYTHONPATH in your dev environment. Once installed in site-packages, calling import edit inside check.py will import the correct module since they are in the same directory. Calling import edit from your dev environ will import the one you added to your PYTHONPATH\n", "Why don't you install symlinks underneath prog_name on your dev machine?\n" ]
[ 2, 0 ]
[]
[]
[ "directory_structure", "import", "python" ]
stackoverflow_0002280761_directory_structure_import_python.txt
Q: Using SQLite3 in Python I am trying to store some parsed feed contents values in Sqlite database table in python.But facing error.Could anybody help me out of this issue.Infact it is so trivial question to ask!I am newbie!..Anyway thanks in advance! from sqlite3 import * import feedparser data = feedparser.parse("some url") conn = connect('location.db') curs = conn.cursor() curs.execute('''create table location_tr (id integer primary key, title text , updated text)''') for i in range(len(data['entries'])): curs.execute("insert into location_tr values\ (NULL, data.entries[i].title,data.feed.updated)") conn.commit() curs.execute("select * from location_tr") for row in curs: print row And Error is: Traceback (most recent call last): File "F:\JavaWorkspace\Test\src\sqlite_example.py", line 16, in <module> (NULL, data.entries[i].title,data.feed.updated)") sqlite3.OperationalError: near "[i]": syntax error A: Try curs.execute("insert into location_tr values\ (NULL, '%s', '%s')" % (data.entries[i].title, data.feed.updated)) A: the error should be this line curs.execute("insert into location_tr values\ (NULL, data.entries[i].title,data.feed.updated)") data.entries[i].title comes from Python. So if you enclose it in double quotes, it becomes a literal string, not a value. It should be something like this: curs.execute("insert into location_tr values (NULL," + data.entries[i].title +","+data.feed.updated+")")
Using SQLite3 in Python
I am trying to store some parsed feed contents values in Sqlite database table in python.But facing error.Could anybody help me out of this issue.Infact it is so trivial question to ask!I am newbie!..Anyway thanks in advance! from sqlite3 import * import feedparser data = feedparser.parse("some url") conn = connect('location.db') curs = conn.cursor() curs.execute('''create table location_tr (id integer primary key, title text , updated text)''') for i in range(len(data['entries'])): curs.execute("insert into location_tr values\ (NULL, data.entries[i].title,data.feed.updated)") conn.commit() curs.execute("select * from location_tr") for row in curs: print row And Error is: Traceback (most recent call last): File "F:\JavaWorkspace\Test\src\sqlite_example.py", line 16, in <module> (NULL, data.entries[i].title,data.feed.updated)") sqlite3.OperationalError: near "[i]": syntax error
[ "Try\ncurs.execute(\"insert into location_tr values\\\n (NULL, '%s', '%s')\" % (data.entries[i].title, data.feed.updated))\n\n", "the error should be this line\n curs.execute(\"insert into location_tr values\\\n (NULL, data.entries[i].title,data.feed.updated)\")\n\ndata.entries[i].title comes from Python. So if you enclose it in double quotes, it becomes a literal string, not a value. It should be something like this:\n curs.execute(\"insert into location_tr values (NULL,\" + data.entries[i].title +\",\"+data.feed.updated+\")\")\n\n" ]
[ 1, 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0002280882_python_sqlite.txt
Q: Django ORM and Unicode data I'm using following model to store info about pages: class Page(models.Model): title = models.TextField(blank = False, null = False) New data saves correctly, I'm saving Unicode data there (lots of non-ASCII titles). But when I'm performing query: page = Page.objects.filter(id = 1) page.title looks odd: u'\u042e\u0449\u0435\u043d\u043a\u043e' What could I made wrong? Thanks. Update: Really, when I'm print page.title - it looks OK. But I need to dump it to JSON, so after such code: dumps({'title': page.title}) All looks bad. Update 2: Thanks to everyone, pointed me that this behavoir is correct. But unicode-escaped strins are so long. Can I translate them to utf-8 somehow? A: You're doing nothing wrong. Have you tried printing it (or outputting it in a web page)? In [1]: l = u'\u042e\u0449\u0435\u043d\u043a\u043e' In [2]: print l Ющенко A: That's perfectly fine. It's "Ющенко" unicode-escaped. A: Might just be your shell not being able to display unicode characters maybe? What happens if you do print page.title? A: There is no problem with what you have posted so far. >>> print json.dumps(u'\u042e\u0449\u0435\u043d\u043a\u043e') "\u042e\u0449\u0435\u043d\u043a\u043e" Which is a correct JavaScript string literal. Assign that to a variable and you'll get Ющенко in a JavaScript string. What is the actual problem? What “looks bad”? A: That's correct behaviour: dumps encodes the json for you. It looks ugly now, but that's just for transmission. To see your unicode string again have to decode it (usually on the other end): >>> from django.utils.simplejson import dumps, loads >>> original = u'\u042e\u0449\u0435\u043d\u043a\u043e' >>> print original Ющенко >>> encoded = dumps(original) >>> print encoded "\u042e\u0449\u0435\u043d\u043a\u043e" >>> decoded = loads(encoded) >>> print decoded Ющенко Generally you won't need to decode it in python, it'll get loaded as a unicode string in javascript.
Django ORM and Unicode data
I'm using following model to store info about pages: class Page(models.Model): title = models.TextField(blank = False, null = False) New data saves correctly, I'm saving Unicode data there (lots of non-ASCII titles). But when I'm performing query: page = Page.objects.filter(id = 1) page.title looks odd: u'\u042e\u0449\u0435\u043d\u043a\u043e' What could I made wrong? Thanks. Update: Really, when I'm print page.title - it looks OK. But I need to dump it to JSON, so after such code: dumps({'title': page.title}) All looks bad. Update 2: Thanks to everyone, pointed me that this behavoir is correct. But unicode-escaped strins are so long. Can I translate them to utf-8 somehow?
[ "You're doing nothing wrong. Have you tried printing it (or outputting it in a web page)?\nIn [1]: l = u'\\u042e\\u0449\\u0435\\u043d\\u043a\\u043e'\n\nIn [2]: print l\nЮщенко\n\n", "That's perfectly fine. It's \"Ющенко\" unicode-escaped.\n", "Might just be your shell not being able to display unicode characters maybe?\nWhat happens if you do print page.title?\n", "There is no problem with what you have posted so far.\n>>> print json.dumps(u'\\u042e\\u0449\\u0435\\u043d\\u043a\\u043e')\n\"\\u042e\\u0449\\u0435\\u043d\\u043a\\u043e\"\n\nWhich is a correct JavaScript string literal. Assign that to a variable and you'll get Ющенко in a JavaScript string.\nWhat is the actual problem? What “looks bad”?\n", "That's correct behaviour: dumps encodes the json for you. It looks ugly now, but that's just for transmission. To see your unicode string again have to decode it (usually on the other end):\n>>> from django.utils.simplejson import dumps, loads\n>>> original = u'\\u042e\\u0449\\u0435\\u043d\\u043a\\u043e'\n>>> print original\nЮщенко\n>>> encoded = dumps(original)\n>>> print encoded\n\"\\u042e\\u0449\\u0435\\u043d\\u043a\\u043e\"\n>>> decoded = loads(encoded)\n>>> print decoded\nЮщенко\n\nGenerally you won't need to decode it in python, it'll get loaded as a unicode string in javascript.\n" ]
[ 3, 2, 1, 1, 1 ]
[]
[]
[ "django", "django_models", "orm", "python", "unicode" ]
stackoverflow_0002280855_django_django_models_orm_python_unicode.txt
Q: Python: Do (explicit) string parameters hurt performance? Suppose some function that always gets some parameter s that it does not use. def someFunc(s): # do something _not_ using s, for example a=1 now consider this call someFunc("the unused string") which gives a string as a parameter that is not built during runtime but compiled straight into the binary (hope thats right). The question is: when calling someFunc this way for, say, severalthousand times the reference to "the unused string" is always passed but does that slow the program down? in my naive thoughts i'd say the reference to "the unused string" is 'constant' and available in O(1) when a call to someFunc occurs. So i'd say 'no, that does not hurt performance'. Same question as before: "Am I right?" thanks for some :-) A: The string is passed (by reference) each time, but the overhead is way too tiny to really affect performance unless it's in a super-tight loop. A: this is an implementation detail of CPython, and may not apply to other pythons but yes, in many cases in a compiled module, a constant string will reference the same object, minimizing the overhead. In general, even if it didn't, you really shouldn't worry about it, as it's probably imperceptibly tiny compared to other things going on. However, here's a little interesting piece of code: >>> def somefunc(x): ... print id(x) # prints the memory address of object pointed to by x ... >>> >>> def test(): ... somefunc("hello") ... >>> test() 134900896 >>> test() 134900896 # Hooray, like expected, it's the same object id >>> somefunc("h" + "ello") 134900896 # Whoa, how'd that work? What's happening here is that python keeps a global string lookup and in many cases, even when you concatenate two strings, you will get the same object if the values match up. Note that this is an implementation detail, and you should NOT rely on it, as strings from any of: files, sockets, databases, string slicing, regex, or really any C module are not guaranteed to have this property. But it is interesting nonetheless.
Python: Do (explicit) string parameters hurt performance?
Suppose some function that always gets some parameter s that it does not use. def someFunc(s): # do something _not_ using s, for example a=1 now consider this call someFunc("the unused string") which gives a string as a parameter that is not built during runtime but compiled straight into the binary (hope thats right). The question is: when calling someFunc this way for, say, severalthousand times the reference to "the unused string" is always passed but does that slow the program down? in my naive thoughts i'd say the reference to "the unused string" is 'constant' and available in O(1) when a call to someFunc occurs. So i'd say 'no, that does not hurt performance'. Same question as before: "Am I right?" thanks for some :-)
[ "The string is passed (by reference) each time, but the overhead is way too tiny to really affect performance unless it's in a super-tight loop.\n", "this is an implementation detail of CPython, and may not apply to other pythons but yes, in many cases in a compiled module, a constant string will reference the same object, minimizing the overhead.\nIn general, even if it didn't, you really shouldn't worry about it, as it's probably imperceptibly tiny compared to other things going on.\nHowever, here's a little interesting piece of code:\n>>> def somefunc(x):\n... print id(x) # prints the memory address of object pointed to by x\n... \n>>> \n>>> def test():\n... somefunc(\"hello\")\n... \n>>> test()\n134900896\n>>> test()\n134900896 # Hooray, like expected, it's the same object id\n>>> somefunc(\"h\" + \"ello\")\n134900896 # Whoa, how'd that work?\n\nWhat's happening here is that python keeps a global string lookup and in many cases, even when you concatenate two strings, you will get the same object if the values match up.\nNote that this is an implementation detail, and you should NOT rely on it, as strings from any of: files, sockets, databases, string slicing, regex, or really any C module are not guaranteed to have this property. But it is interesting nonetheless.\n" ]
[ 2, 1 ]
[]
[]
[ "compile_time", "function", "parameters", "performance", "python" ]
stackoverflow_0002281019_compile_time_function_parameters_performance_python.txt
Q: XMPPPY have function to manage invitation in client side? I'm coding by python about Gtalk I use XMPPPY. But I can chat with GTalk client but the problem is I can't accept invitation. Is XMPPY can do ? A: Looks like you want to "authorize" the request. I'm assuming you've received the request at the client. In the roster class (xmpp.roster) there is an "Authorize" method. It sends the "subscribed" packet to accept the roster request. This is what the method looks like: def Authorize(self,jid): """ Authorise JID 'jid'. Works only if these JID requested auth previously. """ self._owner.send(Presence(jid,'subscribed')) Wait, that may not be what you're asking at all. Are you trying to process a chat or a roster request? Take a look at the example (small) client they have called xtalk.py. I think you're interested in the xmpp_message method.
XMPPPY have function to manage invitation in client side?
I'm coding by python about Gtalk I use XMPPPY. But I can chat with GTalk client but the problem is I can't accept invitation. Is XMPPY can do ?
[ "Looks like you want to \"authorize\" the request. I'm assuming you've received the request at the client. In the roster class (xmpp.roster) there is an \"Authorize\" method. It sends the \"subscribed\" packet to accept the roster request. This is what the method looks like:\ndef Authorize(self,jid):\n \"\"\" Authorise JID 'jid'. Works only if these JID requested auth previously. \"\"\" \n self._owner.send(Presence(jid,'subscribed')) \n\nWait, that may not be what you're asking at all. Are you trying to process a chat or a roster request? Take a look at the example (small) client they have called xtalk.py. I think you're interested in the xmpp_message method.\n" ]
[ 0 ]
[]
[]
[ "chat", "google_talk", "python", "xmpp" ]
stackoverflow_0002266040_chat_google_talk_python_xmpp.txt
Q: Removing empty items from a list (Python) I'm reading a file in Python that isn't well formatted, values are separated by multiple spaces and some tabs too so the lists returned has a lot of empty items, how do I remove/avoid those? This is my current code: import re f = open('myfile.txt','r') for line in f.readlines(): if re.search(r'\bDeposit', line): print line.split(' ') f.close() Thanks A: Don't explicitly specify ' ' as the delimiter. line.split() will split on all whitespace. It's equivalent to using re.split: >>> line = ' a b c \n\tg ' >>> line.split() ['a', 'b', 'c', 'g'] >>> import re >>> re.split('\s+', line) ['', 'a', 'b', 'c', 'g', ''] >>> re.split('\s+', line.strip()) ['a', 'b', 'c', 'g'] A: for line in open("file"): if " Deposit" in line: line=line.rstrip() print line.split() Update: for line in open("file"): if "Deposit" in line: line=line.rstrip() print line[line.index("Deposit"):].split() A: linesAsLists = [line.split() for line in open('myfile.txt', 'r') if 'Deposit' in line)] A: Why not do line.strip() before handling it? Also, you could use re.split to use a regex like '\s+' as your delimiter.
Removing empty items from a list (Python)
I'm reading a file in Python that isn't well formatted, values are separated by multiple spaces and some tabs too so the lists returned has a lot of empty items, how do I remove/avoid those? This is my current code: import re f = open('myfile.txt','r') for line in f.readlines(): if re.search(r'\bDeposit', line): print line.split(' ') f.close() Thanks
[ "Don't explicitly specify ' ' as the delimiter. line.split() will split on all whitespace. It's equivalent to using re.split:\n>>> line = ' a b c \\n\\tg '\n>>> line.split()\n['a', 'b', 'c', 'g']\n>>> import re\n>>> re.split('\\s+', line)\n['', 'a', 'b', 'c', 'g', '']\n>>> re.split('\\s+', line.strip())\n['a', 'b', 'c', 'g']\n\n", "for line in open(\"file\"):\n if \" Deposit\" in line:\n line=line.rstrip()\n print line.split()\n\nUpdate: \nfor line in open(\"file\"):\n if \"Deposit\" in line:\n line=line.rstrip()\n print line[line.index(\"Deposit\"):].split()\n\n", "linesAsLists = [line.split() for line in open('myfile.txt', 'r') if 'Deposit' in line)]\n\n", "Why not do line.strip() before handling it? Also, you could use re.split to use a regex like '\\s+' as your delimiter.\n" ]
[ 11, 2, 1, 0 ]
[]
[]
[ "list", "python", "regex", "split" ]
stackoverflow_0002281263_list_python_regex_split.txt
Q: Are there more ways to define a tuple with only one item? I know this is one way, by placing a comma: >>> empty = () >>> singleton = 'hello', # <-- note trailing comma >>> len(empty) 0 >>> len(singleton) 1 >>> singleton ('hello',) Source: http://docs.python.org/tutorial/datastructures.html Are there more ways to define a tuple with only 1 item? A: >>> tuple(['hello']) ('hello',) But the built-in syntax is there for a reason. A: Even though you can define a tuple as 'hello', I think it would be easy for someone to possibly miss the trailing comma if they were reading your code. I definitely prefer ('hello',) from a readability stand-point. A: singleton = ('hello',) This is more clear I guess, and @jleedev even more clear. But I like the method you used the best: singleton = 'hello', A: Another one is >>> (1, 2)[0:1] (1,) A very obfuscated way, but it is an alternative...
Are there more ways to define a tuple with only one item?
I know this is one way, by placing a comma: >>> empty = () >>> singleton = 'hello', # <-- note trailing comma >>> len(empty) 0 >>> len(singleton) 1 >>> singleton ('hello',) Source: http://docs.python.org/tutorial/datastructures.html Are there more ways to define a tuple with only 1 item?
[ ">>> tuple(['hello'])\n('hello',)\n\nBut the built-in syntax is there for a reason.\n", "Even though you can define a tuple as 'hello', I think it would be easy for someone to possibly miss the trailing comma if they were reading your code. I definitely prefer \n('hello',) from a readability stand-point.\n", "singleton = ('hello',)\nThis is more clear I guess, and @jleedev even more clear. But I like the method you used the best:\nsingleton = 'hello',\n", "Another one is\n>>> (1, 2)[0:1]\n(1,)\n\nA very obfuscated way, but it is an alternative...\n" ]
[ 11, 5, 2, 2 ]
[]
[]
[ "python", "singleton", "tuples" ]
stackoverflow_0002281409_python_singleton_tuples.txt
Q: Trouble importing modules in Python IDEs Right I'm getting a bit tired of this so hopefully you can help me sort it out once and for all. I'm really confused about what's going on with Python on my MacBook. I'm running OS X 10.6.2 and have installed python from the website (the package that includes IDLE). This works absolutely fine, and in fact IDLE will run everything I want to, it's just that I don't want to use IDLE. So, I tried Netbeans, and it's infuriating - it seems to be looking for libraries in completely the wrong place (even when I try and force it to look in different places for Python on my machine). Eclipse did something very similar. This leads to more problems; how exactly should one install modules into python? -Using MacPorts it seemingly disappears into some depths of opt/local/var/macports where it's found by nothing except IDLE. -Running "python setup.py install" from the command line USUALLY ends up with various errors regarding something like: warning: in /opt/local/lib/libfreetype.dylib, file is not of required architecture and then sometimes dumps something in Libraries\Python\2.6\site-packages that doesn't work. -Installing a .dmg version of any module literally seems to do absolutely nothing, can't find any trace of what it's done with it either, even from IDLE. It seems to be there's different versions of Python running on my machine, with different IDEs looking to different places for Python and it's modules. Aswell as this it seems that every method of installation of modules for python puts them in different places. Should it really be this difficult? Is there anyway of forcing Netbeans to run a particular version of python? Or is there a way to force everything to use only one of the versions? Also, which paths belong to which versions of Python? Yours, Seriously confused! Duncan A: I deal with this by sticking to the macports Python installation. For compatibility reasons, I'm very wary of mixing modules for different python versions. Using python_select, port installed modules and the macports version of easy_install should ensure that everything is found. In rare cases, you might have to fool with sys.path, but that should only be for 3rd party stuff that doesn't have a better installer. This solution isn't perfect, but it's worked ok for me. Just make sure you reconfigure your editor to point to the correct interpreter if you start your programs that way. If you need to distribute your software (and can't get in the ports catalog), you can always create a setup tool that targets the native python install.
Trouble importing modules in Python IDEs
Right I'm getting a bit tired of this so hopefully you can help me sort it out once and for all. I'm really confused about what's going on with Python on my MacBook. I'm running OS X 10.6.2 and have installed python from the website (the package that includes IDLE). This works absolutely fine, and in fact IDLE will run everything I want to, it's just that I don't want to use IDLE. So, I tried Netbeans, and it's infuriating - it seems to be looking for libraries in completely the wrong place (even when I try and force it to look in different places for Python on my machine). Eclipse did something very similar. This leads to more problems; how exactly should one install modules into python? -Using MacPorts it seemingly disappears into some depths of opt/local/var/macports where it's found by nothing except IDLE. -Running "python setup.py install" from the command line USUALLY ends up with various errors regarding something like: warning: in /opt/local/lib/libfreetype.dylib, file is not of required architecture and then sometimes dumps something in Libraries\Python\2.6\site-packages that doesn't work. -Installing a .dmg version of any module literally seems to do absolutely nothing, can't find any trace of what it's done with it either, even from IDLE. It seems to be there's different versions of Python running on my machine, with different IDEs looking to different places for Python and it's modules. Aswell as this it seems that every method of installation of modules for python puts them in different places. Should it really be this difficult? Is there anyway of forcing Netbeans to run a particular version of python? Or is there a way to force everything to use only one of the versions? Also, which paths belong to which versions of Python? Yours, Seriously confused! Duncan
[ "I deal with this by sticking to the macports Python installation. For compatibility reasons, I'm very wary of mixing modules for different python versions. \nUsing python_select, port installed modules and the macports version of easy_install should ensure that everything is found. In rare cases, you might have to fool with sys.path, but that should only be for 3rd party stuff that doesn't have a better installer.\nThis solution isn't perfect, but it's worked ok for me. Just make sure you reconfigure your editor to point to the correct interpreter if you start your programs that way. If you need to distribute your software (and can't get in the ports catalog), you can always create a setup tool that targets the native python install.\n" ]
[ 0 ]
[]
[]
[ "macos", "matplotlib", "python" ]
stackoverflow_0002282239_macos_matplotlib_python.txt
Q: Adding an entry to a python tuple I have a list of tuples representing x,y points. I also have a list of values for each of these points. How do I combine them into a list of lists (i.e one entry for each point [x,y,val]) or a list of tuples? Thanks A: You can't add entries to tuples, since tuples are immutable. But you can create a new list of lists: new = [[x, y, val] for (x, y), val in zip(points, vals)] A: Tuples are immutable, they can't be modified. Convert it to a list, then convert it back if you want to (list((a, b))).
Adding an entry to a python tuple
I have a list of tuples representing x,y points. I also have a list of values for each of these points. How do I combine them into a list of lists (i.e one entry for each point [x,y,val]) or a list of tuples? Thanks
[ "You can't add entries to tuples, since tuples are immutable. But you can create a new list of lists:\nnew = [[x, y, val] for (x, y), val in zip(points, vals)]\n\n", "Tuples are immutable, they can't be modified. Convert it to a list, then convert it back if you want to (list((a, b))).\n" ]
[ 10, 1 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0002282300_list_python_tuples.txt
Q: How Do I Get the Module Name of an Object's Class Definition Rather Than the Module Name of the Object's Instantiation? In python 2.5, I have the following code in a module called modtest.py: def print_method_module(method): def printer(self): print self.__module__ return method(self) return printer class ModTest(): @print_method_module def testmethod(self): pass if __name__ == "__main__": ModTest().testmethod() However, when I run this, it prints out: __main__ If I create a second file called modtest2.py and run it: import modtest if __name__ == "__main__": modtest.ModTest().testmethod() This prints out: modtest How can I change the decorator to always print out modtest, the name of the module in which the class is defined? A: When you execute a python source file directly, the module name of that file is __main__, even if it is known by another name when you execute some other file and import it. You probably want to do like you did in modtest2, and import the module containing the class definition instead of executing that file directly. However, you can get the filename of the main module like so, for your diagnostic purposes: def print_method_module(method): def printer(self): name = self.__module__ if name == '__main__': filename = sys.modules[self.__module__].__file__ name = os.path.splitext(os.path.basename(filename))[0] print name return method(self) return printer
How Do I Get the Module Name of an Object's Class Definition Rather Than the Module Name of the Object's Instantiation?
In python 2.5, I have the following code in a module called modtest.py: def print_method_module(method): def printer(self): print self.__module__ return method(self) return printer class ModTest(): @print_method_module def testmethod(self): pass if __name__ == "__main__": ModTest().testmethod() However, when I run this, it prints out: __main__ If I create a second file called modtest2.py and run it: import modtest if __name__ == "__main__": modtest.ModTest().testmethod() This prints out: modtest How can I change the decorator to always print out modtest, the name of the module in which the class is defined?
[ "When you execute a python source file directly, the module name of that file is __main__, even if it is known by another name when you execute some other file and import it. \nYou probably want to do like you did in modtest2, and import the module containing the class definition instead of executing that file directly. However, you can get the filename of the main module like so, for your diagnostic purposes:\ndef print_method_module(method):\n def printer(self):\n name = self.__module__\n if name == '__main__':\n filename = sys.modules[self.__module__].__file__\n name = os.path.splitext(os.path.basename(filename))[0]\n print name\n return method(self)\n return printer\n\n" ]
[ 18 ]
[ "I'm guessing you could use sys._getframe() hackery to get at what you want.\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0002282369_python.txt
Q: Suds + JIRA = SAXException I'm using Python 2.6 and suds 0.3.7 to interact with JIRA 4.0. When I connect to the JIRA server, I get information on all the issues just fine. However, when I want to update an issue, I get a SAXException from suds (presumably): WebFault: Server raised fault: org.xml.sax.SAXException: Found character data inside an array element while deserializing I'm following the steps described here: http://confluence.atlassian.com/display/JIRA/Creating+a+SOAP+Client only replacing SOAPpy calls with suds. My attempt to update an issue looks like this, complete with exceptions: >>> w="http://bugs/rpc/soap/jirasoapservice-v2?wsdl" >>> from suds.client import Client >>> client = Client(w) >>> auth = client.service.login("myname","mypass") >>> issue = client.service.getIssue(auth,"BUG-30112") >>> issue.summary This is the original summary for BUG-30112 >>> >>> client.service.updateIssue(auth,"BUG-30112",[ ... {"id":"summary","values":["My new summary"]}]) Traceback (most recent call last): File "<interactive input>", line 2, in <module> File "C:\Python26\lib\suds\client.py", line 535, in __call__ return client.invoke(args, kwargs) File "C:\Python26\lib\suds\client.py", line 595, in invoke result = self.send(msg) File "C:\Python26\lib\suds\client.py", line 630, in send result = self.failed(binding, e) File "C:\Python26\lib\suds\client.py", line 681, in failed r, p = binding.get_fault(reply) File "C:\Python26\lib\suds\bindings\binding.py", line 235, in get_fault raise WebFault(p, faultroot) WebFault: Server raised fault: 'org.xml.sax.SAXException: Found character data inside an array element while deserializing' >>> Has anyone seen a problem like this? A: How about increasing the verbosity to see what is being sent? Or use wireshark. You could also do the same with SOAPpy and compare exactly what is sent. Debugging soap errors is usually like this for me :-/ ~Matt A: Actually, by just changing the library from suds to SOAPpy, everything started working with no other modifications. Kind of annoying. I skipped SOAPpy because it seemed to have been abandoned and more complex to install, compared to suds. But SOAPpy works! Thanks, all. A: This will be solved if you switch to suds 3.0.9 (beta) ... the only one to have the fix.
Suds + JIRA = SAXException
I'm using Python 2.6 and suds 0.3.7 to interact with JIRA 4.0. When I connect to the JIRA server, I get information on all the issues just fine. However, when I want to update an issue, I get a SAXException from suds (presumably): WebFault: Server raised fault: org.xml.sax.SAXException: Found character data inside an array element while deserializing I'm following the steps described here: http://confluence.atlassian.com/display/JIRA/Creating+a+SOAP+Client only replacing SOAPpy calls with suds. My attempt to update an issue looks like this, complete with exceptions: >>> w="http://bugs/rpc/soap/jirasoapservice-v2?wsdl" >>> from suds.client import Client >>> client = Client(w) >>> auth = client.service.login("myname","mypass") >>> issue = client.service.getIssue(auth,"BUG-30112") >>> issue.summary This is the original summary for BUG-30112 >>> >>> client.service.updateIssue(auth,"BUG-30112",[ ... {"id":"summary","values":["My new summary"]}]) Traceback (most recent call last): File "<interactive input>", line 2, in <module> File "C:\Python26\lib\suds\client.py", line 535, in __call__ return client.invoke(args, kwargs) File "C:\Python26\lib\suds\client.py", line 595, in invoke result = self.send(msg) File "C:\Python26\lib\suds\client.py", line 630, in send result = self.failed(binding, e) File "C:\Python26\lib\suds\client.py", line 681, in failed r, p = binding.get_fault(reply) File "C:\Python26\lib\suds\bindings\binding.py", line 235, in get_fault raise WebFault(p, faultroot) WebFault: Server raised fault: 'org.xml.sax.SAXException: Found character data inside an array element while deserializing' >>> Has anyone seen a problem like this?
[ "How about increasing the verbosity to see what is being sent? Or use wireshark. You could also do the same with SOAPpy and compare exactly what is sent. Debugging soap errors is usually like this for me :-/ \n~Matt\n", "Actually, by just changing the library from suds to SOAPpy, everything started working with no other modifications. Kind of annoying. I skipped SOAPpy because it seemed to have been abandoned and more complex to install, compared to suds. But SOAPpy works!\nThanks, all.\n", "This will be solved if you switch to suds 3.0.9 (beta) ... the only one to have the fix.\n" ]
[ 1, 1, 1 ]
[]
[]
[ "jira", "python", "soap", "suds" ]
stackoverflow_0001609666_jira_python_soap_suds.txt
Q: Why/When in Python does `x==y` call `y.__eq__(x)`? The Python docs clearly state that x==y calls x.__eq__(y). However it seems that under many circumstances, the opposite is true. Where is it documented when or why this happens, and how can I work out for sure whether my object's __cmp__ or __eq__ methods are going to get called. Edit: Just to clarify, I know that __eq__ is called in preferecne to __cmp__, but I'm not clear why y.__eq__(x) is called in preference to x.__eq__(y), when the latter is what the docs state will happen. >>> class TestCmp(object): ... def __cmp__(self, other): ... print "__cmp__ got called" ... return 0 ... >>> class TestEq(object): ... def __eq__(self, other): ... print "__eq__ got called" ... return True ... >>> tc = TestCmp() >>> te = TestEq() >>> >>> 1 == tc __cmp__ got called True >>> tc == 1 __cmp__ got called True >>> >>> 1 == te __eq__ got called True >>> te == 1 __eq__ got called True >>> >>> class TestStrCmp(str): ... def __new__(cls, value): ... return str.__new__(cls, value) ... ... def __cmp__(self, other): ... print "__cmp__ got called" ... return 0 ... >>> class TestStrEq(str): ... def __new__(cls, value): ... return str.__new__(cls, value) ... ... def __eq__(self, other): ... print "__eq__ got called" ... return True ... >>> tsc = TestStrCmp("a") >>> tse = TestStrEq("a") >>> >>> "b" == tsc False >>> tsc == "b" False >>> >>> "b" == tse __eq__ got called True >>> tse == "b" __eq__ got called True Edit: From Mark Dickinson's answer and comment it would appear that: Rich comparison overrides __cmp__ __eq__ is it's own __rop__ to it's __op__ (and similar for __lt__, __ge__, etc) If the left object is a builtin or new-style class, and the right is a subclass of it, the right object's __rop__ is tried before the left object's __op__ This explains the behaviour in theTestStrCmp examples. TestStrCmp is a subclass of str but doesn't implement its own __eq__ so the __eq__ of str takes precedence in both cases (ie tsc == "b" calls b.__eq__(tsc) as an __rop__ because of rule 1). In the TestStrEq examples, tse.__eq__ is called in both instances because TestStrEq is a subclass of str and so it is called in preference. In the TestEq examples, TestEq implements __eq__ and int doesn't so __eq__ gets called both times (rule 1). But I still don't understand the very first example with TestCmp. tc is not a subclass on int so AFAICT 1.__cmp__(tc) should be called, but isn't. A: You're missing a key exception to the usual behaviour: when the right-hand operand is an instance of a subclass of the class of the left-hand operand, the special method for the right-hand operand is called first. See the documentation at: http://docs.python.org/reference/datamodel.html#coercion-rules and in particular, the following two paragraphs: For objects x and y, first x.__op__(y) is tried. If this is not implemented or returns NotImplemented, y.__rop__(x) is tried. If this is also not implemented or returns NotImplemented, a TypeError exception is raised. But see the following exception: Exception to the previous item: if the left operand is an instance of a built-in type or a new-style class, and the right operand is an instance of a proper subclass of that type or class and overrides the base’s __rop__() method, the right operand’s __rop__() method is tried before the left operand’s __op__() method. A: Actually, in the docs, it states: [__cmp__ is c]alled by comparison operations if rich comparison (see above) is not defined. __eq__ is a rich comparison method and, in the case of TestCmp, is not defined, hence the calling of __cmp__ A: Is this not documented in the Language Reference? Just from a quick look there, it looks like __cmp__ is ignored when __eq__, __lt__, etc are defined. I'm understanding that to include the case where __eq__ is defined on a parent class. str.__eq__ is already defined so __cmp__ on its subclasses will be ignored. object.__eq__ etc are not defined so __cmp__ on its subclasses will be honored. In response to the clarified question: I know that __eq__ is called in preferecne to __cmp__, but I'm not clear why y.__eq__(x) is called in preference to x.__eq__(y), when the latter is what the docs state will happen. Docs say x.__eq__(y) will be called first, but it has the option to return NotImplemented in which case y.__eq__(x) is called. I'm not sure why you're confident something different is going on here. Which case are you specifically puzzled about? I'm understanding you just to be puzzled about the "b" == tsc and tsc == "b" cases, correct? In either case, str.__eq__(onething, otherthing) is being called. Since you don't override the __eq__ method in TestStrCmp, eventually you're just relying on the base string method and it's saying the objects aren't equal. Without knowing the implementation details of str.__eq__, I don't know whether ("b").__eq__(tsc) will return NotImplemented and give tsc a chance to handle the equality test. But even if it did, the way you have TestStrCmp defined, you're still going to get a false result. So it's not clear what you're seeing here that's unexpected. Perhaps what's happening is that Python is preferring __eq__ to __cmp__ if it's defined on either of the objects being compared, whereas you were expecting __cmp__ on the leftmost object to have priority over __eq__ on the righthand object. Is that it? A: As I know, __eq__() is a so-called “rich comparison” method, and is called for comparison operators in preference to __cmp__() below. __cmp__() is called if "rich comparison" is not defined. So in A == B: If __eq__() is defined in A it will be called Else __cmp__() will be called __eq__() defined in 'str' so your __cmp__() function was not called. The same rule is for __ne__(), __gt__(), __ge__(), __lt__() and __le__() "rich comparison" methods.
Why/When in Python does `x==y` call `y.__eq__(x)`?
The Python docs clearly state that x==y calls x.__eq__(y). However it seems that under many circumstances, the opposite is true. Where is it documented when or why this happens, and how can I work out for sure whether my object's __cmp__ or __eq__ methods are going to get called. Edit: Just to clarify, I know that __eq__ is called in preferecne to __cmp__, but I'm not clear why y.__eq__(x) is called in preference to x.__eq__(y), when the latter is what the docs state will happen. >>> class TestCmp(object): ... def __cmp__(self, other): ... print "__cmp__ got called" ... return 0 ... >>> class TestEq(object): ... def __eq__(self, other): ... print "__eq__ got called" ... return True ... >>> tc = TestCmp() >>> te = TestEq() >>> >>> 1 == tc __cmp__ got called True >>> tc == 1 __cmp__ got called True >>> >>> 1 == te __eq__ got called True >>> te == 1 __eq__ got called True >>> >>> class TestStrCmp(str): ... def __new__(cls, value): ... return str.__new__(cls, value) ... ... def __cmp__(self, other): ... print "__cmp__ got called" ... return 0 ... >>> class TestStrEq(str): ... def __new__(cls, value): ... return str.__new__(cls, value) ... ... def __eq__(self, other): ... print "__eq__ got called" ... return True ... >>> tsc = TestStrCmp("a") >>> tse = TestStrEq("a") >>> >>> "b" == tsc False >>> tsc == "b" False >>> >>> "b" == tse __eq__ got called True >>> tse == "b" __eq__ got called True Edit: From Mark Dickinson's answer and comment it would appear that: Rich comparison overrides __cmp__ __eq__ is it's own __rop__ to it's __op__ (and similar for __lt__, __ge__, etc) If the left object is a builtin or new-style class, and the right is a subclass of it, the right object's __rop__ is tried before the left object's __op__ This explains the behaviour in theTestStrCmp examples. TestStrCmp is a subclass of str but doesn't implement its own __eq__ so the __eq__ of str takes precedence in both cases (ie tsc == "b" calls b.__eq__(tsc) as an __rop__ because of rule 1). In the TestStrEq examples, tse.__eq__ is called in both instances because TestStrEq is a subclass of str and so it is called in preference. In the TestEq examples, TestEq implements __eq__ and int doesn't so __eq__ gets called both times (rule 1). But I still don't understand the very first example with TestCmp. tc is not a subclass on int so AFAICT 1.__cmp__(tc) should be called, but isn't.
[ "You're missing a key exception to the usual behaviour: when the right-hand operand is an instance of a subclass of the class of the left-hand operand, the special method for the right-hand operand is called first.\nSee the documentation at:\nhttp://docs.python.org/reference/datamodel.html#coercion-rules\nand in particular, the following two paragraphs:\n\nFor objects x and y, first\n x.__op__(y) is tried. If this is not\n implemented or returns\n NotImplemented, y.__rop__(x) is\n tried. If this is also not implemented\n or returns NotImplemented, a\n TypeError exception is raised. But see\n the following exception:\nException to the previous item: if the\n left operand is an instance of a\n built-in type or a new-style class,\n and the right operand is an instance\n of a proper subclass of that type or\n class and overrides the base’s\n __rop__() method, the right\n operand’s __rop__() method is tried\n before the left operand’s __op__()\n method.\n\n", "Actually, in the docs, it states:\n\n[__cmp__ is c]alled by comparison operations if rich comparison (see above) is not defined.\n\n__eq__ is a rich comparison method and, in the case of TestCmp, is not defined, hence the calling of __cmp__\n", "Is this not documented in the Language Reference? Just from a quick look there, it looks like __cmp__ is ignored when __eq__, __lt__, etc are defined. I'm understanding that to include the case where __eq__ is defined on a parent class. str.__eq__ is already defined so __cmp__ on its subclasses will be ignored. object.__eq__ etc are not defined so __cmp__ on its subclasses will be honored.\nIn response to the clarified question: \n\nI know that __eq__ is called in\n preferecne to __cmp__, but I'm not\n clear why y.__eq__(x) is called in\n preference to x.__eq__(y), when the\n latter is what the docs state will\n happen.\n\nDocs say x.__eq__(y) will be called first, but it has the option to return NotImplemented in which case y.__eq__(x) is called. I'm not sure why you're confident something different is going on here.\nWhich case are you specifically puzzled about? I'm understanding you just to be puzzled about the \"b\" == tsc and tsc == \"b\" cases, correct? In either case, str.__eq__(onething, otherthing) is being called. Since you don't override the __eq__ method in TestStrCmp, eventually you're just relying on the base string method and it's saying the objects aren't equal.\nWithout knowing the implementation details of str.__eq__, I don't know whether (\"b\").__eq__(tsc) will return NotImplemented and give tsc a chance to handle the equality test. But even if it did, the way you have TestStrCmp defined, you're still going to get a false result.\nSo it's not clear what you're seeing here that's unexpected.\nPerhaps what's happening is that Python is preferring __eq__ to __cmp__ if it's defined on either of the objects being compared, whereas you were expecting __cmp__ on the leftmost object to have priority over __eq__ on the righthand object. Is that it?\n", "As I know, __eq__() is a so-called “rich comparison” method, and is called for comparison operators in preference to __cmp__() below. __cmp__() is called if \"rich comparison\" is not defined.\nSo in A == B:\n If __eq__() is defined in A it will be called\n Else __cmp__() will be called\n__eq__() defined in 'str' so your __cmp__() function was not called.\nThe same rule is for __ne__(), __gt__(), __ge__(), __lt__() and __le__() \"rich comparison\" methods.\n" ]
[ 33, 6, 1, 1 ]
[]
[]
[ "comparison", "operator_overloading", "python" ]
stackoverflow_0002281222_comparison_operator_overloading_python.txt
Q: Python, trying to run a program from the command prompt I am trying to run a program from the command prompt in windows. I am having some issues. The code is below: commandString = "'C:\Program Files\WebShot\webshotcmd.exe' //url '" + columns[3] + "' //out '"+columns[1]+"~"+columns[2]+".jpg'" os.system(commandString) time.sleep(10) So with the single quotes I get "The filename, directory name, or volume label syntax is incorrect." If I replace the single quotes with \" then it says something to the effect of "'C:\Program' is not a valid executable." I realize it is a syntax error, but I am not quite sure how to fix this.... column[3] contains a full url copy pasted from a web browser (so it should be url encoded). column[1] will only contain numbers and periods. column[2] contains some text, double quotes and colons are replaced. Mentioning just in case... Thanks! A: Windows requires double quotes in this situation, and you used single quotes. Use the subprocess module rather than os.system, which is more robust and avoids calling the shell directly, making you not have to worry about confusing escaping issues. Dont use + to put together long strings. Use string formatting (string %s" % (formatting,)), which is more readable, efficient, and idiomatic. In this case, don't form a long string as a shell command anyhow, make a list and pass it to subprocess.call. As best as I can tell you are escaping your forward slash but not your backslashes, which is backwards. A string literal with // has both slashes in the string it makes. In any event, rather than either you should use the os.path module which avoids any confusion from parsing escapes and often makes scripts more portable. A: Use the subprocess module for calling system commands. Also ,try removing the single quotes and use double quotes.
Python, trying to run a program from the command prompt
I am trying to run a program from the command prompt in windows. I am having some issues. The code is below: commandString = "'C:\Program Files\WebShot\webshotcmd.exe' //url '" + columns[3] + "' //out '"+columns[1]+"~"+columns[2]+".jpg'" os.system(commandString) time.sleep(10) So with the single quotes I get "The filename, directory name, or volume label syntax is incorrect." If I replace the single quotes with \" then it says something to the effect of "'C:\Program' is not a valid executable." I realize it is a syntax error, but I am not quite sure how to fix this.... column[3] contains a full url copy pasted from a web browser (so it should be url encoded). column[1] will only contain numbers and periods. column[2] contains some text, double quotes and colons are replaced. Mentioning just in case... Thanks!
[ "\nWindows requires double quotes in this situation, and you used single quotes.\nUse the subprocess module rather than os.system, which is more robust and avoids calling the shell directly, making you not have to worry about confusing escaping issues.\nDont use + to put together long strings. Use string formatting (string %s\" % (formatting,)), which is more readable, efficient, and idiomatic.\nIn this case, don't form a long string as a shell command anyhow, make a list and pass it to subprocess.call.\nAs best as I can tell you are escaping your forward slash but not your backslashes, which is backwards. A string literal with // has both slashes in the string it makes. In any event, rather than either you should use the os.path module which avoids any confusion from parsing escapes and often makes scripts more portable.\n\n", "Use the subprocess module for calling system commands. Also ,try removing the single quotes and use double quotes.\n" ]
[ 2, 1 ]
[]
[]
[ "command_line", "command_prompt", "os.system", "python", "windows" ]
stackoverflow_0002282544_command_line_command_prompt_os.system_python_windows.txt
Q: How to see if code is backwards compatible for Python? I have some code that I am trying to make it play nicely with ESRI's geoprocessor. However, ESRI's geoprocessor runs on Python 2.2, 2.3, 2.4, 2.5. We need to make our tools work on any version. So I've spent a lot of time working and coding workarounds for different versions, such that the wrapper geoprocessor has identical functionality across all versions. Now here's the big thing, is there some sort of application that can basically scan modules to see if its syntax and methods are backwards compatible with the above Python version's? Unfortunately, I cannot install Python 2.2 since I have Arcgis 9.3, which requires Python 2.5. And vice versa, I've gotten pretty much all the module dependencies sorted and worked out. (win32com, ctypes, etc.). But I am worried about my actual code, I could spend hours going and reading what keywords were added for what version etc, however this basically will be a huge headache. Is there some sort of application that does these things? A: If you are actively developing a commercial product, and you -really- want to support all these versions properly, I would suggest: Writing an automated test suite that can be run and tests functionality for your entire library/application/whatever. Setting up a machine, or ideally virtual machine for each test environment (python 2.2-2.6 and any platform combinations if your product is not win32 only). This is especially easy to do nowadays given that there are several free virtualization products now (VirtualBox and VMWare Server, to name two) Using something like buildbot to automate the test running on all the other platforms, and collecting the results. I might mention however, that there have been significant changes between 2.2 and 2.3, and again between 2.3 and 2.4. This is why most python libraries out there only support 2.3, and a number are moving to only supporting 2.4 and up now. Every major release has a "What's new in python 2.x" document, but coding for 2.2 means you miss out on: Generators (2.3) (well actually, you can get them in 2.2 with from __future__ import generators) Generator expressions (2.4) the subprocess module (2.4) Decorator syntax (2.4) sets (2.3) decimal (2.4, but can be backported) datetime (2.3) itertools (2.3) Just to name a very small subset of awesome things you probably can't have. You have to really consider how badly you want to support a 7-year old python version, and miss out on a lot of cool features that can reduce your code size (or possibly just increase readability). A: Try pyqver: https://github.com/ghewgill/pyqver/ Gives you the minimum version for given python script analyzing the keywords and modules used. Also, you can compile locally python 2.2 and use virtualenv to create a python 2.2 environment with the --python flag.
How to see if code is backwards compatible for Python?
I have some code that I am trying to make it play nicely with ESRI's geoprocessor. However, ESRI's geoprocessor runs on Python 2.2, 2.3, 2.4, 2.5. We need to make our tools work on any version. So I've spent a lot of time working and coding workarounds for different versions, such that the wrapper geoprocessor has identical functionality across all versions. Now here's the big thing, is there some sort of application that can basically scan modules to see if its syntax and methods are backwards compatible with the above Python version's? Unfortunately, I cannot install Python 2.2 since I have Arcgis 9.3, which requires Python 2.5. And vice versa, I've gotten pretty much all the module dependencies sorted and worked out. (win32com, ctypes, etc.). But I am worried about my actual code, I could spend hours going and reading what keywords were added for what version etc, however this basically will be a huge headache. Is there some sort of application that does these things?
[ "If you are actively developing a commercial product, and you -really- want to support all these versions properly, I would suggest:\n\nWriting an automated test suite that can be run and tests functionality for your entire library/application/whatever.\nSetting up a machine, or ideally virtual machine for each test environment (python 2.2-2.6 and any platform combinations if your product is not win32 only). This is especially easy to do nowadays given that there are several free virtualization products now (VirtualBox and VMWare Server, to name two)\nUsing something like buildbot to automate the test running on all the other platforms, and collecting the results.\n\nI might mention however, that there have been significant changes between 2.2 and 2.3, and again between 2.3 and 2.4. This is why most python libraries out there only support 2.3, and a number are moving to only supporting 2.4 and up now. \nEvery major release has a \"What's new in python 2.x\" document, but coding for 2.2 means you miss out on:\n\nGenerators (2.3) (well actually, you can get them in 2.2 with from __future__ import generators)\nGenerator expressions (2.4)\nthe subprocess module (2.4)\nDecorator syntax (2.4)\nsets (2.3)\ndecimal (2.4, but can be backported)\ndatetime (2.3)\nitertools (2.3)\n\nJust to name a very small subset of awesome things you probably can't have.\nYou have to really consider how badly you want to support a 7-year old python version, and miss out on a lot of cool features that can reduce your code size (or possibly just increase readability).\n", "Try pyqver: https://github.com/ghewgill/pyqver/\nGives you the minimum version for given python script analyzing the keywords and modules used.\nAlso, you can compile locally python 2.2 and use virtualenv to create a python 2.2 environment with the --python flag.\n" ]
[ 11, 10 ]
[]
[]
[ "backwards_compatibility", "python" ]
stackoverflow_0002282882_backwards_compatibility_python.txt
Q: Is there a cleaner or more efficient to do this Python assignment? Here's the code I have now: lang = window.get_active_document().get_language() if lang != None: lang = lang.get_name() Is there a better way to do that? I'm new to Pythonic and was wondering if there's a more Python way to say "something equals this if x is true, else it equals that." Thanks. A: You could do lang = lang and lang.get_name() instead of the 'if' statement. If lang is None it will stay None. If not, it will be set to lang.get_name(). I'm not sure if that syntax makes things much clearer, though. P.S. Instead of lang != None you should use not lang is None. A: Try lang = lang.get_name() if lang else None A: try: lang = window.get_active_document().get_language().get_name() except AttributeError: lang = None The advantage here is that window itself and all three nested methods become guarded in one statement. A: Your solution is fine and clearer most solutions offered so far. Slightly more pythonic would be: lang = window.get_active_document().get_language() if lang: lang = lang.get_name() or lang = window.get_active_document().get_language() if lang is not None: lang = lang.get_name()
Is there a cleaner or more efficient to do this Python assignment?
Here's the code I have now: lang = window.get_active_document().get_language() if lang != None: lang = lang.get_name() Is there a better way to do that? I'm new to Pythonic and was wondering if there's a more Python way to say "something equals this if x is true, else it equals that." Thanks.
[ "You could do lang = lang and lang.get_name() instead of the 'if' statement.\nIf lang is None it will stay None. If not, it will be set to lang.get_name().\nI'm not sure if that syntax makes things much clearer, though.\nP.S. Instead of lang != None you should use not lang is None.\n", "Try\nlang = lang.get_name() if lang else None\n\n", "try:\n lang = window.get_active_document().get_language().get_name()\nexcept AttributeError:\n lang = None\n\nThe advantage here is that window itself and all three nested methods become guarded in one statement.\n", "Your solution is fine and clearer most solutions offered so far. Slightly more pythonic would be:\nlang = window.get_active_document().get_language()\nif lang:\n lang = lang.get_name()\n\nor\nlang = window.get_active_document().get_language()\nif lang is not None:\n lang = lang.get_name()\n\n" ]
[ 7, 2, 2, 1 ]
[]
[]
[ "python", "variable_assignment" ]
stackoverflow_0002282526_python_variable_assignment.txt
Q: Help for novice choosing between Java and Python for app with sql db I'm going to write my first non-Access project, and I need advice on choosing the platform. I will be installing it on multiple friends' and family's computers, so (since I'm sure many, many platforms would suffice just fine for my app), my highest priority has two parts: 1) ease of install for the non-technical user and, 2) minimizing compatibility problems. I want to be able to fix bugs and make changes and roll them out without having to troubleshoot OS and program conflicts on their computers (or at least keeping those things to the absolute minimum-this is why these concerns are my highest priority in choosing a platform.) I have narrowed it down to Python or Java. I like Java's use of the JVM, which seems like would serve to protect against incompatibilities on individual computers nicely. And I've heard a lot of good things about Python, but I don't know how much more prone to incompatibilities it is vs Java. In case it is important, I know the app will definitely use some flavor of a free server-enabled SQL db (server-enabled because I want to be able to run the app from multiple computers), but I don't know which to use yet. I thought I could decide that next. My experience level: I've taken a C++ (console app only) class and done some VBA in Access, but mostly I'm going to have to jump in and learn as I go. So of course I don't know much about all of this. I'm not in the computer field, this is just a hobby. So, which would be better for this app, Java or Python? (In case it comes up, I don't want to make it browser-based at all. I've dealt with individual computers' browser settings breaking programs, and that goes against part 2 of my top priority - maximum compatibility.) Thank you. Update: It will need a gui, and I'd like to be able to do a little bit of customization on it (or use a non-standard, or maybe a non-built-in one) to make it pop a little. Update 2: Truthfully, I really am only concerned with Windows computers. I am considering Java only for its reliability as a platform. A: The largest issue I can think of is the need to install an interpreter. With Java, a lot of people will already have that interpreter installed, although you won't necessarily know which version. It may be wise to include the installer for Java with the program. With Python, you're going to have to install the interpreter on each computer, too. One commenter mentioned .NET. .NET 2.0 has a fairly high likelyhood of being installed than either Java or Python on Windows machines. The catch is that you can't (easily) install it on OSX or Linux. A: My personal choice would be to use Java. You shouldn't run into any problems with different OSs' because of the JVM. However, GUI programmign in Java can be cumbersome but there are plenty of good tutorials on how to create good GUIs' using swing. HERE is a link to a decent tutorial on using an embedded, Apache Derby, database and JDBC with a simple GUI. The tutorial doesn't really explain how to create the GUI as it's more geared towards using JDBC for data access. Hope that helps out some. A: Then use Jython and you get the best of both worlds :-) Plus, you can write performance critical parts in pure Java and integrate it easily (more or less). A: If you're going to install only (or mostly) on Windows, I'd go with .Net. If you have experience with C++, then C# would be natural to you, but if you're comfortable with VBA, you can try VB.NET, but if you prefer Python, then there is IronPython or can give a try to IronRuby, but the best of all is you can mix them all as they apply to different parts of your project. In the database area you'll have excellent integration with SQL Server Express, and in the GUI area, Swing can't beat the ease of use of WinForms nor the sophistication of WPF/Silverlight. As an added bonus, you can have your application automatically updated with ClickOnce. A: You can get a program up and running pretty quickly with Python 2.6, the pyodbc module for SQL integration, PyQT for creating the GUI and py2exe to bundle everything together (inlcuding Python) into a single executable so you don't need to install the interpreter on each computer. That should get you started with a Python app - there is tons of info/answered questions for all of those packages on StackOverflow to help you along the way. Doing some searches, like this, will help you get started too... if you get stuck, you can look here for help.
Help for novice choosing between Java and Python for app with sql db
I'm going to write my first non-Access project, and I need advice on choosing the platform. I will be installing it on multiple friends' and family's computers, so (since I'm sure many, many platforms would suffice just fine for my app), my highest priority has two parts: 1) ease of install for the non-technical user and, 2) minimizing compatibility problems. I want to be able to fix bugs and make changes and roll them out without having to troubleshoot OS and program conflicts on their computers (or at least keeping those things to the absolute minimum-this is why these concerns are my highest priority in choosing a platform.) I have narrowed it down to Python or Java. I like Java's use of the JVM, which seems like would serve to protect against incompatibilities on individual computers nicely. And I've heard a lot of good things about Python, but I don't know how much more prone to incompatibilities it is vs Java. In case it is important, I know the app will definitely use some flavor of a free server-enabled SQL db (server-enabled because I want to be able to run the app from multiple computers), but I don't know which to use yet. I thought I could decide that next. My experience level: I've taken a C++ (console app only) class and done some VBA in Access, but mostly I'm going to have to jump in and learn as I go. So of course I don't know much about all of this. I'm not in the computer field, this is just a hobby. So, which would be better for this app, Java or Python? (In case it comes up, I don't want to make it browser-based at all. I've dealt with individual computers' browser settings breaking programs, and that goes against part 2 of my top priority - maximum compatibility.) Thank you. Update: It will need a gui, and I'd like to be able to do a little bit of customization on it (or use a non-standard, or maybe a non-built-in one) to make it pop a little. Update 2: Truthfully, I really am only concerned with Windows computers. I am considering Java only for its reliability as a platform.
[ "The largest issue I can think of is the need to install an interpreter.\nWith Java, a lot of people will already have that interpreter installed, although you won't necessarily know which version. It may be wise to include the installer for Java with the program.\nWith Python, you're going to have to install the interpreter on each computer, too.\nOne commenter mentioned .NET. .NET 2.0 has a fairly high likelyhood of being installed than either Java or Python on Windows machines. The catch is that you can't (easily) install it on OSX or Linux.\n", "My personal choice would be to use Java. You shouldn't run into any problems with different OSs' because of the JVM. However, GUI programmign in Java can be cumbersome but there are plenty of good tutorials on how to create good GUIs' using swing. \nHERE is a link to a decent tutorial on using an embedded, Apache Derby, database and JDBC with a simple GUI. The tutorial doesn't really explain how to create the GUI as it's more geared towards using JDBC for data access.\nHope that helps out some.\n", "Then use Jython and you get the best of both worlds :-)\nPlus, you can write performance critical parts in pure Java and integrate it easily (more or less).\n", "If you're going to install only (or mostly) on Windows, I'd go with .Net. \nIf you have experience with C++, then C# would be natural to you, but if you're comfortable with VBA, you can try VB.NET, but if you prefer Python, then there is IronPython or can give a try to IronRuby, but the best of all is you can mix them all as they apply to different parts of your project.\nIn the database area you'll have excellent integration with SQL Server Express, and in the GUI area, Swing can't beat the ease of use of WinForms nor the sophistication of WPF/Silverlight.\nAs an added bonus, you can have your application automatically updated with ClickOnce.\n", "You can get a program up and running pretty quickly with Python 2.6, the pyodbc module for SQL integration, PyQT for creating the GUI and py2exe to bundle everything together (inlcuding Python) into a single executable so you don't need to install the interpreter on each computer.\nThat should get you started with a Python app - there is tons of info/answered questions for all of those packages on StackOverflow to help you along the way. Doing some searches, like this, will help you get started too... if you get stuck, you can look here for help.\n" ]
[ 1, 1, 1, 1, 0 ]
[]
[]
[ "java", "python" ]
stackoverflow_0002282360_java_python.txt
Q: Python trouble importing modules I am building a web app with this directory structure: app/ __init__.py config/ __init__.py db_config.py models/ __init__.py model.py datasources/ __init__.py database.py ... ... Every __init__.py file has __all__ = ['', '', ...] in it, listing the .py files that are in the same directory as it. So, app/__init__.py is empty, app/config/__init__.py has __all__ = ['db_config'] , etc. in app/models/datasources/database.py, I cannot seem to import anything from app/config/db_config.py. I have tried import app.config.db_config import config.db_config from app.config.db_config import * but none of them has worked. If anyone has any ideas I'd really appreciate hearing them. Also, I apologize if this is a duplicate question, but I wasn't sure exactly what to search for. A: import app.config.db_config is the best way (avoid non-absolute imports and never ever use import *), and for this to work the app directory should be in sys.path. If it is not, add the directory to you PYTHONPATH or move the project to somewhere this is the case.
Python trouble importing modules
I am building a web app with this directory structure: app/ __init__.py config/ __init__.py db_config.py models/ __init__.py model.py datasources/ __init__.py database.py ... ... Every __init__.py file has __all__ = ['', '', ...] in it, listing the .py files that are in the same directory as it. So, app/__init__.py is empty, app/config/__init__.py has __all__ = ['db_config'] , etc. in app/models/datasources/database.py, I cannot seem to import anything from app/config/db_config.py. I have tried import app.config.db_config import config.db_config from app.config.db_config import * but none of them has worked. If anyone has any ideas I'd really appreciate hearing them. Also, I apologize if this is a duplicate question, but I wasn't sure exactly what to search for.
[ "import app.config.db_config is the best way (avoid non-absolute imports and never ever use import *), and for this to work the app directory should be in sys.path. If it is not, add the directory to you PYTHONPATH or move the project to somewhere this is the case.\n" ]
[ 2 ]
[]
[]
[ "filesystems", "module", "python" ]
stackoverflow_0002283394_filesystems_module_python.txt
Q: simple twisted server (twistd .tap)with a pexpect instance error I have been creating an async server socket that sends and recives xml using twisted. The application works great! but because my main objective was to embed it in an init.d script and make it run in the background i decided to transform it in a "twisted application" in order to run it using twistd # from twisted.internet import reactor from twisted.internet.protocol import ServerFactory from twisted.protocols.basic import LineOnlyReceiver from twisted.application import internet, service from xml.etree import ElementTree as ET from aMuleClass import amulecmd class DialogueProtocol(LineOnlyReceiver): def connectionMade(self): print "Connected: %s" % self.transport.getPeer().host def lineReceived(self, line): parsed= ET.XML(line) if parsed.attrib['type'] == 'request': if parsed.attrib['prompt'] == 'results': self.transport.write(self.factory.mule.results()) elif parsed.attrib['prompt'] == 'downloads': self.transport.write(self.factory.mule.downloads()) else: print "Invalid request: %s\n" % line else: query= parsed.attrib['value'] if parsed.attrib['type'] == 'search': print "must search for %s" % query self.factory.mule.search(query) elif parsed.attrib['type'] == 'cancel': print "must cancel %s" % query self.factory.mule.command("cancel %s" % query) elif parsed.attrib['type'] == 'download': print "must download %s" % query self.factory.mule.command("download %s" % query) class DialogueProtocolFactory(ServerFactory): def __init__(self): self.protocol= DialogueProtocol self.mule= amulecmd() def main(): factory= DialogueProtocolFactory() port = 14000 # daemon= internet.TCPServer(port, factory) application= service.Application("aMuleSocket") # daemon.setServiceParent(application) if __name__ == '__main__': main() Running this with "twistd -noy file" (debug) works PERFECTLY. The problem is when i want to background my script! ("twistd -y file") the socket dosent respond and the log gets filled with errors from pexpect, which is imported in my amulecmd class... pexpect communicates with a terminal-prompt application and returns the answers to the socket.. logfile: 2010/02/17 19:54 +0200 [-] Log opened. 2010/02/17 19:54 +0200 [-] twistd 2.5.0 (/usr/bin/python 2.5.2) starting up 2010/02/17 19:54 +0200 [-] reactor class: <class 'twisted.internet.selectreactor.SelectReactor'> 2010/02/17 19:54 +0200 [-] Loading aMuleSocket.tac... 2010/02/17 19:54 +0200 [-] Starting parent 2010/02/17 19:54 +0200 [-] Loaded. 2010/02/17 19:54 +0200 [-] __builtin__.DialogueProtocolFactory starting on 2000 2010/02/17 19:54 +0200 [-] Starting factory <__builtin__.DialogueProtocolFactory instance at 0x82dbd8c> 2010/02/17 19:54 +0200 [__builtin__.DialogueProtocolFactory] Connected: 192.168.0.2 2010/02/17 19:54 +0200 [DialogueProtocol,0,192.168.0.2] Unhandled Error Traceback (most recent call last): File "/usr/lib/python2.5/site-packages/twisted/python/log.py", line 48, in callWithLogger return callWithContext({"system": lp}, func, *args, **kw) File "/usr/lib/python2.5/site-packages/twisted/python/log.py", line 33, in callWithContext return context.call({ILogContext: newCtx}, func, *args, **kw) File "/usr/lib/python2.5/site-packages/twisted/python/context.py", line 59, in callWithContext return self.currentContext().callWithContext(ctx, func, *args, **kw) File "/usr/lib/python2.5/site-packages/twisted/python/context.py", line 37, in callWithContext return func(*args,**kw) --- <exception caught here> --- File "/usr/lib/python2.5/site-packages/twisted/internet/selectreactor.py", line 139, in _doReadOrWrite why = getattr(selectable, method)() File "/usr/lib/python2.5/site-packages/twisted/internet/tcp.py", line 362, in doRead return self.protocol.dataReceived(data) File "/usr/lib/python2.5/site-packages/twisted/protocols/basic.py", line 149, in dataReceived self.lineReceived(line) File "aMuleSocket.tac", line 19, in lineReceived self.transport.write(self.factory.mule.downloads()) File "/home/hecyra/amule_scripts/amule-remote-read-only/server/aMuleClass.py", line 60, in downloads list= self.command('show DL').splitlines() File "/home/hecyra/amule_scripts/amule-remote-read-only/server/aMuleClass.py", line 42, in command self.prompt() File "/home/hecyra/amule_scripts/amule-remote-read-only/server/aMuleClass.py", line 27, in prompt self.process.expect('aMulecmd') File "/usr/lib/python2.5/site-packages/pexpect.py", line 1064, in expect return self.expect_list(compiled_pattern_list, timeout, searchwindowsize) File "/usr/lib/python2.5/site-packages/pexpect.py", line 1116, in expect_list c = self.read_nonblocking (self.maxread, timeout) File "/usr/lib/python2.5/site-packages/pexpect.py", line 656, in read_nonblocking if not self.isalive(): File "/usr/lib/python2.5/site-packages/pexpect.py", line 914, in isalive raise ExceptionPexpect ('isalive() encountered condition where "terminated" is 0, but there was no child process. Did someone else call waitpid() on our process?') pexpect.ExceptionPexpect: isalive() encountered condition where "terminated" is 0, but there was no child process. Did someone else call waitpid() on our process? What could it be?? all i need is to background this script :( looked easy A: You're spawning a child process before daemonizing. After daemonizing that child is now a child of init, and not a child of your daemon. You need to subclass from twisted.application.service import Service and spawn the child process in startService, which will be called after daemonizing. Á La: Twisted network client with multiprocessing workers? Edit: implementation I can't test this entirely as I don't have your amulecmd, but try something more like this: #!/usr/bin/env python # vim:ai:et:ts=2:sw=2:bg=dark from twisted.internet import protocol from twisted.protocols.basic import LineOnlyReceiver from twisted.application import service from xml.etree import ElementTree as ET from aMuleClass import amulecmd class DialogueProtocol(LineOnlyReceiver): def connectionMade(self): print "Connected: %s" % self.transport.getPeer().host def lineReceived(self, line): parsed= ET.XML(line) if parsed.attrib['type'] == 'request': if parsed.attrib['prompt'] == 'results': self.transport.write(self.factory.mule.results()) elif parsed.attrib['prompt'] == 'downloads': self.transport.write(self.factory.mule.downloads()) else: print "Invalid request: %s\n" % line else: query= parsed.attrib['value'] if parsed.attrib['type'] == 'search': print "must search for %s" % query self.factory.mule.search(query) elif parsed.attrib['type'] == 'cancel': print "must cancel %s" % query self.factory.mule.command("cancel %s" % query) elif parsed.attrib['type'] == 'download': print "must download %s" % query self.factory.mule.command("download %s" % query) class MyService(service.Service): def __init__(self,port=14000): self.port = port def startService(self): self.factory = protocol.Factory() self.factory.protocol = DialogueProtocol from twisted.internet import reactor reactor.callWhenRunning(self.startListening) def startListening(self): self.factory.mule = amulecmd() from twisted.internet import reactor self.listener = reactor.listenTCP(self.port,self.factory) print "Started listening" def stopService(self): self.listener.stopListening() if __name__ == '__main__': pass else: application = service.Application("aMuleSocket") services = service.IServiceCollection(application) MyService().setServiceParent(services)
simple twisted server (twistd .tap)with a pexpect instance error
I have been creating an async server socket that sends and recives xml using twisted. The application works great! but because my main objective was to embed it in an init.d script and make it run in the background i decided to transform it in a "twisted application" in order to run it using twistd # from twisted.internet import reactor from twisted.internet.protocol import ServerFactory from twisted.protocols.basic import LineOnlyReceiver from twisted.application import internet, service from xml.etree import ElementTree as ET from aMuleClass import amulecmd class DialogueProtocol(LineOnlyReceiver): def connectionMade(self): print "Connected: %s" % self.transport.getPeer().host def lineReceived(self, line): parsed= ET.XML(line) if parsed.attrib['type'] == 'request': if parsed.attrib['prompt'] == 'results': self.transport.write(self.factory.mule.results()) elif parsed.attrib['prompt'] == 'downloads': self.transport.write(self.factory.mule.downloads()) else: print "Invalid request: %s\n" % line else: query= parsed.attrib['value'] if parsed.attrib['type'] == 'search': print "must search for %s" % query self.factory.mule.search(query) elif parsed.attrib['type'] == 'cancel': print "must cancel %s" % query self.factory.mule.command("cancel %s" % query) elif parsed.attrib['type'] == 'download': print "must download %s" % query self.factory.mule.command("download %s" % query) class DialogueProtocolFactory(ServerFactory): def __init__(self): self.protocol= DialogueProtocol self.mule= amulecmd() def main(): factory= DialogueProtocolFactory() port = 14000 # daemon= internet.TCPServer(port, factory) application= service.Application("aMuleSocket") # daemon.setServiceParent(application) if __name__ == '__main__': main() Running this with "twistd -noy file" (debug) works PERFECTLY. The problem is when i want to background my script! ("twistd -y file") the socket dosent respond and the log gets filled with errors from pexpect, which is imported in my amulecmd class... pexpect communicates with a terminal-prompt application and returns the answers to the socket.. logfile: 2010/02/17 19:54 +0200 [-] Log opened. 2010/02/17 19:54 +0200 [-] twistd 2.5.0 (/usr/bin/python 2.5.2) starting up 2010/02/17 19:54 +0200 [-] reactor class: <class 'twisted.internet.selectreactor.SelectReactor'> 2010/02/17 19:54 +0200 [-] Loading aMuleSocket.tac... 2010/02/17 19:54 +0200 [-] Starting parent 2010/02/17 19:54 +0200 [-] Loaded. 2010/02/17 19:54 +0200 [-] __builtin__.DialogueProtocolFactory starting on 2000 2010/02/17 19:54 +0200 [-] Starting factory <__builtin__.DialogueProtocolFactory instance at 0x82dbd8c> 2010/02/17 19:54 +0200 [__builtin__.DialogueProtocolFactory] Connected: 192.168.0.2 2010/02/17 19:54 +0200 [DialogueProtocol,0,192.168.0.2] Unhandled Error Traceback (most recent call last): File "/usr/lib/python2.5/site-packages/twisted/python/log.py", line 48, in callWithLogger return callWithContext({"system": lp}, func, *args, **kw) File "/usr/lib/python2.5/site-packages/twisted/python/log.py", line 33, in callWithContext return context.call({ILogContext: newCtx}, func, *args, **kw) File "/usr/lib/python2.5/site-packages/twisted/python/context.py", line 59, in callWithContext return self.currentContext().callWithContext(ctx, func, *args, **kw) File "/usr/lib/python2.5/site-packages/twisted/python/context.py", line 37, in callWithContext return func(*args,**kw) --- <exception caught here> --- File "/usr/lib/python2.5/site-packages/twisted/internet/selectreactor.py", line 139, in _doReadOrWrite why = getattr(selectable, method)() File "/usr/lib/python2.5/site-packages/twisted/internet/tcp.py", line 362, in doRead return self.protocol.dataReceived(data) File "/usr/lib/python2.5/site-packages/twisted/protocols/basic.py", line 149, in dataReceived self.lineReceived(line) File "aMuleSocket.tac", line 19, in lineReceived self.transport.write(self.factory.mule.downloads()) File "/home/hecyra/amule_scripts/amule-remote-read-only/server/aMuleClass.py", line 60, in downloads list= self.command('show DL').splitlines() File "/home/hecyra/amule_scripts/amule-remote-read-only/server/aMuleClass.py", line 42, in command self.prompt() File "/home/hecyra/amule_scripts/amule-remote-read-only/server/aMuleClass.py", line 27, in prompt self.process.expect('aMulecmd') File "/usr/lib/python2.5/site-packages/pexpect.py", line 1064, in expect return self.expect_list(compiled_pattern_list, timeout, searchwindowsize) File "/usr/lib/python2.5/site-packages/pexpect.py", line 1116, in expect_list c = self.read_nonblocking (self.maxread, timeout) File "/usr/lib/python2.5/site-packages/pexpect.py", line 656, in read_nonblocking if not self.isalive(): File "/usr/lib/python2.5/site-packages/pexpect.py", line 914, in isalive raise ExceptionPexpect ('isalive() encountered condition where "terminated" is 0, but there was no child process. Did someone else call waitpid() on our process?') pexpect.ExceptionPexpect: isalive() encountered condition where "terminated" is 0, but there was no child process. Did someone else call waitpid() on our process? What could it be?? all i need is to background this script :( looked easy
[ "You're spawning a child process before daemonizing. After daemonizing that child is now a child of init, and not a child of your daemon.\nYou need to subclass from twisted.application.service import Service and spawn the child process in startService, which will be called after daemonizing.\nÁ La: Twisted network client with multiprocessing workers?\nEdit: implementation\nI can't test this entirely as I don't have your amulecmd, but try something more like this:\n#!/usr/bin/env python\n# vim:ai:et:ts=2:sw=2:bg=dark\nfrom twisted.internet import protocol\nfrom twisted.protocols.basic import LineOnlyReceiver\nfrom twisted.application import service\n\n\nfrom xml.etree import ElementTree as ET\n\nfrom aMuleClass import amulecmd\n\nclass DialogueProtocol(LineOnlyReceiver):\n def connectionMade(self):\n print \"Connected: %s\" % self.transport.getPeer().host\n def lineReceived(self, line):\n parsed= ET.XML(line)\n if parsed.attrib['type'] == 'request':\n if parsed.attrib['prompt'] == 'results':\n self.transport.write(self.factory.mule.results())\n elif parsed.attrib['prompt'] == 'downloads':\n self.transport.write(self.factory.mule.downloads())\n else:\n print \"Invalid request: %s\\n\" % line\n else:\n query= parsed.attrib['value']\n if parsed.attrib['type'] == 'search':\n print \"must search for %s\" % query\n self.factory.mule.search(query)\n elif parsed.attrib['type'] == 'cancel':\n print \"must cancel %s\" % query\n self.factory.mule.command(\"cancel %s\" % query)\n elif parsed.attrib['type'] == 'download':\n print \"must download %s\" % query\n self.factory.mule.command(\"download %s\" % query)\n\nclass MyService(service.Service):\n def __init__(self,port=14000):\n self.port = port\n def startService(self):\n self.factory = protocol.Factory()\n self.factory.protocol = DialogueProtocol\n from twisted.internet import reactor\n reactor.callWhenRunning(self.startListening)\n def startListening(self):\n self.factory.mule = amulecmd()\n from twisted.internet import reactor\n self.listener = reactor.listenTCP(self.port,self.factory)\n print \"Started listening\"\n def stopService(self):\n self.listener.stopListening()\n\nif __name__ == '__main__':\n pass\nelse:\n application = service.Application(\"aMuleSocket\")\n services = service.IServiceCollection(application)\n MyService().setServiceParent(services)\n\n" ]
[ 3 ]
[]
[]
[ "daemon", "pexpect", "python", "twisted" ]
stackoverflow_0002283408_daemon_pexpect_python_twisted.txt
Q: Setting the cursor position in PyGTK (for a Gedit plugin) I'm developing a Gedit plugin which is built on PyGTK. I'm trying to figure out how to programatically tell the cursor where to go. For example, I'd like to have the cursor automatically go to right before the first "|" (pipe) in the current line. Any ideas or starting points? I've been using the Gedit API up until now (right here) which is helpful for the most part but doesn't mention anything about manipulating the cursor position. A: Looking at the gedit plugin API, it looks like gedit.Document is a subclass of GtkSourceBuffer which itself subclasses GtkTextBuffer, the last of which has the cursor manipulation API you want. In particular, get_insert() and place_cursor(where) give the basics of moving the cursor around. For other operations (e.g., getting the current line) you'll need to convert to a GtkTextIter using get_iter_at_mark(mark); the cursor is essentially just a special GtkTextMark.
Setting the cursor position in PyGTK (for a Gedit plugin)
I'm developing a Gedit plugin which is built on PyGTK. I'm trying to figure out how to programatically tell the cursor where to go. For example, I'd like to have the cursor automatically go to right before the first "|" (pipe) in the current line. Any ideas or starting points? I've been using the Gedit API up until now (right here) which is helpful for the most part but doesn't mention anything about manipulating the cursor position.
[ "Looking at the gedit plugin API, it looks like gedit.Document is a subclass of GtkSourceBuffer which itself subclasses GtkTextBuffer, the last of which has the cursor manipulation API you want. In particular, get_insert() and place_cursor(where) give the basics of moving the cursor around. For other operations (e.g., getting the current line) you'll need to convert to a GtkTextIter using get_iter_at_mark(mark); the cursor is essentially just a special GtkTextMark.\n" ]
[ 2 ]
[]
[]
[ "gedit", "plugins", "pygtk", "python" ]
stackoverflow_0002283933_gedit_plugins_pygtk_python.txt
Q: OpenGl with Python I am currently in a course that is using OpenGL and I have been using C for all the programs so far. I have Python installed on Fedora as well as OpenGL, however the minute I call an OpenGL command in my Python code, I get a segmentation fault. I have no idea why this is. Just to avoid the "just use C" comments, here is why I want to use Python: There are a couple reasons I am wanting to switch from C to Python, but the main one is because we are about to start writing a raytracer and I would like to use classes to make it easier on me. Since I hate classes in C++ and structs in C seems a little crazy, I thought I would give Python a try at it. I have also been looking for a reason to use Python again as it has been a while. Thanks for any help. A: You may also want to consider using Pyglet instead of PyOpenGL. It's a ctypes-wrapper around the native OpenGL libs on the local platform, along with windowing support (should handle most of the stuff you want to use GLUT for.) The pyglet-users list is pretty active and very helpful. A: Well, I don't know if these are the libs the original poster are using but I saw identical issues in a pet project I'm working on (Graphics Engine using C++ and Python) using PyOpenGL. PyOpenGL didn't correctly pick up the rendering context if it was created after the python script had been loaded (I was loading the script first, then calling Python methods in it from my C++ code). The problem doesn't appear if you initialize the display and create the OpenGL rendering context before loading the Python script. A: What OpenGL library are you using? What windowing library? What version of Python? Most likely cause I can think of is that your windowing library (SDL or whatever you're using) isn't initializing OpenGL before you start calling into it. A: We have neither ideas about random segmentation faults. There is not enough information. What python libraries are you using for opengl? How do you use them? Can you show us your code? It's probably something trivial but my god -skill ends up to telling me just and only that. Raytracer in python? I'd prefer just doing that in C with those structs. But then, I'm assuming you aren't going to do a realtime raytracer so that may be ok. A: Perhaps you are calling an OpenGL function that requires an active OpenGL context, without having one? That shouldn't necessarily crash, but I guess it might. How to set up such a context depends on the platform, and it's been a while since I used GL from Python (and when I did, I also used GTK+ which complicates matters). A: Scripts never cause segmentation faults. But first see if your kernel and kmod video driver working property ... Extension modules can cause "segmentation fault".
OpenGl with Python
I am currently in a course that is using OpenGL and I have been using C for all the programs so far. I have Python installed on Fedora as well as OpenGL, however the minute I call an OpenGL command in my Python code, I get a segmentation fault. I have no idea why this is. Just to avoid the "just use C" comments, here is why I want to use Python: There are a couple reasons I am wanting to switch from C to Python, but the main one is because we are about to start writing a raytracer and I would like to use classes to make it easier on me. Since I hate classes in C++ and structs in C seems a little crazy, I thought I would give Python a try at it. I have also been looking for a reason to use Python again as it has been a while. Thanks for any help.
[ "You may also want to consider using Pyglet instead of PyOpenGL. It's a ctypes-wrapper around the native OpenGL libs on the local platform, along with windowing support (should handle most of the stuff you want to use GLUT for.) The pyglet-users list is pretty active and very helpful.\n", "Well, I don't know if these are the libs the original poster are using but I saw identical issues in a pet project I'm working on (Graphics Engine using C++ and Python) using PyOpenGL.\nPyOpenGL didn't correctly pick up the rendering context if it was created after the python script had been loaded (I was loading the script first, then calling Python methods in it from my C++ code).\nThe problem doesn't appear if you initialize the display and create the OpenGL rendering context before loading the Python script.\n", "What OpenGL library are you using? What windowing library? What version of Python?\nMost likely cause I can think of is that your windowing library (SDL or whatever you're using) isn't initializing OpenGL before you start calling into it.\n", "We have neither ideas about random segmentation faults. There is not enough information. What python libraries are you using for opengl? How do you use them? Can you show us your code? It's probably something trivial but my god -skill ends up to telling me just and only that.\nRaytracer in python? I'd prefer just doing that in C with those structs. But then, I'm assuming you aren't going to do a realtime raytracer so that may be ok.\n", "Perhaps you are calling an OpenGL function that requires an active OpenGL context, without having one? That shouldn't necessarily crash, but I guess it might. How to set up such a context depends on the platform, and it's been a while since I used GL from Python (and when I did, I also used GTK+ which complicates matters).\n", "Scripts never cause segmentation faults. \nBut first see if your kernel and kmod video driver working property ...\nExtension modules can cause \"segmentation fault\".\n" ]
[ 16, 2, 1, 0, 0, 0 ]
[]
[]
[ "fedora", "opengl", "python" ]
stackoverflow_0000242059_fedora_opengl_python.txt
Q: Django extends/include - bug? I'm trying to use both extends and include tags in one template, just like: {% extends "layout.html" %} {% block content %} <div id="content"> <nav class="mainMenu"> {% include "list.html" %} </nav> </div> {% endblock %} Unfortunately what is displayed is only list.html without contents from layout.html and file that is including the list.html. Why is that? A: You are most probably only rendering list.html in your view, check for that.
Django extends/include - bug?
I'm trying to use both extends and include tags in one template, just like: {% extends "layout.html" %} {% block content %} <div id="content"> <nav class="mainMenu"> {% include "list.html" %} </nav> </div> {% endblock %} Unfortunately what is displayed is only list.html without contents from layout.html and file that is including the list.html. Why is that?
[ "You are most probably only rendering list.html in your view, check for that.\n" ]
[ 2 ]
[]
[]
[ "django", "python", "templates" ]
stackoverflow_0002284495_django_python_templates.txt
Q: How can I add consistent whitespace to existing HTML using Python? I just started working on a website that is full of pages with all their HTML on a single line, which is a real pain to read and work with. I'm looking for a tool (preferably a Python library) that will take HTML input and return the same HTML unchanged, except for adding linebreaks and appropriate indentation. (All tags, markup, and content should be untouched.) The library doesn't have to handle malformed HTML; I'm passing the HTML through html5lib first, so it will be getting well-formed HTML. However, as mentioned above, I would rather it didn't change any of the actual markup itself; I trust html5lib and would rather let it handle the correctness aspect. First, does anyone know if this is possible with just html5lib? (Unfortunately, their documentation seems a bit sparse.) If not, what tool would you suggest? I've seen some people recommend HTML Tidy, but I'm not sure if it can be configured to only change whitespace. (Would it do anything except insert whitespace if it were passed well-formed HTML to start with?) A: Algorithm Parse html into some representation Serialize the representation back to html Example html5lib parser with BeautifulSoup tree builder #!/usr/bin/env python from html5lib import HTMLParser, treebuilders parser = HTMLParser(tree=treebuilders.getTreeBuilder("beautifulsoup")) c = """<HTML><HEAD><TITLE>Title</TITLE></HEAD><BODY>...... </BODY></HTML>""" soup = parser.parse(c) print soup.prettify() Output: <html> <head> <title> Title </title> </head> <body> ...... </body> </html> A: I chose J.F. Sebastian's answer because I think it's the simplest and thus the best, but I'm adding another solution for anyone who doesn't want to install Beautiful Soup. (Also, the Beautiful Soup tree builder is going to be deprecated in html5lib 1.0.) This solution was thanks to Amarghosh's tip; I just fleshed it out a bit. Looking at html5lib, I realized that it will output a minidom object natively, which means I can use his suggestion of toprettyxml(). Here's what I came up with: from html5lib import HTMLParser, treebuilders from cStringIO import StringIO def tidy_html(text): """Returns a well-formatted version of input HTML.""" p = HTMLParser(tree=treebuilders.getTreeBuilder("dom")) dom_tree = p.parseFragment(text) # using cStringIO for fast string concatenation pretty_HTML = StringIO() node = dom_tree.firstChild while node: node_contents = node.toprettyxml(indent=' ') pretty_HTML.write(node_contents) node = node.nextSibling output = pretty_HTML.getvalue() pretty_HTML.close() return output And an example: >>> text = """<b><i>bold, italic</b></i><div>a div</div>""" >>> tidy_html(text) <b> <i> bold, italic </i> </b> <div> a div </div> Why am I iterating over the children of the tree, rather than just calling toprettyxml() on dom_tree directly? Some of the HTML I'm dealing with is actually HTML fragments, so it's missing the <head> and <body> tags. To handle this I used the parseFragment() method, which means I get a DocumentFragment in return (rather than a Document). Unfortunately, it doesn't have a writexml() method (which toprettyxml() calls), so I iterate over the child nodes, which do have the method. A: If the html is indeed well formed xml, you can use DOM parser. from xml.dom.minidom import parse, parseString #if you have html string in a variable html = parseString(theHtmlString) #or parse the html file html = parse(htmlFileName) print html.toprettyxml() The toprettyxml() method lets to specify the indent, new-line character and the encoding of the output. You might want to check out the writexml() method also.
How can I add consistent whitespace to existing HTML using Python?
I just started working on a website that is full of pages with all their HTML on a single line, which is a real pain to read and work with. I'm looking for a tool (preferably a Python library) that will take HTML input and return the same HTML unchanged, except for adding linebreaks and appropriate indentation. (All tags, markup, and content should be untouched.) The library doesn't have to handle malformed HTML; I'm passing the HTML through html5lib first, so it will be getting well-formed HTML. However, as mentioned above, I would rather it didn't change any of the actual markup itself; I trust html5lib and would rather let it handle the correctness aspect. First, does anyone know if this is possible with just html5lib? (Unfortunately, their documentation seems a bit sparse.) If not, what tool would you suggest? I've seen some people recommend HTML Tidy, but I'm not sure if it can be configured to only change whitespace. (Would it do anything except insert whitespace if it were passed well-formed HTML to start with?)
[ "Algorithm\n\nParse html into some representation\nSerialize the representation back to html\n\nExample html5lib parser with BeautifulSoup tree builder\n#!/usr/bin/env python\nfrom html5lib import HTMLParser, treebuilders\n\nparser = HTMLParser(tree=treebuilders.getTreeBuilder(\"beautifulsoup\"))\n\nc = \"\"\"<HTML><HEAD><TITLE>Title</TITLE></HEAD><BODY>...... </BODY></HTML>\"\"\"\n\nsoup = parser.parse(c)\nprint soup.prettify()\n\nOutput:\n<html>\n <head>\n <title>\n Title\n </title>\n </head>\n <body>\n ......\n </body>\n</html>\n\n", "I chose J.F. Sebastian's answer because I think it's the simplest and thus the best, but I'm adding another solution for anyone who doesn't want to install Beautiful Soup. (Also, the Beautiful Soup tree builder is going to be deprecated in html5lib 1.0.) This solution was thanks to Amarghosh's tip; I just fleshed it out a bit. Looking at html5lib, I realized that it will output a minidom object natively, which means I can use his suggestion of toprettyxml(). Here's what I came up with:\nfrom html5lib import HTMLParser, treebuilders\nfrom cStringIO import StringIO\n\ndef tidy_html(text):\n \"\"\"Returns a well-formatted version of input HTML.\"\"\"\n\n p = HTMLParser(tree=treebuilders.getTreeBuilder(\"dom\"))\n dom_tree = p.parseFragment(text)\n\n # using cStringIO for fast string concatenation\n pretty_HTML = StringIO()\n\n node = dom_tree.firstChild\n while node:\n node_contents = node.toprettyxml(indent=' ')\n pretty_HTML.write(node_contents)\n node = node.nextSibling\n\n output = pretty_HTML.getvalue()\n pretty_HTML.close()\n return output\n\nAnd an example:\n>>> text = \"\"\"<b><i>bold, italic</b></i><div>a div</div>\"\"\"\n>>> tidy_html(text)\n<b>\n <i>\n bold, italic\n </i>\n</b>\n<div>\n a div\n</div>\n\nWhy am I iterating over the children of the tree, rather than just calling toprettyxml() on dom_tree directly? Some of the HTML I'm dealing with is actually HTML fragments, so it's missing the <head> and <body> tags. To handle this I used the parseFragment() method, which means I get a DocumentFragment in return (rather than a Document). Unfortunately, it doesn't have a writexml() method (which toprettyxml() calls), so I iterate over the child nodes, which do have the method.\n", "If the html is indeed well formed xml, you can use DOM parser.\nfrom xml.dom.minidom import parse, parseString\n\n#if you have html string in a variable\nhtml = parseString(theHtmlString)\n\n#or parse the html file\nhtml = parse(htmlFileName)\n\nprint html.toprettyxml()\n\nThe toprettyxml() method lets to specify the indent, new-line character and the encoding of the output. You might want to check out the writexml() method also.\n" ]
[ 2, 2, 1 ]
[]
[]
[ "html", "html5lib", "python", "whitespace" ]
stackoverflow_0002279404_html_html5lib_python_whitespace.txt
Q: How to install html5lib-0.90 library for Python on Windows? I'm using Windows, and trying to install html5lib-0.90 library on python C:\>python C:\Users\Junior\Downloads\Python\html5lib-0.90\setup.py install Traceback (most recent call last): File "C:\Users\Junior\Downloads\Python\html5lib-0.90\setup.py", line 36, in <module> for name in os.listdir(os.path.join('src','html5lib')) WindowsError: [Error 3] The system cannot find the path specified: 'src\\html5lib/*.*' Is it possible to install this library on windows? Is there a tutorial or installation manual? A: Try: C:\>cd \Users\Junior\Downloads\Python\html5lib-0.90\ C:\Users\Junior\Downloads\Python\html5lib-0.90>python setup.py install
How to install html5lib-0.90 library for Python on Windows?
I'm using Windows, and trying to install html5lib-0.90 library on python C:\>python C:\Users\Junior\Downloads\Python\html5lib-0.90\setup.py install Traceback (most recent call last): File "C:\Users\Junior\Downloads\Python\html5lib-0.90\setup.py", line 36, in <module> for name in os.listdir(os.path.join('src','html5lib')) WindowsError: [Error 3] The system cannot find the path specified: 'src\\html5lib/*.*' Is it possible to install this library on windows? Is there a tutorial or installation manual?
[ "Try:\nC:\\>cd \\Users\\Junior\\Downloads\\Python\\html5lib-0.90\\\nC:\\Users\\Junior\\Downloads\\Python\\html5lib-0.90>python setup.py install\n\n" ]
[ 6 ]
[]
[]
[ "html5lib", "python" ]
stackoverflow_0002285086_html5lib_python.txt
Q: Room for improvement on my Python code? I'm working on a Gedit plugin using Python (and PyGTK) and I really havent' worked with Python much so I have no idea if I'm writing Pythonic code. All of my own code is contained in __init__.py. There are a few other files, but they're from an outside library that I'm hooking into. My __init__.py is as follows: # # @file __init__.py # Does the heavy lifting behind connecting Zen Coding to Gedit. # import gedit, gobject, string, gtk, re, zen_core class ZenCodingPlugin(gedit.Plugin): """ A Gedit plugin to implement Zen Coding's HTML and CSS shorthand expander. This file adds the menu items and keyboard shortcuts to the UI and connects those items with the good stuff (i.e., the code expansion). """ def __init__(self): gedit.Plugin.__init__(self) def activate(self, window): "Gedit callback: install the expansion feature into the UI" ui_manager = window.get_ui_manager() action_group = gtk.ActionGroup("GeditZenCodingPluginActions") # Create the GTK action to be used to connect the key combo # to the Zen Coding expansion (i.e., the good stuff). complete_action = gtk.Action(name="ZenCodingAction", label="Expand Zen code...", tooltip="Expand Zen Code in document to raw HTML", stock_id=gtk.STOCK_GO_FORWARD) # Connect the newly created action with key combo complete_action.connect("activate", lambda a: self.expand_zencode(window)) action_group.add_action_with_accel(complete_action, "<Ctrl><Shift>E") ui_manager.insert_action_group(action_group, 0) # @TODO: Figure out what these lines do ui_merge_id = ui_manager.new_merge_id() ui_manager.add_ui(ui_merge_id, "/MenuBar/EditMenu/EditOps_5", "ZenCoding", "ZenCodingAction", gtk.UI_MANAGER_MENUITEM, False) ui_manager.__ui_data__ = (action_group, ui_merge_id) def deactivate(self, window): "Gedit callback: get rid of the expansion feature" ui_manager = window.get_ui_manager() (action_group, ui_merge_id) = ui_manager.__ui_data__ # Remove the UI data, action group, and UI itself from Gedit del ui_manager.__ui_data__ ui_manager.remove_action_group(action_group) ui_manager.remove_ui(ui_merge_id) def expand_zencode(self, window): "The action which handles the code expansion itself." view = window.get_active_view() buffer = view.get_buffer() # Grab the current cursor position. cursor_iter = buffer.get_iter_at_mark(buffer.get_insert()) # Grab the first character in the line. line_iter = cursor_iter.copy() line_iter.set_line_offset(0) # Grab the text from the start of the line to the cursor. line = buffer.get_text(line_iter, cursor_iter) # Find the last space in the line and remove it, setting a variable # 'before' to the current line. words = line.split(" ") before = words[-1].lstrip() if not before: return # Get the language of the current document. Second line prevents an error # if first line returns None. lang = window.get_active_document().get_language() lang = lang and lang.get_name() # Using the 'before' variable, convert it from Zen Code # to expanded code. If there isn't anything, just return. if lang == 'CSS': after = zen_core.expand_abbreviation(before,'css','xhtml') else: after = zen_core.expand_abbreviation(before,'html','xhtml') if not after: return # Grab the line's indentation and store it. indent = re.match(r"\s*", line).group() # Automatically indent the string and replace \t (tab) with the # correct number of spaces. after = zen_core.pad_string(after,indent) if view.get_insert_spaces_instead_of_tabs(): tabsize = view.get_tab_width() spaces = " " * tabsize after = after.replace("\t",spaces) # We are currently lame and do not know how to do placeholders. # So remove all | characters from after. after = after.replace("|", "") # Delete the last word in the line (i.e., the 'before' text, aka the # Zen un-expanded code), so that we can replace it. word_iter = cursor_iter.copy() position_in_line = cursor_iter.get_line_index() - len(before) word_iter.set_line_index(position_in_line) buffer.delete(word_iter, cursor_iter) # Insert the new expanded text. buffer.insert_at_cursor(after) I'm just asking because the above doesn't seem very object oriented and it kind of strikes me as a bad idea to put this much logic in __init__.py, but being new at this, I'm not sure. Is there room for improvement? If so, how? (I'm trying to shy away from what the plugin actually does because I'm looking more for a coding style review than a logarithm review, but if you need to see the code from the outside library, the whole plugin is at here) A: I've never done a GEdit plugin, so i can't comment on the __init__.py issue, but general notes: Isn't calling parent's __init__ with no new args redundant -- can't you just take out those 2 lines? You create more local variables than I would have. I had to keep looking around to see where a value came from, or if it's used again. For example: tabsize = view.get_tab_width() spaces = " " * tabsize after = after.replace("\t",spaces) could be: after = after.replace("\t", " " * view.get_tab_width()) A little redundancy here: if lang == 'CSS': after = zen_core.expand_abbreviation(before,'css','xhtml') else: after = zen_core.expand_abbreviation(before,'html','xhtml') compare: after = zen_core.expand_abbreviation(before, 'css' if lang == 'CSS' else 'html', 'xhtml') Other than that, it looks like pretty decent Python code to my eye. A: Perhaps you want to move it into a file called zen_plugin.py Then make your __init__.py from zen_plugin import ZenCodingPlugin A: I would try to extract some functions from the long expand_zencode(). Like an expand_tabs(), for example. That's a matter of taste to some extent, but whenever I see a 'travelogue' with comments pointing out 'sights' along the way, it's a strong hint to refactor into functions each with a doc comment instead. (Not necessarily one-to-one; I don't have the energy/knowledge for detailed advice on this function.) This change automatically addresses Ken's complaint about keeping track of the local variables. BTW, you have an odd definition of tab-expansion: changing each tab character to tabsize spaces. I suppose there's a reason. This is unneeded: def __init__(self): gedit.Plugin.__init__(self) The code for the before variable doesn't seem to match its comment. (And the .lstrip() is redundant, isn't it?) You sometimes have spaces between arguments and sometimes not; IIRC the Python style guide wants you to consistently use spaces. (foo(x, y) and not foo(x,y).) Your class's comment says: "This file adds...". Shouldn't that be "This plugin adds..."? Consider asking this sort of thing on http://refactormycode.com/ instead. A: If you only have the one file then your directory structure probably looks like pluginname `- __init__.py In this case you can just flatten your project to pluginname.py If you later need other modules in your package you could go to pluginname +- __init__.py `- plugin.py where plugin.py has this class in it and in __init__.py put from pluginname.plugin import ZenCodingPlugin This way anything that was previously using from pluginname import ZenCodingPlugin or import pluginname; pluginname.ZenCodingPlugin would still work.
Room for improvement on my Python code?
I'm working on a Gedit plugin using Python (and PyGTK) and I really havent' worked with Python much so I have no idea if I'm writing Pythonic code. All of my own code is contained in __init__.py. There are a few other files, but they're from an outside library that I'm hooking into. My __init__.py is as follows: # # @file __init__.py # Does the heavy lifting behind connecting Zen Coding to Gedit. # import gedit, gobject, string, gtk, re, zen_core class ZenCodingPlugin(gedit.Plugin): """ A Gedit plugin to implement Zen Coding's HTML and CSS shorthand expander. This file adds the menu items and keyboard shortcuts to the UI and connects those items with the good stuff (i.e., the code expansion). """ def __init__(self): gedit.Plugin.__init__(self) def activate(self, window): "Gedit callback: install the expansion feature into the UI" ui_manager = window.get_ui_manager() action_group = gtk.ActionGroup("GeditZenCodingPluginActions") # Create the GTK action to be used to connect the key combo # to the Zen Coding expansion (i.e., the good stuff). complete_action = gtk.Action(name="ZenCodingAction", label="Expand Zen code...", tooltip="Expand Zen Code in document to raw HTML", stock_id=gtk.STOCK_GO_FORWARD) # Connect the newly created action with key combo complete_action.connect("activate", lambda a: self.expand_zencode(window)) action_group.add_action_with_accel(complete_action, "<Ctrl><Shift>E") ui_manager.insert_action_group(action_group, 0) # @TODO: Figure out what these lines do ui_merge_id = ui_manager.new_merge_id() ui_manager.add_ui(ui_merge_id, "/MenuBar/EditMenu/EditOps_5", "ZenCoding", "ZenCodingAction", gtk.UI_MANAGER_MENUITEM, False) ui_manager.__ui_data__ = (action_group, ui_merge_id) def deactivate(self, window): "Gedit callback: get rid of the expansion feature" ui_manager = window.get_ui_manager() (action_group, ui_merge_id) = ui_manager.__ui_data__ # Remove the UI data, action group, and UI itself from Gedit del ui_manager.__ui_data__ ui_manager.remove_action_group(action_group) ui_manager.remove_ui(ui_merge_id) def expand_zencode(self, window): "The action which handles the code expansion itself." view = window.get_active_view() buffer = view.get_buffer() # Grab the current cursor position. cursor_iter = buffer.get_iter_at_mark(buffer.get_insert()) # Grab the first character in the line. line_iter = cursor_iter.copy() line_iter.set_line_offset(0) # Grab the text from the start of the line to the cursor. line = buffer.get_text(line_iter, cursor_iter) # Find the last space in the line and remove it, setting a variable # 'before' to the current line. words = line.split(" ") before = words[-1].lstrip() if not before: return # Get the language of the current document. Second line prevents an error # if first line returns None. lang = window.get_active_document().get_language() lang = lang and lang.get_name() # Using the 'before' variable, convert it from Zen Code # to expanded code. If there isn't anything, just return. if lang == 'CSS': after = zen_core.expand_abbreviation(before,'css','xhtml') else: after = zen_core.expand_abbreviation(before,'html','xhtml') if not after: return # Grab the line's indentation and store it. indent = re.match(r"\s*", line).group() # Automatically indent the string and replace \t (tab) with the # correct number of spaces. after = zen_core.pad_string(after,indent) if view.get_insert_spaces_instead_of_tabs(): tabsize = view.get_tab_width() spaces = " " * tabsize after = after.replace("\t",spaces) # We are currently lame and do not know how to do placeholders. # So remove all | characters from after. after = after.replace("|", "") # Delete the last word in the line (i.e., the 'before' text, aka the # Zen un-expanded code), so that we can replace it. word_iter = cursor_iter.copy() position_in_line = cursor_iter.get_line_index() - len(before) word_iter.set_line_index(position_in_line) buffer.delete(word_iter, cursor_iter) # Insert the new expanded text. buffer.insert_at_cursor(after) I'm just asking because the above doesn't seem very object oriented and it kind of strikes me as a bad idea to put this much logic in __init__.py, but being new at this, I'm not sure. Is there room for improvement? If so, how? (I'm trying to shy away from what the plugin actually does because I'm looking more for a coding style review than a logarithm review, but if you need to see the code from the outside library, the whole plugin is at here)
[ "I've never done a GEdit plugin, so i can't comment on the __init__.py issue, but general notes:\n\nIsn't calling parent's __init__ with no new args redundant -- can't you just take out those 2 lines?\nYou create more local variables than I would have. I had to keep looking around to see where a value came from, or if it's used again. For example:\ntabsize = view.get_tab_width()\nspaces = \" \" * tabsize\nafter = after.replace(\"\\t\",spaces)\n\ncould be:\nafter = after.replace(\"\\t\", \" \" * view.get_tab_width())\n\nA little redundancy here:\nif lang == 'CSS':\n after = zen_core.expand_abbreviation(before,'css','xhtml')\nelse:\n after = zen_core.expand_abbreviation(before,'html','xhtml')\n\ncompare:\nafter = zen_core.expand_abbreviation(before, 'css' if lang == 'CSS' else 'html', 'xhtml')\n\n\nOther than that, it looks like pretty decent Python code to my eye.\n", "Perhaps you want to move it into a file called zen_plugin.py\nThen make your __init__.py\nfrom zen_plugin import ZenCodingPlugin\n\n", "I would try to extract some functions from the long expand_zencode(). Like an expand_tabs(), for example. That's a matter of taste to some extent, but whenever I see a 'travelogue' with comments pointing out 'sights' along the way, it's a strong hint to refactor into functions each with a doc comment instead. (Not necessarily one-to-one; I don't have the energy/knowledge for detailed advice on this function.) This change automatically addresses Ken's complaint about keeping track of the local variables.\nBTW, you have an odd definition of tab-expansion: changing each tab character to tabsize spaces. I suppose there's a reason.\nThis is unneeded:\ndef __init__(self):\n gedit.Plugin.__init__(self)\n\nThe code for the before variable doesn't seem to match its comment. (And the .lstrip() is redundant, isn't it?)\nYou sometimes have spaces between arguments and sometimes not; IIRC the Python style guide wants you to consistently use spaces. (foo(x, y) and not foo(x,y).)\nYour class's comment says: \"This file adds...\". Shouldn't that be \"This plugin adds...\"?\nConsider asking this sort of thing on http://refactormycode.com/ instead.\n", "If you only have the one file then your directory structure probably looks like\npluginname\n`- __init__.py\n\nIn this case you can just flatten your project to\npluginname.py\n\nIf you later need other modules in your package you could go to\npluginname\n+- __init__.py\n`- plugin.py\n\nwhere plugin.py has this class in it and in __init__.py put\nfrom pluginname.plugin import ZenCodingPlugin\n\nThis way anything that was previously using from pluginname import ZenCodingPlugin or import pluginname; pluginname.ZenCodingPlugin would still work.\n" ]
[ 3, 2, 1, 1 ]
[ "It's gui code and is always verbose, my best advice is: does it work? good. Next Task !\n" ]
[ -3 ]
[ "gedit", "pygtk", "python" ]
stackoverflow_0002284809_gedit_pygtk_python.txt
Q: Python basics: How to read N ints until '\n' is found in stdin How can I read N ints from the input, and stop reading when I find \n? Also, how can I add them to an array that I can work with? I'm looking for something like this from C but in python while(scanf("%d%c",&somearray[i],&c)!=EOF){ i++; if (c == '\n'){ break; } } A: In Python 2: lst = map(int, raw_input().split()) raw_input() reads a whole line from the input (stopping at the \n) as a string. .split() creates a list of strings by splitting the input into words. map(int, ...) creates integers from those words. In Python 3 raw_input has been renamed to input and map returns an iterator rather than a list, so a couple of changes need to be made: lst = list(map(int, input().split())) A: There is no direct equivalent of scanf in Python, but this should work somearray = map(int, raw_input().split()) In Python3 raw_input has been renamed to input somearray = map(int, input().split()) Here is a breakdown/explanation >>> raw=raw_input() # raw_input waits for some input 1 2 3 4 5 # I entered this >>> print raw 1 2 3 4 5 >>> print raw.split() # Make a list by splitting raw at whitespace ['1', '2', '3', '4', '5'] >>> print map(int, raw.split()) # map calls each int() for each item in the list [1, 2, 3, 4, 5]
Python basics: How to read N ints until '\n' is found in stdin
How can I read N ints from the input, and stop reading when I find \n? Also, how can I add them to an array that I can work with? I'm looking for something like this from C but in python while(scanf("%d%c",&somearray[i],&c)!=EOF){ i++; if (c == '\n'){ break; } }
[ "In Python 2:\nlst = map(int, raw_input().split())\n\nraw_input() reads a whole line from the input (stopping at the \\n) as a string.\n.split() creates a list of strings by splitting the input into words.\nmap(int, ...) creates integers from those words.\nIn Python 3 raw_input has been renamed to input and map returns an iterator rather than a list, so a couple of changes need to be made:\nlst = list(map(int, input().split()))\n\n", "There is no direct equivalent of scanf in Python, but this should work\nsomearray = map(int, raw_input().split())\n\nIn Python3 raw_input has been renamed to input\nsomearray = map(int, input().split())\n\nHere is a breakdown/explanation\n>>> raw=raw_input() # raw_input waits for some input\n1 2 3 4 5 # I entered this\n>>> print raw\n1 2 3 4 5 \n>>> print raw.split() # Make a list by splitting raw at whitespace\n['1', '2', '3', '4', '5'] \n>>> print map(int, raw.split()) # map calls each int() for each item in the list\n[1, 2, 3, 4, 5]\n\n" ]
[ 19, 13 ]
[]
[]
[ "python", "stdin" ]
stackoverflow_0002285284_python_stdin.txt
Q: Pylons: response renaming? Is there a better way? I've got a Pylons controller with an action called serialize returning content_type=text/csv. I'd like the response of the action to be named based on the input patameter, i.e. for the following route, produced csv file should be named {id}.csv : /app/PROD/serialize => PROD.csv (so a user can open the file in Excel with a proper name directly via a webbrowser) map.connect('/app/{id}/serialize',controller = 'csvproducer',action='serialize') I've tried to set different HTTP headers and properties of the webob's response object with no luck. However, I figured out a workaround by simply adding a new action to the controller and dynamically redirecting the original action to that new action, i.e.: map.connect('/app/{id}/serialize',controller = 'csvproducer',action='serialize') map.connect('/app/csv/{foo}',controller = 'csvproducer', action='tocsv') The controller's snippet: def serialize(self,id): try: session['key'] = self.service.serialize(id) #produces csv content session.save() redirect_to(str("/app/csv/%s.csv" % id)) except Exception,e: log.error(e) abort(503) def tocsv(self): try: csv = session.pop("rfa.enviornment.serialize") except Exception,e: log.error(e) abort(503) if csv: response.content_type='text/csv' response.status_int=200 response.write(csv) else: abort(404) The above setup works perfectly fine, however, is there a better/slicker/neater way of doing it? Ideally I wouldn't like to redirect the request; instead I'd like to either rename location or set content-disposition: attachment; filename='XXX.csv' [ unsuccessfully tried both :( ] Am I missing something obvious here? Cheers UPDATE: Thanks to ebo I've managed to do fix content-disposition. Should better read W3C specs next time ;) A: You should be able to set the content-disposition header on a response object. If you have already tried that, it may not have worked because the http standard says that the quotes should be done by double-quote marks.
Pylons: response renaming? Is there a better way?
I've got a Pylons controller with an action called serialize returning content_type=text/csv. I'd like the response of the action to be named based on the input patameter, i.e. for the following route, produced csv file should be named {id}.csv : /app/PROD/serialize => PROD.csv (so a user can open the file in Excel with a proper name directly via a webbrowser) map.connect('/app/{id}/serialize',controller = 'csvproducer',action='serialize') I've tried to set different HTTP headers and properties of the webob's response object with no luck. However, I figured out a workaround by simply adding a new action to the controller and dynamically redirecting the original action to that new action, i.e.: map.connect('/app/{id}/serialize',controller = 'csvproducer',action='serialize') map.connect('/app/csv/{foo}',controller = 'csvproducer', action='tocsv') The controller's snippet: def serialize(self,id): try: session['key'] = self.service.serialize(id) #produces csv content session.save() redirect_to(str("/app/csv/%s.csv" % id)) except Exception,e: log.error(e) abort(503) def tocsv(self): try: csv = session.pop("rfa.enviornment.serialize") except Exception,e: log.error(e) abort(503) if csv: response.content_type='text/csv' response.status_int=200 response.write(csv) else: abort(404) The above setup works perfectly fine, however, is there a better/slicker/neater way of doing it? Ideally I wouldn't like to redirect the request; instead I'd like to either rename location or set content-disposition: attachment; filename='XXX.csv' [ unsuccessfully tried both :( ] Am I missing something obvious here? Cheers UPDATE: Thanks to ebo I've managed to do fix content-disposition. Should better read W3C specs next time ;)
[ "You should be able to set the content-disposition header on a response object.\nIf you have already tried that, it may not have worked because the http standard says that the quotes should be done by double-quote marks.\n" ]
[ 2 ]
[]
[]
[ "pylons", "python", "response", "webob", "wsgi" ]
stackoverflow_0002285247_pylons_python_response_webob_wsgi.txt
Q: Adding text to p tag in Beautiful Soup I was wondering if anyone knew how to add text to a tag (p, b -- any tag where you might want to include character data). The documentation mentions no where how you might do this. A: I'm not sure exactly if this is what you want, but maybe it's a start... from BeautifulSoup import BeautifulSoup, NavigableString html = "<p></p>" soup = BeautifulSoup(html) ptag = soup.find('p') ptag.insert(0, NavigableString("new")) print ptag Outputs <p>new</p> The documentations shows a few more similar examples: http://www.crummy.com/software/BeautifulSoup/documentation.html#Modifying%20the%20Parse%20Tree A: >>> import BeautifulSoup >>> b=BeautifulSoup.BeautifulSoup("<p></p><p></p>") >>> for t,s in zip(b,[u'hello',u'world']): ... t.contents.append(BeautifulSoup.NavigableString(s)) ... >>> b <p>hello</p><p>world</p>
Adding text to p tag in Beautiful Soup
I was wondering if anyone knew how to add text to a tag (p, b -- any tag where you might want to include character data). The documentation mentions no where how you might do this.
[ "I'm not sure exactly if this is what you want, but maybe it's a start...\nfrom BeautifulSoup import BeautifulSoup, NavigableString\n\nhtml = \"<p></p>\"\nsoup = BeautifulSoup(html)\nptag = soup.find('p')\nptag.insert(0, NavigableString(\"new\"))\nprint ptag\n\nOutputs\n<p>new</p>\n\nThe documentations shows a few more similar examples: http://www.crummy.com/software/BeautifulSoup/documentation.html#Modifying%20the%20Parse%20Tree\n", ">>> import BeautifulSoup\n>>> b=BeautifulSoup.BeautifulSoup(\"<p></p><p></p>\")\n>>> for t,s in zip(b,[u'hello',u'world']):\n... t.contents.append(BeautifulSoup.NavigableString(s))\n... \n>>> b\n<p>hello</p><p>world</p>\n\n" ]
[ 8, 1 ]
[]
[]
[ "beautifulsoup", "html", "python", "xml" ]
stackoverflow_0002285389_beautifulsoup_html_python_xml.txt
Q: Do all dynamic languages have the circular import issue? For the following Python code: first.py # first.py from second import Second class First: def __init__(self): print 'Second' second.py # second.py from first import First class Second: def __init__(self): print 'Second' After creating the files and running the following from the shell: python first.py I get the error: ImportError: cannot import name Second Do other dynamic languages like Ruby have this kind of issue? The reason I'm asking is because I'm encountering this issue in a Django project where 2 models depend on each other. I know that the possible solutions are re-designing the project or import on demand. I just want to know if devs in other dynamic languages have experienced this issue. A: Python can handle circular imports to some extent. In cases where no sense can be made, the solution would probably still not make sense in another language. Most of the problems can be cleared up by using import first and later referring to first.First instead of from first import First. It would be better if you could move shared code off to its own module or somehow refactor out the need for a circular import. Circular imports always indicate a design problem. A: Recursive definitions are not a problem restricted to dynamic languages. It's also often an issue in statically types languages. It might show up as a compile error because one of the types will be used before it is defined. In some languages the solution is to use forward declarations. Other languages solve the problem by compiling more than one file at once. In Python you can solve the problem by moving the imports from the top level into the functions where they are needed. Also, a circular reference isn't actually an error, so if you are careful, you can make it work anyway. A: All other posters are correct that circular imports are a serious issue that you should fix, structurally. However, specificly with Python/Django models, you can use string names to setup foreign keys to avoid these circular dependency issues -- #appA/models.py class A(models.Model): b = models.ForeignKey('appB.b') #appB/models.py class B(models.Model): a = models.ForeignKey('appA.a') Circular references in DB tables aren't necessarily a bad thing (but aren't always good); Django allows for definition of keys with a string to help in situations where it's necessary. If you actually need to instantiate the two classes inside one another, you've got bigger problems. A: Logically this is a paradox. It's the chicken and egg issue in code form. One of them has to come first. As suggested by the others, please go back to the drawing board and you'll be better off for it in the long run. Languages prevent you from doing this stuff for a reason! A: Note that if you just move your imports to the end of your module, circular imports will work as expected. Like so: first.py # first.py class First: def __init__(self): print 'Second' from second import Second second.py # second.py class Second: def __init__(self): print 'Second' from first import First Fredrik Lundh's import reference is worth a read. As others have advised, though, you're best off rejiggering your code to avoid circular imports entirely.
Do all dynamic languages have the circular import issue?
For the following Python code: first.py # first.py from second import Second class First: def __init__(self): print 'Second' second.py # second.py from first import First class Second: def __init__(self): print 'Second' After creating the files and running the following from the shell: python first.py I get the error: ImportError: cannot import name Second Do other dynamic languages like Ruby have this kind of issue? The reason I'm asking is because I'm encountering this issue in a Django project where 2 models depend on each other. I know that the possible solutions are re-designing the project or import on demand. I just want to know if devs in other dynamic languages have experienced this issue.
[ "Python can handle circular imports to some extent. In cases where no sense can be made, the solution would probably still not make sense in another language. Most of the problems can be cleared up by using import first and later referring to first.First instead of from first import First. \nIt would be better if you could move shared code off to its own module or somehow refactor out the need for a circular import. Circular imports always indicate a design problem.\n", "Recursive definitions are not a problem restricted to dynamic languages. It's also often an issue in statically types languages. It might show up as a compile error because one of the types will be used before it is defined.\nIn some languages the solution is to use forward declarations. Other languages solve the problem by compiling more than one file at once.\nIn Python you can solve the problem by moving the imports from the top level into the functions where they are needed. Also, a circular reference isn't actually an error, so if you are careful, you can make it work anyway.\n", "All other posters are correct that circular imports are a serious issue that you should fix, structurally.\nHowever, specificly with Python/Django models, you can use string names to setup foreign keys to avoid these circular dependency issues --\n#appA/models.py\nclass A(models.Model):\n b = models.ForeignKey('appB.b')\n\n#appB/models.py\nclass B(models.Model):\n a = models.ForeignKey('appA.a')\n\nCircular references in DB tables aren't necessarily a bad thing (but aren't always good); Django allows for definition of keys with a string to help in situations where it's necessary. If you actually need to instantiate the two classes inside one another, you've got bigger problems.\n", "Logically this is a paradox. It's the chicken and egg issue in code form. One of them has to come first. As suggested by the others, please go back to the drawing board and you'll be better off for it in the long run. Languages prevent you from doing this stuff for a reason!\n", "Note that if you just move your imports to the end of your module, circular imports will work as expected. Like so:\nfirst.py\n# first.py\nclass First:\n def __init__(self):\n print 'Second'\nfrom second import Second\n\nsecond.py\n# second.py\nclass Second:\n def __init__(self):\n print 'Second'\nfrom first import First\n\nFredrik Lundh's import reference is worth a read. As others have advised, though, you're best off rejiggering your code to avoid circular imports entirely.\n" ]
[ 12, 3, 2, 1, 1 ]
[]
[]
[ "dynamic_languages", "python", "ruby" ]
stackoverflow_0002284968_dynamic_languages_python_ruby.txt
Q: What resources/references are available for multithreaded programming in Python? I'm evaluating the use of Python for a new project and ran through some basic tutorials but am looking for some recommendations and resources for multithreaded development in Python? How does it compare to other languages? A: I'd recommend http://herbsutter.wordpress.com/ (scroll down to the efficient concurrency columns) for a really great overview of what multiprocessing is all about. Yes, that guy talks about concurrency in a C++ context, but most of it is applicable for any language. If you mention concurrency and Python, a lot of people might yell out "global interpreter lock" and say Python can't really do concurrency. That's nonsense from the past. The Multiprocess module allows proper usage of multiple cores, with the nice benefit that it is really easy to split certain kinds of tasks over multiple machines as well as cores. The multiprocessing module is fairly recent, and a consequence is that Python still has much unexplored potential in doing concurrency. But the bottom line is that Python has all the proper tools, from multiprocessing with its message passing and shared memory to green threads A: Just to be sure, you mention multithreading and not multiprocessing. Information on Multithreading is available at that link. Multithreading is functionally different than multiprocessing. As mentioned in the other answers, I recommend Multiprocessing since it does a good job of utilizing multiple processors. I have used the multiprocessing modules successfully in a few projects. A: The multiprocessing module is great and relieves from the limitations of the GIL. Of course you can also have recourse to C based modules with threads etc. A: here are 2 good python threading tutorials with code samples and some good background info: http://linuxgazette.net/107/pai.html http://www.ibm.com/developerworks/aix/library/au-threadingpython/ A: To multithread in python, you can use the python built-in threading module. However, be aware that if your threads are compute-bound rather than IO bound, you are likely to have worse performance when multithreading. If your execution threads are indeed compute-bound, take a look at the multiprocessing module or stackless. A: Although the comments about multiprocessing being a very useful new package that allows easily taking advantage of multi-core systems, your requirements for multithreaded behaviour may not require that, and may also be entirely unaffected by the "limitations of the GIL". We've built many applications, all of them multithreaded, which are used for various types of machine control (or "instrumentation", if you wish). The GIL is entirely a non-issue for us, perhaps because we're generally not CPU-bound though in the few areas where we are it's also never been an issue as the external packages we take advantage of release the GIL when required. (The intensity of the negative comments about the GIL always surprises me, probably because we work in somewhat atypical areas and ways.) Python's threading support is highly effective, very easy to work with, and very robust. Not only is it rare that we have to concern ourselves with the lower-level concurrency issues (in some languages you have to spend half your time thinking about what to lock and when to lock it), but in the few areas where we still need to pay attention to it the available support makes it all relatively easy. One key thing is to leverage the Queue class, since using it where possible often eliminates any remaining concerns about critical sections, race conditions, etc. Python's primitive objects (integers, dicts, lists, etc) are all about as thread-safe as one would like, though if you are new to threaded applications they won't protect you from your own ignorance. For experienced programmers in this area, I think Python's highly effective and easy to use.
What resources/references are available for multithreaded programming in Python?
I'm evaluating the use of Python for a new project and ran through some basic tutorials but am looking for some recommendations and resources for multithreaded development in Python? How does it compare to other languages?
[ "I'd recommend http://herbsutter.wordpress.com/ (scroll down to the efficient concurrency columns) for a really great overview of what multiprocessing is all about. Yes, that guy talks about concurrency in a C++ context, but most of it is applicable for any language.\nIf you mention concurrency and Python, a lot of people might yell out \"global interpreter lock\" and say Python can't really do concurrency. That's nonsense from the past. The Multiprocess module allows proper usage of multiple cores, with the nice benefit that it is really easy to split certain kinds of tasks over multiple machines as well as cores.\nThe multiprocessing module is fairly recent, and a consequence is that Python still has much unexplored potential in doing concurrency. But the bottom line is that Python has all the proper tools, from multiprocessing with its message passing and shared memory to green threads\n", "Just to be sure, you mention multithreading and not multiprocessing. Information on Multithreading\nis available at that link. Multithreading is functionally different than multiprocessing. As mentioned in the other answers, I recommend Multiprocessing since it does a good job of utilizing multiple processors. I have used the multiprocessing modules successfully in a few projects.\n", "The multiprocessing module is great and relieves from the limitations of the GIL.\nOf course you can also have recourse to C based modules with threads etc.\n", "here are 2 good python threading tutorials with code samples and some good background info:\nhttp://linuxgazette.net/107/pai.html\nhttp://www.ibm.com/developerworks/aix/library/au-threadingpython/\n", "To multithread in python, you can use the python built-in threading module. However, be aware that if your threads are compute-bound rather than IO bound, you are likely to have worse performance when multithreading. If your execution threads are indeed compute-bound, take a look at the multiprocessing module or stackless.\n", "Although the comments about multiprocessing being a very useful new package that allows easily taking advantage of multi-core systems, your requirements for multithreaded behaviour may not require that, and may also be entirely unaffected by the \"limitations of the GIL\". \nWe've built many applications, all of them multithreaded, which are used for various types of machine control (or \"instrumentation\", if you wish). The GIL is entirely a non-issue for us, perhaps because we're generally not CPU-bound though in the few areas where we are it's also never been an issue as the external packages we take advantage of release the GIL when required. (The intensity of the negative comments about the GIL always surprises me, probably because we work in somewhat atypical areas and ways.)\nPython's threading support is highly effective, very easy to work with, and very robust. Not only is it rare that we have to concern ourselves with the lower-level concurrency issues (in some languages you have to spend half your time thinking about what to lock and when to lock it), but in the few areas where we still need to pay attention to it the available support makes it all relatively easy.\nOne key thing is to leverage the Queue class, since using it where possible often eliminates any remaining concerns about critical sections, race conditions, etc. Python's primitive objects (integers, dicts, lists, etc) are all about as thread-safe as one would like, though if you are new to threaded applications they won't protect you from your own ignorance. For experienced programmers in this area, I think Python's highly effective and easy to use.\n" ]
[ 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0002283610_multithreading_python.txt
Q: splitting one program into several smaller and their binding in python? i want to make from one big program 5 smaller programs:main and program1,program2,program3 and program4.programs1,2,3,4 should use variables from main program and return some new variables,and main program should use(or call) programs1,2,3,4... can i bind these programs using functions,modules or something else and how? i'm new in Python and any help will be usefull A: You can simply use functions to do this: def function1(a): print a def function2(b): print b def function3(c): print c def function4(): return "hello!" def main(): a, b, c = (1, 2, 3) function1(a) function2(b) function3(c) d = function4() print d if __name__ == "__main__": main() Or you can put the definitions of the functions in a seperate file, say functions.py and use import functions in your main program file. import functions def main(): a, b, c = (1, 2, 3) functions.function1(a) functions.function2(b) functions.function3(c) d = functions.function4() print d if __name__ == "__main__": main() This should be enough to get you started. I would recommend Dive Into Python as a good learning reference if you have some previous experience programming and want to learn more about Python.
splitting one program into several smaller and their binding in python?
i want to make from one big program 5 smaller programs:main and program1,program2,program3 and program4.programs1,2,3,4 should use variables from main program and return some new variables,and main program should use(or call) programs1,2,3,4... can i bind these programs using functions,modules or something else and how? i'm new in Python and any help will be usefull
[ "You can simply use functions to do this:\ndef function1(a):\n print a\n\ndef function2(b):\n print b\n\ndef function3(c):\n print c\n\ndef function4():\n return \"hello!\"\n\ndef main():\n a, b, c = (1, 2, 3)\n function1(a)\n function2(b)\n function3(c)\n d = function4()\n print d\n\nif __name__ == \"__main__\":\n main()\n\nOr you can put the definitions of the functions in a seperate file, say functions.py and use import functions in your main program file.\nimport functions\n\ndef main():\n a, b, c = (1, 2, 3)\n functions.function1(a)\n functions.function2(b)\n functions.function3(c)\n d = functions.function4()\n print d\n\nif __name__ == \"__main__\":\n main()\n\nThis should be enough to get you started. I would recommend Dive Into Python as a good learning reference if you have some previous experience programming and want to learn more about Python.\n" ]
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0002285746_python.txt
Q: Python dictionary that maps strings to a set of strings? I would like to be able to make a Python dictionary with strings as keys and sets of strings as the values. E.g.: { "crackers" : ["crunchy", "salty"] } It must be a set, not a list. However, when I try the following: word_dict = dict() word_dict["foo"] = set() word_dict["foo"] = word_dict["foo"].add("baz") word_dict["foo"] = word_dict["foo"].add("bang") I get: Traceback (most recent call last): File "process_input.py", line 56, in <module> test() File "process_input.py", line 51, in test word_dict["foo"] = word_dict["foo"].add("bang") AttributeError: 'NoneType' object has no attribute 'add' If I do this: word_dict = dict() myset = set() myset.add("bar") word_dict["foo"] = myset myset.add("bang") word_dict["foo"] = myset for key, value in word_dict: print key, print value I get: Traceback (most recent call last): File "process_input.py", line 61, in <module> test() File "process_input.py", line 58, in test for key, value in word_dict: ValueError: too many values to unpack Any tips on how to coerce Python into doing what I'd like? I'm an intermediate Python user (or so I thought, until I ran into this problem.) A: set.add() does not return a new set, it modifies the set it is called on. Use it this way: word_dict = dict() word_dict["foo"] = set() word_dict["foo"].add("baz") word_dict["foo"].add("bang") Also, if you use a for loop to iterate over a dict, you are iterating over the keys: for key in word_dict: print key, word_dict[key] Alternatively you could iterate over word_dict.items() or word_dict.iteritems(): for key, value in word_dict.items(): print key, value A: from collections import defaultdict word_dict = defaultdict(set) word_dict['banana'].add('yellow') word_dict['banana'].add('brown') word_dict['apple'].add('red') word_dict['apple'].add('green') for key,values in word_dict.iteritems(): print "%s: %s" % (key, values) A: When you say word_dict["foo"].add("baz"), you are adding 'baz' to the set word_dict["foo"]. The function returns None -- updating the set is a side-effect. So word_dict["foo"] = word_dict["foo"].add("baz") ultimately sets word_dict["foo"] to None. Just word_dict["foo"].add("baz") would be correct. In the second scenario, when you say for key, value in word_dict: you run into an error because the correct syntax is for key in word_dict: to loop over just the keys in word_dict. In this situation, you want for key,value in word_dict.iteritems(): instead. A: Try: word_dict = dict() myset = set() myset.add("bar") word_dict["foo"] = myset myset.add("bang") word_dict["foo"] = myset for key in word_dict: print key, word_dict[key] It looks like standard dictionary iterator returns only key but not tuple. Proof: >>> d = { 'test': 1 } >>> for k, v in d: print k, v ... Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: too many values to unpack >>> for k in d: print d[k] ... 1 A: The problem is this: word_dict["foo"] = word_dict["foo"].add("baz") When you call word_dict["foo"].add("baz"), you're mutating the set that word_dict["foo"] refers to, and that operation returns None. So reading your statement right to left, you're adding "baz" to the set refered to by word_dict["foo"], and then setting the result of that operation (that is, None) to word_dict["foo"]. So, to make this work as you expect, just remove word_dict["foo"] = from your statement. Dictionaries iterate on their keys by default, hence the ValueError you try this: for key, value in word_dict: What's happening here is that iterating on word_dict is returning a key only (say, "foo"), which you're then trying to unpack into the variables key & value. Unpacking "foo" gives you "f", "o", & "o", which is one value too many to fit into two variables, and hence your ValueError. As others have stated, what you want is to iterate on the dictionary's key-value pairs, like so: for key, value in word_dict.iteritems ():
Python dictionary that maps strings to a set of strings?
I would like to be able to make a Python dictionary with strings as keys and sets of strings as the values. E.g.: { "crackers" : ["crunchy", "salty"] } It must be a set, not a list. However, when I try the following: word_dict = dict() word_dict["foo"] = set() word_dict["foo"] = word_dict["foo"].add("baz") word_dict["foo"] = word_dict["foo"].add("bang") I get: Traceback (most recent call last): File "process_input.py", line 56, in <module> test() File "process_input.py", line 51, in test word_dict["foo"] = word_dict["foo"].add("bang") AttributeError: 'NoneType' object has no attribute 'add' If I do this: word_dict = dict() myset = set() myset.add("bar") word_dict["foo"] = myset myset.add("bang") word_dict["foo"] = myset for key, value in word_dict: print key, print value I get: Traceback (most recent call last): File "process_input.py", line 61, in <module> test() File "process_input.py", line 58, in test for key, value in word_dict: ValueError: too many values to unpack Any tips on how to coerce Python into doing what I'd like? I'm an intermediate Python user (or so I thought, until I ran into this problem.)
[ "set.add() does not return a new set, it modifies the set it is called on. Use it this way:\nword_dict = dict()\nword_dict[\"foo\"] = set()\nword_dict[\"foo\"].add(\"baz\") \nword_dict[\"foo\"].add(\"bang\")\n\nAlso, if you use a for loop to iterate over a dict, you are iterating over the keys:\nfor key in word_dict:\n print key, word_dict[key]\n\nAlternatively you could iterate over word_dict.items() or word_dict.iteritems():\nfor key, value in word_dict.items():\n print key, value\n\n", "from collections import defaultdict\n\nword_dict = defaultdict(set)\nword_dict['banana'].add('yellow')\nword_dict['banana'].add('brown')\nword_dict['apple'].add('red')\nword_dict['apple'].add('green')\nfor key,values in word_dict.iteritems():\n print \"%s: %s\" % (key, values)\n\n", "When you say word_dict[\"foo\"].add(\"baz\"), you are adding 'baz' to the set word_dict[\"foo\"].\nThe function returns None -- updating the set is a side-effect. So \nword_dict[\"foo\"] = word_dict[\"foo\"].add(\"baz\") \n\nultimately sets word_dict[\"foo\"] to None.\nJust word_dict[\"foo\"].add(\"baz\") would be correct.\nIn the second scenario, when you say\nfor key, value in word_dict: \n\nyou run into an error because the correct syntax is \nfor key in word_dict: \n\nto loop over just the keys in word_dict. In this situation, you want\nfor key,value in word_dict.iteritems(): \n\ninstead.\n", "Try:\nword_dict = dict()\nmyset = set()\nmyset.add(\"bar\")\nword_dict[\"foo\"] = myset\nmyset.add(\"bang\")\nword_dict[\"foo\"] = myset\n\nfor key in word_dict: \n print key, word_dict[key]\n\nIt looks like standard dictionary iterator returns only key but not tuple.\nProof:\n>>> d = { 'test': 1 }\n>>> for k, v in d: print k, v\n... \nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nValueError: too many values to unpack\n>>> for k in d: print d[k]\n... \n1\n\n", "The problem is this:\nword_dict[\"foo\"] = word_dict[\"foo\"].add(\"baz\") \n\nWhen you call word_dict[\"foo\"].add(\"baz\"), you're mutating the set that word_dict[\"foo\"] refers to, and that operation returns None. So reading your statement right to left, you're adding \"baz\" to the set refered to by word_dict[\"foo\"], and then setting the result of that operation (that is, None) to word_dict[\"foo\"].\nSo, to make this work as you expect, just remove word_dict[\"foo\"] = from your statement.\nDictionaries iterate on their keys by default, hence the ValueError you try this:\nfor key, value in word_dict: \n\nWhat's happening here is that iterating on word_dict is returning a key only (say, \"foo\"), which you're then trying to unpack into the variables key & value. Unpacking \"foo\" gives you \"f\", \"o\", & \"o\", which is one value too many to fit into two variables, and hence your ValueError.\nAs others have stated, what you want is to iterate on the dictionary's key-value pairs, like so:\nfor key, value in word_dict.iteritems (): \n\n" ]
[ 32, 31, 7, 1, 1 ]
[]
[]
[ "dictionary", "python", "set" ]
stackoverflow_0002285874_dictionary_python_set.txt
Q: Endless Recursion in Python Full disclosure, this is part of a homework assignment (though a small snippet, the project itself is a game playing AI). I have this function built into a tree node class: def recursive_score_calc(self): current_score = self.board for c in self.children: child_score = c.recursive_score_calc() if(turn_color == 1): if(child_score > current_score): current_score = child_score else: if(child_score < current_score): current_score = child_score self.recursive_score = current_score return current_score On a tree of depth 1 (a root and some children), it hits the Python recursion limit already. The function is designed to use dynamic programming to build a min-max tree from the bottom up. To be honest, I have no idea why this isn't working as intended, but I am fairly new to Python as well. Good people of Stack Overflow: Why does this code give me a stack overflow? The Entire Class in question: from Numeric import * class TreeNode: children = [] numChildren = 0 board = zeros([8,8], Int) turn_color = 0 # signifies NEXT to act board_score = 0 # tally together board items recursive_score = 0 # set when the recursive score function is called def __init__(self, board, turn_color): self.board = copy.deepcopy(board) self.turn_color = turn_color for x in range (0,7): for y in range (0,7): self.board_score = self.board_score + self.board[x][y] def add_child(self, child): self.children.append(child) self.numChildren = self.numChildren + 1 def recursive_score_calc(self): current_score = self.board # if no valid moves, we are the board. no move will make our score worse for c in self.children: child_score = c.recursive_score_calc() if(turn_color == 1): if(child_score > current_score): current_score = child_score else: if(child_score < current_score): current_score = child_score self.recursive_score = current_score return current_score The function that interacts with this (Please Note, this is bordering on the edge of what is appropriate to post here, I'll remove this part after I accept an answer): [It didn't turn out to be the critical part anyways] A: This bit of your code: class TreeNode: children = [] means that every instance of the class shares the same children list. So, in this bit: def add_child(self, child): self.children.append(child) you're appending to the "class-global" list. So, of course, every node is a child of every other node, and disaster is guaranteed. Fix: change your class to class TreeNode(object): numChildren = 0 board = zeros([8,8], Int) turn_color = 0 # signifies NEXT to act board_score = 0 # tally together board items recursive_score = 0 # set when the recursive score function is called def __init__(self, board, turn_color): self.children = [] self.board = copy.deepcopy(board) self.turn_color = turn_color ... etc, etc ... the rest doesn't need to change to fix this bug (though there may be opportunities to improve it or fix other bugs, I have not inspected it deeply), but failing to assign self.children in __init__ is causing your current bug, and failing to inherit from object (unless you're using Python 3, but I'd hope you would mention this little detail if so;-) is just a bug waiting to happen. A: It looks like self.children contains self. EDIT: The children property is being initialized to the same array instance for every instance of the TreeNode class. You need to create a separate array instance for each TreeNode instance by adding self.children = [] to __init__. The board array has the same problem.
Endless Recursion in Python
Full disclosure, this is part of a homework assignment (though a small snippet, the project itself is a game playing AI). I have this function built into a tree node class: def recursive_score_calc(self): current_score = self.board for c in self.children: child_score = c.recursive_score_calc() if(turn_color == 1): if(child_score > current_score): current_score = child_score else: if(child_score < current_score): current_score = child_score self.recursive_score = current_score return current_score On a tree of depth 1 (a root and some children), it hits the Python recursion limit already. The function is designed to use dynamic programming to build a min-max tree from the bottom up. To be honest, I have no idea why this isn't working as intended, but I am fairly new to Python as well. Good people of Stack Overflow: Why does this code give me a stack overflow? The Entire Class in question: from Numeric import * class TreeNode: children = [] numChildren = 0 board = zeros([8,8], Int) turn_color = 0 # signifies NEXT to act board_score = 0 # tally together board items recursive_score = 0 # set when the recursive score function is called def __init__(self, board, turn_color): self.board = copy.deepcopy(board) self.turn_color = turn_color for x in range (0,7): for y in range (0,7): self.board_score = self.board_score + self.board[x][y] def add_child(self, child): self.children.append(child) self.numChildren = self.numChildren + 1 def recursive_score_calc(self): current_score = self.board # if no valid moves, we are the board. no move will make our score worse for c in self.children: child_score = c.recursive_score_calc() if(turn_color == 1): if(child_score > current_score): current_score = child_score else: if(child_score < current_score): current_score = child_score self.recursive_score = current_score return current_score The function that interacts with this (Please Note, this is bordering on the edge of what is appropriate to post here, I'll remove this part after I accept an answer): [It didn't turn out to be the critical part anyways]
[ "This bit of your code:\nclass TreeNode:\n children = []\n\nmeans that every instance of the class shares the same children list. So, in this bit:\ndef add_child(self, child):\n self.children.append(child)\n\nyou're appending to the \"class-global\" list. So, of course, every node is a child of every other node, and disaster is guaranteed.\nFix: change your class to\nclass TreeNode(object):\n numChildren = 0\n board = zeros([8,8], Int)\n turn_color = 0 # signifies NEXT to act\n board_score = 0 # tally together board items\n recursive_score = 0 # set when the recursive score function is called\n\ndef __init__(self, board, turn_color):\n self.children = []\n self.board = copy.deepcopy(board)\n self.turn_color = turn_color\n... etc, etc ...\n\nthe rest doesn't need to change to fix this bug (though there may be opportunities to improve it or fix other bugs, I have not inspected it deeply), but failing to assign self.children in __init__ is causing your current bug, and failing to inherit from object (unless you're using Python 3, but I'd hope you would mention this little detail if so;-) is just a bug waiting to happen.\n", "It looks like self.children contains self.\nEDIT:\nThe children property is being initialized to the same array instance for every instance of the TreeNode class.\nYou need to create a separate array instance for each TreeNode instance by adding self.children = [] to __init__.\nThe board array has the same problem.\n" ]
[ 7, 3 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0002286019_python_recursion.txt
Q: how does stackoverflow get the user-info when people login site use openid i want to get the userid and somethins other about user. but i don't get this i used pinax what should i do ?? thanks ex:facebook Javascript (from therunaround demo): FB.Facebook.get_sessionState().waitUntilReady(function() { var user = FB.Facebook.apiClient.get_session() ? FB.Facebook.apiClient.get_session().uid : null; } A: You can read about the open-id implementation details on their site, where: http://openid.net/add-openid/add-getting-started/. In a nutshell, you redirect the client to the openid provider who fills out the appropriate information, then the provider sends the client back to your site. You then make a (HTTP) request directly to the OpenID provider to retrieve the information that the client authorized them to give you. What information that is is up to the client and his openid provider, but usually includes a name and email address, and sometimes a physical address. A: I don't think SO got my (google) userid when I logged on with OpenID based on Google -- if it did, somehow miraculously bypassing the OpenID safeguards (?), it certainly kept this fact very well hidden. What makes you think otherwise?
how does stackoverflow get the user-info when people login site use openid
i want to get the userid and somethins other about user. but i don't get this i used pinax what should i do ?? thanks ex:facebook Javascript (from therunaround demo): FB.Facebook.get_sessionState().waitUntilReady(function() { var user = FB.Facebook.apiClient.get_session() ? FB.Facebook.apiClient.get_session().uid : null; }
[ "You can read about the open-id implementation details on their site, where: http://openid.net/add-openid/add-getting-started/.\nIn a nutshell, you redirect the client to the openid provider who fills out the appropriate information, then the provider sends the client back to your site. You then make a (HTTP) request directly to the OpenID provider to retrieve the information that the client authorized them to give you. What information that is is up to the client and his openid provider, but usually includes a name and email address, and sometimes a physical address.\n", "I don't think SO got my (google) userid when I logged on with OpenID based on Google -- if it did, somehow miraculously bypassing the OpenID safeguards (?), it certainly kept this fact very well hidden. What makes you think otherwise?\n" ]
[ 1, 0 ]
[]
[]
[ "django", "openid", "python" ]
stackoverflow_0002285976_django_openid_python.txt
Q: detection of communication failure when "put" in queue I am using the multiprocessing python module with Queue for communication between processes. Some processes only send (i.e. queue.put) and I can't seem to find a way to detect when the receiving end gets terminated abruptly. Is there a way to detect if the process at the other end of the Queue gets terminated without having to get from the Queue? Isn't there a signal I could trap somehow? Or do I have to periodically get from the Queue and trap the EOFError manually. A: I don't believe multiprocessing sets up a "watch-dog" process for you to take care of crashes or kills of some of your processes. It may be worth your while to set one up (pretty hard to do cross-platform, but if, say, you're only worried about Linux, it's not that terrible).
detection of communication failure when "put" in queue
I am using the multiprocessing python module with Queue for communication between processes. Some processes only send (i.e. queue.put) and I can't seem to find a way to detect when the receiving end gets terminated abruptly. Is there a way to detect if the process at the other end of the Queue gets terminated without having to get from the Queue? Isn't there a signal I could trap somehow? Or do I have to periodically get from the Queue and trap the EOFError manually.
[ "I don't believe multiprocessing sets up a \"watch-dog\" process for you to take care of crashes or kills of some of your processes. It may be worth your while to set one up (pretty hard to do cross-platform, but if, say, you're only worried about Linux, it's not that terrible).\n" ]
[ 0 ]
[]
[]
[ "multiprocessing", "python", "queue" ]
stackoverflow_0002285922_multiprocessing_python_queue.txt
Q: Python URL Characters I really new to Python and coding in general, but I have been making some good strides. I am able to pull some data off of the web through an API, and the result should be a string. What I am seeing though, are some instances such as "& amp;"" and " &quot". (I modified the character sets so it would print properly to the screen) I figure there is a way to clean this string and remove the characters such that it looks like it does on a computer screen. I tried searching for urldecoding, but admittedly I dont even know if that is the solution. Any help on how to remove these "extra" characters and produce a readable string will be greatly appreciated! Many thanks in advance, Brock A: xml.sax.saxutils.unescape(data[, entities]): Unescape '&amp', '&lt', and '&gt' in a string of data. You can unescape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value. '&amp', '&lt', and '&gt' are always unescaped, even if entities is provided.
Python URL Characters
I really new to Python and coding in general, but I have been making some good strides. I am able to pull some data off of the web through an API, and the result should be a string. What I am seeing though, are some instances such as "& amp;"" and " &quot". (I modified the character sets so it would print properly to the screen) I figure there is a way to clean this string and remove the characters such that it looks like it does on a computer screen. I tried searching for urldecoding, but admittedly I dont even know if that is the solution. Any help on how to remove these "extra" characters and produce a readable string will be greatly appreciated! Many thanks in advance, Brock
[ "xml.sax.saxutils.unescape(data[, entities]): Unescape '&amp', '&lt', and '&gt' in a string of data.\nYou can unescape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value. '&amp', '&lt', and '&gt' are always unescaped, even if entities is provided.\n" ]
[ 2 ]
[]
[]
[ "html", "html_entities", "python" ]
stackoverflow_0002286188_html_html_entities_python.txt
Q: The origin of using # as a comment in Python? So I just had like this mental explosion dude! I was looking at my Python source code and was reading some comments and then I looked a the comments again. When I came across this: #!/usr/bin/env python # A regular comment Which made me wonder, was # chosen as the symbol to start a comment because it would allow the python program to be invoked in a shell, like so: ./test.py and then be ignored once the python interpreter was running? A: Yes. Using # to start a comment is a convention followed by every major interpreted language designed to work on POSIX systems (i.e. not Windows). It also dovetails nicely with the fact that the sequence "#!" at the beginning of a file is recognized by the OS to mean "run the command on this line" when you try to run the script file itself. But mostly, it's the commonly accepted convention. If python didn't use # to start a comment, it would confuse a lot of people. EDIT Using "#" as a comment marker apparently pre-dates the "#!" hash-bang notation. "#!" was introduced by Dennis Ritchie betwen Unix 7 and 8, while languages that support # as a comment marker existed earlier. For example, the Bourne shell was already the default when Version 7 Unix was introduced. Therefore, the convention of using "#" as a comment marker probably influenced the choice of "#!" as the command line marker, and not the other way around. A: Using # for comments was happening before Python came around. The shebang (#!/usr/bin/env python) convention is almost as old as UNIX itself. The two are intertwined for many interpreted (aka shell) languages. Might as well study up on the history of the shebang! A: "All the rest of the line after character X" is clearly the handiest way to do comments if you have an X available (C++ had to use two characters, //, for the purpose, to offer an alternative to C's clunky PL/I-inspired '/' ... '/' "brackets"). Almost all printable Ascii characters can be used for other purposes in Python -- if the choice is between # and ?, with the first already being familiar from its use in sh, bash, tcl, perl, awk, ... -- it's not a very hard choice, is it? The handiness of hashbang is just a vig. A: Very good, you are correct. This is known as the shebang or hash-bang. I suppose a scripting language could use any comment character it liked and allow #! on the first line as a comment, but it does seem easier to just make # be the comment character...
The origin of using # as a comment in Python?
So I just had like this mental explosion dude! I was looking at my Python source code and was reading some comments and then I looked a the comments again. When I came across this: #!/usr/bin/env python # A regular comment Which made me wonder, was # chosen as the symbol to start a comment because it would allow the python program to be invoked in a shell, like so: ./test.py and then be ignored once the python interpreter was running?
[ "Yes.\nUsing # to start a comment is a convention followed by every major interpreted language designed to work on POSIX systems (i.e. not Windows).\nIt also dovetails nicely with the fact that the sequence \"#!\" at the beginning of a file is recognized by the OS to mean \"run the command on this line\" when you try to run the script file itself.\nBut mostly, it's the commonly accepted convention. If python didn't use # to start a comment, it would confuse a lot of people.\nEDIT\nUsing \"#\" as a comment marker apparently pre-dates the \"#!\" hash-bang notation. \"#!\" was introduced by Dennis Ritchie betwen Unix 7 and 8, while languages that support # as a comment marker existed earlier. For example, the Bourne shell was already the default when Version 7 Unix was introduced.\nTherefore, the convention of using \"#\" as a comment marker probably influenced the choice of \"#!\" as the command line marker, and not the other way around.\n", "Using # for comments was happening before Python came around. The shebang (#!/usr/bin/env python) convention is almost as old as UNIX itself. The two are intertwined for many interpreted (aka shell) languages.\nMight as well study up on the history of the shebang!\n", "\"All the rest of the line after character X\" is clearly the handiest way to do comments if you have an X available (C++ had to use two characters, //, for the purpose, to offer an alternative to C's clunky PL/I-inspired '/' ... '/' \"brackets\").\nAlmost all printable Ascii characters can be used for other purposes in Python -- if the choice is between # and ?, with the first already being familiar from its use in sh, bash, tcl, perl, awk, ... -- it's not a very hard choice, is it? The handiness of hashbang is just a vig.\n", "Very good, you are correct.\nThis is known as the shebang or hash-bang. I suppose a scripting language could use any comment character it liked and allow #! on the first line as a comment, but it does seem easier to just make # be the comment character...\n" ]
[ 13, 6, 1, 0 ]
[]
[]
[ "linux", "python", "shell" ]
stackoverflow_0002286120_linux_python_shell.txt
Q: Syntax error after uploading GAE Python app I have created a GAE app that parses RSS feeds using cElementTree. Testing on my local installation of GAE works fine. When I uploaded this app and tried to test it, I get a SyntaxError. The error is : Traceback (most recent call last): File "/base/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 509, in __call__ handler.post(*groups) File "/base/data/home/apps/palmfeedparser/1-6.339910418736930444/pipes.py", line 285, in post tree = ET.parse(urlopen(URL)) File "<string>", line 45, in parse File "<string>", line 32, in parse SyntaxError: no element found: line 14039, column 45 I did what Mr.Alex Martelli suggested and it printed out the following on my local machine: [ ' <ac:tag><![CDATA[Mobilit\xc3\xa4t]]></ac:tag>\n', ' </ac:tags>\n', ' <ac:images>\n', ' <ac:image ac:number="1">\n', ' <ac:asset_url ac:type="app">http://cdn.downloads.example.com/public/1198/de/images/1/A/01.png</ac:asset_url>\n' ] I uploaded the app and it printed out: [ ' <ac:tag><![CDATA[Mobilit\xc3\xa4t]]></ac:tag>\n', ' </ac:tags>\n', ' <ac:images>\n', ' <ac:image ac:number="1">\n', ' <ac:asset_url ac:type="app">http://cdn.downloads.example.com/public/1198/de/images/1/A/01.png</ac:asset_url>\n' ] These lines correspond to the following lines in the RSS feed I am reading: <ac:tags> <ac:tag><![CDATA[Mobilität]]></ac:tag> </ac:tags> <ac:images> <ac:image ac:number="1"> <ac:asset_url ac:type="app">http://cdn.downloads.example.com/public/1198/de/images/1/A/01.png</ac:asset_url> I notice that there is a newline before the closing ac:tags. Line 14039 corresponds to this new line. Update: I use urllib.urlopen to access the URL of the feed. I displayed the contents it fetches both locally and on GAE proper. Locally, no content is truncated. Testing after uploading the app, shows that the feed that has 15289 lines is truncated to 14185 lines. What method can I use to fetch this huge feed? Would urlfetch work? Thanks in advance for your help! A_iyer A: You may have run into one of the mysterious limits placed on GAE. Urlopen has been overridden by google to it's urlfetch method, so there shouldn't be any difference in it. (though it might be worth trying, there are a lot of hidden things in GAE) newline characters shouldn't effect cElementTree. Are there any other logging messages coming through in your AppEngine Logs? (Relating to the urlopen request?)
Syntax error after uploading GAE Python app
I have created a GAE app that parses RSS feeds using cElementTree. Testing on my local installation of GAE works fine. When I uploaded this app and tried to test it, I get a SyntaxError. The error is : Traceback (most recent call last): File "/base/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 509, in __call__ handler.post(*groups) File "/base/data/home/apps/palmfeedparser/1-6.339910418736930444/pipes.py", line 285, in post tree = ET.parse(urlopen(URL)) File "<string>", line 45, in parse File "<string>", line 32, in parse SyntaxError: no element found: line 14039, column 45 I did what Mr.Alex Martelli suggested and it printed out the following on my local machine: [ ' <ac:tag><![CDATA[Mobilit\xc3\xa4t]]></ac:tag>\n', ' </ac:tags>\n', ' <ac:images>\n', ' <ac:image ac:number="1">\n', ' <ac:asset_url ac:type="app">http://cdn.downloads.example.com/public/1198/de/images/1/A/01.png</ac:asset_url>\n' ] I uploaded the app and it printed out: [ ' <ac:tag><![CDATA[Mobilit\xc3\xa4t]]></ac:tag>\n', ' </ac:tags>\n', ' <ac:images>\n', ' <ac:image ac:number="1">\n', ' <ac:asset_url ac:type="app">http://cdn.downloads.example.com/public/1198/de/images/1/A/01.png</ac:asset_url>\n' ] These lines correspond to the following lines in the RSS feed I am reading: <ac:tags> <ac:tag><![CDATA[Mobilität]]></ac:tag> </ac:tags> <ac:images> <ac:image ac:number="1"> <ac:asset_url ac:type="app">http://cdn.downloads.example.com/public/1198/de/images/1/A/01.png</ac:asset_url> I notice that there is a newline before the closing ac:tags. Line 14039 corresponds to this new line. Update: I use urllib.urlopen to access the URL of the feed. I displayed the contents it fetches both locally and on GAE proper. Locally, no content is truncated. Testing after uploading the app, shows that the feed that has 15289 lines is truncated to 14185 lines. What method can I use to fetch this huge feed? Would urlfetch work? Thanks in advance for your help! A_iyer
[ "You may have run into one of the mysterious limits placed on GAE.\nUrlopen has been overridden by google to it's urlfetch method, so there shouldn't be any difference in it. (though it might be worth trying, there are a lot of hidden things in GAE)\nnewline characters shouldn't effect cElementTree.\nAre there any other logging messages coming through in your AppEngine Logs? (Relating to the urlopen request?)\n" ]
[ 0 ]
[]
[]
[ "feed", "python", "rss" ]
stackoverflow_0002269941_feed_python_rss.txt
Q: Putting a message in the same line import pythoncom, pyHook, logging, string LOG_FILENAME = 'logfile.txt' def OnKeyboardEvent(event): print 'MessageName:',event.MessageName print 'Time:',event.Time print 'WindowName:',event.WindowName print 'Ascii:', event.Ascii, chr(event.Ascii) print 'Key:', event.Key print '---' k = event.Key logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG, format='%(message)s') logging.debug(k) return True hm = pyHook.HookManager() hm.KeyDown = OnKeyboardEvent hm.HookKeyboard() pythoncom.PumpMessages() In the logfile.txt the message shows seperate letters on different lines, how can I make it show the message on the same line? A: There doesn't seem to be any way to make Logger.debug() append messages to the same line. Since your log file format is so simple, why not just use a plain file object? logger = open(LOG_FILENAME, 'a') logger.write(k) logger.close()
Putting a message in the same line
import pythoncom, pyHook, logging, string LOG_FILENAME = 'logfile.txt' def OnKeyboardEvent(event): print 'MessageName:',event.MessageName print 'Time:',event.Time print 'WindowName:',event.WindowName print 'Ascii:', event.Ascii, chr(event.Ascii) print 'Key:', event.Key print '---' k = event.Key logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG, format='%(message)s') logging.debug(k) return True hm = pyHook.HookManager() hm.KeyDown = OnKeyboardEvent hm.HookKeyboard() pythoncom.PumpMessages() In the logfile.txt the message shows seperate letters on different lines, how can I make it show the message on the same line?
[ "There doesn't seem to be any way to make Logger.debug() append messages to the same line. Since your log file format is so simple, why not just use a plain file object?\n\nlogger = open(LOG_FILENAME, 'a')\nlogger.write(k)\nlogger.close()\n\n" ]
[ 0 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0002286287_logging_python.txt
Q: Positional Comparisons in Python (Here's a sort of hypothetical situation for everybody. I'm more looking for directions rather than straight processes, but if you can provide them, awesome!) So let's say we have a list of athletes, I'm going to use figure skaters since I'm knee deep in the Winter Olympics right now. (I'm throwing it in a dictionary since that's my first instinct, doesn't have to be this way.) after_short_program = { '1': 'Evgeni Plushenko', '2': 'Evan Lysacek', '3': 'Daisuke Takahashi', '4': 'Nobunari Oda', '5': 'Stephane Lambiel' } So after the free skate (which hasn't happened as I ask this), let's say these are the standings. after_free_skate = { '1': 'Evan Lysacek', '2': 'Daisuke Takahashi', '3': 'Evgeni Plushenko', '4': 'Stephane Lambiel', '5': 'Nobunari Oda', } So, the questions: How would one go about comparing the two sets of data? Evan Lysacek moved up one space to win the gold, Daisuke moved up one place to win the silver and Evgeni moved down two spaces to win the bronze. Off the top of my head, if I were to render this information, I'd want to say, "Evan (+1 or moved up one), Evgeni (-2 or moved down two), etc." Is there a way in Python to extract that sort of data from comparisons? A: I would use the athlet name as key in your dicts. Then you can look for their position more easily. Something like: diff = {} for (a, pos2) in after_free_skate.items(): pos1 = after_short_program[a] diff[a] = pos2 - pos1 I hope it helps A: This solution prints the results in the same order as the final placings. If the place has not changed (+0) is printed. If you wish to filter those out instead, simply put an if diff: before the print >>> after_short_program = [ ... 'Evgeni Plushenko', ... 'Evan Lysacek', ... 'Daisuke Takahashi', ... 'Nobunari Oda', ... 'Stephane Lambiel', ... ] >>> >>> after_free_skate = [ ... 'Evan Lysacek', ... 'Daisuke Takahashi', ... 'Evgeni Plushenko', ... 'Stephane Lambiel', ... 'Nobunari Oda', ... ] >>> >>> for i,item in enumerate(after_free_skate): ... diff = after_short_program.index(item)-i ... print "%s (%+d)"%(item,diff) ... ... Evan Lysacek (+1) Daisuke Takahashi (+1) Evgeni Plushenko (-2) Stephane Lambiel (+1) Nobunari Oda (-1) As pwdyson points out, if your stopwatches aren't good enough, you might get a tie. So this modification uses dicts instead of lists. The order of the placings is still preserved >>> from operator import itemgetter >>> >>> after_short_program = { ... 'Evgeni Plushenko':1, ... 'Evan Lysacek':2, ... 'Daisuke Takahashi':3, ... 'Stephane Lambiel':4, ... 'Nobunari Oda':5, ... } >>> >>> after_free_skate = { ... 'Evan Lysacek':1, ... 'Daisuke Takahashi':2, ... 'Evgeni Plushenko':3, ... 'Stephane Lambiel':4, # These are tied ... 'Nobunari Oda':4, # at 4th place ... } >>> >>> for k,v in sorted(after_free_skate.items(),key=itemgetter(1)): ... diff = after_short_program[k]-v ... print "%s (%+d)"%(k,diff) ... ... Evan Lysacek (+1) Daisuke Takahashi (+1) Evgeni Plushenko (-2) Nobunari Oda (+1) Stephane Lambiel (+0) >>> If there is a possibility of keys in the second dict that are not in the first you can do something like this for k,v in sorted(after_free_skate.items(),key=itemgetter(1)): try: diff = after_short_program[k]-v print "%s (%+d)"%(k,diff) except KeyError: print "%s (new)"%k A: One way would be to flip the keys and values, then take the difference, ie: for k, v in after_free_skate.items(): print 'k', v - after_short_program[k] A: I'd personally use lists as they are naturally suited to store 'positional' information... the following is a rather functional approach employing lists: ###_* input data after_short_program = [ 'Evgeni Plushenko', 'Evan Lysacek', 'Daisuke Takahashi', 'Nobunari Oda', 'Stephane Lambiel' ] after_free_skate = [ 'Evan Lysacek', 'Daisuke Takahashi', 'Evgeni Plushenko', 'Stephane Lambiel', 'Nobunari Oda' ] ## combine all_athletes = set(after_short_program + after_free_skate) ###_* import libraries, define functions from operator import add, sub from functools import partial def tryit(f,*args): try: return f(*args) except: return None def compose(f,g): ## available in functional library return lambda x: f(g(x)) ###_* apply functions ## original and new positions for each athlete ## I usually wrap list.index() in a try-except clause pos = [(x,{'orig':tryit(compose(partial(add,1),after_short_program.index),x), 'new':tryit(compose(partial(add,1),after_free_skate.index),x)}) for i,x in enumerate(all_athletes)] ## calculate the changes (now edited to sort by final position) changes = [(x[0],tryit(sub,x[1]['orig'],x[1]['new'])) for x in sorted(pos,key=lambda x: x[1]['new'])] The output is as follows: >>> changes [('Evan Lysacek', 1), ('Daisuke Takahashi', 1), ('Evgeni Plushenko', -2), ('Stephane Lambiel', 1), ('Nobunari Oda', -1)] A: I would put the names as keys and the positions as values, with the positions as ints: after_short_program = { '1': 'Evgeni Plushenko', '2': 'Evan Lysacek', '3': 'Daisuke Takahashi', '4': 'Nobunari Oda', '5': 'Stephane Lambiel' } after_free_skate = { '1': 'Evan Lysacek', '2': 'Daisuke Takahashi', '3': 'Evgeni Plushenko', '4': 'Stephane Lambiel', '5': 'Nobunari Oda', } after_short_program_swap = {} for k,v in after_short_program.iteritems(): after_short_program_swap[v]=int(k) after_free_skate_swap = {} for k,v in after_free_skate.iteritems(): after_free_skate_swap[v]=int(k) then the code is much simpler: moved = {} for key in after_short_program_swap: moved[key] = after_short_program_swap[key] - after_free_skate_swap[key] print moved prints: {'Evan Lysacek': 1, 'Nobunari Oda': -1, 'Evgeni Plushenko': -2, 'Stephane Lambiel': 1, 'Daisuke Takahashi': 1} to print out in the medal order, following @gnibbler: from operator import itemgetter print '\n'.join('%s (%+d)' % (k,moved[k]) for k,v in sorted(after_free_skate_swap.items(),key=itemgetter(1))) Evan Lysacek (+1) Daisuke Takahashi (+1) Evgeni Plushenko (-2) Stephane Lambiel (+1) Nobunari Oda (-1)
Positional Comparisons in Python
(Here's a sort of hypothetical situation for everybody. I'm more looking for directions rather than straight processes, but if you can provide them, awesome!) So let's say we have a list of athletes, I'm going to use figure skaters since I'm knee deep in the Winter Olympics right now. (I'm throwing it in a dictionary since that's my first instinct, doesn't have to be this way.) after_short_program = { '1': 'Evgeni Plushenko', '2': 'Evan Lysacek', '3': 'Daisuke Takahashi', '4': 'Nobunari Oda', '5': 'Stephane Lambiel' } So after the free skate (which hasn't happened as I ask this), let's say these are the standings. after_free_skate = { '1': 'Evan Lysacek', '2': 'Daisuke Takahashi', '3': 'Evgeni Plushenko', '4': 'Stephane Lambiel', '5': 'Nobunari Oda', } So, the questions: How would one go about comparing the two sets of data? Evan Lysacek moved up one space to win the gold, Daisuke moved up one place to win the silver and Evgeni moved down two spaces to win the bronze. Off the top of my head, if I were to render this information, I'd want to say, "Evan (+1 or moved up one), Evgeni (-2 or moved down two), etc." Is there a way in Python to extract that sort of data from comparisons?
[ "I would use the athlet name as key in your dicts. Then you can look for their position more easily. Something like:\ndiff = {}\nfor (a, pos2) in after_free_skate.items():\n pos1 = after_short_program[a]\n diff[a] = pos2 - pos1\n\nI hope it helps\n", "This solution prints the results in the same order as the final placings.\nIf the place has not changed (+0) is printed.\nIf you wish to filter those out instead, simply put an if diff: before the print\n>>> after_short_program = [\n... 'Evgeni Plushenko',\n... 'Evan Lysacek',\n... 'Daisuke Takahashi',\n... 'Nobunari Oda',\n... 'Stephane Lambiel',\n... ]\n>>> \n>>> after_free_skate = [\n... 'Evan Lysacek',\n... 'Daisuke Takahashi',\n... 'Evgeni Plushenko',\n... 'Stephane Lambiel',\n... 'Nobunari Oda',\n... ]\n>>> \n>>> for i,item in enumerate(after_free_skate):\n... diff = after_short_program.index(item)-i\n... print \"%s (%+d)\"%(item,diff)\n... \n... \nEvan Lysacek (+1)\nDaisuke Takahashi (+1)\nEvgeni Plushenko (-2)\nStephane Lambiel (+1)\nNobunari Oda (-1)\n\nAs pwdyson points out, if your stopwatches aren't good enough, you might get a tie. So this modification uses dicts instead of lists. The order of the placings is still preserved\n>>> from operator import itemgetter\n>>> \n>>> after_short_program = {\n... 'Evgeni Plushenko':1,\n... 'Evan Lysacek':2,\n... 'Daisuke Takahashi':3,\n... 'Stephane Lambiel':4,\n... 'Nobunari Oda':5,\n... }\n>>> \n>>> after_free_skate = {\n... 'Evan Lysacek':1,\n... 'Daisuke Takahashi':2,\n... 'Evgeni Plushenko':3,\n... 'Stephane Lambiel':4, # These are tied\n... 'Nobunari Oda':4, # at 4th place\n... }\n>>> \n>>> for k,v in sorted(after_free_skate.items(),key=itemgetter(1)):\n... diff = after_short_program[k]-v\n... print \"%s (%+d)\"%(k,diff)\n... \n... \nEvan Lysacek (+1)\nDaisuke Takahashi (+1)\nEvgeni Plushenko (-2)\nNobunari Oda (+1)\nStephane Lambiel (+0)\n>>> \n\nIf there is a possibility of keys in the second dict that are not in the first you can do something like this\nfor k,v in sorted(after_free_skate.items(),key=itemgetter(1)):\n try:\n diff = after_short_program[k]-v\n print \"%s (%+d)\"%(k,diff)\n except KeyError:\n print \"%s (new)\"%k\n\n", "One way would be to flip the keys and values, then take the difference, ie:\nfor k, v in after_free_skate.items():\n print 'k', v - after_short_program[k] \n\n", "I'd personally use lists as they are naturally suited to store 'positional' information... the following is a rather functional approach employing lists:\n###_* input data\nafter_short_program = [\n 'Evgeni Plushenko',\n 'Evan Lysacek',\n 'Daisuke Takahashi',\n 'Nobunari Oda',\n 'Stephane Lambiel'\n ]\nafter_free_skate = [\n 'Evan Lysacek',\n 'Daisuke Takahashi',\n 'Evgeni Plushenko',\n 'Stephane Lambiel',\n 'Nobunari Oda'\n ]\n\n## combine\nall_athletes = set(after_short_program + after_free_skate)\n\n###_* import libraries, define functions\nfrom operator import add, sub\nfrom functools import partial\n\ndef tryit(f,*args):\n try: return f(*args)\n except: return None\ndef compose(f,g): ## available in functional library\n return lambda x: f(g(x))\n\n###_* apply functions\n## original and new positions for each athlete\n## I usually wrap list.index() in a try-except clause\npos = [(x,{'orig':tryit(compose(partial(add,1),after_short_program.index),x),\n 'new':tryit(compose(partial(add,1),after_free_skate.index),x)})\n for i,x in enumerate(all_athletes)]\n\n## calculate the changes (now edited to sort by final position)\nchanges = [(x[0],tryit(sub,x[1]['orig'],x[1]['new']))\n for x in sorted(pos,key=lambda x: x[1]['new'])]\n\nThe output is as follows:\n>>> changes\n[('Evan Lysacek', 1), ('Daisuke Takahashi', 1), ('Evgeni Plushenko', -2), ('Stephane Lambiel', 1), ('Nobunari Oda', -1)]\n\n", "I would put the names as keys and the positions as values, with the positions as ints:\nafter_short_program = {\n '1': 'Evgeni Plushenko',\n '2': 'Evan Lysacek',\n '3': 'Daisuke Takahashi',\n '4': 'Nobunari Oda',\n '5': 'Stephane Lambiel'\n}\n\nafter_free_skate = {\n '1': 'Evan Lysacek',\n '2': 'Daisuke Takahashi',\n '3': 'Evgeni Plushenko',\n '4': 'Stephane Lambiel',\n '5': 'Nobunari Oda',\n}\n\nafter_short_program_swap = {}\nfor k,v in after_short_program.iteritems():\n after_short_program_swap[v]=int(k)\n\nafter_free_skate_swap = {}\nfor k,v in after_free_skate.iteritems():\n after_free_skate_swap[v]=int(k)\n\nthen the code is much simpler:\nmoved = {}\nfor key in after_short_program_swap:\n moved[key] = after_short_program_swap[key] - after_free_skate_swap[key]\n\nprint moved\n\nprints:\n{'Evan Lysacek': 1, 'Nobunari Oda': -1, 'Evgeni Plushenko': -2, 'Stephane Lambiel': 1, 'Daisuke Takahashi': 1}\nto print out in the medal order, following @gnibbler:\nfrom operator import itemgetter\nprint '\\n'.join('%s (%+d)' % (k,moved[k]) for k,v in sorted(after_free_skate_swap.items(),key=itemgetter(1)))\n\nEvan Lysacek (+1)\nDaisuke Takahashi (+1)\nEvgeni Plushenko (-2)\nStephane Lambiel (+1)\nNobunari Oda (-1)\n" ]
[ 7, 3, 1, 1, 0 ]
[]
[]
[ "comparison", "python" ]
stackoverflow_0002286557_comparison_python.txt
Q: How to execute a VS2008 command from Python and grab its output? I wish to run tf changeset 12345 Using the Visual Studio 2008 Command tool. It is located in: "c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\" and the command that gets launched is: %comspec% /k ""c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"" x86 I would like to append the "tf changeset 12345" to it somehow and save it to a string WITHOUT first redirecting it to a file. I noticed that when I simply call it from the command line, I get GUI when I type: tf changeset 12345 and I get the textual output when I do: tf changeset 12345 > out.txt I prefer not to create a file on the file system, but hopefully just read it in the "Pythonic way". I have seen brief examples of os.system(), subprocess, but none of them seem to illustrate how to do what I want to do: Run the process from a particular directory (preferably without using chdir) Executing a command which contains environment variables + custom text. Redirect the output without creating a temporary file. Hopefully you can help me get close to what I want. It would help if you tested the solution on VS2008 or some other Windows program. Thank you! A: process = subprocess.Popen(['tf', 'changeset', '12345'], cwd='c:/somedir', env={'SOMEENVVAR': 'SOMEVALUE', ...}, stdout=subprocess.PIPE) for line in process.stdout: print line process.terminate() A: Have a look at this code I used here to do the job that you're looking for. This is written in C#, and is a flexible class, you just need to change the command, look in ps.FileName and ps.Arguments, the output of the command gets redirected to a StringBuilder instance for parsing if so required. The shell executing command in a window is completely hidden and does not show. Hope this helps, Best regards, Tom.
How to execute a VS2008 command from Python and grab its output?
I wish to run tf changeset 12345 Using the Visual Studio 2008 Command tool. It is located in: "c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\" and the command that gets launched is: %comspec% /k ""c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"" x86 I would like to append the "tf changeset 12345" to it somehow and save it to a string WITHOUT first redirecting it to a file. I noticed that when I simply call it from the command line, I get GUI when I type: tf changeset 12345 and I get the textual output when I do: tf changeset 12345 > out.txt I prefer not to create a file on the file system, but hopefully just read it in the "Pythonic way". I have seen brief examples of os.system(), subprocess, but none of them seem to illustrate how to do what I want to do: Run the process from a particular directory (preferably without using chdir) Executing a command which contains environment variables + custom text. Redirect the output without creating a temporary file. Hopefully you can help me get close to what I want. It would help if you tested the solution on VS2008 or some other Windows program. Thank you!
[ "process = subprocess.Popen(['tf', 'changeset', '12345'], cwd='c:/somedir', env={'SOMEENVVAR': 'SOMEVALUE', ...}, stdout=subprocess.PIPE)\n\nfor line in process.stdout:\n print line\n\nprocess.terminate()\n\n", "Have a look at this code I used here to do the job that you're looking for. This is written in C#, and is a flexible class, you just need to change the command, look in ps.FileName and ps.Arguments, the output of the command gets redirected to a StringBuilder instance for parsing if so required. The shell executing command in a window is completely hidden and does not show.\nHope this helps,\nBest regards,\nTom.\n" ]
[ 3, 2 ]
[]
[]
[ "python", "shellexecute", "visual_studio_2008" ]
stackoverflow_0002258094_python_shellexecute_visual_studio_2008.txt
Q: How do I start GWT devmode on a particular port from the console? So, within the directory containing my GWT application, I can type in the console ant devmode And it will start up my GWT application as per usual. So far so good. However, what if wish to specify the port as a dynamic argument when starting devmode. Something conceptually like: ant devmode port=8821 Or am I supposed to pass in some system variable to GWT? What is the convention for this? Thanks. A: Passing an argument via ant can be done via the ant properties. The call would be: ant devmode -Dport=8821 In your ant file specify a property port. The default value will be overridden when you pass the argument via the command line: <property name="port" value="8080" /> //replace 8080 with the default value you want. And in the ant location where you want to use the property, use it as follows: <arg value="-port"/> <arg value="${port}"/> Update: fixed syntax, as suggested by Stephen, of property to make this example correct.
How do I start GWT devmode on a particular port from the console?
So, within the directory containing my GWT application, I can type in the console ant devmode And it will start up my GWT application as per usual. So far so good. However, what if wish to specify the port as a dynamic argument when starting devmode. Something conceptually like: ant devmode port=8821 Or am I supposed to pass in some system variable to GWT? What is the convention for this? Thanks.
[ "Passing an argument via ant can be done via the ant properties. The call would be:\nant devmode -Dport=8821\n\nIn your ant file specify a property port. The default value will be overridden when you pass the argument via the command line:\n<property name=\"port\" value=\"8080\" /> //replace 8080 with the default value you want.\n\nAnd in the ant location where you want to use the property, use it as follows:\n<arg value=\"-port\"/>\n<arg value=\"${port}\"/>\n\nUpdate: fixed syntax, as suggested by Stephen, of property to make this example correct.\n" ]
[ 2 ]
[]
[]
[ "ant", "gwt", "python" ]
stackoverflow_0002286468_ant_gwt_python.txt
Q: Python : updating values in a dictionary I have the following dictionary -> key : (time,edge_list) Now I want to increment all time values by 1. How do I do that? dict_list = dict(key:(time+1,edge_list) for key:(time,edge_list) in dict_list) A: >>> d={"key" : (100,"edge_list")} >>> for i,(time,edge_list) in d.items(): ... d[i] = time+1, edge_list ... >>> d {'key': (101, 'edge_list')} A: dict((key, (time + 1, edge_list)) for (key, (time, edge_list)) in somedict.iteritems())
Python : updating values in a dictionary
I have the following dictionary -> key : (time,edge_list) Now I want to increment all time values by 1. How do I do that? dict_list = dict(key:(time+1,edge_list) for key:(time,edge_list) in dict_list)
[ ">>> d={\"key\" : (100,\"edge_list\")}\n>>> for i,(time,edge_list) in d.items():\n... d[i] = time+1, edge_list\n... \n>>> d\n{'key': (101, 'edge_list')}\n\n", "dict((key, (time + 1, edge_list)) for (key, (time, edge_list)) in somedict.iteritems())\n\n" ]
[ 9, 7 ]
[]
[]
[ "python" ]
stackoverflow_0002287061_python.txt
Q: Pylons: free module-level variables? Not even sure if module-level is correct here, but... I have a Pylons project and within the model component I have a global variable, doc, in __init__.py that I want to use from different Query objects. (doc is a Document handle on an XML file that I am using as a fake DB.) My question is, when does __init__.py's scope end? Currently I am not freeing the Document with doc.unlink() and I am not sure where to put that. The alternative design I was thinking about deals with making the consuming object (Query) have a class-level variable of this doc (i.e. make it a singleton). But it appears that the life of my Query object is such that doc always gets reallocated a new Document handle. class Query(object): doc = None def __init__(self, content=None): self.content = content if self.doc == None: self.doc = parse(os.path.join(config['app_conf']['xmldb'], "sample_search_result.xml")) I can tell because the address of the elements within the Document keep changing. Anyone want to help a noobie out? A: Objects only stop existing when 1) no references to them exist, or 2) the interpreter ends. A module/package keeps a reference to all module-level names in its private dict; deleting all references to the module in all other modules as well as in sys.modules, and all references to any objects within it will release the module. A: Have you considered putting the doc object in globals? Since it's an immutable object it shall be the perfect place to store it. Than you can reference globals from any controller and pass it to a Query object (during __init__ or explicitly when calling a method on the object) You can also try to store the doc object in the controller's session (if per session reads required)
Pylons: free module-level variables?
Not even sure if module-level is correct here, but... I have a Pylons project and within the model component I have a global variable, doc, in __init__.py that I want to use from different Query objects. (doc is a Document handle on an XML file that I am using as a fake DB.) My question is, when does __init__.py's scope end? Currently I am not freeing the Document with doc.unlink() and I am not sure where to put that. The alternative design I was thinking about deals with making the consuming object (Query) have a class-level variable of this doc (i.e. make it a singleton). But it appears that the life of my Query object is such that doc always gets reallocated a new Document handle. class Query(object): doc = None def __init__(self, content=None): self.content = content if self.doc == None: self.doc = parse(os.path.join(config['app_conf']['xmldb'], "sample_search_result.xml")) I can tell because the address of the elements within the Document keep changing. Anyone want to help a noobie out?
[ "Objects only stop existing when 1) no references to them exist, or 2) the interpreter ends. A module/package keeps a reference to all module-level names in its private dict; deleting all references to the module in all other modules as well as in sys.modules, and all references to any objects within it will release the module.\n", "Have you considered putting the doc object in globals? Since it's an immutable object it shall be the perfect place to store it. Than you can reference globals from any controller and pass it to a Query object (during __init__ or explicitly when calling a method on the object)\nYou can also try to store the doc object in the controller's session (if per session reads required)\n" ]
[ 0, 0 ]
[]
[]
[ "object", "pylons", "python", "scope", "singleton" ]
stackoverflow_0002129164_object_pylons_python_scope_singleton.txt
Q: How to do I integrate a 304 in Django? When a user requests the same page, with the same data...I'd like Django to return a 304, so that the browser doesn't have to load the page all over again. I'm new to this. How can this be done? Thanks. A: There's extensive description in Django documentation: Conditional view processing Following tools are particularly useful: @last_modified and @etag view decorators. You supply them with a function to compute the value from request and everything else is done automatically. django.middleware.http.ConditionalGetMiddleware -- it generates required ETag and returns 304 if there's a cache hit, but this still takes server time to generate full HTML and only network time is saved. Still very good for one-line configuration change. A: You could look into Django's caching system, or if you can easily check if the user is requesting the same data, you can return a HttpResponseNotModified() - this returns a 304. Check out the docs here.
How to do I integrate a 304 in Django?
When a user requests the same page, with the same data...I'd like Django to return a 304, so that the browser doesn't have to load the page all over again. I'm new to this. How can this be done? Thanks.
[ "There's extensive description in Django documentation: Conditional view processing\nFollowing tools are particularly useful:\n\n@last_modified and @etag view decorators. You supply them with a function to compute the value from request and everything else is done automatically.\ndjango.middleware.http.ConditionalGetMiddleware -- it generates required ETag and returns 304 if there's a cache hit, but this still takes server time to generate full HTML and only network time is saved. Still very good for one-line configuration change.\n\n", "You could look into Django's caching system, or if you can easily check if the user is requesting the same data, you can return a HttpResponseNotModified() - this returns a 304. Check out the docs here.\n" ]
[ 13, 6 ]
[]
[]
[ "django", "header", "http_status_code_304", "python" ]
stackoverflow_0002287387_django_header_http_status_code_304_python.txt
Q: Only connect to database when necessary I'm using Pylons + Python and am trying to figure how how to connect to our central database server only when necessary. I created a class called Central() which I would like to instantiate whenever a connection to the central database server is necessary, e.g.: class Central(): def __init__(self): engine = engine_from_config(config, 'sqlalchemy.central.') central_db = create_engine(engine) print central_db However this doesn't work when I call: c = DBConnect.Central() What is the proper code for doing this? Thanks. A: Since I can't tell what's the layout of your code, I can only assume that you've got engine and central_db defined somewhere in the global context. Is that correct? If so you could try something like this: def __init__(self): global engine global central_db engine = engine_from_config(config, 'sqlalchemy.central.') central_db = create_engine(engine) It will reference global engine and central_db objects instead of local ones (as Wim described) A: Can you define "doesn't work"? If you want to use central_db and engine later, you need to store them in the object (use self.central_db, self.engine, you can later access them as c.central_db and c.engine). Now they're just local variables which are destroyed once your constructor is finished.
Only connect to database when necessary
I'm using Pylons + Python and am trying to figure how how to connect to our central database server only when necessary. I created a class called Central() which I would like to instantiate whenever a connection to the central database server is necessary, e.g.: class Central(): def __init__(self): engine = engine_from_config(config, 'sqlalchemy.central.') central_db = create_engine(engine) print central_db However this doesn't work when I call: c = DBConnect.Central() What is the proper code for doing this? Thanks.
[ "Since I can't tell what's the layout of your code, I can only assume that you've got engine and central_db defined somewhere in the global context. Is that correct? If so you could try something like this:\ndef __init__(self):\n global engine\n global central_db\n engine = engine_from_config(config, 'sqlalchemy.central.') \n central_db = create_engine(engine)\n\nIt will reference global engine and central_db objects instead of local ones (as Wim described)\n", "Can you define \"doesn't work\"?\nIf you want to use central_db and engine later, you need to store them in the object (use self.central_db, self.engine, you can later access them as c.central_db and c.engine). Now they're just local variables which are destroyed once your constructor is finished.\n" ]
[ 1, 0 ]
[]
[]
[ "pylons", "python", "sqlalchemy" ]
stackoverflow_0002210646_pylons_python_sqlalchemy.txt
Q: Python MySQL query not completing I am having problems with a Python script which is basically just analysing a CSV file line-by-line and then inserting each line into a MySQL table using a FOR loop: f = csv.reader(open(filePath, "r")) i = 1 for line in f: if (i > skipLines): vals = nullify(line) try: cursor.execute(query, vals) except TypeError: sys.exc_clear() i += 1 return Where the query is of the form: query = ("insert into %s" % tableName) + (" values (%s)" % placeholders) This is working perfectly fine with every file it is used for with one exception - the largest file. It stops at different points each time - sometimes it reaches 600,000 records, sometimes 900,000. But there are about 4,000,000 records in total. I can't figure out why it is doing this. The table type is MyISAM. Plenty of disk space available. The table is reaching about 35MB when it stops. max_allowed_packet is set to 16MB but I don't think is a problem as it is executing line-by-line? Anyone have any ideas what this could be? Not sure whether it is Python, MySQL or the MySQLdb module that is responsible for this. Thanks in advance. A: Have you tried LOAD MySQL function? query = "LOAD DATA INFILE '/path/to/file' INTO TABLE atable FIELDS TERMINATED BY ',' ENCLOSED BY '\"' ESCAPED BY '\\\\'" cursor.execute( query ) You can always pre-process the CSV file (at least that's what I do :) Another thing worth trying would be bulk inserts. You could try to insert multiple rows with one query: INSERT INTO x (a,b) VALUES ('1', 'one'), ('2', 'two'), ('3', 'three') Oh, yeah, and you don't need to commit since it's the MyISAM engine. A: As S. Lott alluded to, aren't cursors used as handles into transactions? So at any time the db is giving you the option of rolling back all those pending inserts. You may simply have too many inserts for one transaction. Try committing the transaction every couple of thousand inserts.
Python MySQL query not completing
I am having problems with a Python script which is basically just analysing a CSV file line-by-line and then inserting each line into a MySQL table using a FOR loop: f = csv.reader(open(filePath, "r")) i = 1 for line in f: if (i > skipLines): vals = nullify(line) try: cursor.execute(query, vals) except TypeError: sys.exc_clear() i += 1 return Where the query is of the form: query = ("insert into %s" % tableName) + (" values (%s)" % placeholders) This is working perfectly fine with every file it is used for with one exception - the largest file. It stops at different points each time - sometimes it reaches 600,000 records, sometimes 900,000. But there are about 4,000,000 records in total. I can't figure out why it is doing this. The table type is MyISAM. Plenty of disk space available. The table is reaching about 35MB when it stops. max_allowed_packet is set to 16MB but I don't think is a problem as it is executing line-by-line? Anyone have any ideas what this could be? Not sure whether it is Python, MySQL or the MySQLdb module that is responsible for this. Thanks in advance.
[ "Have you tried LOAD MySQL function?\nquery = \"LOAD DATA INFILE '/path/to/file' INTO TABLE atable FIELDS TERMINATED BY ',' ENCLOSED BY '\\\"' ESCAPED BY '\\\\\\\\'\"\ncursor.execute( query )\n\nYou can always pre-process the CSV file (at least that's what I do :)\nAnother thing worth trying would be bulk inserts. You could try to insert multiple rows with one query:\nINSERT INTO x (a,b)\nVALUES \n('1', 'one'),\n('2', 'two'), \n('3', 'three')\n\nOh, yeah, and you don't need to commit since it's the MyISAM engine.\n", "As S. Lott alluded to, aren't cursors used as handles into transactions?\nSo at any time the db is giving you the option of rolling back all those pending inserts.\nYou may simply have too many inserts for one transaction. Try committing the transaction every couple of thousand inserts.\n" ]
[ 1, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0002285620_mysql_python.txt
Q: how do I filter values from XML file in python I have a basic grasp of XML and python and have been using minidom with some success. I have run into a situation where I am unable to get the values I want from an XML file. Here is the basic structure of the pre-existing file. <localization> <b n="Stats"> <l k="SomeStat1"> <v>10</v> </l> <l k="SomeStat2"> <v>6</v> </l> </b> <b n="Levels"> <l k="Level1"> <v>Beginner Level</v> </l> <l k="Level2"> <v>Intermediate Level</v> </l> </b> </localization> There are about 15 different <b> tags with dozens of children. What I'd like to do is, if given a level number(1), is find the <v> node for the corresponding level. I just have no idea how to go about this. A: You might consider using XPATH, a language for addressing parts of an xml document. Here's the answer using lxml.etree and it's support for xpath. >>> data = """ ... <localization> ... <b n="Stats"> ... <l k="SomeStat1"> ... <v>10</v> ... </l> ... <l k="SomeStat2"> ... <v>6</v> ... </l> ... </b> ... <b n="Levels"> ... <l k="Level1"> ... <v>Beginner Level</v> ... </l> ... <l k="Level2"> ... <v>Intermediate Level</v> ... </l> ... </b> ... </localization> ... """ >>> >>> from lxml import etree >>> >>> xmldata = etree.XML(data) >>> xmldata.xpath('/localization/b[@n="Levels"]/l[@k=$level]/v/text()',level='Level1') ['Beginner Level'] A: #!/usr/bin/python from xml.dom.minidom import parseString xml = parseString("""<localization> <b n="Stats"> <l k="SomeStat1"> <v>10</v> </l> <l k="SomeStat2"> <v>6</v> </l> </b> <b n="Levels"> <l k="Level1"> <v>Beginner Level</v> </l> <l k="Level2"> <v>Intermediate Level</v> </l> </b> </localization>""") level = 1 blist = xml.getElementsByTagName('b') for b in blist: if b.getAttribute('n') == 'Levels': llist = b.getElementsByTagName('l') l = llist.item(level) v = l.getElementsByTagName('v') print v.item(0).firstChild.nodeValue; #prints Intermediate Level A: If you could use BeautifulSoup library (couldn't you?) you could end up with this dead-simple code: from BeautifulSoup import BeautifulStoneSoup def get_it(xml, level_n): soup = BeautifulStoneSoup(xml) l = soup.find('l', k="Level%d" % level_n) return l.v.string if __name__ == '__main__': print get_it(1) It prints Beginner Level for the example XML you provided. A: If you really only care about searching for an <l> tag with a specific "k" attribute and then getting its <v> tag (that's how I understood your question), you could do it with DOM: from xml.dom.minidom import parseString xmlDoc = parseString("""<document goes here>""") lNodesWithLevel2 = [lNode for lNode in xmlDoc.getElementsByTagName("l") if lNode.getAttribute("k") == "Level2"] matchingVNodes = map(lambda lNode: lNode.getElementsByTagName("v"), lNodesWithLevel2) print map(lambda vNode: vNode.firstChild.nodeValue, matchingVNodes) # Prints [u'Intermediate Level'] How that is what you meant. A: level = "Level"+raw_input("Enter level number: ") content= open("xmlfile").read() data= content.split("</localization>") for item in data: if "localization" in item: s = item.split("</b>") for i in s: if """<b n="Levels">""" in i: for c in i.split("</l>"): if "<l" in c and level in c: for v in c.split("</v>"): if "<v>" in v: print v[v.index("<v>")+3:]
how do I filter values from XML file in python
I have a basic grasp of XML and python and have been using minidom with some success. I have run into a situation where I am unable to get the values I want from an XML file. Here is the basic structure of the pre-existing file. <localization> <b n="Stats"> <l k="SomeStat1"> <v>10</v> </l> <l k="SomeStat2"> <v>6</v> </l> </b> <b n="Levels"> <l k="Level1"> <v>Beginner Level</v> </l> <l k="Level2"> <v>Intermediate Level</v> </l> </b> </localization> There are about 15 different <b> tags with dozens of children. What I'd like to do is, if given a level number(1), is find the <v> node for the corresponding level. I just have no idea how to go about this.
[ "You might consider using XPATH, a language for addressing parts of an xml document.\nHere's the answer using lxml.etree and it's support for xpath.\n>>> data = \"\"\"\n... <localization>\n... <b n=\"Stats\">\n... <l k=\"SomeStat1\">\n... <v>10</v>\n... </l>\n... <l k=\"SomeStat2\">\n... <v>6</v>\n... </l>\n... </b>\n... <b n=\"Levels\">\n... <l k=\"Level1\">\n... <v>Beginner Level</v>\n... </l>\n... <l k=\"Level2\">\n... <v>Intermediate Level</v>\n... </l>\n... </b>\n... </localization>\n... \"\"\"\n>>>\n>>> from lxml import etree\n>>>\n>>> xmldata = etree.XML(data)\n>>> xmldata.xpath('/localization/b[@n=\"Levels\"]/l[@k=$level]/v/text()',level='Level1')\n['Beginner Level']\n\n", "#!/usr/bin/python\n\nfrom xml.dom.minidom import parseString\n\nxml = parseString(\"\"\"<localization>\n <b n=\"Stats\">\n <l k=\"SomeStat1\">\n <v>10</v>\n </l>\n <l k=\"SomeStat2\">\n <v>6</v>\n </l>\n </b>\n <b n=\"Levels\">\n <l k=\"Level1\">\n <v>Beginner Level</v>\n </l>\n <l k=\"Level2\">\n <v>Intermediate Level</v>\n </l>\n </b>\n</localization>\"\"\")\n\nlevel = 1\nblist = xml.getElementsByTagName('b')\nfor b in blist:\n if b.getAttribute('n') == 'Levels':\n llist = b.getElementsByTagName('l')\n l = llist.item(level)\n v = l.getElementsByTagName('v')\n print v.item(0).firstChild.nodeValue;\n #prints Intermediate Level\n\n", "If you could use BeautifulSoup library (couldn't you?) you could end up with this dead-simple code:\nfrom BeautifulSoup import BeautifulStoneSoup\n\ndef get_it(xml, level_n):\n soup = BeautifulStoneSoup(xml)\n l = soup.find('l', k=\"Level%d\" % level_n)\n return l.v.string\n\nif __name__ == '__main__':\n print get_it(1)\n\nIt prints Beginner Level for the example XML you provided.\n", "If you really only care about searching for an <l> tag with a specific \"k\" attribute and then getting its <v> tag (that's how I understood your question), you could do it with DOM:\nfrom xml.dom.minidom import parseString\n\nxmlDoc = parseString(\"\"\"<document goes here>\"\"\")\nlNodesWithLevel2 = [lNode for lNode in xmlDoc.getElementsByTagName(\"l\")\n if lNode.getAttribute(\"k\") == \"Level2\"]\n\nmatchingVNodes = map(lambda lNode: lNode.getElementsByTagName(\"v\"), lNodesWithLevel2)\n\nprint map(lambda vNode: vNode.firstChild.nodeValue, matchingVNodes)\n# Prints [u'Intermediate Level']\n\nHow that is what you meant.\n", "level = \"Level\"+raw_input(\"Enter level number: \")\ncontent= open(\"xmlfile\").read()\ndata= content.split(\"</localization>\")\nfor item in data:\n if \"localization\" in item:\n s = item.split(\"</b>\")\n for i in s:\n if \"\"\"<b n=\"Levels\">\"\"\" in i:\n for c in i.split(\"</l>\"):\n if \"<l\" in c and level in c:\n for v in c.split(\"</v>\"):\n if \"<v>\" in v:\n print v[v.index(\"<v>\")+3:]\n\n" ]
[ 4, 2, 2, 1, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0002286633_python_xml.txt
Q: Python & parsing IRC messages What's the best way to parse messages received from an IRC server with Python according to the RFC? I simply want some kind of list/whatever, for example: :test!~test@test.com PRIVMSG #channel :Hi! becomes this: { "sender" : "test!~test@test.com", "target" : "#channel", "message" : "Hi!" } And so on? (Edit: I want to parse IRC messages in general, not just PRIVMSG's) A: Look at Twisted's implementation http://twistedmatrix.com/ Unfortunately I'm out of time, maybe someone else can paste it here for you. Edit Well I'm back, and strangely no one has pasted it yet so here it is: http://twistedmatrix.com/trac/browser/trunk/twisted/words/protocols/irc.py#54 def parsemsg(s): """Breaks a message from an IRC server into its prefix, command, and arguments. """ prefix = '' trailing = [] if not s: raise IRCBadMessage("Empty line.") if s[0] == ':': prefix, s = s[1:].split(' ', 1) if s.find(' :') != -1: s, trailing = s.split(' :', 1) args = s.split() args.append(trailing) else: args = s.split() command = args.pop(0) return prefix, command, args parsemsg(":test!~test@test.com PRIVMSG #channel :Hi!") # ('test!~test@test.com', 'PRIVMSG', ['#channel', 'Hi!']) This function closely follows the EBNF described in the IRC RFC. A: You can do it with a simple list comprehension if the format is always like this. keys = ['sender', 'type', 'target', 'message'] s = ":test!~test@test.com PRIVMSG #channel :Hi!" dict((key, value.lstrip(':')) for key, value in zip(keys, s.split())) Result: {'message': 'Hi!', 'type': 'PRIVMSG', 'sender': 'test!~test@test.com', 'target': '#channel'} A: Do you just want to parse IRC Messages in general or do you want just parse PRIVMSGs? However I have a implementation for that. def parse_message(s): prefix = '' trailing = '' if s.startswith(':'): prefix, s = s[1:].split(' ', 1) if ' :' in s: s, trailing = s.split(' :', 1) args = s.split() return prefix, args.pop(0), args, trailing A: If you want to keep to a low-level hacking I second the Twisted answer by Unknown, but first I think you should take a look at the very recently announced Yardbird which is a nice request parsing layer on top of Twisted. It lets you use something similar to Django URL dispatching for handling IRC messages with a side benefit of having the Django ORM available for generating responses, etc. A: I know it's not Python, but for a regular expression-based approach to this problem, you could take a look at POE::Filter::IRCD, which handles IRC server protocol (see POE::Filter::IRC::Compat for the client protocol additions) parsing for Perl's POE::Component::IRC framework.
Python & parsing IRC messages
What's the best way to parse messages received from an IRC server with Python according to the RFC? I simply want some kind of list/whatever, for example: :test!~test@test.com PRIVMSG #channel :Hi! becomes this: { "sender" : "test!~test@test.com", "target" : "#channel", "message" : "Hi!" } And so on? (Edit: I want to parse IRC messages in general, not just PRIVMSG's)
[ "Look at Twisted's implementation http://twistedmatrix.com/\nUnfortunately I'm out of time, maybe someone else can paste it here for you.\nEdit\nWell I'm back, and strangely no one has pasted it yet so here it is:\nhttp://twistedmatrix.com/trac/browser/trunk/twisted/words/protocols/irc.py#54\ndef parsemsg(s):\n \"\"\"Breaks a message from an IRC server into its prefix, command, and arguments.\n \"\"\"\n prefix = ''\n trailing = []\n if not s:\n raise IRCBadMessage(\"Empty line.\")\n if s[0] == ':':\n prefix, s = s[1:].split(' ', 1)\n if s.find(' :') != -1:\n s, trailing = s.split(' :', 1)\n args = s.split()\n args.append(trailing)\n else:\n args = s.split()\n command = args.pop(0)\n return prefix, command, args\n\nparsemsg(\":test!~test@test.com PRIVMSG #channel :Hi!\")\n# ('test!~test@test.com', 'PRIVMSG', ['#channel', 'Hi!']) \n\nThis function closely follows the EBNF described in the IRC RFC.\n", "You can do it with a simple list comprehension if the format is always like this.\nkeys = ['sender', 'type', 'target', 'message']\ns = \":test!~test@test.com PRIVMSG #channel :Hi!\"\ndict((key, value.lstrip(':')) for key, value in zip(keys, s.split()))\n\nResult:\n{'message': 'Hi!', 'type': 'PRIVMSG', 'sender': 'test!~test@test.com', 'target': '#channel'}\n\n", "Do you just want to parse IRC Messages in general or do you want just parse PRIVMSGs? However I have a implementation for that.\ndef parse_message(s):\n prefix = ''\n trailing = ''\n if s.startswith(':'):\n prefix, s = s[1:].split(' ', 1)\n if ' :' in s:\n s, trailing = s.split(' :', 1)\n args = s.split()\n return prefix, args.pop(0), args, trailing\n\n", "If you want to keep to a low-level hacking I second the Twisted answer by Unknown, but first I think you should take a look at the very recently announced Yardbird which is a nice request parsing layer on top of Twisted. It lets you use something similar to Django URL dispatching for handling IRC messages with a side benefit of having the Django ORM available for generating responses, etc.\n", "I know it's not Python, but for a regular expression-based approach to this problem, you could take a look at POE::Filter::IRCD, which handles IRC server protocol (see POE::Filter::IRC::Compat for the client protocol additions) parsing for Perl's POE::Component::IRC framework.\n" ]
[ 22, 1, 0, 0, 0 ]
[]
[]
[ "irc", "parsing", "python" ]
stackoverflow_0000930700_irc_parsing_python.txt
Q: What are some good ways to do connection management in C? In C, when making a networking client / server setup, I usually have to do some standard BSD socket setup. Then on the server side, I'll have to manage multiple threads, usually a main thread, an a io thread. Each connection is managed by a connection manager so that you can have connections being processed while new requests are coming in. What are some good ways to do connection management in C? Are there well know libraries to handle all of this? I know about Boost for C++, but I'm interested in C and Python. Thanks, Chenz P.S. Sorry about the not so thought out question. I'll try and polish it up soon. A: Personally, I am not a huge fan of the one-thread-per-connection model with synchronous IO. I prefer X threads with a pool of Y connections with asynchronous IO. You can spawn threads as needed, or round robin the connections as they come in to a pre-allocated pool. If you want to be really tricky, spawn threads with lifetime management, where new connections go to the newest spawned thread so the old thread can be killed off. That way if a thread holds on to a resource, when it is cleaned up the resource will be released. You may want to look at select, poll, epoll, completion pools and AIO. Most of these are wrapped up in libevent.
What are some good ways to do connection management in C?
In C, when making a networking client / server setup, I usually have to do some standard BSD socket setup. Then on the server side, I'll have to manage multiple threads, usually a main thread, an a io thread. Each connection is managed by a connection manager so that you can have connections being processed while new requests are coming in. What are some good ways to do connection management in C? Are there well know libraries to handle all of this? I know about Boost for C++, but I'm interested in C and Python. Thanks, Chenz P.S. Sorry about the not so thought out question. I'll try and polish it up soon.
[ "Personally, I am not a huge fan of the one-thread-per-connection model with synchronous IO. I prefer X threads with a pool of Y connections with asynchronous IO. You can spawn threads as needed, or round robin the connections as they come in to a pre-allocated pool.\nIf you want to be really tricky, spawn threads with lifetime management, where new connections go to the newest spawned thread so the old thread can be killed off. That way if a thread holds on to a resource, when it is cleaned up the resource will be released.\nYou may want to look at select, poll, epoll, completion pools and AIO.\nMost of these are wrapped up in libevent.\n" ]
[ 2 ]
[]
[]
[ "c", "connection_pooling", "python", "service", "sockets" ]
stackoverflow_0002288131_c_connection_pooling_python_service_sockets.txt
Q: Enumerate CD-Drives using Python (Windows) How can I find out the drive letters of available CD/DVD drives? I am using Python 2.5.4 on Windows. A: Using win32api you can get list of drives and using GetDriveType you can check what type of drive it is, you can access win32api either by 'Python for Windows Extensions' or ctypes module Here is an example using ctypes: import string from ctypes import windll driveTypes = ['DRIVE_UNKNOWN', 'DRIVE_NO_ROOT_DIR', 'DRIVE_REMOVABLE', 'DRIVE_FIXED', 'DRIVE_REMOTE', 'DRIVE_CDROM', 'DRIVE_RAMDISK'] def get_drives(): drives = [] bitmask = windll.kernel32.GetLogicalDrives() for letter in string.uppercase: if bitmask & 1: drives.append(letter) bitmask >>= 1 return drives for drive in get_drives(): if not drive: continue print "Drive:", drive try: typeIndex = windll.kernel32.GetDriveTypeW(u"%s:\\"%drive) print "Type:",driveTypes[typeIndex] except Exception,e: print "error:",e This outputs: Drive: C Type: DRIVE_FIXED Drive: D Type: DRIVE_FIXED Drive: E Type: DRIVE_CDROM A: With the Python for Windows extensions, you can use: [drive for drive in win32api.GetLogicalDriveStrings().split('\x00')[:-1] if win32file.GetDriveType(drive)==win32file.DRIVE_CDROM] Adapted from this post. This will give you the drive letters even if there is no CD/DVD in the drive. A: If you use the WMI Module, it's very easy: import wmi c = wmi.WMI() for cdrom in c.Win32_CDROMDrive(): print cdrom.Drive, cdrom.MediaLoaded The Drive attribute will give you the drive letter and MediaLoaded will tell you if there's something in the drive. In case you didn't know, WMI standards for Windows Management Instrumentation and is an API that allows you to query management information about a system. (For what it's worth, WMI is the Windows implementation of the Common Information Model standard.) The Python WMI Module gives you easy access to the Windows WMI calls. In the code above we query the Win32_CDROMDrive WMI Class to find out about the CD ROM drives on the system. This gives us a list of objects with a huge number of attributes which tells us everything we could ever want to know about the CD Drives. We check the drive letter and media state, since that's all we care about right now. A: Use GetDriveType Function from win32file module. Sample code: import win32file for d in ('C', 'D', 'E', 'F', 'G'): dname='%c:\\' % (d) dt=win32file.GetDriveType(dname) if dt == win32file.DRIVE_CDROM: print('%s is CD ROM' % (dname)) A: you can use WMI, see this cookbook for an example
Enumerate CD-Drives using Python (Windows)
How can I find out the drive letters of available CD/DVD drives? I am using Python 2.5.4 on Windows.
[ "Using win32api you can get list of drives and using GetDriveType\nyou can check what type of drive it is, you can access win32api either by 'Python for Windows Extensions' or ctypes module\nHere is an example using ctypes:\nimport string\nfrom ctypes import windll\n\ndriveTypes = ['DRIVE_UNKNOWN', 'DRIVE_NO_ROOT_DIR', 'DRIVE_REMOVABLE', 'DRIVE_FIXED', 'DRIVE_REMOTE', 'DRIVE_CDROM', 'DRIVE_RAMDISK']\n\ndef get_drives():\n drives = []\n bitmask = windll.kernel32.GetLogicalDrives()\n for letter in string.uppercase:\n if bitmask & 1:\n drives.append(letter)\n bitmask >>= 1\n\n return drives\n\nfor drive in get_drives():\n if not drive: continue\n print \"Drive:\", drive\n try:\n typeIndex = windll.kernel32.GetDriveTypeW(u\"%s:\\\\\"%drive)\n print \"Type:\",driveTypes[typeIndex]\n except Exception,e:\n print \"error:\",e\n\nThis outputs:\nDrive: C\nType: DRIVE_FIXED\nDrive: D\nType: DRIVE_FIXED\nDrive: E\nType: DRIVE_CDROM\n\n", "With the Python for Windows extensions, you can use:\n[drive for drive in win32api.GetLogicalDriveStrings().split('\\x00')[:-1] \n if win32file.GetDriveType(drive)==win32file.DRIVE_CDROM]\n\nAdapted from this post.\nThis will give you the drive letters even if there is no CD/DVD in the drive.\n", "If you use the WMI Module, it's very easy:\nimport wmi\nc = wmi.WMI()\nfor cdrom in c.Win32_CDROMDrive():\n print cdrom.Drive, cdrom.MediaLoaded\n\nThe Drive attribute will give you the drive letter and MediaLoaded will tell you if there's something in the drive. \nIn case you didn't know, WMI standards for Windows Management Instrumentation and is an API that allows you to query management information about a system. (For what it's worth, WMI is the Windows implementation of the Common Information Model standard.) The Python WMI Module gives you easy access to the Windows WMI calls.\nIn the code above we query the Win32_CDROMDrive WMI Class to find out about the CD ROM drives on the system. This gives us a list of objects with a huge number of attributes which tells us everything we could ever want to know about the CD Drives. We check the drive letter and media state, since that's all we care about right now.\n", "Use GetDriveType Function from win32file module.\nSample code:\nimport win32file\nfor d in ('C', 'D', 'E', 'F', 'G'):\n dname='%c:\\\\' % (d)\n dt=win32file.GetDriveType(dname)\n if dt == win32file.DRIVE_CDROM:\n print('%s is CD ROM' % (dname))\n\n", "you can use WMI, see this cookbook for an example\n" ]
[ 10, 2, 2, 2, 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0002288065_python_windows.txt
Q: python: two way partial credit card storing encrytion For my ecommece site, I want to store partial credit card numbers as string, for this I need to encrypt the information to store at the database and decrypt when users want to reuse the already entered credit card info from earlier purchases without typing it all over again. I am using Django thus I need to solve this via Python. What would be the clever algorithm to solve this issue ? A: Before you go much further you should take a look at PCI-DSS, which governs exactly what processes you need to have in place to even consider storing encrypted card numbers. In short, you should seriously consider outsourcing to a 3rd party payment gateway. If once you've understood the consequences you do want to go ahead, then again - follow the PCI guidelines. For symmetric encryption of card numbers you probably want to use AES, and draw up very strict key management policies. If however you only want to store a partial card number, then PCI states you can store (at an absolute maximum) the first six and last four digits only. The first six digits are all you need to identify a card type. The last four digits you may deem necessary to help prevent issues where a customer has near identical card numbers. IMHO storing partial card numbers (in plain text) is what you want to do, and then outsource the handling of encryption, authorisation and settlement to a 3rd party gateway. The payment gateway will give you a unique token id for each card you pass to them, so that you can reference a unique card to perform re-authorisation or refunds etc. A: Are you absolutely sure you want to hash sensitive information like this? It might be worth reading this article to get an idea of some of the pitfalls trying to store any sensitive information in a database. In your case it's even worse because you want the transformation to be reversible. Just remember, if you can reverse it, so can an attacker. Think carefully before you embark on this course... Perhaps you might be better of outsourcing this kind of work to someone who specializes in it (such as Paypal or Google Checkout etc).
python: two way partial credit card storing encrytion
For my ecommece site, I want to store partial credit card numbers as string, for this I need to encrypt the information to store at the database and decrypt when users want to reuse the already entered credit card info from earlier purchases without typing it all over again. I am using Django thus I need to solve this via Python. What would be the clever algorithm to solve this issue ?
[ "Before you go much further you should take a look at PCI-DSS, which governs exactly what processes you need to have in place to even consider storing encrypted card numbers. In short, you should seriously consider outsourcing to a 3rd party payment gateway.\nIf once you've understood the consequences you do want to go ahead, then again - follow the PCI guidelines. For symmetric encryption of card numbers you probably want to use AES, and draw up very strict key management policies.\nIf however you only want to store a partial card number, then PCI states you can store (at an absolute maximum) the first six and last four digits only. The first six digits are all you need to identify a card type. The last four digits you may deem necessary to help prevent issues where a customer has near identical card numbers.\nIMHO storing partial card numbers (in plain text) is what you want to do, and then outsource the handling of encryption, authorisation and settlement to a 3rd party gateway. The payment gateway will give you a unique token id for each card you pass to them, so that you can reference a unique card to perform re-authorisation or refunds etc.\n", "Are you absolutely sure you want to hash sensitive information like this? It might be worth reading this article to get an idea of some of the pitfalls trying to store any sensitive information in a database. In your case it's even worse because you want the transformation to be reversible. Just remember, if you can reverse it, so can an attacker.\nThink carefully before you embark on this course...\nPerhaps you might be better of outsourcing this kind of work to someone who specializes in it (such as Paypal or Google Checkout etc).\n" ]
[ 16, 2 ]
[]
[]
[ "credit_card", "django", "encryption", "python" ]
stackoverflow_0002288448_credit_card_django_encryption_python.txt
Q: Install python egg in buildout environment including data files This question assumes that the python package I want to install is a django app that includes templates and media files. But the question is valid for any python package that does not only contain .py files. I'm using buildout to create a re-buildable environment in which I'm developing a django project. My buildout.cfg looks like that: [buildout] parts = python eggs = normal-python-package python-package-with-data-files find-files = http://domain-to-python-package-with-data-files [python] recipe = zc.recipe.egg interpreter = python eggs = ${buildout:eggs} (and some django related stuff). The python-package-with-data-files is available through a link on the page http://domain-to-python-package-with-data-files. The eggs normal-python-package and python-package-with-data-files are installed successfully in the eggs/ directory. Because python-package-with-data-files has set zip_safe to False in its setup.py file it is available unzipped in eggs/. Only the non .py files of python-package-with-data-files are not available in the unzipped egg in eggs/ (they are included in the .tar.gz package available at http://domain-to-python-package-with-data-files). How do I get these data files to be included in the egg? Do I need to change the setup.py file of the package? Or is it buildout related? The things I found out are the following: If I make a python setup.py sdist in python-package-with-data-files root directory, all data files are included in the created .tar.gz file. But if I make a python setup.py bdist it results in a build without including the data files. This makes me think that the problem is not buildout specific. But maybe there is a way to tell buildout not to make a bdist but a sdist to create the egg and install the package into the project. What shall I do? I am the maintainer of python-package-with-data-files, so I can change setup.py if necessary. A: It sounds like you need to make use of the package_data keyword argument in your setup.py file, so distutils knows those files should be installed with your package.
Install python egg in buildout environment including data files
This question assumes that the python package I want to install is a django app that includes templates and media files. But the question is valid for any python package that does not only contain .py files. I'm using buildout to create a re-buildable environment in which I'm developing a django project. My buildout.cfg looks like that: [buildout] parts = python eggs = normal-python-package python-package-with-data-files find-files = http://domain-to-python-package-with-data-files [python] recipe = zc.recipe.egg interpreter = python eggs = ${buildout:eggs} (and some django related stuff). The python-package-with-data-files is available through a link on the page http://domain-to-python-package-with-data-files. The eggs normal-python-package and python-package-with-data-files are installed successfully in the eggs/ directory. Because python-package-with-data-files has set zip_safe to False in its setup.py file it is available unzipped in eggs/. Only the non .py files of python-package-with-data-files are not available in the unzipped egg in eggs/ (they are included in the .tar.gz package available at http://domain-to-python-package-with-data-files). How do I get these data files to be included in the egg? Do I need to change the setup.py file of the package? Or is it buildout related? The things I found out are the following: If I make a python setup.py sdist in python-package-with-data-files root directory, all data files are included in the created .tar.gz file. But if I make a python setup.py bdist it results in a build without including the data files. This makes me think that the problem is not buildout specific. But maybe there is a way to tell buildout not to make a bdist but a sdist to create the egg and install the package into the project. What shall I do? I am the maintainer of python-package-with-data-files, so I can change setup.py if necessary.
[ "It sounds like you need to make use of the package_data keyword argument in your setup.py file, so distutils knows those files should be installed with your package.\n" ]
[ 3 ]
[]
[]
[ "buildout", "django", "egg", "python" ]
stackoverflow_0002288533_buildout_django_egg_python.txt
Q: What's wrong in this caching function in Django? I've created the model for counting the number of views of my page: class RequestCounter(models.Model): count = models.IntegerField(default=0) def __unicode__(self): return str(self.count) For incrementing the counter I use: def inc_counter(): counter = RequestCounter.objects.get_or_create(id =1)[0] counter.count = F('count') + 1 counter.save() Then I show the number of the page views on my page and it works fine. But now I need to cache my counter for some time. I use: def get_view_count(): view_count = cache.get('v_count') if view_count==None: cache.set('v_count',RequestCounter.objects.filter(id = 1)[0],15) view_count = cache.get('v_count') return view_count After this I'm passing the result of get_view_count to my template. So I expect, that my counter would now stand still for 15 sec and then change to a new value. But, actually, it isn't quite so: when I'm testing this from my virtual ubuntu it jumps, for example, from 55 to 56, after 15 secs it changes and now jumps from 87 to 88. The values are always alternating and they don't differ much from each other. If I'm trying this locally from windows, the counter seems to be fine, until I try to open more than browser. Got no idea what to do with it. Do you see what can be the problem? p.s. i tried using caching in the templates - and received the same result. A: What CACHE_BACKEND are you using? If it's locmem:// and you're running Apache, you'll have a different cache active for each Apache child, which would explain the differing results. I had this a while ago and it was a subtle one to work out. I'd recommend switching to memcache if you're not already on it, as this won't give you the multiple-caches problem
What's wrong in this caching function in Django?
I've created the model for counting the number of views of my page: class RequestCounter(models.Model): count = models.IntegerField(default=0) def __unicode__(self): return str(self.count) For incrementing the counter I use: def inc_counter(): counter = RequestCounter.objects.get_or_create(id =1)[0] counter.count = F('count') + 1 counter.save() Then I show the number of the page views on my page and it works fine. But now I need to cache my counter for some time. I use: def get_view_count(): view_count = cache.get('v_count') if view_count==None: cache.set('v_count',RequestCounter.objects.filter(id = 1)[0],15) view_count = cache.get('v_count') return view_count After this I'm passing the result of get_view_count to my template. So I expect, that my counter would now stand still for 15 sec and then change to a new value. But, actually, it isn't quite so: when I'm testing this from my virtual ubuntu it jumps, for example, from 55 to 56, after 15 secs it changes and now jumps from 87 to 88. The values are always alternating and they don't differ much from each other. If I'm trying this locally from windows, the counter seems to be fine, until I try to open more than browser. Got no idea what to do with it. Do you see what can be the problem? p.s. i tried using caching in the templates - and received the same result.
[ "What CACHE_BACKEND are you using? If it's locmem:// and you're running Apache, you'll have a different cache active for each Apache child, which would explain the differing results. I had this a while ago and it was a subtle one to work out. I'd recommend switching to memcache if you're not already on it, as this won't give you the multiple-caches problem\n" ]
[ 4 ]
[]
[]
[ "caching", "django", "python" ]
stackoverflow_0002288720_caching_django_python.txt
Q: Problem with running Django 1.1.1 on Google App Engine Developement Server I've downloaded google_appengine version 1.3.1. Using some web tutorials, I've created basic django 1.1.1 application. Using appcfg I managed to deploy it on GAE and it works. The problem is, that application doesn't want to work on dev_appengine.py developement server. Whenever I run the app GAE local server is returning HTTP 200 without any content. If I set basic environement and run main.py manually, then the page is properly returned on stdout. I've also created very basic helloworld application, and this one is working ok on the devel server. Do you have any idea, how can I debug the devel server? Option -d doesn't give any usefull insight at all. A: I had module nammed same way as the default GAE launcher (main/ and main.py). After renaming the launcher everything works great.
Problem with running Django 1.1.1 on Google App Engine Developement Server
I've downloaded google_appengine version 1.3.1. Using some web tutorials, I've created basic django 1.1.1 application. Using appcfg I managed to deploy it on GAE and it works. The problem is, that application doesn't want to work on dev_appengine.py developement server. Whenever I run the app GAE local server is returning HTTP 200 without any content. If I set basic environement and run main.py manually, then the page is properly returned on stdout. I've also created very basic helloworld application, and this one is working ok on the devel server. Do you have any idea, how can I debug the devel server? Option -d doesn't give any usefull insight at all.
[ "I had module nammed same way as the default GAE launcher (main/ and main.py). After renaming the launcher everything works great.\n" ]
[ 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0002288725_django_google_app_engine_python.txt
Q: Wrong results with Python multiply() and prod() Can anyone explain the following? I'm using Python 2.5 Consider 1*3*5*7*9*11 ... *49. If you type all that from within IPython(x,y) interactive console, you'll get 58435841445947272053455474390625L, which is correct. (why odd numbers: just the way I did it originally) Python multiply.reduce() or prod() should yield the same result for the equivalent range. And it does, up to a certain point. Here, it is already wrong: : k = range(1, 50, 2) : multiply.reduce(k) : -108792223 Using prod(k) will also generate -108792223 as the result. Other incorrect results start to appear for equivalent ranges of length 12 (that is, k = range(1,24,2)). I'm not sure why. Can anyone help? A: This is because numpy.multiply.reduce() converts the range list to an array of type numpy.int32, and the reduce operation overflows what can be stored in 32 bits at some point: >>> type(numpy.multiply.reduce(range(1, 50, 2))) <type 'numpy.int32'> As Mike Graham says, you can use the dtype parameter to use Python integers instead of the default: >>> res = numpy.multiply.reduce(range(1, 50, 2), dtype=object) >>> res 58435841445947272053455474390625L >>> type(res) <type 'long'> But using numpy to work with python objects is pointless in this case, the best solution is KennyTM's: >>> import functools, operator >>> functools.reduce(operator.mul, range(1, 50, 2)) 58435841445947272053455474390625L A: The CPU doesn't multiply arbitrarily large numbers, it only performs specific operations defined on particular ranges of numbers represented in base 2, 0-1 bits. Python '*' handles large integers perfectly through a proper representation and special code beyond the CPU or FPU instructions for multiply. This is actually unusual as languages go. In most other languages, usually a number is represented as a fixed array of bits. For example in C or SQL you could choose to have an 8 bit integer that can represent 0 to 255, or -128 to +127 or you could choose to have a 16 bit integer that can represent up to 2^16-1 which is 65535. When there is only a range of numbers that can be represented, going past the limit with some operation like * or + can have an undesirable effect, like getting a negative number. You may have encountered such a problem when using the external library which is probably natively C and not python.
Wrong results with Python multiply() and prod()
Can anyone explain the following? I'm using Python 2.5 Consider 1*3*5*7*9*11 ... *49. If you type all that from within IPython(x,y) interactive console, you'll get 58435841445947272053455474390625L, which is correct. (why odd numbers: just the way I did it originally) Python multiply.reduce() or prod() should yield the same result for the equivalent range. And it does, up to a certain point. Here, it is already wrong: : k = range(1, 50, 2) : multiply.reduce(k) : -108792223 Using prod(k) will also generate -108792223 as the result. Other incorrect results start to appear for equivalent ranges of length 12 (that is, k = range(1,24,2)). I'm not sure why. Can anyone help?
[ "This is because numpy.multiply.reduce() converts the range list to an array of type numpy.int32, and the reduce operation overflows what can be stored in 32 bits at some point:\n>>> type(numpy.multiply.reduce(range(1, 50, 2)))\n<type 'numpy.int32'>\n\nAs Mike Graham says, you can use the dtype parameter to use Python integers instead of the default:\n>>> res = numpy.multiply.reduce(range(1, 50, 2), dtype=object)\n>>> res\n58435841445947272053455474390625L\n>>> type(res)\n<type 'long'>\n\nBut using numpy to work with python objects is pointless in this case, the best solution is KennyTM's: \n>>> import functools, operator\n>>> functools.reduce(operator.mul, range(1, 50, 2))\n58435841445947272053455474390625L\n\n", "The CPU doesn't multiply arbitrarily large numbers, it only performs specific operations defined on particular ranges of numbers represented in base 2, 0-1 bits. \nPython '*' handles large integers perfectly through a proper representation and special code beyond the CPU or FPU instructions for multiply. \nThis is actually unusual as languages go. \nIn most other languages, usually a number is represented as a fixed array of bits. For example in C or SQL you could choose to have an 8 bit integer that can represent 0 to 255, or -128 to +127 or you could choose to have a 16 bit integer that can represent up to 2^16-1 which is 65535. When there is only a range of numbers that can be represented, going past the limit with some operation like * or + can have an undesirable effect, like getting a negative number. You may have encountered such a problem when using the external library which is probably natively C and not python.\n" ]
[ 6, 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0002288952_numpy_python.txt
Q: displaying a large amount of formatted text in Python I have two large identical-sized files. One is ASCII plain text, and the other is a colour-coded overlay, one byte per text character in the corresponding file. These files can be large - upto 2.5 MB; possibly substantially more, perhaps over 100MB later. I want to display the text is a scrollable text viewer, using the second file as the overlay. Looking something like this: Tkinter Text window with tagged text for colours http://img713.imageshack.us/img713/2584/statsviewer01d.png So I made a simple tkinter Text widget window in Python with scrollbar and such. My code looks like this: hottest = 0 for heat in heatmap: hottest = max(hottest,ord(heat)) hottest += 1 for heat in xrange(0,hottest): factor = int((float(heat)/float(hottest))*100.0) # an observation; tkinter seems to normalise custom colours # to nearest in it's palette, which means I can't use custom # gradients of red; if anyone knows how to use subtle custom colours? bgcolour = "gray%d" % (100-factor) fgcolour = "gray%d" % factor text.tag_config("n%d"%heat,background=bgcolour,foreground=fgcolour) text.insert("1.0",f.read()) ofs = 0 for heat in heatmap: if 0 != ord(heat): coord_start = "1.0 + %d chars"%ofs coord_stop = "1.0 + %d chars"%(ofs+1) text.tag_add("n%d"%ord(heat),coord_start,coord_stop) ofs += 1 text.config(state=DISABLED) text.focus() However, I run into horrid performance problems: loading the text if I simply use textwidget.text = textfile.read() it loads instantly, even for the large file; but then the problem is colour-coding it. (see code above). To add the tags, one character at a time, it seems I force it to take a painter algorithm; by the time the file is about 300KB in size, I give up waiting for it to load if I read the next character from the textfile and the colourfile, and append a properly tagged character, it takes forever; a file bigger than about 200KB and I give up waiting for it to load Scrolling. If this much formatting visible in the current window, it goes very slowly If I was approaching this problem in, say, Dephi or wxWidgets or whatever, I'd have a custom-drawn control. What's the most straightforward way in Python and Tkinter? A: How about using a scrollable canvas instead, and only ever drawing the text/heatmap that is exposed by the user? That should give you a quick initial draw and a quick redraw when things move around, regardless of the size of the file. If you want more speed and more control, then you would need some sort of virtual canvas where only the area on display and an area around it actually exists, anything else is only drawn as and when it gets referenced. I don't think TkInter gives you that much control, although things like the Widget Construction Kit (WCK) should do.
displaying a large amount of formatted text in Python
I have two large identical-sized files. One is ASCII plain text, and the other is a colour-coded overlay, one byte per text character in the corresponding file. These files can be large - upto 2.5 MB; possibly substantially more, perhaps over 100MB later. I want to display the text is a scrollable text viewer, using the second file as the overlay. Looking something like this: Tkinter Text window with tagged text for colours http://img713.imageshack.us/img713/2584/statsviewer01d.png So I made a simple tkinter Text widget window in Python with scrollbar and such. My code looks like this: hottest = 0 for heat in heatmap: hottest = max(hottest,ord(heat)) hottest += 1 for heat in xrange(0,hottest): factor = int((float(heat)/float(hottest))*100.0) # an observation; tkinter seems to normalise custom colours # to nearest in it's palette, which means I can't use custom # gradients of red; if anyone knows how to use subtle custom colours? bgcolour = "gray%d" % (100-factor) fgcolour = "gray%d" % factor text.tag_config("n%d"%heat,background=bgcolour,foreground=fgcolour) text.insert("1.0",f.read()) ofs = 0 for heat in heatmap: if 0 != ord(heat): coord_start = "1.0 + %d chars"%ofs coord_stop = "1.0 + %d chars"%(ofs+1) text.tag_add("n%d"%ord(heat),coord_start,coord_stop) ofs += 1 text.config(state=DISABLED) text.focus() However, I run into horrid performance problems: loading the text if I simply use textwidget.text = textfile.read() it loads instantly, even for the large file; but then the problem is colour-coding it. (see code above). To add the tags, one character at a time, it seems I force it to take a painter algorithm; by the time the file is about 300KB in size, I give up waiting for it to load if I read the next character from the textfile and the colourfile, and append a properly tagged character, it takes forever; a file bigger than about 200KB and I give up waiting for it to load Scrolling. If this much formatting visible in the current window, it goes very slowly If I was approaching this problem in, say, Dephi or wxWidgets or whatever, I'd have a custom-drawn control. What's the most straightforward way in Python and Tkinter?
[ "How about using a scrollable canvas instead, and only ever drawing the text/heatmap that is exposed by the user? That should give you a quick initial draw and a quick redraw when things move around, regardless of the size of the file.\nIf you want more speed and more control, then you would need some sort of virtual canvas where only the area on display and an area around it actually exists, anything else is only drawn as and when it gets referenced. I don't think TkInter gives you that much control, although things like the Widget Construction Kit (WCK) should do.\n" ]
[ 4 ]
[]
[]
[ "performance", "python", "richtextbox", "tkinter" ]
stackoverflow_0002279063_performance_python_richtextbox_tkinter.txt
Q: Effective ways to implement Every-to-Every interaction? Given a list of elements, how to process all elements if every element requires knowledge about states of every other element of this list? For example, direct way to implement it in Python could be: S = [1,2,3,4] for e in S: for j in S: if e!=j: process_it(e,j) but it is very slow O(n²) if number of elements is huge. There must be another effective way, involving concurrency as well. Can you help me? A: If you need to process every pair of items, there are O(n2) pairs, so you will have to make that many calls! If you only need the combinations (ab, ac, bc), not all the permutations (ab,ba,ac,ca,bc,cb), then you can do this, to halve the number of calls (and skip the if): for idA,val in enumerate(items): for idB in range(0, idA): process_it(val,items[idB]) The only way to improve it is to find a way of breaking down you process_it routine so it can work on multiple pairs. Without any more info, not much we can suggest. A: The suitability of a given task to be handled in multi-process fashion depends on the nature of the task and the interdependency (or lack thereof) of various subtasks, not on the way the list of subtasks is produced. In other words, using the question's wording, the ability for this problem to not be so slow by involving concurrency depends on the fact that the process_it() method is either such that: it produces the exact same outcome (direct and by side-effect) each time it is called with a given set of parameters. (this is the typical case for a multi-processable task) its overall outcome for a series of calls is independent of the order of the series (this is a bit of a odd case of a multi-processable task). And it doesn't depend on the fact that the order in which the series of calls to process_it() is produced by cartesian product of a list (the Every-to-Every of the question) or by some preconstructed list, or some other fashion. Also, the complexity of the problem (O(n^2) in the question) does not diminish because the problem is handed in a multi-process fashion. In fact the multi-process logic often introduces additional complexity (to "pay" for organizing and feeding the multiple threads and to combine their results); such added difficulty is however typically of an other order of magnitude of the problem (say constant, or maybe linear in n) and therefore doesn't change the overall complexity. Unrelated to the ability for the process to be split in multiple asynchronous subtasks, it may be such that the complexity of the problem can be reduced, as hinted in some other answers (for example if process_it(a,b) is the same as process_it(b,a), or if the underlying data is such that sorting it first could reduce the number of times process_it needs to be called etc.) Also, and while some programming languages or libraries/environments make it easier to manage multi-processing, the question is generally language-agnostic; maybe the python tag and the illustrative snippet confuse the issue somehow. A: One sure option is to get it implemented in FPGA and have them all work concurrently. Other than that - if there are no exceptions and really -all- need -all-, not "some need some", you're sentenced to the standard approach.
Effective ways to implement Every-to-Every interaction?
Given a list of elements, how to process all elements if every element requires knowledge about states of every other element of this list? For example, direct way to implement it in Python could be: S = [1,2,3,4] for e in S: for j in S: if e!=j: process_it(e,j) but it is very slow O(n²) if number of elements is huge. There must be another effective way, involving concurrency as well. Can you help me?
[ "If you need to process every pair of items, there are O(n2) pairs, so you will have to make that many calls!\nIf you only need the combinations (ab, ac, bc), not all the permutations (ab,ba,ac,ca,bc,cb), then you can do this, to halve the number of calls (and skip the if):\nfor idA,val in enumerate(items):\n for idB in range(0, idA):\n process_it(val,items[idB]) \n\nThe only way to improve it is to find a way of breaking down you process_it routine so it can work on multiple pairs. Without any more info, not much we can suggest.\n", "The suitability of a given task to be handled in multi-process fashion depends on the nature of the task and the interdependency (or lack thereof) of various subtasks, not on the way the list of subtasks is produced.\nIn other words, using the question's wording, the ability for this problem to not be so slow by involving concurrency depends on the fact that the process_it() method is either such that:\n\nit produces the exact same outcome (direct and by side-effect) each time it is called with a given set of parameters. (this is the typical case for a multi-processable task)\nits overall outcome for a series of calls is independent of the order of the series (this is a bit of a odd case of a multi-processable task).\n\nAnd it doesn't depend on the fact that the order in which the series of calls to process_it() is produced by cartesian product of a list (the Every-to-Every of the question) or by some preconstructed list, or some other fashion.\nAlso, the complexity of the problem (O(n^2) in the question) does not diminish because the problem is handed in a multi-process fashion. In fact the multi-process logic often introduces additional complexity (to \"pay\" for organizing and feeding the multiple threads and to combine their results); such added difficulty is however typically of an other order of magnitude of the problem (say constant, or maybe linear in n) and therefore doesn't change the overall complexity.\nUnrelated to the ability for the process to be split in multiple asynchronous subtasks, it may be such that the complexity of the problem can be reduced, as hinted in some other answers (for example if process_it(a,b) is the same as process_it(b,a), or if the underlying data is such that sorting it first could reduce the number of times process_it needs to be called etc.)\nAlso, and while some programming languages or libraries/environments make it easier to manage multi-processing, the question is generally language-agnostic; maybe the python tag and the illustrative snippet confuse the issue somehow.\n", "One sure option is to get it implemented in FPGA and have them all work concurrently. Other than that - if there are no exceptions and really -all- need -all-, not \"some need some\", you're sentenced to the standard approach.\n" ]
[ 2, 1, 0 ]
[]
[]
[ "algorithm", "c", "parallel_processing", "python" ]
stackoverflow_0002288849_algorithm_c_parallel_processing_python.txt
Q: Python, mongo + spider monkey Ok, so this isn't exactly a question that I expect a full answer for but here goes... I am currently using a python driver to fire data at a mongo instance and all it well in the world. Now I want to be able to pull data from mongo and evaluate each record in the collection. Now I need to pass in to this evaluation a script that will look at the row of data and if a condition is met return true i.e. (PSUDO CODE) foreach(row in resultSet) if(row.Name=="Chris) return true return false Now the script that I use to evaluate each item in the row should be sandboxes somehow with limited functionality/security privileges. In other words the code will be evaled, and I dont want it to have rights to i.e. include external libraries, call remote servers or have access any files on the server etc... With this in mind I know that mongo uses something called spider monkey (which I gather is a JS evaluator) to write queries. I wonder would it be possible to take the result of a mongo call and pass it to an evaluated javascript function using spider monkey (somehow) to achieve what I am after? If so would this be safe enough. To be honest, Im writing this question and I realize its sounding a lot like one of those "please help, how to code the world" type questions but any pointers would be helpful. A: Have you looked at $where clauses in MongoDB? Seems like those would pretty much give you exactly what you're looking for. In PyMongo it would look something like: db.foo.find().where("some javascript function that will get applied to each document matched by the find")
Python, mongo + spider monkey
Ok, so this isn't exactly a question that I expect a full answer for but here goes... I am currently using a python driver to fire data at a mongo instance and all it well in the world. Now I want to be able to pull data from mongo and evaluate each record in the collection. Now I need to pass in to this evaluation a script that will look at the row of data and if a condition is met return true i.e. (PSUDO CODE) foreach(row in resultSet) if(row.Name=="Chris) return true return false Now the script that I use to evaluate each item in the row should be sandboxes somehow with limited functionality/security privileges. In other words the code will be evaled, and I dont want it to have rights to i.e. include external libraries, call remote servers or have access any files on the server etc... With this in mind I know that mongo uses something called spider monkey (which I gather is a JS evaluator) to write queries. I wonder would it be possible to take the result of a mongo call and pass it to an evaluated javascript function using spider monkey (somehow) to achieve what I am after? If so would this be safe enough. To be honest, Im writing this question and I realize its sounding a lot like one of those "please help, how to code the world" type questions but any pointers would be helpful.
[ "Have you looked at $where clauses in MongoDB? Seems like those would pretty much give you exactly what you're looking for. In PyMongo it would look something like:\ndb.foo.find().where(\"some javascript function that will get applied to each document matched by the find\")\n\n" ]
[ 3 ]
[]
[]
[ "mongodb", "python", "spidermonkey" ]
stackoverflow_0002285083_mongodb_python_spidermonkey.txt
Q: Fast way to get N Min or Max elements from a list in Python I currently have a long list which is being sorted using a lambda function f. I then choose a random element from the first five elements. Something like: f = lambda x: some_function_of(x, local_variable) my_list.sort(key=f) foo = choice(my_list[:4]) This is a bottleneck in my program, according to the profiler. How can I speed things up? Is there a fast, inbuilt way to retrieve the elements I want (in theory shouldn't need to sort the whole list). Thanks. A: Use heapq.nlargest or heapq.nsmallest. For example: import heapq elements = heapq.nsmallest(4, my_list, key=f) foo = choice(elements) This will take O(N+KlogN) time (where K is the number of elements returned, and N is the list size), which is faster than O(NlogN) for normal sort when K is small relative to N. A: It's actually possible in linear time (O(N)) on average. You need a partition algorithm: def partition(seq, pred, start=0, end=-1): if end == -1: end = len(seq) while True: while True: if start == end: return start if not pred(seq[start]): break start += 1 while True: if pred(seq[end-1]): break end -= 1 if start == end: return start seq[start], seq[end-1] = seq[end-1], seq[start] start += 1 end -= 1 which can be used by an nth_element algorithm: def nth_element(seq_in, n, key=lambda x:x): start, end = 0, len(seq_in) seq = [(x, key(x)) for x in seq_in] def partition_pred(x): return x[1] < seq[end-1][1] while start != end: pivot = (end + start) // 2 seq[pivot], seq[end - 1] = seq[end - 1], seq[pivot] pivot = partition(seq, partition_pred, start, end) seq[pivot], seq[end - 1] = seq[end - 1], seq[pivot] if pivot == n: break if pivot < n: start = pivot + 1 else: end = pivot seq_in[:] = (x for x, k in seq) Given these, just replace your second (sort) line with: nth_element(my_list, 4, key=f)
Fast way to get N Min or Max elements from a list in Python
I currently have a long list which is being sorted using a lambda function f. I then choose a random element from the first five elements. Something like: f = lambda x: some_function_of(x, local_variable) my_list.sort(key=f) foo = choice(my_list[:4]) This is a bottleneck in my program, according to the profiler. How can I speed things up? Is there a fast, inbuilt way to retrieve the elements I want (in theory shouldn't need to sort the whole list). Thanks.
[ "Use heapq.nlargest or heapq.nsmallest.\nFor example:\nimport heapq\n\nelements = heapq.nsmallest(4, my_list, key=f)\nfoo = choice(elements)\n\nThis will take O(N+KlogN) time (where K is the number of elements returned, and N is the list size), which is faster than O(NlogN) for normal sort when K is small relative to N.\n", "It's actually possible in linear time (O(N)) on average.\nYou need a partition algorithm:\ndef partition(seq, pred, start=0, end=-1):\n if end == -1: end = len(seq)\n while True:\n while True:\n if start == end: return start\n if not pred(seq[start]): break\n start += 1\n while True:\n if pred(seq[end-1]): break\n end -= 1\n if start == end: return start\n seq[start], seq[end-1] = seq[end-1], seq[start]\n start += 1\n end -= 1\n\nwhich can be used by an nth_element algorithm:\ndef nth_element(seq_in, n, key=lambda x:x):\n start, end = 0, len(seq_in)\n seq = [(x, key(x)) for x in seq_in]\n\n def partition_pred(x): return x[1] < seq[end-1][1]\n\n while start != end:\n pivot = (end + start) // 2\n seq[pivot], seq[end - 1] = seq[end - 1], seq[pivot]\n pivot = partition(seq, partition_pred, start, end)\n seq[pivot], seq[end - 1] = seq[end - 1], seq[pivot]\n if pivot == n: break\n if pivot < n: start = pivot + 1\n else: end = pivot\n\n seq_in[:] = (x for x, k in seq)\n\nGiven these, just replace your second (sort) line with:\nnth_element(my_list, 4, key=f)\n\n" ]
[ 11, 1 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0002289053_python_sorting.txt
Q: How can I work with base 5 numbers in Python? Possible Duplicate: convert integer to a string in a given numeric base in python I want to work with base 5 numbers, or any other non standard base for that matter. I found out int('123', 5) works, but I need to go the other way around. Should I write my own number class to accomplish this? Maybe I'm just thinking in the wrong direction... A: def to_base_5(n): s = "" while n: s = str(n % 5) + s n /= 5 return s A: I had fun with this a while ago for a python-dev thread. The original post can be found at http://mail.python.org/pipermail/python-dev/2006-January/059925.html This particular algorithm can perform floating point bases as well. #!/usr/bin/env python import math def ibase(n, radix=2, maxlen=None): r = [] while n: n,p = divmod(n, radix) r.append('%d' % p) if maxlen and len(r) > maxlen: break r.reverse() return ''.join(r) def fbase(n, radix=2, maxlen=8): r = [] f = math.modf(n)[0] while f: f, p = math.modf(f*radix) r.append('%.0f' % p) if maxlen and len(r) > maxlen: break return ''.join(r) def base(n, radix, maxfloat=8): if isinstance(n, float): return ibase(n, radix)+'.'+fbase(n, radix, maxfloat) elif isinstance(n, (str, unicode)): n,f = n.split('.') n = int(n, radix) f = int(f, radix)/float(radix**len(f)) return n + f else: return ibase(n, radix) if __name__=='__main__': pi = 3.14 print 'pi:', pi, 'base 10' piBase3 = base(pi, 3) print 'pi:', piBase3, 'base 3' piFromBase3 = base(piBase3, 3) print 'pi:', piFromBase3, 'base 10 from base 3'
How can I work with base 5 numbers in Python?
Possible Duplicate: convert integer to a string in a given numeric base in python I want to work with base 5 numbers, or any other non standard base for that matter. I found out int('123', 5) works, but I need to go the other way around. Should I write my own number class to accomplish this? Maybe I'm just thinking in the wrong direction...
[ "def to_base_5(n):\n s = \"\"\n while n:\n s = str(n % 5) + s\n n /= 5\n return s\n\n", "I had fun with this a while ago for a python-dev thread. The original post can be found at \nhttp://mail.python.org/pipermail/python-dev/2006-January/059925.html This particular algorithm can perform floating point bases as well.\n#!/usr/bin/env python\nimport math\n\ndef ibase(n, radix=2, maxlen=None):\n r = []\n while n:\n n,p = divmod(n, radix)\n r.append('%d' % p)\n if maxlen and len(r) > maxlen:\n break\n r.reverse()\n return ''.join(r)\n\ndef fbase(n, radix=2, maxlen=8):\n r = []\n f = math.modf(n)[0]\n while f:\n f, p = math.modf(f*radix)\n r.append('%.0f' % p)\n if maxlen and len(r) > maxlen:\n break\n return ''.join(r)\n\ndef base(n, radix, maxfloat=8):\n if isinstance(n, float):\n return ibase(n, radix)+'.'+fbase(n, radix, maxfloat)\n elif isinstance(n, (str, unicode)):\n n,f = n.split('.')\n n = int(n, radix)\n f = int(f, radix)/float(radix**len(f))\n return n + f\n else:\n return ibase(n, radix)\n\nif __name__=='__main__':\n pi = 3.14\n print 'pi:', pi, 'base 10'\n\n piBase3 = base(pi, 3)\n print 'pi:', piBase3, 'base 3'\n\n piFromBase3 = base(piBase3, 3)\n print 'pi:', piFromBase3, 'base 10 from base 3'\n\n" ]
[ 5, 3 ]
[]
[]
[ "math", "python" ]
stackoverflow_0002288482_math_python.txt
Q: Disable class instance methods How can I quickly disable all methods in a class instance based on a condition? My naive solution is to override using the __getattr__ but this is not called when the function name exists already. class my(): def method1(self): print 'method1' def method2(self): print 'method2' def __getattr__(self, name): print 'Fetching '+str(name) if self.isValid(): return getattr(self, name) def isValid(self): return False if __name__ == '__main__': m=my() m.method1() A: The equivalent of what you want to do is actually to override __getattribute__, which is going to be called for every attribute access. Besides it being very slow, take care: by definition of every, that includes e.g. the call to self.isValid within __getattribute__'s own body, so you'll have to use some circuitous route to access that attribute (type(self).isValid(self) should work, for example, as it gets the attribute from the class, not from the instance). This points to a horrible terminological confusion: this is not disabling "method from a class", but from an instance, and in particular has nothing to do with classmethods. If you do want to work in a similar way on a class basis, rather than an instance basis, you'll need to make a custom metaclass and override __getattribute__ on the metaclass (that's the one that's called when you access attributes on the class -- as you're asking in your title and text -- rather than on the instance -- as you in fact appear to be doing, which is by far the more normal and usual case). Edit: a completely different approach might be to use a peculiarly Pythonic pathway to implementing the State design pattern: class-switching. E.g.: class _NotValid(object): def isValid(self): return False def setValid(self, yesno): if yesno: self.__class__ = TheGoodOne class TheGoodOne(object): def isValid(self): return True def setValid(self, yesno): if not yesno: self.__class__ = _NotValid # write all other methods here As long as you can call setValid appropriately, so that the object's __class__ is switched appropriately, this is very fast and simple -- essentially, the object's __class__ is where all the object's methods are found, so by switching it you switch, en masse, the set of methods that exist on the object at a given time. However, this does not work if you absolutely insist that validity checking must be performed "just in time", i.e. at the very instant the object's method is being looked up. An intermediate approach between this and the __getattribute__ one would be to introduce an extra level of indirection (which is popularly held to be the solution to all problems;-), along the lines of: class _Valid(object): def __init__(self, actualobject): self._actualobject = actualobject # all actual methods go here # keeping state in self._actualobject class Wrapit(object): def __init__(self): self._themethods = _Valid(self) def isValid(self): # whatever logic you want # (DON'T call other self. methods!-) return False def __getattr__(self, n): if self.isValid(): return getattr(self._themethods, n) raise AttributeError(n) This is more idiomatic than __getattribute__ because it relies on the fact that __getattr__ is only called for attributes that aren't found in other ways -- so the object can hold normal state (data) in its __dict__, and that will be accessed without any big overhead; only method calls pay the extra overhead of indiretion. The _Valid class instances can keep some or all state in their respective self._actualobject, if any of the state needs to stay accessible on invalid objects (so that the invalid state disable methods, but not data attributes access; it's not clear from your Q if that's needed, but it's a free extra possibility offered by this approach). This idiom is less error-prone than __getattribute__, since state can be accessed more directly in the methods (without triggering validity checks). As presented, the solution creates a circular reference loop, which may impose a bit of overhead in terms of garbage collection. If that's a problem in your application, use the weakref module from the standard Python library, of course -- that module is generally the simplest way to remove circular loops of references, if and when they're a problem. (E.g., make the _actualobject attribute of _Valid class instances a weak reference to the object that holds that instance as its _themethods attribute).
Disable class instance methods
How can I quickly disable all methods in a class instance based on a condition? My naive solution is to override using the __getattr__ but this is not called when the function name exists already. class my(): def method1(self): print 'method1' def method2(self): print 'method2' def __getattr__(self, name): print 'Fetching '+str(name) if self.isValid(): return getattr(self, name) def isValid(self): return False if __name__ == '__main__': m=my() m.method1()
[ "The equivalent of what you want to do is actually to override __getattribute__, which is going to be called for every attribute access. Besides it being very slow, take care: by definition of every, that includes e.g. the call to self.isValid within __getattribute__'s own body, so you'll have to use some circuitous route to access that attribute (type(self).isValid(self) should work, for example, as it gets the attribute from the class, not from the instance).\nThis points to a horrible terminological confusion: this is not disabling \"method from a class\", but from an instance, and in particular has nothing to do with classmethods. If you do want to work in a similar way on a class basis, rather than an instance basis, you'll need to make a custom metaclass and override __getattribute__ on the metaclass (that's the one that's called when you access attributes on the class -- as you're asking in your title and text -- rather than on the instance -- as you in fact appear to be doing, which is by far the more normal and usual case).\nEdit: a completely different approach might be to use a peculiarly Pythonic pathway to implementing the State design pattern: class-switching. E.g.:\nclass _NotValid(object):\n def isValid(self):\n return False\n def setValid(self, yesno):\n if yesno:\n self.__class__ = TheGoodOne\n\nclass TheGoodOne(object):\n def isValid(self):\n return True\n def setValid(self, yesno):\n if not yesno:\n self.__class__ = _NotValid\n # write all other methods here\n\nAs long as you can call setValid appropriately, so that the object's __class__ is switched appropriately, this is very fast and simple -- essentially, the object's __class__ is where all the object's methods are found, so by switching it you switch, en masse, the set of methods that exist on the object at a given time. However, this does not work if you absolutely insist that validity checking must be performed \"just in time\", i.e. at the very instant the object's method is being looked up.\nAn intermediate approach between this and the __getattribute__ one would be to introduce an extra level of indirection (which is popularly held to be the solution to all problems;-), along the lines of:\nclass _Valid(object):\n def __init__(self, actualobject):\n self._actualobject = actualobject\n # all actual methods go here\n # keeping state in self._actualobject\n\nclass Wrapit(object):\n def __init__(self):\n self._themethods = _Valid(self)\n def isValid(self):\n # whatever logic you want\n # (DON'T call other self. methods!-)\n return False\n def __getattr__(self, n):\n if self.isValid():\n return getattr(self._themethods, n)\n raise AttributeError(n)\n\nThis is more idiomatic than __getattribute__ because it relies on the fact that __getattr__ is only called for attributes that aren't found in other ways -- so the object can hold normal state (data) in its __dict__, and that will be accessed without any big overhead; only method calls pay the extra overhead of indiretion. The _Valid class instances can keep some or all state in their respective self._actualobject, if any of the state needs to stay accessible on invalid objects (so that the invalid state disable methods, but not data attributes access; it's not clear from your Q if that's needed, but it's a free extra possibility offered by this approach). This idiom is less error-prone than __getattribute__, since state can be accessed more directly in the methods (without triggering validity checks).\nAs presented, the solution creates a circular reference loop, which may impose a bit of overhead in terms of garbage collection. If that's a problem in your application, use the weakref module from the standard Python library, of course -- that module is generally the simplest way to remove circular loops of references, if and when they're a problem.\n(E.g., make the _actualobject attribute of _Valid class instances a weak reference to the object that holds that instance as its _themethods attribute).\n" ]
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0002289797_python.txt
Q: Python and urllib I'm trying to download a zip file ("tl_2008_01001_edges.zip") from an ftp census site using urllib. What form is the zip file in when I get it and how do I save it? I'm fairly new to Python and don't understand how urllib works. This is my attempt: import urllib, sys zip_file = urllib.urlretrieve("ftp://ftp2.census.gov/geo/tiger/TIGER2008/01_ALABAMA/Autauga_County/", "tl_2008_01001_edges.zip") If I know the list of ftp folders (or counties in this case), can I run through the ftp site list using the glob function? Thanks. A: Use urllib2.urlopen() for the zip file data and directory listing. To process zip files with the zipfile module, you can write them to a disk file which is then passed to the zipfile.ZipFile constructor. Retrieving the data is straightforward using read() on the file-like object returned by urllib2.urlopen(). Fetching directories: >>> files = urllib2.urlopen('ftp://ftp2.census.gov/geo/tiger/TIGER2008/01_ALABAMA/').read().splitlines() >>> for l in files[:4]: print l ... drwxrwsr-x 2 0 4009 4096 Nov 26 2008 01001_Autauga_County drwxrwsr-x 2 0 4009 4096 Nov 26 2008 01003_Baldwin_County drwxrwsr-x 2 0 4009 4096 Nov 26 2008 01005_Barbour_County drwxrwsr-x 2 0 4009 4096 Nov 26 2008 01007_Bibb_County >>> Or, splitting for directory names: >>> for l in files[:4]: print l.split()[-1] ... 01001_Autauga_County 01003_Baldwin_County 01005_Barbour_County 01007_Bibb_County A: import os,urllib2 out=os.path.join("/tmp","test.zip") url="ftp://ftp2.census.gov/geo/tiger/TIGER2008/01_ALABAMA/01001_Autauga_County/tl_2008_01001_edges.zip" page=urllib2.urlopen(url) open(out,"wb").write(page.read()) A: Per the docs, urlretrieve puts the file to disk and returns a tuple (filename, headers). So the file is already saved when urlretrieve returns. You can open and read the ZIP file you've retrieved with the zipfile module of the standard library. glob does not work inside zipfiles, only on normal filesystem directories.
Python and urllib
I'm trying to download a zip file ("tl_2008_01001_edges.zip") from an ftp census site using urllib. What form is the zip file in when I get it and how do I save it? I'm fairly new to Python and don't understand how urllib works. This is my attempt: import urllib, sys zip_file = urllib.urlretrieve("ftp://ftp2.census.gov/geo/tiger/TIGER2008/01_ALABAMA/Autauga_County/", "tl_2008_01001_edges.zip") If I know the list of ftp folders (or counties in this case), can I run through the ftp site list using the glob function? Thanks.
[ "Use urllib2.urlopen() for the zip file data and directory listing.\nTo process zip files with the zipfile module, you can write them to a disk file which is then passed to the zipfile.ZipFile constructor.\nRetrieving the data is straightforward using read() on the file-like object returned\nby urllib2.urlopen().\nFetching directories:\n>>> files = urllib2.urlopen('ftp://ftp2.census.gov/geo/tiger/TIGER2008/01_ALABAMA/').read().splitlines()\n>>> for l in files[:4]: print l\n... \ndrwxrwsr-x 2 0 4009 4096 Nov 26 2008 01001_Autauga_County\ndrwxrwsr-x 2 0 4009 4096 Nov 26 2008 01003_Baldwin_County\ndrwxrwsr-x 2 0 4009 4096 Nov 26 2008 01005_Barbour_County\ndrwxrwsr-x 2 0 4009 4096 Nov 26 2008 01007_Bibb_County\n>>> \n\nOr, splitting for directory names:\n>>> for l in files[:4]: print l.split()[-1]\n... \n01001_Autauga_County\n01003_Baldwin_County\n01005_Barbour_County\n01007_Bibb_County\n\n", "import os,urllib2\nout=os.path.join(\"/tmp\",\"test.zip\")\nurl=\"ftp://ftp2.census.gov/geo/tiger/TIGER2008/01_ALABAMA/01001_Autauga_County/tl_2008_01001_edges.zip\"\npage=urllib2.urlopen(url)\nopen(out,\"wb\").write(page.read())\n\n", "Per the docs, urlretrieve puts the file to disk and returns a tuple (filename, headers). So the file is already saved when urlretrieve returns.\nYou can open and read the ZIP file you've retrieved with the zipfile module of the standard library. glob does not work inside zipfiles, only on normal filesystem directories.\n" ]
[ 8, 5, 3 ]
[]
[]
[ "python", "urllib", "urllib2" ]
stackoverflow_0002289768_python_urllib_urllib2.txt
Q: Sort strings by the first N characters I have a text file with lines like this: 2010-02-18 11:46:46.1287 bla 2010-02-18 11:46:46.1333 foo 2010-02-18 11:46:46.1333 bar 2010-02-18 11:46:46.1467 bla A simple sort would swap lines 2 and 3 (bar comes before foo), but I would like to keep lines (that have the same date/time) in their original order. How can I do this in Python? A: sorted(array, key=lambda x:x[:24]) Example: >>> a = ["wxyz", "abce", "abcd", "bcde"] >>> sorted(a) ['abcd', 'abce', 'bcde', 'wxyz'] >>> sorted(a, key=lambda x:x[:3]) ['abce', 'abcd', 'bcde', 'wxyz'] A: The built-in sort is stable, so you the effectively-equal values stay in order by default. import operator with open('filename', 'r') as f: sorted_lines = sorted(f, key=operator.itemgetter(slice(0, 24))) At this point sorted_lines will be a list of the sorted lines. To replace the old file, make a new file, call new_file.writelines(sorted_lines), then move the new file over the old one.
Sort strings by the first N characters
I have a text file with lines like this: 2010-02-18 11:46:46.1287 bla 2010-02-18 11:46:46.1333 foo 2010-02-18 11:46:46.1333 bar 2010-02-18 11:46:46.1467 bla A simple sort would swap lines 2 and 3 (bar comes before foo), but I would like to keep lines (that have the same date/time) in their original order. How can I do this in Python?
[ "sorted(array, key=lambda x:x[:24])\n\nExample:\n>>> a = [\"wxyz\", \"abce\", \"abcd\", \"bcde\"]\n>>> sorted(a)\n['abcd', 'abce', 'bcde', 'wxyz']\n>>> sorted(a, key=lambda x:x[:3])\n['abce', 'abcd', 'bcde', 'wxyz']\n\n", "The built-in sort is stable, so you the effectively-equal values stay in order by default.\nimport operator\n\nwith open('filename', 'r') as f:\n sorted_lines = sorted(f, key=operator.itemgetter(slice(0, 24)))\n\nAt this point sorted_lines will be a list of the sorted lines. To replace the old file, make a new file, call new_file.writelines(sorted_lines), then move the new file over the old one.\n" ]
[ 26, 5 ]
[]
[]
[ "python", "sorting", "string" ]
stackoverflow_0002289870_python_sorting_string.txt
Q: what this python code trying to do The following python code is to traverse a 2D grid of (c, g) in some special order, which is stored in "jobs" and "job_queue". But I am not sure which kind of order it is after trying to understand the code. Is someone able to tell about the order and give some explanation for the purpose of each function? Thanks and regards! import Queue c_begin, c_end, c_step = -5, 15, 2 g_begin, g_end, g_step = 3, -15, -2 def range_f(begin,end,step): # like range, but works on non-integer too seq = [] while True: if step > 0 and begin > end: break if step < 0 and begin < end: break seq.append(begin) begin = begin + step return seq def permute_sequence(seq): n = len(seq) if n <= 1: return seq mid = int(n/2) left = permute_sequence(seq[:mid]) right = permute_sequence(seq[mid+1:]) ret = [seq[mid]] while left or right: if left: ret.append(left.pop(0)) if right: ret.append(right.pop(0)) return ret def calculate_jobs(): c_seq = permute_sequence(range_f(c_begin,c_end,c_step)) g_seq = permute_sequence(range_f(g_begin,g_end,g_step)) nr_c = float(len(c_seq)) nr_g = float(len(g_seq)) i = 0 j = 0 jobs = [] while i < nr_c or j < nr_g: if i/nr_c < j/nr_g: # increase C resolution line = [] for k in range(0,j): line.append((c_seq[i],g_seq[k])) i = i + 1 jobs.append(line) else: # increase g resolution line = [] for k in range(0,i): line.append((c_seq[k],g_seq[j])) j = j + 1 jobs.append(line) return jobs def main(): jobs = calculate_jobs() job_queue = Queue.Queue(0) for line in jobs: for (c,g) in line: job_queue.put((c,g)) main() EDIT: There is a value for each (c,g). The code actually is to search in the 2D grid of (c,g) to find a grid point where the value is the smallest. I guess the code is using some kind of heuristic search algorithm? The original code is here http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/gridsvr/gridregression.py, which is a script to search for svm algorithm the best values for two parameters c and g with minimum validation error. A: permute_sequence reorders a list of values so that the middle value is first, then the midpoint of each half, then the midpoints of the four remaining quarters, and so on. So permute_sequence(range(1000)) starts out like this: [500, 250, 750, 125, 625, 375, ...] calculate_jobs alternately fills in rows and columns using the sequences of 1D coordinates provided by permute_sequence. If you're going to search the entire 2D space eventually anyway, this does not help you finish sooner. You might as well just scan all the points in order. But I think the idea was to find a decent approximation of the minimum as early as possible in the search. I suspect you could do about as well by shuffling the list randomly. xkcd readers will note that the urinal protocol would give only slightly different (and probably better) results: [0, 1000, 500, 250, 750, 125, 625, 375, ...] A: Here is an example of permute_sequence in action: print permute_sequence(range(8)) # prints [4, 2, 6, 1, 5, 3, 7, 0] print permute_sequence(range(12)) # prints [6, 3, 9, 1, 8, 5, 11, 0, 7, 4, 10, 2] I'm not sure why it uses this order, because in main, it appears that all candidate pairs of (c,g) are still evaluated, I think.
what this python code trying to do
The following python code is to traverse a 2D grid of (c, g) in some special order, which is stored in "jobs" and "job_queue". But I am not sure which kind of order it is after trying to understand the code. Is someone able to tell about the order and give some explanation for the purpose of each function? Thanks and regards! import Queue c_begin, c_end, c_step = -5, 15, 2 g_begin, g_end, g_step = 3, -15, -2 def range_f(begin,end,step): # like range, but works on non-integer too seq = [] while True: if step > 0 and begin > end: break if step < 0 and begin < end: break seq.append(begin) begin = begin + step return seq def permute_sequence(seq): n = len(seq) if n <= 1: return seq mid = int(n/2) left = permute_sequence(seq[:mid]) right = permute_sequence(seq[mid+1:]) ret = [seq[mid]] while left or right: if left: ret.append(left.pop(0)) if right: ret.append(right.pop(0)) return ret def calculate_jobs(): c_seq = permute_sequence(range_f(c_begin,c_end,c_step)) g_seq = permute_sequence(range_f(g_begin,g_end,g_step)) nr_c = float(len(c_seq)) nr_g = float(len(g_seq)) i = 0 j = 0 jobs = [] while i < nr_c or j < nr_g: if i/nr_c < j/nr_g: # increase C resolution line = [] for k in range(0,j): line.append((c_seq[i],g_seq[k])) i = i + 1 jobs.append(line) else: # increase g resolution line = [] for k in range(0,i): line.append((c_seq[k],g_seq[j])) j = j + 1 jobs.append(line) return jobs def main(): jobs = calculate_jobs() job_queue = Queue.Queue(0) for line in jobs: for (c,g) in line: job_queue.put((c,g)) main() EDIT: There is a value for each (c,g). The code actually is to search in the 2D grid of (c,g) to find a grid point where the value is the smallest. I guess the code is using some kind of heuristic search algorithm? The original code is here http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/gridsvr/gridregression.py, which is a script to search for svm algorithm the best values for two parameters c and g with minimum validation error.
[ "permute_sequence reorders a list of values so that the middle value is first, then the midpoint of each half, then the midpoints of the four remaining quarters, and so on. So permute_sequence(range(1000)) starts out like this:\n [500, 250, 750, 125, 625, 375, ...]\n\ncalculate_jobs alternately fills in rows and columns using the sequences of 1D coordinates provided by permute_sequence.\nIf you're going to search the entire 2D space eventually anyway, this does not help you finish sooner. You might as well just scan all the points in order. But I think the idea was to find a decent approximation of the minimum as early as possible in the search. I suspect you could do about as well by shuffling the list randomly.\nxkcd readers will note that the urinal protocol would give only slightly different (and probably better) results:\n [0, 1000, 500, 250, 750, 125, 625, 375, ...]\n\n", "Here is an example of permute_sequence in action:\nprint permute_sequence(range(8))\n# prints [4, 2, 6, 1, 5, 3, 7, 0]\nprint permute_sequence(range(12))\n# prints [6, 3, 9, 1, 8, 5, 11, 0, 7, 4, 10, 2]\n\nI'm not sure why it uses this order, because in main, it appears that all candidate pairs of (c,g) are still evaluated, I think.\n" ]
[ 2, 1 ]
[]
[]
[ "algorithm", "libsvm", "machine_learning", "python", "search" ]
stackoverflow_0002286438_algorithm_libsvm_machine_learning_python_search.txt
Q: Accessing a Variable from Within a Doubly Nested Function in Python The following code: x = 0 print "Initialization: ", x def f1(): x = 1 print "In f1 before f2:", x def f2(): global x x = 2 print "In f2: ", x f2() print "In f1 after f2: ", x f1() print "Final: ", x prints: Initialization: 0 In f1 before f2: 1 In f2: 2 In f1 after f2: 1 Final: 2 Is there a way for f2 to access f1's variables? A: In Python 3, you can define x as nonlocal in f2. In Python 2, you can't assign directly to f1's x in f2. However, you can read its value and access its members. So this could be a workaround: def f1(): x = [1] def f2(): x[0] = 2 f2() print x[0] f1() A: You can access the variables, the problem is the assignment. In Python 2 there is no way to rebind x to a new value. See PEP 227 (nested scopes) for more on this. In Python 3 you can use the new nonlocal keyword instead of global. See PEP 3104. A: remove global statement: >>> x 0 >>> def f1(): x = 1 print(x) def f2(): print(x) f2() print(x) >>> f1() 1 1 1 if you want to change variable x from f1 then you need to use global statement in each function.
Accessing a Variable from Within a Doubly Nested Function in Python
The following code: x = 0 print "Initialization: ", x def f1(): x = 1 print "In f1 before f2:", x def f2(): global x x = 2 print "In f2: ", x f2() print "In f1 after f2: ", x f1() print "Final: ", x prints: Initialization: 0 In f1 before f2: 1 In f2: 2 In f1 after f2: 1 Final: 2 Is there a way for f2 to access f1's variables?
[ "In Python 3, you can define x as nonlocal in f2.\nIn Python 2, you can't assign directly to f1's x in f2. However, you can read its value and access its members. So this could be a workaround:\ndef f1():\n x = [1]\n def f2():\n x[0] = 2\n f2()\n print x[0]\nf1()\n\n", "You can access the variables, the problem is the assignment. In Python 2 there is no way to rebind x to a new value. See PEP 227 (nested scopes) for more on this.\nIn Python 3 you can use the new nonlocal keyword instead of global. See PEP 3104.\n", "remove global statement:\n>>> x\n0\n>>> def f1():\n x = 1\n print(x)\n def f2():\n print(x)\n f2()\n print(x)\n\n\n>>> f1()\n1\n1\n1\n\nif you want to change variable x from f1 then you need to use global statement in each function.\n" ]
[ 6, 6, 0 ]
[]
[]
[ "global_variables", "nested_function", "python" ]
stackoverflow_0002290654_global_variables_nested_function_python.txt
Q: python more trouble importing modules I asked a similar question yesterday, but have acquired a really odd problem since then. With this directory structure: app/ models/ __init__.py user.py other.py pages/ __init__.py pages.py The models/__init__.py file has this line: __all__ = ['user', 'other'] and the pages/__init__.py has __all__ = ['pages'] In pages.py, in order to use any of the classes in user.py or other.py, I have to have from models import * import models at the top, and then I can declare a User class like this: my_user = models.user.User() If I exclude either of the import-ing statements at the top, I get errors like "Class user has no attribute User" Any help would be appreciated. I love Python, but I wish it's import functionality worked more like PHP's. A: import models.user A: There are two options, depending on where you want to be explicit and how much you want available "by default" (which also means forced). In those __init__ files you could use: # models/__init__.py shown: import user, other # ambiguous relative import from . import user, other # relative import from app.models import user, other # absolute import Or, where you would otherwise just have import models, use: from models import user, other # or: import models.user, models.other The latter form is more widely preferred. A: One thing that can be real helpful when you're learning python (or debugging), is to run interactively and use the dir() function to see what lives where: >>> dir() ['__builtins__', '__doc__', '__name__', '__package__'] >>> import models >>> dir(models) ['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__'] >>> models.user Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'user' >>> from models import * >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'models', 'other', 'user'] >>> dir(models) ['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__','__path__', 'other', 'user'] >>> user <module 'models.user' from 'C:\test\models\user.py'> >>> models.user <module 'models.user' from 'C:\test\models\user.py'> >>> user.User <class 'models.user.User'> Update: fixed output.
python more trouble importing modules
I asked a similar question yesterday, but have acquired a really odd problem since then. With this directory structure: app/ models/ __init__.py user.py other.py pages/ __init__.py pages.py The models/__init__.py file has this line: __all__ = ['user', 'other'] and the pages/__init__.py has __all__ = ['pages'] In pages.py, in order to use any of the classes in user.py or other.py, I have to have from models import * import models at the top, and then I can declare a User class like this: my_user = models.user.User() If I exclude either of the import-ing statements at the top, I get errors like "Class user has no attribute User" Any help would be appreciated. I love Python, but I wish it's import functionality worked more like PHP's.
[ "import models.user\n\n", "There are two options, depending on where you want to be explicit and how much you want available \"by default\" (which also means forced).\nIn those __init__ files you could use:\n# models/__init__.py shown:\nimport user, other # ambiguous relative import\nfrom . import user, other # relative import\nfrom app.models import user, other # absolute import\n\nOr, where you would otherwise just have import models, use:\nfrom models import user, other\n# or:\nimport models.user, models.other\n\nThe latter form is more widely preferred.\n", "One thing that can be real helpful when you're learning python (or debugging), is to run interactively and use the dir() function to see what lives where: \n>>> dir()\n['__builtins__', '__doc__', '__name__', '__package__']\n>>> import models\n>>> dir(models)\n['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']\n>>> models.user\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'module' object has no attribute 'user'\n>>> from models import *\n>>> dir()\n['__builtins__', '__doc__', '__name__', '__package__', 'models', 'other', 'user']\n>>> dir(models)\n['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__','__path__', 'other', 'user']\n>>> user\n<module 'models.user' from 'C:\\test\\models\\user.py'>\n>>> models.user\n<module 'models.user' from 'C:\\test\\models\\user.py'>\n>>> user.User\n<class 'models.user.User'>\n\nUpdate: fixed output. \n" ]
[ 1, 1, 1 ]
[]
[]
[ "python", "python_import", "python_module" ]
stackoverflow_0002290595_python_python_import_python_module.txt
Q: Any utility function in python which returns value when passed object and attribute to it? Like we have in Java Beans util where you pass object and the property name it gives you the value do we have anything similar in python: def attr(obj, attr) return obj.attr A: You can use getattr for this purpose. From the built-in function documentation: For example, getattr(x, 'foobar') is equivalent to x.foobar.
Any utility function in python which returns value when passed object and attribute to it?
Like we have in Java Beans util where you pass object and the property name it gives you the value do we have anything similar in python: def attr(obj, attr) return obj.attr
[ "You can use getattr for this purpose. From the built-in function documentation:\n\nFor example, getattr(x, 'foobar') is\n equivalent to x.foobar.\n\n" ]
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0002290805_python.txt
Q: Python for a Perl programmer I am an experienced Perl developer with some degree of experience and/or familiarity with other languages (working experience with C/C++, school experience with Java and Scheme, and passing familiarity with many others). I might need to get some web work done in Python (most immediately, related to Google App Engine). As such, I'd like to ask SO overmind for good references on how to best learn Python for someone who's coming from Perl background (e.g. the emphasis would be on differences between the two and how to translate perl idiomatics into Python idiomatics, as opposed to generic Python references). Something also centered on Web development is even better. I'll take anything - articles, tutorials, books, sample apps? Thanks! A: I've recently had to make a similar transition for work reasons, and it's been pretty painful. For better or worse, Python has a very different philosophy and way of working than Perl, and getting used to that can be frustrating. The things I've found most useful have been Spend a few hours going through all the basics. I found the official tutorial quite good, if a little dry. A good reference book to look up basic stuff ("how do I get the length of a string again?"). The ones I've found most useful are the Python Pocket Reference and Python Essential Reference. Take a look at this handy Perl<->Python phrasebook (common tasks, side by side, in both languages). A reference for the Python approach to "common tasks". I use the Python Cookbook. An ipython terminal open at all times to test syntax, introspect object methods etc. Get pip and easy-install (to install Python modules easily). Learn about unit tests fast. This is because without use strict you will feel crippled, and you will make many elementary mistakes which will appear as runtime errors. I recommend nose rather than the unittest framework that comes with the core install. unittest is very verbose if you're used to Test::More. Check out Python questions on Stack Overflow. In particular, Python - Things one MUST avoid and Python 2.x gotcha’s and landmines are well worth a read. Personally, I found Dive Into Python annoying and patronising, but it's freely available online, so you can form your own judgment on that. A: If you happen to be a fan of The Perl Cookbook, you might be interested in checking out PLEAC, the Programming Language Examples Alike Cookbook, specifically the section that shows the Perl Cookbook code translated into Python. A: Being a hardcore Perl programmer, all I can say is DO NOT BUY O'Reilly's "Learning Python". It is nowhere NEAR as good as "Learning Perl", and there's no equivalent I know of to Larry Wall's "Programming Perl", which is simply unbeatable. I've had the most success taking past Perl programs and translating them into Python, trying to make use of as many new techniques as possible. A: Check out the official tutorial, which is actually pretty good. If you are interested in web development you should be ready at that point to jump right in to the documentation of the web framework you will be working with; Python has many to choose from, with zope, cherrypy, pylons, and werkzeug all having good reputations. I would not try to search for things specifically meant to help you transition from Perl, which are not to be of as high of quality as references that can be useful for more people. A: This is the site you should really go to. There's a section called Getting Started which you should take a look. There are also recommendations on books. On top of that, you might also be interested in this on "idioms" A: If what you are looking at is succinct, concise reference to python then the book Python Essential Reference might be helpful.
Python for a Perl programmer
I am an experienced Perl developer with some degree of experience and/or familiarity with other languages (working experience with C/C++, school experience with Java and Scheme, and passing familiarity with many others). I might need to get some web work done in Python (most immediately, related to Google App Engine). As such, I'd like to ask SO overmind for good references on how to best learn Python for someone who's coming from Perl background (e.g. the emphasis would be on differences between the two and how to translate perl idiomatics into Python idiomatics, as opposed to generic Python references). Something also centered on Web development is even better. I'll take anything - articles, tutorials, books, sample apps? Thanks!
[ "I've recently had to make a similar transition for work reasons, and it's been pretty painful. For better or worse, Python has a very different philosophy and way of working than Perl, and getting used to that can be frustrating. The things I've found most useful have been\n\nSpend a few hours going through all the basics. I found the official tutorial quite good, if a little dry.\nA good reference book to look up basic stuff (\"how do I get the length of a string again?\"). The ones I've found most useful are the Python Pocket Reference and Python Essential Reference.\nTake a look at this handy Perl<->Python phrasebook (common tasks, side by side, in both languages).\nA reference for the Python approach to \"common tasks\". I use the Python Cookbook.\nAn ipython terminal open at all times to test syntax, introspect object methods etc.\nGet pip and easy-install (to install Python modules easily).\nLearn about unit tests fast. This is because without use strict you will feel crippled, and you will make many elementary mistakes which will appear as runtime errors. I recommend nose rather than the unittest framework that comes with the core install. unittest is very verbose if you're used to Test::More.\nCheck out Python questions on Stack Overflow. In particular, Python - Things one MUST avoid and Python 2.x gotcha’s and landmines are well worth a read.\n\nPersonally, I found Dive Into Python annoying and patronising, but it's freely available online, so you can form your own judgment on that.\n", "If you happen to be a fan of The Perl Cookbook, you might be interested in checking out PLEAC, the Programming Language Examples Alike Cookbook, specifically the section that shows the Perl Cookbook code translated into Python.\n", "Being a hardcore Perl programmer, all I can say is DO NOT BUY O'Reilly's \"Learning Python\". It is nowhere NEAR as good as \"Learning Perl\", and there's no equivalent I know of to Larry Wall's \"Programming Perl\", which is simply unbeatable.\nI've had the most success taking past Perl programs and translating them into Python, trying to make use of as many new techniques as possible.\n", "Check out the official tutorial, which is actually pretty good. If you are interested in web development you should be ready at that point to jump right in to the documentation of the web framework you will be working with; Python has many to choose from, with zope, cherrypy, pylons, and werkzeug all having good reputations.\nI would not try to search for things specifically meant to help you transition from Perl, which are not to be of as high of quality as references that can be useful for more people. \n", "This is the site you should really go to. There's a section called Getting Started which you should take a look. There are also recommendations on books. On top of that, you might also be interested in this on \"idioms\"\n", "If what you are looking at is succinct, concise reference to python then the book Python Essential Reference\nmight be helpful.\n" ]
[ 71, 16, 9, 4, 3, 2 ]
[ "I wouldn't try to compare Perl and Python too much in order to learn Python, especially since you have working knowledge of other languages. If you are unfamiliar with OOP/Functional programming aspects and just looking to work procedurally like in Perl, start learning the Python language constructs / syntax and then do a couple examples. if you are making a switch to OO or functional style paradigms, I would read up on OO fundamentals first, then start on Python syntax and examples...so you have a sort of mental blueprint of how things can be constructed before you start working with the actual materials. this is just my humble opinion however..\n" ]
[ -4 ]
[ "perl", "python" ]
stackoverflow_0002283034_perl_python.txt
Q: Interrupt method execution after arbitrary time in Python I have some method doA() that occasionally hangs for a while. Are there any common modules in Python that can control time of doA() execution and interrupt it? Of course, it may be implemented via threads, so simple wrapper around threading module may be good solution. In other words i'd like to have code like: import CoolAsyncControl CoolAsyncControl.call(self.doA, timeout = 10) A: You can use a threading.Timer to call thread.interrupt_main, as long as you're running doA in the main thread. Note that the syntax you desire is impossible because Python (like most languages, excepting e.g. Haskell) is "eager" -- arguments are entirely computed before a call is performed, so the self.doA() would run to completion before the call method has any chance to do anything about it! You'll have to use some syntax such as CoolIt.call(self.doA, args=(), timeout=100) so that call can set the timer up before performing the call to doA with the given arguments.
Interrupt method execution after arbitrary time in Python
I have some method doA() that occasionally hangs for a while. Are there any common modules in Python that can control time of doA() execution and interrupt it? Of course, it may be implemented via threads, so simple wrapper around threading module may be good solution. In other words i'd like to have code like: import CoolAsyncControl CoolAsyncControl.call(self.doA, timeout = 10)
[ "You can use a threading.Timer to call thread.interrupt_main, as long as you're running doA in the main thread. Note that the syntax you desire is impossible because Python (like most languages, excepting e.g. Haskell) is \"eager\" -- arguments are entirely computed before a call is performed, so the self.doA() would run to completion before the call method has any chance to do anything about it! You'll have to use some syntax such as\nCoolIt.call(self.doA, args=(), timeout=100)\n\nso that call can set the timer up before performing the call to doA with the given arguments.\n" ]
[ 6 ]
[]
[]
[ "asynchronous", "multithreading", "python" ]
stackoverflow_0002291129_asynchronous_multithreading_python.txt
Q: sqlalchemy 0.6 legacy database access? I feel like this should be simple, but i cant find a single example of it being done. As an example I have the following existing tables: CREATE TABLE `source` ( `source_id` tinyint(3) unsigned NOT NULL auto_increment, `name` varchar(40) default NULL, PRIMARY KEY (`source_id`), UNIQUE KEY `source_name` (`name`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; CREATE TABLE `event` ( `source_id` tinyint(3) unsigned NOT NULL default '0', `info` varchar(255) NOT NULL default '', `item` varchar(100) NOT NULL default '', PRIMARY KEY (`source_id`,`info`,`item`), KEY `event_fkindex1` (`source_id`), CONSTRAINT `event_fk1` FOREIGN KEY (`source_id`) REFERENCES `source` (`source_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; I'd like to use sqlalchemy 0.6 to add a lot of rows to the events table. I've seen some sqlsoup examples, but really hate the way it accesses the db by constantly calling the db object. I followed the docs for the db reflection stuff and got this far: import sqlalchemy from sqlalchemy import Table, Column, MetaData, create_engine from sqlalchemy.orm import sessionmaker engine = create_engine('mysql://user:pass@server/db', echo=True) metadata = MetaData() source = Table('source', metadata, autoload=True, autoload_with=engine) Session = sessionmaker(bind=engine) session = Session() session.query(source).first() This returns a really ugly object. I really want the mapper functionality of the sqlalchemy ORM so I can construct Event objects to insert into the DB. I looked at the sqlsoup stuff: from sqlalchemy.ext.sqlsoup import SqlSoup db = SqlSoup(engine) db.sources.all() #this kinda works out bet But I couldn't figure out how to add objects form this point. I'm not even sure this is what I want, I'd like to be able to follow the tutorial and the declarative_base stuff. Is this possible without having to rewrite a class to model the whole table structure? If its not, can someone show me how I'd do this in this example? Can someone set me down the right path for getting the mapper stuff to work? A: You can use a predefined/autoloaded table with declarative_base by assigning it to the __table__ attribute. The columns are picked up from the table, but you'll still have declare any relations you want to use. class Source(Base): __table__ = source class Event(Base): __table__ = event source = relation(Source) However if you are going to be inserting a huge amount of rows, then going around the ORM and using executemany will get you a large performance increase. You can use execute many like this: conn = engine.connect() conn.execute(event.insert(),[ {'source_id': 1, 'info': 'xyz', 'item': 'foo'}, {'source_id': 1, 'info': 'xyz', 'item': 'bar'}, ... ])
sqlalchemy 0.6 legacy database access?
I feel like this should be simple, but i cant find a single example of it being done. As an example I have the following existing tables: CREATE TABLE `source` ( `source_id` tinyint(3) unsigned NOT NULL auto_increment, `name` varchar(40) default NULL, PRIMARY KEY (`source_id`), UNIQUE KEY `source_name` (`name`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; CREATE TABLE `event` ( `source_id` tinyint(3) unsigned NOT NULL default '0', `info` varchar(255) NOT NULL default '', `item` varchar(100) NOT NULL default '', PRIMARY KEY (`source_id`,`info`,`item`), KEY `event_fkindex1` (`source_id`), CONSTRAINT `event_fk1` FOREIGN KEY (`source_id`) REFERENCES `source` (`source_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; I'd like to use sqlalchemy 0.6 to add a lot of rows to the events table. I've seen some sqlsoup examples, but really hate the way it accesses the db by constantly calling the db object. I followed the docs for the db reflection stuff and got this far: import sqlalchemy from sqlalchemy import Table, Column, MetaData, create_engine from sqlalchemy.orm import sessionmaker engine = create_engine('mysql://user:pass@server/db', echo=True) metadata = MetaData() source = Table('source', metadata, autoload=True, autoload_with=engine) Session = sessionmaker(bind=engine) session = Session() session.query(source).first() This returns a really ugly object. I really want the mapper functionality of the sqlalchemy ORM so I can construct Event objects to insert into the DB. I looked at the sqlsoup stuff: from sqlalchemy.ext.sqlsoup import SqlSoup db = SqlSoup(engine) db.sources.all() #this kinda works out bet But I couldn't figure out how to add objects form this point. I'm not even sure this is what I want, I'd like to be able to follow the tutorial and the declarative_base stuff. Is this possible without having to rewrite a class to model the whole table structure? If its not, can someone show me how I'd do this in this example? Can someone set me down the right path for getting the mapper stuff to work?
[ "You can use a predefined/autoloaded table with declarative_base by assigning it to the __table__ attribute. The columns are picked up from the table, but you'll still have declare any relations you want to use.\nclass Source(Base):\n __table__ = source\n\nclass Event(Base):\n __table__ = event\n source = relation(Source)\n\nHowever if you are going to be inserting a huge amount of rows, then going around the ORM and using executemany will get you a large performance increase. You can use execute many like this:\nconn = engine.connect()\nconn.execute(event.insert(),[\n {'source_id': 1, 'info': 'xyz', 'item': 'foo'},\n {'source_id': 1, 'info': 'xyz', 'item': 'bar'},\n ...\n])\n\n" ]
[ 2 ]
[]
[]
[ "legacy_database", "python", "sqlalchemy" ]
stackoverflow_0002285062_legacy_database_python_sqlalchemy.txt
Q: SQLAlchemy.declarative and deferred column loading is it possible to specify some columns in the SQLAlchemy to be deferred-loading? I am using the sqlalchemy.ext.declarative module to define my mapping, example: from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class SomeClass(Base): __tablename__ = 'some_table' id = Column(Integer, primary_key=True) name = Column(String(50)) I want for example the column name be lazy loaded, how can I accomplish that? Thank you Jan A: Just add deferred() around the column declaration: class SomeClass(Base): __tablename__ = 'some_table' id = Column(Integer, primary_key=True) name = deferred(Column(String(50))) A: Do not define the mapping for the columns which you want to load on demand. Then configure those as described in the Deferred Column Loading using mapper object. Modified code here: from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class SomeClass(Base): __tablename__ = 'some_table' id = Column(Integer, primary_key=True) name = Column(String(50)) #big_name = Column(String(500)) SomeClass.__table__.append_column(Column('big_name', String(500))) SomeClass.__mapper__.add_property('big_name', deferred(SomeClass.__table__.c.big_name)) Running this test code: c = session.query(SomeClass).first() # here SQL is loading all configured properties, but big_name print "c: ", c # only here another SQL request is made to load the property print "big_name: ", c.big_name produces log extract: ... INFO sqlalchemy.engine.base.Engine.0x...77d0 SELECT some_table.id AS some_table_id, some_table.name AS some_table_name FROM some_table LIMIT 1 OFFSET 0 ... INFO sqlalchemy.engine.base.Engine.0x...77d0 SELECT some_table.big_name AS some_table_big_name FROM some_table WHERE some_table.id = ?
SQLAlchemy.declarative and deferred column loading
is it possible to specify some columns in the SQLAlchemy to be deferred-loading? I am using the sqlalchemy.ext.declarative module to define my mapping, example: from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class SomeClass(Base): __tablename__ = 'some_table' id = Column(Integer, primary_key=True) name = Column(String(50)) I want for example the column name be lazy loaded, how can I accomplish that? Thank you Jan
[ "Just add deferred() around the column declaration:\nclass SomeClass(Base):\n __tablename__ = 'some_table'\n id = Column(Integer, primary_key=True)\n name = deferred(Column(String(50)))\n\n", "Do not define the mapping for the columns which you want to load on demand. Then configure those as described in the Deferred Column Loading using mapper object. Modified code here:\nfrom sqlalchemy.ext.declarative import declarative_base\n\nBase = declarative_base()\n\nclass SomeClass(Base):\n __tablename__ = 'some_table'\n id = Column(Integer, primary_key=True)\n name = Column(String(50))\n #big_name = Column(String(500))\n\nSomeClass.__table__.append_column(Column('big_name', String(500)))\nSomeClass.__mapper__.add_property('big_name', deferred(SomeClass.__table__.c.big_name))\n\nRunning this test code:\nc = session.query(SomeClass).first()\n# here SQL is loading all configured properties, but big_name\nprint \"c: \", c\n# only here another SQL request is made to load the property\nprint \"big_name: \", c.big_name\n\nproduces log extract:\n... INFO sqlalchemy.engine.base.Engine.0x...77d0 SELECT some_table.id AS some_table_id, some_table.name AS some_table_name \nFROM some_table \nLIMIT 1 OFFSET 0\n\n... INFO sqlalchemy.engine.base.Engine.0x...77d0 SELECT some_table.big_name AS some_table_big_name \nFROM some_table \nWHERE some_table.id = ?\n\n" ]
[ 12, 2 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0002289401_python_sqlalchemy.txt
Q: Django. Retrieving and opening a zip file from HDD I have a path to a zip file. I don't know how to retrieve the file from the hard drive or open that zip file. Does anyone know? The zip file is a zip file, but it's really a .epub file. A: http://docs.python.org/library/zipfile.html >>> import zipfile >>> path = "example/path.epub" >>> epub = zipfile.ZipFile(open(path)) >>> epub.namelist() ['some_file.txt'] >>> file = epub.open('some_file.txt') >>> file.read() A: You don't need anything Django specific, just use the Python standard library, with the class ZipFile(file_name[, mode[, compression[, allowZip64]]]) from the zipfile package.
Django. Retrieving and opening a zip file from HDD
I have a path to a zip file. I don't know how to retrieve the file from the hard drive or open that zip file. Does anyone know? The zip file is a zip file, but it's really a .epub file.
[ "http://docs.python.org/library/zipfile.html\n>>> import zipfile\n>>> path = \"example/path.epub\"\n>>> epub = zipfile.ZipFile(open(path))\n>>> epub.namelist()\n ['some_file.txt']\n>>> file = epub.open('some_file.txt')\n>>> file.read()\n\n", "You don't need anything Django specific, just use the Python standard library, with the class ZipFile(file_name[, mode[, compression[, allowZip64]]]) from the zipfile package.\n" ]
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002291913_django_python.txt
Q: python timer mystery Well, at least a mystery to me. Consider the following: import time import signal def catcher(signum, _): print "beat!" signal.signal(signal.SIGALRM, catcher) signal.setitimer(signal.ITIMER_REAL, 2, 2) while True: time.sleep(5) Works as expected i.e. delivers a "beat!" message every 2 seconds. Next, no output is produced: import time import signal def catcher(signum, _): print "beat!" signal.signal(signal.SIGVTALRM, catcher) signal.setitimer(signal.ITIMER_VIRTUAL, 2, 2) while True: time.sleep(5) Where is the issue? A: From my system's man setitimer (emphasis mine): The system provides each process with three interval timers, each decrementing in a distinct time domain. When any timer expires, a signal is sent to the process, and the timer (potentially) restarts. ITIMER_REAL decrements in real time, and delivers SIGALRM upon expiration. ITIMER_VIRTUAL decrements only when the process is executing, and delivers SIGVTALRM upon expiration. Did you just miss that your process isn't executing while sleeping? It's going to take an awfully long time for you to accrue actually-used time with that loop. A: The signal.ITIMER_VIRTUAL only counts down with the process is running. time.sleep(5) suspends the process so the timer doesn't decrement.
python timer mystery
Well, at least a mystery to me. Consider the following: import time import signal def catcher(signum, _): print "beat!" signal.signal(signal.SIGALRM, catcher) signal.setitimer(signal.ITIMER_REAL, 2, 2) while True: time.sleep(5) Works as expected i.e. delivers a "beat!" message every 2 seconds. Next, no output is produced: import time import signal def catcher(signum, _): print "beat!" signal.signal(signal.SIGVTALRM, catcher) signal.setitimer(signal.ITIMER_VIRTUAL, 2, 2) while True: time.sleep(5) Where is the issue?
[ "From my system's man setitimer (emphasis mine):\n\nThe system provides each process with three interval timers, each decrementing in a distinct time domain. When any timer expires, a signal is sent to the process, and the timer (potentially) restarts.\nITIMER_REAL decrements in real time, and delivers SIGALRM upon expiration.\nITIMER_VIRTUAL decrements only when the process is executing, and delivers SIGVTALRM upon expiration.\n\nDid you just miss that your process isn't executing while sleeping? It's going to take an awfully long time for you to accrue actually-used time with that loop.\n", "The signal.ITIMER_VIRTUAL only counts down with the process is running. time.sleep(5) suspends the process so the timer doesn't decrement.\n" ]
[ 16, 4 ]
[]
[]
[ "python", "signals", "timer" ]
stackoverflow_0002292054_python_signals_timer.txt
Q: uncompressing tar.Z file with python? I need to write a python script that retrieves tar.Z files from an FTP server, and uncompress them on a windows machine. tar.Z, if I understood correctly is the result of a compress command in Unix. Python doesn't seem to know how to handle these, it's not gz, nor bz2 or zip. Does anyone know a library that would handle these ? Thanks in advance A: If GZIP -- the application -- can handle it, you have two choices. Try the Python gzip library. It may work. Use subprocess Popen to run gzip for you. It may be an InstallShield .Z file. You may want to use InstallShield to unpack it and extract the .TAR file. Again, you may be able to use subprocess Popen to process the file. It may also be a "LZW compressed file". Look at this library, it may help. http://www.chilkatsoft.com/compression-python.asp A: Since you target a specific platform (Windows), the simplest solution may be to run gzip in a system call: http://www.gzip.org/#exe Are there other requirements in your project that the decompression needs to be done in Python? A: A plain Python module that uncompresses is inexistant, AFAIK, but it's feasible to build one, given some knowledge: the .Z format header specification the .Z compression format Almost all necessary information can be found the unarchiver CompressAlgorithm. Additional info from wikipedia for adaptive LZW and perhaps the compress man page. Basically, you read the first three bytes (first two are magic bytes) to modify your algorithm, and then start reading and decompressing. There's a lot of bit fiddling (.Z files begin having 9-bit tokens, up to 16-bit ones and then resetting the symbol table to the initial 256+2 values), which probably you'll deal with doing binary operations (&, <<= etc).
uncompressing tar.Z file with python?
I need to write a python script that retrieves tar.Z files from an FTP server, and uncompress them on a windows machine. tar.Z, if I understood correctly is the result of a compress command in Unix. Python doesn't seem to know how to handle these, it's not gz, nor bz2 or zip. Does anyone know a library that would handle these ? Thanks in advance
[ "If GZIP -- the application -- can handle it, you have two choices.\n\nTry the Python gzip library. It may work.\nUse subprocess Popen to run gzip for you.\n\nIt may be an InstallShield .Z file. You may want to use InstallShield to unpack it and extract the .TAR file. Again, you may be able to use subprocess Popen to process the file.\nIt may also be a \"LZW compressed file\". Look at this library, it may help.\nhttp://www.chilkatsoft.com/compression-python.asp\n", "Since you target a specific platform (Windows), the simplest solution may be to run gzip in a system call: http://www.gzip.org/#exe\nAre there other requirements in your project that the decompression needs to be done in Python?\n", "A plain Python module that uncompresses is inexistant, AFAIK, but it's feasible to build one, given some knowledge:\n\nthe .Z format header specification\nthe .Z compression format\n\nAlmost all necessary information can be found the unarchiver CompressAlgorithm. Additional info from wikipedia for adaptive LZW and perhaps the compress man page.\nBasically, you read the first three bytes (first two are magic bytes) to modify your algorithm, and then start reading and decompressing.\nThere's a lot of bit fiddling (.Z files begin having 9-bit tokens, up to 16-bit ones and then resetting the symbol table to the initial 256+2 values), which probably you'll deal with doing binary operations (&, <<= etc).\n" ]
[ 1, 0, 0 ]
[]
[]
[ "compression", "python", "tar" ]
stackoverflow_0002272199_compression_python_tar.txt
Q: IntelliJ Python plug-in I've been using IntelliJ IDEA at the day job for Java development for a few weeks now. I'm really impressed with it and I'm looking to extend it for other programming languages that I tinker with, starting with Python. I found this plug-in, pythonid. I figured I would look for some input on the Stack before proceeding. First, has anyone given pythonid a try and and have any feedback about it (the site for it is a bit weak)? And second, sre there any other Python plug-ins for IntelliJ IDEA that might be better? A: There is currently an EAP for the Intellij Python IDE (PyCharm): here A: I've tried Pythonid before and found it very limited. There's a new Python plugin from JetBrains, the people that make IDEA, which looks pretty nice, though it's still very unfinished.
IntelliJ Python plug-in
I've been using IntelliJ IDEA at the day job for Java development for a few weeks now. I'm really impressed with it and I'm looking to extend it for other programming languages that I tinker with, starting with Python. I found this plug-in, pythonid. I figured I would look for some input on the Stack before proceeding. First, has anyone given pythonid a try and and have any feedback about it (the site for it is a bit weak)? And second, sre there any other Python plug-ins for IntelliJ IDEA that might be better?
[ "There is currently an EAP for the Intellij Python IDE (PyCharm): here\n", "I've tried Pythonid before and found it very limited. There's a new Python plugin from JetBrains, the people that make IDEA, which looks pretty nice, though it's still very unfinished.\n" ]
[ 5, 4 ]
[]
[]
[ "ide", "java", "python" ]
stackoverflow_0000376765_ide_java_python.txt
Q: ID3 Decision Tree with Numeric Values I'm looking for a ID3 decision tree implementation in Python or any languages which takes a validation and a testing file as an input and returns predictions. I found this and this but I couldn't adapt them to numeric values, e.g. to Iris dataset. Do you know any ID3 tree implementation that works from console or any written in Python? Or any suggestion how to use this with numeric values will be awesome. A: I have a similar algorithm C4.5 written in python. It work from console. If you are interested I put it here. Sorry for a post if you need not this. BTW, I have tested it on Iris data set :) Update: I have uploaded both: code and data: c4.5 - http://pastebin.ca/1802066 iris.data - http://pastebin.ca/1802067 I hope it will help you. BTW, program also can draw a tree into "png" via graphViz
ID3 Decision Tree with Numeric Values
I'm looking for a ID3 decision tree implementation in Python or any languages which takes a validation and a testing file as an input and returns predictions. I found this and this but I couldn't adapt them to numeric values, e.g. to Iris dataset. Do you know any ID3 tree implementation that works from console or any written in Python? Or any suggestion how to use this with numeric values will be awesome.
[ "I have a similar algorithm C4.5 written in python. It work from console. If you are interested I put it here. \nSorry for a post if you need not this.\nBTW, I have tested it on Iris data set :)\nUpdate:\nI have uploaded both: code and data:\n\nc4.5 - http://pastebin.ca/1802066\niris.data - http://pastebin.ca/1802067\n\nI hope it will help you.\nBTW, program also can draw a tree into \"png\" via graphViz\n" ]
[ 2 ]
[]
[]
[ "decision_tree", "id3", "python" ]
stackoverflow_0002292540_decision_tree_id3_python.txt
Q: What Python/IronPython web development framework work on the Microsoft technology stack? I started learning Python using the IronPython implementation. I'd like to do some web development now. I'm looking for a python web development framework that works on the Microsoft technology stack (IIS + MS SQL Server). Django looks like an interesting framework but based on what I have read, getting it to work on the Microsoft technology stack seems very hard or not possible. I want to lean a web framework that leverages python strengths, so ASP.NET is not an option here. The reasons why I want to do Python on full Microsoft stack are: We are a .Net shop and our production servers run the full Microsoft stack With IronPython, I'll be able to interop with our product's existing .Net Libraries Our existing database runs in SQL Server and I want to develop an app that queries that database Deploying my Python projects to our server will not be allowed if I have to install another web server Any recommendations? A: Working with the full MS stack will be hard as not many FLOSS frameworks aim there. You'll have better luck with a WAMP (Windows/Apache/MySQL-PostgreSQL/Python) approach. That being said, Django works on Windows, and even can be made to work under IIS by using PyISAPIe and MS SQL Server support. TurboGears can also be installed on Windows, and has MS SQL Server support through its ORM backends. Trying to use -AMP under Windows can be an exercise in masochism sometimes. It can be done, but using these frameworks under Linux/BSD is much much easier and enjoyable. You should definitely try it. A: While perhaps not entirely mature, isapi-wsgi looks like a promising way to run the WSGI intermediate layer on IIS (I have no hands-on experience with it, but seems worth a try!). Once you have WSGI running just about any Python web framework, including Django, should run on top of it (my personal favorite is werkzeug, a non-framework of utilities on top of WSGI, but I realize it's probably a lower level of abstraction than most web developers prefer for typical web apps and websited). django-mssql should let Django run fine on SQL Server and looks reasonably mature (again, no hands-on experience). If you prefer a more sophisticated obj-relational mapper, SQLalchemy claims to support MS-SQL "out of the box" with minor restrictions (e.g., no more than one IDENTITY column per table). If you want to stick with IronPython, but can live with using SQLite instead of MS-Server, it should also be possible to use Django on IronPython with IIS. A: Django does in theory run on Windows, but using Apache and MySQL. It's not possible (and certainly not recommended) to run it on IIS. I know you totally didn't ask this, but I have to advise that if you really want to get into Python web development then looking into a Linux technology stack is definitely the recommended approach. :)
What Python/IronPython web development framework work on the Microsoft technology stack?
I started learning Python using the IronPython implementation. I'd like to do some web development now. I'm looking for a python web development framework that works on the Microsoft technology stack (IIS + MS SQL Server). Django looks like an interesting framework but based on what I have read, getting it to work on the Microsoft technology stack seems very hard or not possible. I want to lean a web framework that leverages python strengths, so ASP.NET is not an option here. The reasons why I want to do Python on full Microsoft stack are: We are a .Net shop and our production servers run the full Microsoft stack With IronPython, I'll be able to interop with our product's existing .Net Libraries Our existing database runs in SQL Server and I want to develop an app that queries that database Deploying my Python projects to our server will not be allowed if I have to install another web server Any recommendations?
[ "Working with the full MS stack will be hard as not many FLOSS frameworks aim there. You'll have better luck with a WAMP (Windows/Apache/MySQL-PostgreSQL/Python) approach.\nThat being said, Django works on Windows, and even can be made to work under IIS by using PyISAPIe and MS SQL Server support.\nTurboGears can also be installed on Windows, and has MS SQL Server support through its ORM backends.\nTrying to use -AMP under Windows can be an exercise in masochism sometimes. It can be done, but using these frameworks under Linux/BSD is much much easier and enjoyable. You should definitely try it.\n", "While perhaps not entirely mature, isapi-wsgi looks like a promising way to run the WSGI intermediate layer on IIS (I have no hands-on experience with it, but seems worth a try!). Once you have WSGI running just about any Python web framework, including Django, should run on top of it (my personal favorite is werkzeug, a non-framework of utilities on top of WSGI, but I realize it's probably a lower level of abstraction than most web developers prefer for typical web apps and websited).\ndjango-mssql should let Django run fine on SQL Server and looks reasonably mature (again, no hands-on experience). If you prefer a more sophisticated obj-relational mapper, SQLalchemy claims to support MS-SQL \"out of the box\" with minor restrictions (e.g., no more than one IDENTITY column per table).\nIf you want to stick with IronPython, but can live with using SQLite instead of MS-Server, it should also be possible to use Django on IronPython with IIS.\n", "Django does in theory run on Windows, but using Apache and MySQL. It's not possible (and certainly not recommended) to run it on IIS.\nI know you totally didn't ask this, but I have to advise that if you really want to get into Python web development then looking into a Linux technology stack is definitely the recommended approach. :)\n" ]
[ 7, 3, 1 ]
[]
[]
[ "ironpython", "python" ]
stackoverflow_0002292775_ironpython_python.txt
Q: Is windows's setsockopt broken? I want to be able to reuse some ports, and that's why I'm using setsockopt on my sockets, with the following code: sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) However, this doesn't really work. I'm not getting a bind error either, but the server socket just isn't responding (it seems to start , but if I try to connect to it, it doesn't enter the select loop). This behaviour appears if the script ended unexpectedly, and if I change the port the server is listening on, everything works again. Can you provide some advice? EDIT: I renamed the socket to sock. It was just a name I chose for this code snippet. A: It appears that SO_REUSEADDR has different semantics on Windows vs Unix. See this msdn article (particularly the chart below "Using SO_EXCLUSIVEADDRUSE") and this unix faq. Also, see this python bug discussion, this twisted bug discussion, and this list of differences between Windows and Unix sockets. A: setsockopt is a method of a socket object. module socket doesn't have a setsockopt attribute.
Is windows's setsockopt broken?
I want to be able to reuse some ports, and that's why I'm using setsockopt on my sockets, with the following code: sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) However, this doesn't really work. I'm not getting a bind error either, but the server socket just isn't responding (it seems to start , but if I try to connect to it, it doesn't enter the select loop). This behaviour appears if the script ended unexpectedly, and if I change the port the server is listening on, everything works again. Can you provide some advice? EDIT: I renamed the socket to sock. It was just a name I chose for this code snippet.
[ "It appears that SO_REUSEADDR has different semantics on Windows vs Unix.\nSee this msdn article (particularly the chart below \"Using SO_EXCLUSIVEADDRUSE\") and this unix faq.\nAlso, see this python bug discussion, this twisted bug discussion, and this list of differences between Windows and Unix sockets.\n", "setsockopt is a method of a socket object. module socket doesn't have a setsockopt attribute.\n" ]
[ 3, 1 ]
[]
[]
[ "python", "setsockopt", "sockets", "windows" ]
stackoverflow_0000796957_python_setsockopt_sockets_windows.txt
Q: Content of file to tree format using python I have a file containing a file "dir.txt" with the below data: /home/abc/a.txt /home/abc/b.txt /home/xyz/test /home/xyz/test/d.txt /home/xyz/test/e.txt /home/xyz/test/f.txt /home/xyz /home/xyz/g.txt I want to parse the file and get the output like /home/abc/a.txt b.txt /home/xyz/test/d.txt e.txt f.txt /home/xyz/g.txt Using python, basically need to print the content in a tree format. How would I process it? A: you need to use os.path.split on every path, find the first dirname and print path as it is. find it length and print so many spaces before next basename, on change of the dirname repeat as before. >>> import os.path >>> olddir = None >>> for name in open('input.txt'): dirname, fname = os.path.split(name) if olddir != dirname: prefix = ' ' * (len(dirname) +1) olddir = dirname print(name) else: print(prefix + fname) /home/abc/a.txt b.txt /home/xyz/test/d.txt e.txt f.txt /home/xyz/g.txt A: Try this: import os.path txt = """/home/abc/a.txt /home/abc/b.txt /home/xyz/test/d.txt /home/xyz/test/e.txt /home/xyz/test/f.txt /home/xyz/g.txt""" last_d = '' for l in txt.split('\n'): (d, n) = os.path.split(l) if d == last_d: d = ' ' * len(last_d) else: last_d = d print('%s/%s' % (d, n)) A: @Op,use a dictionary. Use the paths as the key and the file names as values from collections import defaultdict d=defaultdict(list) for line in open("file"): line=line.strip() s='/'.join(line.split("/")[:-1]) d[s].append(line.split("/")[-1]) for i,j in d.iteritems(): print i,j output $ ./python.py /home/xyz ['g.txt'] /home/xyz/test ['d.txt', 'e.txt', 'f.txt'] /home/abc ['a.txt', 'b.txt'] Do the formatting as described by the answers others had posted. A: >>> filenames="""/home/abc/a.txt ... /home/abc/b.txt ... /home/xyz/test/d.txt ... /home/xyz/test/e.txt ... /home/xyz/test/f.txt ... /home/xyz/g.txt""".split() >>> >>> import os >>> prev='' >>> for n in filenames: ... path,name = os.path.split(n) ... if path==prev: ... print " "*len(prev)+" "+name ... else: ... print n ... prev=path ... /home/abc/a.txt b.txt /home/xyz/test/d.txt e.txt f.txt /home/xyz/g.txt A: This is an alternate take that offers a different output, just in case the OP would prefer this format: /home/abc/a.txt b.txt xyz/test/d.txt e.txt f.txt g.txt then this code: import os def pretty_printer(seq_of_strings): previous_line= '' for line in seq_of_strings: last_sep= os.path.commonprefix([previous_line, line]).rfind(os.path.sep)+1 yield ' '*last_sep + line[last_sep:] previous_line= line might do the trick. Should the OP comment that they don't need it at all, I'll delete this answer.
Content of file to tree format using python
I have a file containing a file "dir.txt" with the below data: /home/abc/a.txt /home/abc/b.txt /home/xyz/test /home/xyz/test/d.txt /home/xyz/test/e.txt /home/xyz/test/f.txt /home/xyz /home/xyz/g.txt I want to parse the file and get the output like /home/abc/a.txt b.txt /home/xyz/test/d.txt e.txt f.txt /home/xyz/g.txt Using python, basically need to print the content in a tree format. How would I process it?
[ "you need to use os.path.split on every path, find the first dirname and print path as it is. find it length and print so many spaces before next basename, on change of the dirname repeat as before.\n>>> import os.path \n>>> olddir = None\n>>> for name in open('input.txt'):\n dirname, fname = os.path.split(name)\n if olddir != dirname:\n prefix = ' ' * (len(dirname) +1)\n olddir = dirname\n print(name)\n else:\n print(prefix + fname)\n\n\n/home/abc/a.txt\n b.txt\n/home/xyz/test/d.txt\n e.txt\n f.txt\n/home/xyz/g.txt\n\n", "Try this:\nimport os.path\n\ntxt = \"\"\"/home/abc/a.txt\n/home/abc/b.txt\n/home/xyz/test/d.txt\n/home/xyz/test/e.txt\n/home/xyz/test/f.txt\n/home/xyz/g.txt\"\"\"\n\nlast_d = ''\nfor l in txt.split('\\n'):\n (d, n) = os.path.split(l)\n if d == last_d:\n d = ' ' * len(last_d)\n else:\n last_d = d\n print('%s/%s' % (d, n))\n\n", "@Op,use a dictionary. Use the paths as the key and the file names as values\nfrom collections import defaultdict\nd=defaultdict(list)\nfor line in open(\"file\"):\n line=line.strip()\n s='/'.join(line.split(\"/\")[:-1])\n d[s].append(line.split(\"/\")[-1])\n\nfor i,j in d.iteritems():\n print i,j\n\noutput\n$ ./python.py\n/home/xyz ['g.txt']\n/home/xyz/test ['d.txt', 'e.txt', 'f.txt']\n/home/abc ['a.txt', 'b.txt']\n\nDo the formatting as described by the answers others had posted.\n", ">>> filenames=\"\"\"/home/abc/a.txt\n... /home/abc/b.txt\n... /home/xyz/test/d.txt\n... /home/xyz/test/e.txt\n... /home/xyz/test/f.txt\n... /home/xyz/g.txt\"\"\".split()\n>>> \n>>> import os\n>>> prev=''\n>>> for n in filenames:\n... path,name = os.path.split(n) \n... if path==prev:\n... print \" \"*len(prev)+\" \"+name\n... else:\n... print n\n... prev=path\n... \n/home/abc/a.txt\n b.txt\n/home/xyz/test/d.txt\n e.txt\n f.txt\n/home/xyz/g.txt\n\n", "This is an alternate take that offers a different output, just in case the OP would prefer this format:\n/home/abc/a.txt\n b.txt\n xyz/test/d.txt\n e.txt\n f.txt\n g.txt\n\nthen this code:\nimport os\n\ndef pretty_printer(seq_of_strings):\n previous_line= ''\n for line in seq_of_strings:\n last_sep= os.path.commonprefix([previous_line, line]).rfind(os.path.sep)+1\n yield ' '*last_sep + line[last_sep:]\n previous_line= line\n\nmight do the trick.\nShould the OP comment that they don't need it at all, I'll delete this answer.\n" ]
[ 4, 2, 2, 0, 0 ]
[]
[]
[ "python", "treeview" ]
stackoverflow_0002288570_python_treeview.txt
Q: Django decorator getting a WSGIRequest and not the expected function argument I'm creating a decorator for Django views that will check permissions in a non-Django-managed database. Here is the decorator: def check_ownership(failure_redirect_url='/', *args, **kwargs): def _check_ownership(view): def _wrapper(request, csi=None): try: opb_id=request.user.get_profile().opb_id if opb_id and csi and model.is_users_server(opb_id, csi): return view(*args, **kwargs) except Exception, e: logger.debug("Exception checking ownership: %s", str(e)) return HttpResponseRedirect(failure_redirect_url) _wrapper.__dict__=view.__dict__ _wrapper.__doc__=view.__doc__ return _wrapper return _check_ownership And this is how it is being used: @check_ownership def my_view(request, csi=None): """Process my request""" check_ownership() is being called and returning _check_ownership(). When _check_ownership() is called, it is being called with a WSGIRequest object which is what I would have expected _wrapper() to be called with. Anybody have any idea where my method has gone and how I can get it back? I don't have a way to chain to the next decorator or the actual view the way things stand. Oh, Python 2.4.3 on CentOS and Django 1.1.1. I want my function back! ;) Thanks. tj A: @check_ownership def my_view(request, csi=None): ... Translates into: def my_view(request, csi=None): ... my_view = check_ownership(my_view) but check_ownership does not accept a function, but _check_ownership does. This might be where your problem lies. A: So the issue has to do with how the decorator is being called. You get different behavior with these: @my_decorator versus @my_decorator(someparam='someval') In the first case, you get the callable passed directly to my_decorator. In the second case, you don't, but the callable you return from my_decorator will. I'm sure there is some esoteric reason for this, but it is, IMNSO, lame. It makes creating decorators with default arguments much less clear than they ought to be.
Django decorator getting a WSGIRequest and not the expected function argument
I'm creating a decorator for Django views that will check permissions in a non-Django-managed database. Here is the decorator: def check_ownership(failure_redirect_url='/', *args, **kwargs): def _check_ownership(view): def _wrapper(request, csi=None): try: opb_id=request.user.get_profile().opb_id if opb_id and csi and model.is_users_server(opb_id, csi): return view(*args, **kwargs) except Exception, e: logger.debug("Exception checking ownership: %s", str(e)) return HttpResponseRedirect(failure_redirect_url) _wrapper.__dict__=view.__dict__ _wrapper.__doc__=view.__doc__ return _wrapper return _check_ownership And this is how it is being used: @check_ownership def my_view(request, csi=None): """Process my request""" check_ownership() is being called and returning _check_ownership(). When _check_ownership() is called, it is being called with a WSGIRequest object which is what I would have expected _wrapper() to be called with. Anybody have any idea where my method has gone and how I can get it back? I don't have a way to chain to the next decorator or the actual view the way things stand. Oh, Python 2.4.3 on CentOS and Django 1.1.1. I want my function back! ;) Thanks. tj
[ "@check_ownership\ndef my_view(request, csi=None):\n ...\n\nTranslates into:\ndef my_view(request, csi=None):\n ...\nmy_view = check_ownership(my_view)\n\nbut check_ownership does not accept a function, but _check_ownership does. This might be where your problem lies.\n", "So the issue has to do with how the decorator is being called. You get different behavior with these:\n@my_decorator\n\nversus\n@my_decorator(someparam='someval')\n\nIn the first case, you get the callable passed directly to my_decorator. In the second case, you don't, but the callable you return from my_decorator will.\nI'm sure there is some esoteric reason for this, but it is, IMNSO, lame. It makes creating decorators with default arguments much less clear than they ought to be.\n" ]
[ 1, 0 ]
[]
[]
[ "decorator", "django", "python" ]
stackoverflow_0002291616_decorator_django_python.txt
Q: Overloading embedded Python functions using PyArg_ParseTuple If I'm trying to overload an embedded Python function so that the second argument can be a long or an Object, is there a standard way to do it? Is this it? What I'm trying now (names changed to protect the innocent): bool UseLongVar2 = true; if (!PyArg_ParseTuple(args, "ll:foo", &LongVar1, &LongVar2)) { PyErr_Clear(); if (!PyArg_ParseTuple(args, "lO&:foo", &LongVar1, convertObject, &Object)) { UseLongVar2 = false; return NULL; } } A: What I normally do is have two C functions that take the different arguments. The "python-facing" function's job is to parse out the arguments, call the appropriate C function, and build the return value if any. This is pretty common when, for example, you want to allow both byte and Unicode strings. Here is an example of what I mean. // Silly example: get the length of a string, supporting Unicode and byte strings static PyObject* getlen_py(PyObject *self, PyObject *args) { // Unpack our argument (error handling omitted...) PyObject *arg = NULL; PyArg_UnpackTuple(args, "getlen", 1, 1, arg) ; if ( PyUnicode_Check(arg) ) { // It's a Unicode string return PyInt_FromLong(getlen_w(PyUnicode_AS_UNICODE(arg))) ; } else { // It's a byte string return PyInt_FromLong(getlen_a(PyString_AS_STRING(arg))) ; } }
Overloading embedded Python functions using PyArg_ParseTuple
If I'm trying to overload an embedded Python function so that the second argument can be a long or an Object, is there a standard way to do it? Is this it? What I'm trying now (names changed to protect the innocent): bool UseLongVar2 = true; if (!PyArg_ParseTuple(args, "ll:foo", &LongVar1, &LongVar2)) { PyErr_Clear(); if (!PyArg_ParseTuple(args, "lO&:foo", &LongVar1, convertObject, &Object)) { UseLongVar2 = false; return NULL; } }
[ "What I normally do is have two C functions that take the different arguments. The \"python-facing\" function's job is to parse out the arguments, call the appropriate C function, and build the return value if any.\nThis is pretty common when, for example, you want to allow both byte and Unicode strings.\nHere is an example of what I mean.\n// Silly example: get the length of a string, supporting Unicode and byte strings\nstatic PyObject* getlen_py(PyObject *self, PyObject *args)\n{\n // Unpack our argument (error handling omitted...)\n PyObject *arg = NULL;\n PyArg_UnpackTuple(args, \"getlen\", 1, 1, arg) ;\n\n if ( PyUnicode_Check(arg) )\n {\n // It's a Unicode string\n return PyInt_FromLong(getlen_w(PyUnicode_AS_UNICODE(arg))) ;\n }\n else\n {\n // It's a byte string\n return PyInt_FromLong(getlen_a(PyString_AS_STRING(arg))) ;\n }\n}\n\n" ]
[ 3 ]
[]
[]
[ "embedded_language", "overloading", "python" ]
stackoverflow_0002291740_embedded_language_overloading_python.txt
Q: Why dictionaries appear to be reversed? Why dictionaries in python appears reversed? >>> a = {'one': '1', 'two': '2', 'three': '3', 'four': '4'} >>> a {'four': '4', 'three': '3', 'two': '2', 'one': '1'} How can I fix this? A: Dictionaries in python (and hash tables in general) are unordered. In python you can use the sort() method on the keys to sort them. A: Dictionaries have no intrinsic order. You'll have to either roll your own ordered dict implementation, use an ordered list of tuples or use an existing ordered dict implementation. A: Python3.1 has an OrderedDict >>> from collections import OrderedDict >>> o=OrderedDict([('one', '1'), ('two', '2'), ('three', '3'), ('four', '4')]) >>> o OrderedDict([('one', '1'), ('two', '2'), ('three', '3'), ('four', '4')]) >>> for k,v in o.items(): ... print (k,v) ... one 1 two 2 three 3 four 4 A: Now you know dicts are unordered, here is how to convert them to a list which you can order >>> a = {'one': '1', 'two': '2', 'three': '3', 'four': '4'} >>> a {'four': '4', 'three': '3', 'two': '2', 'one': '1'} sorted by key >>> sorted(a.items()) [('four', '4'), ('one', '1'), ('three', '3'), ('two', '2')] sorted by value >>> from operator import itemgetter >>> sorted(a.items(),key=itemgetter(1)) [('one', '1'), ('two', '2'), ('three', '3'), ('four', '4')] >>> A: And what is the "standard order" you would be expecting? It is very much application dependent. A python dictionary doesn't guarantee key ordering anyways. In any case, you can iterate over a dictionary keys() the way you want. A: From the Python Tutorial: It is best to think of a dictionary as an unordered set of key: value pairs And from the Python Standard Library (about dict.items): CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. So if you need to process the dict in a certain order, sort the keys or values, e.g.: >>> sorted(a.keys()) ['four', 'one', 'three', 'two'] >>> sorted(a.values()) ['1', '2', '3', '4']
Why dictionaries appear to be reversed?
Why dictionaries in python appears reversed? >>> a = {'one': '1', 'two': '2', 'three': '3', 'four': '4'} >>> a {'four': '4', 'three': '3', 'two': '2', 'one': '1'} How can I fix this?
[ "Dictionaries in python (and hash tables in general) are unordered. In python you can use the sort() method on the keys to sort them.\n", "Dictionaries have no intrinsic order. You'll have to either roll your own ordered dict implementation, use an ordered list of tuples or use an existing ordered dict implementation. \n", "Python3.1 has an OrderedDict\n>>> from collections import OrderedDict\n>>> o=OrderedDict([('one', '1'), ('two', '2'), ('three', '3'), ('four', '4')])\n>>> o\nOrderedDict([('one', '1'), ('two', '2'), ('three', '3'), ('four', '4')])\n>>> for k,v in o.items():\n... print (k,v)\n... \none 1\ntwo 2\nthree 3\nfour 4\n\n", "Now you know dicts are unordered, here is how to convert them to a list which you can order\n>>> a = {'one': '1', 'two': '2', 'three': '3', 'four': '4'}\n>>> a\n{'four': '4', 'three': '3', 'two': '2', 'one': '1'}\n\nsorted by key\n>>> sorted(a.items())\n[('four', '4'), ('one', '1'), ('three', '3'), ('two', '2')]\n\nsorted by value\n>>> from operator import itemgetter\n>>> sorted(a.items(),key=itemgetter(1))\n[('one', '1'), ('two', '2'), ('three', '3'), ('four', '4')]\n>>> \n\n", "And what is the \"standard order\" you would be expecting? It is very much application dependent. A python dictionary doesn't guarantee key ordering anyways.\nIn any case, you can iterate over a dictionary keys() the way you want.\n", "From the Python Tutorial:\n\nIt is best to think of a dictionary as\n an unordered set of key: value pairs\n\nAnd from the Python Standard Library (about dict.items):\n\nCPython implementation detail: Keys\n and values are listed in an arbitrary\n order which is non-random, varies\n across Python implementations, and\n depends on the dictionary’s history of\n insertions and deletions.\n\nSo if you need to process the dict in a certain order, sort the keys or values, e.g.:\n>>> sorted(a.keys())\n['four', 'one', 'three', 'two']\n>>> sorted(a.values())\n['1', '2', '3', '4']\n\n" ]
[ 16, 5, 5, 2, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0002291637_dictionary_python.txt
Q: How to generate code objects from modules in Python? I have a .pyc file with no corresponding Python source code. I want to see the disassembly of the module using dis. I can import my module just fine with import dis import foo But to call dis.dis on it, I can't use the module object. I need the corresponding code object which backs foo. How do I create it? It seems that the compile builtin can compile strings, classes, methods, and functions, but not files or modules. How do I generate this code object given what I have? A: See http://nedbatchelder.com/blog/200804/the_structure_of_pyc_files.html
How to generate code objects from modules in Python?
I have a .pyc file with no corresponding Python source code. I want to see the disassembly of the module using dis. I can import my module just fine with import dis import foo But to call dis.dis on it, I can't use the module object. I need the corresponding code object which backs foo. How do I create it? It seems that the compile builtin can compile strings, classes, methods, and functions, but not files or modules. How do I generate this code object given what I have?
[ "See http://nedbatchelder.com/blog/200804/the_structure_of_pyc_files.html\n" ]
[ 4 ]
[]
[]
[ "bytecode", "bytecode_manipulation", "cpython", "python" ]
stackoverflow_0002293322_bytecode_bytecode_manipulation_cpython_python.txt
Q: How to solve this using regex? Given that string: \n \n text1\n \ttext2\n Message: 1st message\n some more text\n \n \n Message: 2dn message\n\n \t\t Message: 3rd message\n text3\n I want to extract messages from a multiline string (token is 'Message: '). What regex expression should I use to capture those 3 groups: group 1 : '1st message' group 2 : '2dn message' group 3 : '3rd message' I tried a lot of things but I can get the expression to work because the string is a multiline string. My program is in python 2.6 but I suppose it does not make a big difference what language I use... A: >>> re.findall('Message: (.+?)$', s, re.M) ['1st message', '2dn message', '3rd message'] re.M flag gives special meaning to ^ and $: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline); and the pattern character '$' matches at the end of the string and at the end of each line (immediately preceding each newline). By default, '^' matches only at the beginning of the string, and '$' only at the end of the string and immediately before the newline (if any) at the end of the string. (.+?)$ matches at least one character till the closest end of the string-character. edit: indeed the simple version will work too: >>> re.findall('Message: (.+)', s) ['1st message', '2dn message', '3rd message'] I'm surprised it wasn't in the list of those numerous things you tried :) A: @OP,you don't need a regex. Assuming you don't care about the lines after "Message:", for line in mystring.split("\n") if "Message:" in line: print "found: ",line
How to solve this using regex?
Given that string: \n \n text1\n \ttext2\n Message: 1st message\n some more text\n \n \n Message: 2dn message\n\n \t\t Message: 3rd message\n text3\n I want to extract messages from a multiline string (token is 'Message: '). What regex expression should I use to capture those 3 groups: group 1 : '1st message' group 2 : '2dn message' group 3 : '3rd message' I tried a lot of things but I can get the expression to work because the string is a multiline string. My program is in python 2.6 but I suppose it does not make a big difference what language I use...
[ ">>> re.findall('Message: (.+?)$', s, re.M)\n['1st message', '2dn message', '3rd message']\n\nre.M flag gives special meaning to ^ and $:\n\nWhen specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline); and the pattern character '$' matches at the end of the string and at the end of each line (immediately preceding each newline). By default, '^' matches only at the beginning of the string, and '$' only at the end of the string and immediately before the newline (if any) at the end of the string.\n\n(.+?)$ matches at least one character till the closest end of the string-character.\nedit: indeed the simple version will work too:\n>>> re.findall('Message: (.+)', s)\n['1st message', '2dn message', '3rd message']\n\nI'm surprised it wasn't in the list of those numerous things you tried :)\n", "@OP,you don't need a regex. Assuming you don't care about the lines after \"Message:\",\nfor line in mystring.split(\"\\n\")\n if \"Message:\" in line:\n print \"found: \",line\n\n" ]
[ 9, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002290859_python_regex.txt
Q: the number of images, using "len()" I need to count the number of images (in this case 1 image). Apparently using "len()"? Here is HTML: <div class="detail-headline"> Fotogal&#233;ria </div> <div class="detail-indent"> <table id="ctl00_ctl00_ctl00_containerHolder_mainContentHolder_innnerContentHolder_ZakazkaControl_ZakazkaObrazky1_ObrazkyDataList" cellspacing="0" border="0" style="width:100%;border-collapse:collapse;"> <tr> <td align="center" style="width:25%;"> <div id="ctl00_ctl00_ctl00_containerHolder_mainContentHolder_innnerContentHolder_ZakazkaControl_ZakazkaObrazky1_ObrazkyDataList_ctl02_PictureContainer"> <a title="1-izb. Kaspická" class="highslide detail-img-link" onclick="return hs.expand(this);" href="/imgcache/cache231/3186-000393~8621457~640x480.jpg"><img src="/imgcache/cache231/3186-000393~8621457~120x120.jpg" class="detail-img" width="89" height="120" alt="1-izb. Kaspická" /></a> </div> </td><td></td> </tr> </table> </div> I used before HTMLParser and the number of images must be added to "self.srcData".. Previous code: def handle_starttag(self, tag, attrs): if tag == 'div' and len(attrs) > 1 and attrs[1][0] == 'class' and attrs[1][1] == 'detail-headline' \ and self.srcData[self.getpos()[0]].strip() == u'Realitn&#225; kancel&#225;ria': self.status = 2 if self.status == 2 and tag == 'div' and len(attrs) > 0 and attrs[0][0] == 'class' and attrs[0][1] == 'name': self.record[-1] = decode(self.srcData[self.getpos()[0]].strip()) self.status = 0 Then (check start tag).. Like this? if tag == 'div' and len(attrs) > 0 and attrs[0][0] == 'class' and attrs[0][1] == 'detail-headline' \ and self.srcData[self.getpos()[0]].strip() == 'Fotogal&#233;ria': self.status = 3 Is it ok? And...? Thanks. import urllib import urllib2 import HTMLParser import codecs import time from BeautifulSoup import BeautifulSoup # decode string def decode(istr): ostr = u'' idx = 0 while idx < len(istr): add = True if istr[idx] == '&' and len(istr) > idx + 1 and istr[idx + 1] == '#': iend = istr.find(';', idx) if iend > idx: ostr += unichr(int(istr[idx + 2:iend])) idx = iend add = False if add: ostr += istr[idx] idx += 1 return ostr # parser 1 class FlatDetailParser (HTMLParser.HTMLParser): def __init__ (self): HTMLParser.HTMLParser.__init__(self) def loadDetails(self, link): self.record = (len(self.characts) + 1) * [''] self.status = 0 self.index = -1 self.reset() request = urllib2.Request(link) data = urllib2.urlopen(request) # URL obtained from the next class self.srcData = [] for line in data: line = line.decode('utf8') self.srcData.append(line) for line in self.srcData: self.feed(line) self.close() return self.record def handle_starttag(self, tag, attrs): if tag == 'div' and len(attrs) > 1 and attrs[1][0] == 'class' and attrs[1][1] == 'detail-headline' \ and self.srcData[self.getpos()[0]].strip() == u'Realitn&#225; kancel&#225;ria': self.status = 2 if self.status == 2 and tag == 'div' and len(attrs) > 0 and attrs[0][0] == 'class' \ and attrs[0][1] == 'name': self.record[-1] = decode(self.srcData[self.getpos()[0]].strip()) self.status = 0 ...and next class of parser, and adding data in to the txt file. When I use BeautifulSoup.. What is soup=BeautifulSoup(???). How can I add to srcData? This can be combined? How? A: Your job will be easier if you use BeautifulSoup Perhaps something like this from BeautifulSoup import BeaufitulSoup def count_images(htmltext) soup=BeautifulSoup(htmltext) return len(soup.findAll('div',{'class':'detail-indent'})) Or using lxml from lxml.html.soupparser import fromstring def count_images(htmltext) return len([e.attrib for e in fromstring(htmltext).findall('div') if e.attrib.get('class')=='detail-indent']) A: Just for a lark, I tried a pyparsing approach. Pyparsing includes some methods to help construct matching patterns for HTML tags, which include matches for attributes, unexpected whitespace, single or double quotes, and other hard-to-predict HTML tag gotchas. Here is a pyparsing solution (assumes your HTML source has been read into a string variable 'html'): from pyparsing import makeHTMLTags # makeHTMLTags returns patterns for both opening and closing # tags, we just want the opening ones aTag = makeHTMLTags("A")[0] imgTag = makeHTMLTags("IMG")[0] # find the matching tags tagMatches = (aTag|imgTag).searchString(html) # yes, use len() to see how many there are print len(tagMatches) # get the actual image names for t in tagMatches: if t.startA: print t.href if t.startImg: print t.src Prints: 2 /imgcache/cache231/3186-000393~8621457~640x480.jpg /imgcache/cache231/3186-000393~8621457~120x120.jpg
the number of images, using "len()"
I need to count the number of images (in this case 1 image). Apparently using "len()"? Here is HTML: <div class="detail-headline"> Fotogal&#233;ria </div> <div class="detail-indent"> <table id="ctl00_ctl00_ctl00_containerHolder_mainContentHolder_innnerContentHolder_ZakazkaControl_ZakazkaObrazky1_ObrazkyDataList" cellspacing="0" border="0" style="width:100%;border-collapse:collapse;"> <tr> <td align="center" style="width:25%;"> <div id="ctl00_ctl00_ctl00_containerHolder_mainContentHolder_innnerContentHolder_ZakazkaControl_ZakazkaObrazky1_ObrazkyDataList_ctl02_PictureContainer"> <a title="1-izb. Kaspická" class="highslide detail-img-link" onclick="return hs.expand(this);" href="/imgcache/cache231/3186-000393~8621457~640x480.jpg"><img src="/imgcache/cache231/3186-000393~8621457~120x120.jpg" class="detail-img" width="89" height="120" alt="1-izb. Kaspická" /></a> </div> </td><td></td> </tr> </table> </div> I used before HTMLParser and the number of images must be added to "self.srcData".. Previous code: def handle_starttag(self, tag, attrs): if tag == 'div' and len(attrs) > 1 and attrs[1][0] == 'class' and attrs[1][1] == 'detail-headline' \ and self.srcData[self.getpos()[0]].strip() == u'Realitn&#225; kancel&#225;ria': self.status = 2 if self.status == 2 and tag == 'div' and len(attrs) > 0 and attrs[0][0] == 'class' and attrs[0][1] == 'name': self.record[-1] = decode(self.srcData[self.getpos()[0]].strip()) self.status = 0 Then (check start tag).. Like this? if tag == 'div' and len(attrs) > 0 and attrs[0][0] == 'class' and attrs[0][1] == 'detail-headline' \ and self.srcData[self.getpos()[0]].strip() == 'Fotogal&#233;ria': self.status = 3 Is it ok? And...? Thanks. import urllib import urllib2 import HTMLParser import codecs import time from BeautifulSoup import BeautifulSoup # decode string def decode(istr): ostr = u'' idx = 0 while idx < len(istr): add = True if istr[idx] == '&' and len(istr) > idx + 1 and istr[idx + 1] == '#': iend = istr.find(';', idx) if iend > idx: ostr += unichr(int(istr[idx + 2:iend])) idx = iend add = False if add: ostr += istr[idx] idx += 1 return ostr # parser 1 class FlatDetailParser (HTMLParser.HTMLParser): def __init__ (self): HTMLParser.HTMLParser.__init__(self) def loadDetails(self, link): self.record = (len(self.characts) + 1) * [''] self.status = 0 self.index = -1 self.reset() request = urllib2.Request(link) data = urllib2.urlopen(request) # URL obtained from the next class self.srcData = [] for line in data: line = line.decode('utf8') self.srcData.append(line) for line in self.srcData: self.feed(line) self.close() return self.record def handle_starttag(self, tag, attrs): if tag == 'div' and len(attrs) > 1 and attrs[1][0] == 'class' and attrs[1][1] == 'detail-headline' \ and self.srcData[self.getpos()[0]].strip() == u'Realitn&#225; kancel&#225;ria': self.status = 2 if self.status == 2 and tag == 'div' and len(attrs) > 0 and attrs[0][0] == 'class' \ and attrs[0][1] == 'name': self.record[-1] = decode(self.srcData[self.getpos()[0]].strip()) self.status = 0 ...and next class of parser, and adding data in to the txt file. When I use BeautifulSoup.. What is soup=BeautifulSoup(???). How can I add to srcData? This can be combined? How?
[ "Your job will be easier if you use BeautifulSoup\nPerhaps something like this\nfrom BeautifulSoup import BeaufitulSoup\ndef count_images(htmltext)\n soup=BeautifulSoup(htmltext)\n return len(soup.findAll('div',{'class':'detail-indent'}))\n\nOr using lxml\nfrom lxml.html.soupparser import fromstring\ndef count_images(htmltext)\n return len([e.attrib for e in fromstring(htmltext).findall('div')\n if e.attrib.get('class')=='detail-indent'])\n\n", "Just for a lark, I tried a pyparsing approach. Pyparsing includes some methods to help construct matching patterns for HTML tags, which include matches for attributes, unexpected whitespace, single or double quotes, and other hard-to-predict HTML tag gotchas. Here is a pyparsing solution (assumes your HTML source has been read into a string variable 'html'):\nfrom pyparsing import makeHTMLTags\n\n# makeHTMLTags returns patterns for both opening and closing \n# tags, we just want the opening ones\naTag = makeHTMLTags(\"A\")[0]\nimgTag = makeHTMLTags(\"IMG\")[0]\n\n# find the matching tags\ntagMatches = (aTag|imgTag).searchString(html)\n\n# yes, use len() to see how many there are\nprint len(tagMatches)\n\n# get the actual image names\nfor t in tagMatches:\n if t.startA:\n print t.href\n if t.startImg:\n print t.src\n\nPrints:\n2\n/imgcache/cache231/3186-000393~8621457~640x480.jpg\n/imgcache/cache231/3186-000393~8621457~120x120.jpg\n\n" ]
[ 3, 1 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0002292982_parsing_python.txt
Q: django error when i signup my site . why? This is the signup view: def signup(request, form_class=SignupForm, template_name="account/signup.html", success_url=None): if success_url is None: success_url = get_default_redirect(request) if request.method == "POST": form = form_class(request.POST) if form.is_valid(): username, password = form.save() if settings.ACCOUNT_EMAIL_VERIFICATION: return render_to_response("account/verification_sent.html", { "email": form.cleaned_data["email"], }, context_instance=RequestContext(request)) else: user = authenticate(username=username, password=password) auth_login(request, user) request.user.message_set.create( message=_("Successfully logged in as %(username)s.") % { 'username': user.username }) return HttpResponseRedirect(success_url) else: form = form_class() return render_to_response(template_name, { "form": form, }, context_instance=RequestContext(request)) and SignupForm: class SignupForm(forms.Form): username = forms.CharField(label=_("Username"), max_length=30, widget=forms.TextInput()) password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput(render_value=False)) password2 = forms.CharField(label=_("Password (again)"), widget=forms.PasswordInput(render_value=False)) if settings.ACCOUNT_REQUIRED_EMAIL or settings.ACCOUNT_EMAIL_VERIFICATION: email = forms.EmailField( label = _("Email"), required = True, widget = forms.TextInput() ) else: email = forms.EmailField( label = _("Email (optional)"), required = False, widget = forms.TextInput() ) confirmation_key = forms.CharField(max_length=40, required=False, widget=forms.HiddenInput()) def clean_username(self): if not alnum_re.search(self.cleaned_data["username"]): raise forms.ValidationError(_("Usernames can only contain letters, numbers and underscores.")) try: user = User.objects.get(username__iexact=self.cleaned_data["username"]) except User.DoesNotExist: return self.cleaned_data["username"] raise forms.ValidationError(_("This username is already taken. Please choose another.")) def clean(self): if "password1" in self.cleaned_data and "password2" in self.cleaned_data: if self.cleaned_data["password1"] != self.cleaned_data["password2"]: raise forms.ValidationError(_("You must type the same password each time.")) return self.cleaned_data def save(self): username = self.cleaned_data["username"] email = self.cleaned_data["email"] password = self.cleaned_data["password1"] if self.cleaned_data["confirmation_key"]: from friends.models import JoinInvitation # @@@ temporary fix for issue 93 try: join_invitation = JoinInvitation.objects.get(confirmation_key = self.cleaned_data["confirmation_key"]) confirmed = True except JoinInvitation.DoesNotExist: confirmed = False else: confirmed = False # @@@ clean up some of the repetition below -- DRY! if confirmed: if email == join_invitation.contact.email: new_user = User.objects.create_user(username, email, password) join_invitation.accept(new_user) # should go before creation of EmailAddress below new_user.message_set.create(message=ugettext(u"Your email address has already been verified")) # already verified so can just create EmailAddress(user=new_user, email=email, verified=True, primary=True).save() else: new_user = User.objects.create_user(username, "", password) join_invitation.accept(new_user) # should go before creation of EmailAddress below if email: new_user.message_set.create(message=ugettext(u"Confirmation email sent to %(email)s") % {'email': email}) EmailAddress.objects.add_email(new_user, email) else: new_user = User.objects.create_user(username, "", password) if email: new_user.message_set.create(message=ugettext(u"Confirmation email sent to %(email)s") % {'email': email}) EmailAddress.objects.add_email(new_user, email) if settings.ACCOUNT_EMAIL_VERIFICATION: new_user.is_active = False new_user.save() return username, password # required for authenticate() A: it is ok now i used mysql insteadof squite3
django error when i signup my site . why?
This is the signup view: def signup(request, form_class=SignupForm, template_name="account/signup.html", success_url=None): if success_url is None: success_url = get_default_redirect(request) if request.method == "POST": form = form_class(request.POST) if form.is_valid(): username, password = form.save() if settings.ACCOUNT_EMAIL_VERIFICATION: return render_to_response("account/verification_sent.html", { "email": form.cleaned_data["email"], }, context_instance=RequestContext(request)) else: user = authenticate(username=username, password=password) auth_login(request, user) request.user.message_set.create( message=_("Successfully logged in as %(username)s.") % { 'username': user.username }) return HttpResponseRedirect(success_url) else: form = form_class() return render_to_response(template_name, { "form": form, }, context_instance=RequestContext(request)) and SignupForm: class SignupForm(forms.Form): username = forms.CharField(label=_("Username"), max_length=30, widget=forms.TextInput()) password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput(render_value=False)) password2 = forms.CharField(label=_("Password (again)"), widget=forms.PasswordInput(render_value=False)) if settings.ACCOUNT_REQUIRED_EMAIL or settings.ACCOUNT_EMAIL_VERIFICATION: email = forms.EmailField( label = _("Email"), required = True, widget = forms.TextInput() ) else: email = forms.EmailField( label = _("Email (optional)"), required = False, widget = forms.TextInput() ) confirmation_key = forms.CharField(max_length=40, required=False, widget=forms.HiddenInput()) def clean_username(self): if not alnum_re.search(self.cleaned_data["username"]): raise forms.ValidationError(_("Usernames can only contain letters, numbers and underscores.")) try: user = User.objects.get(username__iexact=self.cleaned_data["username"]) except User.DoesNotExist: return self.cleaned_data["username"] raise forms.ValidationError(_("This username is already taken. Please choose another.")) def clean(self): if "password1" in self.cleaned_data and "password2" in self.cleaned_data: if self.cleaned_data["password1"] != self.cleaned_data["password2"]: raise forms.ValidationError(_("You must type the same password each time.")) return self.cleaned_data def save(self): username = self.cleaned_data["username"] email = self.cleaned_data["email"] password = self.cleaned_data["password1"] if self.cleaned_data["confirmation_key"]: from friends.models import JoinInvitation # @@@ temporary fix for issue 93 try: join_invitation = JoinInvitation.objects.get(confirmation_key = self.cleaned_data["confirmation_key"]) confirmed = True except JoinInvitation.DoesNotExist: confirmed = False else: confirmed = False # @@@ clean up some of the repetition below -- DRY! if confirmed: if email == join_invitation.contact.email: new_user = User.objects.create_user(username, email, password) join_invitation.accept(new_user) # should go before creation of EmailAddress below new_user.message_set.create(message=ugettext(u"Your email address has already been verified")) # already verified so can just create EmailAddress(user=new_user, email=email, verified=True, primary=True).save() else: new_user = User.objects.create_user(username, "", password) join_invitation.accept(new_user) # should go before creation of EmailAddress below if email: new_user.message_set.create(message=ugettext(u"Confirmation email sent to %(email)s") % {'email': email}) EmailAddress.objects.add_email(new_user, email) else: new_user = User.objects.create_user(username, "", password) if email: new_user.message_set.create(message=ugettext(u"Confirmation email sent to %(email)s") % {'email': email}) EmailAddress.objects.add_email(new_user, email) if settings.ACCOUNT_EMAIL_VERIFICATION: new_user.is_active = False new_user.save() return username, password # required for authenticate()
[ "it is ok now \ni used mysql insteadof squite3\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002293500_django_python.txt
Q: How can I show a widget and all its parent containers? In my program, there is a point where all widgets are hidden. Is there a simple way to show a widget and all of its parent containers? I am not able to use show_all(), because that would show other widgets that I don't want shown. I could go down the containers and show them all, but I would prefer not to if there is a more concise solution. A: Other than iterating through Widget.get_parent and showing them all, you can also set the no-show-all property on the widgets you don't want shown, and call show_all on the ancestor.
How can I show a widget and all its parent containers?
In my program, there is a point where all widgets are hidden. Is there a simple way to show a widget and all of its parent containers? I am not able to use show_all(), because that would show other widgets that I don't want shown. I could go down the containers and show them all, but I would prefer not to if there is a more concise solution.
[ "Other than iterating through Widget.get_parent and showing them all, you can also set the no-show-all property on the widgets you don't want shown, and call show_all on the ancestor.\n" ]
[ 1 ]
[]
[]
[ "containers", "gtk", "pygtk", "python", "widget" ]
stackoverflow_0002293672_containers_gtk_pygtk_python_widget.txt