text
stringlengths
226
34.5k
How do I import a COM object namespace/enumeration in Python? Question: I'm relatively new to programming/python, so I'd appreciate any help I can get. I want to save an excel file as a specific format using Excel through COM. Here is the code: import win32com.client as win32 def excel(): app = 'Excel' x1 = win32.gencache.EnsureDispatch('%s.Application' % app) ss = x1.Workbooks.Add() sh = ss.ActiveSheet x1.Visible = True sh.Cells(1,1).Value = 'test write' ss.SaveAs(Filename="temp.xls", FileFormat=56) x1.Application.Quit() if __name__=='__main__': excel() My question is how do I specify the FileFormat if I don't explicitly know the code for it? Browsing through the documentation I find the reference at about a FileFormat object. I'm clueless on how to access the [XlFileFormat object](http://msdn.microsoft.com/en- us/library/microsoft.office.interop.excel.xlfileformat.aspx) and import it in a way that I can find the enumeration value for it. Thanks! Answer: This question is a bit stale, but for those reaching this page from Google (as I did) my solution was accessing the constants via the `win32com.client.constants` object instead of on the application object itself [as suggested by Eric](http://stackoverflow.com/questions/1646230/how-do-i- import-a-com-object-namespace-enumeration-in-python/1647147#1647147). This lets you use enum constants just like in the VBE: >>> import win32com.client >>> xl = win32com.client.gencache.EnsureDispatch('Excel.Application') >>> C = win32com.client.constants >>> C.xlWorkbookNormal -4143 >>> C.xlCSV 6 >>> C.xlErrValue 2015 >>> C.xlThemeColorAccent1 5 Also, unless you've manually run the `makepy` utility, the constants may not be available if initializing the application with the regular `win32com.client.Dispatch(..)` method, which was another issue I was having. Using `win32com.client.gencache.EnsureDispatch(..)` (as the questioner does) checks for and generates the Python bindings at runtime if required. I found [this ActiveState page](http://docs.activestate.com/activepython/2.4/pywin32/html/com/win32com/HTML/QuickStartClientCom.html) to be helpful.
Convert & to &amp; in Python Question: I'm working on a simple crawler in Python. The aim is to create a sitemap.xml. (you can find the very alpha version here: <http://code.google.com/p/sitemappy/>) I noticed that if I generate the xml with URLs containing non HTML entities (such as &), the xml doesn't validate and it isn't accepted by Google Webmaster Tools. Is there a quick way to encode the querystring part of the URLs? Thank you! Matteo Answer: [`cgi.escape`](http://docs.python.org/library/cgi.html#cgi.escape) to the rescue: > `cgi.escape(s[, quote])` > > Convert the characters '&', '<' and '>' in string s to HTML-safe sequences. > Use this if you need to display text that might contain such characters in > HTML. If the optional flag quote is true, the quotation mark character ('"') > is also translated; this helps for inclusion in an HTML attribute value, as > in . If the value to be quoted might include single- or double-quote > characters, or both, consider using the quoteattr() function in the > xml.sax.saxutils module instead. Quick interactive check: >>> import cgi >>> cgi.escape('<&>') '&lt;&amp;&gt;' >>>
Python Array is read-only, can't append values Question: I am new to Python. The following code is causing an error when it attempts to append values to an array. What am I doing wrong? import re from array import array freq_pattern = re.compile("Frequency of Incident[\(\)A-Za-z\s]*\.*\s*([\.0-9]*)") col_pattern = re.compile("([-\.0-9]+)\s+([-\.0-9]+)\s+([-\.0-9]+)\s+([-\.0-9]+)\s+([-\.0-9]+)") e_rcs = array('f') f = open('example.4.out', 'r') for line in f: print line, result = freq_pattern.search(line) if result: freq = float(result.group(1)) cols = col_pattern.search(line) if cols: e_rcs.append = float(cols.group(2)) f.close() **Error** > Traceback (most recent call last): > File "D:\workspace\CATS Parser\cats-post.py", line 31, in e_rcs.append = > float(cols.group(2)) AttributeError: 'list' object attribute 'append' is > read-only attributes (assign to .append) Answer: Do you want to append to the array? e_rcs.append( float(cols.group(2)) ) Doing this: `e_rcs.append = float(cols.group(2))` replaces the `append` method of the array `e-rcs` with a floating-point value. Rarely something you want to do.
Run command pipes with subprocess.Popen Question: How can I run the following command using [`subprocess.Popen`](http://docs.python.org/library/subprocess.html#subprocess.Popen)? mysqldump database_name table_name | bzip2 > filename I know [`os.system()`](http://docs.python.org/library/os.html#os.system) can do the job but I dont want to wait for the dump to finish in main program. Answer: You want the `shell=True` option to make it execute shell commands: import subprocess subprocess.Popen("sleep 4s && echo right thar, right thar",shell=True); print 'i like it when you put it' which yields: I like it when you put it [4 seconds later] right thar, right thar
Google Search from a Python App Question: I'm trying to run a google search query from a python app. Is there any python interface out there that would let me do this? If there isn't does anyone know which Google API will enable me to do this. Thanks. Answer: There's a simple example [here](http://www.ajaxlines.com/ajax/stuff/article/%5Fgoogle%5Fajax%5Fsearch%5Fapi%5Fexample%5Fpython%5Fcode.php) (peculiarly missing some quotes;-). Most of what you'll see on the web is Python interfaces to the old, discontinued SOAP API -- the example I'm pointing to uses the newer and supported AJAX API, that's definitely the one you want!-) **Edit** : here's a more complete Python 2.6 example with all the needed quotes &c;-)...: #!/usr/bin/python import json import urllib def showsome(searchfor): query = urllib.urlencode({'q': searchfor}) url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query search_response = urllib.urlopen(url) search_results = search_response.read() results = json.loads(search_results) data = results['responseData'] print 'Total results: %s' % data['cursor']['estimatedResultCount'] hits = data['results'] print 'Top %d hits:' % len(hits) for h in hits: print ' ', h['url'] print 'For more results, see %s' % data['cursor']['moreResultsUrl'] showsome('ermanno olmi')
How do I fetch an XML document and parse it with Python twisted? Question: I want a fast way to grab a URL and parse it while streaming. Ideally this should be super fast. My language of choice is Python. I have an intuition that twisted can do this but I'm at a loss to find an example. Answer: If you need to handle HTTP responses in a streaming fashion, there are a few options. You can do it via `downloadPage`: from xml.sax import make_parser from twisted.web.client import downloadPage class StreamingXMLParser: def __init__(self): self._parser = make_parser() def write(self, bytes): self._parser.feed(bytes) def close(self): self._parser.feed('', True) parser = StreamingXMLParser() d = downloadPage(url, parser) # d fires when the response is completely received This works because `downloadPage` writes the response body to the _file-like_ object passed to it. Here, passing in an object with `write` and `close` methods satisfies that requirement, but incrementally parses the data as XML instead of putting it on a disk. Another approach is to hook into things at the `HTTPPageGetter` level. `HTTPPageGetter` is the protocol used internally by `getPage`. class StreamingXMLParsingHTTPClient(HTTPPageGetter): def connectionMade(self): HTTPPageGetter.connectionMade(self) self._parser = make_parser() def handleResponsePart(self, bytes): self._parser.feed(bytes) def handleResponseEnd(self): self._parser.feed('', True) self.handleResponse(None) # Whatever you pass to handleResponse will be the result of the Deferred below. factory = HTTPClientFactory(url) factory.protocol = StreamingXMLParsingHTTPClient reactor.connectTCP(host, port, factory) d = factory.deferred # d fires when the response is completely received Finally, there will be a new HTTP client API soon. Since this isn't part of any release yet, it's not as directly useful as the previous two approaches, but it's somewhat nicer, so I'll include it to give you an idea of what the future will bring. :) The new API lets you specify a protocol to receive the response body. So you'd do something like this: class StreamingXMLParser(Protocol): def __init__(self): self.done = Deferred() def connectionMade(self): self._parser = make_parser() def dataReceived(self, bytes): self._parser.feed(bytes) def connectionLost(self, reason): self._parser.feed('', True) self.done.callback(None) from twisted.web.client import Agent from twisted.internet import reactor agent = Agent(reactor) d = agent.request('GET', url, headers, None) def cbRequest(response): # You can look at the response headers here if you like. protocol = StreamingXMLParser() response.deliverBody(protocol) return protocol.done d.addCallback(cbRequest) # d fires when the response is fully received and parsed
Nose test script with command line arguments Question: I would like to be able to run a nose test script which accepts command line arguments. For example, something along the lines: test.py import nose, sys def test(): # do something with the command line arguments print sys.argv if __name__ == '__main__': nose.runmodule() However, whenever I run this with a command line argument, I get an error: $ python test.py arg E ====================================================================== ERROR: Failure: ImportError (No module named arg) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/nose-0.11.1-py2.6.egg/nose/loader.py", line 368, in loadTestsFromName module = resolve_name(addr.module) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/nose-0.11.1-py2.6.egg/nose/util.py", line 334, in resolve_name module = __import__('.'.join(parts_copy)) ImportError: No module named arg ---------------------------------------------------------------------- Ran 1 test in 0.001s FAILED (errors=1) Apparently, nose tries to do something with the arguments passed in sys.argv. Is there a way to make nose ignore those arguments? Answer: Alright, I hate "why would you want to do that?" answers just as much as anyone, but I'm going to have to make one here. I hope you don't mind. I'd argue that doing whatever you're wanting to do isn't within the scope of the framework nose. Nose is intended for _automated_ tests. If you have to pass in command-line arguments for the test to pass, then it isn't automated. Now, what you _can_ do is something like this: import sys class test_something(object): def setUp(self): sys.argv[1] = 'arg' del sys.argv[2] # remember that -s is in sys.argv[2], see below def test_method(self): print sys.argv If you run that, you get this output: [~] nosetests test_something.py -s ['/usr/local/bin/nosetests', 'arg'] . ---------------------------------------------------------------------- Ran 1 test in 0.001s OK (Remember to pass in the -s flag if you want to see what goes on stdout) However, I'd probably still recommend against that, as it's generally a bad idea to mess with global state in automated tests if you can avoid it. What I would likely do is adapt whatever code I'm wanting to test to take an `argv` list. Then, you can pass in whatever you want during testing and pass in `sys.argv` in production. **UPDATE** : > The reason why I need to do it is because I am testing multiple > implementations of the same library. To test those implementations are > correct I use a single nose script, that accepts as a command line argument > the library that it should import for testing. It sounds like you may want to try your hand at writing a nose plugin. It's pretty easy to do. [Here are the latest docs.](http://nose.readthedocs.org/en/latest/plugins/writing.html)
BeautifulSoup with Jython Question: I just tried to run BeautifulSoup (3.1.0.1) with Jython (2.5.1) and I was amazed to see how much slower it was than CPython. Parsing a page (<http://www.fixprotocol.org/specifications/fields/5000-5999>) with CPython took just under a second (0.844 second to be exact). With Jython it took 564 seconds - almost 700 times as much. Can anyone confirm this result? It's doesn't seem reasonable for Jython to run 700 times slower than CPython. Perhaps something is wrong with my setup. [Edit] Here's the code I used to test this (naturally I downloaded the above mentioned HTML file): import time from BeautifulSoup import BeautifulSoup data = open("fix-5000-5999.html").read() start = time.time() soup = BeautifulSoup(data) print time.time() - start Answer: I can confirm similar findings. Intel Mac, OS X 10.6.1, Java 1.6.0_15 64-bit, Jython 2.5.1. Running your code with CPython 2.6.1 takes 0.1–0.2 seconds, but running it with Jython takes at least tens of seconds; I didn't wait more than 30. It also uses a lot of CPU. I tried Beautiful Soup 3.0.7a, because it uses a different parser, but had the same results. Interestingly, I tried running your code on [a different HTML file](https://lists.sourceforge.net/lists/listinfo/jython-users) and it worked fine. But it still seemed much slower than CPython: Jython took 1.02–1.3 seconds; CPython took 0.019–0.020. I don't have any suggestions at this point except that you should consider asking this question on the [jython- users](https://lists.sourceforge.net/lists/listinfo/jython-users) list; I've found the community there, which includes the lead developer, to be responsive and helpful. Good luck!
Python on windows7 intel 64bit Question: I've been messing around with Python over the weekend and find myself pretty much back at where I started. I've specifically been having issues with easy_install and nltk giving me errors about not finding packages, etc. I've tried both Python 2.6 and Python 3.1. I think part of the problem may be that I'm running windows 7 in 64bit mode on an Intel T5750 chipset. I'm thinking of downloading Python for windows extension <http://sourceforge.net/projects/pywin32/files/>, but not sure which version to get. Why do packages have a specific AMD64, but not intel? However, this may not even solve my problems. Any recommendations on getting Python to work in this environment? I've currently got Python 3.1 installed, and removed 2.6 Answer: The most popular 64-bit mode for "86-oid" processor is commonly known as AMD64 because AMD first came up with it (Intel at that time was pushing Itanium instead, and that didn't really catch fire -- it's still around but I don't even know if Win7 supports it); Intel later had to imitate that mode to get into the mass-64 bit market, but it's still commonly known as AMD64 after its originator. For Windows 7 in 64-bit mode, AMD64 seems likely to be what you want. The 64-bit-Windows downloads from [activestate](http://www.activestate.com/activepython/downloads/) come with a few important pieces that aren't part of the standard python.org 64-bit Windows builds, and might perhaps make your life easier.
Python urllib2: Reading content body even during HTTPError exception? Question: I'm using urllib2 to fetch a a page via HTTP. Sometimes the resource throws a HTTP error 400 (Bad Request) when my request contains an error. However, that response also contains an XML element that gives a detailed error message. It would be very handy to be able to see that error rather than just the HTTPError exception returned by urllib2. How do I return the document contents in spite of the exception? Answer: import urllib2 try: request = urllib2.Request('http://www.somesite.com') response = urllib2.urlopen(req) except urllib2.HTTPError as e: error_message = e.read() print error_message
Python string interning and substrings Question: Does python create a completely new string (copying the contents) when you do a substring operation like: new_string = my_old_string[foo:bar] Or does it use interning to point to the old data ? As a clarification, I'm curious if the underlying character buffer is shared as it is in Java. I realize that strings are immutable and will always appear to be a completely new string, and it would have to be an entirely new string object. Answer: You may also be interested in islice which does provide a view of the original string >>> from sys import getrefcount >>> from itertools import islice >>> h="foobarbaz" >>> getrefcount(h) 2 >>> g=islice(h,3,6) >>> getrefcount(h) 3 >>> "".join(g) 'bar' >>>
Reading from files in python Question: I need to find out the maximum and minimum value in a line by reading a file and should be dividing the maximum value by the minimum value. Am interested to do this in python. the contents of the file (file.txt) looks like this.. A28102_at,151,263,88,484,118,270,458,872,62,194 AB000114_at,72,21,20,61,20,85,20,25,20,65 AB000115_at,281,250,358,118,197,71,168,296,198,113 The problem am facing is i should be neglecting the first value, that is upto the first occurrence of comma and am unable to figure out a method. And also am interested to store the values in an array and then do the comparision. Is this approach correct or any better method is sugegsted? Answer: Python comes with batteries! Use the csv module to parse csv files: #!/usr/bin/env python import csv csvobj=csv.reader(open('file.txt','r')) for datum in csvobj: datum=[float(val) for val in datum[1:]] print(datum) maximum=max(datum) minimum=min(datum) print(maximum/minimum) # [151.0, 263.0, 88.0, 484.0, 118.0, 270.0, 458.0, 872.0, 62.0, 194.0] # 14.064516129 # [72.0, 21.0, 20.0, 61.0, 20.0, 85.0, 20.0, 25.0, 20.0, 65.0] # 4.25 # [281.0, 250.0, 358.0, 118.0, 197.0, 71.0, 168.0, 296.0, 198.0, 113.0] # 5.04225352113
Delineating a Read File Question: Not really too sure how to word this question, therefore if you don't particularly understand it then I can try again. I have a file called _example.txt_ and I'd like to import this into my Python program. Here I will do some calculations with what it contains and other things that are irrelevant. Instead of me importing this file, going through it line-by-line and extracting the information I want.. can Python do it instead? As in, if I structure the _.txt_ correctly (whether it be key / value pairs seperated by an equals on each line), is there a current Python 'way' where it can handle it all and I work with that? Answer: with open("example.txt") as f: for line in f: key, value = line.strip().split("=") do_something(key,value) looks like a starting point if I understand you correctly. You need Python 2.6 or 3.x for this. Another place to look is the `csv` module that can parse comma-separated value files - and you can tell it to use `=` as a separator instead. This will abstract away some of the "manual work" in that previous example - but it seems your example doesn't especially need that kind of abstraction. Another idea: with open("example.txt") as f: d = dict([line.strip().split("=") for line in f]) Now that's concise and pythonic :)
Saving work after a SIGINT Question: I have a program which takes a long time to complete. I would like it to be able to catch `SIGINT` (ctrl-c) and call the `self.save_work()` method. As it stands, my `signal_hander()` does not work since `self` is not defined by the time the program reaches `signal_handler()`. How can I set it up so `self.save_work` gets called after a `SIGINT`? #!/usr/bin/env python import signal def signal_handler(signal, frame): self.save_work() # Does not work exit(1) signal.signal(signal.SIGINT, signal_handler) class Main(object): def do_stuff(self): ... def save_work(self): ... def __init__(self): self.do_stuff() self.save_work() if __name__=='__main__': Main() Answer: If you just want to catch ctr+c then you can catch the [KeyboardInterrupt](http://docs.python.org/library/exceptions.html#exceptions.KeyboardInterrupt) exception: class Main(object): def do_stuff(self): ... def save_work(self): ... def __init__(self): try: self.do_stuff() except KeyboardInterrupt: pass # Or print helpful info self.save_work() Not that I think this is a good design after all. It looks like you need to be using a function instead of a constructor.
Django Tests fail with InternalError: no such savepoint. DB: Postgres, passes on mysql Question: Interestingly it also works on the shell. [MY code which calls Model.objects.get_or_create(...)] File "/usr/lib/python2.5/site-packages/django/db/models/manager.py", line 123, in get_or_create return self.get_query_set().get_or_create(**kwargs) File "/usr/lib/python2.5/site-packages/django/db/models/query.py", line 308, in get_or_create transaction.savepoint_rollback(sid) File "/usr/lib/python2.5/site-packages/django/db/transaction.py", line 199, in savepoint_rollback connection._savepoint_rollback(sid) File "/usr/lib/python2.5/site-packages/django/db/backends/__init__.py", line 67, in _savepoint_rollback self.cursor().execute(self.ops.savepoint_rollback_sql(sid)) InternalError: no such savepoint Answer: If you want to test code that uses transactions, you'll need to subclass [`TransactionTestCase`](https://docs.djangoproject.com/en/dev/topics/testing/?from=olddocs#django.test.TransactionTestCase) instead of `TestCase` for example: from django.test import TransactionTestCase class MyTests(TransactionTestCase): ... It probably passes in MySql because you're using MyISAM tables which don't support transactions
Python ClientForm Error Question: import ClientForm from urllib2 import urlopen page = urlopen('http://garciainteractive.com/blog/topic_view/topics/content/') form = ClientForm.ParseResponse(page, backwards_compat=False) print form[0] The problem is that ClientForm parses the first html form the following way: <POST http://garciainteractive.com/blog/topic_view/topics/content/ application/x-www-form-urlencoded <HiddenControl(ACT=1) (readonly)> <HiddenControl(RET=http://garciainteractive.com/blog/topic_view/topics/content/) (readonly)> <HiddenControl(URI=/blog/topic_view/topics/content/) (readonly)> <HiddenControl(PRV=) (readonly)> <HiddenControl(XID=d840927d4eaf95cef7aeca789009fb3991f574da) (readonly)> <HiddenControl(entry_id=42) (readonly)> <HiddenControl(site_id=1) (readonly)> <CheckboxControl(save_info=[yes])> <CheckboxControl(notify_me=[yes])> <TextControl(captcha=)> <SubmitControl(submit=Submit) (readonly)>> Thus, not finding `name`, `email` and `url` inputs. How can I fix it? TIA Update: Actually, I'm not using ClientForm separately, but as a part of mechanize, thus would prefer a solution allowing to fix without rewriting mechanize code Answer: The problem is likely that the HTML itself is invalid - for example it re-uses the id="comment_form" over and over again, while there is only supposed to be one id of a given name per document. Your best solution would probably be to use BeautifulSoup to parse your urlopen page result first, then pretty-print it back into a string for ClientForm - this is likely to get rid of most of the rough edges and give ClientForm a better chance of doing its thing. If this doesn't work, get a pretty-print of the result out and work out what kind of transform you'll have to do on the HTML to make the form very simple for ClientForm - by removing extraneous tags and cruft.
BioPython: extracting sequence IDs from a Blast output file Question: I have a BLAST output file in XML format. It is 22 query sequences with 50 hits reported from each sequence. And I want to extract all the 50x22 hits. This is the code I currently have, but it only extracts the 50 hits from the first query. from Bio.Blast import NCBIXM blast_records = NCBIXML.parse(result_handle) blast_record = blast_records.next() save_file = open("/Users/jonbra/Desktop/my_fasta_seq.fasta", 'w') for alignment in blast_record.alignments: for hsp in alignment.hsps: save_file.write('>%s\n' % (alignment.title,)) save_file.close() Somebody have any suggestions as to extract all the hits? I guess I have to use something else than alignments. Hope this was clear. Thanks! Jon Answer: This should get all records. The novelty compared with the original is the for blast_record in blast_records which is a python idiom to iterate through items in a "list-like" object, such as the blast_records (checking the [CBIXML module documentation](http://www.biopython.org/DIST/docs/api/Bio.Blast.NCBIXML- module.html) showed that parse() indeed returns an iterator) from Bio.Blast import NCBIXM blast_records = NCBIXML.parse(result_handle) save_file = open("/Users/jonbra/Desktop/my_fasta_seq.fasta", 'w') for blast_record in blast_records: for alignment in blast_record.alignments: for hsp in alignment.hsps: save_file.write('>%s\n' % (alignment.title,)) #here possibly to output something to file, between each blast_record save_file.close()
Why we should perfer to store the serialized data not the raw code to DB? Question: If we have some code(a data structure) which should be stored in DB, someone always suggests us to store the serialized data not the raw code string. So I'm not so sure why we should prefer the serialized data. Give a simple instance(in python): we've got a field which will store a dict of python, like { "name" : "BMW", "category":"car", "cost" : "200000"} so we can serialize it using pickle(a python module) and then store the pickled data to db field. Or we can store the dict string directly to DB without serializing. Since we need to convert the string to python data back, two approaches are both easy to do, by using pickle.loads and exec respectively. So which should be preferred? And why? Is it because exec is much slower than pickle? or some other reasons? Thanks. Answer: > Or we can store the dict string directly to DB without serializing. There is no such thing as "the dict string". There are many ways to serialize a dict into a string; you may be thinking of `repr`, possibly as `eval` as the way to get the dict back (you mention `exec`, but that's simply absurd: what statement would you execute...?! I think you probably mean `eval`). They're different serialization methods with their tradeoffs, and in many cases the tradeoffs tend to favor pickling (`cPickle`, for speed, with protocol `-1` meaning "the best you can do", usually). Performance is surely an issue, e.g., in terms of size of what you're storing...: $ python -c 'import cPickle; d=dict.fromkeys(range(99), "banana"); print len(repr(d))' 1376 $ python -c 'import cPickle; d=dict.fromkeys(range(99), "banana"); print len(cPickle.dumps(d,-1))' 412 ...why would you want to store 1.4 KB rather than 0.4 KB each time you serialize a dict like this one...?-) **Edit** : since some suggest Json, it's worth pointing out that json takes 1574 bytes here -- even bulkier than bulky repr! As for speed... $ python -mtimeit -s'import cPickle; d=dict.fromkeys(range(99), "chocolate")' 'eval(repr(d))' 1000 loops, best of 3: 706 usec per loop $ python -mtimeit -s'import cPickle; d=dict.fromkeys(range(99), "chocolate")' 'cPickle.loads(cPickle.dumps(d, -1))' 10000 loops, best of 3: 70.2 usec per loop ...why take 10 times longer? What's the upside that would justify paying such a hefty price? **Edit** : json takes 2.7 **milli** seconds -- almost **forty** times slower than cPickle. Then there's generality -- not every serializable object can properly round- trip with repr and eval, while pickling is much more general. E.g.: $ python -c'def f(): pass d={23:f} print d == eval(repr(d))' Traceback (most recent call last): File "<string>", line 3, in <module> File "<string>", line 1 {23: <function f at 0x241970>} ^ SyntaxError: invalid syntax vs $ python -c'import cPickle def f(): pass d={"x":f} print d == cPickle.loads(cPickle.dumps(d, -1))' True **Edit** : json is even less general than repr in terms of round-trips. So, comparing the two serialization approaches (pickling vs repr/eval), we see: pickling is way more general, it can be e.g. 10 times faster, and take up e.g. 3 times less space in your database. What compensating advantages do you envisage for repr/eval...? BTW, I see some answers mention security, but that's not a real point: pickling is insecure too (the security issue with eval`ing untrusted strings may be more obvious, but unpickling an untrusted string is also insecure, though in subtler and darker ways). **Edit** : json is more secure. Whether that's worth the huge cost in size, speed and generality, is a tradeoff worth pondering. In most cases it won't be.
Problem with python soap library suds. Wsdl was not understood Question: The code below throw a SAXParseException: "mismatched tag": from suds.client import Client <br> url = 'http://www.didww.com/api/?wsdl' client = Client(url, cache=None) print client Is it problem with suds, or there is some errors in wsdl? Answer: Have you looked at the WSDL file in a browser or XML viewer? That should answer your question as to whether the problem is in the wsdl. The exception suggests there is something up with it.
sorl.thumbnail : 'thumbnail' is not a valid tag library? Question: I am trying to install sorl.thumbnail but am getting the following error message: 'thumbnail' is not a valid tag library: Could not load template library from django.templatetags.thumbnail, No module named PIL This error popped up in this question as well <http://stackoverflow.com/questions/1356334/need-help-solving-sorl-thumbnail- error-thumbnail-is-not-a-valid-tag-library> but the solution offered there is no good for me. The solution was to append the project folder to all imports in the sorl files. I want to keep my apps separate from the project they are in for obvious reasons. I have placed the sorl folder in my project folder I have placed 'sorl.thumbnaills' under installed apps and finally placed {% load thumbnail %} in base.html $python2.5 >>>import PIL >>>import sorl These work. Using python2.5, on ubuntu 9.04 with django 1.1 with appengine-patch To try some other things out i placed in settings.py file: import sys sys.path.append("/home/danielle/bu3/mysite/sorl/thumbnail") But that didnt work either. Some more help would be appreciated ... how should i change my path? current path (without above mentioned import): ['/home/danielle/bu3/mysite', '/home/danielle/bu3/mysite/common', '/home/danielle/bu3/mysite/common/appenginepatch/appenginepatcher/lib', '/home/danielle/bu3/mysite/common/zip-packages/django-1.1.zip', '/home/danielle/bu3/mysite/common/appenginepatch', '/usr/local/google_appengine', '/usr/local/google_appengine/lib/antlr3', '/usr/local/google_appengine/lib/yaml/lib', '/usr/local/google_appengine/lib/django', '/usr/local/google_appengine/lib/webob', '/home/danielle/bu3/mysite', '/usr/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg', '/usr/lib/python2.5/site-packages/ZopeSkel-2.10-py2.5.egg', '/usr/lib/python2.5/site-packages/virtualenv-1.3.2-py2.5.egg', '/usr/lib/python2.5/site-packages/pip-0.3.1-py2.5.egg', '/usr/lib/python2.5/site-packages/virtualenvwrapper-1.12-py2.5.egg', '/usr/lib/python2.5/site-packages/PyYAML-3.08-py2.5-linux-i686.egg', '/usr/lib/python2.5/site-packages/xlutils-1.3.0-py2.5.egg', '/usr/lib/python2.5/site-packages/errorhandler-1.0.0-py2.5.egg', '/usr/lib/python2.5/site-packages/xlwt-0.7.1-py2.5.egg', '/usr/lib/python2.5/site-packages/xlrd-0.7.0-py2.5.egg', '/usr/lib/python2.5/site-packages/Fabric-0.0.9-py2.5.egg', '/usr/lib/python2.5/site-packages/multitask-0.2.0-py2.5.egg', '/usr/lib/python2.5/site-packages/logilab.pylintinstaller-0.15.2-py2.5.egg', '/usr/lib/python2.5/site-packages/pylint-0.15.2-py2.5.egg', '/usr/lib/python2.5/site-packages/clonedigger-1.0.9_beta-py2.5.egg', '/usr/lib/python2.5/site-packages/yolk-0.4.1-py2.5.egg', '/usr/lib/python2.5/site-packages/MySQL_python-1.2.3c1-py2.5-linux-i686.egg', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/Numeric', '/usr/lib/python2.5/site- packages/PIL', '/usr/lib/python2.5/site-packages/gst-0.10', '/var/lib/python- support/python2.5', '/usr/lib/python2.5/site-packages/gtk-2.0', '/var/lib/python-support/python2.5/gtk-2.0', '/usr/lib/python2.5/site- packages/wx-2.8-gtk2-unicode'] Answer: Is is a typo in your question? You have mis-spelled 'thumbnails' - for the installed apps you have two l's, i.e. `'sorl.thumbnaills'` rather than 'sorl.thumbnails' if you run `sync.db` does it return an error?
Getting the Current Table in Numbers (Python/Appscript) Question: How do I access the current table in Numbers using `py-appscript`? * * * For posterity, the program I created using this information clears all the cells of the current table and returns the selection to cell `A1`. I turned it into a Service using a python Run Shell Script in Automator and attached it to Numbers. from appscript import * Numbers = app('Numbers') current_table = None for sheet in Numbers.documents.first.sheets(): for table in sheet.tables(): if table.selection_range(): current_table = table if current_table: for cell in current_table.cells(): cell.value.set('') current_table.selection_range.set(to=current_table.ranges[u'A1']) It was used to clear large tables of numbers that I used for temporary calculations. Answer: >>> d = app('Numbers').documents.first() # reference to current top document EDIT: There doesn't seem to be a straight-forward single reference to the current table but it looks like you can find it by searching the current first document's sheets for a table with a non-null selection_range, so something like this: >>> nu = app('Numbers') >>> for sheet in nu.documents.first.sheets(): ... for table in sheet.tables(): ... if table.selection_range(): ... print table.name()
Weekly-based populating a database with the django admin Question: I'm building an small django app in order to manage a store employees roster. The employees are freelancers-like, they have weekly almost-fixed schedules, and may ask for extra ones at any weekday/time. I'm new to both python and django, and I'm using the django admin. Everything works fair enough (for me) when I "manually" add a "Turno" (work assignment, I'm not sure, it probably would be "Shift" in English?). I need some way of adding the weekly fixed Turnos (all at once, and not "manually" one by one) through the django admin, say setting a weekday, the begining and ending times, and a stop date two (or three) months in advance ... How? **Any** kind of help will be great, I'm not asking to you people to make out my duty. Here is my models.py: from django.db import models from django.contrib.auth.models import User import datetime class Dia(models.Model): fecha = models.DateField(unique=True) class Meta: ordering = ['fecha'] def __unicode__(self): return (self.fecha.strftime('%A %d de %b de \'%y')) class Turno(models.Model): dia = models.ForeignKey(Dia) perfil_usuario = models.ForeignKey(User, verbose_name="Usuario") comienza = models.TimeField() finaliza = models.TimeField() comentarios = models.TextField(blank=True, null=True) def __unicode__(self): return self.dia.fecha.strftime('%A %d de %b de \'%y') + ' - ' + self.perfil_usuario.username And here is my admin.py from roquen.horarios.models import Turno, Dia from django.contrib.auth.models import User from django.contrib import admin from django import forms admin.site.register(Dia) class TurnoAdminForm(forms.ModelForm): class Meta: model = Turno def clean_finaliza(self): data = self.cleaned_data['finaliza'] if data <= self.cleaned_data['comienza']: raise forms.ValidationError('La hora de fin debe ser posterior a la de comienzo') return data class TurnoAdmin(admin.ModelAdmin): form = TurnoAdminForm list_display = ['dia', 'perfil_usuario', 'comienza', 'finaliza'] admin.site.register(Turno, TurnoAdmin) Answer: You're actually asking a database architecture question. Your current solution has two concepts: workers and shifts such that a 'shift' is an interval of time on a specific _date_. This model is no longer valid. To introduce scheduled shifts your problem domain must encapsulate two concepts for the word 'shift' and the distinction between the two is critical to the solution: 1. A "shift" is an interval of time on a _day of the week_ 2. A "shift instance" is an interval of time on a _specific date_ So alter your models accordingly by renaming 'shift' to something which reflects the fact it occurs on a specific date. Then create a new model which reflects a shift more generically: it occurs on a day of the week, not any specific date. Thence your workers can be associated with certain shifts which occur during the week, but are free to vary their actual shifts. To assign a worker to a specific shift on a specific day create a shift-instance. You might create a process to periodically (each week) loop over all the shifts and create shift-instances for the coming week.
How to implement a pythonic equivalent of tail -F? Question: What is the pythonic way of watching the tail end of a growing file for the occurrence of certain keywords? In shell I might say: tail -f "$file" | grep "$string" | while read hit; do #stuff done Answer: Well, the simplest way would be to constantly read from the file, check what's new and test for hits. import time def watch(fn, words): fp = open(fn, 'r') while True: new = fp.readline() # Once all lines are read this just returns '' # until the file changes and a new line appears if new: for word in words: if word in new: yield (word, new) else: time.sleep(0.5) fn = 'test.py' words = ['word'] for hit_word, hit_sentence in watch(fn, words): print "Found %r in line: %r" % (hit_word, hit_sentence) This solution with `readline` works if you know your data will appear in lines. If the data is some sort of stream you need a buffer, larger than the largest `word` you're looking for, and fill it first. It gets a bit more complicated that way...
Call Python function from MATLAB Question: I need to call a Python function from MATLAB. how can I do this? Answer: I had a similar requirement on my system and this was my solution: In MATLAB there is a function called perl.m, which allows you to call perl scripts from MATLAB. Depending on which version you are using it will be located somewhere like C:\Program Files\MATLAB\R2008a\toolbox\matlab\general\perl.m Create a copy called python.m, a quick search and replace of perl with python, double check the command path it sets up to point to your installation of python. You should now be able to run python scripts from MATLAB. **Example** A simple squared function in python saved as "sqd.py", naturally if I was doing this properly I'd have a few checks in testing input arguments, valid numbers etc. import sys def squared(x): y = x * x return y if __name__ == '__main__': x = float(sys.argv[1]) sys.stdout.write(str(squared(x))) Then in MATLAB >> r=python('sqd.py','3.5') r = 12.25 >> r=python('sqd.py','5') r = 25.0 >>
send string to serial Question: Buongiorno, I'm trying to send a simple string to a serial port to command an instrument for noise measures. The strings are very easy: "M 1" = instrument on "M 2" = instrument off "M 3" = begin the measure "M 4" = stop the measure I've found this program: import serial ser = serial.Serial(0) #Seleziona la porta seriale COM4 ser.baudrate = 9600 #Imposta il baudrate a 9600bps ser.open() #apre la porta com ser.close() #verifica se la porta e' aperta if ser.isOpen(): com_num = ser.portstr print ("Porta " + com_num + " aperta") #invia il comando alla seriale buffer = "M 3" ser.write(buffer) #Loop d'attesa caratteri num = 0 while num == 0: num = ser.inWaiting() #scarica il buffer della seriale buffer = ser.read(num) print ("Dati ricevuti dalla seriale:") print buffer ser.close() #chiude la porta else: print ("Porta seriale gia' in uso o inesistente") s = raw_input("digita INVIA per uscire") USING LINUX The program is ok and I have only some problems with the type of string. In fact I had to insert a carriage return but I can't to do it. I said that the program is okay because the instrument turn from off to on when I made my first connection, and on video I read "Porta /dev/ttyS= aperta" thet means "open". But this appens for any kind of string I send. In fact this is like an "iniatilization" of the port, not a really communication. Then I don't manage to send string in the correct way, may be for the problem of carriage return. USING WINDOWS I can't open the port, I have an error of Denied Access to the port, this is the error: ` Traceback (most recent call last): File "C:/d.py", line 9, in ser.open() #apre la porta com File "C:\Programmi\Python26\lib\site-packages\serial\serialwin32.py", line 53, in open raise SerialException("could not open port %s: %s" % (self.portstr, ctypes.WinError())) serial.serialutil.SerialException: could not open port COM1: [Error 5] Accesso negato.` Can you help me to: 1\. Manage to run the program under windows 2\. Manage to give in the exactly way the string with carriage return??? Thak you very much. Stefano Answer: To add the carriage return just append `\r` to your string, or perhaps, it may need a carriage return/linefeed `\r\n`, which some systems use to mark the end of line. Of course, it may only need a linefeed. In that case, you would simply use `\n`. buffer = "M 3\r" or buffer = "M 3\r\n" or buffer = "M 3\n" You might find the [pySerial](http://pyserial.sourceforge.net/) documentation of help in resolving your Windows issues.
Euclidian Distance Python Implementation Question: I am playing with the following code from programming collective intelligence, this is a function from the book that calculated eclidian distance between two movie critics. This function sums the difference of the rankings in the dictionary, but euclidean distance in n dimensions also includes the square root of that sum. AFAIK since we use the same function to rank everyone it does not matter we square root or not, but i was wondering is there a particular reason for that? from math import sqrt # Returns a distance-based similarity score for person1 and person2 def sim_distance(prefs,person1,person2): # Get the list of shared_items si={} for item in prefs[person1]: if item in prefs[person2]: si[item]=1 # if they have no ratings in common, return 0 if len(si)==0: return 0 # Add up the squares of all the differences sum_of_squares=sum([pow(prefs[person1][item]-prefs[person2][item],2) for item in prefs[person1] if item in prefs[person2]]) return 1/(1+sum_of_squares) Answer: The reason the square root is not used is because it is computationally expensive; it is monotonic (i.e., it preserves order) with the square function, so if all you're interested in is the order of the distances, the square root is unnecessary (and, as mentioned, very expensive computationally).
[Resolved]Python socket not receiving anything Question: I'm trying to receive a variable length stream from a camera with python, but get weird behaviour. This is Python 2.6.4 (r264:75706) on linux(Ubuntu 9.10) The message is supposed to come with a static header followed by the size, and rest of the stream. here is the code from socket import * import array import select HOST = '169.254.0.10' PORT = 10001 BUFSIZ = 1024 ADDR = (HOST, PORT) tcpCliSock = socket(AF_INET, SOCK_STREAM) tcpCliSock.connect(ADDR) tcpCliSock.setblocking(0) def dump(x): dfile = open('dump','w') dfile.write(x) dfile.close data='I' tcpCliSock.send(data) tcpCliSock.shutdown(1) ready_to_read, ready_to_write, in_error = select.select( [tcpCliSock], [], [], 30) if ready_to_read == []: print "sokadens" data='' while len(data)<10: chunk = tcpCliSock.recv(1024) print 'recv\'d %d bites'%len(data) data=data+chunk index=data.find('##IMJ') if index == -1: dump(data) raise RuntimeError, "imahe get error" datarr = array.array('B',data) size=datarr[6]+datarr[7]<<8+datarr[8]<<16+datarr[9]<<24 ready_to_read, ready_to_write, in_error = select.select( [tcpCliSock], [], [], 30) if ready_to_read == []: print "sokadens" while len(data)<size: chunk = tcpCliSock.recv(1024) data=data+chunk outfile=open('resim.jpg','w') outfile.write(data[10:]) outfile.close tcpCliSock.close() with this code I either get stuck in a "recv\'d 0 bites" loop(which happens rarely) or this: `recv'd 0 bites` Traceback (most recent call last): File "client.py", line 44, in <module> raise RuntimeError, "imahe get error" RuntimeError: imahe get error which is totally weird(receive 0 bytes but get out of the loop). The dumped data is erroneous, which is expected in that situation Edit 1: the device is supposed to send a JPEG image, preceded by a 10-byte header. When(if) I get past the first loop, I need to check this header for correctness and size info. The program terminates with wrong data error, and the dump file is a bunch of binary garbage, so I have no Idea what I received at the end. I am pretty sure the device at the other side is trying to send the correct data. Edit 2: I found the cause of the problem. You can consider this closed. Answer: You don't really know how many bytes you received, since your code is: data='' while len(data)<10: chunk = tcpCliSock.recv(1024) print 'recv\'d %d bites'%len(data) data=data+chunk i.e., you're receiving bytes in `chunk`, but what you're printing is `len(data)` before you update `data`. So of course it will print 0 the first time, always -- then it will update `data` and exit if the `chunk` was at least 10 bytes. This info is not sufficient to debug your problem, but printing len(chunk), and len(data) upon exiting the loop, can't hurt the attempt to understand what's going on. Also, what's in `dump` when you exit with the `imahe get error` message?
Another neural network knight's tour conundrum Question: I've done my best to make a simple java implementation of the neural network knight's tour finder but I'm completely stumped as to why it fails to work.. there are 6 classes, 3 for the GUI which im pretty sure works fine, and 3 to deal with the actual logic etc. If you are wondering, this is inspired by [ Yacoby's python offering](http://www.yacoby.net/programming/knights-tour.html) He had a problem with the implementation also, although I don't think I'm making the same mistake.. I appreciate its not super coding, but any suggestions gratefully received Neuron class: package model; import java.util.Random; public class Neuron { boolean oldActive=true,active=true; //ie part of the solution int state=0,previousState=0; public Square s1,s2; public Neuron(Square s1,Square s2){ this.s1=s1;this.s2=s2; //status of the neuron is initialised randomly oldActive=active= (new Random()).nextInt(2)==1?true:false; } public int activeNeighbours(){ //discount this neuron if it is active int s=0;if(isActive()){s=-2;} for(Object o:s1.neurons) if(((Neuron)o).isActive())s++; for(Object o:s2.neurons) if(((Neuron)o).isActive())s++; return s; } public boolean hasChanged(){ return oldActive != active||previousState != state; } public boolean isActive(){return active;} public void updateState(){ previousState=state; state+=2-activeNeighbours(); } public void updateOutput(){ oldActive=active; if (state>3) active=true; else if(state<0)active=false; } } Square class: package model; import java.util.Vector; public class Square { Vector neurons=new Vector();//neurons which connect to this square public int col; public int row; public Square(int row, int col){ this.col=col; this.row=row; } /** * creates a neuron which links this square with the square s, * then tells both squares about it, * also returns the neuron for inclusion in the global list. * * @param s * @return neuron n, or null */ public Neuron link(Square s){ for(Object o: neurons) //discounts the link if it has already been created if (((Neuron)o).s1==s ||((Neuron)o).s2==s)return null; Neuron n=new Neuron(this,s); neurons.add(n); s.neurons.add(n); return n; } } Control class: package model; import java.util.Vector; import gui.Board; public class Control { Board b; //the graphic board Vector neurons=new Vector(); //all 168 neurons Square[][] squares=new Square[8][8]; int[][] moves={ {-2,-2, 2, 2,-1,-1, 1, 1}, { 1,-1, 1,-1, 2,-2, 2,-2}}; public Control(Board b){ this.b=b; //create 64 squares for(int row=0;row<8;row++) for (int col=0;col<8;col++) squares[row][col]=new Square(row,col); //create neurons for(int row=0;row<8;row++) for(int col=0;col<8;col++) findMoves(squares[row][col]); dl();//draw the initial active neurons on the graphic //try this many enumerations of the board before giving up int counter=1000; //the main updating loop while(counter>0){ for(Object o:neurons)((Neuron)o).updateState();//update all the states for(Object o:neurons)((Neuron)o).updateOutput();//then all the outputs counter--; if(isStable())break; } dl(); //draw the neurons when the solution is found/attempt abandoned } /** * draws the lines (active neurons) on the graphic display */ private void dl(){ b.clear(); for(Object o:neurons) b.drawLine((Neuron)o); b.repaint(); } /** * Identify all of the squares legal to move to from this one - link with a neuron, * then add the neuron to the collection * * @param s */ private void findMoves(Square s){ for (int i=0;i<moves[0].length;i++){ int newRow=s.row+moves[0][i]; int newCol=s.col+moves[1][i]; if(isInBounds(newRow,newCol)){ Neuron n=s.link(squares[newRow][newCol]); if (n!=null)neurons.add(n); } } } /** * tests whether the identified square is contained within the (8*8) board * @param row * @param col * @return */ private boolean isInBounds(int row,int col){ if (row>=0 && row<8 && col>=0 && col<8)return true; return false; } /** * returns true if no neuron changes its state/output * @return */ private boolean isStable(){ for (Object o:neurons) if(((Neuron)o).hasChanged()) return false; return true; } public static void main(String[]s){ Board b=new Board(50,50,60); new Control(b); } } the GUI classes: - Board class: package gui; import java.util.Vector; import javax.swing.JFrame; import model.Neuron; /** * sets up the graphic representation of the chess board, and draws on the neurons as required * @param x * @param y * @param squareSize */ public class Board extends JFrame { Vector lines=new Vector(); int squareSize; public Board(int x, int y,int squareSize){ //initialize dimensions etc super("there."); setDefaultCloseOperation(EXIT_ON_CLOSE); setBounds(x,y,squareSize*8+8,squareSize*8+30); this.setLayout(null); this.setVisible(true); this.squareSize=squareSize; //draw the squares drawSquares(); repaint(); } private void drawSquares(){ for(int i=0;i<8;i++) for (int j=0;j<8;j++){ GuiSquare s=new GuiSquare(i,j,squareSize); this.add(s,0); } } /** * represent the neuron as a line on the board * @param n */ public void drawLine(Neuron n){ Line l=new Line(n.s1.col+n.s1.row*8,n.s2.col+n.s2.row*8,squareSize); if(n.isActive()){ lines.add(l); add (l,0); } } /** * removes all of the lines (neurons) from the board */ public void clear(){ for(Object o:lines) remove((Line)o); lines.clear(); } } GuiSquare class: package gui; import java.awt.*; public class GuiSquare extends Component{ int row,col; int x; int y; int size; public GuiSquare(int row,int col,int size){ this.row=row;this.col=col;this.size=size; y=row*size; x=col*size; setBounds(x,y,size,size); setBackground((row+col)%2==0?Color.white:Color.black); } public void paint(Graphics g){ g.setColor(getBackground()); g.fillRect(0,0, size-1, size-1); g.setColor(Color.gray); g.drawString(""+((row*8)+col), size/2, size/2); } } Line class: package gui; import java.awt.*; public class Line extends Component{ int x1,y1,x2,y2; int x,y,w,h; public Line(int a,int b, int squareSize){ setBackground(Color.blue); x1=((a%8)*squareSize)+(squareSize/2); y1=((a/8)*squareSize)+(squareSize/2); x2=((b%8)*squareSize)+(squareSize/2); y2=((b/8)*squareSize)+(squareSize/2); if(x1<x2){ x=x1;w=x2-x1; }else{ x=x2;w=x1-x2; } if(y1<y2){ y=y1;h=y2-y1; }else{ y=y2;h=y1-y2; } setBounds(x,y,w,h); } public void paint(Graphics g){ g.setColor(getBackground()); g.drawLine(x1-x,y1-y,x2-x,y2-y); } } Answer: I think there is a problem with my code, in that it works fine, but it seems to use a slightly different equation than the one proposed on Wikipedia due to it taking into account the active status of the current neurons. It is waiting for me to go back to it and write it so it uses the proposed formula Try: public int activeNeighbours(){ int s=0; //changed for(Object o:s1.neurons) if(((Neuron)o).isActive())s++; for(Object o:s2.neurons) if(((Neuron)o).isActive())s++; return s; } public boolean hasChanged(){ return oldActive != active||previousState != state; } public boolean isActive(){return active;} public void updateState(){ previousState=state; state+=4-activeNeighbours(); //changed }
Will python.subprocess(cppBinaryExe) compromise cppBinaryExe's performance? Question: i am quite new to python.subprocess() if i folk a new process from python, will the execution speed of this new process be compromised? imagine that i have the #python import subprocess subprocess.call( MyBinary ) basically, is there any difference between ./MyBinary and ./python ruMyBinary.py ? Answer: No. A separate process is a separate process. It competes for OS resources with all other processes "fairly". Your python process that simply does `subprocess.call` is a process, and does consume some system resources. But relatively few, since it will be waiting for a system call to finish. It will occupy a slot in the process table, so it does have a microscopic impact.
How to get SIP to find .sip files for and installed library Question: I'm trying to create python bindings for [source-highlight- qt](http://srchiliteqt.sourceforge.net/) using sip. I'm working on ubuntu - I've installed python-qt4-dev, which has installed the pyqt sip files to /usr/share/sip/PyQt4/ In my sip file, I've got this import: %Import QtCore/qstring.sip I'm getting this error when I run my configure.py: sip: Unable to find file "QtCore/qstring.sip" How do I get sip to find the pyqt .sip files? Answer: This is how I solved it: In my configure.py, I needed to create a pyqtconfig: from PyQt4 import pyqtconfig config = pyqtconfig.Configuration() and then add directories for sip to include: command = " ".join( [config.sip_bin, "-c", ".", "-b", build_file, "-I"+config.pyqt_sip_dir, "-I"+config.qt_inc_dir, config.pyqt_sip_flags, "lib/GNUSyntaxHighlighter.sip"] )
Principal component analysis in Python Question: I'd like to use principal component analysis (PCA) for dimensionality reduction. Does numpy or scipy already have it, or do I have to roll my own using [`numpy.linalg.eigh`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigh.html)? I don't just want to use singular value decomposition (SVD) because my input data are quite high-dimensional (~460 dimensions), so I think SVD will be slower than computing the eigenvectors of the covariance matrix. I was hoping to find a premade, debugged implementation that already makes the right decisions for when to use which method, and which maybe does other optimizations that I don't know about. Answer: Months later, here's a small class PCA, and a picture: #!/usr/bin/env python """ a small class for Principal Component Analysis Usage: p = PCA( A, fraction=0.90 ) In: A: an array of e.g. 1000 observations x 20 variables, 1000 rows x 20 columns fraction: use principal components that account for e.g. 90 % of the total variance Out: p.U, p.d, p.Vt: from numpy.linalg.svd, A = U . d . Vt p.dinv: 1/d or 0, see NR p.eigen: the eigenvalues of A*A, in decreasing order (p.d**2). eigen[j] / eigen.sum() is variable j's fraction of the total variance; look at the first few eigen[] to see how many PCs get to 90 %, 95 % ... p.npc: number of principal components, e.g. 2 if the top 2 eigenvalues are >= `fraction` of the total. It's ok to change this; methods use the current value. Methods: The methods of class PCA transform vectors or arrays of e.g. 20 variables, 2 principal components and 1000 observations, using partial matrices U' d' Vt', parts of the full U d Vt: A ~ U' . d' . Vt' where e.g. U' is 1000 x 2 d' is diag([ d0, d1 ]), the 2 largest singular values Vt' is 2 x 20. Dropping the primes, d . Vt 2 principal vars = p.vars_pc( 20 vars ) U 1000 obs = p.pc_obs( 2 principal vars ) U . d . Vt 1000 obs, p.obs( 20 vars ) = pc_obs( vars_pc( vars )) fast approximate A . vars, using the `npc` principal components Ut 2 pcs = p.obs_pc( 1000 obs ) V . dinv 20 vars = p.pc_vars( 2 principal vars ) V . dinv . Ut 20 vars, p.vars( 1000 obs ) = pc_vars( obs_pc( obs )), fast approximate Ainverse . obs: vars that give ~ those obs. Notes: PCA does not center or scale A; you usually want to first A -= A.mean(A, axis=0) A /= A.std(A, axis=0) with the little class Center or the like, below. See also: http://en.wikipedia.org/wiki/Principal_component_analysis http://en.wikipedia.org/wiki/Singular_value_decomposition Press et al., Numerical Recipes (2 or 3 ed), SVD PCA micro-tutorial iris-pca .py .png """ from __future__ import division import numpy as np dot = np.dot # import bz.numpyutil as nu # dot = nu.pdot __version__ = "2010-04-14 apr" __author_email__ = "denis-bz-py at t-online dot de" #............................................................................... class PCA: def __init__( self, A, fraction=0.90 ): assert 0 <= fraction <= 1 # A = U . diag(d) . Vt, O( m n^2 ), lapack_lite -- self.U, self.d, self.Vt = np.linalg.svd( A, full_matrices=False ) assert np.all( self.d[:-1] >= self.d[1:] ) # sorted self.eigen = self.d**2 self.sumvariance = np.cumsum(self.eigen) self.sumvariance /= self.sumvariance[-1] self.npc = np.searchsorted( self.sumvariance, fraction ) + 1 self.dinv = np.array([ 1/d if d > self.d[0] * 1e-6 else 0 for d in self.d ]) def pc( self ): """ e.g. 1000 x 2 U[:, :npc] * d[:npc], to plot etc. """ n = self.npc return self.U[:, :n] * self.d[:n] # These 1-line methods may not be worth the bother; # then use U d Vt directly -- def vars_pc( self, x ): n = self.npc return self.d[:n] * dot( self.Vt[:n], x.T ).T # 20 vars -> 2 principal def pc_vars( self, p ): n = self.npc return dot( self.Vt[:n].T, (self.dinv[:n] * p).T ) .T # 2 PC -> 20 vars def pc_obs( self, p ): n = self.npc return dot( self.U[:, :n], p.T ) # 2 principal -> 1000 obs def obs_pc( self, obs ): n = self.npc return dot( self.U[:, :n].T, obs ) .T # 1000 obs -> 2 principal def obs( self, x ): return self.pc_obs( self.vars_pc(x) ) # 20 vars -> 2 principal -> 1000 obs def vars( self, obs ): return self.pc_vars( self.obs_pc(obs) ) # 1000 obs -> 2 principal -> 20 vars class Center: """ A -= A.mean() /= A.std(), inplace -- use A.copy() if need be uncenter(x) == original A . x """ # mttiw def __init__( self, A, axis=0, scale=True, verbose=1 ): self.mean = A.mean(axis=axis) if verbose: print "Center -= A.mean:", self.mean A -= self.mean if scale: std = A.std(axis=axis) self.std = np.where( std, std, 1. ) if verbose: print "Center /= A.std:", self.std A /= self.std else: self.std = np.ones( A.shape[-1] ) self.A = A def uncenter( self, x ): return np.dot( self.A, x * self.std ) + np.dot( x, self.mean ) #............................................................................... if __name__ == "__main__": import sys csv = "iris4.csv" # wikipedia Iris_flower_data_set # 5.1,3.5,1.4,0.2 # ,Iris-setosa ... N = 1000 K = 20 fraction = .90 seed = 1 exec "\n".join( sys.argv[1:] ) # N= ... np.random.seed(seed) np.set_printoptions( 1, threshold=100, suppress=True ) # .1f try: A = np.genfromtxt( csv, delimiter="," ) N, K = A.shape except IOError: A = np.random.normal( size=(N, K) ) # gen correlated ? print "csv: %s N: %d K: %d fraction: %.2g" % (csv, N, K, fraction) Center(A) print "A:", A print "PCA ..." , p = PCA( A, fraction=fraction ) print "npc:", p.npc print "% variance:", p.sumvariance * 100 print "Vt[0], weights that give PC 0:", p.Vt[0] print "A . Vt[0]:", dot( A, p.Vt[0] ) print "pc:", p.pc() print "\nobs <-> pc <-> x: with fraction=1, diffs should be ~ 0" x = np.ones(K) # x = np.ones(( 3, K )) print "x:", x pc = p.vars_pc(x) # d' Vt' x print "vars_pc(x):", pc print "back to ~ x:", p.pc_vars(pc) Ax = dot( A, x.T ) pcx = p.obs(x) # U' d' Vt' x print "Ax:", Ax print "A'x:", pcx print "max |Ax - A'x|: %.2g" % np.linalg.norm( Ax - pcx, np.inf ) b = Ax # ~ back to original x, Ainv A x back = p.vars(b) print "~ back again:", back print "max |back - x|: %.2g" % np.linalg.norm( back - x, np.inf ) # end pca.py ![alt text](http://i44.tinypic.com/289aj9u.png)
Quitting matplotlib.pyplot animation gracefully Question: I have a script that plots data of some photometry apertures, and I want to plot them in an xy plot. I am using matplotlib.pyplot with python 2.5. The input data is stored in around 500 files and read. I am aware that this is not the most efficient way of inputting the data but that's another issue... Example code: import matplotlib.pyplot as plt xcoords = [] ycoords = [] # lists are populated with data from first file pltline, = plt.plot(xcoords, ycoords, 'rx') # then loop populating the data from each file for file in filelist: xcoords = [...] ycoords = [...] pltline.set_xdata(xcoords) pltline.set_ydata(ycoords) plt.draw() As there are over 500 files, I will occasionally want to close the animation window in the middle of the plotting. My code to plot works but it doesn't exit very gracefully. The plot window does not respond to clicking the close button and I have to `Ctrl+C` out of it. Can anyone help me find a way to close the animation window while the script is running whilst looking graceful (well more graceful than a series of python traceback errors)? Answer: If you update the data and do the draw in a loop, you should be able to interrupt it. Here's an example (that draws a stationary circle and then moves a line around the perimeter): from pylab import * import time data = [] # make the data for i in range(1000): a = .01*pi*i+.0007 m = -1./tan(a) x = arange(-3, 3, .1) y = m*x data.append((clip(x+cos(a), -3, 3),clip(y+sin(a), -3, 3))) for x, y in data: # make a dynamic plot from the data try: plotdata.set_data(x, y) except NameError: ion() fig = figure() plot(cos(arange(0, 2.21*pi, .2)), sin(arange(0, 2.21*pi, .2))) plotdata = plot(x, y)[0] xlim(-2, 2) ylim(-2, 2) draw() time.sleep(.01) I put in the `time.sleep(.01)` command to be extra sure that I could break the run, but in my tests (running Linux) it wasn't necessary.
Calling Method from Different Python File Question: As I'm currently learning Django / Python, I've not really been using the concept of Classes, yet. As far as I'm aware the method isn't static.. it's just a standard definition. So let's say I have this Package called `Example1` with a `views.py` that contains this method: def adder(x,y): return x + y Then I have an `Example2` which also has a `views.py` where I'd like to use this method `adder`. How would I got about doing this? EDIT: In Java it would be a simple instantiation then a `instantiation.Method()` or if it was static it would be `SomeClass.Method()` however I'm unsure how I should approach this in Python. Answer: Python has module level and class level methods. In this concept a "module" is a very special class that you get by using `import` instead of `Name()`. Try from Example1.views import adder as otherAdder to get access to the module level method. Now you can call `otherAdder()` and it will execute the code in the other module. Note that the method will be executed in the context of `Example1.views`, i.e. when it references things, it will look there.
A dictionary with values that are dictionaries: trying to sum across those keys in python Question: Data structure is a dictionary, each value is another dictionary, like: >>> from lib import schedule >>> schedule = schedule.Schedule() >>> game = schedule.games[0] >>> game.home <lib.schedule.Team instance at 0x9d97c6c> >>> game.home.lineup {'guerv001': {'HR': 392, '1B': 1297}, 'kendh001': {'HR': 12, '1B': 201}, 'andeg001': {'HR': 272, '1B': 1572}, 'mattg002': {'HR': 104, '1B': 632}, 'figgc001': {'HR': 26, '1B': 672}, 'iztum001': {'HR': 16, '1B': 253}, 'huntt001': {'HR': 213, '1B': 834}, 'quinr002': {'HR': 23, '1B': 200}, 'napom001': {'HR': 46, '1B': 96}} Would like Team to have a method getTotals(self, category) where if you called: game.home.getTotals('HR') The method would, in this case, yield: 1104 Essentially you can see what I'm trying to do. Any ideas? **update:** I have this working with two list comprehensions but would like to winnow it down to one: def getTotals(self, category): cats = [x for x in self.lineup.values()] return sum([x[category] for x in cats]) **another update:** Based on [inspectorg4dget](http://stackoverflow.com/users/198633/inspectorg4dget)'s helpful feedback below I've gotten it. Thanks! def getTotals(self, category): return sum(self.lineup[man][category] for man in self.lineup.keys()) **final update:** Based on [Nadia](http://stackoverflow.com/users/97828/nadia- alramli)'s feedback, here's another approach: def getTotals(self, category): return sum(value.get(category, 0) for value in self.lineup.values()) Answer: You can use a generator expression: def total(category): return sum(value.get(category, 0) for value in game.home.lineup.values()) >>> total('HR') 1104 I used [dict.get](http://docs.python.org/library/stdtypes.html#dict.get) to make the default 0 if the category is missing from any dictionary. The self version: def total(self, category): return sum(value.get(category, 0) for value in self.lineup.values())
Python: Issue reading data lines multiple times from a file Question: I am trying to make a Python2.6 script on a Win32 that will read all the text files stored in a directory and print only the lines containing actual data. A sample file - Set : 1 Date: 10212009 12 34 56 25 67 90 End Set +++++++++ Set: 2 Date: 10222009 34 56 89 25 67 89 End Set In the above example file, I want to print only the lines 3, 4 and 9, 10 (the actual data values). The program does this iteratively on all txt files. I wrote the script as below and am testing it on a single txt file as I go. My logic is to read the input files one by one and search for a start string. As soon as the match is found, start searching for end string. when both are found, print the lines from start string to end string.Repeat on the rest of the file before opening another file. The problem I am having is that it successfully reads the Set 1 of data, but then screws up on subsequent sets in the file. For set 2, it identifies the no. of lines to read, but prints them starting at incorrect line number. A little digging leads to following explanations - 1\. Using seek and tell to reposition the 2nd iteration of the loop, which did not work since the file is read from buffer and that screws up "tell" value. 2\. Opening the file in binary mode helped someone, but it is not working for me. 3\. Open the file with 0 buffer mode, but it did not work. Second problem I am having is when it prints data from Set 1, it inserts a blank line between 2 lines of data values. How can I get rid of it? Note: Ignore all references to next_run in the code below. I was trying it out for repositioning line read. Subsequent searches for start string should begin from the last position of end string #!C:/Python26 python # Import necessary modules import os, glob, string, sys, fileinput, linecache from goto import goto, label # Set working path path = 'C:\\System_Data' # -------------------- # PARSE DATA MODULE # -------------------- # Define the search strings for data start_search = "Set :" end_search ="End Set" # For Loop to read the input txt files one by one for inputfile in glob.glob( os.path.join( path, '*.txt' ) ): inputfile_fileHandle = open ( inputfile, 'rb', 0 ) print( "Current file being read: " +inputfile ) # start_line initializes to first line start_line = 0 # After first set of data is extracted, next_run will store the position to read the rest of the file # next_run = 0 # start reading the input files, one line by one line for line in inputfile: line = inputfile_fileHandle.readline() start_line += 1 # next_run+=1 # If a line matched with the start_search string has_match = line.find( start_search ) if has_match >= 0: print ( "Start String found at line number: %d" %( start_line ) ) # Store the location where the search will be restarted # next_run = inputfile_fileHandle.tell() #inputfile_fileHandle.lineno() print ("Current Position: %d" % next_run) end_line = start_line print ( "Start_Line: %d" %start_line ) print ( "End_Line: %d" %end_line ) #print(line) for line in inputfile: line = inputfile_fileHandle.readline() #print (line) end_line += 1 has_match = line.find(end_search) if has_match >= 0: print 'End String found at line number: %d' % (end_line) # total lines to print: k=0 # for loop to print all the lines from start string to end string for j in range(0,end_line-start_line-1): print linecache.getline(inputfile, start_line +1+ j ) k+=1 print ( "Number of lines Printed: %d " %k ) # Using goto to get out of 2 loops at once goto .re_search_start_string label .re_search_start_string #inputfile_fileHandle.seek(next_run,0) inputfile_fileHandle.close () Answer: in_data = False for line in open( 'data.txt' ): if line.startswith( 'Date:' ): in_data = True elif line.startswith( 'End Set' ): in_data = False elif in_data: print line.rstrip() Just put something like that inside a loop over your files (i.e. os.walk) and you should be good to go
To understand Python's optparse Question: Thank you for quack in pointing out the off-by-one! The following code is my first attempt in writing code with Optparse. **How can you fix the following bug in getting the help by Optparse?** #!/usr/bin/env python import sys import os from optparse import OptionParser e = sys.argv[1] b = sys.argv[2] no = sys.argv[3] def set_figu(figu): sum = 777 return sum def main(): usage = "Usage: negative_bin_base.py <eksponentti> <siirre> <figu>" parser = OptionParser(usage) parser.add_option("-h", "--help", dest="help", help="get synopsis of parameters") # print the output of the work-horse print set_figu(no) (options, args) = parser.parse_args() if len(args) < 4: parser.error("incorrect number of arguments") if options.informative: print "reading %s..." % options.help if __name__ == "__main__": main() **Example of wrong output with correct number of parameters** python negative_bin_base.py 13 13 332 Traceback (most recent call last): File "negative_bin_base.py", line 37, in <module> main() File "negative_bin_base.py", line 26, in main help="get synopsis of parameters") File "/usr/lib/python2.6/optparse.py", line 1020, in add_option self._check_conflict(option) File "/usr/lib/python2.6/optparse.py", line 995, in _check_conflict option) optparse.OptionConflictError: option -h/--help: conflicting option string(s): -h, --help Answer: Constructor for `class optparse.OptionParser(...)` has optional named parameter 'add_help_option', which defaults to 'True'. You will have to explicitly reject default help option and message, if you want to provide your own. `parser = OptionParser(usage, add_help_option=False)`
Python detect USB drive then assign drive letter? Question: Here is the problem. We have 100s of external 500gb USB drives. Each drive will travel to a new location through the year. What is the best way to automatically detect that a USB drive has been plugged into a Windows system, then assign a Z:\ drive letter? These USB drives will be plugged into lots of different computers so a script like this import subprocess diskpart_data = "z-drive.txt" open (diskpart_data, "w").write (""" select volume F: assign letter=Z """) subprocess.call ('diskpart /s %s' % diskpart_data) is hard to use due to the dynamic nature of the mobile USB drive on different Windows systems all the time? Could you autodetect through WMI or do some kind of volume mount with NTFS? Answer: as terabytest said, you may run a script from an autorun.inf in the root of the drive. personally, i would do with a batch script: (echo select volume %~d0 && echo assign letter=Z) | diskpart the `%~d0` retrieves the drive letter of the currently executing batch file. if this is not sufficient, there is a way of being informed when a removable drive is inserted by using the [device management functions](http://msdn.microsoft.com/en-us/library/aa363224%28VS.85%29.aspx) of the Windows API. you have to first register for notification using [`RegisterDeviceNotification()`](http://msdn.microsoft.com/en- us/library/aa363431%28VS.85%29.aspx) then process the [`WM_DEVICECHANGE`](http://msdn.microsoft.com/en- us/library/aa363480%28VS.85%29.aspx) message in the event loop. unfortunately, this needs an event loop, and i don't know how you can easily create one in python (apart from creating it from scratch: [here](http://msdn.microsoft.com/en-us/library/ms644928%28VS.85%29.aspx) is an example message loop, note that in your case you should not need to create a window, only have a message loop).
replacing Matlab with python Question: i am a engineering student and i have to do a lot of numerical processing, plots, simulations etc. The tool that i use currently is Matlab. I use it in my university computers for most of my assignments. However, i want to know what are the free options available. i have done some research and many have said that python is a worthy replacement for matlab in various scenarios. i want to know how to do all this with python. i am using a mac so how do i install the different python packages. what are those packages? is it really a viable alternative? what are the things i can and cannot do using this python setup? Answer: On a Mac the easiest ways to get started are (in no particular order): * [Enthought Python Distribution](http://www.enthought.com/products/epd.php) which includes most scientific packages you are likely to need. Free for academic/non-commercial use. * [Macports](http://www.macports.org/) \- up to date with latest releases, so `sudo port install py26-numpy py26-scipy py26-matplotlib py26-ipython` should get you started. * [Scipy Superpack](https://fonnesbeck.github.io/ScipySuperpack/) \- script to install recent svn versions of all the important packages. I've done exactly this (replace Matlab with Python) about 2 years ago and haven't looked back. The broadcasting in Python, more intuitive memory model and other Numpy advantages make numerical work a complete pleasure. Plus with f2py, cython it is incredibly easy to put inner loops in another language. [This](http://www.scipy.org/NumPy_for_Matlab_Users) is a good place to start - other impressive pages to provide motiviation are [PerformancePython](http://wiki.scipy.org/PerformancePython) and [ParallelProgramming](http://wiki.scipy.org/ParallelProgramming). Be sure to understand Pythons "variable is a reference to an object" semantics... after that adjustment everything is plain sailing. One of the coolest things that beats matlab is in 2 lines I run over 8 cores... `p = Pool(8); res = p.map(analysis_function,list_of_data)` \- MATLAB parallels toolboxes are so expensive I've yet to see a University that actually has them.
Making ORM with Python's Storm Question: The question is based on [the thread](http://stackoverflow.com/questions/1779239/converting-sql-commands-to- pythons-orm), since I observed that Storm allows me reuse my SQL-schemas. **How can you solve the following error message in Storm?** The code is based on Jason's answer and on Storm's manual. import os, pg, sys, re, psycopg2, storm from storm.locals import * from storm import * class Courses(): subject = Unicode() database = create_database("postgres://naa:123@localhost:5432/tk") store = Store(database) course = Courses() course.subject = 'abcd' store.add(course) It gives you Traceback (most recent call last): File "<stdin>", line 13, in <module> File "/usr/lib/python2.6/dist-packages/storm/store.py", line 245, in add obj_info = get_obj_info(obj) File "/usr/lib/python2.6/dist-packages/storm/info.py", line 40, in get_obj_info obj_info = ObjectInfo(obj) File "/usr/lib/python2.6/dist-packages/storm/info.py", line 162, in __init__ self.cls_info = get_cls_info(type(obj)) File "/usr/lib/python2.6/dist-packages/storm/info.py", line 51, in get_cls_info cls.__storm_class_info__ = ClassInfo(cls) File "/usr/lib/python2.6/dist-packages/storm/info.py", line 69, in __init__ raise ClassInfoError("%s.__storm_table__ missing" % repr(cls)) storm.exceptions.ClassInfoError: <type 'instance'>.__storm_table__ missing This suggests to me that some module is missing. There is no module `instance` in Storm. Answer: I'll leave out the connection details because I'm not terribly familiar with Postgres. from storm.locals import * class Courses(object): __storm_table__ = 'courses' pkey = Int(primary=True) course_nro = Unicode() course = Courses() course.course_nro = 'abcd' store.add(course) store.commit() Of course, if you want to do the constructor and initialization on one line, you can use [pysistence](http://packages.python.org/pysistence/index.html)'s [expandos](http://packages.python.org/pysistence/pysistence/expando.html): from storm.locals import * from pysistence import Expando class Courses(Expando): __storm_table__ = 'courses' pkey = Int(primary=True) course_nro = Unicode() course = Courses(course_nro='abcd') store.add(course) store.commit()
Distribute a Python program with a minimal environment Question: I want to distribute a Python application to windows users who don't have Python or the correct Python version. I have tried py2exe conversion but my Python program is really complex and involve code import on the fly by xmlrpc process so it is not suitable for py2exe. The complete Python folder takes around 80MB but this includes docs and a lot of non-essential things. Do you know if there exists a small package of a minimal Python interpreter I can include with my program ? Include a folder of 80MB is a bit big ;) Answer: [PyInstaller](http://www.google.com/search?client=safari&rls=en&q=pyinstaller&ie=UTF-8&oe=UTF-8) is a py2exe "competitor" that has many extras (such as being cross-platform, supporting popular third party packages "out of the box", and explicitly supporting advanced importing options) -- it might meet your needs. Just be sure to install the SVN trunk -- the existing (1.3) release is way, WAY obsolete (PyInstaller is under active development again since quite a while, but I can't convince the current maintainers to stop and do a RELEASE already -- they're kind of perfectionists and keep piling more and more great goodies, optimizations, enhancements, etc, into the SVN trunk instead;-).
How to apply a logical operator to all elements in a python list Question: I have a list of booleans in python. I want to AND (or OR or NOT) them and get the result. The following code works but is not very pythonic. def apply_and(alist): if len(alist) > 1: return alist[0] and apply_and(alist[1:]) else: return alist[0] Any suggestions on how to make it more pythonic appreciated. Answer: Logical `and` across all elements in `a_list`: all(a_list) Logical `or` across all elements in `a_list`: any(a_list) * * * If you feel creative, you can also do: import operator def my_all(a_list): return reduce(operator.and_, a_list, True) def my_any(a_list): return reduce(operator.or_, a_list, False) keep in mind that those aren't evaluated in short circuit, whilst the built- ins are ;-) another funny way: def my_all_v2(a_list): return len(filter(None,a_list)) == len(a_list) def my_any_v2(a_list): return len(filter(None,a_list)) > 0 and yet another: def my_all_v3(a_list): for i in a_list: if not i: return False return True def my_any_v3(a_list): for i in a_list: if i: return True return False and we could go on all day, but yes, the pythonic way is to use `all` and `any` :-) By the way, Python has not tail recursion elimination, so don't try to translate LISP code directly ;-)
Running average in Python Question: Is there a pythonic way to **build up a list that contains a running average** of some function? After reading a fun little piece about [Martians, black boxes, and the Cauchy distribution](http://www.johndcook.com/Cauchy%5Festimation.html), I thought it would be fun to calculate a running average of the Cauchy distribution myself: import math import random def cauchy(location, scale): p = 0.0 while p == 0.0: p = random.random() return location + scale*math.tan(math.pi*(p - 0.5)) # is this next block of code a good way to populate running_avg? sum = 0 count = 0 max = 10 running_avg = [] while count < max: num = cauchy(3,1) sum += num count += 1 running_avg.append(sum/count) print running_avg # or do something else with it, besides printing I think that this approach works, but I'm curious if there might be a more elegant approach to building up that `running_avg` list than using loops and counters (e.g. [list comprehensions](http://docs.python.org/tutorial/datastructures.html#list- comprehensions)). There are some related questions, but they address more complicated problems (small window size, exponential weighting) or aren't specific to Python: * <http://stackoverflow.com/questions/488670/calculate-exponential-moving-average-in-python> * <http://stackoverflow.com/questions/1174984/how-to-efficiently-calculate-a-running-standard-deviation> * <http://stackoverflow.com/questions/1319891/calculating-the-moving-average-of-a-list> Answer: You could write a generator: def running_average(): sum = 0 count = 0 while True: sum += cauchy(3,1) count += 1 yield sum/count Or, given a generator for Cauchy numbers and a utility function for a running sum generator, you can have a neat generator expression: # Cauchy numbers generator def cauchy_numbers(): while True: yield cauchy(3,1) # running sum utility function def running_sum(iterable): sum = 0 for x in iterable: sum += x yield sum # Running averages generator expression (** the neat part **) running_avgs = (sum/(i+1) for (i,sum) in enumerate(running_sum(cauchy_numbers()))) # goes on forever for avg in running_avgs: print avg # alternatively, take just the first 10 import itertools for avg in itertools.islice(running_avgs, 10): print avg
Python: Analyzing complex statements during execution Question: I am wondering if there is any way to get some meta information about the interpretation of a python statement during execution. Let's assume this is a complex statement of some single statements joined with **or** (A, B, ... are boolean functions) if A or B and ((C or D and E) or F) or G and H: and I want to know which part of the statement is causing the statement to evaluate to True so I can do something with this knowledge. In the example, there would be 3 possible candidates: A B and ((C or D and E) or F) G and H And in the second case, I would like to know if it was `(C or D and E)` or `F` that evaluated to True and so on... Is there any way without parsing the statement? Can I hook up to the interpreter in some way or utilize the **inspect module** in a way that I haven't found yet? I do not want to debug, it's really about knowing which part of this or-chain triggered the statement at runtime. **Edit - further information:** The type of application that I want to use this in is a categorizing algorithm that inputs an object and outputs a certain category for this object, based on its attributes. I need to know which attributes were decisive for the category. As you might guess, the complex statement from above comes from the categorization algorithm. The code for this algorithm is generated from a formal pseudo-code and contains about 3,000 nested if-elif-statements that determine the category in a hierarchical way like if obj.attr1 < 23 and (is_something(obj.attr10) or eats_spam_for_breakfast(obj)): return 'Category1' elif obj.attr3 == 'Welcome Home' or count_something(obj) >= 2: return 'Category2a' elif ... So aside from the category itself, I need to _flag the attributes that were decisive for that category_ , so if I'd delete all other attributes, the object would still be assigned to the same category (due to the `or`s within the statements). The statements can be really long, up to 1,000 chars, and deeply nested. Every object can have up to 200 attributes. Thanks a lot for your help! Edit 2: Haven't found time in the last two weeks. Thanks for providing this solution, it works! Answer: Could you recode your original code: if A or B and ((C or D and E) or F) or G and H: as, say: e = Evaluator() if e('A or B and ((C or D and E) or F) or G and H'): ...? If so, there's hope!-). The Evaluator class, upon `__call__`, would `compile` its string argument, then `eval` the result with (an empty real dict for globals, and) a pseudo-`dict` for `locals` that actually delegates the value lookups to the locals and globals of its caller (just takes a little black magic, but, not too bad;-) and also takes note of what names it's looked up. Given Python's `and` and `or`'s short-circuiting behavior, you can infer from the actual set of names that were actually looked up, which one determined the truth value of the expression (or each subexpression) -- in an `X or Y or Z`, the first true value (if any) will be the last one looked up, and in a `X and Y and Z`, the first false one will. Would this help? If yes, and if you need help with the coding, I'll be happy to expand on this, but first I'd like some confirmation that getting the code for `Evaluator` **would** indeed be solving whatever problem it is that you're trying to address!-) **Edit** : so here's coding implementing Evaluator and exemplifying its use: import inspect import random class TracingDict(object): def __init__(self, loc, glob): self.loc = loc self.glob = glob self.vars = [] def __getitem__(self, name): try: v = self.loc[name] except KeyError: v = self.glob[name] self.vars.append((name, v)) return v class Evaluator(object): def __init__(self): f = inspect.currentframe() f = inspect.getouterframes(f)[1][0] self.d = TracingDict(f.f_locals, f.f_globals) def __call__(self, expr): return eval(expr, {}, self.d) def f(A, B, C, D, E): e = Evaluator() res = e('A or B and ((C or D and E) or F) or G and H') print 'R=%r from %s' % (res, e.d.vars) for x in range(20): A, B, C, D, E, F, G, H = [random.randrange(2) for x in range(8)] f(A, B, C, D, E) and here's output from a sample run: R=1 from [('A', 1)] R=1 from [('A', 1)] R=1 from [('A', 1)] R=1 from [('A', 0), ('B', 1), ('C', 1)] R=1 from [('A', 1)] R=1 from [('A', 0), ('B', 0), ('G', 1), ('H', 1)] R=1 from [('A', 1)] R=1 from [('A', 1)] R=1 from [('A', 0), ('B', 1), ('C', 1)] R=1 from [('A', 1)] R=1 from [('A', 0), ('B', 1), ('C', 1)] R=1 from [('A', 1)] R=1 from [('A', 1)] R=1 from [('A', 1)] R=0 from [('A', 0), ('B', 0), ('G', 0)] R=1 from [('A', 1)] R=1 from [('A', 1)] R=1 from [('A', 1)] R=0 from [('A', 0), ('B', 0), ('G', 0)] R=1 from [('A', 0), ('B', 1), ('C', 1)] You can see that often (about 50% of the time) A is true, which short-circuits everything. When A is false, B evaluates -- when B is also false, then G is next, when B is true, then C.
Passing SQLite variables in Python Question: I am writing a app in python and utilzing sqlite. I have a list of strings which I would like to add too the database, where each element represents some data which coincides with the column it will be put. currently I have something like this cursor.execute("""insert into credit values ('Citi','5567','visa',6000,9.99,'23',9000)""") I can add strings easily but dont know how to add the variables of my list. Answer: Use parameters to `.execute()`: query = """ INSERT INTO credit (bank, number, card, int1, value, type, int2) VALUES (?, ?, ?, ?, ?, ?, ?) """ data = ['Citi', '5567', 'visa', 6000, 9.99, '23', 9000] cursor.execute(query, data) According to [PEP249](http://www.python.org/dev/peps/pep-0249/): > **_`.execute(operation[,parameters])`** :_ > > _Prepare and execute a database operation (query or command). Parameters may > be provided as sequence or mapping and will be bound to variables in the > operation. Variables are specified in a database-specific notation (see the > module's**`paramstyle`** attribute for details)_ Checking `paramstyle`: >>> import sqlite3 >>> print sqlite3.paramstyle qmark `qmark` means you use `?` for parameters.
How can I get a list of all classes within current module in Python? Question: I've seen plenty of examples of people extracting all of the classes from a module, usually something like: # foo.py class Foo: pass # test.py import inspect import foo for name, obj in inspect.getmembers(foo): if inspect.isclass(obj): print obj Awesome. But I can't find out how to get all of the classes from the _current_ module. # foo.py import inspect class Foo: pass def print_classes(): for name, obj in inspect.getmembers(???): # what do I do here? if inspect.isclass(obj): print obj # test.py import foo foo.print_classes() This is probably something really obvious, but I haven't been able to find anything. Can anyone help me out? Answer: Try this: import sys current_module = sys.modules[__name__] In your context: import sys, inspect def print_classes(): for name, obj in inspect.getmembers(sys.modules[__name__]): if inspect.isclass(obj): print(obj) And even better: clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass) Because `inspect.getmembers()` takes a predicate.
Overcoming Python's limitations regarding instance methods Question: It seems that Python has some limitations regarding instance methods. 1. Instance methods can't be copied. 2. Instance methods can't be pickled. This is problematic for me, because I work on a very object-oriented [project](http://garlicsim.org) in which I reference instance methods, and there's use of both deepcopying and pickling. The pickling thing is done mostly by the multiprocessing mechanism. What would be a good way to solve this? I did some ugly workaround to the copying issue, but I'm looking for a nicer solution to both problems. Does anyone have any suggestions? **Update:** My use case: I have a tiny event system. Each event has an `.action` attribute that points to a function it's supposed to trigger, and sometimes that function is an instance method of some object. Answer: You might be able to do this using [`copy_reg.pickle`](http://docs.python.org/library/copy%5Freg.html#copy%5Freg.pickle). In Python 2.6: import copy_reg import types def reduce_method(m): return (getattr, (m.__self__, m.__func__.__name__)) copy_reg.pickle(types.MethodType, reduce_method) This does not store the _code_ of the method, just its name; but that will work correctly in the common case. This makes both pickling and copying work!
How to identify whether a variable is a class or an object Question: I am working at a bit lower level writing a small framework for creating test fixtures for my project in Python. In this I want to find out whether a particular variable is an instance of a certain class or a class itself and if it is a class, I want to know if it is a subclass of a certain class defined by my framework. How do I do it? class MyBase(object): pass class A(MyBase): a1 = 'Val1' a2 = 'Val2' class B(MyBase): a1 = 'Val3' a2 = A I want to find out if the properties a1 and a2 are instances of a class/type (a1 is a string type in B) or a class object itself (i.e a2 is A in B). Can you please help me how do I find this out? Answer: Use the [inspect module](http://docs.python.org/library/inspect.html#module- inspect). > The inspect module provides several useful functions to help get information > about live objects such as modules, classes, methods, functions, tracebacks, > frame objects, and code objects. For example, it can help you examine the > contents of a class, retrieve the source code of a method, extract and > format the argument list for a function, or get all the information you need > to display a detailed traceback. For example, the [`inspect.isclass()`](http://docs.python.org/library/inspect.html#inspect.isclass) function returns true if the object is a class: >>> import inspect >>> inspect.isclass(inspect) False >>> inspect.isclass(inspect.ArgInfo) True >>>
Scrapy spider index error Question: This is the code for Spyder1 that I've been trying to write within Scrapy framework: from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from scrapy.item import Item from firm.items import FirmItem class Spider1(CrawlSpider): domain_name = 'wc2' start_urls = ['http://www.whitecase.com/Attorneys/List.aspx?LastName=A'] rules = ( Rule(SgmlLinkExtractor(allow=["hxs.select( '//td[@class='altRow'][1]/a/@href').re('/.a\w+')"]), callback='parse'), ) def parse(self, response): hxs = HtmlXPathSelector(response) JD = FirmItem() JD['school'] = hxs.select( '//td[@class="mainColumnTDa"]').re('(?<=(JD,\s))(.*?)(\d+)' ) return JD SPIDER = Spider1() The regex in the `rules` successfully pulls all the bio urls that I want from the start url: >>> hxs.select( ... '//td[@class="altRow"][1]/a/@href').re('/.a\w+') [u'/cabel', u'/jacevedo', u'/jacuna', u'/aadler', u'/zahmedani', u'/tairisto', u '/zalbert', u'/salberts', u'/aaleksandrova', u'/malhadeff', u'/nalivojvodic', u' /kallchurch', u'/jalleyne', u'/lalonzo', u'/malthoff', u'/valvarez', u'/camon', u'/randerson', u'/eandreeva', u'/pangeli', u'/jangland', u'/mantczak', u'/darany i', u'/carhold', u'/marora', u'/garrington', u'/jartzinger', u'/sasayama', u'/ma sschenfeldt', u'/dattanasio', u'/watterbury', u'/jaudrlicka', u'/caverch', u'/fa yanruoh', u'/razar'] >>> But when I run the code I get [wc2] ERROR: Error processing FirmItem(school=[]) - [Failure instance: Traceback: <type 'exceptions.IndexError'>: list index out of range This is the FirmItem in Items.py from scrapy.item import Item, Field class FirmItem(Item): school = Field() pass Can you help me understand where the index error occurs? It seems to me that it has something to do with [SgmLinkExtractor](http://doc.scrapy.org/topics/link- extractors.html#sgmllinkextractor). I've been trying to make this spider work for weeks with Scrapy. They have an excellent tutorial but I am new to python and web programming so I don't understand how for instance `SgmlLinkExtractor` works behind the scene. Would it be easier for me to try to write a spider with the same simple functionality with Python libraries? I would appreciate any comments and help. Thanks Answer: SgmlLinkExtractor doesn't support selectors in its "allow" argument. So this is wrong: SgmlLinkExtractor(allow=["hxs.select('//td[@class='altRow'] ...')"]) This is right: SgmlLinkExtractor(allow=[r"product\.php"])
Scrapy spider is not working Question: Since nothing so far is working I started a new project with python scrapy-ctl.py startproject Nu I followed the tutorial exactly, and created the folders, and a new spider from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from scrapy.item import Item from Nu.items import NuItem from urls import u class NuSpider(CrawlSpider): domain_name = "wcase" start_urls = ['http://www.whitecase.com/aabbas/'] names = hxs.select('//td[@class="altRow"][1]/a/@href').re('/.a\w+') u = names.pop() rules = (Rule(SgmlLinkExtractor(allow=(u, )), callback='parse_item'),) def parse(self, response): self.log('Hi, this is an item page! %s' % response.url) hxs = HtmlXPathSelector(response) item = Item() item['school'] = hxs.select('//td[@class="mainColumnTDa"]').re('(?<=(JD,\s))(.*?)(\d+)') return item SPIDER = NuSpider() and when I run C:\Python26\Scripts\Nu>python scrapy-ctl.py crawl wcase I get [Nu] ERROR: Could not find spider for domain: wcase The other spiders at least are recognized by Scrapy, this one is not. What am I doing wrong? Thanks for your help! Answer: Please also check the version of scrapy. The latest version uses "name" instead of "domain_name" attribute to uniquely identify a spider.
What's an easy way to implement a --quiet option in a python script Question: Am working on a command line python script - throughout the script, I have a lot of information I am `print`-ing to the terminal window so that I may follow along with what is happening. Using `OptionParser` I want to add a `--quiet` option so I can silence all the output. I am looking for a pythonic way to go about implementing this throughout the script so that I _don't_ end up doing something like: if not QUIET: # global variable set by OptionParser print " my output " Am new to python and sure there is a better way. Ideas? Answer: You could use [`logging`](http://docs.python.org/library/logging.html) and assign those things that should not be printed if `QUIET` a different log level. **Edit:** [THC4K's answer](http://stackoverflow.com/questions/1815760/whats- an-easy-way-to-implement-a-quiet-option-in-a-python-script/1815802#1815802) shows an example of how to do this, assuming that all output should be silent if `QUIET` is set. Note that in Python 3 `from __future__ import print_function` is not necessary: print = logging.info logging.basicConfig(level=logging.WARNING if QUIET else logging.INFO, format="%(message)s") For for important output that should not be silenced by `--quiet`, define e.g. `iprint`: iprint = logging.warning
Python OLE2 date format conversion Question: I have created a python script which pulls data out of OLE streams in Word documents, but am having trouble converting the OLE2-formatted timestamp to something more human-readable :( The timestamp which is pulled out is 12760233021 but I cannot for the life of me convert this to a date like 12 Mar 2007 or similar. Any help is greatly appreciated. EDIT: OK I have ran the script over one of my word documents, which was created on **31/10/2009, 10:05:00**. The Create Date in the OLE DocumentSummaryInformation stream is **12901417500**. Another example is a word doc created on 27/10/2009, 15:33:00, gives the Create Date of 12901091580 in the OLE DocumentSummaryInformation stream. The MSDN documentation on the properties of these OLE streams is <http://msdn.microsoft.com/en-us/library/aa380376%28VS.85%29.aspx> The def which pulls these streams out is given below: import OleFileIO_PL as ole def enumerateStreams(item): # item is an arbitrary file if ole.isOleFile('%s' % item): loader = ole.OleFileIO('%s' % item) # enumerate all the OLE streams in the office file streams = loader.listdir() streamProps = [] for stream in streams: if stream[0] == '\x05SummaryInformation': # get all the properties fro the SummaryInformation OLE stream streamProps.append(loader.getproperties(stream)) elif stream[0] == '\x05DocumentSummaryInformation': # get all the properties from the DocumentSummaryInformation stream streamProps.append(loader.getproperties(stream)) return streamProps Answer: (0) Please clarify "like 12 Mar 2007 or similar": do you mean that you expect the 11-digit int to convert to 12 Mar 2007, or is "12 Mar 2007" merely intended to convey the format in which you want to display the date? If the latter, can't you provide expected results by inspecting some files with MS Word or OpenOffice.org's word processing gadget? How do you intend to verify that any solution that is offered actually works? (1) Please give more than one (OLE, expected) pair so that correct operation of any proposed solution can be verified with more assurance. If possible, can you create examples with known expected values like 01 Jan 2000, 01 Jan 2001, 02 Jan 2001, 02 Feb 2001? (2) It is not obvious from "pulls data out of OLE streams" whether you want the file creation etc timestamps in the OLE2 compound document header, or whether you want timestamps that are present in the content. Please say WHERE you are trawling for timestamps. It would also help tremendously if you could give a reference to the MS documentation that relates to the timestamps you are interested in ... surely it must tell you what the format is, even if it does so indirectly by one or two intra/extra-document hops. (3) Please show HOW you are pulling that out -- is it a string? fixed 11 bytes? Or is it str(some int that you have converted from a 64-bit field)? Converted HOW?? As well as a description, show your conversion code. Don't retype your code from memory; use copy/paste. Please provide the requested info by editing your question, not as comments. Update while waiting for info: The file creation and modification timestamps in an OLE compound document header appear to be 64-bit little-endian integers representing (seconds since 1601-01-01T00:00:00) * 10 ** 7. The DATE type used in data in OLE2 data appears to be 64-bit little-endian IEEE 754 float representing (days and a fraction thereof) since 1899-12-30T00:00:00. Yes the day is 30, not 31. **Update after examining the 2 examples supplied:** The difference between the two observed timestamps (which will be in your local time) is 325920 seconds: >>> import datetime >>> t0 = datetime.datetime(2009,10,27,15,33,0) >>> t1 = datetime.datetime(2009,10,31,10,5,0) >>> t1-t0 datetime.timedelta(3, 66720) >>> secs = 3 * 24 * 60 * 60 + 66720 >>> secs 325920 This is the same as the difference between the two magic numbers: >>> 12901417500 - 1290191580 325920 So the magic numbers represent seconds since some epoch ... >>> m1 = 12901417500 >>> days, seconds = divmod(m1, 60*60*24) >>> epoch = t1 - datetime.timedelta(days, seconds) >>> epoch datetime.datetime(1601, 1, 1, 11, 0) So the magic numbers represent seconds since 1601-01-01T00:00:00Z and your TZ is 11 hours away from UTC. Those two magic numbers won't fit in 32 bits ... looks like either (a) it is stored in 64 bits as seconds since 1601 (a waste of about 29 bits!) or (b) it is stored as (number of 100-nanosecond units) since 1601 as expected but something is dividing it by 10**7 before you see it. The documentation reference that you gave merely says that it's a `VF_FILETIME (UTC)` type. Googling that, I find a couple of MS clues on calling Windows functions to manipulate the timestamps, but no definition as far as I looked. However there are two 3rd party notes (from perlmonks and the Apache POI project) which say much the same thing: """This looks like a Windows `VT_FILETIME` data type which is a 64 bit unsigned integer representing the number of elapsed 100 nanoseconds since 1 January 1601""" **Update from the crime scene:** Seems you are using `OleFileIO_PL` to read the files. A quick rummage through the sole source file reveals this: elif type == VT_FILETIME: value = long(i32(s, offset+4)) + (long(i32(s, offset+8))<<32) # FIXME: this is a 64-bit int: "number of 100ns periods # since Jan 1,1601". Should map this to Python time value = value / 10000000L # seconds
Redirecting a user in a django template Question: I have a django website that is spilt depending on what user type you are, I need to redirect users that are not entitled to see certain aspects of the site, in my template, I have {% if user.get_profile.is_store %} <!--DO SOME LOGIC--> {%endif%} how would I go about redirecting said store back to the index of the site? ====EDIT==== ef downloads(request): """ Downloads page, a user facing page for the trade members to downloads POS etc """ if not authenticated_user(request): return HttpResponseRedirect("/professional/") if request.user.get_profile().is_store(): return HttpResponseRedirect("/") user = request.user account = user.get_profile() downloads_list = TradeDownloads.objects.filter(online=1)[:6] downloads_list[0].get_thumbnail() data = {} data['download_list'] = downloads_list return render_to_response('downloads.html', data, RequestContext(request)) I implement the answer from thornomad, and now I get his error Environment: Request Method: GET Request URL: http://localhost:8000/professional/downloads Django Version: 1.1.1 Python Version: 2.6.2 Installed Applications: ['django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'sico.news', 'sico.store_locator', 'sico.css_switch', 'sico.professional', 'sico.contact', 'sico.shop', 'tinymce', 'captcha'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware') Traceback: File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response 92. response = callback(request, *callback_args, **callback_kwargs) File "/var/www/sico/src/sico/../sico/professional/views.py" in downloads 78. if request.user.get_profile().is_store(): File "/var/www/sico/src/sico/../sico/shop/models.py" in is_store 988. return not self.account is None File "/usr/local/lib/python2.6/dist-packages/django/db/models/fields/related.py" in __get__ 191. rel_obj = self.related.model._base_manager.get(**params) File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py" in get 120. return self.get_query_set().get(*args, **kwargs) File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py" in get 305. % self.model._meta.object_name) Exception Type: DoesNotExist at /professional/downloads Exception Value: Account matching query does not exist. Answer: You will want to do this, I think, in a _view_ not in the _template_. So, something like: from django.http import HttpResponseRedirect def myview(request): if request.user.get_profile().is_store(): return HttpResponseRedirect("/path/") # return regular view otherwise You could also use a `@decorator` for the view if you found yourself needing to do this a lot.
Using C++ in xcode for image and video processing Question: I am studying in the area of image and video processing - specifically in the field of pattern recognition (objects, people etc.). I wish to use a programming language to apply the transformation to images and video (more importantly video). I am thinking of using C++ in Xcode to do this. The algorithms I wanna build I want to take data from the web (e.g. submitted videos) - process them and then give an output. My question has several parts: (1) Is C++ the best language to do this in? Can this be done in Python? (I'm guessing C++ is faster than Python and can probably handle larger files/more intense algos) (2) What is the best way for setting up a project for this in xcode - is it a straight (A) Command-line tools "vanilla" project or should I go for (B) a Cocoa application in objective C? (I will need to learn Obj-C) My short term objective is to write some simple alorithms and see how they work on video. Then to hook this up (at the back end) to a front end web GUI (so I can submit videos to my code). Volumes wont be huge - but file sizes may be substantial. Any insight will be hugely appreciated. Max. Answer: My advice is to get a prototype working in python, and then use boost's python integration to rewrite the performance intensive parts in C++ once you have your algorithm working.
Solving a cubic equation Question: As part of a program I'm writing, I need to solve a cubic equation exactly (rather than using a numerical root finder): a*x**3 + b*x**2 + c*x + d = 0. I'm trying to use the equations from [here](http://en.wikipedia.org/wiki/Cubic_function#Root-finding_formula). However, consider the following code (this is Python but it's pretty generic code): a = 1.0 b = 0.0 c = 0.2 - 1.0 d = -0.7 * 0.2 q = (3*a*c - b**2) / (9 * a**2) r = (9*a*b*c - 27*a**2*d - 2*b**3) / (54*a**3) print "q = ",q print "r = ",r delta = q**3 + r**2 print "delta = ",delta # here delta is less than zero so we use the second set of equations from the article: rho = (-q**3)**0.5 # For x1 the imaginary part is unimportant since it cancels out s_real = rho**(1./3.) t_real = rho**(1./3.) print "s [real] = ",s_real print "t [real] = ",t_real x1 = s_real + t_real - b / (3. * a) print "x1 = ", x1 print "should be zero: ",a*x1**3+b*x1**2+c*x1+d But the output is: q = -0.266666666667 r = 0.07 delta = -0.014062962963 s [real] = 0.516397779494 t [real] = 0.516397779494 x1 = 1.03279555899 should be zero: 0.135412149064 so the output is not zero, and so x1 isn't actually a solution. Is there a mistake in the Wikipedia article? ps: I know that numpy.roots will solve this kind of equation but I need to do this for millions of equations and so I need to implement this to work on arrays of coefficients. Answer: Wikipedia's notation `(rho^(1/3), theta/3)` does not mean that `rho^(1/3)` is the real part and `theta/3` is the imaginary part. Rather, this is in polar coordinates. Thus, if you want the real part, you would take `rho^(1/3) * cos(theta/3)`. I made these changes to your code and it worked for me: theta = arccos(r/rho) s_real = rho**(1./3.) * cos( theta/3) t_real = rho**(1./3.) * cos(-theta/3) (Of course, `s_real = t_real` here because `cos` is even.)
pythonic way to aggregate arrays (numpy or not) Question: I would like to make a nice function to aggregate data among an array (it's a numpy record array, but it does not change anything) you have an array of data that you want to aggregate among one axis: for example an array of `dtype=[(name, (np.str_,8), (job, (np.str_,8), (income, np.uint32)]` and you want to have the mean income per job I did this function, and in the example it should be called as `aggregate(data,'job','income',mean)` * * * def aggregate(data, key, value, func): data_per_key = {} for k,v in zip(data[key], data[value]): if k not in data_per_key.keys(): data_per_key[k]=[] data_per_key[k].append(v) return [(k,func(data_per_key[k])) for k in data_per_key.keys()] * * * the problem is that I find it not very nice I would like to have it in one line: do you have any ideas? Thanks for your answer Louis PS: I would like to keep the func in the call so that you can also ask for median, minimum... Answer: Your `if k not in data_per_key.keys()` could be rewritten as `if k not in data_per_key`, but you can do even better with [`defaultdict`](http://docs.python.org/library/collections.html#defaultdict- objects). Here's a version that uses `defaultdict` to get rid of the existence check: import collections def aggregate(data, key, value, func): data_per_key = collections.defaultdict(list) for k,v in zip(data[key], data[value]): data_per_key[k].append(v) return [(k,func(data_per_key[k])) for k in data_per_key.keys()]
Ranking Elements of multiple Lists by their count in Python Question: I want to rank multiple lists according to their elements how often they appear in each list. Example: list1 = 1,2,3,4 list2 = 4,5,6,7 list3 = 4,1,8,9 result = 4,1,2,3,4,5,6,7,8 (4 is counted three times, 1 two times and the rest once) I've tried the following but i need something more intelligent and something i can do with any ammount of lists. l = [] l.append([ 1, 2, 3, 4, 5]) l.append([ 1, 9, 3, 4, 5]) l.append([ 1, 10, 8, 4, 5]) l.append([ 1, 12, 13, 7, 5]) l.append([ 1, 14, 13, 13, 6]) x1 = set(l[0]) & set(l[1]) & set(l[2]) & set(l[3]) x2 = set(l[0]) & set(l[1]) & set(l[2]) & set(l[4]) x3 = set(l[0]) & set(l[1]) & set(l[3]) & set(l[4]) x4 = set(l[0]) & set(l[2]) & set(l[3]) & set(l[4]) x5 = set(l[1]) & set(l[2]) & set(l[3]) & set(l[4]) set1 = set(x1) | set(x2) | set(x3) | set(x4) | set(x5) a1 = list(set(l[0]) & set(l[1]) & set(l[2]) & set(l[3]) & set(l[4])) a2 = getDifference(list(set1),a1) print a1 print a2 Now here is the problem... i can do it again and again with a3,a4 and a5 but its too complex then, i need a function for this... But i don't know how... my math got stuck ;) SOLVED: thanks alot for the discussion. As a newbee i like this system somehow: fast+informative. You helped me all out! Ty Answer: import collections data = [ [1, 2, 3, 4, 5], [1, 9, 3, 4, 5], [1, 10, 8, 4, 5], [1, 12, 13, 7, 5], [1, 14, 13, 13, 6], ] def sorted_by_count(lists): counts = collections.defaultdict(int) for L in lists: for n in L: counts[n] += 1 return [num for num, count in sorted(counts.items(), key=lambda k_v: (k_v[1], k_v[0]), reverse=True)] print sorted_by_count(data) Now let's generalize it (to take any iterable, loosen hashable requirement), allow key and reverse parameters (to match sorted), and rename to [freq_sorted](http://bitbucket.org/kniht/scraps/src/6f5692c4f9d2/python/iter_util.py#cl-9): def freq_sorted(iterable, key=None, reverse=False, include_freq=False): """Return a list of items from iterable sorted by frequency. If include_freq, (item, freq) is returned instead of item. key(item) must be hashable, but items need not be. *Higher* frequencies are returned first. Within the same frequency group, items are ordered according to key(item). """ if key is None: key = lambda x: x key_counts = collections.defaultdict(int) items = {} for n in iterable: k = key(n) key_counts[k] += 1 items.setdefault(k, n) if include_freq: def get_item(k, c): return items[k], c else: def get_item(k, c): return items[k] return [get_item(k, c) for k, c in sorted(key_counts.items(), key=lambda kc: (-kc[1], kc[0]), reverse=reverse)] Example: >>> import itertools >>> print freq_sorted(itertools.chain.from_iterable(data)) [1, 5, 4, 13, 3, 2, 6, 7, 8, 9, 10, 12, 14] >>> print freq_sorted(itertools.chain.from_iterable(data), include_freq=True) # (slightly reformatted) [(1, 5), (5, 4), (4, 3), (13, 3), (3, 2), (2, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (12, 1), (14, 1)]
media.set_xx ValueError Question: New guy here. I asked a while back about a sprite recolouring program that I was having difficulty with and got some great responses. Basically, I tried to write a program that would recolour pixels of all the pictures in a given folder from one given colour to another. I believe I have it down, but, now the program is telling me that I have an invalid value specified for the red component of my colour. (ValueError: Invalid red value specified.), even though it's only being changed from 64 to 56. Any help on the matter would be appreciated! (Here's the code, in case I messed up somewhere else; It's in Python): import os import media import sys def recolour(old, new, folder): old_list = old.split(' ') new_list = new.split(' ') folder_location = os.path.join('C:\\', 'Users', 'Owner', 'Spriting', folder) for filename in os.listdir (folder): current_file = media.load_picture(folder_location + '\\' + filename) for pix in current_file: if (media.get_red(pix) == int(old_list[0])) and \ (media.get_green(pix) == int(old_list[1])) and \ (media.get_blue(pix) == int(old_list[2])): media.set_red(pix, new_list[0]) media.set_green(pix, new_list[1]) media.set_blue(pix, new_list[2]) media.save(pic) if **name** == '**main** ': while 1: old = str(raw_input('Please insert the original RGB component, separated by a single space: ')) if old == 'quit': sys.exit(0) new = str(raw_input('Please insert the new RGB component, separated by a single space: ')) if new == 'quit': sys.exit(0) folder = str(raw_input('Please insert the name of the folder you wish to modify: ')) if folder == 'quit': sys.exit(0) else: recolour(old, new, folder) Answer: Slow going; but no worries I got it. Didn't convert the values to integers, was trying to use strings as arguments...
Python time comparison Question: How do I compare times in python? I see that date comparisons can be done and there's also "timedelta", but I'm struggling to find out how to check if the current time (from datetime.now()) is earlier, the same, or later than a specified time (e.g. 8am) regardless of the date. Answer: You _can't_ compare a specific point in time (such as "right now") against an unfixed, recurring event (8am happens every day). You can check if now is before or after _today's_ 8am: >>> import datetime >>> now = datetime.datetime.now() >>> today8am = now.replace(hour=8, minute=0, second=0, microsecond=0) >>> now < today8am True >>> now == today8am False >>> now > today8am False
Looking for advice on how to develop applets for Gnome / Ubuntu Question: I am a linux (mostly ubuntu) user with a reasonable understanding of how the system works (although I am certainly **not** a linux guru!). In the past I have developed small cross-platform desktop applications in python/GTK and I delivered them to clients as self-contained filetrees, so that the only dependencies were Python itself and GTK. Now **I would like to develop a small applet for ubuntu** , that I would like to release under GPL 2 or 3. In particular these are the new steps _I know I must learn_ in order to achieve my goal (it is _very possible_ there are a few more that I am unaware of, though!): * **Integrating with gnome:** I want my application to be available as an applet in the taskbar. * **Using D-bus:** In particular I want my applet to use the new osd-notification framework for ubuntu, but communication with other applets is also a possible feature for a second iteration. * **Packaging:** I would like to setup a public PPA as soon as the application will reach alpha stage, but I also would like to use dependencies from existing packages in the official repos, rather than include the libraries again in my own package. Of course official documentation will be my first source of knowledge, but - basing my judgment on the very useful answers that I received on [another topic](http://stackoverflow.com/questions/1812926/i-am-looking-for-tips-for- learning-vim-or-emacs-the-smart-way) here on SO - I decided to turn to the SO community to collect additional advice like for example: 1. Are there additional steps to those I outlined before, that I have to learn in order to be able to implement my project? 2. Based on your own experience, would you advise me to learn those steps in advance (as the knowledge of those will influence my way of coding the core functionality) or would you consider integration with gnome / d-bus and packaging as "higher encapsulating levels" that can be added on top of core functionality afterwards (note: D-bus will be used at first just for pushing data. Input data will be retrieved with a webservice)? 3. Would you advise me to separate my application in two packages (back-end and front-end) or to keep it together in a single package?, 4. Do you know of any useful resource that you would advise me to look at, for learning any of the things that I have to? 5. Are you aware of any common "beginner's mistakes" that I should be aware of? **These questions are not meant to be exhaustive, though: if you feel that I am missing something from the general picture, you are more than welcomed to point me in the right direction!** Thank you in advance for your time! PS: Should I have failed in explaining my final goal, take a look at [project hamster](http://projecthamster.wordpress.com/): what I want to achieve is similar in terms of user interface (meaning: the applet should display the status and clicking on it should open the application itself, from which you could both configure the applet and perform various operations). Answer: Well, you list python, so you'll want to have `pynotify` in your arsenal. It wraps DBus, and gives you a direct api for manipulating the osd-notification system. >>> import pynotify >>> pynotify.init("Lil' Applet") True >>> note = pynotify.Notification( ... pynotify.get_app_name(), ... "Lil' Applet wants you to know something's up.", ... "/usr/share/icons/Human/48x48/status/dialog-information.png") >>> note.show() True This displays a notification that looks like this: [ ] **Lil' Applet** [ICON] [ ] Lil' Applet wants you to know something's up.
pygst - glimagesink callback Question: I'm trying to use 'glimagesink' element with python. The element (which is GObject inside) has `client-draw-callback` property which should (in C++ at least) contain a function (`bool func(uint t, uint w, uint h)`) pointer. I've tried `element.set_property('client-draw-callback', myfunc)`, and creating function pointer with ctypes, but every time it says, `TypeError: could not convert argument to correct param type` I could find any docs on using glimagesink or glfilterapp in python ): The working c++ code: gboolean drawCallback (GLuint texture, GLuint width, GLuint height) { ... } GstElement* glimagesink = gst_element_factory_make ("glimagesink", "glimagesink0"); g_object_set(G_OBJECT(glimagesink), "client-draw-callback", drawCallback, NULL) Answer: This isn't the problem you're having (as far as I can tell) but it's important to note that this API has changed recently, now it expects a void pointer of data which allows you to pass in a handle to user_data (or NULL) when you connect your callback. gboolean drawCallback (GLuint texture, GLuint width, GLuint height, gpointer data)
python X.509 asymmetric encryption Question: Hello I'm trying to understand how certificate and asymmetric encryption works. I'm looking for a python library where i can import public or private ca signed certificates and automatically encrypt or decrypt message in string format, i viewed the crypto library embedded in python source, but i don't know how to use the hex modulus and exponent in this part of the certificate: RSA Public Key: (1024 bit) Modulus (1024 bit): 00:b4:31:98:0a:c4:bc:62:c1:88:aa:dc:b0:c8:bb: 33:35:19:d5:0c:64:b9:3d:41:b2:96:fc:f3:31:e1: 66:36:d0:8e:56:12:44:ba:75:eb:e8:1c:9c:5b:66: 70:33:52:14:c9:ec:4f:91:51:70:39:de:53:85:17: 16:94:6e:ee:f4:d5:6f:d5:ca:b3:47:5e:1b:0c:7b: c5:cc:2b:6b:c1:90:c3:16:31:0d:bf:7a:c7:47:77: 8f:a0:21:c7:4c:d0:16:65:00:c1:0f:d7:b8:80:e3: d2:75:6b:c1:ea:9e:5c:5c:ea:7d:c1:a1:10:bc:b8: e8:35:1c:9e:27:52:7e:41:8f Exponent: 65537 (0x10001) is there anyone can help me? thanks Answer: [MeTooCrypto](http://chandlerproject.org/Projects/MeTooCrypto): > M2Crypto is the most complete Python wrapper for OpenSSL featuring RSA, DSA, > DH, HMACs, message digests, symmetric ciphers (including AES); SSL > functionality to implement clients and servers; HTTPS extensions to Python's > httplib, urllib, and xmlrpclib; unforgeable HMAC'ing AuthCookies for web > session management; FTP/TLS client and server; S/MIME; ZServerSSL: A HTTPS > server for Zope and ZSmime: An S/MIME messenger for Zope. M2Crypto can also > be used to provide SSL for Twisted. For an example of loading and manipulating `PKI` keys, see the test source, [`test_rsa.py`](http://svn.osafoundation.org/m2crypto/trunk/tests/test%5Frsa.py). The test source directory contains keys in `.pem` format, and those are used by the code.
sparse assignment list in python Question: I need a list with the following behavior >>> l = SparseList() >>> l [] >>> l[2] = "hello" >>> l [ None, None, "hello"] >>> l[5] None >>> l[4] = 22 >>> l [ None, None, "hello", None, 22] >>> len(l) 5 >>> for i in l: print i None None "hello" None 22 Although it can "emulated" via a dictionary, it's not exactly the same. numpy array can behave this way, but I don't want to import the whole numpy for something like this. Before coding it myself, I ask if something similar exists in the standard library. Answer: Here's minimal code to pass your given examples (with indispensable adjustments: you expect weird spacing and quoting, 'None' to be printed out at the prompt without a `print` statement, etc etc): class SparseList(list): def __setitem__(self, index, value): missing = index - len(self) + 1 if missing > 0: self.extend([None] * missing) list.__setitem__(self, index, value) def __getitem__(self, index): try: return list.__getitem__(self, index) except IndexError: return None __test__ = dict(allem=''' >>> l = SparseList() >>> l [] >>> l[2] = "hello" >>> l [None, None, 'hello'] >>> print l[5] None >>> l[4] = 22 >>> l [None, None, 'hello', None, 22] >>> len(l) 5 >>> for i in l: print i None None hello None 22 ''') import doctest doctest.testmod(verbose=1) I imagine you'll want more (to support negative indices, slicing, and whatever else), but this is all your examples are implicitly specifying.
psycopg2 vs sys.stdin.read() Question: Dear all I have small code like below : #!/usr/bin/python import psycopg2, sys try: conn = psycopg2.connect("dbname='smdr' user='bino'"); except: print "I am unable to connect to the database" cur = conn.cursor() v_num = '1' cur.execute("SELECT * from genctr WHERE code = %(num)s", dict(num=v_num)) rows = cur.fetchall() print "\nShow me the databases:\n" ctrnum =0 for row in rows: print row[0]+","+row[1] when i run it, i got bino@erp:~/mydoc/openerp/smdr$ ./genctr.py Show me the databases: 1,Bahamas 1,Barbados 1,Canada 1,Cayman Islands 1,United States 1,Virgin Islands U.S. I try to replace "v_num = '1' " with "v_num = sys.stdin.read()" #!/usr/bin/python import psycopg2, sys try: conn = psycopg2.connect("dbname='smdr' user='bino'"); except: print "I am unable to connect to the database" cur = conn.cursor() #v_num = '1' v_num = sys.stdin.read() cur.execute("SELECT * from genctr WHERE code = %(num)s", dict(num=v_num)) rows = cur.fetchall() print "\nShow me the databases:\n" ctrnum =0 for row in rows: print row[0]+","+row[1] But when I run it , I only got this : bino@erp:~/mydoc/openerp/smdr$ echo 1 |./genctr.py Show me the databases: Kindly please give me your enlightment on how to fix it Sincerely -bino- Answer: `echo 1` is going to give "1\n" to your program (that is, "1" with a newline character afterward). `sys.stdin.read()` is going to return that exact string, and then psycopg2 is going to prepare the SQL statement as `SELECT * from genctr WHERE code = '1\n'`. The result is going to be no matching results, so the code inside the for loop will never execute, which is why you don't see any extra output. Try doing either `echo -n 1` to suppress the newline, or `sys.stdin.read().strip()` to remove any leading and trailing whitespace from the string. If the `code` field is an integer, it might be a good idea to cast the result of `sys.stdin.read()` to an int, too, like so: int(sys.stdin.read().strip())
Django to use different settings.py file based on subdomains Question: How can Django use different settings.py file based on subdomains. Can these utilities ("django-admin", "python manage.py") still be used if there were different settings connecting to different databases. Answer: ok you have two dimensions you need to cover with your settings: 1. Domain (site) 2. Current Machine Here is what I recommend: `universal_settings.py` \- all the settings you want to inherit everywhere (all machines, all domains) `local_settings.py` \- settings on a per machine basis (database settings, mail server, etc) `site_1.py` \- settings that are specific to a one of your domains `site_2.py` \- settings that are specific to a one of your domains `site_n.py` \- you get the idea the bottom of universal_settings.py should include: from local_settings import * This will override anything in the universal settings as necessary. similarly, each of the `site_1.py`, `site_2.py`, `site_n.py` settings files should begin with: from universal_settings import * Finally you need to set up an apache (or nginx, or whatever) instance for each domain and use the appropriate `site_n.py` as the settings file for that server This is the method that works best for me :)
Insights on SystemError: com_backpatch: offset too large Question: In python, `"SystemError: com_backpatch: offset too large"` is thrown when executing the code generated by the following: f = open("test.py", "w") f.write("def fn():\n a =1000\n") for a in xrange(3000): if a == 0: f.write(" if a == "+str(a)+": \n print "+str(a)+"\n") else: f.write(" elif a == "+str(a)+": \n print "+str(a)+"\n") f.close() import test It is clear that if the length statement goes beyond a certain length, it throws this error. Can someone give more insight into this error? Answer: Accourding to this: <http://www.cgl.ucsf.edu/pipermail/chimera- dev/2007/000404.html> > The Python bytecode compiler has a limitation of a maximum of a 16 bit > offset in a jump instruction. This means that you don't want to have 64K > worth of characters in a single conditional block of code More details here: <http://www.mail-archive.com/python- list@python.org/msg72631.html>
Having trouble installing PIL in Snow Leopard Question: I followed these instructions: <http://proteus-tech.com/blog/cwt/install-pil-in-snow-leopard/> And everything went as described. However, at the end, I tried running: python selftest.py to verify that everything is working properly, but I get: *** The _imaging C module is not installed I then run the python interpreter and tried: import _imaging and get this error: > Traceback (most recent call last): File "", line 1, in ImportError: > dlopen(/Library/Python/2.6/site-packages/PIL/_imaging.so, 2): Symbol not > found: _jpeg_resync_to_restart Referenced from: /Library/Python/2.6/site- > packages/PIL/_imaging.so Expected in: flat namespace in > /Library/Python/2.6/site-packages/PIL/_imaging.so This is on my first Mac, so apologize if I'm missing anything obvious, but any help you could provide would be greatly appreciated. Thanks! Answer: The problem happens because jpeglib is not available as part of standard MAC OS X distribution for Leopard and Snow Leopard. The solution is as follows: \- compile lib jpeg \- make sure tha libjpeg62.dylib is available on your DYLD_LIBRARY_PATH (you might like to put it in places like /usr/local/lib) Useful instructions are available [here](http://jetfar.com/libjpeg-and-python- imaging-pil-on-snow-leopard/)
Use Python to extract ListView items from another application Question: I have an application with a ListView ('SysListView32') control, from which I would like to extract data. The control has 4 columns, only textual data. I have been playing around the following lines (found online somewhere): VALUE_LENGTH = 256 bufferlength_int=struct.pack('i', VALUE_LENGTH) count = win32gui.SendMessage(TargetHwnd, commctrl.LVM_GETITEMCOUNT, 0, 0) for ItemIndex in range(count): valuebuffer = array.array('c',bufferlength_int + " " * (VALUE_LENGTH - len(bufferlength_int))) ListItems = win32gui.SendMessage(TargetHwnd, commctrl.LVM_GETITEMTEXT, ItemIndex, valuebuffer) [The above code may not be entirely executable, as I stripped it from irrelevant stuff. but the gist is certainly here.] This seems to run ok but I must be doing something wrong - I get all sorts of mostly-zeroed data buffers in return, and none of the actual text contents I was looking for. Any suggestions? Thanks, Yonatan Answer: Well, it turns out I was wrong on several points there. However it is possible to do by allocating memory inside the target process, constructing the required struct (LVITEM) there, sending the message and reading back the result from the buffer allocated in said process. For the sake of completeness, I attach a code example for reading SysListView32 items from a foreign process, given a window handle of the control. from win32con import PAGE_READWRITE, MEM_COMMIT, MEM_RESERVE, MEM_RELEASE,\ PROCESS_ALL_ACCESS from commctrl import LVM_GETITEMTEXT, LVM_GETITEMCOUNT import struct import ctypes import win32api import win32gui GetWindowThreadProcessId = ctypes.windll.user32.GetWindowThreadProcessId VirtualAllocEx = ctypes.windll.kernel32.VirtualAllocEx VirtualFreeEx = ctypes.windll.kernel32.VirtualFreeEx OpenProcess = ctypes.windll.kernel32.OpenProcess WriteProcessMemory = ctypes.windll.kernel32.WriteProcessMemory ReadProcessMemory = ctypes.windll.kernel32.ReadProcessMemory memcpy = ctypes.cdll.msvcrt.memcpy def readListViewItems(hwnd, column_index=0): # Allocate virtual memory inside target process pid = ctypes.create_string_buffer(4) p_pid = ctypes.addressof(pid) GetWindowThreadProcessId(hwnd, p_pid) # process owning the given hwnd hProcHnd = OpenProcess(PROCESS_ALL_ACCESS, False, struct.unpack("i",pid)[0]) pLVI = VirtualAllocEx(hProcHnd, 0, 4096, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE) pBuffer = VirtualAllocEx(hProcHnd, 0, 4096, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE) # Prepare an LVITEM record and write it to target process memory lvitem_str = struct.pack('iiiiiiiii', *[0,0,column_index,0,0,pBuffer,4096,0,0]) lvitem_buffer = ctypes.create_string_buffer(lvitem_str) copied = ctypes.create_string_buffer(4) p_copied = ctypes.addressof(copied) WriteProcessMemory(hProcHnd, pLVI, ctypes.addressof(lvitem_buffer), ctypes.sizeof(lvitem_buffer), p_copied) # iterate items in the SysListView32 control num_items = win32gui.SendMessage(hwnd, LVM_GETITEMCOUNT) item_texts = [] for item_index in range(num_items): win32gui.SendMessage(hwnd, LVM_GETITEMTEXT, item_index, pLVI) target_buff = ctypes.create_string_buffer(4096) ReadProcessMemory(hProcHnd, pBuffer, ctypes.addressof(target_buff), 4096, p_copied) item_texts.append(target_buff.value) VirtualFreeEx(hProcHnd, pBuffer, 0, MEM_RELEASE) VirtualFreeEx(hProcHnd, pLVI, 0, MEM_RELEASE) win32api.CloseHandle(hProcHnd) return item_texts
Is it possible to make a custom mouse cursor with Python Tkinter? (Using matplotlib with the TkAgg backend) Question: It's likely that this is just a general Python Tkinter question, not necessarily a matplotlib one. So I'm in the midst of developing a rather large suite of plotting functionality on top of matplotlib using the Matplotlib "TkAgg" backend (Agg rendering to a Tk canvas using TkInter). I'm using some of the default zooming functionality provided by matplotlib out of the box...specifically the "Zoom to box" button on the default matplotlib toolbar. I am creating my own toolbar by subclassing the existing "matplotlib.backends.backend_tkagg.NavigationToolbar2TkAgg" class. Pretty much, the issue here is that I hate the default icon that "Zoom to box" uses (the Tkinter "tcross"). I've figured out how to use a different Tkinter built-in cursor (e.g. this changes the cursor to "plus" instead of "tcross"): import matplotlib matplotlib.use('TkAgg') import matplotlib.backend_bases import matplotlib.backends.backend_tk_agg matplotlib.backends.backend_tkagg.cursord[matplotlib.backend_bases.cursors.SELECT_REGION] = "plus" And in general, I know that to change the current mouse cursor to one of the built-in Tkinter ones from the toolbar class, I can just call: self.window.configure(cursor="cursor_name") So what I would really, really like is to be able to use a magnifying glass icon for when the user is in "zoom mode". I already have a .ppm of the magnifying glass icon I'd like to use and everything, but I can't figure out for the life of me how to use my magnifying glass as the mouse cursor icon. Is it possible to use a custom image as a mouse cursor in Python Tkinter? Help! **Platform note** : This needs to be workable on Mac OS X 10.5+, RedHat Enterprise Linux 5, and possibly Solaris 10, so a platform-specific solution is undesirable. Answer: Something like this works with unix X11 XBM files: import Tkinter t = Tkinter.Tk() t.configure(cursor=('@/usr/include/X11/bitmaps/star', '/usr/include/X11/bitmaps/starMask', 'black', 'white')) t.mainloop() As for the Macs, from the man page for "Tk_GetCursorFromData": > The Macintosh version of Tk supports all of the X cursors and will also > accept any of the standard Mac cursors including ibeam, crosshair, watch, > plus, and arrow. In addition, Tk will load Macintosh cursor resources of the > types crsr (color) and CURS (black and white) by the name of the of the > resource. > The application and all its open dynamic library's resource files will be > searched for the named cursor. If there are conflicts color cursors will > always be loaded in preference to black and white cursors.
Request for comments: python class factory for group of constant values Question: The following python module is meant to be a basis for "constant" handling in python. The use case is the following: * one groups some constants (basically "names") that belong together with their values into a dictionary * with that dictionary bound to class variable a class is created and instantinated run-time * the attributes of this class are the constant names, their values are the constants themselves Code: class ConstantError(Exception): def __init__(self, msg): self._msg = msg class Constant(object): def __init__(self, name): self._name = name def __get__(self, instance, owner): return owner._content[self._name] def __set__(self, instance, value): raise ConstantError, 'Illegal use of constant' def make_const(name, content): class temp(object): _content = content def __init__(self): for k in temp._content: setattr(temp, k, Constant(k)) temp.__name__ = name + 'Constant' return temp() num_const = make_const('numeric', { 'one': 1, 'two': 2 }) str_const = make_const('string', { 'one': '1', 'two': '2' }) Use: >>> from const import * >>> num_const <const.numericConstant object at 0x7f03ca51d5d0> >>> str_const <const.stringConstant object at 0x7f03ca51d710> >>> num_const.one 1 >>> str_const.two '2' >>> str_const.one = 'foo' Traceback (most recent call last): File "<stdin>", line 1, in <module> File "const.py", line 16, in __set__ raise ConstantError, 'Illegal use of constant' const.ConstantError >>> Please, comment the design, implementation and correspondence to python coding guidelines. Answer: In the same spirit as Kugel, but noticing that [`collections.namedtuple`](http://docs.python.org/dev/library/collections.html#collections.namedtuple) is very similar.. it is a tuple, thus immutable, and it has field names. Namedtuple was introduced in Python 2.6. Here is how you might use namedtuple: import collections def make_constants(variables): n = collections.namedtuple('Constants', variables.keys()) return n(**variables) c = make_constants({"a": 2, "b": 76}) print c # the output is: # Constants(a=2, b=76)
Find the nth occurrence of substring in a string Question: This seems like it should be pretty trivial, but I am new at Python and want to do it the most Pythonic way. I want to find the n'th occurrence of a substring in a string. There's got to be something equivalent to what I WANT to do which is `mystring.find("substring", 2nd)` How can you achieve this in Python? Answer: Here's a more Pythonic version of the straightforward iterative solution: def find_nth(haystack, needle, n): start = haystack.find(needle) while start >= 0 and n > 1: start = haystack.find(needle, start+len(needle)) n -= 1 return start _Example:_ >>> find_nth("foofoofoofoo", "foofoo", 2) 6 If you want to find the nth _overlapping_ occurrence of `needle`, you can increment by `1` instead of `len(needle)`, like this: def find_nth_overlapping(haystack, needle, n): start = haystack.find(needle) while start >= 0 and n > 1: start = haystack.find(needle, start+1) n -= 1 return start _Example:_ >>> find_nth_overlapping("foofoofoofoo", "foofoo", 2) 3 This is easier to read than Mark's version, and it doesn't require the extra memory of the splitting version or importing regular expression module. It also adheres to a few of the rules in the [Zen of python](http://www.python.org/dev/peps/pep-0020/), unlike the various `re` approaches: 1. Simple is better than complex. 2. Flat is better than nested. 3. Readability counts.
Refactor large models.py file in Django app Question: After reading monokrome's answer to [Where should Django manager code live?](http://stackoverflow.com/questions/1883322/where-should-django-manager- code-live), I've decided to split a large `models.py` into smaller, more manageable files. I'm using the folder structure foodapp/ models/ __init__.py #contains pizza model morefood.py #contains hamburger & hotdog models In `__init__.py`, I import the models from `morefood.py` with from morefood import hamburger, hotdog However, when I run `python manage.py syncdb`, the only table created is `foodapp_pizza` \- What do I need to do to get Django to create tables for the models I have imported from `morefood.py`? Answer: Try this: foodapp/ __init__.py models.py /morefood __init__.py hamburger.py hotdog.py and do this in models.py: from foodapp.morefood.hamburger import * from foodapp.morefood.hotdog import * as suggested in [this blogpost](https://justin.abrah.ms/this-and- that/fitures_model_subdir.html).
How can I auto-populate a PDF form in Django/Python? Question: I have PDF forms that I want to autopopulate with data from my Django web application and then offer to the user to download. What python library would let me easily pre-populate PDF forms? These forms are intended to be printed out. Answer: Reportlab is great if you're generating very dynamic PDFs and need to programmatically control all of it: data and layout. To just fill out forms in existing PDFs, reportlab is overkill and you'll basically have to rebuild the PDF from scratch in reportlab instead of just taking a PDF with a form that's already been made. PDF forms work with [FDF](http://www.citationsoftware.com/faqFDF.htm) data. I ported a PHP FDF library to Python a while back when I had to do this and released it as [fdfgen](http://pypi.python.org/pypi/fdfgen/). I use that to generate an fdf file with the data for the form, then use [pdftk](http://www.accesspdf.com/pdftk/) to push the fdf into a PDF form and generate the output. The whole process works like this: 1. You (or a designer) design the PDF in Acrobat or whatever and mark the form fields and take note of the field names (I'm not sure exactly how this is done; our designer does this step). Let's say your form has fields "name" and "telephone". 2. Use fdfgen to create a FDF file: from fdfgen import forge_fdf fields = [('name','John Smith'),('telephone','555-1234')] fdf = forge_fdf("",fields,[],[],[]) fdf_file = open("data.fdf","w") fdf_file.write(fdf) fdf_file.close() 3. Then you run pdftk to merge and flatten: pdftk form.pdf fill_form data.fdf output output.pdf flatten and a filled out, flattened (meaning that there are no longer editable form fields) pdf will be in output.pdf. It's a bit complicated, and pdftk can be a pain to install (requires a java stack and there are bugs on Ubuntu 9.10 that have to be worked around) but it's the simplest process I've been able to come up with yet and the workflow is convenient (ie, our designers can make all the layout changes to the PDF they want and as long as they don't change the names of the fields, I can drop the new one in and everything keeps working). I apologize for the lack of docs on fdfgen. forge_fdf() is really the only function you should need and it has a docstrings to explain the arguments. I've just never quite gotten around to doing more with it.
wxPython - picking the right sizer to use in an application Question: I'm having trouble figuring out how to get the sizers in wxPython to work the way I want them to (aside: am I the only one who thinks that wxPython is poorly documented?). I've got 4 buttons and a textctrl that I want arranged like so: ============================================== |WINDOW TITLE _ [] X| |============================================| |Button1 | Button2 | Button3 | Button4| |--------------------------------------------| |xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx| |xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx| |xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx| |xxxxxxxxxxxxxxxxxxTextCtrlxxxxxxxxxxxxxxxxxx| |xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx| |xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx| |xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx| ============================================== The buttons should expand horizontally, but not vertically, and the textctrl should expand both horizontally and vertically. I've tried pretty much every sizer listed in the wxPython demo program and none of them worked - multiple boxsizers, gridsizers + boxsizeres, plain gridsizer, flexgridsizer and rowcolsizer but none of it works, could someone help? For reference, here's the code that I've got right now. ...snip... panel = wx.Panel(self, -1) select_file = wx.Button(panel, self.BUTTON_0, "Select File") button1 = wx.Button(panel, self.BUTTON_1, "250 Words") button2 = wx.Button(panel, self.BUTTON_2, "500 Words") button3 = wx.Button(panel, self.BUTTON_3, "750 Words") self.txt = wx.TextCtrl(panel, -1, "", style=wx.TE_MULTILINE | wx.TE_READONLY) # Now to re-do this with gridsizers instead. # 4 rows, 4 columns, 2 pixel gap horizontally and vertically. grid = rcs.RowColSizer() # These buttons need to expand to fill their space, and then # expand when the windows are resized. grid.Add( select_file, row=1, col=1 ) grid.Add( button1, row=1, col=2 ) grid.Add( button2, row=1, col=3 ) grid.Add( button3, row=1, col=4 ) grid.Add( self.txt, row=2, col=1 ) ...snip... Answer: It took me a while to figure this out. It's something that I do with wxPython all the time. Essentially you need to nest box sizers. You need one vertical box sizer that holds two horizontal box sizers. Here is the code you need: import wx class sizertest(wx.Panel): def __init__(self,parent): wx.Panel.__init__(self,parent) vsizer = wx.BoxSizer(wx.VERTICAL) hsizer1 = wx.BoxSizer(wx.HORIZONTAL) button1 = wx.Button(self,-1,"button 1") self.Bind( wx.EVT_BUTTON,self.button1,button1) hsizer1.Add(button1,1,wx.EXPAND) button2 = wx.Button(self,-1,"button 2") self.Bind( wx.EVT_BUTTON,self.button2,button2) hsizer1.Add(button2,1,wx.EXPAND) vsizer.Add(hsizer1,.1,wx.EXPAND) self.SetSizer(vsizer) tc = wx.TextCtrl(self,-1,"",style=wx.TE_MULTILINE) hsizer2 = wx.BoxSizer(wx.HORIZONTAL) hsizer2.Add(tc,1,wx.EXPAND) vsizer.Add(hsizer2,1,wx.EXPAND) def button1(self,event):pass def button2(self,event):pass if __name__ == "__main__": app = wx.App() frame = wx.Frame(parent=None, id=-1, title="sizer test") panel = sizertest(frame) frame.Show() app.MainLoop() The vertical sizer vsizer holds two horizontal sizers. The first horizontal sizer holds as many buttons as you want to add to it, and they can expand horizontally. Because you add it to the vertical sizer with a number less than one for its "weight" it will not expand vertically. The second horizontal sizer holds the text control, and it can expand to take up all the remaining horizontal and vertical space. Both sizers expand as the window is expanded. I recommend that you get the book wxPython in Action by Rappin and Dunn - it really helped me understand how the wxPython sizers and screen layout works. I use nested boxsizers for 99% of my wxPython programs. Curt
Python tempfile module and threads aren't playing nice; what am I doing wrong? Question: I'm having an interesting problem with threads and the tempfile module in Python. Something doesn't appear to be getting cleaned up until the threads exit, and I'm running against an open file limit. (This is on OS X 10.5.8, Python 2.5.1.) Yet if I sort of replicate what the tempfile module is doing (not all the security checks, but just generating a file descriptor and then using os.fdopen to produce a file object) I have no problems. Before filing this as a bug with Python, I figured I'd check here, as it's much more likely that I'm doing something subtly wrong. But if I am, a day of trying to figure it out hasn't gotten me anywhere. #!/usr/bin/python import threading import thread import tempfile import os import time import sys NUM_THREADS = 10000 def worker_tempfile(): tempfd, tempfn = tempfile.mkstemp() tempobj = os.fdopen(tempfd, 'wb') tempobj.write('hello, world') tempobj.close() os.remove(tempfn) time.sleep(10) def worker_notempfile(index): tempfn = str(index) + '.txt' # The values I'm passing os.open may be different than tempfile.mkstemp # uses, but it works this way as does using the open() function to create # a file object directly. tempfd = os.open(tempfn, os.O_EXCL | os.O_CREAT | os.O_TRUNC | os.O_RDWR) tempobj = os.fdopen(tempfd, 'wb') tempobj.write('hello, world') tempobj.close() os.remove(tempfn) time.sleep(10) def main(): for count in range(NUM_THREADS): if count % 100 == 0: print('Opening thread %s' % count) wthread = threading.Thread(target=worker_tempfile) #wthread = threading.Thread(target=worker_notempfile, args=(count,)) started = False while not started: try: wthread.start() started = True except thread.error: print('failed starting thread %s; sleeping' % count) time.sleep(3) if __name__ == '__main__': main() If I run it with the `worker_notempfile` line active and the `worker_tempfile` line commented-out, it runs to completion. The other way around (using `worker_tempfile`) I get the following error: $ python threadtempfiletest.py Opening thread 0 Opening thread 100 Opening thread 200 Opening thread 300 Exception in thread Thread-301: Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py", line 460, in __bootstrap File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py", line 440, in run File "threadtempfiletest.py", line 17, in worker_tempfile File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/tempfile.py", line 302, in mkstemp File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/tempfile.py", line 236, in _mkstemp_inner OSError: [Errno 24] Too many open files: '/var/folders/4L/4LtD6bCvEoipksvnAcJ2Ok+++Tk/-Tmp-/tmpJ6wjV0' Any ideas what I'm doing wrong? Is this a bug in Python, or am I being bone- headed? **UPDATE 2009-12-14:** I think I've found the answer, but I don't like it. Since nobody was able to replicate the problem, I went hunting around our office for machines. It passed on everything except my machine. I tested on a Mac with the same software versions I was using. I even went hunting for a Desktop G5 with the EXACT same hardware and software config I had -- same result. Both tests (with tempfile and without tempfile) succeeded on everything. For kicks, I downloaded Python 2.6.4, and tried it on my desktop, and same pattern on my system as Python 2.5.1: tempfile failed, and notempfile succeeded. This is leading me to the conclusion that something's hosed on my Mac, but I sure can't figure out what. Any suggestions are welcome. Answer: I am unable to reproduce the problem with (Apple's own build of) Python 2.5.1 on Mac OS X 10.5.9 -- runs to completion just fine! I've tried both on a Macbook Pro, i.e., an Intel processor, and an old PowerMac, i.e., a PPC processor. So I can only imagine there must have been a bug in 10.5.8 which I never noticed (don't have any 10.5.8 around to test, as I always upgrade promptly whenever software update offers it). All I can suggest is that you try upgrading to 10.5.9 and see if the bug disappears -- if it doesn't, I have no idea how this behavior difference between my machines and yours is possible.
libnet creates UDP packets with invalid checksums Question: I'm using pylibnet to construct and send UDP packets. The UDP packets I construct in this way all seem to have invalid checksums. Example: # python Python 2.4.3 (#1, Sep 3 2009, 15:37:12) [GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> import libnet >>> from libnet.constants import * >>> >>> net = libnet.context(RAW4, 'venet0:0') >>> ip = net.name2addr4('www.stackoverflow.com', RESOLVE) >>> data = 'This is my payload.' >>> udptag = net.build_udp(sp=54321, dp=54321, payload=data) >>> packetlen = IPV4_H + UDP_H + len(data) >>> iptag = net.autobuild_ipv4(len=packetlen, prot=IPPROTO_UDP, dst=ip) >>> >>> net.write() Capturing the above packet on the sending host reveals an invalid checksum: # tcpdump -i venet0:0 -n -v -v port 54321 tcpdump: WARNING: arptype 65535 not supported by libpcap - falling back to cooked socket tcpdump: listening on venet0:0, link-type LINUX_SLL (Linux cooked), capture size 96 bytes 08:16:10.303719 IP (tos 0x0, ttl 64, id 1, offset 0, flags [none], proto: UDP (17), length: 47) 192.168.55.10.54321 > 69.59.196.211.54321: [bad udp cksum 50c3!] UDP, length 0 Am I doing something wrong here? Answer: It's nothing to do with tcpdump bugs or checksum offloading. Libnet calculates the checksum in user mode as well (FYI). The problem has to do with the fact that you did not specify a length for the UDP header. This is not automagically calculated in pylibnet or libnet so you have to specify it for the time being. Below is the corrected version of your code. I will apply a patch to pylibnet to automagically detect the header length in rc6. Stay tuned to <http://sourceforge.net/projects/pylibnet> for updates. I will be pushing a new release fixing this issue. By the way, please feel free to contact me via sourceforge's pylibnet page if you have bug or feature requests. I love to hear from developers using my software :) * * * import libnet from libnet.constants import * net = libnet.context(RAW4, 'venet0:0') ip = net.name2addr4('www.stackoverflow.com', RESOLVE) data = 'This is my payload.' udptag = net.build_udp(len=UDP_H+len(data), sp=54321, dp=54321, payload=data) packetlen = IPV4_H + UDP_H + len(data) iptag = net.autobuild_ipv4(len=packetlen, prot=IPPROTO_UDP, dst=ip) net.write()
Python: Checking Header Format Question: I'm new to python and need help with a problem. Basically I need to open a file and read it which I can do no problem. The problem arises at line 0, where I need to check the header format. The header needs to be in the format: `p wncf nvar nclauses hard` where 'nvar' 'nclauses' and 'hard' are all positive integers. For example: `p wncf 1563 817439 186191` would be a valid header line. Here is coding i have already thanks to a question people answered earlier: import re filename = raw_input('Please enter the name of the WNCF file: ') f = open(filename, 'r') for line in f: p = re.compile('p wncf \d+ \d+ \d+$') if p.match(line[0]) == None: print "incorrect format" I still get an incorrect format even when the file is of a correct format. Also, would it be possible to assign the integers to an object? Thanks in advance. Answer: Alright, a few things. 1. You only need to compile your regular expression once. In the example you gave above, you're recompiling it for every line in the file. 2. `line[0]` is just the first character in each line. Replace `line[0]` with `line` and your code should work. To assign the integers to an object, you have to surround the groups you want in parentheses. In your case, let p = re.compile(r"p wncf (\d+) (\d+) (\d+)") And instead of `p.match(line)`, which returns a match object or `None`, you could use `findall`. Check out the following as a replacement for what you have. p = re.compile(r"p wncf (\d+) (\d+) (\d+)") for line in f: matches = p.findall(line) if len(matches) != 0: print matches[0][0], matches[0][1], matches[0][2] else: print "No matches." Edit: If your header values can contain negative numbers as well, you should replace `r"p wncf (\d+) (\d+) (\d+)"` with `r"p wncf (-?\d+) (-?\d+) (-?\d+)"`.
split svnversion output in bash Question: I have this function, works fine, but I would like to rewrite it in bash. the problem is, I have too little knowledge of what's available in bash. #!/usr/bin/python def parse_svnversion(value): """split the output of svnversion into its three components given a string that looks like the output of the command svnversion, returns the 3-tuple (low, high, flags) >>> parse_svnversion('1024') (1024, 1024, '') >>> parse_svnversion('1024:2000') (1024, 2000, '') >>> parse_svnversion('1024M') (1024, 1024, 'M') >>> parse_svnversion('1024:2000MP') (1024, 2000, 'MP') """ values = filter(lambda x: x.isdigit() or x==':', value).split(':') return int(values[0]), int(values[-1]), filter(str.isalpha, value) if __name__ == '__main__': import doctest doctest.testmod() what I would like is a similarly small bash function that I can invoke and that will set something (three variables? an array?) that I can use. if it's an array, I would really like it to be of fixed size (3). Answer: This creates an array called "tuple" with three elements: [[ $(svnversion .) =~ ([0-9]+):*([0-9]*)([A-Z]*) ]] tuple[0]=${BASH_REMATCH[1]} tuple[1]=${BASH_REMATCH[2]:-${tuple[0]}} tuple[2]=${BASH_REMATCH[3]:-''} Requires Bash 3.2 or greater. It may work in Bash >= 3 and < 3.2. Not portable to the Bourne shell, although it can be adapted for the Korn shell or the Z shell. `ksh` uses the `.sh.match` array variable, for example: `${.sh.match[1]}` `zsh` uses the `match` array variable, for example: `${match[1]}` or you can do setopt bashrematch ksharrays to have it work with the Bash version exactly as above. The brace substitutions should be the same for all three.
Problems installing MySQL-python-1.2.3c1 on Mac Snow Leopard Question: Hi All I am having a problem installing the Python MySQL connector (MySQL- python-1.2.3c1) on my Mac OSX Snow Leopard. **System State** I have manually compiled an installed: **mysql-5.1.41** This seems to work fine, as I can create and query a database from the commandline. I have compiled: **MySQL-python-1.2.3c1** I first set the following in the **site.cfg** file: mysql_config = /usr/local/mysql/bin/mysql_config I then built and compiled MySQL-python-1.2.3c1 following their guide: sudo python setup.py build sudo python setup.py install I now test the installation with Python: python -c "import MySQLdb" **Error Message** This then gives me the following error, and I'm stumped as to how to fix it: Traceback (most recent call last): File "<string>", line 1, in <module> File "build/bdist.macosx-10.6-universal/egg/MySQLdb/__init__.py", line 19, in <module> File "build/bdist.macosx-10.6-universal/egg/_mysql.py", line 7, in <module> File "build/bdist.macosx-10.6-universal/egg/_mysql.py", line 6, in __bootstrap__ ImportError: dlopen(/Users/username/.python-eggs/MySQL_python-1.2.3c1-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so, 2): Symbol not found: _mysql_affected_rows Referenced from: /Users/username/.python-eggs/MySQL_python-1.2.3c1-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so Expected in: flat namespace in /Users/username/.python-eggs/MySQL_python-1.2.3c1-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so mymac: username$ **Things I've Tried** I've looked at this blog antoniocangiano.com but it is for an older version of MySQL-python and is not really applicable. But I tried adding the soft link it mentions. I then looked at this blog post: <http://blog.some-abstract- type.com/2009/09/mysql-python-and-mac-os-x-106-snow.html>. And tried building compiling with the ARCHFLAGS settings - but no joy. **Please Help** If you have any ideas please let me know. Many thanks Ben... Answer: What does otool -L /Users/username/.python-eggs/MySQL_python-1.2.3c1-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so report?
Examples of using Doctests in Django in an Agile / BDD way Question: I'm interested in learning how to Doctests and Unit tests in a more Agile / BDD way. I've found a few tutorials that seem reasonable, but they are just thumbnails. What I would really like to see is the source code of some Django projects that were developed BDD style. The things I'm unclear about are how do you handle request objects etc. I have a situation where I have deployed my app and I'm getting completely different behavior in production that I did in development or even from the Python shell on the production server. I'm hoping some Doctests will help me diagnose this and well as open the door for a more Agile process of writing the tests first. Specifically, here is the code I'm trying to test: def match_pictures_with_products( queryset, number_of_images = 3): products = [] i = 0 for product in queryset: if i < ( number_of_images ): image = product.imagemain_set.all()[:1] product.photo_url = image[0].photo.url products.append(product) i += 1 return products def index(request): """returns the top 10 most clicked products""" products = Product.objects.all()[:10] products = match_pictures_with_products( products, 10) . return render_to_response('products/product_list.html', {'products': products}) How do I create a Doctest that ensures that index returns 10 objects? The Product queries seem to work fine from the shell on the production server. The actual server is not returning any products at all. Answer: I've asked myself the same question before. I've found doctests to be of limited utility for things like views, model methods and managers because 1. You need to be able to setup and teardown a test data set to actually use for testing 2. Views need to take a request object. In a doctest, where does that come from? For that reason, I've always used the Django [unit testing](http://docs.djangoproject.com/en/1.1/topics/testing/#writing-unit- tests) framework which handles all this for you. Unfortunately, though, you don't get some of the benefits of the doctests and it makes TDD/BDD harder to do. What follows next is **pure speculation** about how you might make this work: I think you'd want to grab doctests from their respective modules and functions and execute them within the unit testing framework. This would take care of test data setup/teardown. If your doctests were executed from within a test method of something that subclasses Django's unittest.TestCase they'd be able to use that test DB. You'd also be able to pass a mock request object into the doc test's execution context. Here's a [Django snippet](http://www.djangosnippets.org/snippets/963/) that provides a mock request object and [info](http://groups.google.com/group/django- developers/browse%5Fthread/thread/db86050095ebe5db) on it. Let's say you wanted to test the docstrings from all of an applications views. You could do something like this in tests.py : from ??? import RequestFactory from doctest import testmod, DocTestFailure from django.test import TestCase from myapp import views class MyAppTest(TestCase): fixtures = ['test_data.json'] def test_doctests(self): try: testmod(views, extraglobs={ 'REQUEST': RequestFactory() }, raise_on_error=True) except DocTestFailure, e: self.fail(e) This _should_ allow you to do something like this: def index(request): """ returns the top 10 most clicked products >>> response = index(REQUEST) >>> [test response content here] """ products = Product.objects.all()[:10] products = match_pictures_with_products( products, 10) . return render_to_response('products/product_list.html', {'products': products}) Again, this is just off the top of my head and not at all tested, but it's the only way that I think you could what you want without just putting all your view tests in the unit testing framework.
From Sax to Dom with DTD (python) Question: I need a validated DomTree with DTD (to use `getElementById`). Validating and Parsing works, but the dom does't work properly: from xml.dom import minidom from xml.dom.pulldom import SAX2DOM from lxml import etree import lxml.sax from StringIO import StringIO data_string = """\ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE foo [ <!ELEMENT foo (bar)*> <!ELEMENT bar (#PCDATA)> <!ATTLIST bar id ID #REQUIRED>]><foo><bar id="nr_0">text</bar></foo> """ #parser, with vali. at parsing etree_parser = etree.XMLParser(dtd_validation=True,attribute_defaults=True) #parse it sax_tree = etree.parse(StringIO(data_string),etree_parser); handler = SAX2DOM(); lxml.sax.saxify(sax_tree,handler); domObject = handler.document; print domObject.getElementById("nr_0"); #returns None print minidom.parseString(data_string).getElementById("nr_0"); #returns <DOM Element: bar at 0x7f36b77dc0e0> It seems that SAX2DOM wont pass the DTD to the dom. Did I forgott something? I've read it is impossible to load the DTD after the dom is build. any ideas? Answer: As far as I know: SAX DTD events are not handled by the ContentHandler, but by the [DTDHandler](http://docs.python.org/library/xml.sax.reader.html?highlight=setproperty#xml.sax.xmlreader.XMLReader.setDTDHandler), which is a property you can set on the sax parser (XMLReader). This means that you cannot do this without serializing and reparsing the document. validated_string = etree.tostring(tree) domDocument = minidom.parseString(validated_string) On the other hand: unless you _really_ need a minidom document, you'd be better off just staying with the lxml tree. (you can use xpath for the equivalent of `getElementById`, or have a look at `etree.XMLDTDID` and `etree.parseid`)
Parsing XML to a hash table Question: I have an XML file in the following format: <doc> <id name="X"> <type name="A"> <min val="100" id="80"/> <max val="200" id="90"/> </type> <type name="B"> <min val="100" id="20"/> <max val="20" id="90"/> </type> </id> <type...> </type> </doc> I would like to parse this document and build a hash table {X: {"A": [(100,80), (200,90)], "B": [(100,20), (20,90)]}, Y: .....} How would I do this in Python? Answer: I disagree with the suggestion in other answers to use minidom -- that's a so- so Python adaptation of a standard originally conceived for other languages, usable but not a great fit. The recommended approach in modern Python is [ElementTree](http://docs.python.org/library/xml.etree.elementtree.html). The same interface is also implemented, faster, in third party module [lxml](http://codespeak.net/lxml/), but unless you need blazing speed the version included with the Python standard library is fine (and faster than minidom anyway) -- the key point is to program to that interface, then you can always switch to a different implementation of the same interface in the future if you want to, with minimal changes to your own code. For example, after the needed imports &c, the following code is a minimal implementation of your example (it does not verify that the XML is correct, just extracts the data assuming correctness -- adding various kinds of checks is pretty easy of course): from xml.etree import ElementTree as et # or, import any other, faster version of ET def xml2data(xmlfile): tree = et.parse(xmlfile) data = {} for anid in tree.getroot().getchildren(): currdict = data[anid.get('name')] = {} for atype in anid.getchildren(): currlist = currdict[atype.get('name')] = [] for c in atype.getchildren(): currlist.append((c.get('val'), c.get('id'))) return data This produces your desired result given your sample input.
Nested SSH session with Paramiko Question: I'm rewriting a Bash script I wrote into Python. The crux of that script was ssh -t first.com "ssh second.com very_remote_command" I'm having a problem with the nested authentication with paramiko. I wasn't able to find any examples dealing with my precise situation, but I was able to find examples with _sudo_ on a remote host. [The first method](http://jessenoller.com/2009/02/05/ssh-programming-with- paramiko-completely-different/) writes to stdin ssh.connect('127.0.0.1', username='jesse', password='lol') stdin, stdout, stderr = ssh.exec_command("sudo dmesg") stdin.write('lol\n') stdin.flush() [The second](http://www.gossamer-threads.com/lists/python/bugs/765465) creates a channel and uses the socket-like _send_ and _recv_. I was able to get _stdin.write_ to work with _sudo_ , but it doesn't work with _ssh_ on the remote host. import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('first.com', username='luser', password='secret') stdin, stdout, stderr = ssh.exec_command('ssh luser@second.com') stdin.write('secret') stdin.flush() print '---- out ----' print stdout.readlines() print '---- error ----' print stderr.readlines() ssh.close() ...prints... ---- out ---- [] ---- error ---- ['Pseudo-terminal will not be allocated because stdin is not a terminal.\r\n', 'Permission denied, please try again.\r\n', 'Permission denied, please try again.\r\n', 'Permission denied (publickey,password,keyboard-interactive).\r\n'] The pseudo-terminal error reminded me of the -t flag in my original command, so I switched to the second method, using a Channel. Instead of ssh.exec_command and later, I have: t = ssh.get_transport() chan = t.open_session() chan.get_pty() print '---- send ssh cmd ----' print chan.send('ssh luser@second.com') print '---- recv ----' print chan.recv(9999) chan = t.open_session() print '---- send password ----' print chan.send('secret') print '---- recv ----' print chan.recv(9999) ...but it prints '---- send ssh cmd ----' and just hangs until I kill the process. I'm new to Python and none too knowledgeable about networks. In the first case, why does sending the password work with _sudo_ but not with _ssh_? Are the prompts different? Is paramiko even the right library for this? Answer: I managed to find a solution, but it requires a little manual work. If anyone have a better solution, please tell me. ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('first.com', username='luser', password='secret') chan = ssh.invoke_shell() # Ssh and wait for the password prompt. chan.send('ssh second.com\n') buff = '' while not buff.endswith('\'s password: '): resp = chan.recv(9999) buff += resp # Send the password and wait for a prompt. chan.send('secret\n') buff = '' while not buff.endswith('some-prompt$ '): resp = chan.recv(9999) buff += resp # Execute whatever command and wait for a prompt again. chan.send('ls\n') buff = '' while not buff.endswith('some-prompt$ '): resp = chan.recv(9999) buff += resp # Now buff has the data I need. print 'buff', buff ssh.close() The thing to note is that instead of this t = ssh.get_transport() chan = t.open_session() chan.get_pty() ...you want this chan = ssh.invoke_shell() It reminds me of when I tried to write a TradeWars script when I was a kid and gave up coding for ten years. :)
Marking a frame as sticky with wxPython Question: Is there a way to set the "sticky" bit for a frame/window, with wxPython? (wxPython 2.8.9.1 under Ubuntu Jaunty) Answer: Here's what I came up with: import gtk def set_sticky(frame): gdkwin = gtk.gdk.window_lookup(frame.GetHandle()) win = gdkwin.get_user_data() # http://library.gnome.org/devel/gdk/unstable/gdk-Windows.html#gdk-window-get-user-data while not isinstance(win, gtk.Window): win = win.get_parent() win.stick()
split a generator/iterable every n items in python (splitEvery) Question: I'm trying to write the Haskel function 'splitEvery' in Python. Here is it's definition: splitEvery :: Int -> [e] -> [[e]] @'splitEvery' n@ splits a list into length-n pieces. The last piece will be shorter if @n@ does not evenly divide the length of the list. The basic version of this works fine, but I want a version that works with generator expressions, lists, and iterators. _And_ , if there is a generator as an input it should return a generator as an output! ## Tests # should not enter infinite loop with generators or lists splitEvery(itertools.count(), 10) splitEvery(range(1000), 10) # last piece must be shorter if n does not evenly divide assert splitEvery(5, range(9)) == [[0, 1, 2, 3, 4], [5, 6, 7, 8]] # should give same correct results with generators tmp = itertools.islice(itertools.count(), 10) assert list(splitEvery(5, tmp)) == [[0, 1, 2, 3, 4], [5, 6, 7, 8]] ## Current Implementation Here is the code I currently have but it doesn't work with a simple list. def splitEvery_1(n, iterable): res = list(itertools.islice(iterable, n)) while len(res) != 0: yield res res = list(itertools.islice(iterable, n)) This one doesn't work with a generator expression (thanks to jellybean for fixing it): def splitEvery_2(n, iterable): return [iterable[i:i+n] for i in range(0, len(iterable), n)] There has to be a simple piece of code that does the splitting. I know I could just have different functions but it seems like it should be and easy thing to do. I'm probably getting stuck on an unimportant problem but it's really bugging me. * * * It is similar to grouper from <http://docs.python.org/library/itertools.html#itertools.groupby> but I don't want it to fill extra values. def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) It does mention a method that truncates the last value. This isn't what I want either. > The left-to-right evaluation order of the iterables is guaranteed. This > makes possible an idiom for clustering a data series into n-length groups > using izip(_[iter(s)]_ n). list(izip(*[iter(range(9))]*5)) == [[0, 1, 2, 3, 4]] # should be [[0, 1, 2, 3, 4], [5, 6, 7, 8]] Answer: from itertools import islice def split_every(n, iterable): i = iter(iterable) piece = list(islice(i, n)) while piece: yield piece piece = list(islice(i, n)) Some tests: >>> list(split_every(5, range(9))) [[0, 1, 2, 3, 4], [5, 6, 7, 8]] >>> list(split_every(3, (x**2 for x in range(20)))) [[0, 1, 4], [9, 16, 25], [36, 49, 64], [81, 100, 121], [144, 169, 196], [225, 256, 289], [324, 361]] >>> [''.join(s) for s in split_every(6, 'Hello world')] ['Hello ', 'world'] >>> list(split_every(100, [])) []
Inheritable custom exceptions in python Question: I want to create some custom exceptions for my class. I am trying to figure out the best way to make these exception classes inheritable in derived classes. The tutorial shows how to create the Exception classes. So I did that like this: I created a baseclass.py: class Error(Exception): """Base class for exceptions in BaseClass""" pass class SomeError(Error): """Exection for some error""" def __init__(self, msg): self.msg = msg class OtherError(Error): """Exection for some error""" def __init__(self, msg): self.msg = msg class BaseClass(): """Base test class for testing exceptions""" def dosomething(self): raise SomeError, "Got an error doing something" And a derivedclass.py: from baseclass import BaseClass,SomeError,OtherError class DerivedClass(BaseClass): def doother(self): """Do other thing""" raise OtherError, "Error doing other" Then a test that uses the DerivedClass: #!/usr/bin/python from derivedclass import DerivedClass,SomeError,OtherError """Test from within module""" x = DerivedClass() try: x.dosomething() except SomeError: print "I got some error ok" try: x.doother() except OtherError: print "I got other error ok" So as you can see, I imported the exception classes from the base class into the derived class, then again from the derived class into the program. This seems to work ok, but is not very elegant, and I'm worried about having to make sure and do an import in the derived class module for all the Exception classes. It seems like it would be easy to forget one when creating a new derived class. Then a user of the derived class would get an error if they tried to use it. Is there a better way to do this? Thanks! -Mark Answer: The custom exceptions has to be imported in all modules its used in. Also, there is an error in derivedclass.py Wrong (because of the way its imported) raise baseclass.OtherError, "Error doing other" Fixed raise OtherError, "Error doing other"
Compare two images the python/linux way Question: Trying to solve a problem of preventing duplicate images to be uploaded. I have two JPGs. Looking at them I can see that they are in fact identical. But for some reason they have different file size (one is pulled from a backup, the other is another upload) and so they have a different md5 checksum. How can I efficiently and confidently compare two images in the same sense as a human would be able to see that they are clearly identical? Example: <http://static.peterbe.com/a.jpg> and <http://static.peterbe.com/b.jpg> **Update** I wrote this script: import math, operator from PIL import Image def compare(file1, file2): image1 = Image.open(file1) image2 = Image.open(file2) h1 = image1.histogram() h2 = image2.histogram() rms = math.sqrt(reduce(operator.add, map(lambda a,b: (a-b)**2, h1, h2))/len(h1)) return rms if __name__=='__main__': import sys file1, file2 = sys.argv[1:] print compare(file1, file2) Then I downloaded the two visually identical images and ran the script. Output: 58.9830484122 Can anybody tell me what a suitable cutoff should be? **Update II** The difference between a.jpg and b.jpg is that the second one has been saved with PIL: b=Image.open('a.jpg') b.save(open('b.jpg','wb')) This apparently applies some very very light quality modifications. I've now solved my problem by applying the same PIL save to the file being uploaded without doing anything with it and it now works! Answer: There is a OSS project that uses WebDriver to take screen shots and then compares the images to see if there are any issues ([http://code.google.com/p/fighting-layout- bugs/)](http://code.google.com/p/fighting-layout-bugs/)). It does it by openning the file into a stream and then comparing every bit. You may be able to do something similar with [PIL](http://www.pythonware.com/products/pil). EDIT: After more research I found h1 = Image.open("image1").histogram() h2 = Image.open("image2").histogram() rms = math.sqrt(reduce(operator.add, map(lambda a,b: (a-b)**2, h1, h2))/len(h1)) on <http://snipplr.com/view/757/compare-two-pil-images-in-python/> and <http://effbot.org/zone/pil-comparing-images.htm>
packaging cryptography software and distributing Question: I'm developing a python GUI application and plan on calling external program packaged with my program to do some encryption. I noticed from sites like OpenSSL that talk about export laws regarding cryptography software. If I can't package binary forms of the cryptography software with my application, how can I work around this to still be able to encrypt the output of my program? Answer: You need to pick your target audiences with care, especially when you are dancing around with ITAR -- the International Traffic in Arms Regulations. Identify the countries you can legally export your product to and then, at the very least, say that people from other countries can't download it. You may have to do more than that to stay legal in your country. Legally, this is getting into the deep end of the pool and you will want to talk to a _knowledgeable_ attorney about this. If you live in Finland, you can probably do whatever you like. If you live in the US, be careful. If you live in France, be _very_ careful. **Update:** Sometimes I feel old, other days I prove it. Without checking on the current ITAR handling of strong cryptography I responded with an answer that is at least 12 years out of date. Prior to 1997 exporting crypto of any sort, from/to any country, was a very dicey thing to do and carried severe legal penalties. This was especially true in France which, for a time, outlawed all non-governmental uses of crypto, even very weak 40-bit DES. Although France has loosened up a bit, they still seem to behind most other developed countries in understanding that a) their citizens have a valid right to privacy, and b) there's not much they can do to stop it in a world where 4096 bit RSA is available all over the net. ITAR's stance on crypto changed in 96-97. Although matters have improved in general, there are still obstacles to exporting/importing crypto. Before you go too much further you should thoroughly familiarize yourself with the laws of _your_ country regarding cryto -- you might be shocked/saddened by what you find. Even the U.S. [still has some restrictions](http://www.access.gpo.gov/bis/ear/pdf/740.pdf) on what kind of crypto you can export to whom and in what form. Some countries, notably France and the U.K., have had (and appear to still have in some form or other) laws that can require the supplier of the software to either escrow keys used by their customers and/or provide a backdoor into the system in case the government wants to see what you are talking about. **Bottom line:** Good crypto makes governments nervous and the laws on what is legal/illegal are all over the map. Try to understand exactly what role encryption plays in your proposed product/project and determine if it's something that a user can opt in/out of based on their own country's stance on the subject.
Python - specify which function in file to use on command line Question: Assume you have a programme with multiple functions defined. Each function is called in a separate for loop. Is it possible to specify which function should be called via the command line? Example: python prog.py -x <<<filname>>> Where -x tells python to go to a particular for loop and then execute the function called in that for loop? Thanks, Seafoid. Answer: The Python idiom for the main entry point: if __name__ == '__main__': main() Replace `main()` by whatever function should go first ... (more on `if name ...`: <http://effbot.org/pyfaq/tutor-what-is-if-name-main-for.htm>) If you want to specify the function to run via command line argument, just check these arguments, either manually or via some helpers, e.g. <http://docs.python.org/library/optparse.html>, then branch of to the desired function. If you don't want stuff like this: if options.function_to_call == 'mydesiredfunction': mydesiredfunction() You can take advantage of [`getattr`](http://diveintopython.net/power_of_introspection/getattr.html). And finally, another 'generic' approach using [`globals`](http://www.faqs.org/docs/diveintopython/dialect_locals.html) (exception handling excluded): $ cat 1933407.py #!/usr/bin/env python # coding: utf-8 import sys def first(): print '1 of 9' def second(): print '2 of 9' def seventh(): print '7 of 9' if __name__ == '__main__': globals()[sys.argv[1]]() Meanwhile at the command line ... $ python 1933407.py second 2 of 9
Xpath builder in Python Question: I'm building relatively complicated xpath expressions in Python, in order to pass them to selenium. However, its pretty easy to make a mistake, so I'm looking for a library that allows me to build the expressions without messing about with strings. For example, instead of writing locator='//ul[@class="comment-contents"][contains(., "West")]/li[contains(., "reply")] I could write something like: import xpathbuilder as xpb locator = xpb.root("ul") .filter(attr="class",value="comment-contents") .filter(xpb.contains(".", "West") .subclause("li") .filter(xpb.contains (".", "reply")) which is maybe not as readable, but is less error-prone. Does anything like this exist? Answer: though this is not exactly what you want.. you can use css selector ... import lxml.cssselect csssel = 'div[class="main"]' selobj = lxml.cssselect.CSSSelector(csssel) elements = selobj(documenttree) generated XPath expression is in `selobj.path` >>> selobj.path u"descendant-or-self::div[@class = 'main']"
numpy to matlab interface with mlabwrap Question: I am looking for a simple way to visualize some of my data in numpy, and I discovered the `mlabwrap` package which looks really promising. I am trying to create a simple plot with the ability to be updated as the data changes. Here is the matlab code that I am trying to duplicate >> h = plot([1,2,3], [1,2,3], '-o'); >> set(h, 'XData', [0,0,0]); >> drawnow(); to python >> from mlabwrap import mlab >> h = mlab.plot([1,2,3], [1,2,3], '-o') >> mlab.set(h, 'XData', [0,0,0]) >> mlab.drawnow(); However, the second to last command fails with an error message error: One or more output arguments not assigned during call to "set". Any suggestions on how to fix this? Answer: Maybe mlab is mad that you're not saving matlab's return value for that set() call... I don't have this installed, what does `someval = mlab.set(h,'XData')` give? edit: you could also try using nout... `mlab.set(h,'XData',[0,0,0],nout=0)`
How to import constants from .h file into python module Question: What is a recommended way to import a bunch of constants defined in a c-style (not c++, just plain old c) .h file into python module so that it can be used in python's part of a project. In the project we use a mix of languages and in perl I can do this importing by using h2xs utility to generate .pm module. Constants definition looks like #define FOO 1 enum { BAR, BAZ }; etc. C-style comments are also presented an have to be properly handled. Answer: I recently used the pyparsing library to scan for enum constants. Here it is, along with a sample string and the resulting output. Notice it also handles comments and commented out sections. With a little modification it could stuff the constants in a dictionary. from pyparsing import * sample = ''' stuff before enum hello { Zero, One, Two, Three, Five=5, Six, Ten=10 } in the middle enum blah { alpha, // blah beta, /* blah blah gamma = 10 , */ zeta = 50 } at the end ''' # syntax we don't want to see in the final parse tree _lcurl = Suppress('{') _rcurl = Suppress('}') _equal = Suppress('=') _comma = Suppress(',') _enum = Suppress('enum') identifier = Word(alphas,alphanums+'_') integer = Word(nums) enumValue = Group(identifier('name') + Optional(_equal + integer('value'))) enumList = Group(enumValue + ZeroOrMore(_comma + enumValue)) enum = _enum + identifier('enum') + _lcurl + enumList('list') + _rcurl enum.ignore(cppStyleComment) for item,start,stop in enum.scanString(sample): id = 0 for entry in item.list: if entry.value != '': id = int(entry.value) print '%s_%s = %d' % (item.enum.upper(),entry.name.upper(),id) id += 1 OUTPUT: HELLO_ZERO = 0 HELLO_ONE = 1 HELLO_TWO = 2 HELLO_THREE = 3 HELLO_FIVE = 5 HELLO_SIX = 6 HELLO_TEN = 10 BLAH_ALPHA = 0 BLAH_BETA = 1 BLAH_ZETA = 50
Python 3: create a list of possible ip addresses from a CIDR notation Question: I have been handed the task of creating a function in python (3.1) that will take a CIDR notation and return the list of possible ip addresses. I have looked around python.org and found this: <http://docs.python.org/dev/py3k/library/ipaddr.html> but i haven't seen anything that will fill this need... I would be very grateful for any assistance anyone cares to kick my way. thanks in advance. :-) Answer: If you aren't married to using the built-in module, there is a project called [netaddr](http://code.google.com/p/netaddr/) that is the best module I have used for working with IP networks. Have a look at the [IP Tutorial](http://code.google.com/p/netaddr/wiki/IPTutorial) which illustrates how easy it is working with networks and discerning their IPs. Simple example: >>> from netaddr import IPNetwork >>> for ip in IPNetwork('192.0.2.0/23'): ... print '%s' % ip ... 192.0.2.0 192.0.2.1 192.0.2.2 192.0.2.3 ... 192.0.3.252 192.0.3.253 192.0.3.254 192.0.3.255
Does Python support MySQL prepared statements? Question: I worked on a PHP project earlier where prepared statements made the SELECT queries 20% faster. I'm wondering if it works on Python? I can't seem to find anything that specifically says it does or does NOT. Answer: Most languages provide a way to do generic parameterized statements, Python is no different. When a parameterized query is used databases that support preparing statements will automatically do so. In python a parameterized query looks like this: cursor.execute("SELECT FROM tablename WHERE fieldname = %s", [value]) The specific style of parameterization may be different depending on your driver, you can import your db module and then do a `print yourmodule.paramstyle`. From [PEP-249](http://www.python.org/dev/peps/pep-0249/): > paramstyle > > > String constant stating the type of parameter marker > formatting expected by the interface. Possible values are > [2]: > > 'qmark' Question mark style, > e.g. '...WHERE name=?' > 'numeric' Numeric, positional style, > e.g. '...WHERE name=:1' > 'named' Named style, > e.g. '...WHERE name=:name' > 'format' ANSI C printf format codes, > e.g. '...WHERE name=%s' > 'pyformat' Python extended format codes, > e.g. '...WHERE name=%(name)s' >
What's the point of a main function and/or __name__ == "__main__" check in Python? Question: > **Possible Duplicate:** > [What does <if __name__=="__main__":> > do?](http://stackoverflow.com/questions/419163/what-does-if-namemain-do) I occasionally notice something like the following in Python scripts: if __name__ == "__main__": # do stuff like call main() What's the point of this? Answer: Having all substantial Python code live inside a function (i.e., **not** at module top level) is a crucial performance optimization as well as an important factor in good organization of code (the Python compiler can optimize access to local variables in a function much better than it can optimize "local" variables which are actually a module's globals, since the semantics of the latter are more demanding). Making the call to the function conditional on the current module being run as the "main script" (rather than imported from another module) makes for potential reusability of nuggets of functionality contained in the module (since other modules may import it and just call the appropriate functions or classes), and even more importantly it supports solid unit testing (where all sort of mock-ups and fakes for external subsystems may generally need to be set up before the module's functionality is exercised and tested).
get many pages with pycurl? Question: I want to get many pages from a website, like curl "http://farmsubsidy.org/DE/browse?page=[0000-3603]" -o "de.#1" but get the pages' data in python, not disk files. Can someone please post `pycurl` code to do this, or fast `urllib2` (not one-at-a-time) if that's possible, or else say "forget it, curl is faster and more robust" ? Thanks Answer: So you have 2 problem and let me show you in one example. Notice the pycurl already did the multithreading/not one-at-a-time w/o your hardwork. #! /usr/bin/env python import sys, select, time import pycurl,StringIO c1 = pycurl.Curl() c2 = pycurl.Curl() c3 = pycurl.Curl() c1.setopt(c1.URL, "http://www.python.org") c2.setopt(c2.URL, "http://curl.haxx.se") c3.setopt(c3.URL, "http://slashdot.org") s1 = StringIO.StringIO() s2 = StringIO.StringIO() s3 = StringIO.StringIO() c1.setopt(c1.WRITEFUNCTION, s1.write) c2.setopt(c2.WRITEFUNCTION, s2.write) c3.setopt(c3.WRITEFUNCTION, s3.write) m = pycurl.CurlMulti() m.add_handle(c1) m.add_handle(c2) m.add_handle(c3) # Number of seconds to wait for a timeout to happen SELECT_TIMEOUT = 1.0 # Stir the state machine into action while 1: ret, num_handles = m.perform() if ret != pycurl.E_CALL_MULTI_PERFORM: break # Keep going until all the connections have terminated while num_handles: # The select method uses fdset internally to determine which file descriptors # to check. m.select(SELECT_TIMEOUT) while 1: ret, num_handles = m.perform() if ret != pycurl.E_CALL_MULTI_PERFORM: break # Cleanup m.remove_handle(c3) m.remove_handle(c2) m.remove_handle(c1) m.close() c1.close() c2.close() c3.close() print "http://www.python.org is ",s1.getvalue() print "http://curl.haxx.se is ",s2.getvalue() print "http://slashdot.org is ",s3.getvalue() Finally, these code is mainly based on an example on the pycurl site =.= may be you should really read doc. ppl spend huge time on it.
In memory database with socket capability Question: Python --> SQLite --> ASP.NET C# I am looking for an in memory database application that does not have to write the data it receives to disc. Basically, I'll be having a Python server which receives gaming UDP data and translates the data and stores it in the memory database engine. I want to stay away from writing to disc as it takes too long. The data is not important, if something goes wrong, it simply flushes and fills up with the next wave of data sent by players. Next, another ASP.NET server must be able to connect to this in memory database via TCP/IP at regular intervals, say once every second, or 10 seconds. It has to pull this data, and this will in turn update on a website that displays "live" game data. I'm looking at SQlite, and wondering, is this the right tool for the job, anyone have any suggestions? Thanks!!! Answer: Totally not my field, but I think [Redis](http://simonwillison.net/2009/Oct/22/redis/) is along these lines.
pylint PyQt4 error Question: I write a program : from PyQt4.QtCore import * from PyQt4.QtGui import * def main(): app = QApplication([]) button = QPushButton("hello?") button.show() app.exec_() if __name__=="__main__": main() the file name is t.py, when I run: pylint t.py in ubuntu9.10, pyqt4, I got this: pylint t.py No config file found, using default configuration error while building astng for /home/halida/data/workspace/test/t.py Traceback (most recent call last): File "/usr/lib/pymodules/python2.6/logilab/astng/manager.py", line 126, in astng_from_file astng = ASTNGBuilder(self).file_build(filepath, modname) File "/usr/lib/pymodules/python2.6/logilab/astng/builder.py", line 118, in file_build node = self.string_build(data, modname, path) File "/usr/lib/pymodules/python2.6/logilab/astng/builder.py", line 128, in string_build return self.ast_build(parse(data + '\n'), modname, path) File "/usr/lib/pymodules/python2.6/logilab/astng/builder.py", line 147, in ast_build self.rebuilder.walk(node) File "/usr/lib/pymodules/python2.6/logilab/astng/rebuilder.py", line 89, in walk self._walk(node) File "/usr/lib/pymodules/python2.6/logilab/astng/rebuilder.py", line 109, in _walk self._walk(child, node) File "/usr/lib/pymodules/python2.6/logilab/astng/rebuilder.py", line 103, in _walk handle_leave = node.accept(self) File "/usr/lib/pymodules/python2.6/logilab/astng/nodes.py", line 159, in accept return func(self) File "/usr/lib/pymodules/python2.6/logilab/astng/rebuilder.py", line 188, in visit_from imported = node.root().import_module(node.modname) File "/usr/lib/pymodules/python2.6/logilab/astng/scoped_nodes.py", line 282, in import_module return MANAGER.astng_from_module_name(self.relative_name(modname, level)) File "/usr/lib/pymodules/python2.6/logilab/astng/manager.py", line 172, in astng_from_module_name return self.astng_from_module(module, modname) File "/usr/lib/pymodules/python2.6/logilab/astng/manager.py", line 207, in astng_from_module astng = ASTNGBuilder(self).module_build(module, modname) File "/usr/lib/pymodules/python2.6/logilab/astng/builder.py", line 80, in module_build node = self.inspect_build(module, modname=modname, path=path) File "/usr/lib/pymodules/python2.6/logilab/astng/builder.py", line 95, in inspect_build self.object_build(node, module) File "/usr/lib/pymodules/python2.6/logilab/astng/builder.py", line 195, in object_build self.object_build(class_node, member) File "/usr/lib/pymodules/python2.6/logilab/astng/builder.py", line 198, in object_build object_build_methoddescriptor(node, member) File "/usr/lib/pymodules/python2.6/logilab/astng/raw_building.py", line 150, in object_build_methoddescriptor func = build_function(member.__name__, doc=member.__doc__) AttributeError: 'PyQt4.QtCore.pyqtSignal' object has no attribute '__name__' ************* Module t F: 1: <class 'logilab.astng._exceptions.ASTNGBuildingException'>: Unable to load module t ('PyQt4.QtCore.pyqtSignal' object has no attribute '__name__') Compilation exited abnormally with code 1 at Sat Dec 26 10:43:54 in windows XP, with pythonxy, I only got a error message, why? Answer: Looks like a bug in `astng`. They try to read the name of a function which does not publish it (native extension func). I'd report a bug to both `astng` and `pyqt` projects. The first one would be that they should handle a no-name situation better. The second one would be that every sane extension should publish at least the function names.
Inserting multiple types into an SQLite database with Python Question: I'm trying to create an [SQLite](http://en.wikipedia.org/wiki/SQLite) 3 database from Python. I have a few types I'd like to insert into each record: A float, and then 3 groups of n floats, currently a tuple but could be an array or list.. I'm not well-enough versed in Python to understand all the differences. My problem is the INSERT statement. DAS = 12345 lats = (42,43,44,45) lons = (10,11,12,13) times = (1,2,3,4,5,6,7,8,9) import sqlite3 connection = sqlite3.connect("test.db") cursor = connection.cursor() cursor.execute( "create table foo(DAS LONG PRIMARY KEY,lats real(4),lons real(4), times real(9) )" ) I'm not sure what comes next. Something along the lines of: cmd = 'INSERT into foo values (?,?,?,?), ..." cursor.execute(cmd) How should I best build the SQL insert command given this data? Answer: The type `real(4)` does not mean an array/list/tuple of 4 reals; the 4 alters the 'real' type. However, SQLite mostly ignores column types due to its manifest typing, but they can still affect [column affinity](http://sqlite.org/datatype3.html#affinity). You have a few options, such as storing the text representation (from repr) or using four columns, one for each. You can modify this with various hooks provided by the Python's [SQLite library](http://docs.python.org/library/sqlite3.html) to handle some of the transformation for you, but separate columns (with functions to localize and handle various statements, so you don't repeat yourself) is probably the easiest to work with if you need to search/etc. in SQL on each value. If you do store a text representation, [ast.literal_eval](http://docs.python.org/library/ast.html#ast.literal_eval) (or eval, under special conditions) will convert back into a Python object.
Measure time of a function with arguments in Python Question: I am trying to measure the time of `raw_queries(...)`, unsuccessfully so far. I found that I should use the timeit module. The problem is that I can't (= I don't know how) pass the arguments to the function from the environment. Important note: Before calling `raw_queries`, we have to execute `phase2()` (environment initialization). Side note: The code is in Python 3. def raw_queries(queries, nlp): """ Submit queries without getting visual response """ for q in queries: nlp.query(q) def evaluate_queries(queries, nlp): """ Measure the time that the queries need to return their results """ t = Timer("raw_queries(queries, nlp)", "?????") print(t.timeit()) def phase2(): """ Load dictionary to memory and subsequently submit queries """ # prepare Linguistic Processor to submit it the queries all_files = get_files() b = LinguisticProcessor(all_files) b.loadDictionary() # load the queries queries_file = 'queries.txt' queries = load_queries(queries_file) if __name__ == '__main__': phase2() Thanks for any help. UPDATE: We can call `phase2()` using the second argument of `Timer`. The problem is that we need the arguments `(queries, nlp)` from the environment. UPDATE: The best solution so far, with unutbu's help (only what has changed): def evaluate_queries(): """ Measure the time that the queries need to return their results """ t = Timer("main.raw_queries(queries, nlp)", "import main;\ (queries,nlp)=main.phase2()") sf = 'Execution time: {} ms' print(sf.format(t.timeit(number=1000))) def phase2(): ... return queries, b def main(): evaluate_queries() if __name__ == '__main__': main() Answer: First, never use the time module to time functions. It can easily lead to wrong conclusions. See <http://stackoverflow.com/questions/1622943/timeit- versus-timing-decorator> for an example. The easiest way to time a function call is to use IPython's %timeit command. There, you simply start an interactive IPython session, call `phase2()`, define `queries`, and then run %timeit raw_queries(queries,nlp) The second easiest way that I know to use timeit is to call it from the command-line: python -mtimeit -s"import test; queries=test.phase2()" "test.raw_queries(queries)" (In the command above, I assume the script is called `test.py`) The idiom here is python -mtimeit -s"SETUP_COMMANDS" "COMMAND_TO_BE_TIMED" To be able to pass `queries` to the `raw_queries` function call, you have to define the `queries` variable. In the code you posted `queries` is defined in `phase2()`, but only locally. So to setup `queries` as a global variable, you need to do something like have `phase2` return `queries`: def phase2(): ... return queries If you don't want to mess up `phase2` this way, create a dummy function: def phase3(): # Do stuff like phase2() but return queries return queries
Is there any Visual Studio-like tool for creating GUIs for Python? Question: My girlfriend asked me if there was a tool (actually, an IDE) that would let her create her GUI visually and edit functions associated with GUI-related events with little effort. **For example, she wants to double-click a button she just created and immediately see (and edit) the code associated with that button's on-click event. I believe this is what she does in Visual Studio.** The toolkit doesn't matter. She just wants this funcionality. Is there some tool that accomplishes this? Thank you. EDIT: Made the example look bold. Seemed no one was looking at it, and it's an important requirement. Answer: I would recommend based on your needs: * Qt Designer * wxGlade Check this out: <http://wiki.python.org/moin/GuiProgramming>