content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
sequence
answers_scores
sequence
non_answers
sequence
non_answers_scores
sequence
tags
sequence
name
stringlengths
35
137
Q: _lsprof.c profiler behaviour towards python multi-threading This is a question about Python native c file _lsprof. How does _lsprof.profile() profiler counts total time spent on a function f in a multi-threaded program if the execution of f is interrupted by another thread? For example: def f(): linef1 linef2 linef3 def g(): lineg1 lineg2 And at the execution we have, f and g not being in the same thread: linef1 linef2 lineg1 linef3 lineg2 Then will the total runtime of f be perceived as the amount of time needed to do: linef1 linef2 linef3 or will it be the effective latency time: linef1 linef2 lineg1 linef3 in the results of _lsprof.profile()? A: Quoting from the documentation for setprofile: The function is thread-specific, but there is no way for the profiler to know about context switches between threads, so it does not make sense to use this in the presence of multiple threads. A: Thank you for this answer! Actually I am running one profiler in each context, so the question make sense. From the tests I made the profiler would measure "linef1 linef2 linef3" in the above example.
_lsprof.c profiler behaviour towards python multi-threading
This is a question about Python native c file _lsprof. How does _lsprof.profile() profiler counts total time spent on a function f in a multi-threaded program if the execution of f is interrupted by another thread? For example: def f(): linef1 linef2 linef3 def g(): lineg1 lineg2 And at the execution we have, f and g not being in the same thread: linef1 linef2 lineg1 linef3 lineg2 Then will the total runtime of f be perceived as the amount of time needed to do: linef1 linef2 linef3 or will it be the effective latency time: linef1 linef2 lineg1 linef3 in the results of _lsprof.profile()?
[ "Quoting from the documentation for setprofile:\n\nThe function is thread-specific, but\n there is no way for the profiler to\n know about context switches between\n threads, so it does not make sense to\n use this in the presence of multiple\n threads.\n\n", "Thank you for this answer! Actually I am running one profiler in each context, so the question make sense. From the tests I made the profiler would measure \"linef1 linef2 linef3\" in the above example.\n" ]
[ 1, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0000443082_multithreading_python.txt
Q: How to Alter Photographed Document to Look "Scanned" How can I do this in Python/PIL? I.e., given the four points of an offset rectangle (a photographed document), make it look flat on as if it were scanned. Is there a simple algorithm for it? Also, are there any other manipulations I should do to make it look more "scan-like"? I want to make a simple version of this program for myself in Python. A: Look at transform() with method set to QUAD https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.transform im.transform(size, QUAD, data) => image im.transform(size, QUAD, data, filter) => image Maps a quadrilateral (a region defined by four corners) from the image to a rectangle with the given size. Data is an 8-tuple (x0, y0, x1, y1, x2, y2, y3, y3) which contain the upper left, lower left, lower right, and upper right corner of the source quadrilateral.
How to Alter Photographed Document to Look "Scanned"
How can I do this in Python/PIL? I.e., given the four points of an offset rectangle (a photographed document), make it look flat on as if it were scanned. Is there a simple algorithm for it? Also, are there any other manipulations I should do to make it look more "scan-like"? I want to make a simple version of this program for myself in Python.
[ "Look at transform() with method set to QUAD\nhttps://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.transform\n\nim.transform(size, QUAD, data) => image\nim.transform(size, QUAD, data, filter) => image\n\nMaps a quadrilateral (a region defined by four corners) from the image to a rectangle with the given size.\nData is an 8-tuple (x0, y0, x1, y1, x2, y2, y3, y3) which contain the upper left, lower left, lower right, and upper right corner of the source quadrilateral.\n\n" ]
[ 8 ]
[]
[]
[ "image_processing", "image_scanner", "python", "python_imaging_library" ]
stackoverflow_0000662638_image_processing_image_scanner_python_python_imaging_library.txt
Q: Help with subprocess.call on a Windows machine I am trying to modify a trac plugin that allows downloading of wiki pages to word documents. pagetodoc.py throws an exception on this line: # Call the subprocess using convenience method retval = subprocess.call(command, shell=True, stderr=errptr, stdout=outptr, close_fds = True) Saying that close_fds is not supported on Windows. The process seems to create some temporary files in C:\Windows\Temp. I tried removing the close_fds parameter, but then files the subprocess writes to stay open indefinitely. An exception is then thrown when the files are written to later. This is my first time working with Python, and I am not familiar with the libraries. It is even more difficult since most people probably code on Unix machines. Any ideas how I can rework this code? Thanks! A: close_fds is supported on Windows (search for "close_fds" after that link) starting with Python 2.6 (if stdin/stdout/stderr are not redirected). You might consider upgrading. From the linked doc: Note that on Windows, you cannot set close_fds to true and also redirect the standard handles by setting stdin, stdout or stderr. So you can either subprocess.call with close_fds = True and not setting stdin, stdout or stderr (the default) (or setting them to None): subprocess.call(command, shell=True, close_fds = True) or you subprocess.call with close_fds = False: subprocess.call(command, shell=True, stderr=errptr, stdout=outptr, close_fds = False) or (Python >= 3.2) you let subprocess.call figure out the value of close_fds by itself: subprocess.call(command, shell=True, stderr=errptr, stdout=outptr)
Help with subprocess.call on a Windows machine
I am trying to modify a trac plugin that allows downloading of wiki pages to word documents. pagetodoc.py throws an exception on this line: # Call the subprocess using convenience method retval = subprocess.call(command, shell=True, stderr=errptr, stdout=outptr, close_fds = True) Saying that close_fds is not supported on Windows. The process seems to create some temporary files in C:\Windows\Temp. I tried removing the close_fds parameter, but then files the subprocess writes to stay open indefinitely. An exception is then thrown when the files are written to later. This is my first time working with Python, and I am not familiar with the libraries. It is even more difficult since most people probably code on Unix machines. Any ideas how I can rework this code? Thanks!
[ "close_fds is supported on Windows (search for \"close_fds\" after that link) starting with Python 2.6 (if stdin/stdout/stderr are not redirected). You might consider upgrading.\nFrom the linked doc:\n\nNote that on Windows, you cannot set close_fds to true and also\nredirect the standard handles by setting stdin, stdout or stderr.\n\nSo you can either subprocess.call with close_fds = True and not setting stdin, stdout or stderr (the default) (or setting them to None):\n\nsubprocess.call(command, shell=True, close_fds = True)\n\nor you subprocess.call with close_fds = False:\n\nsubprocess.call(command, shell=True, stderr=errptr, stdout=outptr, close_fds = False)\n\nor (Python >= 3.2) you let subprocess.call figure out the value of close_fds by itself:\n\nsubprocess.call(command, shell=True, stderr=errptr, stdout=outptr)\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_2.4", "trac" ]
stackoverflow_0000662641_python_python_2.4_trac.txt
Q: HTML Entity Codes to Text Does anyone know an easy way in Python to convert a string with HTML entity codes (e.g. &lt; &amp;) to a normal string (e.g. < &)? cgi.escape() will escape strings (poorly), but there is no unescape(). A: HTMLParser has the functionality in the standard library. It is, unfortunately, undocumented: (Python2 Docs) >>> import HTMLParser >>> h= HTMLParser.HTMLParser() >>> h.unescape('alpha &lt; &beta;') u'alpha < \u03b2' (Python 3 Docs) >>> import html.parser >>> h = html.parser.HTMLParser() >>> h.unescape('alpha &lt; &beta;') 'alpha < \u03b2' htmlentitydefs is documented, but requires you to do a lot of the work yourself. If you only need the XML predefined entities (lt, gt, amp, quot, apos), you could use minidom to parse them. If you only need the predefined entities and no numeric character references, you could even just use a plain old string replace for speed. A: I forgot to tag it at first, but I'm using BeautifulSoup. Digging around in the documentation, I found: soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES) does it exactly as I was hoping. A: There is nothing built into the Python stdlib to unescape HTML, but there's a short script you can tailor to your needs at http://www.w3.org/QA/2008/04/unescape-html-entities-python.html. A: Use htmlentitydefs module. This my old code, it worked, but I'm sure there is cleaner and more pythonic way to do it: e2c = dict(('&%s;'%k,eval("u'\\u%04x'"%v)) for k, v in htmlentitydefs.name2codepoint.items())
HTML Entity Codes to Text
Does anyone know an easy way in Python to convert a string with HTML entity codes (e.g. &lt; &amp;) to a normal string (e.g. < &)? cgi.escape() will escape strings (poorly), but there is no unescape().
[ "HTMLParser has the functionality in the standard library. It is, unfortunately, undocumented:\n(Python2 Docs)\n>>> import HTMLParser\n>>> h= HTMLParser.HTMLParser()\n>>> h.unescape('alpha &lt; &beta;')\nu'alpha < \\u03b2'\n\n(Python 3 Docs)\n>>> import html.parser\n>>> h = html.parser.HTMLParser()\n>>> h.unescape('alpha &lt; &beta;')\n'alpha < \\u03b2'\n\nhtmlentitydefs is documented, but requires you to do a lot of the work yourself.\nIf you only need the XML predefined entities (lt, gt, amp, quot, apos), you could use minidom to parse them. If you only need the predefined entities and no numeric character references, you could even just use a plain old string replace for speed.\n", "I forgot to tag it at first, but I'm using BeautifulSoup.\nDigging around in the documentation, I found:\nsoup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES)\n\ndoes it exactly as I was hoping.\n", "There is nothing built into the Python stdlib to unescape HTML, but there's a short script you can tailor to your needs at http://www.w3.org/QA/2008/04/unescape-html-entities-python.html.\n", "Use htmlentitydefs module. This my old code, it worked, but I'm sure there is cleaner and more pythonic way to do it: \ne2c = dict(('&%s;'%k,eval(\"u'\\\\u%04x'\"%v)) for k, v in htmlentitydefs.name2codepoint.items())\n\n" ]
[ 45, 12, 1, 1 ]
[]
[]
[ "beautifulsoup", "html", "python" ]
stackoverflow_0000663058_beautifulsoup_html_python.txt
Q: Can I write Python web application for Windows and Linux platforms at the same time? Can I write web application that I can host on Windows(IIS web server) and Linux (Apache or lighttpd) without any changes? CGI? Maybe something new? WSGI | FastCGI ? A: Yes you can. But you can also use apache on windows. If you go the IIS way there's only CGI and it's pretty hard to set up. You can also use python based server like CherryPy which is pretty good and will work on all platforms with python. Some frameworks like django support both CGI and WSGI, so you don't have to worry about the details of WSGI or CGI much. If you ask me, WSGI is the future for python web apps. A: web.py includes a server... It will do the trick for small jobs. By the way, Apache works on windows. A: Yes, if you use CGI, FastCGI or depending on your framework, even a self-contained web server (so IIS and Apache would be a reverse-proxy) then that would all work. The difference will be the configuration of the OS-specific servers, and also your Python environment on each OS. So you may find yourself doing a small bit of work at the beginning to make sure your paths are right, etc. A: A rather big Python based web framework is ZOPE. Zope is an open source application server for building content management systems, intranets, portals, and custom applications. The Zope community consists of hundreds of companies and thousands of developers all over the world, working on building the platform and Zope applications. Zope is written in Python, a highly-productive, object-oriented scripting language ZOPE is available on Linux and Windows, and you can use Python to write your Zope Web Apps (it includes a simpler templating system, too). A: consider also the possibility of using web2Py, or XML-RPC implementation, or Twisted... A: Writing python web apps is a topic on itself, but I would say that by default, it will be portable on multiple servers / platforms. When developping python web applications, you will often use frameworks that provide their own web server. For performance reasons, you might want to place it behind apache, but it is not even necessary, however, you might get a performance boost by placing it behind an apache server. Some of the most popular frameworks for web python are : Plone, Zope, CherryPy and TurboGears, only to name a few. Under apache, you could also use python server pages through mod_python, and since apache runs on windows too, this would aslo be portable.
Can I write Python web application for Windows and Linux platforms at the same time?
Can I write web application that I can host on Windows(IIS web server) and Linux (Apache or lighttpd) without any changes? CGI? Maybe something new? WSGI | FastCGI ?
[ "Yes you can. But you can also use apache on windows. If you go the IIS way there's only CGI and it's pretty hard to set up. You can also use python based server like CherryPy which is pretty good and will work on all platforms with python.\nSome frameworks like django support both CGI and WSGI, so you don't have to worry about the details of WSGI or CGI much.\nIf you ask me, WSGI is the future for python web apps.\n", "web.py includes a server... It will do the trick for small jobs.\nBy the way, Apache works on windows.\n", "Yes, if you use CGI, FastCGI or depending on your framework, even a self-contained web server (so IIS and Apache would be a reverse-proxy) then that would all work.\nThe difference will be the configuration of the OS-specific servers, and also your Python environment on each OS. So you may find yourself doing a small bit of work at the beginning to make sure your paths are right, etc.\n", "A rather big Python based web framework is ZOPE.\n\nZope is an open source application server for building content management systems, intranets, portals, and custom applications. The Zope community consists of hundreds of companies and thousands of developers all over the world, working on building the platform and Zope applications. Zope is written in Python, a highly-productive, object-oriented scripting language\n\nZOPE is available on Linux and Windows, and you can use Python to write your Zope Web Apps (it includes a simpler templating system, too).\n", "consider also the possibility of using web2Py, or XML-RPC implementation, or Twisted...\n", "Writing python web apps is a topic on itself, but I would say that by default, it will be portable on multiple servers / platforms. \nWhen developping python web applications, you will often use frameworks that provide their own web server. For performance reasons, you might want to place it behind apache, but it is not even necessary, however, you might get a performance boost by placing it behind an apache server.\nSome of the most popular frameworks for web python are : Plone, Zope, CherryPy and TurboGears, only to name a few.\nUnder apache, you could also use python server pages through mod_python, and since apache runs on windows too, this would aslo be portable.\n" ]
[ 7, 2, 2, 2, 0, 0 ]
[]
[]
[ "cgi", "fastcgi", "python", "wsgi" ]
stackoverflow_0000662762_cgi_fastcgi_python_wsgi.txt
Q: write a table with empty cells based on dictionary of values I have this view in my app: def context_detail(request, context_id): c = get_object_or_404(Context, pk=context_id) scs = SherdCount.objects.filter(assemblage__context=c).exclude(count__isnull=True) total = sum(sc.count for sc in scs) table = [] forms = [] for a in c.assemblage_set.all(): for sc in a.sherdcount_set.all(): forms.append(sc.typename) forms_set = set(forms) for a in c.assemblage_set.all(): diko = {} diko['assemblage'] = a for f in forms_set: for sc in a.sherdcount_set.all(): if f == sc.typename: diko[f] = sc.count else: diko[f] = 0 table.append(diko) return render_to_response('tesi/context_detail.html', {'context': c, 'total': total, 'sherdcounts': scs, 'table': table, 'forms': forms_set}, context_instance=RequestContext(request)) The aim of the two for loops would be that of creating a list of dictionaries that holds values of SherdCount.count with reference to the SherdCount.typename foreign key (and I was able to do that, even if the current code is a bit messed up). The "table" list should contain something like this: [{<Type: Hayes 61B>: 0, <Type: Hayes 99A-B>: 0, <Type: Hayes 105>: 0, <Type: Hayes 104A>: 0, <Type: Hayes 104B>: 0, <Type: Hayes 103>: 0, <Type: Hayes 91>: 0, <Type: Hayes 91A>: 0, <Type: Hayes 91B>: 0, <Type: Hayes 91C>: 0, <Type: Hayes 91D>: 0, <Type: Hayes 85B>: 0, <Type: Hayes 82A>: 0, <Type: Hayes 76>: 0, <Type: Hayes 73>: 0, <Type: Hayes 72>: 0, <Type: Hayes 70>: 0, <Type: Hayes 68>: 0, <Type: Hayes 67>: 0, <Type: Hayes 66>: 0, <Type: Hayes 62A>: 0, <Type: Hayes 80B>: 0, <Type: Hayes 59>: 0, <Type: Hayes 61A>: 0, <Type: Hayes 91A-B>: 0, <Type: Hayes 58>: 0, <Type: Hayes 50>: 0, <Type: Hayes 53>: 0, <Type: Hayes 71>: 0, <Type: Hayes 60>: 0, <Type: Hayes 80A>: 0, <Type: Hayes Style A2-3>: 0, <Type: Hayes Style B>: 0, <Type: Hayes Style E1>: 1, 'assemblage': <Assemblage: Brescia, Santa Giulia : non periodizzato>}, {<Type: Hayes 61B>: 0, <Type: Hayes 99A-B>: 0, <Type: Hayes 105>: 0, <Type: Hayes 104A>: 0, <Type: Hayes 104B>: 0, <Type: Hayes 103>: 0, <Type: Hayes 91>: 0, <Type: Hayes 91A>: 0, <Type: Hayes 91B>: 0, <Type: Hayes 91C>: 0, <Type: Hayes 91D>: 0, <Type: Hayes 85B>: 0, <Type: Hayes 82A>: 0, <Type: Hayes 76>: 0, <Type: Hayes 73>: 0, <Type: Hayes 72>: 0, <Type: Hayes 70>: 0, <Type: Hayes 68>: 0, <Type: Hayes 67>: 0, <Type: Hayes 66>: 0, <Type: Hayes 62A>: 0, <Type: Hayes 80B>: 0, <Type: Hayes 59>: 0, <Type: Hayes 61A>: 0, <Type: Hayes 91A-B>: 0, <Type: Hayes 58>: 0, <Type: Hayes 50>: 0, <Type: Hayes 53>: 0, <Type: Hayes 71>: 0, <Type: Hayes 60>: 0, <Type: Hayes 80A>: 0, <Type: Hayes Style A2-3>: 0, <Type: Hayes Style B>: 3, <Type: Hayes Style E1>: 0, 'assemblage': <Assemblage: Brescia, Santa Giulia : Periodo IIIA>}, But the many 0 values are obviously wrong. even though there might be some zeros (the empty cells I was referring to) The question is, once I have built such a list, how do I create a table in the template with all the cells (e.g. 1 row per Type and 1 column per Context, with SherdCount at cells) ? Steko A: Here's the data structure. [{<Type1>: 16, <Type2>: 10, <Type3>: 12, <Type4>: 7, <Type5>: 0, 'assemblage': <Assemblage1>}, {<Type1>: 85, <Type2>: 18, <Type3>: 21, <Type4>: 12, <Type5>: 2, 'assemblage': <Assemblage2>}, ...] The problem is that the resulting table must be generated in row order, and this list of dictionaries is in column order. So the list of dicts must be pivoted into row-major order. from collections import defaultdict titles = [] cells = defaultdict(list) for x,col in enumerate(table): titles.append( col['assemblage'] ) for rk in col: if rk == 'assemblage': continue # skip the title cells[rk][x]= col[rk] Also, it helps to formalize the results as a list of lists; dictionaries have no inherent order. final= [] for name in sorted( cells.keys() ): final.append( cells[name] ) Here's the template to render titles and final as a table. <table> <tr> {% for t in titles %}<th>{{t}}</th>{% endfor %} </tr> {% for row in final %} <tr> {% for cell in row %}<td>{{cell}}</td>{% endfor %} </tr> {% endfor %} </table>
write a table with empty cells based on dictionary of values
I have this view in my app: def context_detail(request, context_id): c = get_object_or_404(Context, pk=context_id) scs = SherdCount.objects.filter(assemblage__context=c).exclude(count__isnull=True) total = sum(sc.count for sc in scs) table = [] forms = [] for a in c.assemblage_set.all(): for sc in a.sherdcount_set.all(): forms.append(sc.typename) forms_set = set(forms) for a in c.assemblage_set.all(): diko = {} diko['assemblage'] = a for f in forms_set: for sc in a.sherdcount_set.all(): if f == sc.typename: diko[f] = sc.count else: diko[f] = 0 table.append(diko) return render_to_response('tesi/context_detail.html', {'context': c, 'total': total, 'sherdcounts': scs, 'table': table, 'forms': forms_set}, context_instance=RequestContext(request)) The aim of the two for loops would be that of creating a list of dictionaries that holds values of SherdCount.count with reference to the SherdCount.typename foreign key (and I was able to do that, even if the current code is a bit messed up). The "table" list should contain something like this: [{<Type: Hayes 61B>: 0, <Type: Hayes 99A-B>: 0, <Type: Hayes 105>: 0, <Type: Hayes 104A>: 0, <Type: Hayes 104B>: 0, <Type: Hayes 103>: 0, <Type: Hayes 91>: 0, <Type: Hayes 91A>: 0, <Type: Hayes 91B>: 0, <Type: Hayes 91C>: 0, <Type: Hayes 91D>: 0, <Type: Hayes 85B>: 0, <Type: Hayes 82A>: 0, <Type: Hayes 76>: 0, <Type: Hayes 73>: 0, <Type: Hayes 72>: 0, <Type: Hayes 70>: 0, <Type: Hayes 68>: 0, <Type: Hayes 67>: 0, <Type: Hayes 66>: 0, <Type: Hayes 62A>: 0, <Type: Hayes 80B>: 0, <Type: Hayes 59>: 0, <Type: Hayes 61A>: 0, <Type: Hayes 91A-B>: 0, <Type: Hayes 58>: 0, <Type: Hayes 50>: 0, <Type: Hayes 53>: 0, <Type: Hayes 71>: 0, <Type: Hayes 60>: 0, <Type: Hayes 80A>: 0, <Type: Hayes Style A2-3>: 0, <Type: Hayes Style B>: 0, <Type: Hayes Style E1>: 1, 'assemblage': <Assemblage: Brescia, Santa Giulia : non periodizzato>}, {<Type: Hayes 61B>: 0, <Type: Hayes 99A-B>: 0, <Type: Hayes 105>: 0, <Type: Hayes 104A>: 0, <Type: Hayes 104B>: 0, <Type: Hayes 103>: 0, <Type: Hayes 91>: 0, <Type: Hayes 91A>: 0, <Type: Hayes 91B>: 0, <Type: Hayes 91C>: 0, <Type: Hayes 91D>: 0, <Type: Hayes 85B>: 0, <Type: Hayes 82A>: 0, <Type: Hayes 76>: 0, <Type: Hayes 73>: 0, <Type: Hayes 72>: 0, <Type: Hayes 70>: 0, <Type: Hayes 68>: 0, <Type: Hayes 67>: 0, <Type: Hayes 66>: 0, <Type: Hayes 62A>: 0, <Type: Hayes 80B>: 0, <Type: Hayes 59>: 0, <Type: Hayes 61A>: 0, <Type: Hayes 91A-B>: 0, <Type: Hayes 58>: 0, <Type: Hayes 50>: 0, <Type: Hayes 53>: 0, <Type: Hayes 71>: 0, <Type: Hayes 60>: 0, <Type: Hayes 80A>: 0, <Type: Hayes Style A2-3>: 0, <Type: Hayes Style B>: 3, <Type: Hayes Style E1>: 0, 'assemblage': <Assemblage: Brescia, Santa Giulia : Periodo IIIA>}, But the many 0 values are obviously wrong. even though there might be some zeros (the empty cells I was referring to) The question is, once I have built such a list, how do I create a table in the template with all the cells (e.g. 1 row per Type and 1 column per Context, with SherdCount at cells) ? Steko
[ "Here's the data structure.\n[{<Type1>: 16,\n <Type2>: 10,\n <Type3>: 12,\n <Type4>: 7,\n <Type5>: 0,\n 'assemblage': <Assemblage1>},\n {<Type1>: 85,\n <Type2>: 18,\n <Type3>: 21,\n <Type4>: 12,\n <Type5>: 2,\n 'assemblage': <Assemblage2>},\n ...]\n\nThe problem is that the resulting table must be generated in row order, and this list of dictionaries is in column order. So the list of dicts must be pivoted into row-major order.\nfrom collections import defaultdict\ntitles = []\ncells = defaultdict(list)\nfor x,col in enumerate(table):\n titles.append( col['assemblage'] )\n for rk in col:\n if rk == 'assemblage': continue # skip the title\n cells[rk][x]= col[rk]\n\nAlso, it helps to formalize the results as a list of lists; dictionaries have no inherent order.\nfinal= []\nfor name in sorted( cells.keys() ):\n final.append( cells[name] )\n\nHere's the template to render titles and final as a table.\n<table>\n <tr>\n {% for t in titles %}<th>{{t}}</th>{% endfor %}\n </tr>\n {% for row in final %}\n <tr>\n {% for cell in row %}<td>{{cell}}</td>{% endfor %}\n </tr>\n {% endfor %}\n</table>\n\n" ]
[ 2 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0000662463_django_django_templates_python.txt
Q: Using PyQT, how do you filter mousePressEvent for a QComboBox with custom list I've got a QComboBox with a custom list object. The custom list object has a custom mousePressEvent so that when the user click on one of the circles with a +/- (a twisty), the list is expanded/collapsed. When I use the list with the combo box, when the user clicks on a twisty, the list is expanded/collapsed, but the selection is changed, and the list is hidden. How can I filter this so that when the user click on a twisty, the selection is not changed, and the list not hidden. Additional screenshots All of the nodes collapsed: List hidden: A: QT has a eventFilter that "captures" QEvent.MouseButtonRelease. So what I have done is installed my own eventFilter that filters QEvent.MouseButtonRelease events if the user click on a node. In my list object I have the following method: def mousePressEvent (self, e): self.colapse_expand_click = False if <user clicked node>: colapse_expand_node() e.accept () self.colapse_expand_click = True The mousePressEvent runs before mouseReleaseEvent. Then in the custom combobox, I filter the event: class RevisionSelectorWidget(QtGui.QComboBox): def __init__(self, parent = None): QtGui.QComboBox.__init__(self, parent) self.log_list = RevisionSelectorLogList(self) self.setView(self.log_list) self.log_list.installEventFilter(self) self.log_list.viewport().installEventFilter(self) def eventFilter(self, object, event): if event.type() == QtCore.QEvent.MouseButtonRelease: if self.log_list.colapse_expand_click: return True return False A: Off the top of my head, you could subclass QComboBox and override hideEvent(QHideEvent) (inherited from QWidget) def hideEvent(self, event): if self.OkToHide(): event.accept() else: event.ignore() Your screenshot looks like an interesting use of a combo box, I'm curious as to why you haven't used a TreeView style control instead of a list? Edit (Mar 14 2009): I looked at the Qt source code and it looks like when the keyboard and mouse events are captured, that as soon as qt has decided to emit the "activated(int index)" signal, "hidePopup()" has been called. So apart from rewriting their event filter code, another option is to connect the "activated(int index)" or "highlighted(int index)" signal to a slot that can call "showPopup()" which would re-raise the list items. If you get a nasty disappear/appear paint issue you may have to get Qt to delay the paint events while the popup is visible. Hope that helps!
Using PyQT, how do you filter mousePressEvent for a QComboBox with custom list
I've got a QComboBox with a custom list object. The custom list object has a custom mousePressEvent so that when the user click on one of the circles with a +/- (a twisty), the list is expanded/collapsed. When I use the list with the combo box, when the user clicks on a twisty, the list is expanded/collapsed, but the selection is changed, and the list is hidden. How can I filter this so that when the user click on a twisty, the selection is not changed, and the list not hidden. Additional screenshots All of the nodes collapsed: List hidden:
[ "QT has a eventFilter that \"captures\" QEvent.MouseButtonRelease. So what I have done is installed my own eventFilter that filters QEvent.MouseButtonRelease events if the user click on a node. \nIn my list object I have the following method:\ndef mousePressEvent (self, e):\n self.colapse_expand_click = False\n if <user clicked node>:\n colapse_expand_node()\n e.accept ()\n self.colapse_expand_click = True\n\nThe mousePressEvent runs before mouseReleaseEvent.\nThen in the custom combobox, I filter the event:\nclass RevisionSelectorWidget(QtGui.QComboBox):\n def __init__(self, parent = None):\n QtGui.QComboBox.__init__(self, parent)\n\n self.log_list = RevisionSelectorLogList(self)\n self.setView(self.log_list)\n self.log_list.installEventFilter(self)\n self.log_list.viewport().installEventFilter(self)\n\n def eventFilter(self, object, event):\n if event.type() == QtCore.QEvent.MouseButtonRelease:\n if self.log_list.colapse_expand_click:\n return True\n return False\n\n", "Off the top of my head, you could subclass QComboBox and override hideEvent(QHideEvent) (inherited from QWidget)\ndef hideEvent(self, event):\n if self.OkToHide():\n event.accept()\n else:\n event.ignore()\n\nYour screenshot looks like an interesting use of a combo box, I'm curious as to why you haven't used a TreeView style control instead of a list?\nEdit (Mar 14 2009):\nI looked at the Qt source code and it looks like when the keyboard and mouse events are captured, that as soon as qt has decided to emit the \"activated(int index)\" signal, \"hidePopup()\" has been called. \nSo apart from rewriting their event filter code, another option is to connect the \"activated(int index)\" or \"highlighted(int index)\" signal to a slot that can call \"showPopup()\" which would re-raise the list items. If you get a nasty disappear/appear paint issue you may have to get Qt to delay the paint events while the popup is visible.\nHope that helps!\n" ]
[ 2, 1 ]
[]
[]
[ "pyqt", "python", "qcombobox", "qt", "qt4" ]
stackoverflow_0000603528_pyqt_python_qcombobox_qt_qt4.txt
Q: Using norwegian letters æøå in python I'm learning python and PyGTK now, and have created a simple Music Organizer. http://pastebin.com/m2b596852 But when it edits songs with the Norwegian letters æ, ø, and å it's just changing them to a weird character. So is there any good way of opening or encode the names into utf-8 characters? Two relevant places from the above code: Read info from a file: def __parse(self, filename): "parse ID3v1.0 tags from MP3 file" self.clear() self['artist'] = 'Unknown' self['title'] = 'Unknown' try: fsock = open(filename, "rb", 0) try: fsock.seek(-128, 2) tagdata = fsock.read(128) finally: fsock.close() if tagdata[:3] == 'TAG': for tag, (start, end, parseFunc) in self.tagDataMap.items(): self[tag] = parseFunc(tagdata[start:end]) except IOError: pass Print to sys.stdout info: for info in files: try: os.rename(info['name'], os.path.join(self.dir, info['artist'])+' - '+info['title']+'.mp3') print 'From: '+ info['name'].replace(os.path.join(self.dir, ''), '') print 'To: '+ info['artist'] +' - '+info['title']+'.mp3' print self.progressbar.set_fraction(i/num) self.progressbar.set_text('File %d of %d' % (i, num)) i += 1 except IOError: print 'Rename fail' A: You want to start by decoding the input FROM the charset it is in TO utf-8 (in Python, encode means "take it from unicode/utf-8 to some other charset"). Some googling suggests the Norwegian charset is plain-ole 'iso-8859-1'... I hope someone can correct me if I'm wrong on this detail. Regardless, whatever the name of the charset in the following example: tagdata[start:end].decode('iso-8859-1') In a real-world app, I realize you can't guarantee that the input is norwegian, or any other charset. In this case, you will probably want to proceed through a series of likely charsets to see which you can convert successfully. Both SO and Google have some suggestions on algorithms for doing this effectively in Python. It sounds scarier than it really is. A: You'd need to convert the bytestrings you read from the file into Unicode character strings. Looking at your code, I would do this in the parsing function, i.e. replace stripnulls with something like this def stripnulls_and_decode(data): return codecs.utf_8_decode(data.replace("\00", "")).strip() Note that this will only work if the strings in the file are in fact encoded in UTF-8 - if they're in a different encoding, you'd have to use the corresponding decoding function from the codecs module. A: I don't know what encodings are used for mp3 tags but if you are sure that it is UTF-8 then: tagdata[start:end].decode("utf-8") The line # -*- coding: utf-8 -*- defines your source code encoding and doesn't define encoding used to read from or write to files.
Using norwegian letters æøå in python
I'm learning python and PyGTK now, and have created a simple Music Organizer. http://pastebin.com/m2b596852 But when it edits songs with the Norwegian letters æ, ø, and å it's just changing them to a weird character. So is there any good way of opening or encode the names into utf-8 characters? Two relevant places from the above code: Read info from a file: def __parse(self, filename): "parse ID3v1.0 tags from MP3 file" self.clear() self['artist'] = 'Unknown' self['title'] = 'Unknown' try: fsock = open(filename, "rb", 0) try: fsock.seek(-128, 2) tagdata = fsock.read(128) finally: fsock.close() if tagdata[:3] == 'TAG': for tag, (start, end, parseFunc) in self.tagDataMap.items(): self[tag] = parseFunc(tagdata[start:end]) except IOError: pass Print to sys.stdout info: for info in files: try: os.rename(info['name'], os.path.join(self.dir, info['artist'])+' - '+info['title']+'.mp3') print 'From: '+ info['name'].replace(os.path.join(self.dir, ''), '') print 'To: '+ info['artist'] +' - '+info['title']+'.mp3' print self.progressbar.set_fraction(i/num) self.progressbar.set_text('File %d of %d' % (i, num)) i += 1 except IOError: print 'Rename fail'
[ "You want to start by decoding the input FROM the charset it is in TO utf-8 (in Python, encode means \"take it from unicode/utf-8 to some other charset\"). \nSome googling suggests the Norwegian charset is plain-ole 'iso-8859-1'... I hope someone can correct me if I'm wrong on this detail. Regardless, whatever the name of the charset in the following example:\ntagdata[start:end].decode('iso-8859-1')\n\nIn a real-world app, I realize you can't guarantee that the input is norwegian, or any other charset. In this case, you will probably want to proceed through a series of likely charsets to see which you can convert successfully. Both SO and Google have some suggestions on algorithms for doing this effectively in Python. It sounds scarier than it really is.\n", "You'd need to convert the bytestrings you read from the file into Unicode character strings. Looking at your code, I would do this in the parsing function, i.e. replace stripnulls with something like this\ndef stripnulls_and_decode(data):\n return codecs.utf_8_decode(data.replace(\"\\00\", \"\")).strip()\n\nNote that this will only work if the strings in the file are in fact encoded in UTF-8 - if they're in a different encoding, you'd have to use the corresponding decoding function from the codecs module.\n", "I don't know what encodings are used for mp3 tags but if you are sure that it is UTF-8 then:\n tagdata[start:end].decode(\"utf-8\")\n\nThe line # -*- coding: utf-8 -*- defines your source code encoding and doesn't define encoding used to read from or write to files.\n" ]
[ 8, 1, 1 ]
[]
[]
[ "python", "utf_8" ]
stackoverflow_0000664372_python_utf_8.txt
Q: How do I format positional argument help using Python's optparse? As mentioned in the docs the optparse.OptionParser uses an IndentedHelpFormatter to output the formatted option help, for which which I found some API documentation. I want to display a similarly formatted help text for the required, positional arguments in the usage text. Is there an adapter or a simple usage pattern that can be used for similar positional argument formatting? Clarification Preferably only using the stdlib. Optparse does great except for this one formatting nuance, which I feel like we should be able to fix without importing whole other packages. :-) A: The best bet would be to write a patch to the optparse module. In the meantime, you can accomplish this with a slightly modified OptionParser class. This isn't perfect, but it'll get what you want done. #!/usr/bin/env python from optparse import OptionParser, Option, IndentedHelpFormatter class PosOptionParser(OptionParser): def format_help(self, formatter=None): class Positional(object): def __init__(self, args): self.option_groups = [] self.option_list = args positional = Positional(self.positional) formatter = IndentedHelpFormatter() formatter.store_option_strings(positional) output = ['\n', formatter.format_heading("Positional Arguments")] formatter.indent() pos_help = [formatter.format_option(opt) for opt in self.positional] pos_help = [line.replace('--','') for line in pos_help] output += pos_help return OptionParser.format_help(self, formatter) + ''.join(output) def add_positional_argument(self, option): try: args = self.positional except AttributeError: args = [] args.append(option) self.positional = args def set_out(self, out): self.out = out def main(): usage = "usage: %prog [options] bar baz" parser = PosOptionParser(usage) parser.add_option('-f', '--foo', dest='foo', help='Enable foo') parser.add_positional_argument(Option('--bar', action='store_true', help='The bar positional argument')) parser.add_positional_argument(Option('--baz', action='store_true', help='The baz positional argument')) (options, args) = parser.parse_args() if len(args) != 2: parser.error("incorrect number of arguments") pass if __name__ == '__main__': main() And the output you get from running this: Usage: test.py [options] bar baz Options: -h, --help show this help message and exit -f FOO, --foo=FOO Enable foo Positional Arguments: bar The bar positional argument baz The baz positional argument A: Try taking a look at argparse. Documentation says it supports position arguments and nicer looking help messages. A: I'd be interested in a clean solution to this; I wasn't able to come up with one. The OptionParser really focuses entirely on the options; it doesn't give you anything to work with position args, as far as I've been able to find. What I did was to generate a list of little documentation blocks for each of my positional arguments, using \ts to get the right spacing. Then I joined them with newlines, and appended that to the 'usage' string that gets passed to the OptionParser. It looks fine, but it feels silly, and of course that documentation ends up appearing above the list of options. I haven't found any way around that, or how to do any complex stuff, i.e. a given set of options is described beneath the description for a positional arg, because they only apply to that arg. I looked at monkey-patching OptionParser's methods and I remember (this was a year or so ago) that it wouldn't have been that difficult, but I didn't want to go down that path. A: Most help text for positional arguments resembles the format frequently used in man pages for *NIX boxes. Take a look at how the 'cp' command is documented. Your help text should resemble that. Otherwise as long as you fill out the "help" argument while using the parser, the documentation should produce itself.
How do I format positional argument help using Python's optparse?
As mentioned in the docs the optparse.OptionParser uses an IndentedHelpFormatter to output the formatted option help, for which which I found some API documentation. I want to display a similarly formatted help text for the required, positional arguments in the usage text. Is there an adapter or a simple usage pattern that can be used for similar positional argument formatting? Clarification Preferably only using the stdlib. Optparse does great except for this one formatting nuance, which I feel like we should be able to fix without importing whole other packages. :-)
[ "The best bet would be to write a patch to the optparse module. In the meantime, you can accomplish this with a slightly modified OptionParser class. This isn't perfect, but it'll get what you want done.\n#!/usr/bin/env python\nfrom optparse import OptionParser, Option, IndentedHelpFormatter\n\nclass PosOptionParser(OptionParser):\n def format_help(self, formatter=None):\n class Positional(object):\n def __init__(self, args):\n self.option_groups = []\n self.option_list = args\n\n positional = Positional(self.positional)\n formatter = IndentedHelpFormatter()\n formatter.store_option_strings(positional)\n output = ['\\n', formatter.format_heading(\"Positional Arguments\")]\n formatter.indent()\n pos_help = [formatter.format_option(opt) for opt in self.positional]\n pos_help = [line.replace('--','') for line in pos_help]\n output += pos_help\n return OptionParser.format_help(self, formatter) + ''.join(output)\n\n def add_positional_argument(self, option):\n try:\n args = self.positional\n except AttributeError:\n args = []\n args.append(option)\n self.positional = args\n\n def set_out(self, out):\n self.out = out\ndef main():\n usage = \"usage: %prog [options] bar baz\"\n parser = PosOptionParser(usage)\n parser.add_option('-f', '--foo', dest='foo',\n help='Enable foo')\n parser.add_positional_argument(Option('--bar', action='store_true',\n help='The bar positional argument'))\n parser.add_positional_argument(Option('--baz', action='store_true',\n help='The baz positional argument'))\n (options, args) = parser.parse_args()\n if len(args) != 2:\n parser.error(\"incorrect number of arguments\")\n pass\n\nif __name__ == '__main__':\n main()\n\nAnd the output you get from running this:\nUsage: test.py [options] bar baz\n\n Options:\n -h, --help show this help message and exit\n -f FOO, --foo=FOO Enable foo\n\nPositional Arguments:\n bar The bar positional argument\n baz The baz positional argument\n\n", "Try taking a look at argparse. Documentation says it supports position arguments and nicer looking help messages.\n", "I'd be interested in a clean solution to this; I wasn't able to come up with one. The OptionParser really focuses entirely on the options; it doesn't give you anything to work with position args, as far as I've been able to find.\nWhat I did was to generate a list of little documentation blocks for each of my positional arguments, using \\ts to get the right spacing. Then I joined them with newlines, and appended that to the 'usage' string that gets passed to the OptionParser.\nIt looks fine, but it feels silly, and of course that documentation ends up appearing above the list of options. I haven't found any way around that, or how to do any complex stuff, i.e. a given set of options is described beneath the description for a positional arg, because they only apply to that arg.\nI looked at monkey-patching OptionParser's methods and I remember (this was a year or so ago) that it wouldn't have been that difficult, but I didn't want to go down that path.\n", "Most help text for positional arguments resembles the format frequently used in man pages for *NIX boxes. Take a look at how the 'cp' command is documented. Your help text should resemble that. \nOtherwise as long as you fill out the \"help\" argument while using the parser, the documentation should produce itself.\n" ]
[ 20, 8, 1, 0 ]
[]
[]
[ "command_line", "command_line_arguments", "formatting", "optparse", "python" ]
stackoverflow_0000642648_command_line_command_line_arguments_formatting_optparse_python.txt
Q: python postgres cursor timestamp issue I am somewhat new to transactional databases and have come across an issue I am trying to understand. I have created a simple demonstration where a database connection is stored inside each of the 5 threads created by cherrypy. I have a method that displays a table of timestamps stored in the database and a button to add a new record of time stamps. the table has 2 fields, one for the datetime.datetime.now() timestamp passed by python and one for the database timestamp set to default NOW(). CREATE TABLE test (given_time timestamp, default_time timestamp DEFAULT NOW()); I have 2 methods that interact with the database. The first will create a new cursor, insert a new given_timestamp, commit the cursor, and return to the index page. The second method will create a new cursor, select the 10 most recent timestamps and return those to the caller. import sys import datetime import psycopg2 import cherrypy def connect(thread_index): # Create a connection and store it in the current thread cherrypy.thread_data.db = psycopg2.connect('dbname=timestamps') # Tell CherryPy to call "connect" for each thread, when it starts up cherrypy.engine.subscribe('start_thread', connect) class Root: @cherrypy.expose def index(self): html = [] html.append("<html><body>") html.append("<table border=1><thead>") html.append("<tr><td>Given Time</td><td>Default Time</td></tr>") html.append("</thead><tbody>") for given, default in self.get_timestamps(): html.append("<tr><td>%s<td>%s" % (given, default)) html.append("</tbody>") html.append("</table>") html.append("<form action='add_timestamp' method='post'>") html.append("<input type='submit' value='Add Timestamp'/>") html.append("</form>") html.append("</body></html>") return "\n".join(html) @cherrypy.expose def add_timestamp(self): c = cherrypy.thread_data.db.cursor() now = datetime.datetime.now() c.execute("insert into test (given_time) values ('%s')" % now) c.connection.commit() c.close() raise cherrypy.HTTPRedirect('/') def get_timestamps(self): c = cherrypy.thread_data.db.cursor() c.execute("select * from test order by given_time desc limit 10") records = c.fetchall() c.close() return records if __name__ == '__main__': cherrypy.config.update({'server.socket_host': '0.0.0.0', 'server.socket_port': 8081, 'server.thread_pool': 5, 'tools.log_headers.on': False, }) cherrypy.quickstart(Root()) I would expect the given_time and default_time timestamps to be only a few microseconds off from each other. However I am getting some strange behavior. If I add timestamps every few seconds, the default_time is not a few microseconds off from the given_time, but is usually a few microseconds off from the previous given_time. Given Time Default Time 2009-03-18 09:31:30.725017 2009-03-18 09:31:25.218871 2009-03-18 09:31:25.198022 2009-03-18 09:31:17.642010 2009-03-18 09:31:17.622439 2009-03-18 09:31:08.266720 2009-03-18 09:31:08.246084 2009-03-18 09:31:01.970120 2009-03-18 09:31:01.950780 2009-03-18 09:30:53.571090 2009-03-18 09:30:53.550952 2009-03-18 09:30:47.260795 2009-03-18 09:30:47.239150 2009-03-18 09:30:41.177318 2009-03-18 09:30:41.151950 2009-03-18 09:30:36.005037 2009-03-18 09:30:35.983541 2009-03-18 09:30:31.666679 2009-03-18 09:30:31.649717 2009-03-18 09:30:28.319693 Yet, if I add a new timestamp about once a minute, both the given_time and default_time are only a few microseconds off as expected. However, after submitting the 6th timestamp (the number of threads + 1) the default_time is a few microseconds off from the first given_time timestamp. Given Time Default Time 2009-03-18 09:38:15.906788 2009-03-18 09:33:58.839075 2009-03-18 09:37:19.520227 2009-03-18 09:37:19.520293 2009-03-18 09:36:04.744987 2009-03-18 09:36:04.745039 2009-03-18 09:35:05.958962 2009-03-18 09:35:05.959053 2009-03-18 09:34:10.961227 2009-03-18 09:34:10.961298 2009-03-18 09:33:58.822138 2009-03-18 09:33:55.423485 Even though I am explicitly closing the cursor after each use, it appears that the previous cursor is still being reused. How is that possible if I am closing the cursor after I'm done with it and creating a new cursor each time? Can someone please explain what is going on here? Closer to an answer: I've added a cursor.connection.commit() to the get_timestamps method and that now gives me accurate data with the timestamps. Can anyone explain why I could need to call cursor.connection.commit() when all I am doing is a select? I am guessing that every time I get a cursor, a transaction begins (or continues with an existing transaction unit it gets committed). Is there a better way to do this or am I stuck committing every time I get a cursor regardless of what I do with that cursor? A: Try calling c.close() as described in the module documentation: http://tools.cherrypy.org/wiki/Databases def add_timestamp(self): c = cherrypy.thread_data.db.cursor() now = datetime.datetime.now() c.execute("insert into test (given_time) values ('%s')" % now) c.connection.commit() c.close() raise cherrypy.HTTPRedirect('/') def get_timestamps(self): c = cherrypy.thread_data.db.cursor() c.execute("select * from test order by given_time desc limit 10") records = c.fetchall() c.close() return records A: To address the question posed by your most recent edits: In PostgreSQL, NOW() is not the current time, but the time at the start of the current transaction. Psycopg2 is probably starting a transaction implicitly for you, and since the transaction is never closed (by a commit or otherwise), the timestamp gets 'stuck' and becomes stale. Possible fixes: Commit frequently (silly if you're only doing SELECTs) Set up Psycopg2 to use different behavior for automatically creating transactions (probably tricky to get right, and will affect other parts of your app) Use a different timestamp function, like statement_timestamp() (not SQL-standard-compliant, but otherwise perfect for this scenario) From the manual, section 9.9.4, emphasis added: PostgreSQL provides a number of functions that return values related to the current date and time. These SQL-standard functions all return values based on the start time of the current transaction: CURRENT_DATE CURRENT_TIME CURRENT_TIMESTAMP CURRENT_TIME(precision) CURRENT_TIMESTAMP(precision) LOCALTIME LOCALTIMESTAMP LOCALTIME(precision) LOCALTIMESTAMP(precision) CURRENT_TIME and CURRENT_TIMESTAMP deliver values with time zone; LOCALTIME and LOCALTIMESTAMP deliver values without time zone. CURRENT_TIME, CURRENT_TIMESTAMP, LOCALTIME, and LOCALTIMESTAMP can optionally be given a precision parameter, which causes the result to be rounded to that many fractional digits in the seconds field. Without a precision parameter, the result is given to the full available precision. ... Since these functions return the start time of the current transaction, their values do not change during the transaction. This is considered a feature: the intent is to allow a single transaction to have a consistent notion of the "current" time, so that multiple modifications within the same transaction bear the same time stamp. Note: Other database systems might advance these values more frequently. PostgreSQL also provides functions that return the start time of the current statement, as well as the actual current time at the instant the function is called. The complete list of non-SQL-standard time functions is: now() transaction_timestamp() statement_timestamp() clock_timestamp() timeofday() now() is a traditional PostgreSQL equivalent to CURRENT_TIMESTAMP. transaction_timestamp() is likewise equivalent to CURRENT_TIMESTAMP, but is named to clearly reflect what it returns. statement_timestamp() returns the start time of the current statement (more specifically, the time of receipt of the latest command message from the client). statement_timestamp() and transaction_timestamp() return the same value during the first command of a transaction, but might differ during subsequent commands. clock_timestamp() returns the actual current time, and therefore its value changes even within a single SQL command. timeofday() is a historical PostgreSQL function. Like clock_timestamp(), it returns the actual current time, but as a formatted text string rather than a timestamp with time zone value. A: I have added a commit to the method that selects the timestamps and that has solved the problem. def get_timestamps(self): c = cherrypy.thread_data.db.cursor() c.execute("select * from test order by given_time desc limit 10") records = c.fetchall() c.connection.commit() # Adding this line fixes the timestamp issue c.close() return records Can anyone explain why I would need to call cursor.connection.commit() when all I'm doing is a select?
python postgres cursor timestamp issue
I am somewhat new to transactional databases and have come across an issue I am trying to understand. I have created a simple demonstration where a database connection is stored inside each of the 5 threads created by cherrypy. I have a method that displays a table of timestamps stored in the database and a button to add a new record of time stamps. the table has 2 fields, one for the datetime.datetime.now() timestamp passed by python and one for the database timestamp set to default NOW(). CREATE TABLE test (given_time timestamp, default_time timestamp DEFAULT NOW()); I have 2 methods that interact with the database. The first will create a new cursor, insert a new given_timestamp, commit the cursor, and return to the index page. The second method will create a new cursor, select the 10 most recent timestamps and return those to the caller. import sys import datetime import psycopg2 import cherrypy def connect(thread_index): # Create a connection and store it in the current thread cherrypy.thread_data.db = psycopg2.connect('dbname=timestamps') # Tell CherryPy to call "connect" for each thread, when it starts up cherrypy.engine.subscribe('start_thread', connect) class Root: @cherrypy.expose def index(self): html = [] html.append("<html><body>") html.append("<table border=1><thead>") html.append("<tr><td>Given Time</td><td>Default Time</td></tr>") html.append("</thead><tbody>") for given, default in self.get_timestamps(): html.append("<tr><td>%s<td>%s" % (given, default)) html.append("</tbody>") html.append("</table>") html.append("<form action='add_timestamp' method='post'>") html.append("<input type='submit' value='Add Timestamp'/>") html.append("</form>") html.append("</body></html>") return "\n".join(html) @cherrypy.expose def add_timestamp(self): c = cherrypy.thread_data.db.cursor() now = datetime.datetime.now() c.execute("insert into test (given_time) values ('%s')" % now) c.connection.commit() c.close() raise cherrypy.HTTPRedirect('/') def get_timestamps(self): c = cherrypy.thread_data.db.cursor() c.execute("select * from test order by given_time desc limit 10") records = c.fetchall() c.close() return records if __name__ == '__main__': cherrypy.config.update({'server.socket_host': '0.0.0.0', 'server.socket_port': 8081, 'server.thread_pool': 5, 'tools.log_headers.on': False, }) cherrypy.quickstart(Root()) I would expect the given_time and default_time timestamps to be only a few microseconds off from each other. However I am getting some strange behavior. If I add timestamps every few seconds, the default_time is not a few microseconds off from the given_time, but is usually a few microseconds off from the previous given_time. Given Time Default Time 2009-03-18 09:31:30.725017 2009-03-18 09:31:25.218871 2009-03-18 09:31:25.198022 2009-03-18 09:31:17.642010 2009-03-18 09:31:17.622439 2009-03-18 09:31:08.266720 2009-03-18 09:31:08.246084 2009-03-18 09:31:01.970120 2009-03-18 09:31:01.950780 2009-03-18 09:30:53.571090 2009-03-18 09:30:53.550952 2009-03-18 09:30:47.260795 2009-03-18 09:30:47.239150 2009-03-18 09:30:41.177318 2009-03-18 09:30:41.151950 2009-03-18 09:30:36.005037 2009-03-18 09:30:35.983541 2009-03-18 09:30:31.666679 2009-03-18 09:30:31.649717 2009-03-18 09:30:28.319693 Yet, if I add a new timestamp about once a minute, both the given_time and default_time are only a few microseconds off as expected. However, after submitting the 6th timestamp (the number of threads + 1) the default_time is a few microseconds off from the first given_time timestamp. Given Time Default Time 2009-03-18 09:38:15.906788 2009-03-18 09:33:58.839075 2009-03-18 09:37:19.520227 2009-03-18 09:37:19.520293 2009-03-18 09:36:04.744987 2009-03-18 09:36:04.745039 2009-03-18 09:35:05.958962 2009-03-18 09:35:05.959053 2009-03-18 09:34:10.961227 2009-03-18 09:34:10.961298 2009-03-18 09:33:58.822138 2009-03-18 09:33:55.423485 Even though I am explicitly closing the cursor after each use, it appears that the previous cursor is still being reused. How is that possible if I am closing the cursor after I'm done with it and creating a new cursor each time? Can someone please explain what is going on here? Closer to an answer: I've added a cursor.connection.commit() to the get_timestamps method and that now gives me accurate data with the timestamps. Can anyone explain why I could need to call cursor.connection.commit() when all I am doing is a select? I am guessing that every time I get a cursor, a transaction begins (or continues with an existing transaction unit it gets committed). Is there a better way to do this or am I stuck committing every time I get a cursor regardless of what I do with that cursor?
[ "Try calling c.close() as described in the module documentation: http://tools.cherrypy.org/wiki/Databases\ndef add_timestamp(self):\n c = cherrypy.thread_data.db.cursor()\n now = datetime.datetime.now()\n c.execute(\"insert into test (given_time) values ('%s')\" % now)\n c.connection.commit()\n c.close()\n raise cherrypy.HTTPRedirect('/')\n\ndef get_timestamps(self):\n c = cherrypy.thread_data.db.cursor()\n c.execute(\"select * from test order by given_time desc limit 10\")\n records = c.fetchall()\n c.close()\n return records\n\n", "To address the question posed by your most recent edits:\nIn PostgreSQL, NOW() is not the current time, but the time at the start of the current transaction. Psycopg2 is probably starting a transaction implicitly for you, and since the transaction is never closed (by a commit or otherwise), the timestamp gets 'stuck' and becomes stale.\nPossible fixes:\n\nCommit frequently (silly if you're only doing SELECTs)\nSet up Psycopg2 to use different behavior for automatically creating transactions (probably tricky to get right, and will affect other parts of your app)\nUse a different timestamp function, like statement_timestamp() (not SQL-standard-compliant, but otherwise perfect for this scenario)\n\nFrom the manual, section 9.9.4, emphasis added:\n\nPostgreSQL provides a number of\n functions that return values related\n to the current date and time. These\n SQL-standard functions all return\n values based on the start time of the\n current transaction:\n\nCURRENT_DATE\nCURRENT_TIME\nCURRENT_TIMESTAMP\nCURRENT_TIME(precision)\nCURRENT_TIMESTAMP(precision)\nLOCALTIME LOCALTIMESTAMP\nLOCALTIME(precision)\nLOCALTIMESTAMP(precision)\n\nCURRENT_TIME and CURRENT_TIMESTAMP\n deliver values with time zone;\n LOCALTIME and LOCALTIMESTAMP\n deliver values without time zone. \nCURRENT_TIME, CURRENT_TIMESTAMP,\n LOCALTIME, and LOCALTIMESTAMP can\n optionally be given a precision\n parameter, which causes the result to\n be rounded to that many fractional\n digits in the seconds field. Without a\n precision parameter, the result is\n given to the full available precision.\n...\nSince these functions return the\n start time of the current transaction,\n their values do not change during the\n transaction. This is considered a\n feature: the intent is to allow a\n single transaction to have a\n consistent notion of the \"current\"\n time, so that multiple modifications\n within the same transaction bear the\n same time stamp. \nNote: Other database systems might advance these values more frequently. \nPostgreSQL also provides functions\n that return the start time of the\n current statement, as well as the\n actual current time at the instant the\n function is called. The complete list\n of non-SQL-standard time functions is:\n\nnow()\ntransaction_timestamp()\nstatement_timestamp()\nclock_timestamp()\ntimeofday()\n\nnow() is a traditional PostgreSQL\n equivalent to CURRENT_TIMESTAMP.\n transaction_timestamp() is likewise\n equivalent to CURRENT_TIMESTAMP, but\n is named to clearly reflect what it\n returns. statement_timestamp()\n returns the start time of the current\n statement (more specifically, the time\n of receipt of the latest command\n message from the client).\n statement_timestamp() and\n transaction_timestamp() return the\n same value during the first command of\n a transaction, but might differ during\n subsequent commands.\n clock_timestamp() returns the actual\n current time, and therefore its value\n changes even within a single SQL\n command. timeofday() is a historical\n PostgreSQL function. Like\n clock_timestamp(), it returns the\n actual current time, but as a\n formatted text string rather than a\n timestamp with time zone value.\n\n", "I have added a commit to the method that selects the timestamps and that has solved the problem. \n def get_timestamps(self):\n c = cherrypy.thread_data.db.cursor()\n c.execute(\"select * from test order by given_time desc limit 10\")\n records = c.fetchall()\n c.connection.commit() # Adding this line fixes the timestamp issue\n c.close()\n return records\n\nCan anyone explain why I would need to call cursor.connection.commit() when all I'm doing is a select?\n" ]
[ 3, 2, 0 ]
[]
[]
[ "cherrypy", "postgresql", "python" ]
stackoverflow_0000655125_cherrypy_postgresql_python.txt
Q: Uninitialized value in Python? What's the uninitialized value in Python, so I can compare if something is initialized, like: val if val == undefined ? EDIT: added a pseudo keyword. EDIT2: I think I didn't make it clear, but say val is already there, but nothing is assigned to it. A: Will throw a NameError exception: >>> val Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'val' is not defined You can either catch that or use 'val' in dir(), i.e.: try: val except NameError: print("val not set") or if 'val' in dir(): print('val set') else: print('val not set') A: In python, variables either refer to an object, or they don't exist. If they don't exist, you will get a NameError. Of course, one of the objects they might refer to is None. try: val except NameError: print "val is not set" if val is None: print "val is None" A: A name does not exist unless a value is assigned to it. There is None, which generally represents no usable value, but it is a value in its own right. A: This question leads on to some fun diversions concerning the nature of python objects and it's garbage collector: It's probably helpful to understand that all variables in python are really pointers, that is they are names in a namespace (implemented as a hash-table) whch point to an address in memory where the object actually resides. Asking for the value of an uninitialized variable is the same as asking for the value of the thing a pointer points to when the pointer has not yet been created yet... it's obviously nonsense which is why the most sensible thing Python can do is throw a meaningful NameError. Another oddity of the python language is that it's possible that an object exists long before you execute an assignment statement. Consider: a = 1 Did you magically create an int(1) object here? Nope - it already existed. Since int(1) is an immutable singleton there are already a few hundred pointers to it: >>> sys.getrefcount(a) 592 >>> Fun, eh? EDIT: commment by JFS (posted here to show the code) >>> a = 1 + 1 >>> sys.getrefcount(a) # integers less than 256 (or so) are cached 145 >>> b = 1000 + 1000 >>> sys.getrefcount(b) 2 >>> sys.getrefcount(2000) 3 >>> sys.getrefcount(1000+1000) 2 A: In Python, for a variable to exist, something must have been assigned to it. You can think of your variable name as a dictionary key that must have some value associated with it (even if that value is None). A: Q: How do I discover if a variable is defined at a point in my code? A: Read up in the source file until you see a line where that variable is defined. A: Usually a value of None is used to mark something as "declared but not yet initialized; I would consider an uninitialized variable a defekt in the code A: try: print val except NameError: print "val wasn't set." A: To add to phihag's answer: you can use dir() to get a list of all of the variables in the current scope, so if you want to test if var is in the current scope without using exceptions, you can do: if 'var' in dir(): # var is in scope
Uninitialized value in Python?
What's the uninitialized value in Python, so I can compare if something is initialized, like: val if val == undefined ? EDIT: added a pseudo keyword. EDIT2: I think I didn't make it clear, but say val is already there, but nothing is assigned to it.
[ "Will throw a NameError exception:\n>>> val\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nNameError: name 'val' is not defined\n\nYou can either catch that or use 'val' in dir(), i.e.:\ntry:\n val\nexcept NameError:\n print(\"val not set\")\n\nor\nif 'val' in dir():\n print('val set')\nelse:\n print('val not set')\n\n", "In python, variables either refer to an object, or they don't exist. If they don't exist, you will get a NameError. Of course, one of the objects they might refer to is None.\ntry:\n val\nexcept NameError:\n print \"val is not set\"\n\n\nif val is None:\n print \"val is None\"\n\n", "A name does not exist unless a value is assigned to it. There is None, which generally represents no usable value, but it is a value in its own right.\n", "This question leads on to some fun diversions concerning the nature of python objects and it's garbage collector:\nIt's probably helpful to understand that all variables in python are really pointers, that is they are names in a namespace (implemented as a hash-table) whch point to an address in memory where the object actually resides. \nAsking for the value of an uninitialized variable is the same as asking for the value of the thing a pointer points to when the pointer has not yet been created yet... it's obviously nonsense which is why the most sensible thing Python can do is throw a meaningful NameError.\nAnother oddity of the python language is that it's possible that an object exists long before you execute an assignment statement. Consider:\na = 1\n\nDid you magically create an int(1) object here? Nope - it already existed. Since int(1) is an immutable singleton there are already a few hundred pointers to it:\n>>> sys.getrefcount(a)\n592\n>>>\n\nFun, eh?\nEDIT: commment by JFS (posted here to show the code)\n>>> a = 1 + 1\n>>> sys.getrefcount(a) # integers less than 256 (or so) are cached\n145\n>>> b = 1000 + 1000\n>>> sys.getrefcount(b) \n2\n>>> sys.getrefcount(2000)\n3\n>>> sys.getrefcount(1000+1000)\n2\n\n", "In Python, for a variable to exist, something must have been assigned to it. You can think of your variable name as a dictionary key that must have some value associated with it (even if that value is None).\n", "Q: How do I discover if a variable is defined at a point in my code?\nA: Read up in the source file until you see a line where that variable is defined.\n", "Usually a value of None is used to mark something as \"declared but not yet initialized; I would consider an uninitialized variable a defekt in the code\n", "try:\n print val\nexcept NameError:\n print \"val wasn't set.\"\n\n", "To add to phihag's answer: you can use dir() to get a list of all of the variables in the current scope, so if you want to test if var is in the current scope without using exceptions, you can do:\nif 'var' in dir():\n # var is in scope\n\n" ]
[ 10, 5, 5, 4, 1, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000664219_python.txt
Q: box drawing in python Platform: WinXP SP2, python 2.5.4.3. (activestate distribution) Has anyone succeded in writing out box drawing characters in python? When I try to run this: print u'\u2500' print u'\u2501' print u'\u2502' print u'\u2503' print u'\u2504' All tips appreciated. What am I doing wrong ? Does python support full unicode ? Is it possible at all to get those characters to print. Related Default encoding for python for stderr? A: Your problem is not in Python but in cmd.exe. It has to be set to support UTF-8. Unfortunately, it is not very easy to switch windows console (cmd.exe) to UTF-8 "Python-compatible" way. You can use command (in cmd.exe) to switch to UTF8: chcp 65001 but Python (2.5) does not recognize that encoding. Anyway you have to set correct font that support unicode! For box drawing, I recommend to use old dos codepage 437, so you need to set up it before running python script: chcp 437 Then you can print cp437 encoded chars directly to stdout or decode chars to unicode and print unicode, try this script: # -*- coding: utf-8 -*- for i in range(0xB3, 0xDA): print chr(i).decode('cp437'), # without decoding (see comment by J.F.Sebastian) print ''.join(map(chr, range(0xb3, 0xda))) However, you can use box drawing chars, but you cannot use other chars you may need because of limitation of cp437. A: This varies greatly based on what your terminal supports. If it uses UTF-8, and if Python can detect it, then it works just fine. >>> print u'\u2500' ─ >>> print u'\u2501' ━ >>> print u'\u2502' │ >>> print u'\u2503' ┃ >>> print u'\u2504' ┄ A: Printing them will print in the default character encoding, which perhaps is not the right encoding for your terminal. Have you tried transcoding them to utf-8 first? print u'\u2500'.encode('utf-8') print u'\u2501'.encode('utf-8') print u'\u2502'.encode('utf-8') print u'\u2503'.encode('utf-8') print u'\u2504'.encode('utf-8') This works for me on linux in a terminal that supports utf-8 encoded data. A: Python supports Unicode. It is possible to print these characters. For example, see my answer to "Default encoding for python for stderr?" where I've showed how to print Unicode to sys.stderr (replace it by sys.stdout for bare print statements).
box drawing in python
Platform: WinXP SP2, python 2.5.4.3. (activestate distribution) Has anyone succeded in writing out box drawing characters in python? When I try to run this: print u'\u2500' print u'\u2501' print u'\u2502' print u'\u2503' print u'\u2504' All tips appreciated. What am I doing wrong ? Does python support full unicode ? Is it possible at all to get those characters to print. Related Default encoding for python for stderr?
[ "Your problem is not in Python but in cmd.exe. It has to be set to support UTF-8. Unfortunately, it is not very easy to switch windows console (cmd.exe) to UTF-8 \"Python-compatible\" way.\nYou can use command (in cmd.exe) to switch to UTF8:\nchcp 65001\n\nbut Python (2.5) does not recognize that encoding. Anyway you have to set correct font that support unicode!\nFor box drawing, I recommend to use old dos codepage 437, so you need to set up it before running python script:\nchcp 437\n\nThen you can print cp437 encoded chars directly to stdout or decode chars to unicode and print unicode, try this script:\n# -*- coding: utf-8 -*- \nfor i in range(0xB3, 0xDA):\n print chr(i).decode('cp437'),\n\n# without decoding (see comment by J.F.Sebastian)\nprint ''.join(map(chr, range(0xb3, 0xda)))\n\nHowever, you can use box drawing chars, but you cannot use other chars you may need because of limitation of cp437.\n", "This varies greatly based on what your terminal supports. If it uses UTF-8, and if Python can detect it, then it works just fine.\n>>> print u'\\u2500'\n─\n>>> print u'\\u2501'\n━\n>>> print u'\\u2502'\n│\n>>> print u'\\u2503'\n┃\n>>> print u'\\u2504'\n┄\n\n", "Printing them will print in the default character encoding, which perhaps is not the right encoding for your terminal.\nHave you tried transcoding them to utf-8 first?\nprint u'\\u2500'.encode('utf-8')\nprint u'\\u2501'.encode('utf-8')\nprint u'\\u2502'.encode('utf-8')\nprint u'\\u2503'.encode('utf-8')\nprint u'\\u2504'.encode('utf-8')\n\nThis works for me on linux in a terminal that supports utf-8 encoded data.\n", "Python supports Unicode. It is possible to print these characters. \nFor example, see my answer to \"Default encoding for python for stderr?\" where I've showed how to print Unicode to sys.stderr (replace it by sys.stdout for bare print statements).\n" ]
[ 6, 2, 1, 0 ]
[]
[]
[ "python", "unicode", "windows" ]
stackoverflow_0000664991_python_unicode_windows.txt
Q: How can I improve this "register" view in Django? I've got a Django-based site that allows users to register (but requires an admin to approve the account before they can view certain parts of the site). I'm basing it off of django.contrib.auth. I require users to register with an email address from a certain domain name, so I've overridden the UserCreationForm's save() and clean_email() methods. My registration page uses the following view. I'm interested in hearing about how I might improve this view—code improvements or process improvements (or anything else, really). def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): message = None form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] email = user.email # If valid new user account if (user is not None) and (user.is_active): login(request, user) message = "<strong>Congratulations!</strong> You have been registered." # Send emails try: # Admin email pk = None try: pk = User.objects.filter(username=username)[0].pk except: pass admin_email_template = loader.get_template('accounts/email_notify_admin_of_registration.txt') admin_email_context = Context({ 'first_name': first_name, 'last_name': last_name, 'username': username, 'email': email, 'pk': pk, }) admin_email_body = admin_email_template.render(admin_email_context) mail_admins("New User Registration", admin_email_body) # User email user_email_template = loader.get_template('accounts/email_registration_success.txt') user_email_context = Context({ 'first_name': form.cleaned_data['first_name'], 'username': username, 'password': password, }) user_email_body = user_email_template.render(user_email_context) user.email_user("Successfully Registered at example.com", user_email_body) except: message = "There was an error sending you the confirmation email. You should still be able to login normally." else: message = "There was an error automatically logging you in. Try <a href=\"/login/\">logging in</a> manually." # Display success page return render_to_response('accounts/register_success.html', { 'username': username, 'message': message, }, context_instance=RequestContext(request) ) else: # If not POST form = UserCreationForm() return render_to_response('accounts/register.html', { 'form': form, }, context_instance=RequestContext(request) ) A: You don't even need this code, but I think the style: pk = None try: pk = User.objects.filter(username=username)[0].pk except: pass is more naturally written like: try: user = User.objects.get(username=username) except User.DoesNotExist: user = None and then in your admin notify template use {{ user.id }} instead of {{ pk }}. But, like I said, you don't need that code at all because you already have a user object from your call to authenticate(). Generally in Python, it's considered poor practice to have the exception handler in a try/except block be empty. In other words, always capture a specific exception such as User.DoesNotExist for this case. It's also poor practice to have many lines inside the try part of the try/except block. It is better form to code this way: try: ... a line of code that can generate exceptions to be handled ... except SomeException: ... handle this particular exception ... else: ... the rest of the code to execute if there were no exceptions ... A final, minor, recommendation is to not send the email directly in your view because this won't scale if your site starts to see heavy registration requests. It is better add in the django-mailer app to offload the work into a queue handled by another process. A: I personally try to put the short branch of an if-else statement first. Especially if it returns. This to avoid getting large branches where its difficult to see what ends where. Many others do like you have done and put a comment at the else statement. But python doesnt always have an end of block statement - like if a form isn't valid for you. So for example: def register(request): if request.method != 'POST': form = UserCreationForm() return render_to_response('accounts/register.html', { 'form': form, }, context_instance=RequestContext(request) ) form = UserCreationForm(request.POST) if not form.is_valid(): return render_to_response('accounts/register.html', { 'form': form, }, context_instance=RequestContext(request) ) ... A: First response: It looks a heck of a lot better than 95% of the "improve my code" questions. Is there anything in particular you are dissatisfied with?
How can I improve this "register" view in Django?
I've got a Django-based site that allows users to register (but requires an admin to approve the account before they can view certain parts of the site). I'm basing it off of django.contrib.auth. I require users to register with an email address from a certain domain name, so I've overridden the UserCreationForm's save() and clean_email() methods. My registration page uses the following view. I'm interested in hearing about how I might improve this view—code improvements or process improvements (or anything else, really). def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): message = None form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] email = user.email # If valid new user account if (user is not None) and (user.is_active): login(request, user) message = "<strong>Congratulations!</strong> You have been registered." # Send emails try: # Admin email pk = None try: pk = User.objects.filter(username=username)[0].pk except: pass admin_email_template = loader.get_template('accounts/email_notify_admin_of_registration.txt') admin_email_context = Context({ 'first_name': first_name, 'last_name': last_name, 'username': username, 'email': email, 'pk': pk, }) admin_email_body = admin_email_template.render(admin_email_context) mail_admins("New User Registration", admin_email_body) # User email user_email_template = loader.get_template('accounts/email_registration_success.txt') user_email_context = Context({ 'first_name': form.cleaned_data['first_name'], 'username': username, 'password': password, }) user_email_body = user_email_template.render(user_email_context) user.email_user("Successfully Registered at example.com", user_email_body) except: message = "There was an error sending you the confirmation email. You should still be able to login normally." else: message = "There was an error automatically logging you in. Try <a href=\"/login/\">logging in</a> manually." # Display success page return render_to_response('accounts/register_success.html', { 'username': username, 'message': message, }, context_instance=RequestContext(request) ) else: # If not POST form = UserCreationForm() return render_to_response('accounts/register.html', { 'form': form, }, context_instance=RequestContext(request) )
[ "You don't even need this code, but I think the style:\npk = None\ntry: pk = User.objects.filter(username=username)[0].pk\nexcept: pass\n\nis more naturally written like:\ntry:\n user = User.objects.get(username=username)\nexcept User.DoesNotExist:\n user = None\n\nand then in your admin notify template use {{ user.id }} instead of {{ pk }}.\nBut, like I said, you don't need that code at all because you already have a user object from your call to authenticate().\nGenerally in Python, it's considered poor practice to have the exception handler in a try/except block be empty. In other words, always capture a specific exception such as User.DoesNotExist for this case.\nIt's also poor practice to have many lines inside the try part of the try/except block. It is better form to code this way:\ntry:\n ... a line of code that can generate exceptions to be handled ...\nexcept SomeException:\n ... handle this particular exception ...\nelse:\n ... the rest of the code to execute if there were no exceptions ...\n\nA final, minor, recommendation is to not send the email directly in your view because this won't scale if your site starts to see heavy registration requests. It is better add in the django-mailer app to offload the work into a queue handled by another process.\n", "I personally try to put the short branch of an if-else statement first. Especially if it returns. This to avoid getting large branches where its difficult to see what ends where. Many others do like you have done and put a comment at the else statement. But python doesnt always have an end of block statement - like if a form isn't valid for you. \nSo for example:\ndef register(request):\n if request.method != 'POST':\n form = UserCreationForm()\n return render_to_response('accounts/register.html', \n { 'form': form, },\n context_instance=RequestContext(request)\n )\n\n form = UserCreationForm(request.POST)\n if not form.is_valid():\n return render_to_response('accounts/register.html', \n { 'form': form, },\n context_instance=RequestContext(request)\n )\n ...\n\n", "First response: It looks a heck of a lot better than 95% of the \"improve my code\" questions.\nIs there anything in particular you are dissatisfied with?\n" ]
[ 4, 3, 0 ]
[]
[]
[ "django", "python", "user_registration" ]
stackoverflow_0000664937_django_python_user_registration.txt
Q: Extract array from list in python If I have a list like this: >>> data = [(1,2),(40,2),(9,80)] how can I extract the the two lists [1,40,9] and [2,2,80] ? Of course I can iterate and extract the numbers myself but I guess there is a better way ? A: The unzip operation is: In [1]: data = [(1,2),(40,2),(9,80)] In [2]: zip(*data) Out[2]: [(1, 40, 9), (2, 2, 80)] Edit: You can decompose the resulting list on assignment: In [3]: first_elements, second_elements = zip(*data) And if you really need lists as results: In [4]: first_elements, second_elements = map(list, zip(*data)) To better understand why this works: zip(*data) is equivalent to zip((1,2), (40,2), (9,80)) The two tuples in the result list are built from the first elements of zip()'s arguments and from the second elements of zip()'s arguments. A: List comprehensions save the day: first = [x for (x,y) in data] second = [y for (x,y) in data] A: There is also In [1]: data = [(1,2),(40,2),(9,80)] In [2]: x=map(None, *data) Out[2]: [(1, 40, 9), (2, 2, 80)] In [3]: map(None,*x) Out[3]: [(1, 2), (40, 2), (9, 80)]
Extract array from list in python
If I have a list like this: >>> data = [(1,2),(40,2),(9,80)] how can I extract the the two lists [1,40,9] and [2,2,80] ? Of course I can iterate and extract the numbers myself but I guess there is a better way ?
[ "The unzip operation is:\nIn [1]: data = [(1,2),(40,2),(9,80)]\nIn [2]: zip(*data)\nOut[2]: [(1, 40, 9), (2, 2, 80)]\n\nEdit: You can decompose the resulting list on assignment:\nIn [3]: first_elements, second_elements = zip(*data)\n\nAnd if you really need lists as results:\nIn [4]: first_elements, second_elements = map(list, zip(*data))\n\nTo better understand why this works:\nzip(*data)\n\nis equivalent to\nzip((1,2), (40,2), (9,80))\n\nThe two tuples in the result list are built from the first elements of zip()'s arguments and from the second elements of zip()'s arguments.\n", "List comprehensions save the day:\nfirst = [x for (x,y) in data]\nsecond = [y for (x,y) in data]\n\n", "There is also \nIn [1]: data = [(1,2),(40,2),(9,80)]\nIn [2]: x=map(None, *data)\nOut[2]: [(1, 40, 9), (2, 2, 80)]\nIn [3]: map(None,*x)\nOut[3]: [(1, 2), (40, 2), (9, 80)]\n\n" ]
[ 27, 14, 5 ]
[]
[]
[ "arrays", "list", "python" ]
stackoverflow_0000665652_arrays_list_python.txt
Q: Decorator classes in Python I want to construct classes for use as decorators with the following principles intact: It should be possible to stack multiple such class decorators on top off 1 function. The resulting function name pointer should be indistinguishable from the same function without a decorator, save maybe for just which type/class it is. Ordering off the decorators should not be relevant unless actually mandated by the decorators. Ie. independent decorators could be applied in any order. This is for a Django project, and the specific case I am working on now the method needs 2 decorators, and to appear as a normal python function: @AccessCheck @AutoTemplate def view(request, item_id) {} @AutoTemplate changes the function so that instead of returning a HttpResponse, it just returns a dictionary for use in the context. A RequestContext is used, and the template name is inferred from the method name and module. @AccessCheck adds additional checks on the user based on the item_id. I am guessing it's just to get the constructor right and copy the appropriate attributes, but which attributes are these? The following decorator won't work as I describe: class NullDecl (object): def __init__ (self, func): self.func = func def __call__ (self, * args): return self.func (*args) As demonstrated by the following code: @NullDecl @NullDecl def decorated(): pass def pure(): pass # results in set(['func_closure', 'func_dict', '__get__', 'func_name', # 'func_defaults', '__name__', 'func_code', 'func_doc', 'func_globals']) print set(dir(pure)) - set(dir(decorated)); Additionally, try and add "print func.name" in the NullDecl constructor, and it will work for the first decorator, but not the second - as name will be missing. Refined eduffy's answer a bit, and it seems to work pretty well: class NullDecl (object): def __init__ (self, func): self.func = func for n in set(dir(func)) - set(dir(self)): setattr(self, n, getattr(func, n)) def __call__ (self, * args): return self.func (*args) def __repr__(self): return self.func A: A do-nothing decorator class would look like this: class NullDecl (object): def __init__ (self, func): self.func = func for name in set(dir(func)) - set(dir(self)): setattr(self, name, getattr(func, name)) def __call__ (self, *args): return self.func (*args) And then you can apply it normally: @NullDecl def myFunc (x,y,z): return (x+y)/z A: The decorator module helps you writing signature-preserving decorators. And the PythonDecoratorLibrary might provide useful examples for decorators. A: To create a decorator that wraps functions in a matter that make them indistinguishable from the original function, use functools.wraps. Example: def mydecorator(func): @functools.wraps(func): def _mydecorator(*args, **kwargs): do_something() try: return func(*args, **kwargs) finally: clean_up() return _mydecorator # ... and with parameters def mydecorator(param1, param2): def _mydecorator(func): @functools.wraps(func) def __mydecorator(*args, **kwargs): do_something(param1, param2) try: return func(*args, **kwargs) finally: clean_up() return __mydecorator return _mydecorator (my personal preference is to create decorators using functions, not classes) The ordering of decorators is as follows: @d1 @d2 def func(): pass # is equivalent to def func(): pass func = d1(d2(func))
Decorator classes in Python
I want to construct classes for use as decorators with the following principles intact: It should be possible to stack multiple such class decorators on top off 1 function. The resulting function name pointer should be indistinguishable from the same function without a decorator, save maybe for just which type/class it is. Ordering off the decorators should not be relevant unless actually mandated by the decorators. Ie. independent decorators could be applied in any order. This is for a Django project, and the specific case I am working on now the method needs 2 decorators, and to appear as a normal python function: @AccessCheck @AutoTemplate def view(request, item_id) {} @AutoTemplate changes the function so that instead of returning a HttpResponse, it just returns a dictionary for use in the context. A RequestContext is used, and the template name is inferred from the method name and module. @AccessCheck adds additional checks on the user based on the item_id. I am guessing it's just to get the constructor right and copy the appropriate attributes, but which attributes are these? The following decorator won't work as I describe: class NullDecl (object): def __init__ (self, func): self.func = func def __call__ (self, * args): return self.func (*args) As demonstrated by the following code: @NullDecl @NullDecl def decorated(): pass def pure(): pass # results in set(['func_closure', 'func_dict', '__get__', 'func_name', # 'func_defaults', '__name__', 'func_code', 'func_doc', 'func_globals']) print set(dir(pure)) - set(dir(decorated)); Additionally, try and add "print func.name" in the NullDecl constructor, and it will work for the first decorator, but not the second - as name will be missing. Refined eduffy's answer a bit, and it seems to work pretty well: class NullDecl (object): def __init__ (self, func): self.func = func for n in set(dir(func)) - set(dir(self)): setattr(self, n, getattr(func, n)) def __call__ (self, * args): return self.func (*args) def __repr__(self): return self.func
[ "A do-nothing decorator class would look like this:\nclass NullDecl (object):\n def __init__ (self, func):\n self.func = func\n for name in set(dir(func)) - set(dir(self)):\n setattr(self, name, getattr(func, name))\n\n def __call__ (self, *args):\n return self.func (*args)\n\nAnd then you can apply it normally:\n@NullDecl\ndef myFunc (x,y,z):\n return (x+y)/z\n\n", "The decorator module helps you writing signature-preserving decorators.\nAnd the PythonDecoratorLibrary might provide useful examples for decorators.\n", "To create a decorator that wraps functions in a matter that make them indistinguishable from the original function, use functools.wraps.\nExample:\n\ndef mydecorator(func):\n @functools.wraps(func):\n def _mydecorator(*args, **kwargs):\n do_something()\n try:\n return func(*args, **kwargs)\n finally:\n clean_up()\n return _mydecorator\n\n# ... and with parameters\ndef mydecorator(param1, param2):\n def _mydecorator(func):\n @functools.wraps(func)\n def __mydecorator(*args, **kwargs):\n do_something(param1, param2)\n try:\n return func(*args, **kwargs)\n finally:\n clean_up()\n return __mydecorator\n return _mydecorator\n\n(my personal preference is to create decorators using functions, not classes)\nThe ordering of decorators is as follows:\n\n@d1\n@d2\ndef func():\n pass\n\n# is equivalent to\ndef func():\n pass\n\nfunc = d1(d2(func))\n\n" ]
[ 24, 10, 8 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0000666216_decorator_python.txt
Q: What errors/exceptions do I need to handle with urllib2.Request / urlopen? I have the following code to do a postback to a remote URL: request = urllib2.Request('http://www.example.com', postBackData, { 'User-Agent' : 'My User Agent' }) try: response = urllib2.urlopen(request) except urllib2.HTTPError, e: checksLogger.error('HTTPError = ' + str(e.code)) except urllib2.URLError, e: checksLogger.error('URLError = ' + str(e.reason)) except httplib.HTTPException, e: checksLogger.error('HTTPException') The postBackData is created using a dictionary encoded using urllib.urlencode. checksLogger is a logger using logging. I have had a problem where this code runs when the remote server is down and the code exits (this is on customer servers so I don't know what the exit stack dump / error is at this time). I'm assuming this is because there is an exception and/or error that is not being handled. So are there any other exceptions that might be triggered that I'm not handling above? A: Add generic exception handler: request = urllib2.Request('http://www.example.com', postBackData, { 'User-Agent' : 'My User Agent' }) try: response = urllib2.urlopen(request) except urllib2.HTTPError, e: checksLogger.error('HTTPError = ' + str(e.code)) except urllib2.URLError, e: checksLogger.error('URLError = ' + str(e.reason)) except httplib.HTTPException, e: checksLogger.error('HTTPException') except Exception: import traceback checksLogger.error('generic exception: ' + traceback.format_exc()) A: From the docs page urlopen entry, it looks like you just need to catch URLError. If you really want to hedge your bets against problems within the urllib code, you can also catch Exception as a fall-back. Do not just except:, since that will catch SystemExit and KeyboardInterrupt also. Edit: What I mean to say is, you're catching the errors it's supposed to throw. If it's throwing something else, it's probably due to urllib code not catching something that it should have caught and wrapped in a URLError. Even the stdlib tends to miss simple things like AttributeError. Catching Exception as a fall-back (and logging what it caught) will help you figure out what's happening, without trapping SystemExit and KeyboardInterrupt. A: $ grep "raise" /usr/lib64/python/urllib2.py IOError); for HTTP errors, raises an HTTPError, which can also be raise AttributeError, attr raise ValueError, "unknown url type: %s" % self.__original # XXX raise an exception if no one else should try to handle raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) perform the redirect. Otherwise, raise HTTPError if no-one raise HTTPError(req.get_full_url(), code, msg, headers, fp) raise HTTPError(req.get_full_url(), code, raise HTTPError(req.get_full_url(), 401, "digest auth failed", raise ValueError("AbstractDigestAuthHandler doesn't know " raise URLError('no host given') raise URLError('no host given') raise URLError(err) raise URLError('unknown url type: %s' % type) raise URLError('file not on local host') raise IOError, ('ftp error', 'no host given') raise URLError(msg) raise IOError, ('ftp error', msg), sys.exc_info()[2] raise GopherError('no host given') There is also the possibility of exceptions in urllib2 dependencies, or of exceptions caused by genuine bugs. You are best off logging all uncaught exceptions in a file via a custom sys.excepthook. The key rule of thumb here is to never catch exceptions you aren't planning to correct, and logging is not a correction. So don't catch them just to log them. A: You can catch all exceptions and log what's get caught: import sys import traceback def formatExceptionInfo(maxTBlevel=5): cla, exc, trbk = sys.exc_info() excName = cla.__name__ try: excArgs = exc.__dict__["args"] except KeyError: excArgs = "<no args>" excTb = traceback.format_tb(trbk, maxTBlevel) return (excName, excArgs, excTb) try: x = x + 1 except: print formatExceptionInfo() (Code from http://www.linuxjournal.com/article/5821) Also read documentation on sys.exc_info. A: I catch: httplib.HTTPException urllib2.HTTPError urllib2.URLError I believe this covers everything including socket errors.
What errors/exceptions do I need to handle with urllib2.Request / urlopen?
I have the following code to do a postback to a remote URL: request = urllib2.Request('http://www.example.com', postBackData, { 'User-Agent' : 'My User Agent' }) try: response = urllib2.urlopen(request) except urllib2.HTTPError, e: checksLogger.error('HTTPError = ' + str(e.code)) except urllib2.URLError, e: checksLogger.error('URLError = ' + str(e.reason)) except httplib.HTTPException, e: checksLogger.error('HTTPException') The postBackData is created using a dictionary encoded using urllib.urlencode. checksLogger is a logger using logging. I have had a problem where this code runs when the remote server is down and the code exits (this is on customer servers so I don't know what the exit stack dump / error is at this time). I'm assuming this is because there is an exception and/or error that is not being handled. So are there any other exceptions that might be triggered that I'm not handling above?
[ "Add generic exception handler:\nrequest = urllib2.Request('http://www.example.com', postBackData, { 'User-Agent' : 'My User Agent' })\n\ntry: \n response = urllib2.urlopen(request)\nexcept urllib2.HTTPError, e:\n checksLogger.error('HTTPError = ' + str(e.code))\nexcept urllib2.URLError, e:\n checksLogger.error('URLError = ' + str(e.reason))\nexcept httplib.HTTPException, e:\n checksLogger.error('HTTPException')\nexcept Exception:\n import traceback\n checksLogger.error('generic exception: ' + traceback.format_exc())\n\n", "From the docs page urlopen entry, it looks like you just need to catch URLError. If you really want to hedge your bets against problems within the urllib code, you can also catch Exception as a fall-back. Do not just except:, since that will catch SystemExit and KeyboardInterrupt also.\nEdit: What I mean to say is, you're catching the errors it's supposed to throw. If it's throwing something else, it's probably due to urllib code not catching something that it should have caught and wrapped in a URLError. Even the stdlib tends to miss simple things like AttributeError. Catching Exception as a fall-back (and logging what it caught) will help you figure out what's happening, without trapping SystemExit and KeyboardInterrupt.\n", "$ grep \"raise\" /usr/lib64/python/urllib2.py\nIOError); for HTTP errors, raises an HTTPError, which can also be\n raise AttributeError, attr\n raise ValueError, \"unknown url type: %s\" % self.__original\n # XXX raise an exception if no one else should try to handle\n raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)\n perform the redirect. Otherwise, raise HTTPError if no-one\n raise HTTPError(req.get_full_url(), code, msg, headers, fp)\n raise HTTPError(req.get_full_url(), code,\n raise HTTPError(req.get_full_url(), 401, \"digest auth failed\",\n raise ValueError(\"AbstractDigestAuthHandler doesn't know \"\n raise URLError('no host given')\n raise URLError('no host given')\n raise URLError(err)\n raise URLError('unknown url type: %s' % type)\n raise URLError('file not on local host')\n raise IOError, ('ftp error', 'no host given')\n raise URLError(msg)\n raise IOError, ('ftp error', msg), sys.exc_info()[2]\n raise GopherError('no host given')\n\nThere is also the possibility of exceptions in urllib2 dependencies, or of exceptions caused by genuine bugs.\nYou are best off logging all uncaught exceptions in a file via a custom sys.excepthook. The key rule of thumb here is to never catch exceptions you aren't planning to correct, and logging is not a correction. So don't catch them just to log them.\n", "You can catch all exceptions and log what's get caught:\n import sys\n import traceback\n def formatExceptionInfo(maxTBlevel=5):\n cla, exc, trbk = sys.exc_info()\n excName = cla.__name__\n try:\n excArgs = exc.__dict__[\"args\"]\n except KeyError:\n excArgs = \"<no args>\"\n excTb = traceback.format_tb(trbk, maxTBlevel)\n return (excName, excArgs, excTb)\n try:\n x = x + 1\n except:\n print formatExceptionInfo()\n\n(Code from http://www.linuxjournal.com/article/5821)\nAlso read documentation on sys.exc_info.\n", "I catch:\nhttplib.HTTPException\nurllib2.HTTPError\nurllib2.URLError\n\nI believe this covers everything including socket errors.\n" ]
[ 65, 20, 15, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000666022_python.txt
Q: qt design issue i'm trying to design interface like this one http://www.softpedia.com/screenshots/FlashFXP_2.png i'm using the QT design and programming with python well on the left it's a treeWidget but what is on the right side ? as everytime i change the cursor on the tree all widgets replace... thanks :p A: Use QStackedWidget. You insert several widgets which correspond to the pages. Changing the active item in tree should switch the active widget/page inside the stacked widget.
qt design issue
i'm trying to design interface like this one http://www.softpedia.com/screenshots/FlashFXP_2.png i'm using the QT design and programming with python well on the left it's a treeWidget but what is on the right side ? as everytime i change the cursor on the tree all widgets replace... thanks :p
[ "Use QStackedWidget. You insert several widgets which correspond to the pages. Changing the active item in tree should switch the active widget/page inside the stacked widget.\n" ]
[ 8 ]
[]
[]
[ "python", "qt", "user_interface" ]
stackoverflow_0000666712_python_qt_user_interface.txt
Q: How to get whole text of an Element in xml.minidom? I want to get the whole text of an Element to parse some xhtml: <div id='asd'> <pre>skdsk</pre> </div> begin E = div element on the above example, I want to get <pre>skdsk</pre> How? A: Strictly speaking: from xml.dom.minidom import parse, parseString tree = parseString("<div id='asd'><pre>skdsk</pre></div>") root = tree.firstChild node = root.childNodes[0] print node.toxml() In practice, though, I'd recommend looking at the http://www.crummy.com/software/BeautifulSoup/ library. Finding the right childNode in an xhtml document, and skipping "whitespace nodes" is a pain. BeautifulSoup is a robust html/xhtml parser with fantastic tree-search capacilities. Edit: The example above compresses the HTML into one string. If you use the HTML as in the question, the line breaks and so-forth will generate "whitespace" nodes, so the node you want won't be at childNodes[0].
How to get whole text of an Element in xml.minidom?
I want to get the whole text of an Element to parse some xhtml: <div id='asd'> <pre>skdsk</pre> </div> begin E = div element on the above example, I want to get <pre>skdsk</pre> How?
[ "Strictly speaking:\nfrom xml.dom.minidom import parse, parseString\ntree = parseString(\"<div id='asd'><pre>skdsk</pre></div>\")\nroot = tree.firstChild\nnode = root.childNodes[0]\nprint node.toxml()\n\nIn practice, though, I'd recommend looking at the http://www.crummy.com/software/BeautifulSoup/ library. Finding the right childNode in an xhtml document, and skipping \"whitespace nodes\" is a pain. BeautifulSoup is a robust html/xhtml parser with fantastic tree-search capacilities.\nEdit: The example above compresses the HTML into one string. If you use the HTML as in the question, the line breaks and so-forth will generate \"whitespace\" nodes, so the node you want won't be at childNodes[0].\n" ]
[ 2 ]
[]
[]
[ "minidom", "python" ]
stackoverflow_0000666724_minidom_python.txt
Q: Unable to decode unicode string in Python 2.4 This is in python 2.4. Here is my situation. I pull a string from a database, and it contains an umlauted 'o' (\xf6). At this point if I run type(value) it returns str. I then attempt to run .decode('utf-8'), and I get an error ('utf8' codec can't decode bytes in position 1-4). Really my goal here is just to successfully make type(value) return unicode. I found an earlier question that had some useful information, but the example from the picked answer doesn't seem to run for me. Is there something I am doing wrong here? Here is some code to reproduce: Name = 'w\xc3\xb6rner'.decode('utf-8') file.write('Name: %s - %s\n' %(Name, type(Name))) I never actually get to the write statement, because it fails on the first statement. Thank you for your help. Edit: I verified that the DB's charset is utf8. So in my code to reproduce I changed '\xf6' to '\xc3\xb6', and the failure still occurs. Is there a difference between 'utf-8' and 'utf8'? The tip on using codecs to write to a file is handy (I'll definitely use it), but in this scenario I am only writing to a log file for debugging purposes. A: Your string is not in UTF8 encoding. If you want to 'decode' string to unicode, your string must be in encoding you specified by parameter. I tried this and it works perfectly: print 'w\xf6rner'.decode('cp1250') EDIT For writing unicode strings to the file you can use codecs module: import codecs f = codecs.open("yourfile.txt", "w", "utf8") f.write( ... ) It is handy to specify encoding of the input/output and using 'unicode' string throughout your code without bothering of different encodings. A: It's obviously 1-byte encoding. 'ö' in UTF-8 is '\xc3\xb6'. The encoding might be: ISO-8859-1 ISO-8859-2 ISO-8859-13 ISO-8859-15 Win-1250 Win-1252 A: You need to use "ISO-8859-1": Name = 'w\xf6rner'.decode('iso-8859-1') file.write('Name: %s - %s\n' %(Name, type(Name))) utf-8 uses 2 bytes for escaping anything outside ascii, but here it's just 1 byte, so iso-8859-1 is probably correct. A: So in my code to reproduce I changed '\xf6' to '\xc3\xb6', and the failure still occurs Not in the first line it doesn't: >>> 'w\xc3\xb6rner'.decode('utf-8') u'w\xf6rner' The second line will error out though: >>> file.write('Name: %s - %s\n' %(Name, type(Name))) UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 7: ordinal not in range(128) Which is entirely what you'd expect, trying to write non-ASCII Unicode characters to a byte stream. If you use Jiri's suggestion of a codecs-wrapped stream you can write Unicode directly, otherwise you will have to re-encode the Unicode string into bytes manually. Better, for logging purposes, would be simply to spit out a repr() of the variable. Then you don't have to worry about Unicode characters being in there, or newlines or other unwanted characters: name= 'w\xc3\xb6rner'.decode('utf-8') file.write('Name: %r\n' % name) Name: u'w\xf6rner'
Unable to decode unicode string in Python 2.4
This is in python 2.4. Here is my situation. I pull a string from a database, and it contains an umlauted 'o' (\xf6). At this point if I run type(value) it returns str. I then attempt to run .decode('utf-8'), and I get an error ('utf8' codec can't decode bytes in position 1-4). Really my goal here is just to successfully make type(value) return unicode. I found an earlier question that had some useful information, but the example from the picked answer doesn't seem to run for me. Is there something I am doing wrong here? Here is some code to reproduce: Name = 'w\xc3\xb6rner'.decode('utf-8') file.write('Name: %s - %s\n' %(Name, type(Name))) I never actually get to the write statement, because it fails on the first statement. Thank you for your help. Edit: I verified that the DB's charset is utf8. So in my code to reproduce I changed '\xf6' to '\xc3\xb6', and the failure still occurs. Is there a difference between 'utf-8' and 'utf8'? The tip on using codecs to write to a file is handy (I'll definitely use it), but in this scenario I am only writing to a log file for debugging purposes.
[ "Your string is not in UTF8 encoding. If you want to 'decode' string to unicode, your string must be in encoding you specified by parameter. I tried this and it works perfectly:\nprint 'w\\xf6rner'.decode('cp1250')\n\nEDIT\nFor writing unicode strings to the file you can use codecs module:\nimport codecs\nf = codecs.open(\"yourfile.txt\", \"w\", \"utf8\")\nf.write( ... )\n\nIt is handy to specify encoding of the input/output and using 'unicode' string throughout your code without bothering of different encodings.\n", "It's obviously 1-byte encoding. 'ö' in UTF-8 is '\\xc3\\xb6'.\nThe encoding might be:\n\nISO-8859-1\nISO-8859-2\nISO-8859-13\nISO-8859-15\nWin-1250\nWin-1252\n\n", "You need to use \"ISO-8859-1\":\nName = 'w\\xf6rner'.decode('iso-8859-1')\nfile.write('Name: %s - %s\\n' %(Name, type(Name)))\n\nutf-8 uses 2 bytes for escaping anything outside ascii, but here it's just 1 byte, so iso-8859-1 is probably correct.\n", "\nSo in my code to reproduce I changed '\\xf6' to '\\xc3\\xb6', and the failure still occurs\n\nNot in the first line it doesn't:\n>>> 'w\\xc3\\xb6rner'.decode('utf-8')\nu'w\\xf6rner'\n\nThe second line will error out though:\n>>> file.write('Name: %s - %s\\n' %(Name, type(Name)))\nUnicodeEncodeError: 'ascii' codec can't encode character u'\\xf6' in position 7: ordinal not in range(128)\n\nWhich is entirely what you'd expect, trying to write non-ASCII Unicode characters to a byte stream. If you use Jiri's suggestion of a codecs-wrapped stream you can write Unicode directly, otherwise you will have to re-encode the Unicode string into bytes manually.\nBetter, for logging purposes, would be simply to spit out a repr() of the variable. Then you don't have to worry about Unicode characters being in there, or newlines or other unwanted characters:\nname= 'w\\xc3\\xb6rner'.decode('utf-8')\nfile.write('Name: %r\\n' % name)\n\nName: u'w\\xf6rner'\n\n" ]
[ 10, 5, 3, 2 ]
[]
[]
[ "decode", "python", "unicode" ]
stackoverflow_0000666417_decode_python_unicode.txt
Q: Uses for Dynamic Languages My primary language right now is D, and I'm in the process of learning Python because it's required for a course I'm taking. While I understand why dynamic languages would be a breath of fresh air for people programming in static languages without type inference or templates (IMHO templates are to a large extent compile-time duck typing), I'm curious what the benefits are of dynamic languages even when you have those. The bottom line is that, if I'm going to learn Python, I want to learn it in a way that really changes my thinking about programming, rather than just writing D in Python. I have not used dynamic languages since I was a fairly novice programmer and unable to appreciate the flexibility they supposedly offer, and want to learn to take full advantage of them now. What can be done easily/elegantly in a dynamically typed, interpreted language that's awkward or impossible in a static language, even with templates, polymorphism, static type inference, and maybe runtime reflection? A: In theory, there's nothing that dynamic languages can do and static languages can't. Smart people put a lot of work into making very good dynamic languages, leading to a perception at the moment that dynamic languages are ahead while static ones need to catch up. In time, this will swing the other way. Already various static languages have: Generics, which make static types less stupid by letting it select the right type when objects are passed around, saving the programmer from having to cast it themselves Type inference, which saves having to waste time on writing the stuff that should be obvious Closures, which among many other things help to separate mechanism from intention, letting you pull together complicated algorithms from mostly existing ingredients. Implicit conversions, which lets you simulate "monkey patching" without the risks it usually involves. Code loading and easy programmatic access to the compiler, so users and third parties can script your program. Use with caution! Syntaxes that are more conducive to the creation of Domain Specific Languages within them. ...and no doubt more to come. The dynamic movement has spawned some interesting developments in static language design, and we all benefit from the competition. I only hope more of these features make it to the mainstream. There's one place where I don't see the dominant dynamic language being replaced, and that's Javascript in the browser. There's just too much of an existing market to replace, so the emphasis seems to be towards making Javascript itself better instead. A: Here's Steve Yegge on the subject. Guido van Rossum also linked to that talk in his take of Scala. A: "I'm curious what the benefits are of dynamic languages even when you have those." Compared to D programming language: Python is a more compact language. It allows you to express as much as D but it uses many fewer different concepts to achieve it -- less is more. Python has a powerful standard library -- batteries included. I don't know whether D has interactive prompts but in Python an interactive shell such as ipython is an integrated part of development process. A: Example in Python: def lengths(sequence): try: return sum(len(item) for item in sequence) except TypeError: return "Wolf among the sheep!" >>> lengths(["a", "b", "c", (1, 2, 3)]) 6 >>> lengths( ("1", "2", 3) ) 'Wolf among the sheep!' How long do you think this took me to write, and how many compile-run-debug cycles? If you think my example is trivial, I can reply by saying that dynamic languages make trivial many programming tasks. A: In dynamic languages you can use values in ways that you know are correct. In a statically typed language you can only use values in ways the compiler knows are correct. You need all of the things you mentioned to regain flexibility that's taken away by the type system (I'm not bashing static type systems, the flexibility is often taken away for good reasons). This is a lot of complexity that you don't have to deal with in a dynamic language if you want to use values in ways the language designer didn't anticipate (for example, putting values of different types in a hash table). So it's not that you can't do these things in a statically typed language (if you have runtime reflection), it's just more complicated. A: I actually wrote a blog post on this: linky. But that post basically can be summed up like this: You'd be surprised at how much of a load off your mind it is to not have to name at compile time what type your variable is. Thus, python tends to be a very productive language. On the other hand, even with good unit tests, you'd also be surprised at what kinds of stupid mistakes you're allowing yourself to make. A: One big advantage of dynamic typing when using objects is that you don't need to use class hierarchies anymore when you want several classes to have the same interface - that's more or less what is called duck typing. Bad inheritance is very difficult to fix afterwards - this makes refactoring often harder than it is in a language like python. A: The point is that in a dynamic language you can implement the same functionality much quicker than in a statically typed one. Therefore the productivity is typically much higher. Things like templates or polymorphism in principle give you lots of flexibility, but you have to write a large amount of code to make it work. In a dynamic language this flexibility almost comes for free. So I think you look at the difference in the wrong way, productivity really is the main point here (just like garbage collection improves productivity, but otherwise does not really allow you to do new things). A: I was going to say closures but found this thread... (not that I understand how it would work in a "static" language) Related concepts are functions-as-first-class-objects and higher-order procedures. (e.g. a function that takes a function as input and/or returns a function as output) edit: (for the nitpickers here) I'll echo a comment I made on @David Locke's post. Dynamically-interpreted languages make it possible to use an existing software program/project in conjunction with a small function or class created at the spur-of-the-moment to explore something interactively. Probably the best example is function graphing. If I wrote a function-graphing object with a graph(f,xmin,xmax) function, I could use it to explore functions like x2 or sin(x) or whatever. I do this in MATLAB all the time; it's interpreted and has anonymous functions (@(x) x^2) that can be constructed at the interpreter prompt to pass into higher-order functions (graphing functions, derivative operators, root finders, etc). A: With a dynamic language it's much easier to have a command line interpreter so you can test things on the command line and don't have to worry about a compile step to see if they work. A: I find dynamic languages like Perl and to a lesser extent Python allow me to write quick and dirty scripts for things I need to do. The run cycle is much shorter in dynamic languages and often less code needs to be written then in a statically typed language which increases my productivity. This unfortunately comes at the cost of maintainability but that is a fault of the way I write programs in dynamic languages not in the languages them selves. A: Take a look at this e4x example in JavaScript: var sales = <sales vendor="John"> <item type="peas" price="4" quantity="6"/> <item type="carrot" price="3" quantity="10"/> <item type="chips" price="5" quantity="3"/> </sales>; alert( sales.item.(@type == "carrot").@quantity ); alert( sales.@vendor ); for each( var price in sales..@price ) { alert( price ); } Especially, take a look at line: alert( sales.item.(@type == "carrot").@quantity ); In typical static languages, you don’t get to write sales.item, since you can not know that item is property of sales until runtime. This is not limited to e4x. You get to program in similar style when connecting when writing SOAP clients or any other underlying type you do not know until runtime. In a static language, you would typically need to run a tool that will generate stub classes or program in a very verbose way. Then, if something changes in a web service, you need to regenerate stubs all over again. Take a look at java DOM code: import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; public class Foo { public Document createDocument() { Document document = DocumentHelper.createDocument(); Element root = document.addElement( "root" ); Element author1 = root.addElement( "author" ) .addAttribute( "name", "James" ) .addAttribute( "location", "UK" ) .addText( "James Strachan" ); Element author2 = root.addElement( "author" ) .addAttribute( "name", "Bob" ) .addAttribute( "location", "US" ) .addText( "Bob McWhirter" ); return document; } } Definitely much more verbose than your dynamic code. And, of course, it is not statically typed. There is no way to check that you misspelled “author” as "autor" until runtime. All this verbosity is essentially there to let you capture something that is dynamic in nature in static style. I think this is one of the strong points of dynamic languages.
Uses for Dynamic Languages
My primary language right now is D, and I'm in the process of learning Python because it's required for a course I'm taking. While I understand why dynamic languages would be a breath of fresh air for people programming in static languages without type inference or templates (IMHO templates are to a large extent compile-time duck typing), I'm curious what the benefits are of dynamic languages even when you have those. The bottom line is that, if I'm going to learn Python, I want to learn it in a way that really changes my thinking about programming, rather than just writing D in Python. I have not used dynamic languages since I was a fairly novice programmer and unable to appreciate the flexibility they supposedly offer, and want to learn to take full advantage of them now. What can be done easily/elegantly in a dynamically typed, interpreted language that's awkward or impossible in a static language, even with templates, polymorphism, static type inference, and maybe runtime reflection?
[ "In theory, there's nothing that dynamic languages can do and static languages can't. Smart people put a lot of work into making very good dynamic languages, leading to a perception at the moment that dynamic languages are ahead while static ones need to catch up.\nIn time, this will swing the other way. Already various static languages have:\n\nGenerics, which make static types less stupid by letting it select the right type when objects are passed around, saving the programmer from having to cast it themselves\nType inference, which saves having to waste time on writing the stuff that should be obvious\nClosures, which among many other things help to separate mechanism from intention, letting you pull together complicated algorithms from mostly existing ingredients.\nImplicit conversions, which lets you simulate \"monkey patching\" without the risks it usually involves.\nCode loading and easy programmatic access to the compiler, so users and third parties can script your program. Use with caution!\nSyntaxes that are more conducive to the creation of Domain Specific Languages within them.\n\n...and no doubt more to come. The dynamic movement has spawned some interesting developments in static language design, and we all benefit from the competition. I only hope more of these features make it to the mainstream.\nThere's one place where I don't see the dominant dynamic language being replaced, and that's Javascript in the browser. There's just too much of an existing market to replace, so the emphasis seems to be towards making Javascript itself better instead.\n", "Here's Steve Yegge on the subject.\nGuido van Rossum also linked to that talk in his take of Scala.\n", "\n\"I'm curious what the benefits are of\n dynamic languages even when you have\n those.\"\n\nCompared to D programming language:\n\nPython is a more compact language. It allows you to express as much as D but it uses many fewer different concepts to achieve it -- less is more.\nPython has a powerful standard library -- batteries included.\n\nI don't know whether D has interactive prompts but in Python an interactive shell such as ipython is an integrated part of development process.\n", "Example in Python:\ndef lengths(sequence):\n try:\n return sum(len(item) for item in sequence)\n except TypeError:\n return \"Wolf among the sheep!\"\n\n>>> lengths([\"a\", \"b\", \"c\", (1, 2, 3)])\n6\n>>> lengths( (\"1\", \"2\", 3) )\n'Wolf among the sheep!'\n\nHow long do you think this took me to write, and how many compile-run-debug cycles?\nIf you think my example is trivial, I can reply by saying that dynamic languages make trivial many programming tasks.\n", "In dynamic languages you can use values in ways that you know are correct. In a statically typed language you can only use values in ways the compiler knows are correct. You need all of the things you mentioned to regain flexibility that's taken away by the type system (I'm not bashing static type systems, the flexibility is often taken away for good reasons). This is a lot of complexity that you don't have to deal with in a dynamic language if you want to use values in ways the language designer didn't anticipate (for example, putting values of different types in a hash table).\nSo it's not that you can't do these things in a statically typed language (if you have runtime reflection), it's just more complicated.\n", "I actually wrote a blog post on this: linky. But that post basically can be summed up like this:\nYou'd be surprised at how much of a load off your mind it is to not have to name at compile time what type your variable is. Thus, python tends to be a very productive language.\nOn the other hand, even with good unit tests, you'd also be surprised at what kinds of stupid mistakes you're allowing yourself to make.\n", "One big advantage of dynamic typing when using objects is that you don't need to use class hierarchies anymore when you want several classes to have the same interface - that's more or less what is called duck typing. Bad inheritance is very difficult to fix afterwards - this makes refactoring often harder than it is in a language like python.\n", "The point is that in a dynamic language you can implement the same functionality much quicker than in a statically typed one. Therefore the productivity is typically much higher.\nThings like templates or polymorphism in principle give you lots of flexibility, but you have to write a large amount of code to make it work. In a dynamic language this flexibility almost comes for free.\nSo I think you look at the difference in the wrong way, productivity really is the main point here (just like garbage collection improves productivity, but otherwise does not really allow you to do new things).\n", "I was going to say closures but found this thread... (not that I understand how it would work in a \"static\" language)\nRelated concepts are functions-as-first-class-objects and higher-order procedures. (e.g. a function that takes a function as input and/or returns a function as output)\nedit: (for the nitpickers here) I'll echo a comment I made on @David Locke's post. Dynamically-interpreted languages make it possible to use an existing software program/project in conjunction with a small function or class created at the spur-of-the-moment to explore something interactively. Probably the best example is function graphing. If I wrote a function-graphing object with a graph(f,xmin,xmax) function, I could use it to explore functions like x2 or sin(x) or whatever. I do this in MATLAB all the time; it's interpreted and has anonymous functions (@(x) x^2) that can be constructed at the interpreter prompt to pass into higher-order functions (graphing functions, derivative operators, root finders, etc).\n", "With a dynamic language it's much easier to have a command line interpreter so you can test things on the command line and don't have to worry about a compile step to see if they work.\n", "I find dynamic languages like Perl and to a lesser extent Python allow me to write quick and dirty scripts for things I need to do. The run cycle is much shorter in dynamic languages and often less code needs to be written then in a statically typed language which increases my productivity. This unfortunately comes at the cost of maintainability but that is a fault of the way I write programs in dynamic languages not in the languages them selves.\n", "Take a look at this e4x example in JavaScript:\nvar sales = <sales vendor=\"John\">\n <item type=\"peas\" price=\"4\" quantity=\"6\"/>\n <item type=\"carrot\" price=\"3\" quantity=\"10\"/>\n <item type=\"chips\" price=\"5\" quantity=\"3\"/>\n </sales>;\n\nalert( sales.item.(@type == \"carrot\").@quantity );\nalert( sales.@vendor );\nfor each( var price in sales..@price ) {\n alert( price );\n}\n\nEspecially, take a look at line:\nalert( sales.item.(@type == \"carrot\").@quantity );\n\nIn typical static languages, you don’t get to write sales.item, since you can not know that item is property of sales until runtime.\nThis is not limited to e4x. You get to program in similar style when connecting when writing SOAP clients or any other underlying type you do not know until runtime.\nIn a static language, you would typically need to run a tool that will generate stub classes or program in a very verbose way. Then, if something changes in a web service, you need to regenerate stubs all over again. Take a look at java DOM code: \nimport org.dom4j.Document;\nimport org.dom4j.DocumentHelper;\nimport org.dom4j.Element;\n\npublic class Foo {\n\n public Document createDocument() {\n Document document = DocumentHelper.createDocument();\n Element root = document.addElement( \"root\" );\n\n Element author1 = root.addElement( \"author\" )\n .addAttribute( \"name\", \"James\" )\n .addAttribute( \"location\", \"UK\" )\n .addText( \"James Strachan\" );\n\n Element author2 = root.addElement( \"author\" )\n .addAttribute( \"name\", \"Bob\" )\n .addAttribute( \"location\", \"US\" )\n .addText( \"Bob McWhirter\" );\n\n return document;\n }\n}\n\nDefinitely much more verbose than your dynamic code. And, of course, it is not statically typed. There is no way to check that you misspelled “author” as \"autor\" until runtime. All this verbosity is essentially there to let you capture something that is dynamic in nature in static style.\nI think this is one of the strong points of dynamic languages.\n" ]
[ 15, 3, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0 ]
[ "Compiled languages tend to be used when efficiency and type safety are the priorities. Otherwise I can't think of any reason why anyone wouldn't be using ruby :)\n" ]
[ -2 ]
[ "duck_typing", "dynamic_languages", "language_design", "programming_languages", "python" ]
stackoverflow_0000493973_duck_typing_dynamic_languages_language_design_programming_languages_python.txt
Q: Best continuously updated resource about python web "plumbing" I'm a programmer in Python who works on web-applications. I know a fair bit about the application level. But not so much about the underlying "plumbing" which I find myself having to configure or debug. I'm thinking of everything from using memcached to flup, fcgi, WSGI etc. When looking for information about these, online, Google typically delivers older-documents (eg. tutorials from before 2007), fragments of problems that may or may not have been resolved etc. Are there any good comprehensive and up-to-date resources to learn about how to put together a modern, high-performance server? One that explains both principles of the architecture and the actual packages? A: Buy this. http://www.amazon.com/Scalable-Internet-Architectures-Developers-Library/dp/067232699X A: General info about highly efficient web architecture: http://highscalability.com/ Interesting Python related articles: http://www.onlamp.com/python/ Printed magazine: http://pythonmagazine.com/ A: Zope is a still evolving framework, written in Python and is documented online. For a start, see Zope Concepts and Architecture. Like other Python based web frameworks, the source is your best reference. Note that Zope is not easy to grasp, and is different from frameworks like Django. A: You can use this terminology to limit search results to the past year: http://www.tech-recipes.com/rx/2860/google_how_to_access_filter_by_date_dropdown_box/
Best continuously updated resource about python web "plumbing"
I'm a programmer in Python who works on web-applications. I know a fair bit about the application level. But not so much about the underlying "plumbing" which I find myself having to configure or debug. I'm thinking of everything from using memcached to flup, fcgi, WSGI etc. When looking for information about these, online, Google typically delivers older-documents (eg. tutorials from before 2007), fragments of problems that may or may not have been resolved etc. Are there any good comprehensive and up-to-date resources to learn about how to put together a modern, high-performance server? One that explains both principles of the architecture and the actual packages?
[ "Buy this. http://www.amazon.com/Scalable-Internet-Architectures-Developers-Library/dp/067232699X\n", "\nGeneral info about highly efficient web architecture: http://highscalability.com/\nInteresting Python related articles: http://www.onlamp.com/python/ \nPrinted magazine: http://pythonmagazine.com/\n\n", "Zope is a still evolving framework, written in Python and is documented online. For a start, see Zope Concepts and Architecture. Like other Python based web frameworks, the source is your best reference.\nNote that Zope is not easy to grasp, and is different from frameworks like Django.\n", "You can use this terminology to limit search results to the past year:\nhttp://www.tech-recipes.com/rx/2860/google_how_to_access_filter_by_date_dropdown_box/\n" ]
[ 1, 1, 0, 0 ]
[]
[]
[ "flup", "python", "wsgi" ]
stackoverflow_0000665848_flup_python_wsgi.txt
Q: Crunching xml with python I need to remove white spaces between xml tags, e.g. if the original xml looks like: <node1> <node2> <node3>foo</node3> </node2> </node1> I'd like the end-result to be crunched down to single line: <node1><node2><node3>foo</node3></node2></node1> Please note that I will not have control over the xml structure, so the solution should be generic enough to be able to handle any valid xml. Also the xml might contain CDATA blocks, which I'd need to exclude from this crunching and leave them as-is. I have couple of ideas so far: (1) parse the xml as text and look for start and end of tags < and > (2) another approach is to load the xml document and go node-by-node and print out a new document by concatenating the tags. I think either method would work, but I'd rather not reinvent the wheel here, so may be there is a python library that already does something like this? If not, then any issues/pitfalls to be aware of when rolling out my own cruncher? Any recommendations? EDIT Thank you all for answers/suggestions, both Triptych's and Van Gale's solutions work for me and do exactly what I want. Wish I could accept both answers. A: This is pretty easily handled with lxml (note: this particular feature isn't in ElementTree): from lxml import etree parser = etree.XMLParser(remove_blank_text=True) foo = """<node1> <node2> <node3>foo </node3> </node2> </node1>""" bar = etree.XML(foo, parser) print etree.tostring(bar,pretty_print=False,with_tail=True) Results in: <node1><node2><node3>foo </node3></node2></node1> Edit: The answer by Triptych reminded me about the CDATA requirements, so the line creating the parser object should actually look like this: parser = etree.XMLParser(remove_blank_text=True, strip_cdata=False) A: I'd use XSLT: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" encoding="UTF-8" omit-xml-declaration="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="*"> <xsl:copy> <xsl:copy-of select="@*" /> <xsl:apply-templates /> </xsl:copy> </xsl:template> </xsl:stylesheet> That should do the trick. In python you could use lxml (direct link to sample on homepage) to transform it. For some tests, use xsltproc, sample: xsltproc test.xsl test.xml where test.xsl is the file above and test.xml your XML file. A: Pretty straightforward with BeautifulSoup. This solution assumes it is ok to strip whitespace from the tail ends of character data. Example: <foo> bar </foo> becomes <foo>bar</foo> It will correctly ignore comments and CDATA. import BeautifulSoup s = """ <node1> <node2> <node3>foo</node3> </node2> <node3> <!-- I'm a comment! Leave me be! --> </node3> <node4> <![CDATA[ I'm CDATA! Changing me would be bad! ]]> </node4> </node1> """ soup = BeautifulSoup.BeautifulStoneSoup(s) for t in soup.findAll(text=True): if type(t) is BeautifulSoup.NavigableString: # Ignores comments and CDATA t.replaceWith(t.strip()) print soup A: Not a solution really but since you asked for recommendations: I'd advise against doing your own parsing (unless you want to learn how to write a complex parser) because, as you say, not all spaces should be removed. There are not only CDATA blocks but also elements with the "xml:space=preserve" attribute, which correspond to things like <pre> in XHTML (where the enclosed whitespaces actually have meaning), and writing a parser that is able to recognize those elements and leave the whitespace alone would be possible but unpleasant. I would go with the parsing method, i.e. load the document and go node-by-node printing them out. That way you can easily identify which nodes you can strip the spaces out of and which you can't. There are some modules in the Python standard library, none of which I have ever used ;-) that could be useful to you... try xml.dom, or I'm not sure if you could do this with xml.parsers.expat.
Crunching xml with python
I need to remove white spaces between xml tags, e.g. if the original xml looks like: <node1> <node2> <node3>foo</node3> </node2> </node1> I'd like the end-result to be crunched down to single line: <node1><node2><node3>foo</node3></node2></node1> Please note that I will not have control over the xml structure, so the solution should be generic enough to be able to handle any valid xml. Also the xml might contain CDATA blocks, which I'd need to exclude from this crunching and leave them as-is. I have couple of ideas so far: (1) parse the xml as text and look for start and end of tags < and > (2) another approach is to load the xml document and go node-by-node and print out a new document by concatenating the tags. I think either method would work, but I'd rather not reinvent the wheel here, so may be there is a python library that already does something like this? If not, then any issues/pitfalls to be aware of when rolling out my own cruncher? Any recommendations? EDIT Thank you all for answers/suggestions, both Triptych's and Van Gale's solutions work for me and do exactly what I want. Wish I could accept both answers.
[ "This is pretty easily handled with lxml (note: this particular feature isn't in ElementTree):\nfrom lxml import etree\n\nparser = etree.XMLParser(remove_blank_text=True)\n\nfoo = \"\"\"<node1>\n <node2>\n <node3>foo </node3>\n </node2>\n</node1>\"\"\"\n\nbar = etree.XML(foo, parser)\nprint etree.tostring(bar,pretty_print=False,with_tail=True)\n\nResults in:\n<node1><node2><node3>foo </node3></node2></node1>\n\nEdit: The answer by Triptych reminded me about the CDATA requirements, so the line creating the parser object should actually look like this:\nparser = etree.XMLParser(remove_blank_text=True, strip_cdata=False)\n\n", "I'd use XSLT:\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:output method=\"xml\" encoding=\"UTF-8\" omit-xml-declaration=\"yes\"/>\n <xsl:strip-space elements=\"*\"/>\n\n <xsl:template match=\"*\">\n <xsl:copy>\n <xsl:copy-of select=\"@*\" />\n <xsl:apply-templates />\n </xsl:copy>\n </xsl:template>\n</xsl:stylesheet>\n\nThat should do the trick.\nIn python you could use lxml (direct link to sample on homepage) to transform it.\nFor some tests, use xsltproc, sample:\nxsltproc test.xsl test.xml\n\nwhere test.xsl is the file above and test.xml your XML file.\n", "Pretty straightforward with BeautifulSoup.\nThis solution assumes it is ok to strip whitespace from the tail ends of character data.\nExample: <foo> bar </foo> becomes <foo>bar</foo>\nIt will correctly ignore comments and CDATA.\nimport BeautifulSoup\n\ns = \"\"\"\n<node1>\n <node2>\n <node3>foo</node3>\n </node2>\n <node3>\n <!-- I'm a comment! Leave me be! -->\n </node3>\n <node4>\n <![CDATA[\n I'm CDATA! Changing me would be bad!\n ]]>\n </node4>\n</node1>\n\"\"\"\n\nsoup = BeautifulSoup.BeautifulStoneSoup(s)\n\nfor t in soup.findAll(text=True):\n if type(t) is BeautifulSoup.NavigableString: # Ignores comments and CDATA\n t.replaceWith(t.strip())\n\nprint soup\n\n", "Not a solution really but since you asked for recommendations: I'd advise against doing your own parsing (unless you want to learn how to write a complex parser) because, as you say, not all spaces should be removed. There are not only CDATA blocks but also elements with the \"xml:space=preserve\" attribute, which correspond to things like <pre> in XHTML (where the enclosed whitespaces actually have meaning), and writing a parser that is able to recognize those elements and leave the whitespace alone would be possible but unpleasant. \nI would go with the parsing method, i.e. load the document and go node-by-node printing them out. That way you can easily identify which nodes you can strip the spaces out of and which you can't. There are some modules in the Python standard library, none of which I have ever used ;-) that could be useful to you... try xml.dom, or I'm not sure if you could do this with xml.parsers.expat.\n" ]
[ 8, 5, 4, 2 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0000667359_python_xml.txt
Q: Alternatives to ffmpeg as a cli tools for video still extraction? I need to extract stills from video files. Currently I am using ffmpeg, but I am looking for a simpler tool and for a tool that my collegues can just install. No need to compile it from a svn checkout. Any hints? A python interface would be nice. A: Your requirements "cli tool" and "python interface" aren't entirely compatible. Which do you want? The following media libraries all have Python bindings: GStreamer, libVLC (pyvlc provides w32 binaries), Xine (via Pyxine). I'm pretty sure none of them will be easier than using the ffmpeg or mplayer command-line tools, though. Regarding ffmpeg: why would more than one person need to compile from a svn checkout (or tarball, as they've recently had their 0.5 release)? Grab or make a binary package and have everybody use it.
Alternatives to ffmpeg as a cli tools for video still extraction?
I need to extract stills from video files. Currently I am using ffmpeg, but I am looking for a simpler tool and for a tool that my collegues can just install. No need to compile it from a svn checkout. Any hints? A python interface would be nice.
[ "Your requirements \"cli tool\" and \"python interface\" aren't entirely compatible. Which do you want?\nThe following media libraries all have Python bindings: GStreamer, libVLC (pyvlc provides w32 binaries), Xine (via Pyxine). I'm pretty sure none of them will be easier than using the ffmpeg or mplayer command-line tools, though.\nRegarding ffmpeg: why would more than one person need to compile from a svn checkout (or tarball, as they've recently had their 0.5 release)? Grab or make a binary package and have everybody use it.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0000668240_python.txt
Q: Problem Extending Python(Linking Error )? I have installed Python 3k(C:\Python30) and Visual Studio Professional Edition 2008. I'm studying this. Here is a problem: C:\hello>dir Volume in drive C has no label. Volume Serial Number is 309E-14FB Directory of C:\hello 03/21/2009 01:15 AM <DIR> . 03/21/2009 01:15 AM <DIR> .. 03/21/2009 01:14 AM 481 hellomodule.c 1 File(s) 481 bytes 2 Dir(s) 10,640,642,048 bytes free C:\hello>cl /LD hellomodule.c /Ic:\Python30\include c:\Python30\libs\python30.lib /link/out:hello. dll Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 for 80x86 Copyright (C) Microsoft Corporation. All rights reserved. hellomodule.c c:\hello\hellomodule.c(26) : warning C4716: 'inithello' : must return a value Microsoft (R) Incremental Linker Version 9.00.21022.08 Copyright (C) Microsoft Corporation. All rights reserved. /out:hellomodule.dll /dll /implib:hellomodule.lib /out:hello.dll hellomodule.obj c:\Python30\libs\python30.lib Creating library hellomodule.lib and object hellomodule.exp hellomodule.obj : error LNK2019: unresolved external symbol _Py_InitModule referenced in function _inithello hello.dll : fatal error LNK1120: 1 unresolved externals C:\hello> What is the problem? Please, guide me. A: If Python is installed in c:\python30, why are you searching for the libraries in c:\Python24\libs\python30? And now that you've changed the question to fix this :-), I don't think Py_InitModule is available any more, you have to use PyModule_Create (this may have changed since the early betas of Py3k which is the last time I looked). Based on your comments, David, I'd suggest you need to avoid the HowTo sites outside of the official Python docs (I suspect they're well out of date). There was a lot of work happening on the extension interface at the 3.0 level and the best place to look is either at the 3.0 docs or 3.1 alpha docs. The specific Windows build instructions are here.
Problem Extending Python(Linking Error )?
I have installed Python 3k(C:\Python30) and Visual Studio Professional Edition 2008. I'm studying this. Here is a problem: C:\hello>dir Volume in drive C has no label. Volume Serial Number is 309E-14FB Directory of C:\hello 03/21/2009 01:15 AM <DIR> . 03/21/2009 01:15 AM <DIR> .. 03/21/2009 01:14 AM 481 hellomodule.c 1 File(s) 481 bytes 2 Dir(s) 10,640,642,048 bytes free C:\hello>cl /LD hellomodule.c /Ic:\Python30\include c:\Python30\libs\python30.lib /link/out:hello. dll Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 for 80x86 Copyright (C) Microsoft Corporation. All rights reserved. hellomodule.c c:\hello\hellomodule.c(26) : warning C4716: 'inithello' : must return a value Microsoft (R) Incremental Linker Version 9.00.21022.08 Copyright (C) Microsoft Corporation. All rights reserved. /out:hellomodule.dll /dll /implib:hellomodule.lib /out:hello.dll hellomodule.obj c:\Python30\libs\python30.lib Creating library hellomodule.lib and object hellomodule.exp hellomodule.obj : error LNK2019: unresolved external symbol _Py_InitModule referenced in function _inithello hello.dll : fatal error LNK1120: 1 unresolved externals C:\hello> What is the problem? Please, guide me.
[ "If Python is installed in c:\\python30, why are you searching for the libraries in c:\\Python24\\libs\\python30?\nAnd now that you've changed the question to fix this :-),\nI don't think Py_InitModule is available any more, you have to use PyModule_Create (this may have changed since the early betas of Py3k which is the last time I looked).\nBased on your comments, David, I'd suggest you need to avoid the HowTo sites outside of the official Python docs (I suspect they're well out of date). There was a lot of work happening on the extension interface at the 3.0 level and the best place to look is either \nat the 3.0 docs or 3.1 alpha docs.\nThe specific Windows build instructions are here.\n" ]
[ 2 ]
[]
[]
[ "c", "linker", "python", "visual_studio", "visual_studio_2008" ]
stackoverflow_0000668971_c_linker_python_visual_studio_visual_studio_2008.txt
Q: Can someone explain Gtk2 packing? I need to use Gtk2 for a project. I will be using python/ruby for it. The problem is that packing seems kind of mystical to me. I tried using a VBox so that I could have the following widgets in my window ( in the following order ): menubar toolbar text view/editor control I've managed to "guess" my way with pack_start and get the layout I need, but I'd like to be able to understand it. The documentation at Ruby Gtk2 seems way too unintuitive (and so is the python one, since it's the same, only written for python), could you shed some light? Also, set_size_request isn't always working when I add a component with pack_start. Why is that ? A: Box packing is really simple, so perhaps your failure to understand it is because you imagine it is more complicated than it is. Layout is either Vertical (like a pile of bricks) or horizontal (like a queue of people). Each element in that layout can expand or it can not expand. Horizontal (HBox) [widget][widget][widget][widget] Vertical (VBox) [widget] [widget] [widget] [widget] So for example, a Horizontal layout (HBox) with two buttons, which the code would be: import gtk box = gtk.HBox() b1 = gtk.Button('button1') b2 = gtk.Button('button2') box.pack_start(b1) box.pack_start(b2) Now since the default for packing is to have expand=True, both those buttons added to the box will expand and they will each occupy half the area. No matter what the size of the container is. I think of this as "stretchy". Expanding widgets: [[ widget ][ widget ]] So, if you want one of the buttons to not expand, you will pack it like this: box.pack_start(b1, expand=False) Non-expanding widget: [[widget][ widget ]] Then the button will only occupy the space it needs to draw itself: text + borders + shadows + images (if any) etc. And the other button will expand to fill the remaining area. Normally, buttons don't need to be expanded, so a more real-life situation is a TextArea which you would want to expand to fill the window. The other parameter that can be passed to pack_start is the fill parameter, and normally this can be ignored. It is enough here to say that if expand=False then the fill parameter is entirely ignored (because it doesn't make sense in that situation). The other thing you mentioned is set_size_request. I would generally say that this is not a good idea. I say generally, because there are situations where you will need to use it. But for someone beginning out with packing a GTK+ user interface, I would strongly recommend not using it. In general, let the boxes and other containers handle your layout for you. The set_size_request does not do exactly what you would expect it to do. It does not change the size of a widget, but merely how much space it will request. It may use more, and may even stretch to fill larger spaces. It will rarely become smaller than the request, but again because it is just a "request" there is no guarantee theat the request will be fulfilled.
Can someone explain Gtk2 packing?
I need to use Gtk2 for a project. I will be using python/ruby for it. The problem is that packing seems kind of mystical to me. I tried using a VBox so that I could have the following widgets in my window ( in the following order ): menubar toolbar text view/editor control I've managed to "guess" my way with pack_start and get the layout I need, but I'd like to be able to understand it. The documentation at Ruby Gtk2 seems way too unintuitive (and so is the python one, since it's the same, only written for python), could you shed some light? Also, set_size_request isn't always working when I add a component with pack_start. Why is that ?
[ "Box packing is really simple, so perhaps your failure to understand it is because you imagine it is more complicated than it is.\nLayout is either Vertical (like a pile of bricks) or horizontal (like a queue of people). Each element in that layout can expand or it can not expand.\nHorizontal (HBox)\n[widget][widget][widget][widget]\n\nVertical (VBox)\n[widget]\n[widget]\n[widget]\n[widget]\n\nSo for example, a Horizontal layout (HBox) with two buttons, which the code would be:\nimport gtk\nbox = gtk.HBox()\nb1 = gtk.Button('button1')\nb2 = gtk.Button('button2')\nbox.pack_start(b1)\nbox.pack_start(b2)\n\nNow since the default for packing is to have expand=True, both those buttons added to the box will expand and they will each occupy half the area. No matter what the size of the container is. I think of this as \"stretchy\".\nExpanding widgets:\n[[ widget ][ widget ]]\n\nSo, if you want one of the buttons to not expand, you will pack it like this:\nbox.pack_start(b1, expand=False)\n\nNon-expanding widget:\n[[widget][ widget ]]\n\nThen the button will only occupy the space it needs to draw itself: text + borders + shadows + images (if any) etc. And the other button will expand to fill the remaining area. Normally, buttons don't need to be expanded, so a more real-life situation is a TextArea which you would want to expand to fill the window.\nThe other parameter that can be passed to pack_start is the fill parameter, and normally this can be ignored. It is enough here to say that if expand=False then the fill parameter is entirely ignored (because it doesn't make sense in that situation).\nThe other thing you mentioned is set_size_request. I would generally say that this is not a good idea. I say generally, because there are situations where you will need to use it. But for someone beginning out with packing a GTK+ user interface, I would strongly recommend not using it. In general, let the boxes and other containers handle your layout for you. The set_size_request does not do exactly what you would expect it to do. It does not change the size of a widget, but merely how much space it will request. It may use more, and may even stretch to fill larger spaces. It will rarely become smaller than the request, but again because it is just a \"request\" there is no guarantee theat the request will be fulfilled.\n" ]
[ 14 ]
[]
[]
[ "gtk2", "packing", "pygtk", "python", "ruby" ]
stackoverflow_0000668226_gtk2_packing_pygtk_python_ruby.txt
Q: PyS60: Bluetooth sockets From the website http://www.mobilepythonbook.org/ I found the following example of bluetooth sockets: BT chat example Here in function chat_server() the bind method accepts a tuple with two elements. The first one has been used as a null string. What does it signify? Which node will act as master in the Bluetooth, the one that starts chat_client or the one that starts chat_server? I feel it should be the node running chat_client. Andhence Bluetooth slave will be the other nodes. A: For IPv4 addresses, two special forms are accepted instead of a host address: the empty string represents INADDR_ANY, and the string '' represents INADDR_BROADCAST -- http://docs.python.org/library/socket.html There you'll find more than enough information. Basically what INADDR_ANY means that it will bind to any address that the host has. The server is would be the Bluetooth master and the clients the slave, this is because the master has to exist before the the client can be spawned. As a discoverable device the server is the one that determines how the channel gets configured. I hope this clarifies things up. A: I found the answer the device that starts listening for incoming connections is slave and the one that discovers and requests for connection is the master. Sorry michelpeterson your answer is totally wrong.
PyS60: Bluetooth sockets
From the website http://www.mobilepythonbook.org/ I found the following example of bluetooth sockets: BT chat example Here in function chat_server() the bind method accepts a tuple with two elements. The first one has been used as a null string. What does it signify? Which node will act as master in the Bluetooth, the one that starts chat_client or the one that starts chat_server? I feel it should be the node running chat_client. Andhence Bluetooth slave will be the other nodes.
[ "For IPv4 addresses, two special forms are accepted instead of a host address: the empty string represents INADDR_ANY, and the string '' represents INADDR_BROADCAST -- http://docs.python.org/library/socket.html\nThere you'll find more than enough information. Basically what INADDR_ANY means that it will bind to any address that the host has.\nThe server is would be the Bluetooth master and the clients the slave, this is because the master has to exist before the the client can be spawned. As a discoverable device the server is the one that determines how the channel gets configured.\nI hope this clarifies things up.\n", "I found the answer the device that starts listening for incoming connections is slave and the one that discovers and requests for connection is the master.\nSorry michelpeterson your answer is totally wrong.\n" ]
[ 1, 0 ]
[]
[]
[ "bluetooth", "nokia", "pys60", "python" ]
stackoverflow_0000599737_bluetooth_nokia_pys60_python.txt
Q: Can I use a single file as a buffer? I.e. write to and read from at same time I want to have an application writing out information at the same time that a monitor is reading it. The application is "embedded" (and on Win32 XP) and so has restricted memory and I/O functionality. The simplest way I can think to do this is by writing the data to a buffer file from the application, and then read the same file using the monitor application. The writer application is C++, and the reader is currently Python on Win32 XP. Are there libraries to do this? Has anyone seen examples of this? I don't want to have to use a database as I don't want to link to a database library in the applcation. I.e. don't have space and may not be supported on the embedded platform. Another way to do this is over a network connection, but I figure files are the simplest solution. A: Most systems has several solutions for what you want to do, such as pipes and unix sockets. These are intended for this, unlike regular files. There are however programs that does this on regular files, and I think the clearest example of this is the unix-utility tail, which can "follow" a file. Take a look at http://msdn.microsoft.com/en-us/library/aa365590(VS.85).aspx Python has a good wrapper library for win32, so anything you see there can probably be access from python. A: You can use memory-mapped files, standard Python module called mmap. A: What you're talking about is called "Interprocess Communication". There are lots of ways of doing this. Using Unix pipes. https://docs.python.org/library/pipes.html Using sockets. https://docs.python.org/library/socket.html Using queues. https://docs.python.org/library/queue.html Any of these is better than file I/O.
Can I use a single file as a buffer? I.e. write to and read from at same time
I want to have an application writing out information at the same time that a monitor is reading it. The application is "embedded" (and on Win32 XP) and so has restricted memory and I/O functionality. The simplest way I can think to do this is by writing the data to a buffer file from the application, and then read the same file using the monitor application. The writer application is C++, and the reader is currently Python on Win32 XP. Are there libraries to do this? Has anyone seen examples of this? I don't want to have to use a database as I don't want to link to a database library in the applcation. I.e. don't have space and may not be supported on the embedded platform. Another way to do this is over a network connection, but I figure files are the simplest solution.
[ "Most systems has several solutions for what you want to do, such as pipes and unix sockets. These are intended for this, unlike regular files. There are however programs that does this on regular files, and I think the clearest example of this is the unix-utility tail, which can \"follow\" a file.\nTake a look at\nhttp://msdn.microsoft.com/en-us/library/aa365590(VS.85).aspx\nPython has a good wrapper library for win32, so anything you see there can probably be access from python.\n", "You can use memory-mapped files, standard Python module called mmap.\n", "What you're talking about is called \"Interprocess Communication\". There are lots of ways of doing this.\nUsing Unix pipes.\nhttps://docs.python.org/library/pipes.html\nUsing sockets.\nhttps://docs.python.org/library/socket.html\nUsing queues.\nhttps://docs.python.org/library/queue.html\nAny of these is better than file I/O.\n" ]
[ 4, 2, 1 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0000661826_file_io_python.txt
Q: How can I change the display text of a MenuItem in Gtk2? I need to change the display text of a MenuItem. Is there any way of doing this without removing the MenuItem and then adding another one with a different text? A: It somewhat depends how you created the menu item, since a MenuItem is a container that can contain anything. If you created it like: menuitem = gtk.MenuItem('This is the label') Then you can access the label widget in the menu item with: label = menuitem.child And can then treat that as a normal label: label.set_text('This is the new label') However, unless you made the menu item yourself, you can't guarantee that the child widget will be a label like this, so you should take some care.
How can I change the display text of a MenuItem in Gtk2?
I need to change the display text of a MenuItem. Is there any way of doing this without removing the MenuItem and then adding another one with a different text?
[ "It somewhat depends how you created the menu item, since a MenuItem is a container that can contain anything. If you created it like:\nmenuitem = gtk.MenuItem('This is the label')\n\nThen you can access the label widget in the menu item with:\nlabel = menuitem.child\n\nAnd can then treat that as a normal label:\nlabel.set_text('This is the new label')\n\nHowever, unless you made the menu item yourself, you can't guarantee that the child widget will be a label like this, so you should take some care.\n" ]
[ 3 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0000669152_gtk_pygtk_python.txt
Q: Why GQL Query does not match? What I want to do is build some mini cms which hold pages with a uri. The last route in my urls.py points to a function in my views.py, which checks in the datastore if there's a page available with the same uri of the current request, and if so show the page. I have a model: class Page(db.Model): title = db.StringProperty(required=True) uri = db.TextProperty(required=True) created = db.DateTimeProperty(auto_now_add=True) modified = db.DateTimeProperty(auto_now=True) content = db.TextProperty() In my view: def show(request): page = db.GqlQuery('SELECT * FROM Page WHERE uri=:uri', uri=request.path).get() if page is None: return http.HttpResponseNotFound() else: return respond(request, 'pages_show', {'content': request.path}) And I've added an entity with '/work' as uri to the datastore. Even when request.path is exactly '/work', the query does not return a match. Thanks for any advice you can give me! And yes, i'm a python noob, App Engine is perfect to finally learn the language. A: I've found the solution! The problem lies in the model. App engines datastore does not index a TextProperty. Using that type was wrong from the beginning, so i changed it to StringProperty, which does get indexed, and thus which datastore allows us to use in a WHERE clause. Example of working model: class Page(db.Model): title = db.StringProperty(required=True) // string property now uri = db.StringProperty(required=True) created = db.DateTimeProperty(auto_now_add=True) modified = db.DateTimeProperty(auto_now=True) content = db.TextProperty() A: If you use named keyword arguments ("uri=:uri"), you have to explicitly bind your parameters to the named keyword. Instead of: # incorrect named parameter GqlQuery('SELECT * FROM Page WHERE uri=:uri', request.path).get() you want # correct named parameter GqlQuery('SELECT * FROM Page WHERE uri=:uri', uri=request.path).get() or you could just use a positional parameter: # correct positional parameter GqlQuery('SELECT * FROM Page WHERE uri=:1', request.path).get()
Why GQL Query does not match?
What I want to do is build some mini cms which hold pages with a uri. The last route in my urls.py points to a function in my views.py, which checks in the datastore if there's a page available with the same uri of the current request, and if so show the page. I have a model: class Page(db.Model): title = db.StringProperty(required=True) uri = db.TextProperty(required=True) created = db.DateTimeProperty(auto_now_add=True) modified = db.DateTimeProperty(auto_now=True) content = db.TextProperty() In my view: def show(request): page = db.GqlQuery('SELECT * FROM Page WHERE uri=:uri', uri=request.path).get() if page is None: return http.HttpResponseNotFound() else: return respond(request, 'pages_show', {'content': request.path}) And I've added an entity with '/work' as uri to the datastore. Even when request.path is exactly '/work', the query does not return a match. Thanks for any advice you can give me! And yes, i'm a python noob, App Engine is perfect to finally learn the language.
[ "I've found the solution!\nThe problem lies in the model. \nApp engines datastore does not index a TextProperty. Using that type was wrong from the beginning, so i changed it to StringProperty, which does get indexed, and thus which datastore allows us to use in a WHERE clause.\nExample of working model:\n class Page(db.Model): \n title = db.StringProperty(required=True) \n // string property now\n uri = db.StringProperty(required=True) \n created = db.DateTimeProperty(auto_now_add=True) \n modified = db.DateTimeProperty(auto_now=True) \n content = db.TextProperty()\n\n", "If you use named keyword arguments (\"uri=:uri\"), you have to explicitly bind your parameters to the named keyword. Instead of:\n# incorrect named parameter\nGqlQuery('SELECT * FROM Page WHERE uri=:uri', request.path).get()\n\nyou want\n# correct named parameter\nGqlQuery('SELECT * FROM Page WHERE uri=:uri', uri=request.path).get()\n\nor you could just use a positional parameter:\n# correct positional parameter\nGqlQuery('SELECT * FROM Page WHERE uri=:1', request.path).get()\n\n" ]
[ 4, 2 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0000669043_google_app_engine_google_cloud_datastore_python.txt
Q: Highlighting trailing whitespace in Textmate for Python? I would like to do something like this Textmate tip, so that trailing whitespace are always highlighted in some way when I code something in Python - it makes it easier to correct it immediately and other editors such as Emacs can do it. Unfortunately the discussion after that post seems to suggest it's difficult to do. For me the invalid.trailing-whitespace scope selector is not even visible in the preferences after following this tip. Has anyone else had any success with this? A: I don't know how to highlight the trailing space but you can remove it by going to Bundles -> Text -> Converting/Stripping -> Remove trailing spaces in document Also, because textmate has emacs bindings, you may be able to do it the same way you would do it in emacs. A: This code works (but not with comment) : { scopeName = 'source.whitespace'; patterns = ( { name = 'source.invalid.trailing-whitespace'; match = '(\s+)$'; captures = { 1 = { name = 'invalid.trailing-whitespace'; }; }; }, ); } PS: I have changed "source" to "source.whitespace" For comment change in Python grammar : { name = 'comment.line.number-sign.python'; match = '(#).*$\n?'; captures = { 1 = { name = 'punctuation.definition.comment.python'; }; }; }, In: { name = 'comment.line.number-sign.python'; match = '(#).*?(\s*)$\n?'; captures = { 1 = { name = 'punctuation.definition.comment.python'; }; 2 = { name = 'invalid.trailing-whitespace'; }; }; }, You'll need to add an 'include' in Python language definition where: : patterns = ( { name = 'comment.line.number-sign.python'; : Turns to: : patterns = ( { include = 'source.whitespace'; }, { name = 'comment.line.number-sign.python'; :
Highlighting trailing whitespace in Textmate for Python?
I would like to do something like this Textmate tip, so that trailing whitespace are always highlighted in some way when I code something in Python - it makes it easier to correct it immediately and other editors such as Emacs can do it. Unfortunately the discussion after that post seems to suggest it's difficult to do. For me the invalid.trailing-whitespace scope selector is not even visible in the preferences after following this tip. Has anyone else had any success with this?
[ "I don't know how to highlight the trailing space but you can remove it by going to\nBundles -> Text -> Converting/Stripping -> Remove trailing spaces in document\nAlso, because textmate has emacs bindings, you may be able to do it the same way you would do it in emacs.\n", "This code works (but not with comment) :\n{ scopeName = 'source.whitespace';\n patterns = (\n { name = 'source.invalid.trailing-whitespace';\n match = '(\\s+)$';\n captures = { 1 = { name = 'invalid.trailing-whitespace'; }; };\n },\n );\n}\n\nPS: I have changed \"source\" to \"source.whitespace\"\nFor comment change in Python grammar :\n{ name = 'comment.line.number-sign.python';\n match = '(#).*$\\n?';\n captures = { 1 = { name = 'punctuation.definition.comment.python'; }; };\n},\n\nIn:\n{ name = 'comment.line.number-sign.python';\n match = '(#).*?(\\s*)$\\n?';\n captures = { \n 1 = { name = 'punctuation.definition.comment.python'; }; \n 2 = { name = 'invalid.trailing-whitespace'; }; \n };\n},\n\nYou'll need to add an 'include' in Python language definition where:\n:\npatterns = (\n { name = 'comment.line.number-sign.python';\n:\n\nTurns to:\n:\npatterns = (\n { include = 'source.whitespace'; },\n { name = 'comment.line.number-sign.python';\n:\n\n" ]
[ 5, 5 ]
[]
[]
[ "macos", "python", "textmate" ]
stackoverflow_0000641794_macos_python_textmate.txt
Q: Hierarchy traversal and comparison modules for Python? I deal with a lot of hierarchies in my day to day development. File systems, nested DAG nodes in Autodesk Maya, etc. I'm wondering, are there any good modules for Python specifically designed to traverse and compare hierarchies of objects? Of particular interest would be ways to do 'fuzzy' comparisons between two nearly identical hierarchies. Some of the reasons for doing this would be for matching two node hierarchies in Maya from two different characters in order to transfer animation from one to the other. Based on what I've been reading, I'd probably need something with a name threshold (which I could build myself) for comparing how close two node names are to each other. I'd then need a way to optionally ignore the order that child nodes appear in the hierarchy. Lastly, I'd need to deal with a depth threshold, in cases where a node may have been slightly moved up or down the hierarchy. A: I'm not sure I see the need for a complete module -- hierarchies are a design pattern, and each hierarchy has enough unique features that it's hard to generalize. class Node( object ): def __init__( self, myData, children=None ) self.myData= myData self.children= children if children is not None else [] def visit( self, aVisitor ): aVisitor.at( self ) aVisitor.down() for c in self.children: aVisitor.at( c ) aVisitor.up() class Visitor( object ): def __init__( self ): self.depth= 0 def down( self ): self.depth += 1 def up( self ): self.depth -= 1 I find that this is all I need. And I've found that it's hard to make a reusable module out of this because (a) there's so little here and (b) each application adds or changes so much code. Further, I find that the most commonly used hierarchy is the file system, for which I have the os module. The second most commonly used hierarchy is XML messages, for which I have ElementTree (usually via lxml). After those two, I use the above structures as templates for my classes, not as a literal reusable module. A: I recommend digging around xmldifff http://www.logilab.org/859 and seeing how they compare nodes and handle parallel trees. Or, try writing a [recursive] generator that yields each [significant] node in a tree, say f(t), then use itertools.izip(f(t1),f(t2)) to collect together pairs of nodes for comparison. Most of the hierarchical structures I deal with have more than one "axis", like elements and attributes in XML, and some nodes are more significant than others. For a more bizarre solution, serialize the two trees to text files, make a referential note that line #n comes from node #x in a tree. Do that to both trees, feed the files into diff, and scan the results to notice which parts of the tree have changed. You can map that line #n from file 1 (and therefore node #x in the first tree) and line #m from file 2 (and therefore node #y of the second tree) mean that some part of each tree is the same or different. For any solution your are going to have to establish a "canonical form" of your tree, one that might drop all ignorable whitespace, display attributes, optional nodes, etc., from the comparison process. It might also mean doing a breadth first vs. depth first traversal of the tree(s). A: http://code.google.com/p/pytree/ these maybe overkill or not suited at all for what you need: http://networkx.lanl.gov/ http://www.osl.iu.edu/~dgregor/bgl-python/
Hierarchy traversal and comparison modules for Python?
I deal with a lot of hierarchies in my day to day development. File systems, nested DAG nodes in Autodesk Maya, etc. I'm wondering, are there any good modules for Python specifically designed to traverse and compare hierarchies of objects? Of particular interest would be ways to do 'fuzzy' comparisons between two nearly identical hierarchies. Some of the reasons for doing this would be for matching two node hierarchies in Maya from two different characters in order to transfer animation from one to the other. Based on what I've been reading, I'd probably need something with a name threshold (which I could build myself) for comparing how close two node names are to each other. I'd then need a way to optionally ignore the order that child nodes appear in the hierarchy. Lastly, I'd need to deal with a depth threshold, in cases where a node may have been slightly moved up or down the hierarchy.
[ "I'm not sure I see the need for a complete module -- hierarchies are a design pattern, and each hierarchy has enough unique features that it's hard to generalize.\nclass Node( object ):\n def __init__( self, myData, children=None )\n self.myData= myData\n self.children= children if children is not None else []\n def visit( self, aVisitor ):\n aVisitor.at( self )\n aVisitor.down()\n for c in self.children:\n aVisitor.at( c )\n aVisitor.up()\n\nclass Visitor( object ):\n def __init__( self ):\n self.depth= 0\n def down( self ):\n self.depth += 1\n def up( self ):\n self.depth -= 1\n\nI find that this is all I need. And I've found that it's hard to make a reusable module out of this because (a) there's so little here and (b) each application adds or changes so much code.\nFurther, I find that the most commonly used hierarchy is the file system, for which I have the os module. The second most commonly used hierarchy is XML messages, for which I have ElementTree (usually via lxml). After those two, I use the above structures as templates for my classes, not as a literal reusable module.\n", "I recommend digging around xmldifff http://www.logilab.org/859 and seeing how they compare nodes and handle parallel trees. Or, try writing a [recursive] generator that yields each [significant] node in a tree, say f(t), then use itertools.izip(f(t1),f(t2)) to collect together pairs of nodes for comparison.\nMost of the hierarchical structures I deal with have more than one \"axis\", like elements and attributes in XML, and some nodes are more significant than others.\nFor a more bizarre solution, serialize the two trees to text files, make a referential note that line #n comes from node #x in a tree. Do that to both trees, feed the files into diff, and scan the results to notice which parts of the tree have changed. You can map that line #n from file 1 (and therefore node #x in the first tree) and line #m from file 2 (and therefore node #y of the second tree) mean that some part of each tree is the same or different.\nFor any solution your are going to have to establish a \"canonical form\" of your tree, one that might drop all ignorable whitespace, display attributes, optional nodes, etc., from the comparison process. It might also mean doing a breadth first vs. depth first traversal of the tree(s).\n", "http://code.google.com/p/pytree/\nthese maybe overkill or not suited at all for what you need:\nhttp://networkx.lanl.gov/\nhttp://www.osl.iu.edu/~dgregor/bgl-python/\n" ]
[ 4, 2, 1 ]
[]
[]
[ "hierarchy", "module", "python", "traversal", "tree" ]
stackoverflow_0000664898_hierarchy_module_python_traversal_tree.txt
Q: Encoding of string returned by GetUserName() How do I get the encoding that is used for the string returned by GetUserName from the win32 API? I'm using pywin32 and it returns an 8-bit string. On my German XP, this string is obviously encoded using Latin-1, but this might not be the case for other Windows installations. I could use GetUserNameW, but I would have to wrap that myself using ctypes, which I'd like to avoid for now if there is a simpler solution. A: You can call GetACP to find the current ANSI codepage, which is what non-Unicode APIs use. You can also use MultiByteToWideChar, and pass zero as the codepage (CP_ACP is defined as zero in the Windows headers) to convert a codepage string to Unicode. A: I realize this isn't answering your question directly, but I strongly recommend you go through the trouble of using the Unicode-clean GetUserNameW as you mentioned. The non-wide commands work differently on different Windows editions (e.g. ME, although I admit that example is old!), so IMHO it's worth just getting it right. Having done a lot of multi-lingual Windows development, although the wide API can add a layer of translation or wrapping (as you suggest!), it's worth it. A: Okay, here's what I'm using right now: >>> import win32api >>> u = unicode(win32api.GetUserName(), "mbcs") >>> type(u) <type 'unicode'> mbcs is a special standard encoding in Windows: Windows only: Encode operand according to the ANSI codepage (CP_ACP) A: From the API docs, GetUserNameA will return the name in ANSI and GetUserNameW returns the name in Unicode. You will have to use GetUserNameW.
Encoding of string returned by GetUserName()
How do I get the encoding that is used for the string returned by GetUserName from the win32 API? I'm using pywin32 and it returns an 8-bit string. On my German XP, this string is obviously encoded using Latin-1, but this might not be the case for other Windows installations. I could use GetUserNameW, but I would have to wrap that myself using ctypes, which I'd like to avoid for now if there is a simpler solution.
[ "You can call GetACP to find the current ANSI codepage, which is what non-Unicode APIs use. You can also use MultiByteToWideChar, and pass zero as the codepage (CP_ACP is defined as zero in the Windows headers) to convert a codepage string to Unicode.\n", "I realize this isn't answering your question directly, but I strongly recommend you go through the trouble of using the Unicode-clean GetUserNameW as you mentioned.\nThe non-wide commands work differently on different Windows editions (e.g. ME, although I admit that example is old!), so IMHO it's worth just getting it right.\nHaving done a lot of multi-lingual Windows development, although the wide API can add a layer of translation or wrapping (as you suggest!), it's worth it.\n", "Okay, here's what I'm using right now:\n>>> import win32api\n>>> u = unicode(win32api.GetUserName(), \"mbcs\")\n>>> type(u)\n<type 'unicode'>\n\nmbcs is a special standard encoding in Windows:\n\nWindows only: Encode operand according to the ANSI codepage (CP_ACP)\n\n", "From the API docs, GetUserNameA will return the name in ANSI and GetUserNameW returns the name in Unicode. You will have to use GetUserNameW.\n" ]
[ 5, 5, 4, 0 ]
[]
[]
[ "encoding", "python", "pywin32", "winapi" ]
stackoverflow_0000669770_encoding_python_pywin32_winapi.txt
Q: Unable to find files/folders with permissions 777 by AWK/SED/Python Problems to get permissions of each file in every folder to find files which have 777 permissions, and then print the filenames with their paths to a list We can get permissions for files in one folder by ls -ls I do not know how you can get permissions of each file in every folder effectively. How can you find files which have permissions 777 by AWK/SED/Python? A: Are you looking for find? find /some/path -perm 0777 A: find /some/path -perm 0777 -type f
Unable to find files/folders with permissions 777 by AWK/SED/Python
Problems to get permissions of each file in every folder to find files which have 777 permissions, and then print the filenames with their paths to a list We can get permissions for files in one folder by ls -ls I do not know how you can get permissions of each file in every folder effectively. How can you find files which have permissions 777 by AWK/SED/Python?
[ "Are you looking for find?\nfind /some/path -perm 0777\n\n", "find /some/path -perm 0777 -type f\n" ]
[ 6, 4 ]
[]
[]
[ "awk", "python", "sed" ]
stackoverflow_0000670269_awk_python_sed.txt
Q: Any DAL/ORM on GAE? Is there any Database Abstraction Layer (DAL) or Object Relational Mapper (ORM) that works on Google App Engine (GAE), and on normal relational databases (RDBS), other than web2py's? If not, is anybody working on porting one of the existing DAL/ORM to GAE? A: There is an ORM for Google App Engine. There are some differences between it and SQLAlchemy, but looks like it works. Check this page: http://code.google.com/appengine/docs/python/datastore/entitiesandmodels.html A: Web2Py has a DAL that is compatible to GAE. In fact, the whole framework can be deployed to GAE: http://mdp.cti.depaul.edu/examples/default/index A: Currently, it looks like SQLAlchemy is working on it, but it's incomplete / unfinished. Good luck!
Any DAL/ORM on GAE?
Is there any Database Abstraction Layer (DAL) or Object Relational Mapper (ORM) that works on Google App Engine (GAE), and on normal relational databases (RDBS), other than web2py's? If not, is anybody working on porting one of the existing DAL/ORM to GAE?
[ "There is an ORM for Google App Engine. There are some differences between it and SQLAlchemy, but looks like it works. Check this page: http://code.google.com/appengine/docs/python/datastore/entitiesandmodels.html\n", "Web2Py has a DAL that is compatible to GAE. In fact, the whole framework can be deployed to GAE: http://mdp.cti.depaul.edu/examples/default/index\n", "Currently, it looks like SQLAlchemy is working on it, but it's incomplete / unfinished. Good luck!\n" ]
[ 4, 2, 0 ]
[]
[]
[ "data_access_layer", "google_app_engine", "orm", "python", "rdbms" ]
stackoverflow_0000310890_data_access_layer_google_app_engine_orm_python_rdbms.txt
Q: Python : is it ok returning both boolean and string? Original Question I have made a function which is waiting for a particular string to appear on a serial port, and returns all character read until the string was found, or false if not. This is quite convenient, but I was wondering if it is considered bad practice or not ? Clarification : The primary goal is to wait for a particular string to appear in a given amount of time. Except for IO error, the possible outcome is True (the string did appear) or False The secondary goal is to get the entire output, because there might be information that I would like to parse for before the actual answer that is looked for. I thought may be I could combine the primary and secondary goal in one return value. def MyFunc(s, timeout) : test = get_some_input(timeout) if test.endswith(s) return test else return False Edit : Another proposed answer is to raise an exception. I don't think it is a good idea, because the timeout is an expected behaviour. I mean, if there is a parameter for specifying a timeout, then a timeout is a possible outcome, and not an exception. Edit 2 : Since I need to store the input, maybe using a class is the right solution. The wait for function has a clear return value, yet the entire string that was read until timeout is also accessible. class Parser : def __init__(self, sport_name): self.currentMsg = '' self.ser = serial.Serial(sport_name, 115200) def WaitFor(self, s, timeOut=None): self.ser.timeout = timeOut self.currentMsg = '' while self.currentMsg.endswith(s) != True : # should add a try catch here c=self.ser.read() if c != '' : self.currentMsg += c else : print 'timeout waiting for ' + s return False return True A: Would it not be more suitable to return a None instead of False? A: I believe the orthodox Python design would be to return None. The manual says: None This type has a single value. There is a single object with this value. This object is accessed through the built-in name None. It is used to signify the absence of a value in many situations, e.g., it is returned from functions that don’t explicitly return anything. Its truth value is false. A: It would be better to return a string AND a boolean (as in the title) instead of returning a string OR a boolean. You shouldn't have to figure out what the return value means. It should be totally explicit and orthogonal issues should be separated into different variables. (okay,value) = get_some_input(blah); if (okay): print value I tend not to return tuples a lot, because it feels funny. But it's perfectly valid to do so. Returning "None" is a valid solution, already mentioned here. A: The convenient thing is to return an empty string in this case. Besides an empty string in Python will evaluate to False anyway. So you could call it like: if Myfunc(s, timeout): print "success" Addition: As pointed out by S.Lott the true Pythonic way is to return None. Though I choose to return strings in string related funcs. A matter of preference indeed. Also I assume the caller of Myfunc only cares about getting a string to manipulate on - empty or not. If the caller needs to check about timeout issues, etc.. it's better to use exceptions or returning None. A: You could return the string if it arrived in time, or raise a suitable exception indicating time out. A: Maybe if you return a tuple like (False, None) and (True, test) it would be better, as you can evaluate them separatedly and not add unnecesary complexity. EDIT: Perhaps the string that appeared on the serial port is "" (maybe expected), so returning True can say that it arrived that way. A: To add to Ber's point, you might want to take something else into account. If you use an empty string or None, you leave the door open for bugs of the "dumb" variety. On the other hand, if you raise an exception, you're forcing the execution of whatever operation is running to be aborted. For example, consider the following code: result = MyFunc(s, timeout) if result[0] == 'a': do_something() This will raise an exception if the operation timed out and got either an empty string or None. So you'd have to change that to: result = MyFunc(s, timeout) if result and result[0] == 'a': do_something() These kinds of changes tend to add up and make your code more difficult to understand. Of course, I'm sure that your answer to this will be something along the lines of "I won't do that" or "that won't happen" to which my answer is "Even if you don't run into it with this function, you will eventually if you make a habit of doing this." These kinds of bugs are almost always the result of corner cases that you don't usually think about. A: This is a classic use case for Python generators. The yield keyword provides a simple way to iterate over discrete sets without returning the whole thing at once: def MyFunc(s, timeout) : test = get_some_input(timeout) while test.endswith(s) yield test test = get_some_input(timeout) for input in MyFunc(s, timeout): print input The key here is there is no return value to specify the end of input; instead, you simply reach the end of the iterator. More information on generators here.
Python : is it ok returning both boolean and string?
Original Question I have made a function which is waiting for a particular string to appear on a serial port, and returns all character read until the string was found, or false if not. This is quite convenient, but I was wondering if it is considered bad practice or not ? Clarification : The primary goal is to wait for a particular string to appear in a given amount of time. Except for IO error, the possible outcome is True (the string did appear) or False The secondary goal is to get the entire output, because there might be information that I would like to parse for before the actual answer that is looked for. I thought may be I could combine the primary and secondary goal in one return value. def MyFunc(s, timeout) : test = get_some_input(timeout) if test.endswith(s) return test else return False Edit : Another proposed answer is to raise an exception. I don't think it is a good idea, because the timeout is an expected behaviour. I mean, if there is a parameter for specifying a timeout, then a timeout is a possible outcome, and not an exception. Edit 2 : Since I need to store the input, maybe using a class is the right solution. The wait for function has a clear return value, yet the entire string that was read until timeout is also accessible. class Parser : def __init__(self, sport_name): self.currentMsg = '' self.ser = serial.Serial(sport_name, 115200) def WaitFor(self, s, timeOut=None): self.ser.timeout = timeOut self.currentMsg = '' while self.currentMsg.endswith(s) != True : # should add a try catch here c=self.ser.read() if c != '' : self.currentMsg += c else : print 'timeout waiting for ' + s return False return True
[ "Would it not be more suitable to return a None instead of False?\n", "I believe the orthodox Python design would be to return None. The manual says:\n\nNone\nThis type has a single value. There is\n a single object with this value. This\n object is accessed through the\n built-in name None. It is used to\n signify the absence of a value in many\n situations, e.g., it is returned from\n functions that don’t explicitly return\n anything. Its truth value is false.\n\n", "It would be better to return a string AND a boolean (as in the title) instead of returning a string OR a boolean. You shouldn't have to figure out what the return value means. It should be totally explicit and orthogonal issues should be separated into different variables.\n(okay,value) = get_some_input(blah);\nif (okay): print value\n\nI tend not to return tuples a lot, because it feels funny. But it's perfectly valid to do so.\nReturning \"None\" is a valid solution, already mentioned here.\n", "The convenient thing is to return an empty string in this case.\nBesides an empty string in Python will evaluate to False anyway. So you could call it like:\nif Myfunc(s, timeout):\n print \"success\"\n\nAddition: As pointed out by S.Lott the true Pythonic way is to return None. Though I choose to return strings in string related funcs. A matter of preference indeed.\nAlso I assume the caller of Myfunc only cares about getting a string to manipulate on - empty or not. If the caller needs to check about timeout issues, etc.. it's better to use exceptions or returning None.\n", "You could return the string if it arrived in time, or raise a suitable exception indicating time out.\n", "Maybe if you return a tuple like (False, None) and (True, test) it would be better, as you can evaluate them separatedly and not add unnecesary complexity.\nEDIT: Perhaps the string that appeared on the serial port is \"\" (maybe expected), so returning True can say that it arrived that way.\n", "To add to Ber's point, you might want to take something else into account. If you use an empty string or None, you leave the door open for bugs of the \"dumb\" variety. On the other hand, if you raise an exception, you're forcing the execution of whatever operation is running to be aborted.\nFor example, consider the following code:\nresult = MyFunc(s, timeout)\nif result[0] == 'a':\n do_something()\n\nThis will raise an exception if the operation timed out and got either an empty string or None. So you'd have to change that to:\nresult = MyFunc(s, timeout)\nif result and result[0] == 'a':\n do_something()\n\nThese kinds of changes tend to add up and make your code more difficult to understand.\nOf course, I'm sure that your answer to this will be something along the lines of \"I won't do that\" or \"that won't happen\" to which my answer is \"Even if you don't run into it with this function, you will eventually if you make a habit of doing this.\" These kinds of bugs are almost always the result of corner cases that you don't usually think about.\n", "This is a classic use case for Python generators. The yield keyword provides a simple way to iterate over discrete sets without returning the whole thing at once:\ndef MyFunc(s, timeout) :\n test = get_some_input(timeout)\n while test.endswith(s)\n yield test\n test = get_some_input(timeout)\n\nfor input in MyFunc(s, timeout):\n print input\n\nThe key here is there is no return value to specify the end of input; instead, you simply reach the end of the iterator. More information on generators here.\n" ]
[ 27, 11, 8, 6, 5, 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000657857_python.txt
Q: unsubscriptable object I'm using PIL im = Image.open(teh_file) if im: colors = im.resize( (1,1), Image.ANTIALIAS).getpixel((0,0)) # simple way to get average color red = colors[0] # and so on, some operations on color data The problem is, on a few (very few, particulary don't know why those exactly, simple jpegs) I get 'unsubscriptable object' on line "colors[0]". Tried: if colors: gets true and goes on. if len(colors): gives 'len() of unsized object' What condition should I apply not to get this exception? What's the cause of the problem? A: From the PIL docs: getpixel im.getpixel(xy) => value or tuple Returns the pixel at the given position. If the image is a multi-layer image, this method returns a tuple. So it seems that some of your images are multilayer, and some are single-layer. A: As noted in another answer, getpixel returns either a single value, or a tuple. You could check the type and do the appropriate action in the following ways: if isinstance(colors, tuple): color = colors[0] else: color = colors # Do other stuff or: try: color = colors[0] except: # Whatever the exception is - IndexError or whatever color = colors # Do other stuff The second way is probably more Pythonic. A: Ok the case was, that when B&W images have no RGB band (L band), it returns an integer with the pixel color single value, not a list of rgb values. The solution is to check bands im.getbands() or the simpler for my needs was: if isinstance(colors, tuple): values = {'r':colors[0], 'g':colors[1], 'b':colors[2]} else: values = {'r':colors, 'g':colors, 'b':colors}
unsubscriptable object
I'm using PIL im = Image.open(teh_file) if im: colors = im.resize( (1,1), Image.ANTIALIAS).getpixel((0,0)) # simple way to get average color red = colors[0] # and so on, some operations on color data The problem is, on a few (very few, particulary don't know why those exactly, simple jpegs) I get 'unsubscriptable object' on line "colors[0]". Tried: if colors: gets true and goes on. if len(colors): gives 'len() of unsized object' What condition should I apply not to get this exception? What's the cause of the problem?
[ "From the PIL docs:\ngetpixel\n\nim.getpixel(xy) => value or tuple\n\nReturns the pixel at the given position. If the image is a multi-layer image, this method returns a tuple.\n\nSo it seems that some of your images are multilayer, and some are single-layer.\n", "As noted in another answer, getpixel returns either a single value, or a tuple. You could check the type and do the appropriate action in the following ways:\nif isinstance(colors, tuple):\n color = colors[0]\nelse:\n color = colors\n# Do other stuff\n\nor:\ntry:\n color = colors[0]\nexcept: # Whatever the exception is - IndexError or whatever\n color = colors\n# Do other stuff\n\nThe second way is probably more Pythonic.\n", "Ok the case was, that when B&W images have no RGB band (L band), it returns an integer with the pixel color single value, not a list of rgb values. The solution is to check bands\nim.getbands()\n\nor the simpler for my needs was:\n if isinstance(colors, tuple):\n values = {'r':colors[0], 'g':colors[1], 'b':colors[2]}\n else:\n values = {'r':colors, 'g':colors, 'b':colors}\n\n" ]
[ 4, 2, 2 ]
[]
[]
[ "colors", "image", "image_processing", "python", "python_imaging_library" ]
stackoverflow_0000671363_colors_image_image_processing_python_python_imaging_library.txt
Q: How do I create a D-Bus service that dynamically creates multiple objects? I'm new to D-Bus (and to Python, double whammy!) and I am trying to figure out the best way to do something that was discussed in the tutorial. However, a text editor application could as easily own multiple bus names (for example, org.kde.KWrite in addition to generic TextEditor), have multiple objects (maybe /org/kde/documents/4352 where the number changes according to the document), and each object could implement multiple interfaces, such as org.freedesktop.DBus.Introspectable, org.freedesktop.BasicTextField, org.kde.RichTextDocument. For example, say I want to create a wrapper around flickrapi such that the service can expose a handful of Flickr API methods (say, urls_lookupGroup()). This is relatively straightforward if I want to assume that the service will always be specifying the same API key and that the auth information will be the same for everyone using the service. Especially in the latter case, I cannot really assume this will be true. Based on the documentation quoted above, I am assuming there should be something like this: # Get the connection proxy object. flickrConnectionService = bus.get_object("com.example.FlickrService", "/Connection") # Ask the connection object to connect, the return value would be # maybe something like "/connection/5512" ... flickrObjectPath = flickrConnectionService.connect("MY_APP_API_KEY", "MY_APP_API_SECRET", flickrUsername) # Get the service proxy object. flickrService = bus.get_object("com.example.FlickrService", flickrObjectPath); # As the flickr service object to get group information. groupInfo = flickrService.getFlickrGroupInfo('s3a-belltown') So, my questions: 1) Is this how this should be handled? 2) If so, how will the service know when the client is done? Is there a way to detect if the current client has broken connection so that the service can cleanup its dynamically created objects? Also, how would I create the individual objects in the first place? 3) If this is not how this should be handled, what are some other suggestions for accomplishing something similar? I've read through a number of D-Bus tutorials and various documentation and about the closest I've come to seeing what I am looking for is what I quoted above. However, none of the examples look to actually do anything like this so I am not sure how to proceed. A: 1) Mostly yes, I would only change one thing in the connect method as I explain in 2). 2) D-Bus connections are not persistent, everything is done with request/response messages, no connection state is stored unless you implement this in third objects as you do with your flickerObject. The d-bus objects in python bindings are mostly proxies that abstract the remote objects as if you were "connected" to them, but what it really does is to build messages based on the information you give to D-Bus object instantiation (object path, interface and so). So the service cannot know when the client is done if client doesn't announce it with other explicit call. To handle unexpected client finalization you can create a D-Bus object in the client and send the object path to the service when connecting, change your connect method to accept also an ObjectPath parameter. The service can listen to NameOwnerChanged signal to know if a client has died. To create the individual object you only have to instantiate an object in the same service as you do with your "/Connection", but you have to be sure that you are using an unexisting name. You could have a "/Connection/Manager", and various "/Connection/1", "/Connection/2"... 3) If you need to store the connection state, you have to do something like that.
How do I create a D-Bus service that dynamically creates multiple objects?
I'm new to D-Bus (and to Python, double whammy!) and I am trying to figure out the best way to do something that was discussed in the tutorial. However, a text editor application could as easily own multiple bus names (for example, org.kde.KWrite in addition to generic TextEditor), have multiple objects (maybe /org/kde/documents/4352 where the number changes according to the document), and each object could implement multiple interfaces, such as org.freedesktop.DBus.Introspectable, org.freedesktop.BasicTextField, org.kde.RichTextDocument. For example, say I want to create a wrapper around flickrapi such that the service can expose a handful of Flickr API methods (say, urls_lookupGroup()). This is relatively straightforward if I want to assume that the service will always be specifying the same API key and that the auth information will be the same for everyone using the service. Especially in the latter case, I cannot really assume this will be true. Based on the documentation quoted above, I am assuming there should be something like this: # Get the connection proxy object. flickrConnectionService = bus.get_object("com.example.FlickrService", "/Connection") # Ask the connection object to connect, the return value would be # maybe something like "/connection/5512" ... flickrObjectPath = flickrConnectionService.connect("MY_APP_API_KEY", "MY_APP_API_SECRET", flickrUsername) # Get the service proxy object. flickrService = bus.get_object("com.example.FlickrService", flickrObjectPath); # As the flickr service object to get group information. groupInfo = flickrService.getFlickrGroupInfo('s3a-belltown') So, my questions: 1) Is this how this should be handled? 2) If so, how will the service know when the client is done? Is there a way to detect if the current client has broken connection so that the service can cleanup its dynamically created objects? Also, how would I create the individual objects in the first place? 3) If this is not how this should be handled, what are some other suggestions for accomplishing something similar? I've read through a number of D-Bus tutorials and various documentation and about the closest I've come to seeing what I am looking for is what I quoted above. However, none of the examples look to actually do anything like this so I am not sure how to proceed.
[ "1) Mostly yes, I would only change one thing in the connect method as I explain in 2). \n2) D-Bus connections are not persistent, everything is done with request/response messages, no connection state is stored unless you implement this in third objects as you do with your flickerObject. The d-bus objects in python bindings are mostly proxies that abstract the remote objects as if you were \"connected\" to them, but what it really does is to build messages based on the information you give to D-Bus object instantiation (object path, interface and so). So the service cannot know when the client is done if client doesn't announce it with other explicit call.\nTo handle unexpected client finalization you can create a D-Bus object in the client and send the object path to the service when connecting, change your connect method to accept also an ObjectPath parameter. The service can listen to NameOwnerChanged signal to know if a client has died.\nTo create the individual object you only have to instantiate an object in the same service as you do with your \"/Connection\", but you have to be sure that you are using an unexisting name. You could have a \"/Connection/Manager\", and various \"/Connection/1\", \"/Connection/2\"...\n3) If you need to store the connection state, you have to do something like that.\n" ]
[ 2 ]
[]
[]
[ "dbus", "python" ]
stackoverflow_0000667760_dbus_python.txt
Q: How do you send AT GSM commands using python? How do i send AT GSM commands using python? Am able to do this quite easily using Delphi and some comport component (TComport), but how do i talk to my modem using python? Gath A: I do it like this with pyserial: import serial serialPort = serial.Serial(port=1,baudrate=115200,timeout=0,rtscts=0,xonxoff=0) def sendatcmd(cmd): serialPort.write('at'+cmd+'\r') print 'Loading profile...', sendatcmd('+npsda=0,2') Then I listen for an answer... A: I don't know if there is an AT module, but you can use pyserial to communicate with a serial port.
How do you send AT GSM commands using python?
How do i send AT GSM commands using python? Am able to do this quite easily using Delphi and some comport component (TComport), but how do i talk to my modem using python? Gath
[ "I do it like this with pyserial:\nimport serial\n\nserialPort = serial.Serial(port=1,baudrate=115200,timeout=0,rtscts=0,xonxoff=0)\ndef sendatcmd(cmd):\n serialPort.write('at'+cmd+'\\r')\n\nprint 'Loading profile...',\nsendatcmd('+npsda=0,2')\n\nThen I listen for an answer...\n", "I don't know if there is an AT module, but you can use pyserial to communicate with a serial port.\n" ]
[ 15, 4 ]
[]
[]
[ "modem", "python" ]
stackoverflow_0000672366_modem_python.txt
Q: Getting the value of href attributes in all tags on a html file with Python I'm building an app in python, and I need to get the URL of all links in one webpage. I already have a function that uses urllib to download the html file from the web, and transform it to a list of strings with readlines(). Currently I have this code that uses regex (I'm not very good at it) to search for links in every line: for line in lines: result = re.match ('/href="(.*)"/iU', line) print result This is not working, as it only prints "None" for every line in the file, but I'm sure that at least there are 3 links on the file I'm opening. Can someone give me a hint on this? Thanks in advance A: Beautiful Soup can do this almost trivially: from BeautifulSoup import BeautifulSoup as soup html = soup('<body><a href="123">qwe</a><a href="456">asd</a></body>') print [tag.attrMap['href'] for tag in html.findAll('a', {'href': True})] A: Another alternative to BeautifulSoup is lxml (http://lxml.de/); import lxml.html links = lxml.html.parse("http://stackoverflow.com/").xpath("//a/@href") for link in links: print link A: There's an HTML parser that comes standard in Python. Checkout htmllib. A: What others haven't told you is that using regular expressions for this is not a reliable solution. Using regular expression will give you wrong results on many situations: if there are <A> tags that are commented out, or if there are text in the page which include the string "href=", or if there are <textarea> elements with html code in it, and many others. Plus, the href attribute may exist on tags other that the anchor tag. What you need for this is XPath, which is a query language for DOM trees, i.e. it lets you retrieve any set of nodes satisfying the conditions you specify (HTML attributes are nodes in the DOM). XPath is a well standarized language now a days (W3C), and is well supported by all major languages. I strongly suggest you use XPath and not regexp for this. adw's answer shows one example of using XPath for your particular case. A: As previously mentioned: regex does not have the power to parse HTML. Do not use regex for parsing HTML. Do not pass Go. Do not collect £200. Use an HTML parser. But for completeness, the primary problem is: re.match ('/href="(.*)"/iU', line) You don't use the “/.../flags” syntax for decorating regexes in Python. Instead put the flags in a separate argument: re.match('href="(.*)"', line, re.I|re.U) Another problem is the greedy ‘.*’ pattern. If you have two hrefs in a line, it'll happily suck up all the content between the opening " of the first match and the closing " of the second match. You can use the non-greedy ‘.*?’ or, more simply, ‘[^"]*’ to only match up to the first closing quote. But don't use regexes for parsing HTML. Really. A: Don't divide the html content into lines, as there maybe multiple matches in a single line. Also don't assume there is always quotes around the url. Do something like this: links = re.finditer(' href="?([^\s^"]+)', content) for link in links: print link A: Well, just for completeness I will add here what I found to be the best answer, and I found it on the book Dive Into Python, from Mark Pilgrim. Here follows the code to list all URL's from a webpage: from sgmllib import SGMLParser class URLLister(SGMLParser): def reset(self): SGMLParser.reset(self) self.urls = [] def start_a(self, attrs): href = [v for k, v in attrs if k=='href'] if href: self.urls.extend(href) import urllib, urllister usock = urllib.urlopen("http://diveintopython.net/") parser = urllister.URLLister() parser.feed(usock.read()) usock.close() parser.close() for url in parser.urls: print url Thanks for all the replies.
Getting the value of href attributes in all tags on a html file with Python
I'm building an app in python, and I need to get the URL of all links in one webpage. I already have a function that uses urllib to download the html file from the web, and transform it to a list of strings with readlines(). Currently I have this code that uses regex (I'm not very good at it) to search for links in every line: for line in lines: result = re.match ('/href="(.*)"/iU', line) print result This is not working, as it only prints "None" for every line in the file, but I'm sure that at least there are 3 links on the file I'm opening. Can someone give me a hint on this? Thanks in advance
[ "Beautiful Soup can do this almost trivially:\nfrom BeautifulSoup import BeautifulSoup as soup\n\nhtml = soup('<body><a href=\"123\">qwe</a><a href=\"456\">asd</a></body>')\nprint [tag.attrMap['href'] for tag in html.findAll('a', {'href': True})]\n\n", "Another alternative to BeautifulSoup is lxml (http://lxml.de/);\nimport lxml.html\nlinks = lxml.html.parse(\"http://stackoverflow.com/\").xpath(\"//a/@href\")\nfor link in links:\n print link\n\n", "There's an HTML parser that comes standard in Python. Checkout htmllib.\n", "What others haven't told you is that using regular expressions for this is not a reliable solution.\nUsing regular expression will give you wrong results on many situations: if there are <A> tags that are commented out, or if there are text in the page which include the string \"href=\", or if there are <textarea> elements with html code in it, and many others. Plus, the href attribute may exist on tags other that the anchor tag.\nWhat you need for this is XPath, which is a query language for DOM trees, i.e. it lets you retrieve any set of nodes satisfying the conditions you specify (HTML attributes are nodes in the DOM).\nXPath is a well standarized language now a days (W3C), and is well supported by all major languages. I strongly suggest you use XPath and not regexp for this.\nadw's answer shows one example of using XPath for your particular case.\n", "As previously mentioned: regex does not have the power to parse HTML. Do not use regex for parsing HTML. Do not pass Go. Do not collect £200.\nUse an HTML parser.\nBut for completeness, the primary problem is:\nre.match ('/href=\"(.*)\"/iU', line)\n\nYou don't use the “/.../flags” syntax for decorating regexes in Python. Instead put the flags in a separate argument:\nre.match('href=\"(.*)\"', line, re.I|re.U)\n\nAnother problem is the greedy ‘.*’ pattern. If you have two hrefs in a line, it'll happily suck up all the content between the opening \" of the first match and the closing \" of the second match. You can use the non-greedy ‘.*?’ or, more simply, ‘[^\"]*’ to only match up to the first closing quote.\nBut don't use regexes for parsing HTML. Really.\n", "Don't divide the html content into lines, as there maybe multiple matches in a single line. Also don't assume there is always quotes around the url. \nDo something like this:\nlinks = re.finditer(' href=\"?([^\\s^\"]+)', content)\n\nfor link in links:\n print link\n\n", "Well, just for completeness I will add here what I found to be the best answer, and I found it on the book Dive Into Python, from Mark Pilgrim.\nHere follows the code to list all URL's from a webpage:\nfrom sgmllib import SGMLParser\n\nclass URLLister(SGMLParser):\n def reset(self): \n SGMLParser.reset(self)\n self.urls = []\n\n def start_a(self, attrs): \n href = [v for k, v in attrs if k=='href'] \n if href:\n self.urls.extend(href)\n\nimport urllib, urllister\nusock = urllib.urlopen(\"http://diveintopython.net/\")\nparser = urllister.URLLister()\nparser.feed(usock.read()) \nusock.close() \nparser.close() \nfor url in parser.urls: print url\n\nThanks for all the replies.\n" ]
[ 11, 8, 4, 3, 3, 1, 1 ]
[]
[]
[ "html", "parsing", "python", "regex" ]
stackoverflow_0000671323_html_parsing_python_regex.txt
Q: On interface up, possible to scan for a specific MAC address? I admit the linux network system is somewhat foreign to me, I know enough of it to configure routes manually and assign a static IP if necessary. So quick question, in the ifconfig configuration files, is it possible to add a post connect hook to a python script then use a python script to reassign a hostname in /etc/hosts and spawn off a new process to do other things once the hostname has been updated. This is a "fun" project for me to solve an annoyance in my daily routine. When I boot up my workstation in the morning, the DHCP service assigns it a IP at random. So I usually stop what I'm doing, lookup my new IP, type that IP into my laptop and get synergy running so I can share the two machines. I figure I lose 10-15 minutes a day doing this everyday of the week and I've never really messed with linux's networking system so it would ultimately pan out. I already figured my python script would have to run as root, therefore I'd store it in /root or somewhere else that's safe. I found a similar question on stack overflow that pointed me in the direction of http://www.secdev.org/projects/scapy/index.html a raw packet toolset to work with ARP. Editing the host file is a snap... just wondering what possible side effects of trying to put this hook into a core service might cause. A: Just make sure Avahi / Bonjour's running, then type hostname.local (or also try hostname.localdomain) - it resolves using mDNS, so you don't have to care what your IP is or rigging /etc/hosts. A: Sorry, it looks like an attempt to create a problem where no problem exists, and subsequently solve it using a bit crazy methods. :) You can configure your dhcp server (router) to always issue a fixed ip for your workstation. If you don't have dhcp server, then why do you use dhcp for configuring the interface? Change the configuration (/etc/network/interfaces in Ubuntu and Debian) to assign static ip address to the interface. A: Cleanest solution would be to have a DHCP server that exchanges its assignments with a local DNS server. So regardless which IP address your workstation is being assigned to, it is accessible under the same hostname. This concept is used in every full-blown windows network as well as in any other well configured network. A: You could also use arp-scan (a Debian package of the name exists, not sure about other distributions) to scan your whole network. Have a script parse its output and you'll be all set.
On interface up, possible to scan for a specific MAC address?
I admit the linux network system is somewhat foreign to me, I know enough of it to configure routes manually and assign a static IP if necessary. So quick question, in the ifconfig configuration files, is it possible to add a post connect hook to a python script then use a python script to reassign a hostname in /etc/hosts and spawn off a new process to do other things once the hostname has been updated. This is a "fun" project for me to solve an annoyance in my daily routine. When I boot up my workstation in the morning, the DHCP service assigns it a IP at random. So I usually stop what I'm doing, lookup my new IP, type that IP into my laptop and get synergy running so I can share the two machines. I figure I lose 10-15 minutes a day doing this everyday of the week and I've never really messed with linux's networking system so it would ultimately pan out. I already figured my python script would have to run as root, therefore I'd store it in /root or somewhere else that's safe. I found a similar question on stack overflow that pointed me in the direction of http://www.secdev.org/projects/scapy/index.html a raw packet toolset to work with ARP. Editing the host file is a snap... just wondering what possible side effects of trying to put this hook into a core service might cause.
[ "Just make sure Avahi / Bonjour's running, then type hostname.local (or also try hostname.localdomain) - it resolves using mDNS, so you don't have to care what your IP is or rigging /etc/hosts.\n", "Sorry, it looks like an attempt to create a problem where no problem exists, and subsequently solve it using a bit crazy methods. :)\nYou can configure your dhcp server (router) to always issue a fixed ip for your workstation. If you don't have dhcp server, then why do you use dhcp for configuring the interface? Change the configuration (/etc/network/interfaces in Ubuntu and Debian) to assign static ip address to the interface.\n", "Cleanest solution would be to have a DHCP server that exchanges its assignments with a local DNS server. So regardless which IP address your workstation is being assigned to, it is accessible under the same hostname. \nThis concept is used in every full-blown windows network as well as in any other well configured network.\n", "You could also use arp-scan (a Debian package of the name exists, not sure about other distributions) to scan your whole network. Have a script parse its output and you'll be all set.\n" ]
[ 1, 1, 1, 0 ]
[]
[]
[ "linux", "networking", "python", "sysadmin" ]
stackoverflow_0000637399_linux_networking_python_sysadmin.txt
Q: Python Programming - Rules/Advice for developing enterprise-level software in Python? I'm a somewhat advanced C++/Java Developer who recently became interested in Python and I enjoy its dynamic typing and efficient coding style very much. I currently use it on my small programming needs like solving programming riddles and scripting, but I'm curious if anyone out there has successfully used Python in an enterprise-quality project? (Preferably using modern programming concepts such as OOP and some type of Design Pattern) If so, would you please explain why you chose Python (specifically) and give us some of the lessons you learned from this project? (Feel free to compare the use of Python in the project vs Java or etc) A: I'm using Python for developing a complex insurance underwriting application. Our application software essentially repackages our actuarial model in a form that companies can subscribe to it. This business is based on our actuaries and their deep thinking. We're not packaging a clever algorithm that's relatively fixed. We're renting our actuarial brains to customers via a web service. The actuaries must be free to make changes as they gain deeper insight into the various factors that lead to claims. Static languages (Java, C++, C#) lead to early lock-in to a data model. Python allows us to have a very flexible data model. They're free to add, change or delete factors or information sources without a lot of development cost and complexity. Duck typing allows us to introduce new pieces without a lot rework. Our software is a service (not a package) so we have an endless integration problem. Static languages need complex mapping components. Often some kind of configurable, XML-driven mapping from customer messages to our ever-changing internal structures. Python allows us to have the mappings as a simple Python class definition that we simply tweak, test and put into production. There are no limitations on this module -- it's first-class Python code. We have to do extensive, long-running proof-of-concept. These involve numerous "what-if" scenarios with different data feeds and customized features. Static languages require a lot of careful planning and thinking to create yet another demo, yet another mapping from yet another customer-supplied file to the current version of our actuarial models. Python requires much less planning. Duck typing (and Django) let us knock out a demo without very much pain. The data mappings are simple python class definitions; our actuarial models are in a fairly constant state of flux. Our business model is subject to a certain amount of negotiation. We have rather complex contracts with information providers; these don't change as often as the actuarial model, but changes here require customization. Static languages bind in assumptions about the contracts, and require fairly complex designs (or workarounds) to handle the brain-farts of the business folks negotiating the deals. In Python, we use an extensive test suite and do a lot of refactoring as the various contract terms and conditions trickle down to us. Every week we get a question like "Can we handle a provision like X?" Our standard answer is "Absolutely." Followed by an hour of refactoring to be sure we could handle it if the deal was struck in that form. We're mostly a RESTful web service. Django does a lot of this out of the box. We had to write some extensions because our security model is a bit more strict than the one provided by Django. Static languages don't have to ship source. Don't like the security model? Pay the vendor $$$. Dynamic languages must ship as source. In our case, we spend time reading the source of Django carefully to make sure that our security model fits cleanly with the rest of Django. We don't need HIPAA compliance, but we're building it in anyway. We use web services from information providers. urllib2 does this for us nicely. We can prototype an interface rapidly. With a static language, you have API's, you write, you run, and you hope it worked. The development cycle is Edit, Compile, Build, Run, Crash, Look at Logs; and this is just to spike the interface and be sure we have the protocol, credentials and configuration right. We exercise the interface in interactive Python. Since we're executing it interactively, we can examine the responses immediately. The development cycle is reduced to Run, Edit. We can spike a web services API in an afternoon. A: I've been using Python as distributed computing framework in one of the worlds largest banks. It was chosen because: It had to be extremely fast for developing and deploying new functionalities; It had to be easily integrable with C and C++; Some parts of the code were to be written by people whose area of expertise was mathematical modeling, not software development.
Python Programming - Rules/Advice for developing enterprise-level software in Python?
I'm a somewhat advanced C++/Java Developer who recently became interested in Python and I enjoy its dynamic typing and efficient coding style very much. I currently use it on my small programming needs like solving programming riddles and scripting, but I'm curious if anyone out there has successfully used Python in an enterprise-quality project? (Preferably using modern programming concepts such as OOP and some type of Design Pattern) If so, would you please explain why you chose Python (specifically) and give us some of the lessons you learned from this project? (Feel free to compare the use of Python in the project vs Java or etc)
[ "I'm using Python for developing a complex insurance underwriting application.\nOur application software essentially repackages our actuarial model in a form that companies can subscribe to it. This business is based on our actuaries and their deep thinking. We're not packaging a clever algorithm that's relatively fixed. We're renting our actuarial brains to customers via a web service.\n\nThe actuaries must be free to make changes as they gain deeper insight into the various factors that lead to claims.\n\nStatic languages (Java, C++, C#) lead to early lock-in to a data model.\nPython allows us to have a very flexible data model. They're free to add, change or delete factors or information sources without a lot of development cost and complexity. Duck typing allows us to introduce new pieces without a lot rework.\n\nOur software is a service (not a package) so we have an endless integration problem.\n\nStatic languages need complex mapping components. Often some kind of configurable, XML-driven mapping from customer messages to our ever-changing internal structures.\nPython allows us to have the mappings as a simple Python class definition that we simply tweak, test and put into production. There are no limitations on this module -- it's first-class Python code.\n\nWe have to do extensive, long-running proof-of-concept. These involve numerous \"what-if\" scenarios with different data feeds and customized features.\n\nStatic languages require a lot of careful planning and thinking to create yet another demo, yet another mapping from yet another customer-supplied file to the current version of our actuarial models.\nPython requires much less planning. Duck typing (and Django) let us knock out a demo without very much pain. The data mappings are simple python class definitions; our actuarial models are in a fairly constant state of flux.\n\nOur business model is subject to a certain amount of negotiation. We have rather complex contracts with information providers; these don't change as often as the actuarial model, but changes here require customization.\n\nStatic languages bind in assumptions about the contracts, and require fairly complex designs (or workarounds) to handle the brain-farts of the business folks negotiating the deals.\nIn Python, we use an extensive test suite and do a lot of refactoring as the various contract terms and conditions trickle down to us. \n\nEvery week we get a question like \"Can we handle a provision like X?\" Our standard answer is \"Absolutely.\" Followed by an hour of refactoring to be sure we could handle it if the deal was struck in that form.\nWe're mostly a RESTful web service. Django does a lot of this out of the box. We had to write some extensions because our security model is a bit more strict than the one provided by Django. \n\nStatic languages don't have to ship source. Don't like the security model? Pay the vendor $$$.\nDynamic languages must ship as source. In our case, we spend time reading the source of Django carefully to make sure that our security model fits cleanly with the rest of Django. We don't need HIPAA compliance, but we're building it in anyway. \n\nWe use web services from information providers. urllib2 does this for us nicely. We can prototype an interface rapidly. \n\nWith a static language, you have API's, you write, you run, and you hope it worked. The development cycle is Edit, Compile, Build, Run, Crash, Look at Logs; and this is just to spike the interface and be sure we have the protocol, credentials and configuration right.\nWe exercise the interface in interactive Python. Since we're executing it interactively, we can examine the responses immediately. The development cycle is reduced to Run, Edit. We can spike a web services API in an afternoon.\n\n\n", "I've been using Python as distributed computing framework in one of the worlds largest banks. \nIt was chosen because:\n\nIt had to be extremely fast for developing and deploying new functionalities;\nIt had to be easily integrable with C and C++; \nSome parts of the code were to be written by people whose area of expertise was mathematical modeling, not software development.\n\n" ]
[ 17, 3 ]
[]
[]
[ "design_patterns", "dynamic_typing", "java", "programming_languages", "python" ]
stackoverflow_0000672781_design_patterns_dynamic_typing_java_programming_languages_python.txt
Q: Django Custom Queryset filters Is there, in Django, a standard way to write complex, custom filters for QuerySets? Just as I can write MyClass.objects.all().filter(field=val) I'd like to do something like this : MyClass.objects.all().filter(customFilter) I could use a generator expression (x for x in MyClass.objects.all() if customFilter(x)) but that would lose the chainability and whatever other functions the QuerySets provide. A: The recommendation to start using manager methods is a good one, but to answer your question more directly: yes, use Q objects. For example: from django.db.models import Q complexQuery = Q(name__startswith='Xa') | ~Q(birthdate__year=2000) MyModel.objects.filter(complexQuery) Q objects can be combined with | (OR), & (AND), and ~ (NOT). A: I think you may need custom managers.
Django Custom Queryset filters
Is there, in Django, a standard way to write complex, custom filters for QuerySets? Just as I can write MyClass.objects.all().filter(field=val) I'd like to do something like this : MyClass.objects.all().filter(customFilter) I could use a generator expression (x for x in MyClass.objects.all() if customFilter(x)) but that would lose the chainability and whatever other functions the QuerySets provide.
[ "The recommendation to start using manager methods is a good one, but to answer your question more directly: yes, use Q objects. For example:\nfrom django.db.models import Q\n\ncomplexQuery = Q(name__startswith='Xa') | ~Q(birthdate__year=2000)\n\nMyModel.objects.filter(complexQuery)\n\nQ objects can be combined with | (OR), & (AND), and ~ (NOT).\n", "I think you may need custom managers.\n" ]
[ 16, 9 ]
[]
[]
[ "django", "django_queryset", "generator_expression", "python" ]
stackoverflow_0000672182_django_django_queryset_generator_expression_python.txt
Q: What signals should I catch for clipboard pasting and character insertion in GTK? I have a Window with a TextView, and I would like to perform some actions when the user pastes some text. I would also like to know what signal(s) should I catch in order to perform something when the user presses a key inside the TextView. Can you tell me what are the signals I must connect? A: For paste: Take a look at the paste-done signal of the GtkTextBuffer class, it sounds about right. For regular character insert: insert-text.
What signals should I catch for clipboard pasting and character insertion in GTK?
I have a Window with a TextView, and I would like to perform some actions when the user pastes some text. I would also like to know what signal(s) should I catch in order to perform something when the user presses a key inside the TextView. Can you tell me what are the signals I must connect?
[ "For paste: Take a look at the paste-done signal of the GtkTextBuffer class, it sounds about right.\nFor regular character insert: insert-text.\n" ]
[ 2 ]
[]
[]
[ "clipboard", "gtk", "pygtk", "python", "signals" ]
stackoverflow_0000673605_clipboard_gtk_pygtk_python_signals.txt
Q: python: arbitrary order by In Oracle SQL there is a feature to order as follow: order by decode("carrot" = 2 ,"banana" = 1 ,"apple" = 3) What is the best way to implement this in python? I want to be able to order a dict by its keys. And that order isn't necessarily alphabetically or anything - I determine the order. A: Use the key named keyword argument of sorted(). #set up the order you want the keys to appear here order = ["banana", "carrot", "apple"] # this uses the order list to sort the actual keys. sorted(keys, key=order.index) For higher performance than list.index, you could use dict.get instead. #this builds a dictionary to lookup the desired ordering order = dict((key, idx) for idx, key in enumerate(["banana", "carrot", "apple"])) # this uses the order dict to sort the actual keys. sorted(keys, key=order.get) A: You can't order a dict per se, but you can convert it to a list of (key, value) tuples, and you can sort that. You use the .items() method to do that. For example, >>> {'a': 1, 'b': 2} {'a': 1, 'b': 2} >>> {'a': 1, 'b': 2}.items() [('a', 1), ('b', 2)] Most efficient way to sort that is to use a key function. using cmp is less efficient because it has to be called for every pair of items, where using key it only needs to be called once for every item. Just specify a callable that will transform the item according to how it should be sorted: sorted(somedict.items(), key=lambda x: {'carrot': 2, 'banana': 1, 'apple':3}[x[0]]) The above defines a dict that specifies the custom order of the keys that you want, and the lambda returns that value for each key in the old dict. A: Python's dict is a hashmap, so it has no order. But you can sort the keys separately, extracting them from the dictionary with keys() method. sorted() takes comparison and key functions as arguments. You can do exact copy of your decode with sortedKeys = sorted(dictionary, {"carrot": 2 ,"banana": 1 ,"apple": 3}.get); A: You can't sort a dictionary; a dictionary is a mapping and a mapping has no ordering. You could extract the keys and sort those, however: keys = myDict.keys() sorted_keys = sorted(keys, myCompare) A: There will be OrderedDict in new Python versions: http://www.python.org/dev/peps/pep-0372/. Meanwhile, you can try one of the alternative implementations: http://code.activestate.com/recipes/496761/, Ordered Dictionary. A: A dict is not ordered. You will need to keep a list of keys. You can pass your own comparison function to list.sort() or sorted(). If you need to sort on multiple keys, just concatenate them in a tuple, and sort on the tuple.
python: arbitrary order by
In Oracle SQL there is a feature to order as follow: order by decode("carrot" = 2 ,"banana" = 1 ,"apple" = 3) What is the best way to implement this in python? I want to be able to order a dict by its keys. And that order isn't necessarily alphabetically or anything - I determine the order.
[ "Use the key named keyword argument of sorted().\n#set up the order you want the keys to appear here\norder = [\"banana\", \"carrot\", \"apple\"]\n\n# this uses the order list to sort the actual keys.\nsorted(keys, key=order.index)\n\nFor higher performance than list.index, you could use dict.get instead.\n#this builds a dictionary to lookup the desired ordering\norder = dict((key, idx) for idx, key in enumerate([\"banana\", \"carrot\", \"apple\"]))\n\n# this uses the order dict to sort the actual keys.\nsorted(keys, key=order.get)\n\n", "You can't order a dict per se, but you can convert it to a list of (key, value) tuples, and you can sort that.\nYou use the .items() method to do that. For example,\n>>> {'a': 1, 'b': 2}\n{'a': 1, 'b': 2}\n>>> {'a': 1, 'b': 2}.items()\n[('a', 1), ('b', 2)]\n\nMost efficient way to sort that is to use a key function. using cmp is less efficient because it has to be called for every pair of items, where using key it only needs to be called once for every item. Just specify a callable that will transform the item according to how it should be sorted:\nsorted(somedict.items(), key=lambda x: {'carrot': 2, 'banana': 1, 'apple':3}[x[0]])\n\nThe above defines a dict that specifies the custom order of the keys that you want, and the lambda returns that value for each key in the old dict.\n", "Python's dict is a hashmap, so it has no order. But you can sort the keys separately, extracting them from the dictionary with keys() method.\nsorted() takes comparison and key functions as arguments.\nYou can do exact copy of your decode with\nsortedKeys = sorted(dictionary, {\"carrot\": 2\n ,\"banana\": 1\n ,\"apple\": 3}.get);\n\n", "You can't sort a dictionary; a dictionary is a mapping and a mapping has no ordering.\nYou could extract the keys and sort those, however:\nkeys = myDict.keys()\nsorted_keys = sorted(keys, myCompare)\n\n", "There will be OrderedDict in new Python versions: http://www.python.org/dev/peps/pep-0372/.\nMeanwhile, you can try one of the alternative implementations: http://code.activestate.com/recipes/496761/, Ordered Dictionary.\n", "A dict is not ordered. You will need to keep a list of keys.\nYou can pass your own comparison function to list.sort() or sorted().\nIf you need to sort on multiple keys, just concatenate them in a tuple, and sort on the tuple.\n" ]
[ 17, 4, 2, 1, 1, 0 ]
[]
[]
[ "python", "sql_order_by" ]
stackoverflow_0000673867_python_sql_order_by.txt
Q: Using PiL to take a screenshot of HTML/CSS I want to enable a user on a website to upload an image, and write some text over it. Also, they should be able to crop/scale/move the image and text. For that stuff, I can do it in jQuery. After they've made the image the way they want it, is there a way i can take a screenshot of that image (using PiL) and save it on the server? What is the best/proper way to do this? A: Taking a "screenshot" of the picture is neither the best, nor the proper way to do it. To take a screenshot, you need to execute code on the client machine, which is "not possible" in a website scenario. Have a look at lolcat builder (I can't think of a more serious example right now ;). Everytime you click the "Preview" button, the image src is updated with an url containing the text, its style and position. The request is handled by the server which will generate a new picture to display. A: I assume you got Python on the server side. The best way imo is to somehow 'get' all the editing parameters from the client, then re-render it using PIL. Update: How I will do it On the server side, you need an url to handle posts. On the client side, (after each edit, )send a post to that url, with the editing parameters. I think there is not an easy solution to this. Maybe if you don't use PIL to render the final image, but only remember the parameters, each view from clients can render itself? A: PIL isn't available on the client side.. so unless, as Jack Ha suggests, you intend to upload all the instructions of your image editing to the server and re-execute them, it's not an option. I would shy away from this because you'd need to implement the same editing routines on both the client and the server, doubling the size of your code base. (Perhaps if your server-side code was written in Javascript it would make sense, so the drawing code could be reused.) Instead, look into finding a Javascript library that does complete image manipulation client-side, and have the browser upload the final, edited image. I'm not familiar with the options in that area, but a quick Google search turned this up, which uses the canvas element to store the pixel data. A: Well, even if others are trying to discourage you from doing this, it would probably not be that hard. On the client-side, you, you define a div that is floated/resizable over the image, with transparency, that can be scaled for the crop. Move, I assume it applies only to the text, so you dynamically create draggable spans on the client side, still easy. Scale, I have no Idea of a simple UI to do it. When you want to update your Image, you serialize your data (position of your cropping div and position of your text spans / scaling, relative to the position to the image.) Then, using json or anything similar you'd like, you transfer the data to the server. Then, on the server, using python/PIL, you reproduce the transformations that you have serialized.
Using PiL to take a screenshot of HTML/CSS
I want to enable a user on a website to upload an image, and write some text over it. Also, they should be able to crop/scale/move the image and text. For that stuff, I can do it in jQuery. After they've made the image the way they want it, is there a way i can take a screenshot of that image (using PiL) and save it on the server? What is the best/proper way to do this?
[ "Taking a \"screenshot\" of the picture is neither the best, nor the proper way to do it. To take a screenshot, you need to execute code on the client machine, which is \"not possible\" in a website scenario.\nHave a look at lolcat builder (I can't think of a more serious example right now ;). Everytime you click the \"Preview\" button, the image src is updated with an url containing the text, its style and position. The request is handled by the server which will generate a new picture to display.\n", "I assume you got Python on the server side.\nThe best way imo is to somehow 'get' all the editing parameters from the client, then re-render it using PIL.\nUpdate: How I will do it\nOn the server side, you need an url to handle posts. \nOn the client side, (after each edit, )send a post to that url, with the editing parameters.\nI think there is not an easy solution to this.\nMaybe if you don't use PIL to render the final image, but only remember the parameters, each view from clients can render itself?\n", "PIL isn't available on the client side.. so unless, as Jack Ha suggests, you intend to upload all the instructions of your image editing to the server and re-execute them, it's not an option. I would shy away from this because you'd need to implement the same editing routines on both the client and the server, doubling the size of your code base. (Perhaps if your server-side code was written in Javascript it would make sense, so the drawing code could be reused.)\nInstead, look into finding a Javascript library that does complete image manipulation client-side, and have the browser upload the final, edited image. I'm not familiar with the options in that area, but a quick Google search turned this up, which uses the canvas element to store the pixel data.\n", "Well, even if others are trying to discourage you from doing this, it would probably not be that hard.\nOn the client-side, you, you define a div that is floated/resizable over the image, with transparency, that can be scaled for the crop.\nMove, I assume it applies only to the text, so you dynamically create draggable spans on the client side, still easy.\nScale, I have no Idea of a simple UI to do it.\nWhen you want to update your Image, you serialize your data (position of your cropping div and position of your text spans / scaling, relative to the position to the image.) Then, using json or anything similar you'd like, you transfer the data to the server. \nThen, on the server, using python/PIL, you reproduce the transformations that you have serialized.\n" ]
[ 2, 1, 0, 0 ]
[]
[]
[ "css", "jquery", "python", "python_imaging_library", "xhtml" ]
stackoverflow_0000673725_css_jquery_python_python_imaging_library_xhtml.txt
Q: How to read from an os.pipe() without getting blocked? I'm trying to read from an open os.pipe() to see if it's empty at the moment of the reading. The problem is that calling read() causes the program to block there until there is actually something to read there however there won't be any, if the test I'm doing succeeded. I know I can use select.select() with a timeout however I wanted to know if there is another solution to the problem. A: You might try this. import os, fcntl fcntl.fcntl(thePipe, fcntl.F_SETFL, os.O_NONBLOCK) With this thePipe.read() should be non-blocking. From pipe(7) man page: If a process attempts to read from an empty pipe, then read(2) will block until data is available. (...) Non-blocking I/O is possible by using the fcntl(2) F_SETFL operation to enable the O_NONBLOCK open file status flag.
How to read from an os.pipe() without getting blocked?
I'm trying to read from an open os.pipe() to see if it's empty at the moment of the reading. The problem is that calling read() causes the program to block there until there is actually something to read there however there won't be any, if the test I'm doing succeeded. I know I can use select.select() with a timeout however I wanted to know if there is another solution to the problem.
[ "You might try this. \nimport os, fcntl\nfcntl.fcntl(thePipe, fcntl.F_SETFL, os.O_NONBLOCK) \n\nWith this thePipe.read() should be non-blocking. \nFrom pipe(7) man page:\n\nIf a process attempts to read from an\n empty pipe, then read(2) will block\n until data is available. (...)\n Non-blocking I/O is possible by using\n the fcntl(2) F_SETFL operation to\n enable the O_NONBLOCK open file status\n flag.\n\n" ]
[ 17 ]
[]
[]
[ "file", "pipe", "python" ]
stackoverflow_0000673844_file_pipe_python.txt
Q: How should I best emulate and/or avoid enum's in Python? I've been using a small class to emulate Enums in some Python projects. Is there a better way or does this make the most sense for some situations? Class code here: class Enum(object): '''Simple Enum Class Example Usage: >>> codes = Enum('FOO BAR BAZ') # codes.BAZ will be 2 and so on ...''' def __init__(self, names): for number, name in enumerate(names.split()): setattr(self, name, number) A: Enums have been proposed for inclusion into the language before, but were rejected (see http://www.python.org/dev/peps/pep-0354/), though there are existing packages you could use instead of writing your own implementation: enum: http://pypi.python.org/pypi/enum SymbolType (not quite the same as enums, but still useful): http://pypi.python.org/pypi/SymbolType Or just do a search A: The most common enum case is enumerated values that are part of a State or Strategy design pattern. The enums are specific states or specific optional strategies to be used. In this case, they're almost always part and parcel of some class definition class DoTheNeedful( object ): ONE_CHOICE = 1 ANOTHER_CHOICE = 2 YET_ANOTHER = 99 def __init__( self, aSelection ): assert aSelection in ( self.ONE_CHOICE, self.ANOTHER_CHOICE, self.YET_ANOTHER ) self.selection= aSelection Then, in a client of this class. dtn = DoTheNeeful( DoTheNeeful.ONE_CHOICE ) A: What I see more often is this, in top-level module context: FOO_BAR = 'FOO_BAR' FOO_BAZ = 'FOO_BAZ' FOO_QUX = 'FOO_QUX' ...and later... if something is FOO_BAR: pass # do something here elif something is FOO_BAZ: pass # do something else elif something is FOO_QUX: pass # do something else else: raise Exception('Invalid value for something') Note that the use of is rather than == is taking a risk here -- it assumes that folks are using your_module.FOO_BAR rather than the string 'FOO_BAR' (which will normally be interned such that is will match, but that certainly can't be counted on), and so may not be appropriate depending on context. One advantage of doing it this way is that by looking anywhere a reference to that string is being stored, it's immediately obvious where it came from; FOO_BAZ is much less ambiguous than 2. Besides that, the other thing that offends my Pythonic sensibilities re the class you propose is the use of split(). Why not just pass in a tuple, list or other enumerable to start with? A: There's a lot of good discussion here. A: The builtin way to do enums is: (FOO, BAR, BAZ) = range(3) which works fine for small sets, but has some drawbacks: you need to count the number of elements by hand you can't skip values if you add one name, you also need to update the range number For a complete enum implementation in python, see: http://code.activestate.com/recipes/67107/ A: I started with something that looks a lot like S.Lott's answer but I only overloaded 'str' and 'eq' (instead of the whole object class) so I could print and compare the enum's value. class enumSeason(): Spring = 0 Summer = 1 Fall = 2 Winter = 3 def __init__(self, Type): self.value = Type def __str__(self): if self.value == enumSeason.Spring: return 'Spring' if self.value == enumSeason.Summer: return 'Summer' if self.value == enumSeason.Fall: return 'Fall' if self.value == enumSeason.Winter: return 'Winter' def __eq__(self,y): return self.value==y.value Print(x) will yield the name instead of the value and two values holding Spring will be equal to one another. >>> x = enumSeason(enumSeason.Spring) >>> print(x) Spring >>> y = enumSeason(enumSeason.Spring) >>> x == y True
How should I best emulate and/or avoid enum's in Python?
I've been using a small class to emulate Enums in some Python projects. Is there a better way or does this make the most sense for some situations? Class code here: class Enum(object): '''Simple Enum Class Example Usage: >>> codes = Enum('FOO BAR BAZ') # codes.BAZ will be 2 and so on ...''' def __init__(self, names): for number, name in enumerate(names.split()): setattr(self, name, number)
[ "Enums have been proposed for inclusion into the language before, but were rejected (see http://www.python.org/dev/peps/pep-0354/), though there are existing packages you could use instead of writing your own implementation:\n\nenum: http://pypi.python.org/pypi/enum\nSymbolType (not quite the same as enums, but still useful): http://pypi.python.org/pypi/SymbolType\nOr just do a search\n\n", "The most common enum case is enumerated values that are part of a State or Strategy design pattern. The enums are specific states or specific optional strategies to be used. In this case, they're almost always part and parcel of some class definition\nclass DoTheNeedful( object ):\n ONE_CHOICE = 1\n ANOTHER_CHOICE = 2 \n YET_ANOTHER = 99\n def __init__( self, aSelection ):\n assert aSelection in ( self.ONE_CHOICE, self.ANOTHER_CHOICE, self.YET_ANOTHER )\n self.selection= aSelection\n\nThen, in a client of this class.\ndtn = DoTheNeeful( DoTheNeeful.ONE_CHOICE )\n\n", "What I see more often is this, in top-level module context:\nFOO_BAR = 'FOO_BAR'\nFOO_BAZ = 'FOO_BAZ'\nFOO_QUX = 'FOO_QUX'\n\n...and later...\nif something is FOO_BAR: pass # do something here\nelif something is FOO_BAZ: pass # do something else\nelif something is FOO_QUX: pass # do something else\nelse: raise Exception('Invalid value for something')\n\nNote that the use of is rather than == is taking a risk here -- it assumes that folks are using your_module.FOO_BAR rather than the string 'FOO_BAR' (which will normally be interned such that is will match, but that certainly can't be counted on), and so may not be appropriate depending on context.\nOne advantage of doing it this way is that by looking anywhere a reference to that string is being stored, it's immediately obvious where it came from; FOO_BAZ is much less ambiguous than 2.\nBesides that, the other thing that offends my Pythonic sensibilities re the class you propose is the use of split(). Why not just pass in a tuple, list or other enumerable to start with?\n", "There's a lot of good discussion here. \n", "The builtin way to do enums is:\n(FOO, BAR, BAZ) = range(3)\n\nwhich works fine for small sets, but has some drawbacks:\n\nyou need to count the number of elements by hand\nyou can't skip values \nif you add one name, you also need to update the range number\n\nFor a complete enum implementation in python, see:\nhttp://code.activestate.com/recipes/67107/\n", "I started with something that looks a lot like S.Lott's answer but I only overloaded 'str' and 'eq' (instead of the whole object class) so I could print and compare the enum's value.\nclass enumSeason():\n Spring = 0\n Summer = 1\n Fall = 2\n Winter = 3\n def __init__(self, Type):\n self.value = Type\n def __str__(self):\n if self.value == enumSeason.Spring:\n return 'Spring'\n if self.value == enumSeason.Summer:\n return 'Summer'\n if self.value == enumSeason.Fall:\n return 'Fall'\n if self.value == enumSeason.Winter:\n return 'Winter'\n def __eq__(self,y):\n return self.value==y.value\n\nPrint(x) will yield the name instead of the value and two values holding Spring will be equal to one another.\n >>> x = enumSeason(enumSeason.Spring)\n >>> print(x)\n Spring\n >>> y = enumSeason(enumSeason.Spring)\n >>> x == y\n True\n\n" ]
[ 5, 4, 3, 3, 2, 1 ]
[]
[]
[ "enums", "python" ]
stackoverflow_0000108523_enums_python.txt
Q: In Python 2.6, How Might You Pass a List Object to a Method Which Expects A List of Arguments? I have a list full of various bits of information that I would like to pass to several strings for inclusion via the new string format method. As a toy example, let us define thelist = ['a', 'b', 'c'] I would like to do a print statement like print '{0} {2}'.format(thelist) and print '{1} {2}'.format(thelist) When I run this, I receive the message IndexError: tuple index out of range; when mucking about, it clearly takes the whole list as a single object. I would, of course, rather it translate thelist to 'a', 'b', 'c'. I tried using a tuple and received the same error. What on Earth is this particular technique called? If I knew the name, I could have searched for it. "Expand" is clearly not it. "Explode" doesn't yield anything useful. My actual use is much longer and more tedious than the toy example. A: .format(*thelist) It's part of the calling syntax in Python. I don't know the name either, and I'm not convinced it has one. See the tutorial. It doesn't just work on lists, though, it works for any iterable object. A: '{0} {2}'.format(*thelist) docs
In Python 2.6, How Might You Pass a List Object to a Method Which Expects A List of Arguments?
I have a list full of various bits of information that I would like to pass to several strings for inclusion via the new string format method. As a toy example, let us define thelist = ['a', 'b', 'c'] I would like to do a print statement like print '{0} {2}'.format(thelist) and print '{1} {2}'.format(thelist) When I run this, I receive the message IndexError: tuple index out of range; when mucking about, it clearly takes the whole list as a single object. I would, of course, rather it translate thelist to 'a', 'b', 'c'. I tried using a tuple and received the same error. What on Earth is this particular technique called? If I knew the name, I could have searched for it. "Expand" is clearly not it. "Explode" doesn't yield anything useful. My actual use is much longer and more tedious than the toy example.
[ ".format(*thelist)\nIt's part of the calling syntax in Python. I don't know the name either, and I'm not convinced it has one. See the tutorial.\nIt doesn't just work on lists, though, it works for any iterable object.\n", "'{0} {2}'.format(*thelist)\n\ndocs\n" ]
[ 10, 2 ]
[]
[]
[ "arguments", "list", "python" ]
stackoverflow_0000674690_arguments_list_python.txt
Q: How to display errors to the user while still logging it? I'm using a PyQt4 user interface. I've redirected stderr to a log file for easy debugging and trouble-shooting, but now I need to display error messages to the user when an error occurs. My issue is that I need to catch an exception when it happens and let the user know that it happened, but still let the traceback propagate to stderr (i.e. the log file). If I do something like this: def updateResults(self): try: #code that updates the results except: #display error message box This will catch the exception and not propogate to the error log. Is there some way to show the user the message and then continue to propogate the error? Would this work? except, e: #display error message box raise e Is there a better way to accomplish my goal? A: I think you are thinking about this in the wrong way. You shouldn't be re-raising the error simply to log it further down the line. The cannonical way of doing this in Python is to use the logging module. Adapted from the docs: import logging LOG_FILENAME = '/tmp/logging_example.out' logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,) ... try: # code except: logging.debug('Something bad happened', exc_info=True) # display message box # raise (if necessary) This gives a far more flexible logging system than relying on errors produced on sys.stdout. You may not need to re-raise the exception if you can recover from the exception in some way. A: Exactly, but you can just raise which will re-raise the currently handled exception. A: Some additional information: (With PyQt4) you will also need to rebind sys.excepthook to your own function to catch all uncaught exceptions. Otherwise PyQt will just print them to the console, which may not be what you need... import sys def excepthook(exc_type, exc_val, tracebackobj): # do something useful with the uncaught exception ... def main(): # rebind excepthook sys.excepthook = excepthook ...
How to display errors to the user while still logging it?
I'm using a PyQt4 user interface. I've redirected stderr to a log file for easy debugging and trouble-shooting, but now I need to display error messages to the user when an error occurs. My issue is that I need to catch an exception when it happens and let the user know that it happened, but still let the traceback propagate to stderr (i.e. the log file). If I do something like this: def updateResults(self): try: #code that updates the results except: #display error message box This will catch the exception and not propogate to the error log. Is there some way to show the user the message and then continue to propogate the error? Would this work? except, e: #display error message box raise e Is there a better way to accomplish my goal?
[ "I think you are thinking about this in the wrong way. You shouldn't be re-raising the error simply to log it further down the line. The cannonical way of doing this in Python is to use the logging module. Adapted from the docs:\nimport logging\nLOG_FILENAME = '/tmp/logging_example.out'\nlogging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,)\n\n...\n\ntry:\n # code\nexcept:\n logging.debug('Something bad happened', exc_info=True)\n # display message box\n # raise (if necessary)\n\nThis gives a far more flexible logging system than relying on errors produced on sys.stdout. You may not need to re-raise the exception if you can recover from the exception in some way. \n", "Exactly, but you can just\nraise\n\nwhich will re-raise the currently handled exception.\n", "Some additional information:\n(With PyQt4) you will also need to rebind sys.excepthook to your own function to catch all uncaught exceptions. Otherwise PyQt will just print them to the console, which may not be what you need...\nimport sys\n\ndef excepthook(exc_type, exc_val, tracebackobj):\n # do something useful with the uncaught exception\n ...\n\ndef main():\n # rebind excepthook\n sys.excepthook = excepthook\n ...\n\n" ]
[ 6, 3, 1 ]
[]
[]
[ "error_handling", "error_logging", "exception_handling", "pyqt4", "python" ]
stackoverflow_0000674067_error_handling_error_logging_exception_handling_pyqt4_python.txt
Q: benchmarking PHP vs Pylons I want to benchmark PHP vs Pylons. I want my comparison of both to be as even as possible, so here is what I came up with: PHP 5.1.6 with APC, using a smarty template connecting to a MySQL database Python 2.6.1, using Pylons with a mako template connecting the the same MySQL database Is there anything that I should change in that setup to make it a more fair comparison? I'm going to run it on a spare server that has almost no activity, 2G of ram and 4 cores. Any suggestions of how I should or shouldn't benchmark them? I plan on using ab to do the actual benchmarking. Related Which is faster, python webpages or php webpages? A: If you're not using an ORM in PHP you should not use the SQLAlchemy ORM or SQL-Expression language either but use raw SQL commands. If you're using APC you should make sure that Python has write privileges to the folder your application is in, or that the .py files are precompiled. Also if you're using the smarty cache consider enabling the Mako cache as well for fairness sake. However there is a catch: the Python MySQL adapter is incredible bad. For the database connections you will probably notice either slow performance (if SQLAlchemy performs the unicode decoding for itself) or it leaks memory (if the MySQL adapter does that). Both issues you don't have with PHP because there is no unicode support. So for total fairness you would have to disable unicode in the database connection (which however is an incredible bad idea). So: there doesn't seem to be a fair way to compare PHP and Pylons :) A: your PHP version is out of date, PHP has been in the 5.2.x area for awhile and while there are not massive improvements, there are enough changes that I would say to test anything older is an unfair comparison. PHP 5.3 is on the verge of becomming final and you should include that in your benchmarks as there are massive improvements to PHP 5.x as well as being the last version of 5.x, if you really want to split hairs PHP 6 is also in alpha/beta and that's a heavy overhaul also. Comparing totally different languages can be interesting but don't forget you are comparing apples to oranges, and the biggest bottleneck in any 2/3/N-Tier app is waiting on I/O. So the biggest factor is your database speed, comparing PHP vs Python VS ASP.Net purely on speed is pointless as all 3 of them will execute in less than 1 second but yet you can easily wait 2-3 seconds on your database query, depending on your hardware and what you are doing. If you are worried what is faster, you're taking the absolute wrong approach to choosing a platform. There are more important issues, such as (not in order): a. How easily can I find skilled devs in that platform b. How much do those skilled devs cost c. How much ROI does the language offer d. How feature rich is the language
benchmarking PHP vs Pylons
I want to benchmark PHP vs Pylons. I want my comparison of both to be as even as possible, so here is what I came up with: PHP 5.1.6 with APC, using a smarty template connecting to a MySQL database Python 2.6.1, using Pylons with a mako template connecting the the same MySQL database Is there anything that I should change in that setup to make it a more fair comparison? I'm going to run it on a spare server that has almost no activity, 2G of ram and 4 cores. Any suggestions of how I should or shouldn't benchmark them? I plan on using ab to do the actual benchmarking. Related Which is faster, python webpages or php webpages?
[ "If you're not using an ORM in PHP you should not use the SQLAlchemy ORM or SQL-Expression language either but use raw SQL commands. If you're using APC you should make sure that Python has write privileges to the folder your application is in, or that the .py files are precompiled.\nAlso if you're using the smarty cache consider enabling the Mako cache as well for fairness sake.\nHowever there is a catch: the Python MySQL adapter is incredible bad. For the database connections you will probably notice either slow performance (if SQLAlchemy performs the unicode decoding for itself) or it leaks memory (if the MySQL adapter does that).\nBoth issues you don't have with PHP because there is no unicode support. So for total fairness you would have to disable unicode in the database connection (which however is an incredible bad idea).\nSo: there doesn't seem to be a fair way to compare PHP and Pylons :)\n", "\nyour PHP version is out of date, PHP has been in the 5.2.x area for awhile and while there are not massive improvements, there are enough changes that I would say to test anything older is an unfair comparison.\nPHP 5.3 is on the verge of becomming final and you should include that in your benchmarks as there are massive improvements to PHP 5.x as well as being the last version of 5.x, if you really want to split hairs PHP 6 is also in alpha/beta and that's a heavy overhaul also.\nComparing totally different languages can be interesting but don't forget you are comparing apples to oranges, and the biggest bottleneck in any 2/3/N-Tier app is waiting on I/O. So the biggest factor is your database speed, comparing PHP vs Python VS ASP.Net purely on speed is pointless as all 3 of them will execute in less than 1 second but yet you can easily wait 2-3 seconds on your database query, depending on your hardware and what you are doing.\nIf you are worried what is faster, you're taking the absolute wrong approach to choosing a platform. There are more important issues, such as (not in order):\na. How easily can I find skilled devs in that platform\nb. How much do those skilled devs cost\nc. How much ROI does the language offer\nd. How feature rich is the language\n\n" ]
[ 3, 2 ]
[]
[]
[ "benchmarking", "php", "pylons", "python" ]
stackoverflow_0000674739_benchmarking_php_pylons_python.txt
Q: How to upload a file with django (python) and s3? I'm looking for a way to upload a file to s3. I am using django. I am currently using amazon's python library for uploading along with the following code: View: def submitpicture(request): fuser = request.session["login"] copied_data = request.POST.copy() copied_data.update(request.FILES) content_type = copied_data['file'].get('content-type') ffile = copied_data['file']['content'] key = '%s-%s' % (fuser, ''.join(copied_data['file']['filename'].split(' '))) site_s3.save_s3_data(key, ffile, content_type) Template: <form action="/submitpicture/" method="POST"> <input type="file" id="file" name="file" /> <input type="submit" value="submit" /> </form> However, when I actually try to run it i get the following error: "Key 'file' not found in <QueryDict: {}>" #MultiValueDictKeyError I really don't see what I'm doing wrong. Can someone point me in the right direction? Edit: Just in case someone wonders, I am planning on adding some validation after I get the actual upload working. A: You will have to provide the enctype attribute to the FORM element (I've been bitten by this before). For example, your FORM tag should look like: <form action="/submitpicture/" method="POST" enctype="multipart/form-data" > Without the enctype, you will find yourself with an empty request.FILES. A: Instead of doing this manually I would take a look at the storage backend David Larlet has written for Django, django-storages A: Adding enctype="multipart/form-data" seems like something that's worth mentioning in the "File Uploads" section of the django docs (http://docs.djangoproject.com/en/dev/topics/http/file-uploads/). Thoughts?
How to upload a file with django (python) and s3?
I'm looking for a way to upload a file to s3. I am using django. I am currently using amazon's python library for uploading along with the following code: View: def submitpicture(request): fuser = request.session["login"] copied_data = request.POST.copy() copied_data.update(request.FILES) content_type = copied_data['file'].get('content-type') ffile = copied_data['file']['content'] key = '%s-%s' % (fuser, ''.join(copied_data['file']['filename'].split(' '))) site_s3.save_s3_data(key, ffile, content_type) Template: <form action="/submitpicture/" method="POST"> <input type="file" id="file" name="file" /> <input type="submit" value="submit" /> </form> However, when I actually try to run it i get the following error: "Key 'file' not found in <QueryDict: {}>" #MultiValueDictKeyError I really don't see what I'm doing wrong. Can someone point me in the right direction? Edit: Just in case someone wonders, I am planning on adding some validation after I get the actual upload working.
[ "You will have to provide the enctype attribute to the FORM element (I've been bitten by this before). For example, your FORM tag should look like: \n<form action=\"/submitpicture/\" method=\"POST\" enctype=\"multipart/form-data\" >\n\nWithout the enctype, you will find yourself with an empty request.FILES.\n", "Instead of doing this manually I would take a look at the storage backend David Larlet has written for Django, django-storages\n", "Adding enctype=\"multipart/form-data\" seems like something that's worth mentioning in the \"File Uploads\" section of the django docs (http://docs.djangoproject.com/en/dev/topics/http/file-uploads/). Thoughts?\n" ]
[ 19, 5, 2 ]
[]
[]
[ "amazon_s3", "django", "file_upload", "python" ]
stackoverflow_0000319923_amazon_s3_django_file_upload_python.txt
Q: Python, __init__ and self confusion Alright, so I was taking a look at some source when I came across this: >>> def __parse(self, filename): ... "parse ID3v1.0 tags from MP3 file" ... self.clear() ... try: ... fsock = open(filename, "rb", 0) ... try: ... fsock.seek(-128, 2) ... tagdata = fsock.read(128) ... finally: ... fsock.close() ... if tagdata[:3] == 'TAG': ... for tag, (start, end, parseFunc) in self.tagDataMap.items(): ... self[tag] = parseFunc(tagdata[start:end]) ... except IOError: ... pass ... So, I decided to test it out. >>> __parse("blah.mp3") And, I received this error: Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: __parse() takes exactly 2 arguments (1 given) This wouldn't be the first time I've encountered this, I keep thinking I'm meant to include self in the argument parameter list, but I know that that's not right. Could someone explain to me why this happens a lot with code I try to play around with, I suppose its due to my level of understanding about the terms, I barely even understand what init or self does, or why it's relevant. def x(b): print b is the same as def x(self, b): self.b = b print self.b isn't it? Why does it matter so much! I just want a basic explanation, so I can get this out of my mind,thanks. A: The def __parse was inside some class definition. You can't pull the method defs out of the class definitions. The method function definition is part of the class. Look at these two examples: def add( a, b ): return a + b And class Adder( object ): def __init__( self ): self.grand_total = 0 def add( self, a, b ): self.grand_total += a+b return a+b Notes. The function does not use self. The class method does use self. Generally, all instance methods will use self, unless they have specific decorators like @classmethod that say otherwise. The function doesn't depend on anything else else. The class method depends on being called by an instance of the class Adder; further, it depends on that instance of the class Adder having been initialized correctly. In this case, the initialization function (__init__) has assured that each instance of Adder always has an instance variable named grand_total and that instance variable has an initial value of 0. You can't pull the add method function out of the Adder class and use it separately. It is not a stand-alone function. It was defined inside the class and has certain expectations because of that location inside the class. A: Functions/methods can be written outside of a class and then used for a technique in Python called monkeypatching: class C(object): def __init__(self): self.foo = 'bar' def __output(self): print self.foo C.output = __output c = C() c.output() A: Looks like you're a bit confused about classes and object-oriented programming. The 'self' thing is one of the gotchas in python for people coming from other programming languages. IMO the official tutorial doesn't handle it too well. This tutorial seems quite good. If you've ever learnt java, self in python is very similar to this in java. The difference is that python requires you to list self as the first argument to every function in a class definition. If python is your first programming language (or your first object-oriented language), you could remember this as a simple rule-of-thumb: if you're defining a function that's part of a class, you need to include self as the first argument. If you're defining a function that's not part of a class, you shouldn't include self in the arguments. You can't take a class function and make it stand-alone without doing some (or possibly a lot of) extra coding. Finally, never include self as an argument when calling a function. There are exceptions to those rules, but they're not worth worrying about now. A: self is passed in automatically by the instancemethod wrapper on classes. This function isn't wrapped; it's not a method, it's just a function. It doesn't even make sense without being attached to a class, since it needs the self parameter. A: As an aside, it is possible to create static methods of a class in Python. The simplest way to do this is via decorators (e.g. @staticmethod). I suspect this kind of thing is usually not the Pythonic solution though.
Python, __init__ and self confusion
Alright, so I was taking a look at some source when I came across this: >>> def __parse(self, filename): ... "parse ID3v1.0 tags from MP3 file" ... self.clear() ... try: ... fsock = open(filename, "rb", 0) ... try: ... fsock.seek(-128, 2) ... tagdata = fsock.read(128) ... finally: ... fsock.close() ... if tagdata[:3] == 'TAG': ... for tag, (start, end, parseFunc) in self.tagDataMap.items(): ... self[tag] = parseFunc(tagdata[start:end]) ... except IOError: ... pass ... So, I decided to test it out. >>> __parse("blah.mp3") And, I received this error: Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: __parse() takes exactly 2 arguments (1 given) This wouldn't be the first time I've encountered this, I keep thinking I'm meant to include self in the argument parameter list, but I know that that's not right. Could someone explain to me why this happens a lot with code I try to play around with, I suppose its due to my level of understanding about the terms, I barely even understand what init or self does, or why it's relevant. def x(b): print b is the same as def x(self, b): self.b = b print self.b isn't it? Why does it matter so much! I just want a basic explanation, so I can get this out of my mind,thanks.
[ "The def __parse was inside some class definition.\nYou can't pull the method defs out of the class definitions. The method function definition is part of the class.\nLook at these two examples:\ndef add( a, b ):\n return a + b\n\nAnd\nclass Adder( object ):\n def __init__( self ):\n self.grand_total = 0\n def add( self, a, b ):\n self.grand_total += a+b\n return a+b\n\nNotes.\n\nThe function does not use self.\nThe class method does use self. Generally, all instance methods will use self, unless they have specific decorators like @classmethod that say otherwise.\nThe function doesn't depend on anything else else.\nThe class method depends on being called by an instance of the class Adder; further, it depends on that instance of the class Adder having been initialized correctly. In this case, the initialization function (__init__) has assured that each instance of Adder always has an instance variable named grand_total and that instance variable has an initial value of 0.\nYou can't pull the add method function out of the Adder class and use it separately. It is not a stand-alone function. It was defined inside the class and has certain expectations because of that location inside the class.\n\n", "Functions/methods can be written outside of a class and then used for a technique in Python called monkeypatching:\nclass C(object):\n def __init__(self):\n self.foo = 'bar'\n\ndef __output(self):\n print self.foo\n\nC.output = __output\nc = C()\nc.output()\n\n", "Looks like you're a bit confused about classes and object-oriented programming. The 'self' thing is one of the gotchas in python for people coming from other programming languages. IMO the official tutorial doesn't handle it too well. This tutorial seems quite good.\nIf you've ever learnt java, self in python is very similar to this in java. The difference is that python requires you to list self as the first argument to every function in a class definition.\nIf python is your first programming language (or your first object-oriented language), you could remember this as a simple rule-of-thumb: if you're defining a function that's part of a class, you need to include self as the first argument. If you're defining a function that's not part of a class, you shouldn't include self in the arguments. You can't take a class function and make it stand-alone without doing some (or possibly a lot of) extra coding. Finally, never include self as an argument when calling a function.\nThere are exceptions to those rules, but they're not worth worrying about now.\n", "self is passed in automatically by the instancemethod wrapper on classes. This function isn't wrapped; it's not a method, it's just a function. It doesn't even make sense without being attached to a class, since it needs the self parameter.\n", "As an aside, it is possible to create static methods of a class in Python. The simplest way to do this is via decorators (e.g. @staticmethod). I suspect this kind of thing is usually not the Pythonic solution though.\n" ]
[ 8, 2, 1, 0, 0 ]
[]
[]
[ "init", "python", "self" ]
stackoverflow_0000674600_init_python_self.txt
Q: learning python 3.0 on ubuntu [resolved] I tweaked the preferences in komodo edit and ended up with: don't auto indent don't allow file contents to override tab settings prefer tab characters over spaces 4 spaces per indent 4 width of each tab char I also set komodo to show whitespace and tabs, which eneded up revealing the screwed up sections. yeah - it's a little picky. :) [/resolved] I have installed python 3.0 on ubuntu 8.10 along with komodo-edit ide. I'm just getting into python, and I'm reading through visual quickstart guide python 2nd ed. (the example below is from that book). I'm getting some really frustrating errors and would really appreciate your thoughts. I've re-typed and checked tabs many times over. I'm starting to think that something in the install or setup has gone wrong. I typed the following into komodo-edit: #!/usr/bin/python3.0 for row in range(1, 10): for col in range(1, 10): p = row * col if p < 10: print(' ', end = '') print(row * col, ' ', end = '') print() I can't test this is IDLE with python 3 - can't seem to get that version of IDLE installed. for now, I'm trying to run from the shell. first, just using "python" to call the program... PYTHON [1] $ python ktest.py File "ktest.py", line 6 print(' ', end = '') ^ SyntaxError: invalid syntax now trying different ways of calling the python compiler... PYTHON [1] $ python ktest.py File "ktest.py", line 6 print(' ', end = '') ^ SyntaxError: invalid syntax PYTHON [1] $ python3 ktest.py File "ktest.py", line 4 p = row * col ^ TabError: inconsistent use of tabs and spaces in indentation PYTHON [1] $ python3.0 ktest.py File "ktest.py", line 4 p = row * col ^ TabError: inconsistent use of tabs and spaces in indentation A: The example used python 2.x , since python apparently referred to python2.x (for some x), not python3.0 (which is good, since most programs are for 2.x). The second two examples used python 3.0 . You mixed tabs and spaces in your source, and should get rid of the tab characters (don't retype-- use regular-expression replacement). Python 3.0 is more sensitive about this than 2.x-- you can get the same behavior using python -tt for 2.x .
learning python 3.0 on ubuntu
[resolved] I tweaked the preferences in komodo edit and ended up with: don't auto indent don't allow file contents to override tab settings prefer tab characters over spaces 4 spaces per indent 4 width of each tab char I also set komodo to show whitespace and tabs, which eneded up revealing the screwed up sections. yeah - it's a little picky. :) [/resolved] I have installed python 3.0 on ubuntu 8.10 along with komodo-edit ide. I'm just getting into python, and I'm reading through visual quickstart guide python 2nd ed. (the example below is from that book). I'm getting some really frustrating errors and would really appreciate your thoughts. I've re-typed and checked tabs many times over. I'm starting to think that something in the install or setup has gone wrong. I typed the following into komodo-edit: #!/usr/bin/python3.0 for row in range(1, 10): for col in range(1, 10): p = row * col if p < 10: print(' ', end = '') print(row * col, ' ', end = '') print() I can't test this is IDLE with python 3 - can't seem to get that version of IDLE installed. for now, I'm trying to run from the shell. first, just using "python" to call the program... PYTHON [1] $ python ktest.py File "ktest.py", line 6 print(' ', end = '') ^ SyntaxError: invalid syntax now trying different ways of calling the python compiler... PYTHON [1] $ python ktest.py File "ktest.py", line 6 print(' ', end = '') ^ SyntaxError: invalid syntax PYTHON [1] $ python3 ktest.py File "ktest.py", line 4 p = row * col ^ TabError: inconsistent use of tabs and spaces in indentation PYTHON [1] $ python3.0 ktest.py File "ktest.py", line 4 p = row * col ^ TabError: inconsistent use of tabs and spaces in indentation
[ "The example used python 2.x , since python apparently referred to python2.x (for some x), not python3.0 (which is good, since most programs are for 2.x).\nThe second two examples used python 3.0 . You mixed tabs and spaces in your source, and should get rid of the tab characters (don't retype-- use regular-expression replacement). Python 3.0 is more sensitive about this than 2.x-- you can get the same behavior using python -tt for 2.x .\n" ]
[ 2 ]
[]
[]
[ "development_environment", "komodo", "python", "ubuntu" ]
stackoverflow_0000675754_development_environment_komodo_python_ubuntu.txt
Q: Does Python have something like Perl 5.10's "state" variables? In Perl 5.10, I can say: sub foo () { state $x = 1; say $x++; } foo(); foo(); foo(); ...and it will print out: 1 2 3 Does Python have something like this? A: A class may be a better fit here (and is usually a better fit for anything involving "state"): class Stateful(object): def __init__(self): self.state_var = 0 def __call__(self): self.state_var = self.state_var + 1 print self.state_var foo = Stateful() foo() foo() A: The closest parallel is probably to attach values to the function itself. def foo(): foo.bar = foo.bar + 1 foo.bar = 0 foo() foo() foo() print foo.bar # prints 3 A: Python has generators which do something similar: What does the "yield" keyword do in Python? A: Not sure if this is what you're looking for, but python has generator functions that don't return a value per se, but a generator object that generates a new value everytime def gen(): x = 10 while True: yield x x += 1 usage: >>> a = gen() >>> a.next() 10 >>> a.next() 11 >>> a.next() 12 >>> a.next() 13 >>> look here for more explanation on yield: What does the "yield" keyword do in Python? A: Here's one way to implement a closure in python: def outer(): a = [4] def inner(): print a[0] a[0] = a[0] + 1 return inner fn = outer() fn() # => 4 fn() # => 5 fn() # => 6 I borrowed this example verbatim from a python mailing list post. A: Not that I'm recommending this, but just for fun: def foo(var=[1]): print var[0] var[0] += 1 This works because of the way mutable default arguments work in Python. A: Yes, though you have to declare your global variable first before it is encountered in foo: x = 0 def foo(): global x x += 1 print x foo() foo() foo() EDIT: In response to the comment, it's true that python has no static variables scoped within a function. Note that x in this example is only exposed as global to the rest of the module. For example, say the code above is in test.py. Now suppose you write the following module: from test import foo x = 100 foo() foo() The output will be only 1 and 2, not 101 and 102. A: You could also use something like def static_num2(): k = 0 while True: k += 1 yield k static = static_num2().next for i in range(0,10) : print static() to avoid a global var. Lifted from this link about the same question. A: The preferable way is to use class or generator (yield). For the sake of completeness here's a variant w/ closure in Python 3.x: >>> def make_foo(): ... x = 1 ... def foo(): ... nonlocal x ... print(x) ... x += 1 ... return foo ... >>> foo = make_foo() >>> foo() 1 >>> foo() 2 >>> foo() 3 A: >>> def foo(): x = 1 while True: yield x x += 1 >>> z = iter(foo()) >>> next(z) 1 >>> next(z) 2 >>> next(z) 3 A: Here's another dirty cheap way to do it, it's a variation on Tryiptich's answer, but using decorators def static_var( name, value ): def dec( function ): setattr( function, name, value ) return function return dec @static_var( 'counter', 0 ) def counting_function(): counting_function.counter = counting_function.counter + 1 print counting_function.counter """ >>> counting_function() 1 >>> counting_function() 2 >>> counting_function() 3 >>> counting_function() 4 >>> counting_function() 5 >>> """
Does Python have something like Perl 5.10's "state" variables?
In Perl 5.10, I can say: sub foo () { state $x = 1; say $x++; } foo(); foo(); foo(); ...and it will print out: 1 2 3 Does Python have something like this?
[ "A class may be a better fit here (and is usually a better fit for anything involving \"state\"):\nclass Stateful(object):\n\n def __init__(self):\n self.state_var = 0\n\n def __call__(self):\n self.state_var = self.state_var + 1\n print self.state_var\n\nfoo = Stateful()\nfoo()\nfoo()\n\n", "The closest parallel is probably to attach values to the function itself.\ndef foo():\n foo.bar = foo.bar + 1\n\nfoo.bar = 0\n\nfoo()\nfoo()\nfoo()\n\nprint foo.bar # prints 3\n\n", "Python has generators which do something similar:\nWhat does the \"yield\" keyword do in Python?\n", "Not sure if this is what you're looking for, but python has generator functions that don't return a value per se, but a generator object that generates a new value everytime\ndef gen():\n x = 10\n while True:\n yield x\n x += 1\n\nusage:\n>>> a = gen()\n>>> a.next()\n10\n>>> a.next()\n11\n>>> a.next()\n12\n>>> a.next()\n13\n>>> \n\nlook here for more explanation on yield:\nWhat does the \"yield\" keyword do in Python?\n", "Here's one way to implement a closure in python:\ndef outer():\n a = [4]\n def inner():\n print a[0]\n a[0] = a[0] + 1\n return inner\n\nfn = outer()\nfn() # => 4\nfn() # => 5\nfn() # => 6\n\nI borrowed this example verbatim from a python mailing list post.\n", "Not that I'm recommending this, but just for fun:\ndef foo(var=[1]):\n print var[0]\n var[0] += 1\n\nThis works because of the way mutable default arguments work in Python.\n", "Yes, though you have to declare your global variable first before it is encountered in foo:\nx = 0\n\ndef foo():\n global x\n x += 1\n print x\n\nfoo()\nfoo()\nfoo()\n\nEDIT: In response to the comment, it's true that python has no static variables scoped within a function. Note that x in this example is only exposed as global to the rest of the module. For example, say the code above is in test.py. Now suppose you write the following module:\nfrom test import foo\nx = 100\nfoo()\nfoo()\n\nThe output will be only 1 and 2, not 101 and 102.\n", "You could also use something like\ndef static_num2():\n k = 0\n while True:\n k += 1\n yield k\n\nstatic = static_num2().next\n\nfor i in range(0,10) :\n print static()\n\nto avoid a global var. Lifted from this link about the same question.\n", "The preferable way is to use class or generator (yield).\nFor the sake of completeness here's a variant w/ closure in Python 3.x:\n>>> def make_foo():\n... x = 1\n... def foo():\n... nonlocal x\n... print(x)\n... x += 1\n... return foo\n...\n>>> foo = make_foo()\n>>> foo()\n1\n>>> foo()\n2\n>>> foo()\n3\n\n", ">>> def foo():\n x = 1\n while True:\n yield x\n x += 1\n\n\n>>> z = iter(foo())\n>>> next(z)\n1\n>>> next(z)\n2\n>>> next(z)\n3\n\n", "Here's another dirty cheap way to do it, it's a variation on Tryiptich's answer, but using decorators\ndef static_var( name, value ):\n def dec( function ):\n setattr( function, name, value )\n return function\n return dec\n\n\n@static_var( 'counter', 0 )\ndef counting_function():\n counting_function.counter = counting_function.counter + 1\n print counting_function.counter\n\n\n\n\"\"\"\n>>> counting_function()\n1\n>>> counting_function()\n2\n>>> counting_function()\n3\n>>> counting_function()\n4\n>>> counting_function()\n5\n>>> \n\"\"\" \n\n" ]
[ 18, 12, 9, 9, 5, 3, 2, 2, 2, 1, 1 ]
[]
[]
[ "perl", "python" ]
stackoverflow_0000604622_perl_python.txt
Q: Is there a Python library for easily writing zoomable UI's? My next work is going to be heavily focused on working with data that is best understood when organized on a two-dimensional zoomable plane or canvas, instead of using lists and property forms. The library can be based on OpenGL, GTK+ or Cairo. It should allow me to: build widgets out of vector shapes and text (perhaps even SVG based?) arrange these widgets on a 2D plane catch widget-related events zoom deeply into a widget to reveal additional data arrange widgets in a tree animate widgets fluidly It wouldn't hurt if it would also allow for some databinding or model/view concept. A: Qt has this covered... check PyQt A: I think Clutter is perfect for you. From the web site: Clutter is an open source software library for creating fast, visually rich and animated graphical user interfaces. Clutter is written in C, but it has great Python bindings. A very similar project is Pigment: Pigment is a 3D scene graph library designed to easily create rich application user interfaces.
Is there a Python library for easily writing zoomable UI's?
My next work is going to be heavily focused on working with data that is best understood when organized on a two-dimensional zoomable plane or canvas, instead of using lists and property forms. The library can be based on OpenGL, GTK+ or Cairo. It should allow me to: build widgets out of vector shapes and text (perhaps even SVG based?) arrange these widgets on a 2D plane catch widget-related events zoom deeply into a widget to reveal additional data arrange widgets in a tree animate widgets fluidly It wouldn't hurt if it would also allow for some databinding or model/view concept.
[ "Qt has this covered... check PyQt\n", "I think Clutter is perfect for you.\nFrom the web site:\n\nClutter is an open source software\n library for creating fast, visually\n rich and animated graphical user\n interfaces.\n\nClutter is written in C, but it has great Python bindings.\nA very similar project is Pigment:\n\nPigment is a 3D scene graph library\n designed to easily create rich\n application user interfaces.\n\n" ]
[ 3, 2 ]
[]
[]
[ "cairo", "gtk", "opengl", "python", "user_interface" ]
stackoverflow_0000673434_cairo_gtk_opengl_python_user_interface.txt
Q: Error while deploying Django on Apache I have a small Django website which I am trying to run on an Apache 2.2 HTTP-Server. The application is running fine using "python manage.py runserver". Django Version: 1.0.2 final Python: 2.5 OS: Windows 2000 I wen't through the steps described in the documentation and after some fiddling, came out with the following in my httpd.conf. <Location "/therap/"> SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE settings PythonOption django.root /therap PythonDebug On PythonPath "['D:/therap/therap'] + sys.path" </Location> MaxRequestsPerChild 1 D:\therap\therap beeing the place where my manage.py is. When I try to open in my browser, I see an error in the style used by Django (as opposed to black courier on white background.) ImportError at / No module named therap.urls Request Method: GET Request URL: http://****:8080/ Exception Type: ImportError Exception Value: No module named therap.urls Exception Location: C:\python25\lib\site-packages\django\core\urlresolvers.py in _get_urlconf_module, line 200 Python Executable: C:\Programme\Apache Software Foundation\Apache2.2\bin\httpd.exe Python Version: 2.5.1 Python Path: ['D:/therap/therap', 'C:\\WINNT\\system32\\python25.zip', 'C:\\Python25\\Lib', 'C:\\Python25\\DLLs', 'C:\\Python25\\Lib\\lib-tk', 'C:\\Programme\\Apache Software Foundation\\Apache2.2', 'C:\\Programme\\Apache Software Foundation\\Apache2.2\\bin', 'C:\\Python25', 'C:\\Python25\\lib\\site-packages', 'C:\\Python25\\lib\\site-packages\\pyserial-2.2', 'C:\\Python25\\lib\\site-packages\\win32', 'C:\\Python25\\lib\\site-packages\\win32\\lib', 'C:\\Python25\\lib\\site-packages\\Pythonwin', 'C:\\Python25\\lib\\site-packages\\wx-2.8-msw-unicode'] Server time: Mo, 23 Mär 2009 16:27:03 +0100 There is a urls.py in D:\therap\therap. However there is none in D:\therap\therap\main where most of my code is. I then tried using the parent folder <Location "/therap/"> SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE therap.settings PythonOption django.root /therap PythonDebug On PythonPath "['D:/therap'] + sys.path" </Location> MaxRequestsPerChild 1 Which gave me a different error: MOD_PYTHON ERROR ProcessId: 2424 Interpreter: '***' ServerName: '****' DocumentRoot: 'C:/Programme/Apache Software Foundation/Apache2.2/htdocs' URI: '/therap/' Location: '/therap/' Directory: None Filename: 'C:/Programme/Apache Software Foundation/Apache2.2/htdocs/therap' PathInfo: '/' Phase: 'PythonHandler' Handler: 'django.core.handlers.modpython' Traceback (most recent call last): File "C:\Python25\Lib\site-packages\mod_python\importer.py", line 1537, in HandlerDispatch default=default_handler, arg=req, silent=hlist.silent) File "C:\Python25\Lib\site-packages\mod_python\importer.py", line 1229, in _process_target result = _execute_target(config, req, object, arg) File "C:\Python25\Lib\site-packages\mod_python\importer.py", line 1128, in _execute_target result = object(arg) File "C:\Python25\lib\site-packages\django\core\handlers\modpython.py", line 228, in handler return ModPythonHandler()(req) File "C:\Python25\lib\site-packages\django\core\handlers\modpython.py", line 201, in __call__ response = self.get_response(request) File "C:\python25\Lib\site-packages\django\core\handlers\base.py", line 67, in get_response response = middleware_method(request) File "C:\python25\Lib\site-packages\django\middleware\locale.py", line 17, in process_request translation.activate(language) File "C:\python25\Lib\site-packages\django\utils\translation\__init__.py", line 73, in activate return real_activate(language) File "C:\python25\Lib\site-packages\django\utils\translation\trans_real.py", line 209, in activate _active[currentThread()] = translation(language) File "C:\python25\Lib\site-packages\django\utils\translation\trans_real.py", line 198, in translation default_translation = _fetch(settings.LANGUAGE_CODE) File "C:\python25\Lib\site-packages\django\utils\translation\trans_real.py", line 183, in _fetch app = __import__(appname, {}, {}, []) ImportError: No module named main I do use the internationalization module, but I do not see why it causes a problem at this point. "main" is the name of the only Django app (containing views, models, forms and such). The full path is D:\therap\therap\main. I put __init__.py-files everywhere from the main folder to d:\therap. Now I don't know what else I could do. Any ideas? A: The problem is that you are importing your app ("main") as if it lives directly on the Python path, and your URLconf ("therap.urls") as if it lives within a "therap" module on the Python path. This can only work if both "D:/therap" and "D:/therap/therap" are BOTH on the Python path (which runserver does for you automatically to "make things easy"; though it ends up just delaying the confusion until deployment time). You can emulate runserver's behavior by using the following line in your Apache config: PythonPath "['D:/therap', 'D:/therap/therap'] + sys.path" It probably makes more sense to standardize your references so your Python path only need include one or the other. The usual way (at least the way I see referenced more often) would be to put "D:\therap" on the Python path and qualify your app as "therap.main" instead of just "main". Personally, I take the opposite approach and it works just fine: put "D:\therap\therap" on your Python path and set ROOT_URLCONF to "urls" instead of "therap.urls". The advantage of this is that if in future you want to make your "main" app reusable and move it out of the particular project, your references to it aren't tied to the project name "therap" (though with an app named "main" it doesn't sound like you're thinking in terms of reusable apps anyway).
Error while deploying Django on Apache
I have a small Django website which I am trying to run on an Apache 2.2 HTTP-Server. The application is running fine using "python manage.py runserver". Django Version: 1.0.2 final Python: 2.5 OS: Windows 2000 I wen't through the steps described in the documentation and after some fiddling, came out with the following in my httpd.conf. <Location "/therap/"> SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE settings PythonOption django.root /therap PythonDebug On PythonPath "['D:/therap/therap'] + sys.path" </Location> MaxRequestsPerChild 1 D:\therap\therap beeing the place where my manage.py is. When I try to open in my browser, I see an error in the style used by Django (as opposed to black courier on white background.) ImportError at / No module named therap.urls Request Method: GET Request URL: http://****:8080/ Exception Type: ImportError Exception Value: No module named therap.urls Exception Location: C:\python25\lib\site-packages\django\core\urlresolvers.py in _get_urlconf_module, line 200 Python Executable: C:\Programme\Apache Software Foundation\Apache2.2\bin\httpd.exe Python Version: 2.5.1 Python Path: ['D:/therap/therap', 'C:\\WINNT\\system32\\python25.zip', 'C:\\Python25\\Lib', 'C:\\Python25\\DLLs', 'C:\\Python25\\Lib\\lib-tk', 'C:\\Programme\\Apache Software Foundation\\Apache2.2', 'C:\\Programme\\Apache Software Foundation\\Apache2.2\\bin', 'C:\\Python25', 'C:\\Python25\\lib\\site-packages', 'C:\\Python25\\lib\\site-packages\\pyserial-2.2', 'C:\\Python25\\lib\\site-packages\\win32', 'C:\\Python25\\lib\\site-packages\\win32\\lib', 'C:\\Python25\\lib\\site-packages\\Pythonwin', 'C:\\Python25\\lib\\site-packages\\wx-2.8-msw-unicode'] Server time: Mo, 23 Mär 2009 16:27:03 +0100 There is a urls.py in D:\therap\therap. However there is none in D:\therap\therap\main where most of my code is. I then tried using the parent folder <Location "/therap/"> SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE therap.settings PythonOption django.root /therap PythonDebug On PythonPath "['D:/therap'] + sys.path" </Location> MaxRequestsPerChild 1 Which gave me a different error: MOD_PYTHON ERROR ProcessId: 2424 Interpreter: '***' ServerName: '****' DocumentRoot: 'C:/Programme/Apache Software Foundation/Apache2.2/htdocs' URI: '/therap/' Location: '/therap/' Directory: None Filename: 'C:/Programme/Apache Software Foundation/Apache2.2/htdocs/therap' PathInfo: '/' Phase: 'PythonHandler' Handler: 'django.core.handlers.modpython' Traceback (most recent call last): File "C:\Python25\Lib\site-packages\mod_python\importer.py", line 1537, in HandlerDispatch default=default_handler, arg=req, silent=hlist.silent) File "C:\Python25\Lib\site-packages\mod_python\importer.py", line 1229, in _process_target result = _execute_target(config, req, object, arg) File "C:\Python25\Lib\site-packages\mod_python\importer.py", line 1128, in _execute_target result = object(arg) File "C:\Python25\lib\site-packages\django\core\handlers\modpython.py", line 228, in handler return ModPythonHandler()(req) File "C:\Python25\lib\site-packages\django\core\handlers\modpython.py", line 201, in __call__ response = self.get_response(request) File "C:\python25\Lib\site-packages\django\core\handlers\base.py", line 67, in get_response response = middleware_method(request) File "C:\python25\Lib\site-packages\django\middleware\locale.py", line 17, in process_request translation.activate(language) File "C:\python25\Lib\site-packages\django\utils\translation\__init__.py", line 73, in activate return real_activate(language) File "C:\python25\Lib\site-packages\django\utils\translation\trans_real.py", line 209, in activate _active[currentThread()] = translation(language) File "C:\python25\Lib\site-packages\django\utils\translation\trans_real.py", line 198, in translation default_translation = _fetch(settings.LANGUAGE_CODE) File "C:\python25\Lib\site-packages\django\utils\translation\trans_real.py", line 183, in _fetch app = __import__(appname, {}, {}, []) ImportError: No module named main I do use the internationalization module, but I do not see why it causes a problem at this point. "main" is the name of the only Django app (containing views, models, forms and such). The full path is D:\therap\therap\main. I put __init__.py-files everywhere from the main folder to d:\therap. Now I don't know what else I could do. Any ideas?
[ "The problem is that you are importing your app (\"main\") as if it lives directly on the Python path, and your URLconf (\"therap.urls\") as if it lives within a \"therap\" module on the Python path. This can only work if both \"D:/therap\" and \"D:/therap/therap\" are BOTH on the Python path (which runserver does for you automatically to \"make things easy\"; though it ends up just delaying the confusion until deployment time). You can emulate runserver's behavior by using the following line in your Apache config:\nPythonPath \"['D:/therap', 'D:/therap/therap'] + sys.path\"\n\nIt probably makes more sense to standardize your references so your Python path only need include one or the other. The usual way (at least the way I see referenced more often) would be to put \"D:\\therap\" on the Python path and qualify your app as \"therap.main\" instead of just \"main\". Personally, I take the opposite approach and it works just fine: put \"D:\\therap\\therap\" on your Python path and set ROOT_URLCONF to \"urls\" instead of \"therap.urls\". The advantage of this is that if in future you want to make your \"main\" app reusable and move it out of the particular project, your references to it aren't tied to the project name \"therap\" (though with an app named \"main\" it doesn't sound like you're thinking in terms of reusable apps anyway).\n" ]
[ 3 ]
[]
[]
[ "apache", "django", "mod_python", "python", "windows" ]
stackoverflow_0000673936_apache_django_mod_python_python_windows.txt
Q: Is it possible to implement properties in languages other than C#? During a bout of C# and WPF recently, I got to like C#'s properties: public double length_inches { get { return length_metres * 39.0; } set { length_metres = value/39.0; } } Noticing, of course, that length_metres may change from being a field to a property, and the code need not care. WPF can also bind UI elements to object properties very happily. When I first learnt about classes and objects, I assumed that there was a way to do it, because it seemed so obvious! The point of hiding complexity inside a class is that you don't need to care what is being stored any more. But it has taken until now to see it. Amusingly, I first saw it done in VB.Net. That leading edge of OO purity. The question is, can I recreate properties in other languages which I use more often, like javascript, python, php? In javascript, if I set a variable to a closure, won't I get the closure back again, rather than the result of it? A: Python definitely supports properties: class Foo(object): def get_length_inches(self): return self.length_meters * 39.0 def set_length_inches(self, val): self.length_meters = val/39.0 length_inches = property(get_length_inches, set_length_inches) Starting in Python 2.5, syntactic sugar exists for read-only properties, and in 2.6, writable ones as well: class Foo(object): # 2.5 or later @property def length_inches(self): return self.length_meters * 39.0 # 2.6 or later @length_inches.setter def length_inches(self, val): self.length_meters = val/39.0 A: In JavaScript: var object = { // .. other property definitions ... get length_inches(){ return this.length_metres * 39.0; }, set length_inches(value){ this.length_metres = value/39.0; } }; A: In C# properties are mostly just a compiler feature. The compiler generates special methods get_PropertyName and set_PropertyName and works out the calls and so forth. It also set the specialname IL property of the methods. If your language of choice supports some kind of preprocessor, you can implement something similar but otherwise you're pretty much stuck with what you got. And of course, if you're implementing your own .NET language you can do what the C# compiler does as well. Due to the implementation details, there are actually subtle differences between fields and properties. See this question for details. A: Delphi, from which C# is derived, has had properties from the word go. And the word go was about 15 years ago. A: Most dynamic languages support something like that. In Smalltalk and Ruby, fields are not directly exposed - The only way to get at them is through a method. In other words - All variables are private. Ruby has some macros (class methods really), to make it simpler to type: class Thing attr_accessor :length_inches end will make a getter and a setter for length_inches. Behind the scenes, it's simply generating this: class Thing def length_inches @length_inches end def length_inches=(value) @length_inches = value end end (Ruby crash-course: The @ prefix means it's an instance variable. return is implicit in Ruby. t.length_inches = 42 will automatically invoke length_inches=(42), if t is a Thingy.) If you later on want to put some logic in the getters/setters, you can simply manually implement the same methods: class Thing def length_inches @length_metres * 39.0 end def length_inches=(value) @length_metres = value / 39.0 end end A: Out of the box in VB (that's VB 6.0, not VB.net) and VBScript! Public Property Get LengthInches() As Double LengthInches = LengthMetres * 39 End Property Public Property Let LengthInches(Value As Double) LengthMetres = Value / 39 End Property Also possible to fake quite nicely in PHP creating a class that you extend in combination with naming guidelines, protected members and magic functions. Yuch. A: Delphi has a property pattern (with Setter and Getter methods), which also can be used in interfaces. Properties with "published" visibility also will be displayed in the IDE object inspector. A class definition with a property would look like this: TFoo = class private FBar: string; procedure SetBar(Value: string); function GetBar: string; public property Bar: string read GetBar write SetBar; end; or (without Setter / Getter): TFoo = class private FBar: string; public property Bar: string read FBar write FBar; end; A: I think this is the Python equivalent class Length( object ): conversion = 39.0 def __init__( self, value ): self.set(value) def get( self ): return self.length_metres def set( self, value ): self.length_metres= value metres= property( get, set ) def get_inches( self ): return self.length_metres*self.conversion def set_inches( self, value ): self.length_metres= value/self.conversion inches = property( get_inches, set_inches ) It works like this. >>> l=Length(2) >>> l.metres 2 >>> l.inches 78.0 >>> l.inches=47 >>> l.metres 1.2051282051282051 A: In Objective-C 2.0 / Cocoa: @interface MyClass : NSObject { int myInt; NSString *myString; } @property int myInt; @property (nonatomic, copy) NSString *myString; @end Then in the implementation, simply specify: @synthesize myInt, myString; This generates the accessors for that member variable with key-value-coding compliant naming conventions like: - (void)setMyString:(NSString *)newString { [myString autorelease]; myString = [newString copy]; } Saves a lot of work typing out your accessors. A: It's definitely possible to implement properties in other languages. VB and F# for example have explicit property support. But these both target the CLR which has property support. VB. Public Property Name As String Get return "someName" End Get Set ... End Set End Property I do not believe javascript or PHP supports property syntax but I'm not very familiar with those languages. It is possible to create field get/set accessor methods in pretty much any language which simulate properties. Under the hood, .Net properties really just result down to get/set methods. They just have a really nice wrapper :) A: ActionScript 3 (javascript on steroids) has get/set syntax also A: Sadly, I haven't tried it myself yet, but I read that it was possible to implement properties in PHP through __set and __get magic methods. Here's a blog post on this subject. A: You can make something like it with PHP5 magic functions. class Length { public $metres; public function __get($name) { if ($name == 'inches') return $this->metres * 39; } public function __set($name, $value) { if ($name == 'inches') $this->metres = $value/39.0; } } $l = new Length; $l->metres = 3; echo $l->inches; A: You could do it in all sorts of languages, with varying degrees of syntactic sugar and magic. Python, as already mentioned, provides support for this (and, using decorators you could definitely clean it up even more). PHP could provide a reasonable facsimile with appropriate __get() and __set() methods (probably some indirection to. If you're working with Perl, you could use some source filters to replicate the behaviour. Ruby already requires everything to go through. A: When I first played with Visual Basic (like, version 1 or something) the first thing I did was try to recreate properties in C++. Probably before templates were available to me at the time, but now it would be something like: template <class TValue, class TOwner, class TKey> class property { TOwner *owner_; public: property(TOwner *owner) : owner_(owner) {} TValue value() const { return owner_->get_property(TKey()); } operator TValue() const { return value(); } TValue operator=(const TValue &value) { owner_->set_property(TKey(), value); return value; } }; class my_class { public: my_class() : first_name(this), limbs(this) {} struct limbs_k {}; struct first_name_k {}; property<std::string, my_class, first_name_k> first_name; property<int, my_class, limbs_k> limbs; std::string get_property(const first_name_k &); void set_property(const first_name_k &, const std::string &value); int get_property(const limbs_k &); void set_property(const limbs_k &, int value); }; Note that the "key" parameter is ignored in the implementations of get_property/set_property - it's only there to effectively act as part of the name of the function, via overload resolution. Now the user of my_class would be able to refer to the public members first_name and limbs in many situations as if they were raw fields, but they merely provide an alternative syntax for calling the corresponding get_property/set_property member functions. It's not perfect, because there are some situations where you'd have to call value() on a property to get the value, whenever the compiler is unable to infer the required type conversion. Also you might get a warning from the passing of this to members in the constructor, but you could silence that in this case. A: Boo is a .NET language very similar to Python, but with static typing. It can implement properties: class MyClass: //a field, initialized to the value 1 regularfield as int = 1 //default access level: protected //a string field mystringfield as string = "hello" //a private field private _privatefield as int //a public field public publicfield as int = 3 //a static field: the value is stored in one place and shared by all //instances of this class static public staticfield as int = 4 //a property (default access level: public) RegularProperty as int: get: //getter: called when you retrieve property return regularfield set: //setter: notice the special "value" variable regularfield = value ReadOnlyProperty as int: get: return publicfield SetOnlyProperty as int: set: publicfield = value //a field with an automatically generated property [Property(MyAutoProperty)] _mypropertyfield as int = 5
Is it possible to implement properties in languages other than C#?
During a bout of C# and WPF recently, I got to like C#'s properties: public double length_inches { get { return length_metres * 39.0; } set { length_metres = value/39.0; } } Noticing, of course, that length_metres may change from being a field to a property, and the code need not care. WPF can also bind UI elements to object properties very happily. When I first learnt about classes and objects, I assumed that there was a way to do it, because it seemed so obvious! The point of hiding complexity inside a class is that you don't need to care what is being stored any more. But it has taken until now to see it. Amusingly, I first saw it done in VB.Net. That leading edge of OO purity. The question is, can I recreate properties in other languages which I use more often, like javascript, python, php? In javascript, if I set a variable to a closure, won't I get the closure back again, rather than the result of it?
[ "Python definitely supports properties:\nclass Foo(object):\n\n def get_length_inches(self):\n return self.length_meters * 39.0\n\n def set_length_inches(self, val):\n self.length_meters = val/39.0\n\n length_inches = property(get_length_inches, set_length_inches)\n\nStarting in Python 2.5, syntactic sugar exists for read-only properties, and in 2.6, writable ones as well:\nclass Foo(object):\n\n # 2.5 or later\n @property\n def length_inches(self):\n return self.length_meters * 39.0\n\n # 2.6 or later\n @length_inches.setter\n def length_inches(self, val):\n self.length_meters = val/39.0\n\n", "In JavaScript:\nvar object = {\n // .. other property definitions ...\n get length_inches(){ return this.length_metres * 39.0; },\n set length_inches(value){ this.length_metres = value/39.0; }\n};\n\n", "In C# properties are mostly just a compiler feature. The compiler generates special methods get_PropertyName and set_PropertyName and works out the calls and so forth. It also set the specialname IL property of the methods.\nIf your language of choice supports some kind of preprocessor, you can implement something similar but otherwise you're pretty much stuck with what you got. \nAnd of course, if you're implementing your own .NET language you can do what the C# compiler does as well. \nDue to the implementation details, there are actually subtle differences between fields and properties. See this question for details.\n", "Delphi, from which C# is derived, has had properties from the word go. And the word go was about 15 years ago.\n", "Most dynamic languages support something like that. In Smalltalk and Ruby, fields are not directly exposed - The only way to get at them is through a method. In other words - All variables are private. Ruby has some macros (class methods really), to make it simpler to type:\nclass Thing\n attr_accessor :length_inches\nend\n\nwill make a getter and a setter for length_inches. Behind the scenes, it's simply generating this:\nclass Thing\n def length_inches\n @length_inches\n end\n def length_inches=(value)\n @length_inches = value\n end\nend\n\n(Ruby crash-course: The @ prefix means it's an instance variable. return is implicit in Ruby. t.length_inches = 42 will automatically invoke length_inches=(42), if t is a Thingy.)\nIf you later on want to put some logic in the getters/setters, you can simply manually implement the same methods:\nclass Thing\n def length_inches\n @length_metres * 39.0\n end\n def length_inches=(value)\n @length_metres = value / 39.0\n end\nend\n\n", "Out of the box in VB (that's VB 6.0, not VB.net) and VBScript!\nPublic Property Get LengthInches() As Double\n LengthInches = LengthMetres * 39\nEnd Property\n\nPublic Property Let LengthInches(Value As Double)\n LengthMetres = Value / 39\nEnd Property\n\nAlso possible to fake quite nicely in PHP creating a class that you extend in combination with naming guidelines, protected members and magic functions. Yuch.\n", "Delphi has a property pattern (with Setter and Getter methods), which also can be used in interfaces. Properties with \"published\" visibility also will be displayed in the IDE object inspector.\nA class definition with a property would look like this:\nTFoo = class\nprivate\n FBar: string;\n procedure SetBar(Value: string);\n function GetBar: string;\n\npublic\n property Bar: string read GetBar write SetBar;\n\nend;\n\nor (without Setter / Getter):\nTFoo = class\nprivate\n FBar: string;\n\npublic\n property Bar: string read FBar write FBar;\n\nend;\n\n", "I think this is the Python equivalent\nclass Length( object ):\n conversion = 39.0\n def __init__( self, value ):\n self.set(value)\n def get( self ):\n return self.length_metres\n def set( self, value ):\n self.length_metres= value\n metres= property( get, set )\n def get_inches( self ):\n return self.length_metres*self.conversion\n def set_inches( self, value ):\n self.length_metres= value/self.conversion\n inches = property( get_inches, set_inches )\n\nIt works like this.\n>>> l=Length(2)\n>>> l.metres\n2\n>>> l.inches\n78.0\n>>> l.inches=47\n>>> l.metres\n1.2051282051282051\n\n", "In Objective-C 2.0 / Cocoa:\n@interface MyClass : NSObject\n{\n int myInt;\n NSString *myString;\n}\n\n@property int myInt;\n@property (nonatomic, copy) NSString *myString;\n\n@end\n\nThen in the implementation, simply specify:\n@synthesize myInt, myString;\n\nThis generates the accessors for that member variable with key-value-coding compliant naming conventions like:\n- (void)setMyString:(NSString *)newString\n{\n [myString autorelease];\n myString = [newString copy];\n}\n\nSaves a lot of work typing out your accessors.\n", "It's definitely possible to implement properties in other languages. VB and F# for example have explicit property support. But these both target the CLR which has property support. \nVB.\nPublic Property Name As String \n Get \n return \"someName\"\n End Get\n Set\n ...\n End Set\nEnd Property\n\nI do not believe javascript or PHP supports property syntax but I'm not very familiar with those languages. It is possible to create field get/set accessor methods in pretty much any language which simulate properties. \nUnder the hood, .Net properties really just result down to get/set methods. They just have a really nice wrapper :)\n", "ActionScript 3 (javascript on steroids) has get/set syntax also\n", "Sadly, I haven't tried it myself yet, but I read that it was possible to implement properties in PHP through __set and __get magic methods. Here's a blog post on this subject.\n", "You can make something like it with PHP5 magic functions.\nclass Length {\n public $metres;\n public function __get($name) {\n if ($name == 'inches')\n return $this->metres * 39;\n }\n public function __set($name, $value) {\n if ($name == 'inches')\n $this->metres = $value/39.0;\n }\n}\n\n$l = new Length;\n$l->metres = 3;\necho $l->inches;\n\n", "You could do it in all sorts of languages, with varying degrees of syntactic sugar and magic. Python, as already mentioned, provides support for this (and, using decorators you could definitely clean it up even more). PHP could provide a reasonable facsimile with appropriate __get() and __set() methods (probably some indirection to. If you're working with Perl, you could use some source filters to replicate the behaviour. Ruby already requires everything to go through.\n", "When I first played with Visual Basic (like, version 1 or something) the first thing I did was try to recreate properties in C++. Probably before templates were available to me at the time, but now it would be something like:\ntemplate <class TValue, class TOwner, class TKey>\nclass property\n{\n TOwner *owner_;\n\npublic:\n property(TOwner *owner)\n : owner_(owner) {}\n\n TValue value() const\n {\n return owner_->get_property(TKey());\n }\n\n operator TValue() const\n {\n return value();\n }\n\n TValue operator=(const TValue &value)\n {\n owner_->set_property(TKey(), value);\n return value;\n }\n};\n\nclass my_class\n{\npublic:\n my_class()\n : first_name(this), limbs(this) {}\n\n struct limbs_k {};\n struct first_name_k {};\n\n property<std::string, my_class, first_name_k> first_name;\n property<int, my_class, limbs_k> limbs;\n\n std::string get_property(const first_name_k &);\n void set_property(const first_name_k &, const std::string &value);\n\n int get_property(const limbs_k &);\n void set_property(const limbs_k &, int value);\n};\n\nNote that the \"key\" parameter is ignored in the implementations of get_property/set_property - it's only there to effectively act as part of the name of the function, via overload resolution.\nNow the user of my_class would be able to refer to the public members first_name and limbs in many situations as if they were raw fields, but they merely provide an alternative syntax for calling the corresponding get_property/set_property member functions.\nIt's not perfect, because there are some situations where you'd have to call value() on a property to get the value, whenever the compiler is unable to infer the required type conversion. Also you might get a warning from the passing of this to members in the constructor, but you could silence that in this case.\n", "Boo is a .NET language very similar to Python, but with static typing. It can implement properties: \nclass MyClass:\n //a field, initialized to the value 1\n regularfield as int = 1 //default access level: protected\n\n //a string field\n mystringfield as string = \"hello\"\n\n //a private field\n private _privatefield as int\n\n //a public field\n public publicfield as int = 3\n\n //a static field: the value is stored in one place and shared by all\n //instances of this class\n static public staticfield as int = 4\n\n //a property (default access level: public)\n RegularProperty as int:\n get: //getter: called when you retrieve property\n return regularfield\n set: //setter: notice the special \"value\" variable\n regularfield = value\n\n ReadOnlyProperty as int:\n get:\n return publicfield\n\n SetOnlyProperty as int:\n set:\n publicfield = value\n\n //a field with an automatically generated property\n [Property(MyAutoProperty)]\n _mypropertyfield as int = 5\n\n" ]
[ 18, 8, 6, 4, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0 ]
[ "The convention is to implement a get_PropertyName() and a set_PropertyName() method (that's all it is in the CLR as well. Properties are just syntactic sugar in VB.NET/C# - which is why a change from field to property or vice-versa is breaking and requires client code to recompile.\npublic int get_SomeValue() { return someValue; }\npublic void set_SomeValue(int value) { someValue = value; }\nprivate int someValue = 10;\n\n// client\nint someValue = someClass.get_SomeValue();\nsomeClass.set_SomeValue(12);\n\n" ]
[ -1 ]
[ "c#", "javascript", "php", "properties", "python" ]
stackoverflow_0000675161_c#_javascript_php_properties_python.txt
Q: Create static graphics files (png, gif, jpg) using Ruby or Python I'd like to create a graphic image on the fly based on user input, and then present that image as a PNG file (or jpg or gif if necessary, but PNG is preferred). This is actually for an astrology application; what I'd like to do is generate the chart in PNG for display. Python or Ruby is fine; in fact, the library available may determine the language I use. Update Here's an example image: A: Maybe a vectorial format is better suited for your needs, but is hard to tell without having a concrete example of what you'd like to get. For example, if the images are all alike, you could create a SVG base image with Inkscape, then edit it programmaticaly from Python or Ruby (either by editing the text or using a XML library) and finally export it to PNG. Update: After seeing the example image, I think SVG would be the most convenient choice. A SVG image is an XML file that basically says "draw a circle from here to here, write the string '13º52' there", etc. You could draw a unique base chart in Inkscape and have your program just adding the lines and symbols for each case. Finally you export to PNG. The advantages are: easier for you to draw, the image is fully scalable, you can change the styling just by editing a property ("make all lines wider", "change all text to Arial", "paint the background blue"), you can export to any format without losing quality, and I think it's more mantainable. A: In Python, you'd typically use PIL, the Python Image Library. I've never used PIL for anything beyond the simplest tasks, so I can't say how well it performs in practice. I'd start digging into PIL with a look at its documentation, particularly the documentation for the draw module. A: I found Gruff easy to use when I was in your shoes. Shameless blog plug. A: Look at Ruby-GD2 or an ImageMagick or GraphicsMagick binding. A: For Python I the most common choice for image formats is PIL and then Pycairo for vector formats. The two can work together, for exadmple in this cookbook entry to use PIL images for Pycairo surfaces. A: when I was doing python chalange (http://www.pythonchallenge.com/) I've used Python Image Library (http://www.pythonware.com/library/pil/)
Create static graphics files (png, gif, jpg) using Ruby or Python
I'd like to create a graphic image on the fly based on user input, and then present that image as a PNG file (or jpg or gif if necessary, but PNG is preferred). This is actually for an astrology application; what I'd like to do is generate the chart in PNG for display. Python or Ruby is fine; in fact, the library available may determine the language I use. Update Here's an example image:
[ "Maybe a vectorial format is better suited for your needs, but is hard to tell without having a concrete example of what you'd like to get.\nFor example, if the images are all alike, you could create a SVG base image with Inkscape, then edit it programmaticaly from Python or Ruby (either by editing the text or using a XML library) and finally export it to PNG.\n\nUpdate:\nAfter seeing the example image, I think SVG would be the most convenient choice. A SVG image is an XML file that basically says \"draw a circle from here to here, write the string '13º52' there\", etc. You could draw a unique base chart in Inkscape and have your program just adding the lines and symbols for each case. Finally you export to PNG.\nThe advantages are: easier for you to draw, the image is fully scalable, you can change the styling just by editing a property (\"make all lines wider\", \"change all text to Arial\", \"paint the background blue\"), you can export to any format without losing quality, and I think it's more mantainable.\n", "In Python, you'd typically use PIL, the Python Image Library. I've never used PIL for anything beyond the simplest tasks, so I can't say how well it performs in practice.\nI'd start digging into PIL with a look at its documentation, particularly the documentation for the draw module.\n", "I found Gruff easy to use when I was in your shoes. \nShameless blog plug.\n", "Look at Ruby-GD2 or an ImageMagick or GraphicsMagick binding.\n", "For Python I the most common choice for image formats is PIL and then Pycairo for vector formats. The two can work together, for exadmple in this cookbook entry to use PIL images for Pycairo surfaces.\n", "when I was doing python chalange (http://www.pythonchallenge.com/) I've used Python Image Library (http://www.pythonware.com/library/pil/)\n" ]
[ 11, 9, 3, 2, 2, 1 ]
[]
[]
[ "graphics", "png", "python", "ruby" ]
stackoverflow_0000676159_graphics_png_python_ruby.txt
Q: How do I generate test data for my Python script? A equation takes values in the following form : x = [0x02,0x00] # which is later internally converted to in the called function to 0x300 y = [0x01, 0xFF] z = [0x01, 0x0F] How do I generate a series of test values for this function ? for instance I want to send a 100 odd values from a for loop for i in range(0,300): # where a,b are derived for a range x = [a,b] My question was a bit unclear so please let my clarify. what I wanted to ask how I can do x =[a,b] generate different values for a,b A: use generators: def gen_xyz( max_iteration ): for i in xrange( 0, max_iteration ): # code which will generate next ( x, y, z ) yield ( x, y, z ) for x, y, z in gen_xyz( 1000 ): f( x, y, z ) A: The hex() function? import random for i in range(10): a1, a2 = random.randint(1,100), random.randint(1,100) x = [hex(a1), hex(a2)] print x ..outputs something similar to.. ['0x21', '0x4f'] ['0x59', '0x5c'] ['0x61', '0x40'] ['0x57', '0x45'] ['0x1a', '0x11'] ['0x4c', '0x49'] ['0x40', '0x1b'] ['0x1f', '0x7'] ['0x8', '0x2b'] ['0x1e', '0x13']
How do I generate test data for my Python script?
A equation takes values in the following form : x = [0x02,0x00] # which is later internally converted to in the called function to 0x300 y = [0x01, 0xFF] z = [0x01, 0x0F] How do I generate a series of test values for this function ? for instance I want to send a 100 odd values from a for loop for i in range(0,300): # where a,b are derived for a range x = [a,b] My question was a bit unclear so please let my clarify. what I wanted to ask how I can do x =[a,b] generate different values for a,b
[ "use generators:\ndef gen_xyz( max_iteration ):\n for i in xrange( 0, max_iteration ):\n # code which will generate next ( x, y, z )\n yield ( x, y, z ) \n\nfor x, y, z in gen_xyz( 1000 ):\n f( x, y, z )\n\n", "The hex() function?\nimport random\nfor i in range(10):\n a1, a2 = random.randint(1,100), random.randint(1,100)\n x = [hex(a1), hex(a2)]\n print x\n\n..outputs something similar to..\n['0x21', '0x4f']\n['0x59', '0x5c']\n['0x61', '0x40']\n['0x57', '0x45']\n['0x1a', '0x11']\n['0x4c', '0x49']\n['0x40', '0x1b']\n['0x1f', '0x7']\n['0x8', '0x2b']\n['0x1e', '0x13']\n\n" ]
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000676198_python.txt
Q: Are there any built-in cross-thread events in python? Is there any built-in syntax in python that allows me to post a message to specific python thread inside my problem? Like 'queued connected signal' in pyQt or ::PostMessage() in Windows. I need this for asynchronous communication between program parts: there is a number of threads that handle network events and they need to post these events to a single 'logic' thread that translates events safe single-threaded way. A: The Queue module is python is well suited to what you're describing. You could have one queue set up that is shared between all your threads. The threads that handle the network events can use queue.put to post events onto the queue. The logic thread would use queue.get to retrieve events from the queue. import Queue # maxsize of 0 means that we can put an unlimited number of events # on the queue q = Queue.Queue(maxsize=0) def network_thread(): while True: e = get_network_event() q.put(e) def logic_thread(): while True: # This will wait until there are events to process e = q.get() process_event(e) A: I'm not really sure what you are looking for. But there is certainly no built-in syntax for that. Have a look at the queue and threading modules. There is a lot of helpful stuff like Queues, Conditions, Events, Locks and Semaphores that can be used to implement all kind of synchronous and asynchronous communications.
Are there any built-in cross-thread events in python?
Is there any built-in syntax in python that allows me to post a message to specific python thread inside my problem? Like 'queued connected signal' in pyQt or ::PostMessage() in Windows. I need this for asynchronous communication between program parts: there is a number of threads that handle network events and they need to post these events to a single 'logic' thread that translates events safe single-threaded way.
[ "The Queue module is python is well suited to what you're describing.\nYou could have one queue set up that is shared between all your threads. The threads that handle the network events can use queue.put to post events onto the queue. The logic thread would use queue.get to retrieve events from the queue.\nimport Queue\n# maxsize of 0 means that we can put an unlimited number of events\n# on the queue\nq = Queue.Queue(maxsize=0)\n\ndef network_thread():\n while True:\n e = get_network_event()\n q.put(e)\n\ndef logic_thread():\n while True:\n # This will wait until there are events to process\n e = q.get()\n process_event(e)\n\n", "I'm not really sure what you are looking for. But there is certainly no built-in syntax for that. Have a look at the queue and threading modules. There is a lot of helpful stuff like Queues, Conditions, Events, Locks and Semaphores that can be used to implement all kind of synchronous and asynchronous communications.\n" ]
[ 11, 1 ]
[]
[]
[ "delegates", "events", "python" ]
stackoverflow_0000676485_delegates_events_python.txt
Q: verbose_name_plural unexpected in a model? I've been doing some models of a future app, and, after adding verbose_name and verbose_name_plural to every entry on a working model, for making it 'beautiful', I've found that at validate time, Django doesn't like that, so it says: File "/home/andor/Documentos/desarrollo/grundymanage/../grundymanage/concursantes/models.py", line 4, in <module> class Concursante(models.Model): File "/home/andor/Documentos/desarrollo/grundymanage/../grundymanage/concursantes/models.py", line 7, in Concursante nombre_artistico = models.CharField(verbose_name='Nombre Artístico', verbose_name_plural='Nombres Artísticos', max_length=50) TypeError: __init__() got an unexpected keyword argument 'verbose_name_plural' My model begins like this: # -*- encoding: utf-8 -*- from django.db import models class Concursante(models.Model): nombre = models.CharField(verbose_name='Nombre', max_length=30) apellidos = models.CharField(verbose_name='Apellidos', max_length=50) nombre_artistico = models.CharField(verbose_name='Nombre Artístico', verbose_name_plural='Nombres Artísticos', max_length=50) Why 'he' didn't expects a plural verbose name there? Cannot live together with verbose_name? FYI, this are my software versions: Ubuntu 8.04 Python 2.5.2 Django "1" "0" "final" Django ubuntu package version "1.0-1ubuntu1" A: There is no verbose_name_plural. It does not make sense to have both singular and plural for one field. They are mutually exclusive. In Django, they share the same name: verbose_name. If your data represents multiple items (e.g. in a one-to-many relationship) use a plural form in verbose_name. Otherwise, if your data represents a single item, use a singular form. Verbose name fields in the Django documentation provides some examples. A: Unfortunately, verbose_name_plural is not an option on the field. It's a meta option for the model itself. A field has no plural name since, unless it's a many-to-many relationship (in which case Django will use the plural for the model pointed to by the relationship), there's only one entity in that field. Here's the doc section: http://docs.djangoproject.com/en/dev/topics/db/models/#id3
verbose_name_plural unexpected in a model?
I've been doing some models of a future app, and, after adding verbose_name and verbose_name_plural to every entry on a working model, for making it 'beautiful', I've found that at validate time, Django doesn't like that, so it says: File "/home/andor/Documentos/desarrollo/grundymanage/../grundymanage/concursantes/models.py", line 4, in <module> class Concursante(models.Model): File "/home/andor/Documentos/desarrollo/grundymanage/../grundymanage/concursantes/models.py", line 7, in Concursante nombre_artistico = models.CharField(verbose_name='Nombre Artístico', verbose_name_plural='Nombres Artísticos', max_length=50) TypeError: __init__() got an unexpected keyword argument 'verbose_name_plural' My model begins like this: # -*- encoding: utf-8 -*- from django.db import models class Concursante(models.Model): nombre = models.CharField(verbose_name='Nombre', max_length=30) apellidos = models.CharField(verbose_name='Apellidos', max_length=50) nombre_artistico = models.CharField(verbose_name='Nombre Artístico', verbose_name_plural='Nombres Artísticos', max_length=50) Why 'he' didn't expects a plural verbose name there? Cannot live together with verbose_name? FYI, this are my software versions: Ubuntu 8.04 Python 2.5.2 Django "1" "0" "final" Django ubuntu package version "1.0-1ubuntu1"
[ "There is no verbose_name_plural. It does not make sense to have both singular and plural for one field. They are mutually exclusive. In Django, they share the same name: verbose_name.\nIf your data represents multiple items (e.g. in a one-to-many relationship) use a plural form in verbose_name. Otherwise, if your data represents a single item, use a singular form.\nVerbose name fields in the Django documentation provides some examples.\n", "Unfortunately, verbose_name_plural is not an option on the field. It's a meta option for the model itself. A field has no plural name since, unless it's a many-to-many relationship (in which case Django will use the plural for the model pointed to by the relationship), there's only one entity in that field.\nHere's the doc section: http://docs.djangoproject.com/en/dev/topics/db/models/#id3\n" ]
[ 5, 5 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0000677172_django_django_models_python.txt
Q: What's the best online tutorial for starting with Spring Python Spring Python seems to be the gold-standard for how to define good quality APIs in Python - it's based on Spring which also seems to be the gold-standard for Java APIs. My manager has complained (with good reason) that our APIs are in a mess - we need to impose some order on them. Since we will be re-factoring it makes sense to take advantage of what is considered best practice - so we would like to consider Spring. Could somebody point me to the best learning resources for getting started with Spring? I've googled for a while and not found anything which seems to start from first principles. I'm looking for something which assumes good knowledge of Python but zero knowledge of Spring on other platforms or it's principles. A: How did you come to decide on Spring Python as your API of choice? Spring works well on Java where there's a tradition of declarative programming; defining your application primarily using XML to control a core engine is a standard pattern in Java. In Python, while the underlying patterns like Inversion of Control are still apposite (depending on your use case), the implementation chosen by Spring looks like a classic case of something produced by a Java programmer who doesn't want to learn Python. See the oft-referenced article Python is Not Java. I applaud your decision to introduce order and thoughtfulness to your codebase, but you may wish to evaluate a number of options before making your decision. In particular, you may find that using Spring Python will make it difficult to hire good Python programmers, many of whom will run the other way when faced with 1000-line XML files describing object interactions. Perhaps start by re-examining what you really want to accomplish. The problem cannot simply be that "you need a framework". There are lots of frameworks out there, and it's hard to evaluate a) if you truly need one and b) which one will work if you haven't identified what underlying software problems you need to solve. If the real problem is that your code is an unmaintainable mess, introducing a framework probably won't fix the issue. Instead of just messy code, you'll have code that is messy in someone else's style :-) Perhaps rigour in the dev team is where you should recommend starting first: good planning, code reviews, stringent hiring practices, a "cleanup" release, etc... Good luck with the research. A: I won't go so far as to suggest that Spring Python is bad (because I don't know enough about it). But, to call Spring Python the "gold standard for Python APIs" is a stretch. To me, it seems that Spring Python is more of a way to allow Python apps to interact with Java Apps using Spring. At any rate, after taking a precursory glance at the official documentation, it seems fairly easy to understand for me having decent knowledge of Python but no knowledge of spring. Aside from the fact that it almost looks like Java code where the author forgot the typenames, semicolons, and curly braces. :-)
What's the best online tutorial for starting with Spring Python
Spring Python seems to be the gold-standard for how to define good quality APIs in Python - it's based on Spring which also seems to be the gold-standard for Java APIs. My manager has complained (with good reason) that our APIs are in a mess - we need to impose some order on them. Since we will be re-factoring it makes sense to take advantage of what is considered best practice - so we would like to consider Spring. Could somebody point me to the best learning resources for getting started with Spring? I've googled for a while and not found anything which seems to start from first principles. I'm looking for something which assumes good knowledge of Python but zero knowledge of Spring on other platforms or it's principles.
[ "How did you come to decide on Spring Python as your API of choice? Spring works well on Java where there's a tradition of declarative programming; defining your application primarily using XML to control a core engine is a standard pattern in Java. \nIn Python, while the underlying patterns like Inversion of Control are still apposite (depending on your use case), the implementation chosen by Spring looks like a classic case of something produced by a Java programmer who doesn't want to learn Python. See the oft-referenced article Python is Not Java.\nI applaud your decision to introduce order and thoughtfulness to your codebase, but you may wish to evaluate a number of options before making your decision. In particular, you may find that using Spring Python will make it difficult to hire good Python programmers, many of whom will run the other way when faced with 1000-line XML files describing object interactions.\nPerhaps start by re-examining what you really want to accomplish. The problem cannot simply be that \"you need a framework\". There are lots of frameworks out there, and it's hard to evaluate a) if you truly need one and b) which one will work if you haven't identified what underlying software problems you need to solve.\nIf the real problem is that your code is an unmaintainable mess, introducing a framework probably won't fix the issue. Instead of just messy code, you'll have code that is messy in someone else's style :-) Perhaps rigour in the dev team is where you should recommend starting first: good planning, code reviews, stringent hiring practices, a \"cleanup\" release, etc...\nGood luck with the research.\n", "I won't go so far as to suggest that Spring Python is bad (because I don't know enough about it). But, to call Spring Python the \"gold standard for Python APIs\" is a stretch. To me, it seems that Spring Python is more of a way to allow Python apps to interact with Java Apps using Spring.\nAt any rate, after taking a precursory glance at the official documentation, it seems fairly easy to understand for me having decent knowledge of Python but no knowledge of spring. Aside from the fact that it almost looks like Java code where the author forgot the typenames, semicolons, and curly braces. :-)\n" ]
[ 11, 1 ]
[]
[]
[ "python", "spring" ]
stackoverflow_0000677255_python_spring.txt
Q: How to check if an RGB image contains only one color? I'm using Python and PIL. I have images in RGB and I would like to know those who contain only one color (say #FF0000 for example) or a few very close colors (#FF0000 and #FF0001). I was thinking about using the histogram but it is very hard to figure out something with the 3 color bands, so I'm looking for a more clever algorithm. Any ideas? ImageStat module is THE answer! Thanks Aaron. I use ImageStat.var to get the variance and it works perfectly. Here is my piece of code: from PIL import Image, ImageStat MONOCHROMATIC_MAX_VARIANCE = 0.005 def is_monochromatic_image(src): v = ImageStat.Stat(Image.open(src)).var return reduce(lambda x, y: x and y < MONOCHROMATIC_MAX_VARIANCE, v, True) A: Try the ImageStat module. If the values returned by extrema are the same, you have only a single color in the image. A: First, you should define a distance between two colors. Then you just have to verify for each pixel that it's distance to your color is small enough. A: Here's a little snippet you could make use of : import Image im = Image.open("path_to_image") width,height = im.size for w in range(0,width): for h in range(0,height): # this will hold the value of all the channels color_tuple = im.getpixel((w,h)) # do something with the colors here Maybe use a hash and store the tuples as the key and it's number of appearances as value?
How to check if an RGB image contains only one color?
I'm using Python and PIL. I have images in RGB and I would like to know those who contain only one color (say #FF0000 for example) or a few very close colors (#FF0000 and #FF0001). I was thinking about using the histogram but it is very hard to figure out something with the 3 color bands, so I'm looking for a more clever algorithm. Any ideas? ImageStat module is THE answer! Thanks Aaron. I use ImageStat.var to get the variance and it works perfectly. Here is my piece of code: from PIL import Image, ImageStat MONOCHROMATIC_MAX_VARIANCE = 0.005 def is_monochromatic_image(src): v = ImageStat.Stat(Image.open(src)).var return reduce(lambda x, y: x and y < MONOCHROMATIC_MAX_VARIANCE, v, True)
[ "Try the ImageStat module. If the values returned by extrema are the same, you have only a single color in the image.\n", "First, you should define a distance between two colors.\nThen you just have to verify for each pixel that it's distance to your color is small enough.\n", "Here's a little snippet you could make use of :\n\nimport Image\n\nim = Image.open(\"path_to_image\")\nwidth,height = im.size\n\nfor w in range(0,width):\n for h in range(0,height):\n # this will hold the value of all the channels\n color_tuple = im.getpixel((w,h))\n # do something with the colors here\n\nMaybe use a hash and store the tuples as the key and it's number of appearances as value?\n" ]
[ 6, 0, 0 ]
[]
[]
[ "colors", "image", "python", "python_imaging_library" ]
stackoverflow_0000677395_colors_image_python_python_imaging_library.txt
Q: How to extract from a list of objects a list of specific attribute? I have a list of objects. Object has 3 string attributes. I want to make a list containing only a specific attribute from class. Is there any built-in functions to do that? A: A list comprehension would work just fine: [o.my_attr for o in my_list] But there is a combination of built-in functions, since you ask :-) from operator import attrgetter map(attrgetter('my_attr'), my_list) A: are you looking for something like this? [o.specific_attr for o in objects] A: The first thing that came to my mind: attrList = map(lambda x: x.attr, objectList) A: Assuming you want field b for the objects in a list named objects do this: [o.b for o in objects]
How to extract from a list of objects a list of specific attribute?
I have a list of objects. Object has 3 string attributes. I want to make a list containing only a specific attribute from class. Is there any built-in functions to do that?
[ "A list comprehension would work just fine:\n[o.my_attr for o in my_list]\n\nBut there is a combination of built-in functions, since you ask :-)\nfrom operator import attrgetter\nmap(attrgetter('my_attr'), my_list)\n\n", "are you looking for something like this?\n[o.specific_attr for o in objects]\n\n", "The first thing that came to my mind:\nattrList = map(lambda x: x.attr, objectList)\n\n", "Assuming you want field b for the objects in a list named objects do this: \n[o.b for o in objects]\n\n" ]
[ 88, 10, 9, 4 ]
[]
[]
[ "python" ]
stackoverflow_0000677656_python.txt
Q: Yahoo Pipes, simplejson and slashes Im trying to use http://www.javarants.com/2008/04/13/using-google-app-engine-to-extend-yahoo-pipes/ as inspiration, but I'm having some troubles with the output. Its obvious when testing with the console and the App Engine "django util simplejson": /cygdrive/c/Program Files/Google/google_appengine/lib/django $ python Python 2.5.2 (r252:60911, Dec 2 2008, 09:26:14) [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> from django.utils import simplejson as json >>> json.dumps('/') '"\\/"' >>> json.dumps('http://stackoverflow.com') '"http:\\/\\/stackoverflow.com" As far as I can read this is ok behavior: In JSON only the backslash, double quote and ASCII control characters need to be escaped. Forward slashes may be escaped as in the URL example below, but do not have to be. But when inputting back to yahoopipes, they don't "unescape" the output and all my urls and html doesnt work. should I really do a self.response.out.write(json.dumps(obj).replace('\\/','/')) ? ==== Edit === To my great suprise I see that newest simplejson downloaded from simplejson site doesnt do the "slash" stuff :( So the real issue is with app engines django.util.simplejson version? === Edit again === And now Ive created an issue in the tracker for it: http://code.google.com/p/googleappengine/issues/detail?id=1128 A: Nothing here to see. The ticket is there, but thats it, as far as I can see
Yahoo Pipes, simplejson and slashes
Im trying to use http://www.javarants.com/2008/04/13/using-google-app-engine-to-extend-yahoo-pipes/ as inspiration, but I'm having some troubles with the output. Its obvious when testing with the console and the App Engine "django util simplejson": /cygdrive/c/Program Files/Google/google_appengine/lib/django $ python Python 2.5.2 (r252:60911, Dec 2 2008, 09:26:14) [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> from django.utils import simplejson as json >>> json.dumps('/') '"\\/"' >>> json.dumps('http://stackoverflow.com') '"http:\\/\\/stackoverflow.com" As far as I can read this is ok behavior: In JSON only the backslash, double quote and ASCII control characters need to be escaped. Forward slashes may be escaped as in the URL example below, but do not have to be. But when inputting back to yahoopipes, they don't "unescape" the output and all my urls and html doesnt work. should I really do a self.response.out.write(json.dumps(obj).replace('\\/','/')) ? ==== Edit === To my great suprise I see that newest simplejson downloaded from simplejson site doesnt do the "slash" stuff :( So the real issue is with app engines django.util.simplejson version? === Edit again === And now Ive created an issue in the tracker for it: http://code.google.com/p/googleappengine/issues/detail?id=1128
[ "Nothing here to see. The ticket is there, but thats it, as far as I can see\n" ]
[ 0 ]
[]
[]
[ "python", "simplejson", "yahoo_pipes" ]
stackoverflow_0000610205_python_simplejson_yahoo_pipes.txt
Q: Using 'old' database with django I'm using a hand built (Postgres) database with Django. With "inspectdb" I was able to automatically create a model for it. The problem is that some tables have multiple primary keys (for many-to-many relations) and they are not accessible via Django. What's the best way to access these tables? A: There is no way to use composite primary keys in Django's ORM as of now (up to v1.0.2). I can only think of three solutions/workarounds: There is a fork of django with a composite pk patch at github that you might want to try. You could use SQLAlchemy together with Django. You have to add a single field primary key field to those tables. A: Django does have support for many-to-many relationships. If you want to use a helper table to manage this relationships, the ManyToManyField takes a through argument which specifies the table to use. You can't model anything terribly complex this way, but it is good for most simple applications.
Using 'old' database with django
I'm using a hand built (Postgres) database with Django. With "inspectdb" I was able to automatically create a model for it. The problem is that some tables have multiple primary keys (for many-to-many relations) and they are not accessible via Django. What's the best way to access these tables?
[ "There is no way to use composite primary keys in Django's ORM as of now (up to v1.0.2).\nI can only think of three solutions/workarounds:\n\nThere is a fork of django with a composite pk patch at github that you might want to try.\nYou could use SQLAlchemy together with Django.\nYou have to add a single field primary key field to those tables.\n\n", "Django does have support for many-to-many relationships. If you want to use a helper table to manage this relationships, the ManyToManyField takes a through argument which specifies the table to use. You can't model anything terribly complex this way, but it is good for most simple applications.\n" ]
[ 4, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000677476_django_python.txt
Q: python and symbian - keystroke capture I'm trying to write a simple prototyping appliaction in python to capture a users keystrokes while writing a text messages (SMS) to collect some stat info for use in a biometric application for Symbian based phones. I have never used python before and have had very little exposure to it. However, I did come across an example http://wiki.forum.nokia.com/index.php/How_to_use_Keys_in_PyS60 detailing how to capture UP, DOWN, LEFT, RIGHT, and 0-9 easily enough. I tried to find information on key_codes and keypress in the pys60 API but little is available as I'm looking for an example of how to capture characters such as 'a', 'b' etc. assuming that predictive text is disabled. Also, if it is not possible to capture characters, how feasible is it to map keypresses to characters? i.e. 228 = 'b','t'? Can anyone provide me with some examples, suggestions or a push in the right direction? A: I think you are searching for the wrong thing here. Key codes and keypress events will only capture up, down, etc. (actual buttons), as you already stated. The user can enter letters in multiple ways, which is all done through software (e.g. 22 is a 'b', or 228 might be 'cat' or 'bat') and there is no way to tell what the user entered based just on the buttons they hit. There is also auto-completion built into most phones, which will add characters the user did not press buttons for. Try searching for ways of capturing the actual text the user is seeing.
python and symbian - keystroke capture
I'm trying to write a simple prototyping appliaction in python to capture a users keystrokes while writing a text messages (SMS) to collect some stat info for use in a biometric application for Symbian based phones. I have never used python before and have had very little exposure to it. However, I did come across an example http://wiki.forum.nokia.com/index.php/How_to_use_Keys_in_PyS60 detailing how to capture UP, DOWN, LEFT, RIGHT, and 0-9 easily enough. I tried to find information on key_codes and keypress in the pys60 API but little is available as I'm looking for an example of how to capture characters such as 'a', 'b' etc. assuming that predictive text is disabled. Also, if it is not possible to capture characters, how feasible is it to map keypresses to characters? i.e. 228 = 'b','t'? Can anyone provide me with some examples, suggestions or a push in the right direction?
[ "I think you are searching for the wrong thing here.\nKey codes and keypress events will only capture up, down, etc. (actual buttons), as you already stated. The user can enter letters in multiple ways, which is all done through software (e.g. 22 is a 'b', or 228 might be 'cat' or 'bat') and there is no way to tell what the user entered based just on the buttons they hit. There is also auto-completion built into most phones, which will add characters the user did not press buttons for.\nTry searching for ways of capturing the actual text the user is seeing.\n" ]
[ 1 ]
[]
[]
[ "pys60", "python", "symbian" ]
stackoverflow_0000677846_pys60_python_symbian.txt
Q: Doctest for dynamically created objects What is the best way to test code like this (the one below obviously fails while object is created in different block every time): def get_session(db_name, verbose, test): """Returns current DB session from SQLAlchemy pool. >>> get_session('Mmusc20090126', False, True) <sqlalchemy.orm.session.Session object at 0xfb5ff0> """ if test: engine = create_engine('sqlite:///:memory:', echo=verbose) log_load.debug('DB in RAM.') else: engine = create_engine('sqlite:///' + 'DB/' + db_name + '.db', echo=verbose) log_load.debug('DB stored in file: %s' % 'DB/' + db_name + '.db') # Create TABLES: Structures, Interactions, Interactors, PDB_UniProt, UniProtSeq meta.create_all(engine) Session = sessionmaker(bind=engine) session = Session() return session A: I think you want to use ellipsis, like this: >>> get_session('Mmusc20090126', False, True) #doctest: +ELLIPSIS <sqlalchemy.orm.session.Session object at 0x...> See here for more info.
Doctest for dynamically created objects
What is the best way to test code like this (the one below obviously fails while object is created in different block every time): def get_session(db_name, verbose, test): """Returns current DB session from SQLAlchemy pool. >>> get_session('Mmusc20090126', False, True) <sqlalchemy.orm.session.Session object at 0xfb5ff0> """ if test: engine = create_engine('sqlite:///:memory:', echo=verbose) log_load.debug('DB in RAM.') else: engine = create_engine('sqlite:///' + 'DB/' + db_name + '.db', echo=verbose) log_load.debug('DB stored in file: %s' % 'DB/' + db_name + '.db') # Create TABLES: Structures, Interactions, Interactors, PDB_UniProt, UniProtSeq meta.create_all(engine) Session = sessionmaker(bind=engine) session = Session() return session
[ "I think you want to use ellipsis, like this:\n>>> get_session('Mmusc20090126', False, True) #doctest: +ELLIPSIS\n<sqlalchemy.orm.session.Session object at 0x...>\n\nSee here for more info.\n" ]
[ 10 ]
[]
[]
[ "docstring", "doctest", "python", "sqlalchemy", "testing" ]
stackoverflow_0000677931_docstring_doctest_python_sqlalchemy_testing.txt
Q: Specifying different template names in Django generic views I have the code in my urls.py for my generic views; infodict = { 'queryset': Post.objects.all(), 'date_field': 'date', 'template_name': 'index.html', 'template_object_name': 'latest_post_list', } urlpatterns += patterns('django.views.generic.date_based', (r'^gindex/$', 'archive_index', infodict), ) So going to the address /gindex/ will use a generic view with the template of 'index.html'. But since I will have more generic views in this urlpattern, how am I supposed to provide a different template name using the same infodict? I don't want to have to use lots of infodicts, and I can't use the default template name. Please note this also applies to template object name within infodict. Thanks for your help! Edit: This is one of my first questions on stackoverflow and I am amazed with the thorough answers! I prefer using the dict constructor which I didn't know about. I find using the python documentation a bit harder as I can't find what i'm looking for usually! Thanks again for all the answers and different approaches. A: Use the dict() constructor: infodict = { 'queryset': Post.objects.all(), 'date_field': 'date', 'template_name': 'index.html', 'template_object_name': 'latest_post_list', } urlpatterns = patterns('django.views.generic.date_based', url(r'^gindex/$', 'archive_index', dict(infodict, template_name='gindex.html')), url(r'^hindex/$', 'archive_index', dict(infodict, template_name='hindex.html')), ) A: If you want to supply different template names to different views, the common practice is indeed to pass in a unique dictionary to each URL pattern. For example: urlpatterns = patterns('', url(r'^home/$', 'my.views.home', {'template_name': 'home.html'}, name='home'), url(r'^about/$', 'my.views.about', {'template_name': 'about.html'}, name='about'), ) This kind of pattern is common and acceptable. A: Not as simple, but possibly useful if you have a whole lot of different patterns matching the same view: base_dict={ ... #defaults go here } def make_dict(template_name,template_object_name): base_dict.update({ 'template_name':template_name, 'template_object_name':template_object_name, }) return base_dict urlpatterns += patterns('django.views.generic.date_based', (r'^gindex/$', 'archive_index', make_dict('index1.html','latest_poll_list')), (r'^hindex/$', 'archive_index', make_dict('index2.html','oldest_poll_list')), ) For a lot of similar generic views, this will condense your code calls a wee bit, at the expense of a little bit of transparency. If you've got many lines customizing the same few parameters, this might be easiest to read. Finally, if all or most of your views require some, but not all, of the same information, never forget how useful a context processor is. It takes only a little more work to set up than the above solutions, but it extends much better, because it will guarantee that (unless you use the render_to_response shortcut without the RequestContext keyword) the defaults will always be available to your template no matter how your view or url conf changes. A: you can define wrapper view functions to parametrize generic views. In your urls.py add pattern url(r'^/(?P<tmpl_name>\w+)/$', 'my.views.datebasedproxy') in your views.py add view function def datebasedproxy(request, tmpl_name): return django.views.generic.date_based(request,otherparameters, template_name=tmpl_matrix[tmpl_name]) where tmpl_matrix is hypothetic list that matches template file name with parameter and otherparameters stands for other dictionary items required for date_based function
Specifying different template names in Django generic views
I have the code in my urls.py for my generic views; infodict = { 'queryset': Post.objects.all(), 'date_field': 'date', 'template_name': 'index.html', 'template_object_name': 'latest_post_list', } urlpatterns += patterns('django.views.generic.date_based', (r'^gindex/$', 'archive_index', infodict), ) So going to the address /gindex/ will use a generic view with the template of 'index.html'. But since I will have more generic views in this urlpattern, how am I supposed to provide a different template name using the same infodict? I don't want to have to use lots of infodicts, and I can't use the default template name. Please note this also applies to template object name within infodict. Thanks for your help! Edit: This is one of my first questions on stackoverflow and I am amazed with the thorough answers! I prefer using the dict constructor which I didn't know about. I find using the python documentation a bit harder as I can't find what i'm looking for usually! Thanks again for all the answers and different approaches.
[ "Use the dict() constructor:\ninfodict = {\n 'queryset': Post.objects.all(),\n 'date_field': 'date',\n 'template_name': 'index.html',\n 'template_object_name': 'latest_post_list',\n}\n\nurlpatterns = patterns('django.views.generic.date_based',\n url(r'^gindex/$', 'archive_index', dict(infodict, template_name='gindex.html')),\n url(r'^hindex/$', 'archive_index', dict(infodict, template_name='hindex.html')),\n)\n\n", "If you want to supply different template names to different views, the common practice is indeed to pass in a unique dictionary to each URL pattern. For example:\nurlpatterns = patterns('',\n url(r'^home/$', 'my.views.home', {'template_name': 'home.html'}, name='home'),\n url(r'^about/$', 'my.views.about', {'template_name': 'about.html'}, name='about'),\n)\n\nThis kind of pattern is common and acceptable.\n", "Not as simple, but possibly useful if you have a whole lot of different patterns matching the same view:\nbase_dict={\n...\n#defaults go here\n}\ndef make_dict(template_name,template_object_name):\n base_dict.update({\n 'template_name':template_name,\n 'template_object_name':template_object_name,\n })\n return base_dict\n\nurlpatterns += patterns('django.views.generic.date_based',\n(r'^gindex/$', 'archive_index', make_dict('index1.html','latest_poll_list')),\n(r'^hindex/$', 'archive_index', make_dict('index2.html','oldest_poll_list')),\n)\n\nFor a lot of similar generic views, this will condense your code calls a wee bit, at the expense of a little bit of transparency. If you've got many lines customizing the same few parameters, this might be easiest to read.\nFinally, if all or most of your views require some, but not all, of the same information, never forget how useful a context processor is. It takes only a little more work to set up than the above solutions, but it extends much better, because it will guarantee that (unless you use the render_to_response shortcut without the RequestContext keyword) the defaults will always be available to your template no matter how your view or url conf changes.\n", "you can define wrapper view functions to parametrize generic views.\nIn your urls.py add pattern\nurl(r'^/(?P<tmpl_name>\\w+)/$', 'my.views.datebasedproxy')\n\nin your views.py add view function\ndef datebasedproxy(request, tmpl_name):\n return django.views.generic.date_based(request,otherparameters,\n template_name=tmpl_matrix[tmpl_name])\n\nwhere tmpl_matrix is hypothetic list that matches template file name with parameter and otherparameters stands for other dictionary items required for date_based function\n" ]
[ 8, 1, 0, 0 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0000677793_django_django_urls_python.txt
Q: What payment processing frameworks, like ActiveMerchant, are available for other languages? Rails has frameworks such as ActiveMerchant and Freemium (which uses ActiveMerchant) to simplify dealing with payment processing. What other frameworks are there for other programming languages such as PHP or Python? A: Edit For processing payments, there are several GetPaid modules available for Python. Check out the core package, as well as some extensions for different payment methods. ----------original answer------------ From a StackOverflow search: Satchmo is a Python alternative. See that question link above for other ideas.
What payment processing frameworks, like ActiveMerchant, are available for other languages?
Rails has frameworks such as ActiveMerchant and Freemium (which uses ActiveMerchant) to simplify dealing with payment processing. What other frameworks are there for other programming languages such as PHP or Python?
[ "Edit For processing payments, there are several GetPaid modules available for Python.\nCheck out the core package, as well as some extensions for different payment methods.\n----------original answer------------\nFrom a StackOverflow search: Satchmo is a Python alternative.\nSee that question link above for other ideas.\n" ]
[ 3 ]
[]
[]
[ "activemerchant", "php", "programming_languages", "python", "ruby_on_rails" ]
stackoverflow_0000678525_activemerchant_php_programming_languages_python_ruby_on_rails.txt
Q: Fill Django application with data using very large Python script I wrote a program that outputs a Python program that fills my Django application with data. This program however is 23 MB large and my computer won't run it. Is there a solution for this? Another possible solution to fill the database would be using a fixture. The problem is that I don't know the new primary keys yet... or I would have to use the old ones (which I don't prefer). Any suggestions? The reason for my path: I'm migrating a database that is very different from the new one, it also has many relations. The 23 MB program remembers all objects from the source database, that's why it's not easily cut in half. Maybe there is a better way to do this? I prefer using Django than using raw SQL. A: In most cases, you can find a natural hierarchy to your objects. Sometimes there is some kind of "master" and all other objects have foreign key (FK) references to this master and to each other. In this case, you can use an XML-like structure with each master object "containing" a lot of subsidiary objects. In this case, you insert the master first, and all the children have FK references to an existing object. In some cases, however, there are relationships that can't be simple FK's to an existing object. In this case you have circular dependencies and you must (1) break this dependency temporarily and (2) recreate the dependency after the objects are loaded. You do this by (a) defining your model to have an optional FK, (b) and having a temporary "natural key" reference. You'll load data without the proper FK (it's optional). Then, after your data is loaded, you go back through a second pass and insert all of the missing FK references. Once this is done you can then modify your model to make the FK mandatory. Program 1 - export from old database to simple flat-file. CSV format or JSON format or something simple. for m in OldModel.objects.all(): aDict = { 'col1':m.col1, 'old_at_fk':m.fktoanothertable.id, 'old_id':id } csvwriter.writerow( aDict ) Program 2 - read simple flat-file; build new database model objects. # Pass 1 - raw load for row in csv.reader: new= NewModel.create( **row ) # Pass 2 - resolve FK's for nm in NewModel.objects.all(): ref1= OtherModel.objects.get( old_id=nm.old_at_fk ) nm.properfk = ref1 nm.save() A: Your computer wouldn't run it because is a large program? Maybe you should reference an external file, or files, with all the structure, and then dump it inside the database, instead of writing it inside your script/software... A: Put the data in a separate file (or files). Then write a small program that reads in the data and populates your database via Django. A: If I am reading your post correctly, you are reading from the old database and writing a "python program" based on that data. This seems to me to be the wrong way to do this. My suggestion would be to create a malleable version of the old database (XML would work well for this) by reading the data from the DB, modifying it as needed, and then dumping it into a file. With this malleable version of the data, use a separate program to import this data into the new database via your Django Models. This will also give you a level of flexibility if you ever need to duplicate this process.
Fill Django application with data using very large Python script
I wrote a program that outputs a Python program that fills my Django application with data. This program however is 23 MB large and my computer won't run it. Is there a solution for this? Another possible solution to fill the database would be using a fixture. The problem is that I don't know the new primary keys yet... or I would have to use the old ones (which I don't prefer). Any suggestions? The reason for my path: I'm migrating a database that is very different from the new one, it also has many relations. The 23 MB program remembers all objects from the source database, that's why it's not easily cut in half. Maybe there is a better way to do this? I prefer using Django than using raw SQL.
[ "In most cases, you can find a natural hierarchy to your objects. Sometimes there is some kind of \"master\" and all other objects have foreign key (FK) references to this master and to each other.\nIn this case, you can use an XML-like structure with each master object \"containing\" a lot of subsidiary objects. In this case, you insert the master first, and all the children have FK references to an existing object.\nIn some cases, however, there are relationships that can't be simple FK's to an existing object. In this case you have circular dependencies and you must (1) break this dependency temporarily and (2) recreate the dependency after the objects are loaded.\nYou do this by (a) defining your model to have an optional FK, (b) and having a temporary \"natural key\" reference. You'll load data without the proper FK (it's optional). \nThen, after your data is loaded, you go back through a second pass and insert all of the missing FK references. Once this is done you can then modify your model to make the FK mandatory.\nProgram 1 - export from old database to simple flat-file. CSV format or JSON format or something simple.\nfor m in OldModel.objects.all():\n aDict = { 'col1':m.col1, 'old_at_fk':m.fktoanothertable.id, 'old_id':id }\n csvwriter.writerow( aDict )\n\nProgram 2 - read simple flat-file; build new database model objects.\n# Pass 1 - raw load\n\nfor row in csv.reader:\n new= NewModel.create( **row )\n\n# Pass 2 - resolve FK's\n\nfor nm in NewModel.objects.all():\n ref1= OtherModel.objects.get( old_id=nm.old_at_fk )\n nm.properfk = ref1\n nm.save()\n\n", "Your computer wouldn't run it because is a large program?\nMaybe you should reference an external file, or files, with all the structure, and then dump it inside the database, instead of writing it inside your script/software...\n", "Put the data in a separate file (or files). Then write a small program that reads in the data and populates your database via Django. \n", "If I am reading your post correctly, you are reading from the old database and writing a \"python program\" based on that data. This seems to me to be the wrong way to do this.\nMy suggestion would be to create a malleable version of the old database (XML would work well for this) by reading the data from the DB, modifying it as needed, and then dumping it into a file.\nWith this malleable version of the data, use a separate program to import this data into the new database via your Django Models.\nThis will also give you a level of flexibility if you ever need to duplicate this process.\n" ]
[ 1, 0, 0, 0 ]
[]
[]
[ "database", "django", "migration", "python" ]
stackoverflow_0000677962_database_django_migration_python.txt
Q: What's the correct way to add extra find-links to easy_install when called as a function? I need to call easy_install as a function to install some Python eggs from a bunch of servers. Precisely what I install and where I get it from is determined at run-time: For example which servers I use depends on the geographic location of the computer. Since I cannot guarantee that any single server will always be available, it has been decided that my script needs to check a number of servers. Some locations have prohibitive web-filtering so I need to check a UNC path. Other locations require me to check a mix, as in this example: myargs = ['-vv', '-m', '-a', '-f', '//filesrver/eggs http://webserver1/python_eggs http://webserver2/python_eggs, 'myproject==trunk-99'] setuptools.command.easy_install.main( myargs ) It seems to work just fine when I do not provide a find-links option (-f) (in this case it just picks up the defaults from distutils.cfg), when I try to specify an additional find-links the option all I get is: Traceback (most recent call last): File "D:\workspace\pythonscripts_trunk\javapy_egg\Scripts\test_javapy.py", line 20, in ? result = pyproxy.requireEgg( eggspec , True, hosts ) File "d:\workspace\pythonscripts_trunk\javapy_egg\src\calyon\javapy\pyproxy.py", line 141, in requireEgg pkg_resources.require(eggname) File "d:\python24\lib\site-packages\setuptools-0.6c9-py2.4.egg\pkg_resources. py", line 626, in require needed = self.resolve(parse_requirements(requirements)) File "d:\python24\lib\site-packages\setuptools-0.6c9-py2.4.egg\pkg_resources.py", line 524, in resolve raise DistributionNotFound(req) # XXX put more info here pkg_resources.DistributionNotFound: myproject==trunk-99 Can somebody confirm the correct way to do this? For example do I use Windows or UNIX slashes in the arguments? What character must be used to seperate multiple URLs? I'm using setuptools 0.6c9 on Windows32 A: Quote: myargs = ['-vv', '-m', '-a', '-f', '//filesrver/eggs http://webserver1/python_eggs http://webserver2/python_eggs, 'myproject==trunk-99'] setuptools.command.easy_install.main( myargs ) This first problem I see with this is that you're missing a single quote on the end of your list of servers to look in. Also, it's generally a good idea to surround each URL with double quotes to make sure they each get interpreted as a single item. I'm not sure what you're doing with this argument 'myproject==trunk-99', but the way you have it written above, easy_install is interpreting it as a package name (see the documentation). You probably want to drop the myproject== as it is only looking for the project name, not a Boolean or keyword argument. Also, I think you meant to use the -v argument instead of the non-existant -vv. You were correct to use a space to separate your list of URLs/servers. Forward slashes will work on both Unix and Windows. Something like this should work for you: myargs = ['-v', '-m', '-a', '-f', '"//filesrver/eggs/" "http://webserver1/python_eggs/" "http://webserver2/python_eggs/"', 'trunk-99'] setuptools.command.easy_install.main( myargs )
What's the correct way to add extra find-links to easy_install when called as a function?
I need to call easy_install as a function to install some Python eggs from a bunch of servers. Precisely what I install and where I get it from is determined at run-time: For example which servers I use depends on the geographic location of the computer. Since I cannot guarantee that any single server will always be available, it has been decided that my script needs to check a number of servers. Some locations have prohibitive web-filtering so I need to check a UNC path. Other locations require me to check a mix, as in this example: myargs = ['-vv', '-m', '-a', '-f', '//filesrver/eggs http://webserver1/python_eggs http://webserver2/python_eggs, 'myproject==trunk-99'] setuptools.command.easy_install.main( myargs ) It seems to work just fine when I do not provide a find-links option (-f) (in this case it just picks up the defaults from distutils.cfg), when I try to specify an additional find-links the option all I get is: Traceback (most recent call last): File "D:\workspace\pythonscripts_trunk\javapy_egg\Scripts\test_javapy.py", line 20, in ? result = pyproxy.requireEgg( eggspec , True, hosts ) File "d:\workspace\pythonscripts_trunk\javapy_egg\src\calyon\javapy\pyproxy.py", line 141, in requireEgg pkg_resources.require(eggname) File "d:\python24\lib\site-packages\setuptools-0.6c9-py2.4.egg\pkg_resources. py", line 626, in require needed = self.resolve(parse_requirements(requirements)) File "d:\python24\lib\site-packages\setuptools-0.6c9-py2.4.egg\pkg_resources.py", line 524, in resolve raise DistributionNotFound(req) # XXX put more info here pkg_resources.DistributionNotFound: myproject==trunk-99 Can somebody confirm the correct way to do this? For example do I use Windows or UNIX slashes in the arguments? What character must be used to seperate multiple URLs? I'm using setuptools 0.6c9 on Windows32
[ "Quote:\nmyargs = ['-vv', '-m', '-a', '-f', '//filesrver/eggs http://webserver1/python_eggs http://webserver2/python_eggs, 'myproject==trunk-99']\n\nsetuptools.command.easy_install.main( myargs )\n\nThis first problem I see with this is that you're missing a single quote on the end of your list of servers to look in.\nAlso, it's generally a good idea to surround each URL with double quotes to make sure they each get interpreted as a single item.\nI'm not sure what you're doing with this argument 'myproject==trunk-99', but the way you have it written above, easy_install is interpreting it as a package name (see the documentation).\nYou probably want to drop the myproject== as it is only looking for the project name, not a Boolean or keyword argument.\nAlso, I think you meant to use the -v argument instead of the non-existant -vv.\nYou were correct to use a space to separate your list of URLs/servers. Forward slashes will work on both Unix and Windows.\nSomething like this should work for you:\nmyargs = ['-v', '-m', '-a', '-f', '\"//filesrver/eggs/\" \"http://webserver1/python_eggs/\" \"http://webserver2/python_eggs/\"', 'trunk-99']\nsetuptools.command.easy_install.main( myargs )\n\n" ]
[ 3 ]
[]
[]
[ "python", "setuptools" ]
stackoverflow_0000659575_python_setuptools.txt
Q: Select Distinct Years and Months for Django Archive Page I want to make an archive_index page for my django site. However, the date-based generic views really aren't any help. I want the dictionary returned by the view to have all the years and months for which at least one instance of the object type exists. So if my blog started in September 2007, but there were no posts in April 2008, I could get something like this 2009 - Jan, Feb, Mar 2008 - Jan, Feb, Mar, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec 2007 - Sep, Oct, Nov, Dec A: This will give you a list of unique posting dates: Posts.objects.filter(draft=False).dates('post_date','month',order='DESC') Of course you might not need the draft filter, and change 'post_date' to your field name, etc. A: I found the answer to my own question. It's on this page in the documentation. There's a function called dates that will give you distinct dates. So I can do Entry.objects.dates('pub_date','month') to get a list of datetime objects, one for each year/month. A: You should be able to get all the info you describe from the built-in views. Can you be more specific as to what you cannot get? This should have everything you need: django.views.generic.date_based.archive_month Reference page (search for the above string on that page)
Select Distinct Years and Months for Django Archive Page
I want to make an archive_index page for my django site. However, the date-based generic views really aren't any help. I want the dictionary returned by the view to have all the years and months for which at least one instance of the object type exists. So if my blog started in September 2007, but there were no posts in April 2008, I could get something like this 2009 - Jan, Feb, Mar 2008 - Jan, Feb, Mar, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec 2007 - Sep, Oct, Nov, Dec
[ "This will give you a list of unique posting dates:\nPosts.objects.filter(draft=False).dates('post_date','month',order='DESC')\n\nOf course you might not need the draft filter, and change 'post_date' to your field name, etc.\n", "I found the answer to my own question. \nIt's on this page in the documentation.\nThere's a function called dates that will give you distinct dates. So I can do\nEntry.objects.dates('pub_date','month') to get a list of datetime objects, one for each year/month. \n", "You should be able to get all the info you describe from the built-in views. Can you be more specific as to what you cannot get? This should have everything you need:\ndjango.views.generic.date_based.archive_month\n\nReference page (search for the above string on that page)\n" ]
[ 41, 14, 1 ]
[]
[]
[ "datetime", "django", "django_queryset", "django_views", "python" ]
stackoverflow_0000678927_datetime_django_django_queryset_django_views_python.txt
Q: SQLAlchemy with count, group_by and order_by using the ORM I've got several function where I need to do a one-to-many join, using count(), group_by, and order_by. I'm using the sqlalchemy.select function to produce a query that will return me a set of id's, which I then iterate over to do an ORM select on the individual records. What I'm wondering is if there is a way to do what I need using the ORM in a single query so that I can avoid having to do the iteration. Here's an example of what I'm doing now. In this case the entities are Location and Guide, mapped one-to-many. I'm trying get a list of the top locations sorted by how many guides they are related to. def popular_world_cities(self): query = select([locations.c.id, func.count(Guide.location_id).label('count')], from_obj=[locations, guides], whereclause="guides.location_id = locations.id AND (locations.type = 'city' OR locations.type = 'custom')", group_by=[Location.id], order_by='count desc', limit=10) return map(lambda x: meta.Session.query(Location).filter_by(id=x[0]).first(), meta.engine.execute(query).fetchall()) Solution I've found the best way to do this. Simply supply a from_statement instead of a filter_by or some such. Like so: meta.Session.query(Location).from_statement(query).all() A: What you're trying to do maps directly to a SQLAlchemy join between a subquery [made from your current select call] and a table. You'll want to move the ordering out of the subselect and create a separate, labeled column with count(desc); order the outer select by that column. Other than that, I don't see much that's nonobvious. A: I found this the hard way but SQLAlchemy does support group_by. The documentation under Query doesn't say so but it does support it - I have used it! And, you can also use order_by. I was going to create a special class/query like you did but then I found out there is a group_by() function. A: I've found the best way to do this. Simply supply a from_statement instead of a filter_by or some such. Like so: meta.Session.query(Location).from_statement(query).all()
SQLAlchemy with count, group_by and order_by using the ORM
I've got several function where I need to do a one-to-many join, using count(), group_by, and order_by. I'm using the sqlalchemy.select function to produce a query that will return me a set of id's, which I then iterate over to do an ORM select on the individual records. What I'm wondering is if there is a way to do what I need using the ORM in a single query so that I can avoid having to do the iteration. Here's an example of what I'm doing now. In this case the entities are Location and Guide, mapped one-to-many. I'm trying get a list of the top locations sorted by how many guides they are related to. def popular_world_cities(self): query = select([locations.c.id, func.count(Guide.location_id).label('count')], from_obj=[locations, guides], whereclause="guides.location_id = locations.id AND (locations.type = 'city' OR locations.type = 'custom')", group_by=[Location.id], order_by='count desc', limit=10) return map(lambda x: meta.Session.query(Location).filter_by(id=x[0]).first(), meta.engine.execute(query).fetchall()) Solution I've found the best way to do this. Simply supply a from_statement instead of a filter_by or some such. Like so: meta.Session.query(Location).from_statement(query).all()
[ "What you're trying to do maps directly to a SQLAlchemy join between a subquery [made from your current select call] and a table. You'll want to move the ordering out of the subselect and create a separate, labeled column with count(desc); order the outer select by that column.\nOther than that, I don't see much that's nonobvious.\n", "I found this the hard way but SQLAlchemy does support group_by. The documentation under Query doesn't say so but it does support it - I have used it!\nAnd, you can also use order_by. I was going to create a special class/query like you did but then I found out there is a group_by() function.\n", "I've found the best way to do this. Simply supply a from_statement instead of a filter_by or some such. Like so:\nmeta.Session.query(Location).from_statement(query).all()\n\n" ]
[ 1, 1, 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0000370174_python_sqlalchemy.txt
Q: min heap in python I'd like to store a set of objects in a min heap by defining a custom comparison function. I see there is a heapq module available as part of the python distribution. Is there a way to use a custom comparator with this module? If not, has someone else built a custom min heap? A: Two options (aside from Devin Jeanpierre's suggestion): Decorate your data before using the heap. This is the equivalent of the key= option to sorting. e.g. if you (for some reason) wanted to heapify a list of numbers according to their sine: data = [ # list of numbers ] heap = [(math.sin(x), x) for x in data] heapq.heapify(heap) # get the min element item = heappop(heap)[1] The heapq module is implemented in pure python. You could just copy it to your working directory and change the relevant bits. From a quick look, you would have to modify siftdown() and siftup(), and possibly nlargest and nsmallest if you need them. A: Yes, there is a way. Define a wrapping class that implements your custom comparator, and use a list of those instead of a list of your actual objects. That's about the best there is while still using the heapq module, since it provides no key= or cmp= arguments like the sorting functions/methods do. def gen_wrapper(cmp): class Wrapper(object): def __init__(self, value): self.value = value def __cmp__(self, obj): return cmp(self.value, obj.value) return Wrapper
min heap in python
I'd like to store a set of objects in a min heap by defining a custom comparison function. I see there is a heapq module available as part of the python distribution. Is there a way to use a custom comparator with this module? If not, has someone else built a custom min heap?
[ "Two options (aside from Devin Jeanpierre's suggestion):\n\nDecorate your data before using the heap. This is the equivalent of the key= option to sorting. e.g. if you (for some reason) wanted to heapify a list of numbers according to their sine:\ndata = [ # list of numbers ]\nheap = [(math.sin(x), x) for x in data]\nheapq.heapify(heap)\n# get the min element\nitem = heappop(heap)[1]\n\nThe heapq module is implemented in pure python. You could just copy it to your working directory and change the relevant bits. From a quick look, you would have to modify siftdown() and siftup(), and possibly nlargest and nsmallest if you need them.\n\n", "Yes, there is a way. Define a wrapping class that implements your custom comparator, and use a list of those instead of a list of your actual objects. That's about the best there is while still using the heapq module, since it provides no key= or cmp= arguments like the sorting functions/methods do.\ndef gen_wrapper(cmp):\n class Wrapper(object):\n def __init__(self, value): self.value = value\n def __cmp__(self, obj): return cmp(self.value, obj.value)\n return Wrapper\n\n" ]
[ 16, 14 ]
[]
[]
[ "heap", "min_heap", "object", "python" ]
stackoverflow_0000679731_heap_min_heap_object_python.txt
Q: Python 2.5.2 continued This is a continuation of my question Python2.5.2 The code i developed is working fine with clr.Addreference(). Now thee problem is I have to load ny script which uses dll developed in .NET to another application.They had used QT for its implementation.There is a Script console in that application.When ii entered 'import clr' ,it was saying 'No module named clr' or 'Cannot import clr'.What shall i do? A: You won't be able to run your script in that application. The script console in that QT application doubtlessly uses plain ol' CPython instead of IronPython. There's no real good way to change that without significant surgery to the application that's hosting the python console.
Python 2.5.2 continued
This is a continuation of my question Python2.5.2 The code i developed is working fine with clr.Addreference(). Now thee problem is I have to load ny script which uses dll developed in .NET to another application.They had used QT for its implementation.There is a Script console in that application.When ii entered 'import clr' ,it was saying 'No module named clr' or 'Cannot import clr'.What shall i do?
[ "You won't be able to run your script in that application. The script console in that QT application doubtlessly uses plain ol' CPython instead of IronPython. There's no real good way to change that without significant surgery to the application that's hosting the python console.\n" ]
[ 3 ]
[]
[]
[ "ironpython", "python" ]
stackoverflow_0000680336_ironpython_python.txt
Q: Why does windows give an sqlite3.OperationalError and linux does not? The problem I've got a programm that uses storm 0.14 and it gives me this error on windows: sqlite3.OperationError: database table is locked The thing is, under linux it works correctly. I've got the impression that it happens only after a certain amount of changes have been done, as it happens in some code, that copies a lot of objects. Turning on the debug mode gives me this on windows: 83 EXECUTE: 'UPDATE regularorder_product SET discount=? WHERE regularorder_product.order_id = ? AND regularorder_product.product_id = ?', (Decimal("25.00"), 788, 274) 84 DONE 85 EXECUTE: 'UPDATE repeated_orders SET nextDate=? WHERE repeated_orders.id = ?', (datetime.date(2009, 3, 31), 189) 86 ERROR: database table is locked On linux: 83 EXECUTE: 'UPDATE regularorder_product SET discount=? WHERE regularorder_product.order_id = ? AND regularorder_product.product_id = ?', (Decimal("25.00"), 789, 274) 84 DONE 85 EXECUTE: 'UPDATE repeated_orders SET nextDate=? WHERE repeated_orders.id = ?', (datetime.date(2009, 3, 31), 189) 86 DONE System info Windows Windows XP SP 3 Python 2.5.4 NTFS partition Linux Ubuntu 8.10 Python 2.5.2 ext3 partition Some code def createRegularOrderCopy(self): newOrder = RegularOrder() newOrder.date = self.nextDate # the exception is thrown on the next line, # while calling self.products.__iter__ # this happens when this function is invoked the second time for product in self.products: newOrder.customer = self.customer newOrder.products.add(product) return newOrder orders = getRepeatedOrders(date) week = timedelta(days=7) for order in orders: newOrder = order.createRegularOrderCopy() store.add(newOrder) order.nextDate = date + week The question Is there anything about sqlite3/python that differs between windows and linux? What could be the reason for this bug and how can I fix it? Another observation When adding a COMMIT at the place where the error happens, this error is thrown instead: sqlite3.OperationalError: cannot commit transaction - SQL statements in progress Answers to answers I'm not using multiple threads / processes, therefore concurrency shouldn't be a problem and also I've got only one Store object. A: The "database table is locked" error is often a generic/default error in SQLite, so narrowing down your problem is not obvious. Are you able to execute any SQL queries? I would start there, and get some basic SELECT statements working. It could just be a permissions issue. A: Hard to say without a little more info on the structure of your database access (which is a little obscured by using Storm). I'd start by reading these documents; they contain very relevant information: https://storm.canonical.com/Manual#SQLite%20and%20threads http://sqlite.org/lockingv3.html A: Are you running any sort of anti-virus scanners? Anti-virus scanners will frequently lock a file after it has been updated, so that they can inspect it without it being changed. This may explain why you get this error after a lot of changes have been made; the anti-virus scanner has more new data to scan. If you are running an anti-virus scanner, try turning it off and see if you can reproduce this problem. A: It looks to me like storm is broken, though my first guess was virus scanner as Brian suggested. Have you tried using sqlite3_busy_timeout() to set the timeout very high? This might cause SQLite3 to wait long enough for the lock holder, whoever that is, to release the lock. A: I've solved the problem at the moment by replacing the sqlite3-dll with the newest version. I'm still not sure if this was a bug in the windows code of sqlite or if python installed an older version on windows than on linux. Thanks for your help.
Why does windows give an sqlite3.OperationalError and linux does not?
The problem I've got a programm that uses storm 0.14 and it gives me this error on windows: sqlite3.OperationError: database table is locked The thing is, under linux it works correctly. I've got the impression that it happens only after a certain amount of changes have been done, as it happens in some code, that copies a lot of objects. Turning on the debug mode gives me this on windows: 83 EXECUTE: 'UPDATE regularorder_product SET discount=? WHERE regularorder_product.order_id = ? AND regularorder_product.product_id = ?', (Decimal("25.00"), 788, 274) 84 DONE 85 EXECUTE: 'UPDATE repeated_orders SET nextDate=? WHERE repeated_orders.id = ?', (datetime.date(2009, 3, 31), 189) 86 ERROR: database table is locked On linux: 83 EXECUTE: 'UPDATE regularorder_product SET discount=? WHERE regularorder_product.order_id = ? AND regularorder_product.product_id = ?', (Decimal("25.00"), 789, 274) 84 DONE 85 EXECUTE: 'UPDATE repeated_orders SET nextDate=? WHERE repeated_orders.id = ?', (datetime.date(2009, 3, 31), 189) 86 DONE System info Windows Windows XP SP 3 Python 2.5.4 NTFS partition Linux Ubuntu 8.10 Python 2.5.2 ext3 partition Some code def createRegularOrderCopy(self): newOrder = RegularOrder() newOrder.date = self.nextDate # the exception is thrown on the next line, # while calling self.products.__iter__ # this happens when this function is invoked the second time for product in self.products: newOrder.customer = self.customer newOrder.products.add(product) return newOrder orders = getRepeatedOrders(date) week = timedelta(days=7) for order in orders: newOrder = order.createRegularOrderCopy() store.add(newOrder) order.nextDate = date + week The question Is there anything about sqlite3/python that differs between windows and linux? What could be the reason for this bug and how can I fix it? Another observation When adding a COMMIT at the place where the error happens, this error is thrown instead: sqlite3.OperationalError: cannot commit transaction - SQL statements in progress Answers to answers I'm not using multiple threads / processes, therefore concurrency shouldn't be a problem and also I've got only one Store object.
[ "The \"database table is locked\" error is often a generic/default error in SQLite, so narrowing down your problem is not obvious.\nAre you able to execute any SQL queries? I would start there, and get some basic SELECT statements working. It could just be a permissions issue.\n", "Hard to say without a little more info on the structure of your database access (which is a little obscured by using Storm).\nI'd start by reading these documents; they contain very relevant information:\n\nhttps://storm.canonical.com/Manual#SQLite%20and%20threads\nhttp://sqlite.org/lockingv3.html\n\n", "Are you running any sort of anti-virus scanners? Anti-virus scanners will frequently lock a file after it has been updated, so that they can inspect it without it being changed. This may explain why you get this error after a lot of changes have been made; the anti-virus scanner has more new data to scan.\nIf you are running an anti-virus scanner, try turning it off and see if you can reproduce this problem.\n", "It looks to me like storm is broken, though my first guess was virus scanner as Brian suggested.\nHave you tried using sqlite3_busy_timeout() to set the timeout very high? This might cause SQLite3 to wait long enough for the lock holder, whoever that is, to release the lock.\n", "I've solved the problem at the moment by replacing the sqlite3-dll with the newest version. I'm still not sure if this was a bug in the windows code of sqlite or if python installed an older version on windows than on linux.\nThanks for your help.\n" ]
[ 1, 1, 1, 1, 1 ]
[]
[]
[ "linux", "python", "sqlite", "windows" ]
stackoverflow_0000679162_linux_python_sqlite_windows.txt
Q: wxPython: Making a scrollable DC I am drawing inside a wx.Window using a PaintDC. I am drawing circles and stuff like that into that window. Problem is, sometimes the circles go outside the scope of the window. I want a scrollbar to automatically appear whenever the drawing gets too big. What do I do? A: Use a wx.ScrolledWindow and set the size of the window as soon as your 'drawing go outside' the window with SetVirtualSize(width,height) If this size is bigger than the client size, then wx will show scrollbars. When drawing in the window make sure to use CalcUnscrolledPosition and CalcScrolledPosition Here you can find some more information.
wxPython: Making a scrollable DC
I am drawing inside a wx.Window using a PaintDC. I am drawing circles and stuff like that into that window. Problem is, sometimes the circles go outside the scope of the window. I want a scrollbar to automatically appear whenever the drawing gets too big. What do I do?
[ "Use a wx.ScrolledWindow and set the size of the window as soon as your 'drawing go outside' the window with\nSetVirtualSize(width,height)\n\nIf this size is bigger than the client size, then wx will show scrollbars. When drawing in the window make sure to use CalcUnscrolledPosition and CalcScrolledPosition\nHere you can find some more information.\n" ]
[ 1 ]
[]
[]
[ "python", "scroll", "scrollbar", "wxpython" ]
stackoverflow_0000677590_python_scroll_scrollbar_wxpython.txt
Q: How can I make the Django contrib Admin change list for a particular model class editable with drop downs for related items displayed in the listing? Basically I want to have an editable form for related entries instead of a static listing. A: Try Django 1.1 beta. It's got the option to make items in the changelist editable (as well as incorporating the django-batchadmin project)
How can I make the Django contrib Admin change list for a particular model class editable with drop downs for related items displayed in the listing?
Basically I want to have an editable form for related entries instead of a static listing.
[ "Try Django 1.1 beta. It's got the option to make items in the changelist editable (as well as incorporating the django-batchadmin project) \n" ]
[ 1 ]
[]
[]
[ "django", "django_admin", "django_forms", "django_templates", "python" ]
stackoverflow_0000673970_django_django_admin_django_forms_django_templates_python.txt
Q: Python dynamic function names I'm looking for a better way to call functions based on a variable in Python vs using if/else statements like below. Each status code has a corresponding function if status == 'CONNECT': return connect(*args, **kwargs) elif status == 'RAWFEED': return rawfeed(*args, **kwargs) elif status == 'RAWCONFIG': return rawconfig(*args, **kwargs) elif status == 'TESTFEED': return testfeed(*args, **kwargs) ... I assume this will require some sort of factory function but unsure as to the syntax A: you might find getattr useful, I guess import module getattr(module, status.lower())(*args, **kwargs) A: The canonical way to do this is to use a dictionary to emulate switch or if/elif. You will find several questions to similar problems here on SO. Put your functions into a dictionary with your status codes as keys: funcs = { 'CONNECT': connect, 'RAWFEED': rawfeed, 'RAWCONFIG' : rawconfig, 'TESTFEED': testfeed } funcs[status](*args, **kwargs) A: assuming that these functions belong to some module: import module return getattr(module, status.lower()).__call__(*args, **kwargs) A: it seams that you can use getattr in a slightly different (in my opinion more elegant way) import math getattr(math, 'sin')(1) or if function is imported like below from math import sin sin is now in namespace so you can call it by vars()['sin'](1) A: Some improvement to SilentGhost's answer: globals()[status.lower()](*args, **kwargs) if you want to call the function defined in the current module. Though it looks ugly. I'd use the solution with dictionary. A: Look at this: getattra as a function dispatcher A: I encountered the same problem previously. Have a look at this question, I think its what you are looking for. Dictionary or If Statements Hope this is helpful Eef A: some change from previous one: funcs = { 'CONNECT': connect, 'RAWFEED': rawfeed, 'RAWCONFIG' : rawconfig, 'TESTFEED': testfeed } func = funcs.get('status') if func: func(*args, **kwargs)
Python dynamic function names
I'm looking for a better way to call functions based on a variable in Python vs using if/else statements like below. Each status code has a corresponding function if status == 'CONNECT': return connect(*args, **kwargs) elif status == 'RAWFEED': return rawfeed(*args, **kwargs) elif status == 'RAWCONFIG': return rawconfig(*args, **kwargs) elif status == 'TESTFEED': return testfeed(*args, **kwargs) ... I assume this will require some sort of factory function but unsure as to the syntax
[ "you might find getattr useful, I guess\nimport module\ngetattr(module, status.lower())(*args, **kwargs)\n\n", "The canonical way to do this is to use a dictionary to emulate switch or if/elif. You will find several questions to similar problems here on SO.\nPut your functions into a dictionary with your status codes as keys:\nfuncs = {\n 'CONNECT': connect,\n 'RAWFEED': rawfeed,\n 'RAWCONFIG' : rawconfig,\n 'TESTFEED': testfeed\n}\nfuncs[status](*args, **kwargs)\n\n", "assuming that these functions belong to some module:\nimport module\nreturn getattr(module, status.lower()).__call__(*args, **kwargs)\n\n", "it seams that you can use getattr in a slightly different (in my opinion more elegant way)\nimport math\ngetattr(math, 'sin')(1)\n\nor if function is imported like below\nfrom math import sin\n\nsin is now in namespace so you can call it by\nvars()['sin'](1)\n\n", "Some improvement to SilentGhost's answer:\nglobals()[status.lower()](*args, **kwargs)\n\nif you want to call the function defined in the current module.\nThough it looks ugly. I'd use the solution with dictionary.\n", "Look at this: getattra as a function dispatcher\n", "I encountered the same problem previously. Have a look at this question, I think its what you are looking for.\nDictionary or If Statements\nHope this is helpful\nEef\n", "some change from previous one:\nfuncs = {\n'CONNECT': connect,\n'RAWFEED': rawfeed,\n'RAWCONFIG' : rawconfig,\n'TESTFEED': testfeed\n}\n\nfunc = funcs.get('status')\nif func:\n func(*args, **kwargs)\n\n" ]
[ 38, 20, 15, 5, 4, 3, 1, 0 ]
[]
[]
[ "factory", "python" ]
stackoverflow_0000680941_factory_python.txt
Q: Python: How to extract variable name of a dictionary entry? I'm wondering how I would go about finding the variable name of a dictionary element: For example: >>>dict1={} >>>dict2={} >>>dict1['0001']='0002' >>>dict2['nth_dict_item']=dict1 >>>print dict2 {'nth_dict_item': {'0001': '0002'}} >>>print dict2['nth_dict_item'] {'001': '002'} How can I go about making it tell me that dict2['nth_dict_item'] is or is referencing "dict1" ? I want the name of the data structure it's referencing and not the data itself. If I compare the output of id(dict1) to id(dict2['nth_dict_item']) I can find they are the same. But how can I turn that id back into a variable name? Is there a more direct/cleaner method of getting the information that I want to know? I'm sure I'm just overlooking a function that would make my life easy but I'm pretty new to Python :) Any help is appreciated, thanks! Related python, can i print original var name? How can you print a variable name in python? Update: Here's why I wanted this to work: I'm trying to make an app that uses a dictionary kinda like a database. I wanted the functionality of this psuedocode to function: dict_1={} dict_2={} dict_3={} dict_1["FooBar1.avi"]=[movie_duration,movie_type,comments] dict_2["FooBar2.avi"]=[movie_duration,movie_type,comments] dict_3["FooBar3.avi"]=[movie_duration,movie_type,comments] dict_database[SomeUniqueIdentifier1]=dict_1 dict_database[SomeUniqueIdentifier2]=dict_2 dict_database[SomeUniqueIdentifier3]=dict_3 SomeUniqueIdentifier# would be a unique value that I'm using as a database key/unqiueID to look up entries. I want to be able to update the "comments" field of FooBar1.avi by: WhichDict= dict_database[SomeUniqueIdentifier1] WhichDict[WhichDict.keys()[0]][2]='newcomment' instead of having to do: dict_database['SomeUniqueIdentifier1'][dict_database['SomeUniqueIdentifier1'].keys()[0]][2]='newcomment' Thanks everyone. I now understand I was misunderstanding a LOT of basics (total brain fart). Will go back and fix the design. Thanks to you all!. A: A variable name is just a name--it has no real meaning as far as the program is concerned, except as a convenience to the programmer (this isn't quite true in Python, but bear with me). As far as the Python interpreter is concerned, the name dict1 is just the programmer's way of telling Python to look at memory address 0x1234. Furthermore, the very idea of turning a memory address (0x1234) back into a variable name (dict1) doesn't make sense, especially considering that more than one variable name can reference the same object: dict1 = {...} dictCopy = dict1 Now dictCopy is just as much the name of the dictionary as dict1 is--they both reference the same thing. If the function you're looking for existed, which name should Python choose? A: To add what zenazn said: But how can I turn that id back into a variable name? The short answer is that you don't want really want to. If you think you need to, there's something very wrong with the design of your program. If you told us more concretely what problem you were trying to solve, we could help you work out a better way to accomplish it. A: The trivial answer: instead of WhichDict[WhichDict.keys()[0]][2]='newcomment' use: WhichDict.values()[0][2]='newcomment' But using a dictionary to represent a single movie is grossly inappropriate. Why not use a class instead? class Movie(object): def __init__(self, filename, movie_duration, movie_type, comments): self.filename = filename self.movie_duration = movie_duration self.movie_type = movie_type self.comments = comments database = dict() database['unique_id_1'] = Movie("FooBar1.avi", duration, type, comments) # ... some_movie = database[some_id] some_movie.comment = 'newcomment' A: You need to rethink your design. A quick hack would be to actually put the variable name in ... dict2['item_n'] = 'dict1' or maybe use a tuple .. dict2['item_n'] = ('dict1', dict1) There's a function called locals() which gives a dictionary of local variable names, maybe you can consider it when you rethink about your design. Here, have a look at how locals() works: >>> x = 10 >>> y = 20 >>> c = "kmf" >>> olk = 12 >>> km = (1,6,"r",x) >>> from pprint import pprint >>> pprint( locals() ) {'__builtins__': <module '__builtin__' (built-in)>, '__doc__': None, '__name__': '__main__', 'c': 'kmf', 'km': (1, 6, 'r', 10), 'olk': 12, 'pprint': <function pprint at 0x016A0EB0>, 'x': 10, 'y': 20} UPDATE I want to be able to update the "comments" field of FooBar1.avi by: WhichDict= dict_database[SomeUniqueIdentifier1] WhichDict[WhichDict.keys()[0]][2]='newcomment' Well, this is trivial dict_databse[identifier][2] = the_new_comment A: Right now, for each movie, you're doing: dict_n = {} dict_n["000n"] = [movie_duration,movie_type,comments] with only one entry per dict. Then you're storing multiple movie dicts in a central one: dict_database = {} dict_database["0001"] = dict_1 dict_database["0002"] = dict_2 dict_database["0003"] = dict_3 dict_database["000n"] = dict_n Edit: This is probably what you had in mind. For each movie, there's a dict going from property names to values. movie_n = {} movie_n["movie_duration"] = 333 movie_n["movie_type"] = "Fantasy" movie_n["comments"] = "" Then movies["any_file.avi"] gives you that dict. To add the movie to the directory and then add a comment, you enter: movies["any_file.avi"] = movie_n movies["any_file.avi"]["comments"] = "new comment" If you have to choose between the number of that movie and the filename, I'd go with the filename because it's simply more relevant when you're actually trying to access a movie. Plus, if necessary you can enumerate your movies (albeit out of order) through movies.keys() or something similar. If you want to use both a number and the filename, add the filename as another key for each movie. movie_n["filename"] = "any_file.avi" or movies["000n"]["filename"] = "any_file.avi" A: How can I go about making it tell me that dict2['nth_dict_item'] is or is referencing "dict1" ? >>> print dict2['nth_dict_item'] is dict1 True A: Use Guppy. from guppy import hpy h=hpy() h.iso(dict2['nth_dict_item']).sp 0: h.Root.i0_modules['__main__'].__dict__['dict1']
Python: How to extract variable name of a dictionary entry?
I'm wondering how I would go about finding the variable name of a dictionary element: For example: >>>dict1={} >>>dict2={} >>>dict1['0001']='0002' >>>dict2['nth_dict_item']=dict1 >>>print dict2 {'nth_dict_item': {'0001': '0002'}} >>>print dict2['nth_dict_item'] {'001': '002'} How can I go about making it tell me that dict2['nth_dict_item'] is or is referencing "dict1" ? I want the name of the data structure it's referencing and not the data itself. If I compare the output of id(dict1) to id(dict2['nth_dict_item']) I can find they are the same. But how can I turn that id back into a variable name? Is there a more direct/cleaner method of getting the information that I want to know? I'm sure I'm just overlooking a function that would make my life easy but I'm pretty new to Python :) Any help is appreciated, thanks! Related python, can i print original var name? How can you print a variable name in python? Update: Here's why I wanted this to work: I'm trying to make an app that uses a dictionary kinda like a database. I wanted the functionality of this psuedocode to function: dict_1={} dict_2={} dict_3={} dict_1["FooBar1.avi"]=[movie_duration,movie_type,comments] dict_2["FooBar2.avi"]=[movie_duration,movie_type,comments] dict_3["FooBar3.avi"]=[movie_duration,movie_type,comments] dict_database[SomeUniqueIdentifier1]=dict_1 dict_database[SomeUniqueIdentifier2]=dict_2 dict_database[SomeUniqueIdentifier3]=dict_3 SomeUniqueIdentifier# would be a unique value that I'm using as a database key/unqiueID to look up entries. I want to be able to update the "comments" field of FooBar1.avi by: WhichDict= dict_database[SomeUniqueIdentifier1] WhichDict[WhichDict.keys()[0]][2]='newcomment' instead of having to do: dict_database['SomeUniqueIdentifier1'][dict_database['SomeUniqueIdentifier1'].keys()[0]][2]='newcomment' Thanks everyone. I now understand I was misunderstanding a LOT of basics (total brain fart). Will go back and fix the design. Thanks to you all!.
[ "A variable name is just a name--it has no real meaning as far as the program is concerned, except as a convenience to the programmer (this isn't quite true in Python, but bear with me). As far as the Python interpreter is concerned, the name dict1 is just the programmer's way of telling Python to look at memory address 0x1234.\nFurthermore, the very idea of turning a memory address (0x1234) back into a variable name (dict1) doesn't make sense, especially considering that more than one variable name can reference the same object:\ndict1 = {...}\ndictCopy = dict1\n\nNow dictCopy is just as much the name of the dictionary as dict1 is--they both reference the same thing. If the function you're looking for existed, which name should Python choose?\n", "To add what zenazn said:\n\nBut how can I turn that id back into a variable name?\n\nThe short answer is that you don't want really want to. If you think you need to, there's something very wrong with the design of your program. If you told us more concretely what problem you were trying to solve, we could help you work out a better way to accomplish it.\n", "The trivial answer: instead of\nWhichDict[WhichDict.keys()[0]][2]='newcomment'\n\nuse:\nWhichDict.values()[0][2]='newcomment'\n\nBut using a dictionary to represent a single movie is grossly inappropriate. Why not use a class instead?\nclass Movie(object):\n def __init__(self, filename, movie_duration, movie_type, comments):\n self.filename = filename\n self.movie_duration = movie_duration\n self.movie_type = movie_type\n self.comments = comments\n\ndatabase = dict()\ndatabase['unique_id_1'] = Movie(\"FooBar1.avi\", duration, type, comments)\n# ...\n\nsome_movie = database[some_id]\nsome_movie.comment = 'newcomment'\n\n", "You need to rethink your design.\nA quick hack would be to actually put the variable name in ...\ndict2['item_n'] = 'dict1'\n\nor maybe use a tuple ..\ndict2['item_n'] = ('dict1', dict1)\n\nThere's a function called locals() which gives a dictionary of local variable names, maybe you can consider it when you rethink about your design.\nHere, have a look at how locals() works:\n>>> x = 10\n>>> y = 20\n>>> c = \"kmf\"\n>>> olk = 12\n>>> km = (1,6,\"r\",x)\n>>> from pprint import pprint\n>>> pprint( locals() )\n{'__builtins__': <module '__builtin__' (built-in)>,\n '__doc__': None,\n '__name__': '__main__',\n 'c': 'kmf',\n 'km': (1, 6, 'r', 10),\n 'olk': 12,\n 'pprint': <function pprint at 0x016A0EB0>,\n 'x': 10,\n 'y': 20}\n\n\nUPDATE\n\nI want to be able to update the \"comments\" field of FooBar1.avi by:\nWhichDict= dict_database[SomeUniqueIdentifier1]\nWhichDict[WhichDict.keys()[0]][2]='newcomment'\n\nWell, this is trivial\ndict_databse[identifier][2] = the_new_comment\n", "Right now, for each movie, you're doing:\ndict_n = {}\ndict_n[\"000n\"] = [movie_duration,movie_type,comments]\n\nwith only one entry per dict. Then you're storing multiple movie dicts in a central one:\ndict_database = {}\ndict_database[\"0001\"] = dict_1\ndict_database[\"0002\"] = dict_2\ndict_database[\"0003\"] = dict_3\ndict_database[\"000n\"] = dict_n\n\nEdit: This is probably what you had in mind.\nFor each movie, there's a dict going from property names to values.\nmovie_n = {}\nmovie_n[\"movie_duration\"] = 333\nmovie_n[\"movie_type\"] = \"Fantasy\"\nmovie_n[\"comments\"] = \"\"\n\nThen movies[\"any_file.avi\"] gives you that dict. To add the movie to the directory and then add a comment, you enter:\nmovies[\"any_file.avi\"] = movie_n\nmovies[\"any_file.avi\"][\"comments\"] = \"new comment\"\n\nIf you have to choose between the number of that movie and the filename, I'd go with the filename because it's simply more relevant when you're actually trying to access a movie. Plus, if necessary you can enumerate your movies (albeit out of order) through movies.keys() or something similar. If you want to use both a number and the filename, add the filename as another key for each movie.\nmovie_n[\"filename\"] = \"any_file.avi\"\n\nor\nmovies[\"000n\"][\"filename\"] = \"any_file.avi\"\n\n", "\nHow can I go about making it tell me\n that dict2['nth_dict_item'] is or is\n referencing \"dict1\" ?\n\n>>> print dict2['nth_dict_item'] is dict1\nTrue\n\n", "Use Guppy.\nfrom guppy import hpy\nh=hpy()\nh.iso(dict2['nth_dict_item']).sp\n\n0: h.Root.i0_modules['__main__'].__dict__['dict1']\n\n" ]
[ 9, 7, 4, 1, 1, 0, 0 ]
[]
[]
[ "dictionary", "lookup", "python", "variables" ]
stackoverflow_0000680032_dictionary_lookup_python_variables.txt
Q: Whats the difference between list[-1:][0] and list[len(list)-1]? Lest say you want the last element of a python list: what is the difference between myList[-1:][0] and myList[len(myList)-1] I thought there was no difference but then I tried this >>> list = [0] >>> list[-1:][0] 0 >>> list[-1:][0] += 1 >>> list [0] >>> list[len(list)-1] += 1 >>> list [1] I was a little surprised... A: if you use slicing [-1:], the returned list is a shallow-copy, not reference. so [-1:][0] modifies the new list. [len(list)-1] is reference to last object. A: list[-1:] creates a new list. To get the same behaviour as list[len(list)-1] it would have to return a view of some kind of list, but as I said, it creates a new temporary list. You then proceed to edit the temporary list. Anyway, you know you can use list[-1] for the same thing, right? A: Slicing creates copy (shallow copy). It's often used as an shallow copy idiom. i.e. list2 = list1[:] is equivalent to import copy list2 = copy.copy(list1)
Whats the difference between list[-1:][0] and list[len(list)-1]?
Lest say you want the last element of a python list: what is the difference between myList[-1:][0] and myList[len(myList)-1] I thought there was no difference but then I tried this >>> list = [0] >>> list[-1:][0] 0 >>> list[-1:][0] += 1 >>> list [0] >>> list[len(list)-1] += 1 >>> list [1] I was a little surprised...
[ "if you use slicing [-1:], the returned list is a shallow-copy, not reference. so [-1:][0] modifies the new list. [len(list)-1] is reference to last object.\n", "list[-1:] creates a new list. To get the same behaviour as list[len(list)-1] it would have to return a view of some kind of list, but as I said, it creates a new temporary list. You then proceed to edit the temporary list.\nAnyway, you know you can use list[-1] for the same thing, right?\n", "Slicing creates copy (shallow copy). It's often used as an shallow copy idiom.\ni.e.\nlist2 = list1[:]\n\nis equivalent to\nimport copy\nlist2 = copy.copy(list1)\n\n" ]
[ 14, 9, 3 ]
[]
[]
[ "list", "python", "slice" ]
stackoverflow_0000681123_list_python_slice.txt
Q: Web crawlers and Google App Engine Hosted applications Is it impossible to run a web crawler on GAE along side with my app considering the I am running the free startup version? A: While Google hadn't exposed scheduling, queue and background tasks API, you can do any processing only as an answer to external HTTP request. You'd need some heartbeat service that will process one item from crawler's queue at a time (not to hit GAE limits). To do crawling from GAE, you have to split your application into queue (that stores queue data in Datastore), queue processor that will react to external HTTP heartbeat and your actual crawling logic. You'd manually have to watch your quota usage and start heartbeat when you have spare quota, and stop if it is used up. When Google introduces the APIs I've told in the beginning you'd have to rewrite parts that are implemented more effectively via Google API. UPDATE: Google introduced Task Queue API some time ago. See task queue docs for python and java. A: App Engine code only runs in response to HTTP requests, so you can't run a persistent crawler in the background. With the upcoming release of scheduled tasks, you could write a crawler that uses that functionality, but it would be less than ideal. A: I suppose you can (i.e., it's not impossible to) run it, but it will be slow and you'll run into limits quite quickly. As CPU quotas are going to be decreased at the end of May even further, I'd recommend against it. A: It's possible. But that's not really an application for appengine just as Arachnid wrote. If you manage to get it working I'll doubt you'll stay in the qotas for free accounts.
Web crawlers and Google App Engine Hosted applications
Is it impossible to run a web crawler on GAE along side with my app considering the I am running the free startup version?
[ "While Google hadn't exposed scheduling, queue and background tasks API, you can do any processing only as an answer to external HTTP request. You'd need some heartbeat service that will process one item from crawler's queue at a time (not to hit GAE limits).\nTo do crawling from GAE, you have to split your application into queue (that stores queue data in Datastore), queue processor that will react to external HTTP heartbeat and your actual crawling logic.\nYou'd manually have to watch your quota usage and start heartbeat when you have spare quota, and stop if it is used up.\nWhen Google introduces the APIs I've told in the beginning you'd have to rewrite parts that are implemented more effectively via Google API.\nUPDATE: Google introduced Task Queue API some time ago. See task queue docs for python and java.\n", "App Engine code only runs in response to HTTP requests, so you can't run a persistent crawler in the background. With the upcoming release of scheduled tasks, you could write a crawler that uses that functionality, but it would be less than ideal.\n", "I suppose you can (i.e., it's not impossible to) run it, but it will be slow and you'll run into limits quite quickly. As CPU quotas are going to be decreased at the end of May even further, I'd recommend against it.\n", "It's possible. But that's not really an application for appengine just as Arachnid wrote. If you manage to get it working I'll doubt you'll stay in the qotas for free accounts.\n" ]
[ 3, 1, 0, 0 ]
[]
[]
[ "google_app_engine", "python", "web_crawler" ]
stackoverflow_0000676460_google_app_engine_python_web_crawler.txt
Q: Game map from Code It's a long one so you might want to get that cup of tea/coffee you've been holding off on ;) I run a game called World of Arl, it's a turn based strategy game akin to Risk or Diplomacy. Each player has a set of cities, armies and whatnot. The question revolves around the display of these things. Currently the map is created using a background image with CSS positioning of team icons on top of that to represent cities. You can see how it looks here: WoA Map The background image for the map is located here: Map background and created in Omnigraffle. It's not designed to draw maps but I'm hopelessly incompetent with photoshop and this works for my purposes just fine. The problem comes that I want to perform such fun things as pathfinding and for that I need to have the map somehow stored in code. I have tried using PIL, I have looked at incorporating it with Blender, I tried going "old school" and creating tiles as from many older games and finally I tried to use SVG. I say this so you can see clearly that it's not through lack of trying that I have this problem ;) I want to be able to store the map layout in code and both create an image from it and use it for things such as pathfinding. I'm using Python but I suspect that most answers will be generic. The cities other such things are stored already and easily drawn on, I want to store the layout of the landmass and features on the landmass. As for pathfinding, each type of terrain has a movement cost and when the map is stored as just an image I can't access the terrain of a given area. In addition to pathfinding I wish to be able to know the terrain for various things related to the game, cities in mountains produce stone for example. Is there a good way to do this and what terms should I have used in Google because the terms I tried all came up with unrelated stuff (mapping being something completely different most of the time). Edit 2: Armies can be placed anywhere on the map as can cities, well, anywhere but in the water where they'd sink, drown and probably complain (in that order). After chatting to somebody on MSN who made me go over the really minute details and who has a better understanding of the game (owing to the fact that he's played it) it's occurring to me that tiles are the way to go but not the way I had initially thought. I put the bitmap down as it is now but also have a data layer of tiles, each tile has a given terrain type and thus pathfinding and suchlike can be done on it yet at the same time I still render using Omnigraffle which works pretty well. I will be making an editor for this as suggested by Adam Smith. I don't know that graphs will be relevant Xynth but I've not had a chance to look into them fully yet. I really appreciate all those that answered my question, thanks. A: I'd store a game map in code as a graph. Each node would represent a country/city and each edge would represent adjacency. Once you have a map like that, I'm sure you can find many resources on AI (pathfinding, strategy, etc.) online. If you want to be able to build an image of the map programattically, consider adding an (x, y) coordinate and an image for each node. That way you can display all of the images at the given coordinates to build up a map view. A: The key thing to realize here is that you don't have to use just one map. You can use two maps: The one you already have which is drawn on screen A hidden map which isn't drawn but which is used for path finding, collision detection etc. The natural next question then is where does this second map come from? Easy, you create your own tool which can load your first map, and display it. Your tool will then let you draw boundaries around you islands and place markers at your cities. These markers and boundaries (simple polygons e.g.) are stored as your second map and is used in your code to do path finding etc. In fact you can have your tool emit python code which creates the graphs and polygons so that you don't have to load any data yourself. I am just basically telling you to make a level editor. It isn't very hard to do. You just need some buttons to click on to define what you are adding. e.g. if you are adding a polygon. Then you can just add each mouse coordinate to an array each time you click on your mouse if you have toggled your add polygon button. You can have another button for adding cities so that each time you click on the map you will record that coordinate for the city and possibly a corresponding name that you can provide in a text box. A: You're going to have to translate your map into an abstract representation of some kind. Either a grid (hex or square) or a graph as xynth suggests. That's the only way you're going to be able to apply things like pathfinding algorithms to it. A: IMO, the map should be rendered in the first place instead of being a bitmap. What you should be doing is to have separate objects each knowing its dimensions clearly such as a generic Area class and classes like City, Town etc derived from this class. Your objects should have all the information about their location, their terrain etc and should be rendered/painted etc. This way you will have exact knowledge of where everything lies. Another option is to keep the bitmap as it is and keep this information in your objects as their data. By doing this the objects won't have a draw function but they will have precise information of their placement etc. This is sort of duplicating the data but if you want to go with the bitmap option, I can't think of any other way. A: If you just want to do e.g. 2D hit-testing on the map, then storing it yourself is fine. There are a few possibilities for how you can store the information: A polygon per island Representing each island as union of a list rectangles (commonly used by windowing systems) Creating a special (maybe greyscale) bitmap of the map which uses a unique solid colour for each island Something more complex (perhaps whatever Omnigiraffe's internal representation is) A: Asuming the map is fixed (not created on the fly) its "correct" to use a bitmap as graphical representation - you want to make it as pretty as possible. For any game related features such as pathfinding or whatever fancy stuff you want to add you should add adequate data structures, even if that means some data is redundant. E.g. describe the boundaries of the isles as polygon splines (either manually or automatically created from the bitmap, thats up to you and how much effort you want to spend and is needed to get the functionality you want). To sum it up: create data structures matching the problems you have to solve, the bitmap is fine for looks but avoid doing pathfining or other stuff on it.
Game map from Code
It's a long one so you might want to get that cup of tea/coffee you've been holding off on ;) I run a game called World of Arl, it's a turn based strategy game akin to Risk or Diplomacy. Each player has a set of cities, armies and whatnot. The question revolves around the display of these things. Currently the map is created using a background image with CSS positioning of team icons on top of that to represent cities. You can see how it looks here: WoA Map The background image for the map is located here: Map background and created in Omnigraffle. It's not designed to draw maps but I'm hopelessly incompetent with photoshop and this works for my purposes just fine. The problem comes that I want to perform such fun things as pathfinding and for that I need to have the map somehow stored in code. I have tried using PIL, I have looked at incorporating it with Blender, I tried going "old school" and creating tiles as from many older games and finally I tried to use SVG. I say this so you can see clearly that it's not through lack of trying that I have this problem ;) I want to be able to store the map layout in code and both create an image from it and use it for things such as pathfinding. I'm using Python but I suspect that most answers will be generic. The cities other such things are stored already and easily drawn on, I want to store the layout of the landmass and features on the landmass. As for pathfinding, each type of terrain has a movement cost and when the map is stored as just an image I can't access the terrain of a given area. In addition to pathfinding I wish to be able to know the terrain for various things related to the game, cities in mountains produce stone for example. Is there a good way to do this and what terms should I have used in Google because the terms I tried all came up with unrelated stuff (mapping being something completely different most of the time). Edit 2: Armies can be placed anywhere on the map as can cities, well, anywhere but in the water where they'd sink, drown and probably complain (in that order). After chatting to somebody on MSN who made me go over the really minute details and who has a better understanding of the game (owing to the fact that he's played it) it's occurring to me that tiles are the way to go but not the way I had initially thought. I put the bitmap down as it is now but also have a data layer of tiles, each tile has a given terrain type and thus pathfinding and suchlike can be done on it yet at the same time I still render using Omnigraffle which works pretty well. I will be making an editor for this as suggested by Adam Smith. I don't know that graphs will be relevant Xynth but I've not had a chance to look into them fully yet. I really appreciate all those that answered my question, thanks.
[ "I'd store a game map in code as a graph. \nEach node would represent a country/city and each edge would represent adjacency. Once you have a map like that, I'm sure you can find many resources on AI (pathfinding, strategy, etc.) online.\nIf you want to be able to build an image of the map programattically, consider adding an (x, y) coordinate and an image for each node. That way you can display all of the images at the given coordinates to build up a map view.\n", "The key thing to realize here is that you don't have to use just one map. You can use two maps:\n\nThe one you already have which is drawn on screen\nA hidden map which isn't drawn but which is used for path finding, collision detection etc.\n\nThe natural next question then is where does this second map come from? Easy, you create your own tool which can load your first map, and display it. Your tool will then let you draw boundaries around you islands and place markers at your cities. These markers and boundaries (simple polygons e.g.) are stored as your second map and is used in your code to do path finding etc. \nIn fact you can have your tool emit python code which creates the graphs and polygons so that you don't have to load any data yourself. \nI am just basically telling you to make a level editor. It isn't very hard to do. You just need some buttons to click on to define what you are adding. e.g. if you are adding a polygon. Then you can just add each mouse coordinate to an array each time you click on your mouse if you have toggled your add polygon button. You can have another button for adding cities so that each time you click on the map you will record that coordinate for the city and possibly a corresponding name that you can provide in a text box.\n", "You're going to have to translate your map into an abstract representation of some kind. Either a grid (hex or square) or a graph as xynth suggests. That's the only way you're going to be able to apply things like pathfinding algorithms to it.\n", "IMO, the map should be rendered in the first place instead of being a bitmap. What you should be doing is to have separate objects each knowing its dimensions clearly such as a generic Area class and classes like City, Town etc derived from this class. Your objects should have all the information about their location, their terrain etc and should be rendered/painted etc. This way you will have exact knowledge of where everything lies.\nAnother option is to keep the bitmap as it is and keep this information in your objects as their data. By doing this the objects won't have a draw function but they will have precise information of their placement etc. This is sort of duplicating the data but if you want to go with the bitmap option, I can't think of any other way.\n", "If you just want to do e.g. 2D hit-testing on the map, then storing it yourself is fine. There are a few possibilities for how you can store the information:\n\nA polygon per island\nRepresenting each island as union of a list rectangles (commonly used by windowing systems)\nCreating a special (maybe greyscale) bitmap of the map which uses a unique solid colour for each island\nSomething more complex (perhaps whatever Omnigiraffe's internal representation is)\n\n", "Asuming the map is fixed (not created on the fly) its \"correct\" to use a bitmap as graphical representation - you want to make it as pretty as possible.\nFor any game related features such as pathfinding or whatever fancy stuff you want to add you should add adequate data structures, even if that means some data is redundant.\nE.g. describe the boundaries of the isles as polygon splines (either manually or automatically created from the bitmap, thats up to you and how much effort you want to spend and is needed to get the functionality you want).\nTo sum it up: create data structures matching the problems you have to solve, the bitmap is fine for looks but avoid doing pathfining or other stuff on it.\n" ]
[ 5, 3, 2, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000681310_python.txt
Q: How is string.find implemented in CPython? I was wondering if the 'find' method on strings was implemented with a linear search, or if python did something more sophisticated. The Python documentation doesn't discuss implementation details, so http://docs.python.org/library/stdtypes.html is of no help. Could someone please point me to the relevant source code? A: The comment on the implementation has the following to say: fast search/count implementation, based on a mix between boyer-moore and horspool, with a few more bells and whistles on the top. for some more background, see: http://effbot.org/zone/stringlib.htm —https://github.com/python/cpython/blob/master/Objects/stringlib/fastsearch.h#L5 A: You should be able to find it in Objects/stringlib/find.h, although the real code is in fastsearch.h. A: Looks like the algorithm used originates from Boyer-Moore-Horspool algorithm
How is string.find implemented in CPython?
I was wondering if the 'find' method on strings was implemented with a linear search, or if python did something more sophisticated. The Python documentation doesn't discuss implementation details, so http://docs.python.org/library/stdtypes.html is of no help. Could someone please point me to the relevant source code?
[ "The comment on the implementation has the following to say:\n\nfast search/count implementation,\n based on a mix between boyer-moore\n and horspool, with a few more bells\n and whistles on the top.\nfor some more background, see: http://effbot.org/zone/stringlib.htm\n\n—https://github.com/python/cpython/blob/master/Objects/stringlib/fastsearch.h#L5\n", "You should be able to find it in Objects/stringlib/find.h, although the real code is in fastsearch.h.\n", "Looks like the algorithm used originates from Boyer-Moore-Horspool algorithm\n" ]
[ 22, 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000681649_python.txt
Q: Redirecting function definitions in python This is a very contrived example as it's not easy to explain the context in which I have ended up implementing this solution. However, if anyone can answer why this particular peculiarity happens, I'd be grateful. The example: class A(dict): def __init__(self): self['a'] = 'success' def __getitem__(self, name): print 'getitem' return dict.__getitem__(name) class B(object): def __init__(self): self._a = A() setattr(self, '__getitem__', self._a.__getitem__) b = B() c = b['a'] This outputs: c = b['a'] TypeError: 'B' object is unsubscriptable Even though it's a bizarre way of doing this (clearly subclassing would be more logical), why doesn't it find the method I have explicitly set? If I do this: dir(b) I get this: ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', '_a'] The same issue occurs with other methods such as __iter__. What is it about explicitly defining this method that works? A: When you use brackets [] python looks in the class. You must set the method in the class. Here's your code adapted: class A(dict): def __init__(self): self['a'] = 'success' def __getitem__(self, name): print 'getitem!' return dict.__getitem__(self, name) class B(object): def __init__(self): self._a = A() B.__getitem__ = self._a.__getitem__ b = B() c = b['a'] A: This is because you can't override special class methods on the fly. I wasn't able to find a reference about this but is basically because they are class methods and are not allowed to be instance methods.
Redirecting function definitions in python
This is a very contrived example as it's not easy to explain the context in which I have ended up implementing this solution. However, if anyone can answer why this particular peculiarity happens, I'd be grateful. The example: class A(dict): def __init__(self): self['a'] = 'success' def __getitem__(self, name): print 'getitem' return dict.__getitem__(name) class B(object): def __init__(self): self._a = A() setattr(self, '__getitem__', self._a.__getitem__) b = B() c = b['a'] This outputs: c = b['a'] TypeError: 'B' object is unsubscriptable Even though it's a bizarre way of doing this (clearly subclassing would be more logical), why doesn't it find the method I have explicitly set? If I do this: dir(b) I get this: ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', '_a'] The same issue occurs with other methods such as __iter__. What is it about explicitly defining this method that works?
[ "When you use brackets [] python looks in the class. You must set the method in the class.\nHere's your code adapted:\nclass A(dict): \n def __init__(self):\n self['a'] = 'success'\n\n def __getitem__(self, name):\n print 'getitem!'\n return dict.__getitem__(self, name)\n\nclass B(object):\n def __init__(self):\n self._a = A()\n B.__getitem__ = self._a.__getitem__\n\nb = B()\nc = b['a']\n\n", "This is because you can't override special class methods on the fly.\nI wasn't able to find a reference about this but is basically because they are class methods and are not allowed to be instance methods.\n" ]
[ 7, 1 ]
[]
[]
[ "class_attributes", "python" ]
stackoverflow_0000682822_class_attributes_python.txt
Q: Dynamically change the choices in a wx.ComboBox() I didn't find a better way to change the different choices in a wx.ComboBox() than swap the old ComboBox with a new one. Is there a better way? Oerjan Pettersen #!/usr/bin/python #20_combobox.py import wx import wx.lib.inspection class MyFrame(wx.Frame): def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) self.p1 = wx.Panel(self) lst = ['1','2','3'] self.st = wx.ComboBox(self.p1, -1, choices = lst, style=wx.TE_PROCESS_ENTER) self.st.Bind(wx.EVT_COMBOBOX, self.text_return) def text_return(self, event): lst = ['3','4'] self.st = wx.ComboBox(self.p1, -1, choices = lst, style=wx.TE_PROCESS_ENTER) class MyApp(wx.App): def OnInit(self): frame = MyFrame(None, -1, '20_combobox.py') frame.Show() self.SetTopWindow(frame) return 1 if __name__ == "__main__": app = MyApp(0) # wx.lib.inspection.InspectionTool().Show() app.MainLoop() A: wx.ComboBox derives from wx.ItemContainer, which has methods for Appending, Clearing, Inserting and Deleting items, all of these methods are available on wx.ComboBox. One way to do what you want would be to define the text_return() method as follows: def text_return(self, event): self.st.Clear() self.st.Append('3') self.st.Append('4')
Dynamically change the choices in a wx.ComboBox()
I didn't find a better way to change the different choices in a wx.ComboBox() than swap the old ComboBox with a new one. Is there a better way? Oerjan Pettersen #!/usr/bin/python #20_combobox.py import wx import wx.lib.inspection class MyFrame(wx.Frame): def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) self.p1 = wx.Panel(self) lst = ['1','2','3'] self.st = wx.ComboBox(self.p1, -1, choices = lst, style=wx.TE_PROCESS_ENTER) self.st.Bind(wx.EVT_COMBOBOX, self.text_return) def text_return(self, event): lst = ['3','4'] self.st = wx.ComboBox(self.p1, -1, choices = lst, style=wx.TE_PROCESS_ENTER) class MyApp(wx.App): def OnInit(self): frame = MyFrame(None, -1, '20_combobox.py') frame.Show() self.SetTopWindow(frame) return 1 if __name__ == "__main__": app = MyApp(0) # wx.lib.inspection.InspectionTool().Show() app.MainLoop()
[ "wx.ComboBox derives from wx.ItemContainer, which has methods for Appending, Clearing, Inserting and Deleting items, all of these methods are available on wx.ComboBox.\nOne way to do what you want would be to define the text_return() method as follows:\ndef text_return(self, event):\n self.st.Clear()\n self.st.Append('3')\n self.st.Append('4')\n\n" ]
[ 37 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0000682923_python_wxpython_wxwidgets.txt
Q: Timeout on a HTTP request in python Very occasionally when making a http request, I am waiting for an age for a response that never comes. What is the recommended way to cancel this request after a reasonable period of time? A: Set the HTTP request timeout. A: The timeout parameter to urllib2.urlopen, or httplib. The original urllib has no such convenient feature. You can also use an asynchronous HTTP client such as twisted.web.client, but that's probably not necessary. A: If you are making a lot of HTTP requests, you can change this globally by calling socket.setdefaulttimeout
Timeout on a HTTP request in python
Very occasionally when making a http request, I am waiting for an age for a response that never comes. What is the recommended way to cancel this request after a reasonable period of time?
[ "Set the HTTP request timeout.\n", "The timeout parameter to urllib2.urlopen, or httplib. The original urllib has no such convenient feature. You can also use an asynchronous HTTP client such as twisted.web.client, but that's probably not necessary.\n", "If you are making a lot of HTTP requests, you can change this globally by calling socket.setdefaulttimeout\n" ]
[ 2, 1, 1 ]
[]
[]
[ "httpwebrequest", "python" ]
stackoverflow_0000683493_httpwebrequest_python.txt
Q: how to put a function and arguments into python queue? I have a python program with 2 threads ( let's name them 'source' and 'destination' ). Source thread sometimes post a message to destination thread with some arguments. Than destination thread picks a message it must call a corresponding function with aruments saved in message. This task can be solved multiple ways. The easy one is tu put a big 'if...if..if' in destination thread's message pick cycle and call function according to received message type and saved arguments. But this will result in huge amounf of code ( or big lookup table ) and adding new messages / handler function will evolve additonal step to write code in message pick cycle. Since python treats functions as first-class objects and have tuples, i want to put a function and argumens inside a message, so than destination thread picks a message it just call a functon saved within a message without any knowledge what function it is. I can write a code for a functions with specified number of arguments: from Queue import * from thread import * from time import * q = Queue() def HandleMsg( arg1, arg2 ) : print arg1, arg2 def HandleAnotherMsg( arg1, arg2, arg3 ) : print arg1, arg2, arg3 def DestinationThread( a ) : while True : (f, a, b) = q.get() f( a, b ) start_new_thread( DestinationThread, ( 0, ) ) print "start" sleep( 1 ) q.put( (HandleMsg, 1, 2) ) sleep( 1 ) print "stop" The question is: how to modify a code so i can put() a function with any number of arguments in queue? for example HandleAnotherMsg() ? Using q.put( (HandleAnotherMsg, 1, 2, 3) ) will rise a compilation error :( A: So simple: def DestinationThread( a ) : while True : items = q.get() func = items[0] args = items[1:] func(*args) A: Another interesting option is simply to pass in a lambda. q.put(lambda: HandleMsg(1,2)) q.put(lambda: HandleAnother(8, "hello", extra="foo")) def DestinationThread() : while True : f = q.get() f() A: from Queue import * from thread import * from time import * q = Queue() def HandleMsg( arg1, arg2 ) : print arg1, arg2 def HandleAnotherMsg( arg1, arg2, arg3 ) : print arg1, arg2, arg3 def DestinationThread() : while True : f, args = q.get() f(*args) start_new_thread( DestinationThread, tuple() ) print "start" sleep( 1 ) q.put( (HandleMsg, [1, 2]) ) sleep( 1 ) q.put( (HandleAnotherMsg, [1, 2, 3]) ) sleep( 1 ) print "stop" A: I've used a similar construct before: class Call: def __init__(self, fn, *args, **kwargs): self.fn = fn self.args = args self.kwargs = kwargs def __call__(self): return self.fn(*self.args, **self.kwargs) x = Call(zip, [0,1], [2,3], [4,5]) You should then be able to pass x to your other thread and call it from there: x() # returns the same as zip([0,1], [2,3], [4,5]) A: It sounds like you want to use the apply() intrinsic or its successor: def f(x. y): print x+y args = ( 1, 2 ) apply(f, args) # old way f(*args) # new way A: You can create an abstract message class with a run method. Then for each function that need to be transmitted via the queue, subclass and implement the function as the run method. The sending thread will create an instance of the proper sub class and put it into the queue. The receiving thread will get an object from the queue and blindly execute the run method. This is usually called the Command pattern (Gamma et al.) Example: class Message (object): """abstract message class""" def __init__(self, **kwargs): self.kwargs = kwargs def run(self): pass class MessageOne (Message): """one message class""" def run(self): # perform this emssage's action using the kwargs The sender will instantiate and send a message: queue.put(MessageOne(one='Eins', two='Deux')) The receiver simply gets a message object and execute it run method (without having to it..else.. thru the available types of messages): msg = queue.get() msg.run()
how to put a function and arguments into python queue?
I have a python program with 2 threads ( let's name them 'source' and 'destination' ). Source thread sometimes post a message to destination thread with some arguments. Than destination thread picks a message it must call a corresponding function with aruments saved in message. This task can be solved multiple ways. The easy one is tu put a big 'if...if..if' in destination thread's message pick cycle and call function according to received message type and saved arguments. But this will result in huge amounf of code ( or big lookup table ) and adding new messages / handler function will evolve additonal step to write code in message pick cycle. Since python treats functions as first-class objects and have tuples, i want to put a function and argumens inside a message, so than destination thread picks a message it just call a functon saved within a message without any knowledge what function it is. I can write a code for a functions with specified number of arguments: from Queue import * from thread import * from time import * q = Queue() def HandleMsg( arg1, arg2 ) : print arg1, arg2 def HandleAnotherMsg( arg1, arg2, arg3 ) : print arg1, arg2, arg3 def DestinationThread( a ) : while True : (f, a, b) = q.get() f( a, b ) start_new_thread( DestinationThread, ( 0, ) ) print "start" sleep( 1 ) q.put( (HandleMsg, 1, 2) ) sleep( 1 ) print "stop" The question is: how to modify a code so i can put() a function with any number of arguments in queue? for example HandleAnotherMsg() ? Using q.put( (HandleAnotherMsg, 1, 2, 3) ) will rise a compilation error :(
[ "So simple:\ndef DestinationThread( a ) :\n while True :\n items = q.get()\n func = items[0]\n args = items[1:]\n func(*args)\n\n", "Another interesting option is simply to pass in a lambda.\nq.put(lambda: HandleMsg(1,2))\nq.put(lambda: HandleAnother(8, \"hello\", extra=\"foo\"))\n\ndef DestinationThread() :\n while True :\n f = q.get()\n f()\n\n", "from Queue import *\nfrom thread import *\nfrom time import *\n\nq = Queue()\n\ndef HandleMsg( arg1, arg2 ) :\n print arg1, arg2\n\ndef HandleAnotherMsg( arg1, arg2, arg3 ) :\n print arg1, arg2, arg3\n\ndef DestinationThread() :\n while True :\n f, args = q.get()\n f(*args)\n\nstart_new_thread( DestinationThread, tuple() )\nprint \"start\"\nsleep( 1 )\nq.put( (HandleMsg, [1, 2]) )\nsleep( 1 )\nq.put( (HandleAnotherMsg, [1, 2, 3]) )\nsleep( 1 )\nprint \"stop\"\n\n", "I've used a similar construct before:\nclass Call:\n def __init__(self, fn, *args, **kwargs):\n self.fn = fn\n self.args = args\n self.kwargs = kwargs\n\n def __call__(self):\n return self.fn(*self.args, **self.kwargs)\n\n\nx = Call(zip, [0,1], [2,3], [4,5])\n\nYou should then be able to pass x to your other thread and call it from there:\nx() # returns the same as zip([0,1], [2,3], [4,5])\n\n", "It sounds like you want to use the apply() intrinsic or its successor:\ndef f(x. y):\n print x+y\n\nargs = ( 1, 2 )\n\napply(f, args) # old way\n\nf(*args) # new way\n\n", "You can create an abstract message class with a run method. Then for each function that need to be transmitted via the queue, subclass and implement the function as the run method.\nThe sending thread will create an instance of the proper sub class and put it into the queue. The receiving thread will get an object from the queue and blindly execute the run method.\nThis is usually called the Command pattern (Gamma et al.)\nExample:\nclass Message (object):\n \"\"\"abstract message class\"\"\"\n def __init__(self, **kwargs):\n self.kwargs = kwargs\n\n def run(self):\n pass\n\n\nclass MessageOne (Message):\n \"\"\"one message class\"\"\"\n def run(self):\n # perform this emssage's action using the kwargs\n\nThe sender will instantiate and send a message:\nqueue.put(MessageOne(one='Eins', two='Deux'))\n\nThe receiver simply gets a message object and execute it run method (without having to it..else.. thru the available types of messages):\nmsg = queue.get()\nmsg.run()\n\n" ]
[ 31, 14, 10, 2, 0, 0 ]
[ "Why don't you subclass Queue?\n\nclass MyQueue(Queue):\n # by using *args, you can have a variable number of arguments\n def put(self,*args):\n for arg in args:\n Queue.put(self,arg)\n\nor, why don't you put a list?\n\nlist = [function_obj]\nfor arg in function_args:\n list.append(arg)\nqueue.put(list)\n\n" ]
[ -2 ]
[ "multithreading", "python" ]
stackoverflow_0000683542_multithreading_python.txt
Q: How to save an xml file to disk? I did something similar to this, but couldn't find a way to write the result to an xml file. A: The code on the web page you linked to uses doc.toprettyxml to create a string from the XML DOM, so you can just write that string to a file: f = open("output.xml", "w") try: f.write(doc.toprettyxml(indent=" ")) finally: f.close() In Python 2.6 (or 2.7 I suppose, whenever it comes out), you can use the "with" statement: with open("output.xml", "w") as f: f.write(doc.toprettyxml(indent=" ")) This also works in Python 2.5 if you put from __future__ import with_statement at the beginning of the file. A: coonj is kind of right, but xml.dom.ext.PrettyPrint is part of the increasingly neglected PyXML extension package. If you want to stay within the supplied-as-standard minidom, you'd say: f= open('yourfile.xml', 'wb') doc.writexml(f, encoding= 'utf-8') f.close() (Or using the ‘with’ statement as mentioned by David to make it slightly shorter. Use mode 'wb' to avoid unwanted CRLF newlines on Windows interfering with encodings like UTF-16. Because XML has its own mechanisms for handling newline interpretation, it should be treated as a binary file rather than text.) If you don't include the ‘encoding’ argument (to either writexml or toprettyxml), it'll try to write a Unicode string direct to the file, so if there are any non-ASCII characters in it, you'll get a UnicodeEncodeError. Don't try to .encode() the results of toprettyxml yourself; for non-UTF-8 encodings this can generate non-well-formed XML. There's no ‘writeprettyxml()’ function, but it's trivially simple to do it yourself: with open('output.xml', 'wb') as f: doc.writexml(f, encoding= 'utf-8', indent= ' ', newl= '\n') A: f = open('yourfile.xml', 'w') xml.dom.ext.PrettyPrint(doc, f) f.close()
How to save an xml file to disk?
I did something similar to this, but couldn't find a way to write the result to an xml file.
[ "The code on the web page you linked to uses doc.toprettyxml to create a string from the XML DOM, so you can just write that string to a file:\nf = open(\"output.xml\", \"w\")\ntry:\n f.write(doc.toprettyxml(indent=\" \"))\nfinally:\n f.close()\n\nIn Python 2.6 (or 2.7 I suppose, whenever it comes out), you can use the \"with\" statement:\nwith open(\"output.xml\", \"w\") as f:\n f.write(doc.toprettyxml(indent=\" \"))\n\nThis also works in Python 2.5 if you put\nfrom __future__ import with_statement\n\nat the beginning of the file.\n", "coonj is kind of right, but xml.dom.ext.PrettyPrint is part of the increasingly neglected PyXML extension package. If you want to stay within the supplied-as-standard minidom, you'd say:\nf= open('yourfile.xml', 'wb')\ndoc.writexml(f, encoding= 'utf-8')\nf.close()\n\n(Or using the ‘with’ statement as mentioned by David to make it slightly shorter. Use mode 'wb' to avoid unwanted CRLF newlines on Windows interfering with encodings like UTF-16. Because XML has its own mechanisms for handling newline interpretation, it should be treated as a binary file rather than text.)\nIf you don't include the ‘encoding’ argument (to either writexml or toprettyxml), it'll try to write a Unicode string direct to the file, so if there are any non-ASCII characters in it, you'll get a UnicodeEncodeError. Don't try to .encode() the results of toprettyxml yourself; for non-UTF-8 encodings this can generate non-well-formed XML.\nThere's no ‘writeprettyxml()’ function, but it's trivially simple to do it yourself:\nwith open('output.xml', 'wb') as f:\n doc.writexml(f, encoding= 'utf-8', indent= ' ', newl= '\\n')\n\n", "f = open('yourfile.xml', 'w')\nxml.dom.ext.PrettyPrint(doc, f)\nf.close()\n\n" ]
[ 11, 9, 1 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0000683494_python_xml.txt
Q: can you distinguish between a test & a variable setting? I like doctest but when you have complex arguments that you need to set before you pass to a function it become really hard to read.. Hence, you start using multiple lines assigning then calling the function that you would like to test.. This approach however, will report that you have multiple tests rather then the real number of tests that you have.. An example will illustrate what I mean.. def returnme(x): """ Returns what you pass >>> y = (2, 3, 5, 7) >>> returnme(y) (2, 3, 5, 7) """ return x In the above snippet, there is only one test and the other is just a variable assignment, however, this is what gets reported.. Trying: y = (2, 3, 5, 7) Expecting nothing ok Trying: returnme(y) Expecting: (2, 3, 5, 7) ok 2 tests in 2 items. 2 passed and 0 failed. I've looked at the flags documented, surely I missing something.. A: Prepend three periods to indicate that you want to continue the current line, like so: def returnme(x): """ Returns what you pass >>> y = (2, 3, 5, 7) ... returnme(y) # Note the difference here. ... # Another blank line ends this test. (2, 3, 5, 7) """ return x That should do the trick. You can read more about how doctest interprets the individual tests here.
can you distinguish between a test & a variable setting?
I like doctest but when you have complex arguments that you need to set before you pass to a function it become really hard to read.. Hence, you start using multiple lines assigning then calling the function that you would like to test.. This approach however, will report that you have multiple tests rather then the real number of tests that you have.. An example will illustrate what I mean.. def returnme(x): """ Returns what you pass >>> y = (2, 3, 5, 7) >>> returnme(y) (2, 3, 5, 7) """ return x In the above snippet, there is only one test and the other is just a variable assignment, however, this is what gets reported.. Trying: y = (2, 3, 5, 7) Expecting nothing ok Trying: returnme(y) Expecting: (2, 3, 5, 7) ok 2 tests in 2 items. 2 passed and 0 failed. I've looked at the flags documented, surely I missing something..
[ "Prepend three periods to indicate that you want to continue the current line, like so:\ndef returnme(x):\n \"\"\"\n Returns what you pass\n\n >>> y = (2, 3, 5, 7)\n ... returnme(y) # Note the difference here.\n ... # Another blank line ends this test.\n (2, 3, 5, 7)\n \"\"\"\n return x\n\nThat should do the trick. You can read more about how doctest interprets the individual tests here.\n" ]
[ 5 ]
[]
[]
[ "doctest", "python", "unit_testing" ]
stackoverflow_0000684109_doctest_python_unit_testing.txt
Q: XML schema I've a schema file (.xsd), I'd like to generate a xml document using this schema. Is there any online tool available,if not what is quickest way (like couple of lines of code using vb.net). Thanks for your help. -Vuppala A: If I'm understanding you correct, this tool might help. XML Generator It's what I usually use when working with XML. If you want a solution through code you can use this: XmlTextWriter textWriter = new XmlTextWriter("po.xml", null); textWriter.Formatting = Formatting.Indented; XmlQualifiedName qname = new XmlQualifiedName("PurchaseOrder", "http://tempuri.org"); XmlSampleGenerator generator = new XmlSampleGenerator("po.xsd", qname); genr.WriteXml(textWriter); Taken from MSDN A: Download pyXSD. Use it to build Python class definitions from the XSD's. Build objects from those class definitions. Save the Python objects in XML notation. An alternative is GenerateDS.
XML schema
I've a schema file (.xsd), I'd like to generate a xml document using this schema. Is there any online tool available,if not what is quickest way (like couple of lines of code using vb.net). Thanks for your help. -Vuppala
[ "If I'm understanding you correct, this tool might help.\nXML Generator\nIt's what I usually use when working with XML.\nIf you want a solution through code you can use this:\nXmlTextWriter textWriter = new XmlTextWriter(\"po.xml\", null);\ntextWriter.Formatting = Formatting.Indented;\nXmlQualifiedName qname = new XmlQualifiedName(\"PurchaseOrder\", \n \"http://tempuri.org\");\nXmlSampleGenerator generator = new XmlSampleGenerator(\"po.xsd\", qname);\ngenr.WriteXml(textWriter);\n\nTaken from MSDN\n", "Download pyXSD.\nUse it to build Python class definitions from the XSD's.\nBuild objects from those class definitions.\nSave the Python objects in XML notation.\nAn alternative is GenerateDS.\n" ]
[ 1, 0 ]
[]
[]
[ "c#", "python", "ruby" ]
stackoverflow_0000684117_c#_python_ruby.txt
Q: Django Template if tag not working under FastCGI when checking bool True I have a strange issue specific to my Django deployment under Python 2.6 + Ubuntu + Apache 2.2 + FastCGI. If I have a template as such: {% with True as something %} {%if something%} It Worked!!! {%endif%} {%endwith%} it should output the string "It Worked!!!". It does not on my production server with mod_fastcgi. This works perfectly when I run locally with runserver. I modified the code to the following to make it work for the sake of expediency, and the problem went away. {% with "True" as something %} {%if something%} It Worked!!! {%endif%} {%endwith%} It seems that the template parser, when running under FastCGI, cannot ascertain Truthiness (or Truthitude)[kudos if you get the reference] of bool variables. Has anyone seen this? Do you have a solution? A: Hmm... True is not a valid token in django template language, is it? I have no idea how it worked locally -- unless it's being added to the context with a non-zero value somewhere. Therefore, I think your second problem may not be related to the first one.
Django Template if tag not working under FastCGI when checking bool True
I have a strange issue specific to my Django deployment under Python 2.6 + Ubuntu + Apache 2.2 + FastCGI. If I have a template as such: {% with True as something %} {%if something%} It Worked!!! {%endif%} {%endwith%} it should output the string "It Worked!!!". It does not on my production server with mod_fastcgi. This works perfectly when I run locally with runserver. I modified the code to the following to make it work for the sake of expediency, and the problem went away. {% with "True" as something %} {%if something%} It Worked!!! {%endif%} {%endwith%} It seems that the template parser, when running under FastCGI, cannot ascertain Truthiness (or Truthitude)[kudos if you get the reference] of bool variables. Has anyone seen this? Do you have a solution?
[ "Hmm... True is not a valid token in django template language, is it? I have no idea how it worked locally -- unless it's being added to the context with a non-zero value somewhere. Therefore, I think your second problem may not be related to the first one.\n" ]
[ 3 ]
[]
[]
[ "django", "fastcgi", "python", "python_2.6", "templates" ]
stackoverflow_0000684371_django_fastcgi_python_python_2.6_templates.txt
Q: Hierarchy / Flyweight / Instancing Problem in Python Here is the problem I am trying to solve, (I have simplified the actual problem, but this should give you all the relevant information). I have a hierarchy like so: 1.A 1.B 1.C 2.A 3.D 4.B 5.F (This is hard to illustrate - each number is the parent, each letter is the child). Creating an instance of the 'letter' objects is expensive (IO, database costs, etc), so should only be done once. The hierarchy needs to be easy to navigate. Children in the hierarchy need to have just one parent. Modifying the contents of the letter objects should be possible directly from the objects in the hierarchy. There needs to be a central store containing all of the 'letter' objects (and only those in the hierarchy). 'letter' and 'number' objects need to be possible to create from a constructor (such as Letter(**kwargs) ). It is perfectably acceptable to expect that when a letter changes from the hierarchy, all other letters will respect the same change. Hope this isn't too abstract to illustrate the problem. What would be the best way of solving this? (Then I'll post my solution) Here's an example script: one = Number('one') a = Letter('a') one.addChild(a) two = Number('two') a = Letter('a') two.addChild(a) for child in one: child.method1() for child in two: print '%s' % child.method2() A: A basic approach will use builtin data types. If I get your drift, the Letter object should be created by a factory with a dict cache to keep previously generated Letter objects. The factory will create only one Letter object for each key. A Number object can be a sub-class of list that will hold the Letter objects, so that append() can be used to add a child. A list is easy to navigate. A crude outline of a caching factory: >>> class Letters(object): ... def __init__(self): ... self.cache = {} ... def create(self, v): ... l = self.cache.get(v, None) ... if l: ... return l ... l = self.cache[v] = Letter(v) ... return l >>> factory=Letters() >>> factory.cache {} >>> factory.create('a') <__main__.Letter object at 0x00EF2950> >>> factory.create('a') <__main__.Letter object at 0x00EF2950> >>> To fulfill requirement 6 (constructor), here is a more contrived example, using __new__, of a caching constructor. This is similar to Recipe 413717: Caching object creation . class Letter(object): cache = {} def __new__(cls, v): o = cls.cache.get(v, None) if o: return o else: o = cls.cache[v] = object.__new__(cls) return o def __init__(self, v): self.v = v self.refcount = 0 def addAsChild(self, chain): if self.refcount > 0: return False self.refcount += 1 chain.append(self) return True Testing the cache functionality >>> l1 = Letter('a') >>> l2 = Letter('a') >>> l1 is l2 True >>> For enforcing a single parent, you'll need a method on Letter objects (not Number) - with a reference counter. When called to perform the addition it will refuse addition if the counter is greater than zero. l1.addAsChild(num4)
Hierarchy / Flyweight / Instancing Problem in Python
Here is the problem I am trying to solve, (I have simplified the actual problem, but this should give you all the relevant information). I have a hierarchy like so: 1.A 1.B 1.C 2.A 3.D 4.B 5.F (This is hard to illustrate - each number is the parent, each letter is the child). Creating an instance of the 'letter' objects is expensive (IO, database costs, etc), so should only be done once. The hierarchy needs to be easy to navigate. Children in the hierarchy need to have just one parent. Modifying the contents of the letter objects should be possible directly from the objects in the hierarchy. There needs to be a central store containing all of the 'letter' objects (and only those in the hierarchy). 'letter' and 'number' objects need to be possible to create from a constructor (such as Letter(**kwargs) ). It is perfectably acceptable to expect that when a letter changes from the hierarchy, all other letters will respect the same change. Hope this isn't too abstract to illustrate the problem. What would be the best way of solving this? (Then I'll post my solution) Here's an example script: one = Number('one') a = Letter('a') one.addChild(a) two = Number('two') a = Letter('a') two.addChild(a) for child in one: child.method1() for child in two: print '%s' % child.method2()
[ "A basic approach will use builtin data types. If I get your drift, the Letter object should be created by a factory with a dict cache to keep previously generated Letter objects. The factory will create only one Letter object for each key.\nA Number object can be a sub-class of list that will hold the Letter objects, so that append() can be used to add a child. A list is easy to navigate.\nA crude outline of a caching factory:\n>>> class Letters(object):\n... def __init__(self):\n... self.cache = {}\n... def create(self, v):\n... l = self.cache.get(v, None)\n... if l:\n... return l\n... l = self.cache[v] = Letter(v)\n... return l\n>>> factory=Letters()\n>>> factory.cache\n{}\n>>> factory.create('a')\n<__main__.Letter object at 0x00EF2950>\n>>> factory.create('a')\n<__main__.Letter object at 0x00EF2950>\n>>> \n\nTo fulfill requirement 6 (constructor), here is\na more contrived example, using __new__, of a caching constructor. This is similar to Recipe 413717: Caching object creation .\nclass Letter(object):\n cache = {}\n\n def __new__(cls, v):\n o = cls.cache.get(v, None)\n if o:\n return o\n else:\n o = cls.cache[v] = object.__new__(cls)\n return o\n\n def __init__(self, v):\n self.v = v\n self.refcount = 0\n\n def addAsChild(self, chain):\n if self.refcount > 0:\n return False\n self.refcount += 1\n chain.append(self)\n return True\n\nTesting the cache functionality\n>>> l1 = Letter('a')\n>>> l2 = Letter('a')\n>>> l1 is l2\nTrue\n>>> \n\nFor enforcing a single parent, you'll need a method on Letter objects (not Number) - with a reference counter. When called to perform the addition it will refuse addition if the counter is greater than zero.\nl1.addAsChild(num4)\n\n" ]
[ 0 ]
[]
[]
[ "design_patterns", "python" ]
stackoverflow_0000685253_design_patterns_python.txt
Q: Handling file attributes in python 3.0 I am currently developing an application in python 3 and i need to be able to hide certain files from the view of people. i found a few places that used the win32api and win32con but they don't seem to exist in python 3. Does anyone know if this is possible without rolling back or writing my own attribute library in C++ A: You need the pywin32 Python Extensions for Windows. Recently released for Python 3. A: You can use ctypes to directly access functions from kernel32.dll. The function you're looking for is windll.kernel32.SetFileAttributesA
Handling file attributes in python 3.0
I am currently developing an application in python 3 and i need to be able to hide certain files from the view of people. i found a few places that used the win32api and win32con but they don't seem to exist in python 3. Does anyone know if this is possible without rolling back or writing my own attribute library in C++
[ "You need the pywin32 Python Extensions for Windows. Recently released for Python 3.\n", "You can use ctypes to directly access functions from kernel32.dll. \nThe function you're looking for is windll.kernel32.SetFileAttributesA\n" ]
[ 5, 3 ]
[]
[]
[ "python", "python_3.x", "windows" ]
stackoverflow_0000685488_python_python_3.x_windows.txt
Q: django : using admin datepicker I'm trying to use the admin datepicker in my own django forms. Roughly following the discussion here : http://www.mail-archive.com/django-users@googlegroups.com/msg72138.html I've a) In my forms.py included the line from django.contrib.admin import widgets b) and used the widget like this : date = forms.DateTimeField(widget=widgets.AdminDateWidget()) c) And in my actual template I've added : {{form.media}} To include the js / styles etc. However, when I try to view my form I get no nice widget; just an ordinary text box. And the Firefox javascript error console shows me : gettext is not defined in calendar.js (line 26) and addEvent is not defined in DateTimeShortcuts.js (line 254) Any suggestions? Is this a bug in Django's own javascript library? Update : Basically, need to include the core and (or fake) the i18lization Update 2 : Carl points out this is pretty much a duplicate of Using Django time/date widgets in custom form (although starting from a different position) A: No, it's not a bug. It's trying to call the gettext() internationalization function in js. You can do js internationalization much like you do it in python code or templates, it's only a less known feature. If you don't use js internationalization in your project you can just put. <script>function gettext(txt){ return txt }</script> in your top template so the js interpreter doesn't choke. This is a hacky way to solve it I know. Edit: Or you can include the exact jsi18n js django admin references to get it working even with other languages. I don't know which one it is. This was posted on django-users today: http://groups.google.com/group/django-users/browse_thread/thread/2f529966472c479d# Maybe it was you, anyway, just in case. A: I think I solved the first half by explicitly adding these lines to my template : <script type="text/javascript" src="../../../jsi18n/"></script> <script type="text/javascript" src="/admin_media/js/core.js"></script> <script type="text/javascript" src="/admin_media/js/admin/RelatedObjectLookups.js"></script> But it still reports not knowing gettext A: You may find the following works for you: <link href="/media/css/base.css" rel="stylesheet" type="text/css" media="screen" /> <script type="text/javascript" src="/admin/jsi18n/"></script> <script type="text/javascript" src="/media/js/core.js"></script> {{ form.media }}
django : using admin datepicker
I'm trying to use the admin datepicker in my own django forms. Roughly following the discussion here : http://www.mail-archive.com/django-users@googlegroups.com/msg72138.html I've a) In my forms.py included the line from django.contrib.admin import widgets b) and used the widget like this : date = forms.DateTimeField(widget=widgets.AdminDateWidget()) c) And in my actual template I've added : {{form.media}} To include the js / styles etc. However, when I try to view my form I get no nice widget; just an ordinary text box. And the Firefox javascript error console shows me : gettext is not defined in calendar.js (line 26) and addEvent is not defined in DateTimeShortcuts.js (line 254) Any suggestions? Is this a bug in Django's own javascript library? Update : Basically, need to include the core and (or fake) the i18lization Update 2 : Carl points out this is pretty much a duplicate of Using Django time/date widgets in custom form (although starting from a different position)
[ "No, it's not a bug. \nIt's trying to call the gettext() internationalization function in js. You can do js internationalization much like you do it in python code or templates, it's only a less known feature.\nIf you don't use js internationalization in your project you can just put.\n<script>function gettext(txt){ return txt }</script>\n\nin your top template so the js interpreter doesn't choke.\nThis is a hacky way to solve it I know.\nEdit:\nOr you can include the exact jsi18n js django admin references to get it working even with other languages. I don't know which one it is.\nThis was posted on django-users today:\nhttp://groups.google.com/group/django-users/browse_thread/thread/2f529966472c479d#\nMaybe it was you, anyway, just in case.\n", "I think I solved the first half by explicitly adding these lines to my template :\n<script type=\"text/javascript\" src=\"../../../jsi18n/\"></script> \n<script type=\"text/javascript\" src=\"/admin_media/js/core.js\"></script>\n<script type=\"text/javascript\" src=\"/admin_media/js/admin/RelatedObjectLookups.js\"></script>\n\nBut it still reports not knowing gettext\n", "You may find the following works for you:\n<link href=\"/media/css/base.css\" rel=\"stylesheet\" type=\"text/css\" media=\"screen\" />\n<script type=\"text/javascript\" src=\"/admin/jsi18n/\"></script>\n<script type=\"text/javascript\" src=\"/media/js/core.js\"></script>\n{{ form.media }} \n\n" ]
[ 5, 2, 1 ]
[]
[]
[ "date", "django", "django_forms", "forms", "python" ]
stackoverflow_0000660898_date_django_django_forms_forms_python.txt
Q: Is there any particular reason why this syntax is used for instantiating a class? I was wondering if anyone knew of a particular reason (other than purely stylistic) why the following languages these syntaxes to initiate a class? Python: class MyClass: def __init__(self): x = MyClass() Ruby: class AnotherClass def initialize() end end x = AnotherClass.new() I can't understand why the syntax used for the constructor and the syntax used to actually get an instance of the class are so different. Sure, I know it doesn't really make a difference but, for example, in ruby what's wrong with making the constructor "new()"? A: When you are creating an object of a class, you are doing more than just initializing it. You are allocating the memory for it, then initializing it, then returning it. Note also that in Ruby, new() is a class method, while initialize() is an instance method. If you simply overrode new(), you would have to create the object first, then operate on that object, and return it, rather than the simpler initialize() where you can just refer to self, as the object has already been created for you by the built-in new() (or in Ruby, leave self off as it's implied). In Objective-C, you can actually see what's going on a little more clearly (but more verbosely) because you need to do the allocation and initialization separately, since Objective-C can't pass argument lists from the allocation method to the initialization one: [[MyClass alloc] initWithFoo: 1 bar: 2]; A: Actually in Python the constructor is __new__(), while __init__() is instance initializer. __new__() is static class method, thus it has to be called first, as a first parameter (usually named cls or klass) it gets the class . It creates object instance, which is then passed to __init__() as first parameter (usually named self), along with all the rest of __new__'s parameters. A: This is useful because in Python, a constructor is just another function. For example, I've done this several times: def ClassThatShouldntBeDirectlyInstantiated(): return _classThatShouldntBeDirectlyInstantiated() class _classThatShouldntBeDirectlyInstantiated(object): ... Of course, that's a contrived example, but you get the idea. Essentially, most people that use your class will probably think of ClassThatShouldntBeDirectlyInstantiated as your class, and there's no need to let them think otherwise. Doing things this way, all you have to do is document the factory function as the class it instantiates and not confuse anyone using the class. In a language like C# or Java, I sometimes find it annoying to make classes like this because it can be difficult to determine whether you should use the constructor or some factory function. I'm not sure if this is also the case in Ruby though.
Is there any particular reason why this syntax is used for instantiating a class?
I was wondering if anyone knew of a particular reason (other than purely stylistic) why the following languages these syntaxes to initiate a class? Python: class MyClass: def __init__(self): x = MyClass() Ruby: class AnotherClass def initialize() end end x = AnotherClass.new() I can't understand why the syntax used for the constructor and the syntax used to actually get an instance of the class are so different. Sure, I know it doesn't really make a difference but, for example, in ruby what's wrong with making the constructor "new()"?
[ "When you are creating an object of a class, you are doing more than just initializing it. You are allocating the memory for it, then initializing it, then returning it.\nNote also that in Ruby, new() is a class method, while initialize() is an instance method. If you simply overrode new(), you would have to create the object first, then operate on that object, and return it, rather than the simpler initialize() where you can just refer to self, as the object has already been created for you by the built-in new() (or in Ruby, leave self off as it's implied).\nIn Objective-C, you can actually see what's going on a little more clearly (but more verbosely) because you need to do the allocation and initialization separately, since Objective-C can't pass argument lists from the allocation method to the initialization one:\n[[MyClass alloc] initWithFoo: 1 bar: 2];\n\n", "Actually in Python the constructor is __new__(), while __init__() is instance initializer. \n__new__() is static class method, thus it has to be called first, as a first parameter (usually named cls or klass) it gets the class . It creates object instance, which is then passed to __init__() as first parameter (usually named self), along with all the rest of __new__'s parameters.\n", "This is useful because in Python, a constructor is just another function. For example, I've done this several times:\ndef ClassThatShouldntBeDirectlyInstantiated():\n return _classThatShouldntBeDirectlyInstantiated()\n\nclass _classThatShouldntBeDirectlyInstantiated(object):\n ...\n\nOf course, that's a contrived example, but you get the idea. Essentially, most people that use your class will probably think of ClassThatShouldntBeDirectlyInstantiated as your class, and there's no need to let them think otherwise. Doing things this way, all you have to do is document the factory function as the class it instantiates and not confuse anyone using the class.\nIn a language like C# or Java, I sometimes find it annoying to make classes like this because it can be difficult to determine whether you should use the constructor or some factory function. I'm not sure if this is also the case in Ruby though.\n" ]
[ 5, 4, 0 ]
[]
[]
[ "constructor", "python", "ruby" ]
stackoverflow_0000685713_constructor_python_ruby.txt
Q: Any alternatives to IronPython, Python for .NET for accessing CLR from python? Are there any alternatives to Python for .NET or IronPython for accessing .NET CLR? Both of these seem to have downsides in that Python for .NET is not under active development (as far as I can tell) and you lose some features available in CPython if you use IronPython. So are there any alternatives? A: Apart from Python for .NET (which works pretty well for me), the only other solution I'm aware of is exposing the .NET libraries via COM interop, so you can use them via the pywin32 extensions. (I don't know much about .NET com interop yet, so hopefully someone else can provide further explanation on that.) A: What feature are you missing? There is a project called IronClad that is helping to open access to CPython extensions from IronPython, it may be helpful. A: As far as I know you are not going to get anything more actively developed than IronPython . IronPython is currently one of the .NET 5 being developed by the language team (C#, VB.NET, F#, IronPython and IronRuby) so I doubt that there's another open source .NET Python project that's gone anywhere near as far. A: Well it's a python derivative, but you always have Boo.
Any alternatives to IronPython, Python for .NET for accessing CLR from python?
Are there any alternatives to Python for .NET or IronPython for accessing .NET CLR? Both of these seem to have downsides in that Python for .NET is not under active development (as far as I can tell) and you lose some features available in CPython if you use IronPython. So are there any alternatives?
[ "Apart from Python for .NET (which works pretty well for me), the only other solution I'm aware of is exposing the .NET libraries via COM interop, so you can use them via the pywin32 extensions. \n(I don't know much about .NET com interop yet, so hopefully someone else can provide further explanation on that.)\n", "What feature are you missing? There is a project called IronClad that is helping to open access to CPython extensions from IronPython, it may be helpful. \n", "As far as I know you are not going to get anything more actively developed than IronPython .\nIronPython is currently one of the .NET 5 being developed by the language team (C#, VB.NET, F#, IronPython and IronRuby) so I doubt that there's another open source .NET Python project that's gone anywhere near as far.\n", "Well it's a python derivative, but you always have Boo.\n" ]
[ 4, 1, 1, 1 ]
[]
[]
[ ".net", "clr", "ironpython", "python" ]
stackoverflow_0000681853_.net_clr_ironpython_python.txt
Q: separate threads in pygtk application I'm having some problems threading my pyGTK application. I give the thread some time to complete its task, if there is a problem I just continue anyway but warn the user. However once I continue, this thread stops until gtk.main_quit is called. This is confusing me. The relevant code: class MTP_Connection(threading.Thread): def __init__(self, HOME_DIR, username): self.filename = HOME_DIR + "mtp-dump_" + username threading.Thread.__init__(self) def run(self): #test run for i in range(1, 10): time.sleep(1) print i .......................... start_time = time.time() conn = MTP_Connection(self.HOME_DIR, self.username) conn.start() progress_bar = ProgressBar(self.tree.get_widget("progressbar"), update_speed=100, pulse_mode=True) while conn.isAlive(): while gtk.events_pending(): gtk.main_iteration() if time.time() - start_time > 5: self.write_info("problems closing connection.") break #after this the program continues normally, but my conn thread stops A: Firstly, don't subclass threading.Thread, use Thread(target=callable).start(). Secondly, and probably the cause of your apparent block is that gtk.main_iteration takes a parameter block, which defaults to True, so your call to gtk.main_iteration will actually block when there are no events to iterate on. Which can be solved with: gtk.main_iteration(block=False) However, there is no real explanation why you would use this hacked up loop rather than the actual gtk main loop. If you are already running this inside a main loop, then I would suggest that you are doing the wrong thing. I can expand on your options if you give us a bit more detail and/or the complete example. Thirdly, and this only came up later: Always always always always make sure you have called gtk.gdk.threads_init in any pygtk application with threads. GTK+ has different code paths when running threaded, and it needs to know to use these. I wrote a small article about pygtk and threads that offers you a small abstraction so you never have to worry about these things. That post also includes a progress bar example.
separate threads in pygtk application
I'm having some problems threading my pyGTK application. I give the thread some time to complete its task, if there is a problem I just continue anyway but warn the user. However once I continue, this thread stops until gtk.main_quit is called. This is confusing me. The relevant code: class MTP_Connection(threading.Thread): def __init__(self, HOME_DIR, username): self.filename = HOME_DIR + "mtp-dump_" + username threading.Thread.__init__(self) def run(self): #test run for i in range(1, 10): time.sleep(1) print i .......................... start_time = time.time() conn = MTP_Connection(self.HOME_DIR, self.username) conn.start() progress_bar = ProgressBar(self.tree.get_widget("progressbar"), update_speed=100, pulse_mode=True) while conn.isAlive(): while gtk.events_pending(): gtk.main_iteration() if time.time() - start_time > 5: self.write_info("problems closing connection.") break #after this the program continues normally, but my conn thread stops
[ "Firstly, don't subclass threading.Thread, use Thread(target=callable).start().\nSecondly, and probably the cause of your apparent block is that gtk.main_iteration takes a parameter block, which defaults to True, so your call to gtk.main_iteration will actually block when there are no events to iterate on. Which can be solved with:\ngtk.main_iteration(block=False)\n\nHowever, there is no real explanation why you would use this hacked up loop rather than the actual gtk main loop. If you are already running this inside a main loop, then I would suggest that you are doing the wrong thing. I can expand on your options if you give us a bit more detail and/or the complete example.\nThirdly, and this only came up later: Always always always always make sure you have called gtk.gdk.threads_init in any pygtk application with threads. GTK+ has different code paths when running threaded, and it needs to know to use these.\nI wrote a small article about pygtk and threads that offers you a small abstraction so you never have to worry about these things. That post also includes a progress bar example.\n" ]
[ 9 ]
[]
[]
[ "multithreading", "pygtk", "python" ]
stackoverflow_0000685224_multithreading_pygtk_python.txt
Q: Writing binary data to a socket (or file) with Python Let's say I have a socket connection, and the 3rd party listener on the other side expects to see data flowing in a very structured manner. For example, it looks for an unsigned byte that denotes a type of message being sent, followed by an unsigned integer that denotes the length of message, then another unsigned byte which is really a bit field with some flags set or unset and etc... How would I do this in python? I'm just wondering how to reliably generate this data and make sure I'm sending it correctly (i.e. that I'm really sending an unsigned byte rather than say a signed integer or worse, a string). A: Use the struct module to build a buffer and write that. A: A very elegant way to handle theses transitions between Python objects and a binary representation (both directions) is using the Construct library. In their documentation you'll find many nice examples of using it. I've been using it myself for several years now for serial communications protocols and decoding binary data. A: At the lowest level, socket I/O consists of reading or writing a string of byte values to a socket. To do this, I encode the information to be written as a string of characters containing the byte values, and write it to the socket. I do this by creating a superstring, and then appending one character at a time. for example, to create a Modbus/Ethernet read request: readRequest = """""" readRequest += chr(self.transactionID / 0x100) # Transaction ID MSB (0) readRequest += chr(self.transactionID % 0x100) # Transaction ID LSB (1) readRequest += chr(0) # Protocol ID MSB (Always 0) (2) readRequest += chr(0) # Protocol ID LSB (Always 0) (3) readRequest += chr(0) # Length MSB (Always 0) (4) readRequest += chr(6) # Length LSB (Always 6) (5) readRequest += chr(0) # Unit ID (Always 0) (6) readRequest += chr(0x04) # Function code 4 (0) readRequest += chr(startOffset / 0x100) # Starting offset MSB (1) readRequest += chr(startOffset % 0x100) # Starting offset LSB (2) readRequest += chr(0) # Word count MSB (3) readRequest += chr(2 * nToRead) # Word count LSB (4) sockOutfile.write(readRequest) To convert multibyte values into character strings so they can be appended onto the I/O string, use the 'Pack()' function in the struct module. This function converts one or more single or multiple byte values into a string of individual byte values. Of course, this method is about as simple as a hammer. It will need to be fixed when the default character encoding in a string is Unicode instead of ASCII.
Writing binary data to a socket (or file) with Python
Let's say I have a socket connection, and the 3rd party listener on the other side expects to see data flowing in a very structured manner. For example, it looks for an unsigned byte that denotes a type of message being sent, followed by an unsigned integer that denotes the length of message, then another unsigned byte which is really a bit field with some flags set or unset and etc... How would I do this in python? I'm just wondering how to reliably generate this data and make sure I'm sending it correctly (i.e. that I'm really sending an unsigned byte rather than say a signed integer or worse, a string).
[ "Use the struct module to build a buffer and write that.\n", "A very elegant way to handle theses transitions between Python objects and a binary representation (both directions) is using the Construct library.\nIn their documentation you'll find many nice examples of using it. I've been using it myself for several years now for serial communications protocols and decoding binary data.\n", "At the lowest level, socket I/O consists of reading or writing a string of byte values to a socket. To do this, I encode the information to be written as a string of characters containing the byte values, and write it to the socket. I do this by creating a superstring, and then appending one character at a time. for example, to create a Modbus/Ethernet read request:\n readRequest = \"\"\"\"\"\"\n readRequest += chr(self.transactionID / 0x100) # Transaction ID MSB (0)\n readRequest += chr(self.transactionID % 0x100) # Transaction ID LSB (1)\n readRequest += chr(0) # Protocol ID MSB (Always 0) (2)\n readRequest += chr(0) # Protocol ID LSB (Always 0) (3)\n readRequest += chr(0) # Length MSB (Always 0) (4)\n readRequest += chr(6) # Length LSB (Always 6) (5)\n readRequest += chr(0) # Unit ID (Always 0) (6)\n\n readRequest += chr(0x04) # Function code 4 (0)\n readRequest += chr(startOffset / 0x100) # Starting offset MSB (1)\n readRequest += chr(startOffset % 0x100) # Starting offset LSB (2)\n readRequest += chr(0) # Word count MSB (3)\n readRequest += chr(2 * nToRead) # Word count LSB (4)\n\n sockOutfile.write(readRequest)\n\nTo convert multibyte values into character strings so they can be appended onto the I/O string, use the 'Pack()' function in the struct module. This function converts one or more single or multiple byte values into a string of individual byte values.\nOf course, this method is about as simple as a hammer. It will need to be fixed when the default character encoding in a string is Unicode instead of ASCII.\n" ]
[ 11, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000686296_python.txt